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/SmallPtrSet.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetLowering.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Target/TargetOptions.h"
37 #include "llvm/Target/TargetRegisterInfo.h"
38 #include "llvm/Target/TargetSubtargetInfo.h"
42 #define DEBUG_TYPE "dagcombine"
44 STATISTIC(NodesCombined , "Number of dag nodes combined");
45 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
46 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
47 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
48 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
49 STATISTIC(SlicedLoads, "Number of load sliced");
53 CombinerAA("combiner-alias-analysis", cl::Hidden,
54 cl::desc("Enable DAG combiner alias-analysis heuristics"));
57 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
58 cl::desc("Enable DAG combiner's use of IR alias analysis"));
61 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
62 cl::desc("Enable DAG combiner's use of TBAA"));
65 static cl::opt<std::string>
66 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
67 cl::desc("Only use DAG-combiner alias analysis in this"
71 /// Hidden option to stress test load slicing, i.e., when this option
72 /// is enabled, load slicing bypasses most of its profitability guards.
74 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
75 cl::desc("Bypass the profitability model of load "
79 //------------------------------ DAGCombiner ---------------------------------//
83 const TargetLowering &TLI;
85 CodeGenOpt::Level OptLevel;
90 // Worklist of all of the nodes that need to be simplified.
92 // This has the semantics that when adding to the worklist,
93 // the item added must be next to be processed. It should
94 // also only appear once. The naive approach to this takes
97 // To reduce the insert/remove time to logarithmic, we use
98 // a set and a vector to maintain our worklist.
100 // The set contains the items on the worklist, but does not
101 // maintain the order they should be visited.
103 // The vector maintains the order nodes should be visited, but may
104 // contain duplicate or removed nodes. When choosing a node to
105 // visit, we pop off the order stack until we find an item that is
106 // also in the contents set. All operations are O(log N).
107 SmallPtrSet<SDNode*, 64> WorkListContents;
108 SmallVector<SDNode*, 64> WorkListOrder;
110 // AA - Used for DAG load/store alias analysis.
113 /// AddUsersToWorkList - When an instruction is simplified, add all users of
114 /// the instruction to the work lists because they might get more simplified
117 void AddUsersToWorkList(SDNode *N) {
118 for (SDNode *Node : N->uses())
122 /// visit - call the node-specific routine that knows how to fold each
123 /// particular type of node.
124 SDValue visit(SDNode *N);
127 /// AddToWorkList - Add to the work list making sure its instance is at the
128 /// back (next to be processed.)
129 void AddToWorkList(SDNode *N) {
130 WorkListContents.insert(N);
131 WorkListOrder.push_back(N);
134 /// removeFromWorkList - remove all instances of N from the worklist.
136 void removeFromWorkList(SDNode *N) {
137 WorkListContents.erase(N);
140 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
143 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
144 return CombineTo(N, &Res, 1, AddTo);
147 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
149 SDValue To[] = { Res0, Res1 };
150 return CombineTo(N, To, 2, AddTo);
153 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
157 /// SimplifyDemandedBits - Check the specified integer node value to see if
158 /// it can be simplified or if things it uses can be simplified by bit
159 /// propagation. If so, return true.
160 bool SimplifyDemandedBits(SDValue Op) {
161 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
162 APInt Demanded = APInt::getAllOnesValue(BitWidth);
163 return SimplifyDemandedBits(Op, Demanded);
166 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
168 bool CombineToPreIndexedLoadStore(SDNode *N);
169 bool CombineToPostIndexedLoadStore(SDNode *N);
170 bool SliceUpLoad(SDNode *N);
172 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
173 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
174 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
175 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
176 SDValue PromoteIntBinOp(SDValue Op);
177 SDValue PromoteIntShiftOp(SDValue Op);
178 SDValue PromoteExtend(SDValue Op);
179 bool PromoteLoad(SDValue Op);
181 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
182 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
183 ISD::NodeType ExtType);
185 /// combine - call the node-specific routine that knows how to fold each
186 /// particular type of node. If that doesn't do anything, try the
187 /// target-specific DAG combines.
188 SDValue combine(SDNode *N);
190 // Visitation implementation - Implement dag node combining for different
191 // node types. The semantics are as follows:
193 // SDValue.getNode() == 0 - No change was made
194 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
195 // otherwise - N should be replaced by the returned Operand.
197 SDValue visitTokenFactor(SDNode *N);
198 SDValue visitMERGE_VALUES(SDNode *N);
199 SDValue visitADD(SDNode *N);
200 SDValue visitSUB(SDNode *N);
201 SDValue visitADDC(SDNode *N);
202 SDValue visitSUBC(SDNode *N);
203 SDValue visitADDE(SDNode *N);
204 SDValue visitSUBE(SDNode *N);
205 SDValue visitMUL(SDNode *N);
206 SDValue visitSDIV(SDNode *N);
207 SDValue visitUDIV(SDNode *N);
208 SDValue visitSREM(SDNode *N);
209 SDValue visitUREM(SDNode *N);
210 SDValue visitMULHU(SDNode *N);
211 SDValue visitMULHS(SDNode *N);
212 SDValue visitSMUL_LOHI(SDNode *N);
213 SDValue visitUMUL_LOHI(SDNode *N);
214 SDValue visitSMULO(SDNode *N);
215 SDValue visitUMULO(SDNode *N);
216 SDValue visitSDIVREM(SDNode *N);
217 SDValue visitUDIVREM(SDNode *N);
218 SDValue visitAND(SDNode *N);
219 SDValue visitOR(SDNode *N);
220 SDValue visitXOR(SDNode *N);
221 SDValue SimplifyVBinOp(SDNode *N);
222 SDValue SimplifyVUnaryOp(SDNode *N);
223 SDValue visitSHL(SDNode *N);
224 SDValue visitSRA(SDNode *N);
225 SDValue visitSRL(SDNode *N);
226 SDValue visitRotate(SDNode *N);
227 SDValue visitCTLZ(SDNode *N);
228 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
229 SDValue visitCTTZ(SDNode *N);
230 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
231 SDValue visitCTPOP(SDNode *N);
232 SDValue visitSELECT(SDNode *N);
233 SDValue visitVSELECT(SDNode *N);
234 SDValue visitSELECT_CC(SDNode *N);
235 SDValue visitSETCC(SDNode *N);
236 SDValue visitSIGN_EXTEND(SDNode *N);
237 SDValue visitZERO_EXTEND(SDNode *N);
238 SDValue visitANY_EXTEND(SDNode *N);
239 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
240 SDValue visitTRUNCATE(SDNode *N);
241 SDValue visitBITCAST(SDNode *N);
242 SDValue visitBUILD_PAIR(SDNode *N);
243 SDValue visitFADD(SDNode *N);
244 SDValue visitFSUB(SDNode *N);
245 SDValue visitFMUL(SDNode *N);
246 SDValue visitFMA(SDNode *N);
247 SDValue visitFDIV(SDNode *N);
248 SDValue visitFREM(SDNode *N);
249 SDValue visitFCOPYSIGN(SDNode *N);
250 SDValue visitSINT_TO_FP(SDNode *N);
251 SDValue visitUINT_TO_FP(SDNode *N);
252 SDValue visitFP_TO_SINT(SDNode *N);
253 SDValue visitFP_TO_UINT(SDNode *N);
254 SDValue visitFP_ROUND(SDNode *N);
255 SDValue visitFP_ROUND_INREG(SDNode *N);
256 SDValue visitFP_EXTEND(SDNode *N);
257 SDValue visitFNEG(SDNode *N);
258 SDValue visitFABS(SDNode *N);
259 SDValue visitFCEIL(SDNode *N);
260 SDValue visitFTRUNC(SDNode *N);
261 SDValue visitFFLOOR(SDNode *N);
262 SDValue visitBRCOND(SDNode *N);
263 SDValue visitBR_CC(SDNode *N);
264 SDValue visitLOAD(SDNode *N);
265 SDValue visitSTORE(SDNode *N);
266 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
267 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
268 SDValue visitBUILD_VECTOR(SDNode *N);
269 SDValue visitCONCAT_VECTORS(SDNode *N);
270 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
271 SDValue visitVECTOR_SHUFFLE(SDNode *N);
272 SDValue visitINSERT_SUBVECTOR(SDNode *N);
274 SDValue XformToShuffleWithZero(SDNode *N);
275 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
277 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
279 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
280 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
281 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
282 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
283 SDValue N3, ISD::CondCode CC,
284 bool NotExtCompare = false);
285 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
286 SDLoc DL, bool foldBooleans = true);
288 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
290 bool isOneUseSetCC(SDValue N) const;
292 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
294 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
295 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
296 SDValue BuildSDIV(SDNode *N);
297 SDValue BuildUDIV(SDNode *N);
298 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
299 bool DemandHighBits = true);
300 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
301 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
302 SDValue InnerPos, SDValue InnerNeg,
303 unsigned PosOpcode, unsigned NegOpcode,
305 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
306 SDValue ReduceLoadWidth(SDNode *N);
307 SDValue ReduceLoadOpStoreWidth(SDNode *N);
308 SDValue TransformFPLoadStorePair(SDNode *N);
309 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
310 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
312 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
314 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
315 /// looking for aliasing nodes and adding them to the Aliases vector.
316 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
317 SmallVectorImpl<SDValue> &Aliases);
319 /// isAlias - Return true if there is any possibility that the two addresses
321 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
323 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
324 /// looking for a better chain (aliasing node.)
325 SDValue FindBetterChain(SDNode *N, SDValue Chain);
327 /// Merge consecutive store operations into a wide store.
328 /// This optimization uses wide integers or vectors when possible.
329 /// \return True if some memory operations were changed.
330 bool MergeConsecutiveStores(StoreSDNode *N);
332 /// \brief Try to transform a truncation where C is a constant:
333 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
335 /// \p N needs to be a truncation and its first operand an AND. Other
336 /// requirements are checked by the function (e.g. that trunc is
337 /// single-use) and if missed an empty SDValue is returned.
338 SDValue distributeTruncateThroughAnd(SDNode *N);
341 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
342 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
343 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
344 AttributeSet FnAttrs =
345 DAG.getMachineFunction().getFunction()->getAttributes();
347 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
348 Attribute::OptimizeForSize) ||
349 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
352 /// Run - runs the dag combiner on all nodes in the work list
353 void Run(CombineLevel AtLevel);
355 SelectionDAG &getDAG() const { return DAG; }
357 /// getShiftAmountTy - Returns a type large enough to hold any valid
358 /// shift amount - before type legalization these can be huge.
359 EVT getShiftAmountTy(EVT LHSTy) {
360 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
361 if (LHSTy.isVector())
363 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
364 : TLI.getPointerTy();
367 /// isTypeLegal - This method returns true if we are running before type
368 /// legalization or if the specified VT is legal.
369 bool isTypeLegal(const EVT &VT) {
370 if (!LegalTypes) return true;
371 return TLI.isTypeLegal(VT);
374 /// getSetCCResultType - Convenience wrapper around
375 /// TargetLowering::getSetCCResultType
376 EVT getSetCCResultType(EVT VT) const {
377 return TLI.getSetCCResultType(*DAG.getContext(), VT);
384 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
385 /// nodes from the worklist.
386 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
389 explicit WorkListRemover(DAGCombiner &dc)
390 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
392 void NodeDeleted(SDNode *N, SDNode *E) override {
393 DC.removeFromWorkList(N);
398 //===----------------------------------------------------------------------===//
399 // TargetLowering::DAGCombinerInfo implementation
400 //===----------------------------------------------------------------------===//
402 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
403 ((DAGCombiner*)DC)->AddToWorkList(N);
406 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
407 ((DAGCombiner*)DC)->removeFromWorkList(N);
410 SDValue TargetLowering::DAGCombinerInfo::
411 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
412 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
415 SDValue TargetLowering::DAGCombinerInfo::
416 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
417 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
421 SDValue TargetLowering::DAGCombinerInfo::
422 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
423 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
426 void TargetLowering::DAGCombinerInfo::
427 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
428 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
431 //===----------------------------------------------------------------------===//
433 //===----------------------------------------------------------------------===//
435 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
436 /// specified expression for the same cost as the expression itself, or 2 if we
437 /// can compute the negated form more cheaply than the expression itself.
438 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
439 const TargetLowering &TLI,
440 const TargetOptions *Options,
441 unsigned Depth = 0) {
442 // fneg is removable even if it has multiple uses.
443 if (Op.getOpcode() == ISD::FNEG) return 2;
445 // Don't allow anything with multiple uses.
446 if (!Op.hasOneUse()) return 0;
448 // Don't recurse exponentially.
449 if (Depth > 6) return 0;
451 switch (Op.getOpcode()) {
452 default: return false;
453 case ISD::ConstantFP:
454 // Don't invert constant FP values after legalize. The negated constant
455 // isn't necessarily legal.
456 return LegalOperations ? 0 : 1;
458 // FIXME: determine better conditions for this xform.
459 if (!Options->UnsafeFPMath) return 0;
461 // After operation legalization, it might not be legal to create new FSUBs.
462 if (LegalOperations &&
463 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
466 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
467 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
470 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
471 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
474 // We can't turn -(A-B) into B-A when we honor signed zeros.
475 if (!Options->UnsafeFPMath) return 0;
477 // fold (fneg (fsub A, B)) -> (fsub B, A)
482 if (Options->HonorSignDependentRoundingFPMath()) return 0;
484 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
485 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
489 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
495 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
500 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
501 /// returns the newly negated expression.
502 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
503 bool LegalOperations, unsigned Depth = 0) {
504 // fneg is removable even if it has multiple uses.
505 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
507 // Don't allow anything with multiple uses.
508 assert(Op.hasOneUse() && "Unknown reuse!");
510 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
511 switch (Op.getOpcode()) {
512 default: llvm_unreachable("Unknown code");
513 case ISD::ConstantFP: {
514 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
516 return DAG.getConstantFP(V, Op.getValueType());
519 // FIXME: determine better conditions for this xform.
520 assert(DAG.getTarget().Options.UnsafeFPMath);
522 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
523 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
524 DAG.getTargetLoweringInfo(),
525 &DAG.getTarget().Options, Depth+1))
526 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
527 GetNegatedExpression(Op.getOperand(0), DAG,
528 LegalOperations, Depth+1),
530 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
531 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
532 GetNegatedExpression(Op.getOperand(1), DAG,
533 LegalOperations, Depth+1),
536 // We can't turn -(A-B) into B-A when we honor signed zeros.
537 assert(DAG.getTarget().Options.UnsafeFPMath);
539 // fold (fneg (fsub 0, B)) -> B
540 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
541 if (N0CFP->getValueAPF().isZero())
542 return Op.getOperand(1);
544 // fold (fneg (fsub A, B)) -> (fsub B, A)
545 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
546 Op.getOperand(1), Op.getOperand(0));
550 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
552 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
553 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
554 DAG.getTargetLoweringInfo(),
555 &DAG.getTarget().Options, Depth+1))
556 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
557 GetNegatedExpression(Op.getOperand(0), DAG,
558 LegalOperations, Depth+1),
561 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
562 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
564 GetNegatedExpression(Op.getOperand(1), DAG,
565 LegalOperations, Depth+1));
569 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
570 GetNegatedExpression(Op.getOperand(0), DAG,
571 LegalOperations, Depth+1));
573 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
574 GetNegatedExpression(Op.getOperand(0), DAG,
575 LegalOperations, Depth+1),
580 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
581 // that selects between the target values used for true and false, making it
582 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
583 // the appropriate nodes based on the type of node we are checking. This
584 // simplifies life a bit for the callers.
585 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
587 if (N.getOpcode() == ISD::SETCC) {
588 LHS = N.getOperand(0);
589 RHS = N.getOperand(1);
590 CC = N.getOperand(2);
594 if (N.getOpcode() != ISD::SELECT_CC ||
595 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
596 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
599 LHS = N.getOperand(0);
600 RHS = N.getOperand(1);
601 CC = N.getOperand(4);
605 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
606 // one use. If this is true, it allows the users to invert the operation for
607 // free when it is profitable to do so.
608 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
610 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
615 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
616 /// elements are all the same constant or undefined.
617 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
618 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
623 unsigned SplatBitSize;
625 EVT EltVT = N->getValueType(0).getVectorElementType();
626 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
628 EltVT.getSizeInBits() >= SplatBitSize);
631 // \brief Returns the SDNode if it is a constant BuildVector or constant.
632 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
633 if (isa<ConstantSDNode>(N))
635 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
636 if(BV && BV->isConstant())
641 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
643 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
644 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
647 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
648 ConstantSDNode *CN = BV->getConstantSplatValue();
650 // BuildVectors can truncate their operands. Ignore that case here.
651 if (CN && CN->getValueType(0) == N.getValueType().getScalarType())
658 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
659 SDValue N0, SDValue N1) {
660 EVT VT = N0.getValueType();
661 if (N0.getOpcode() == Opc) {
662 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
663 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
664 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
665 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
666 if (!OpNode.getNode())
668 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
670 if (N0.hasOneUse()) {
671 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
673 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
674 if (!OpNode.getNode())
676 AddToWorkList(OpNode.getNode());
677 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
682 if (N1.getOpcode() == Opc) {
683 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
684 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
685 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
686 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
687 if (!OpNode.getNode())
689 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
691 if (N1.hasOneUse()) {
692 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
694 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
695 if (!OpNode.getNode())
697 AddToWorkList(OpNode.getNode());
698 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
706 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
708 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
710 DEBUG(dbgs() << "\nReplacing.1 ";
712 dbgs() << "\nWith: ";
713 To[0].getNode()->dump(&DAG);
714 dbgs() << " and " << NumTo-1 << " other values\n";
715 for (unsigned i = 0, e = NumTo; i != e; ++i)
716 assert((!To[i].getNode() ||
717 N->getValueType(i) == To[i].getValueType()) &&
718 "Cannot combine value to value of different type!"));
719 WorkListRemover DeadNodes(*this);
720 DAG.ReplaceAllUsesWith(N, To);
722 // Push the new nodes and any users onto the worklist
723 for (unsigned i = 0, e = NumTo; i != e; ++i) {
724 if (To[i].getNode()) {
725 AddToWorkList(To[i].getNode());
726 AddUsersToWorkList(To[i].getNode());
731 // Finally, if the node is now dead, remove it from the graph. The node
732 // may not be dead if the replacement process recursively simplified to
733 // something else needing this node.
734 if (N->use_empty()) {
735 // Nodes can be reintroduced into the worklist. Make sure we do not
736 // process a node that has been replaced.
737 removeFromWorkList(N);
739 // Finally, since the node is now dead, remove it from the graph.
742 return SDValue(N, 0);
746 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
747 // Replace all uses. If any nodes become isomorphic to other nodes and
748 // are deleted, make sure to remove them from our worklist.
749 WorkListRemover DeadNodes(*this);
750 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
752 // Push the new node and any (possibly new) users onto the worklist.
753 AddToWorkList(TLO.New.getNode());
754 AddUsersToWorkList(TLO.New.getNode());
756 // Finally, if the node is now dead, remove it from the graph. The node
757 // may not be dead if the replacement process recursively simplified to
758 // something else needing this node.
759 if (TLO.Old.getNode()->use_empty()) {
760 removeFromWorkList(TLO.Old.getNode());
762 // If the operands of this node are only used by the node, they will now
763 // be dead. Make sure to visit them first to delete dead nodes early.
764 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
765 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
766 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
768 DAG.DeleteNode(TLO.Old.getNode());
772 /// SimplifyDemandedBits - Check the specified integer node value to see if
773 /// it can be simplified or if things it uses can be simplified by bit
774 /// propagation. If so, return true.
775 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
776 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
777 APInt KnownZero, KnownOne;
778 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
782 AddToWorkList(Op.getNode());
784 // Replace the old value with the new one.
786 DEBUG(dbgs() << "\nReplacing.2 ";
787 TLO.Old.getNode()->dump(&DAG);
788 dbgs() << "\nWith: ";
789 TLO.New.getNode()->dump(&DAG);
792 CommitTargetLoweringOpt(TLO);
796 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
798 EVT VT = Load->getValueType(0);
799 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
801 DEBUG(dbgs() << "\nReplacing.9 ";
803 dbgs() << "\nWith: ";
804 Trunc.getNode()->dump(&DAG);
806 WorkListRemover DeadNodes(*this);
807 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
808 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
809 removeFromWorkList(Load);
810 DAG.DeleteNode(Load);
811 AddToWorkList(Trunc.getNode());
814 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
817 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
818 EVT MemVT = LD->getMemoryVT();
819 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
820 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
822 : LD->getExtensionType();
824 return DAG.getExtLoad(ExtType, dl, PVT,
825 LD->getChain(), LD->getBasePtr(),
826 MemVT, LD->getMemOperand());
829 unsigned Opc = Op.getOpcode();
832 case ISD::AssertSext:
833 return DAG.getNode(ISD::AssertSext, dl, PVT,
834 SExtPromoteOperand(Op.getOperand(0), PVT),
836 case ISD::AssertZext:
837 return DAG.getNode(ISD::AssertZext, dl, PVT,
838 ZExtPromoteOperand(Op.getOperand(0), PVT),
840 case ISD::Constant: {
842 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
843 return DAG.getNode(ExtOpc, dl, PVT, Op);
847 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
849 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
852 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
853 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
855 EVT OldVT = Op.getValueType();
857 bool Replace = false;
858 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
859 if (!NewOp.getNode())
861 AddToWorkList(NewOp.getNode());
864 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
865 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
866 DAG.getValueType(OldVT));
869 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
870 EVT OldVT = Op.getValueType();
872 bool Replace = false;
873 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
874 if (!NewOp.getNode())
876 AddToWorkList(NewOp.getNode());
879 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
880 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
883 /// PromoteIntBinOp - Promote the specified integer binary operation if the
884 /// target indicates it is beneficial. e.g. On x86, it's usually better to
885 /// promote i16 operations to i32 since i16 instructions are longer.
886 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
887 if (!LegalOperations)
890 EVT VT = Op.getValueType();
891 if (VT.isVector() || !VT.isInteger())
894 // If operation type is 'undesirable', e.g. i16 on x86, consider
896 unsigned Opc = Op.getOpcode();
897 if (TLI.isTypeDesirableForOp(Opc, VT))
901 // Consult target whether it is a good idea to promote this operation and
902 // what's the right type to promote it to.
903 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
904 assert(PVT != VT && "Don't know what type to promote to!");
906 bool Replace0 = false;
907 SDValue N0 = Op.getOperand(0);
908 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
912 bool Replace1 = false;
913 SDValue N1 = Op.getOperand(1);
918 NN1 = PromoteOperand(N1, PVT, Replace1);
923 AddToWorkList(NN0.getNode());
925 AddToWorkList(NN1.getNode());
928 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
930 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
932 DEBUG(dbgs() << "\nPromoting ";
933 Op.getNode()->dump(&DAG));
935 return DAG.getNode(ISD::TRUNCATE, dl, VT,
936 DAG.getNode(Opc, dl, PVT, NN0, NN1));
941 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
942 /// target indicates it is beneficial. e.g. On x86, it's usually better to
943 /// promote i16 operations to i32 since i16 instructions are longer.
944 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
945 if (!LegalOperations)
948 EVT VT = Op.getValueType();
949 if (VT.isVector() || !VT.isInteger())
952 // If operation type is 'undesirable', e.g. i16 on x86, consider
954 unsigned Opc = Op.getOpcode();
955 if (TLI.isTypeDesirableForOp(Opc, VT))
959 // Consult target whether it is a good idea to promote this operation and
960 // what's the right type to promote it to.
961 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
962 assert(PVT != VT && "Don't know what type to promote to!");
964 bool Replace = false;
965 SDValue N0 = Op.getOperand(0);
967 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
968 else if (Opc == ISD::SRL)
969 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
971 N0 = PromoteOperand(N0, PVT, Replace);
975 AddToWorkList(N0.getNode());
977 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
979 DEBUG(dbgs() << "\nPromoting ";
980 Op.getNode()->dump(&DAG));
982 return DAG.getNode(ISD::TRUNCATE, dl, VT,
983 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
988 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
989 if (!LegalOperations)
992 EVT VT = Op.getValueType();
993 if (VT.isVector() || !VT.isInteger())
996 // If operation type is 'undesirable', e.g. i16 on x86, consider
998 unsigned Opc = Op.getOpcode();
999 if (TLI.isTypeDesirableForOp(Opc, VT))
1003 // Consult target whether it is a good idea to promote this operation and
1004 // what's the right type to promote it to.
1005 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1006 assert(PVT != VT && "Don't know what type to promote to!");
1007 // fold (aext (aext x)) -> (aext x)
1008 // fold (aext (zext x)) -> (zext x)
1009 // fold (aext (sext x)) -> (sext x)
1010 DEBUG(dbgs() << "\nPromoting ";
1011 Op.getNode()->dump(&DAG));
1012 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1017 bool DAGCombiner::PromoteLoad(SDValue Op) {
1018 if (!LegalOperations)
1021 EVT VT = Op.getValueType();
1022 if (VT.isVector() || !VT.isInteger())
1025 // If operation type is 'undesirable', e.g. i16 on x86, consider
1027 unsigned Opc = Op.getOpcode();
1028 if (TLI.isTypeDesirableForOp(Opc, VT))
1032 // Consult target whether it is a good idea to promote this operation and
1033 // what's the right type to promote it to.
1034 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1035 assert(PVT != VT && "Don't know what type to promote to!");
1038 SDNode *N = Op.getNode();
1039 LoadSDNode *LD = cast<LoadSDNode>(N);
1040 EVT MemVT = LD->getMemoryVT();
1041 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1042 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1044 : LD->getExtensionType();
1045 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1046 LD->getChain(), LD->getBasePtr(),
1047 MemVT, LD->getMemOperand());
1048 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1050 DEBUG(dbgs() << "\nPromoting ";
1053 Result.getNode()->dump(&DAG);
1055 WorkListRemover DeadNodes(*this);
1056 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1057 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1058 removeFromWorkList(N);
1060 AddToWorkList(Result.getNode());
1067 //===----------------------------------------------------------------------===//
1068 // Main DAG Combiner implementation
1069 //===----------------------------------------------------------------------===//
1071 void DAGCombiner::Run(CombineLevel AtLevel) {
1072 // set the instance variables, so that the various visit routines may use it.
1074 LegalOperations = Level >= AfterLegalizeVectorOps;
1075 LegalTypes = Level >= AfterLegalizeTypes;
1077 // Add all the dag nodes to the worklist.
1078 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1079 E = DAG.allnodes_end(); I != E; ++I)
1082 // Create a dummy node (which is not added to allnodes), that adds a reference
1083 // to the root node, preventing it from being deleted, and tracking any
1084 // changes of the root.
1085 HandleSDNode Dummy(DAG.getRoot());
1087 // The root of the dag may dangle to deleted nodes until the dag combiner is
1088 // done. Set it to null to avoid confusion.
1089 DAG.setRoot(SDValue());
1091 // while the worklist isn't empty, find a node and
1092 // try and combine it.
1093 while (!WorkListContents.empty()) {
1095 // The WorkListOrder holds the SDNodes in order, but it may contain
1097 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1098 // worklist *should* contain, and check the node we want to visit is should
1099 // actually be visited.
1101 N = WorkListOrder.pop_back_val();
1102 } while (!WorkListContents.erase(N));
1104 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1105 // N is deleted from the DAG, since they too may now be dead or may have a
1106 // reduced number of uses, allowing other xforms.
1107 if (N->use_empty() && N != &Dummy) {
1108 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1109 AddToWorkList(N->getOperand(i).getNode());
1115 SDValue RV = combine(N);
1122 // If we get back the same node we passed in, rather than a new node or
1123 // zero, we know that the node must have defined multiple values and
1124 // CombineTo was used. Since CombineTo takes care of the worklist
1125 // mechanics for us, we have no work to do in this case.
1126 if (RV.getNode() == N)
1129 assert(N->getOpcode() != ISD::DELETED_NODE &&
1130 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1131 "Node was deleted but visit returned new node!");
1133 DEBUG(dbgs() << "\nReplacing.3 ";
1135 dbgs() << "\nWith: ";
1136 RV.getNode()->dump(&DAG);
1139 // Transfer debug value.
1140 DAG.TransferDbgValues(SDValue(N, 0), RV);
1141 WorkListRemover DeadNodes(*this);
1142 if (N->getNumValues() == RV.getNode()->getNumValues())
1143 DAG.ReplaceAllUsesWith(N, RV.getNode());
1145 assert(N->getValueType(0) == RV.getValueType() &&
1146 N->getNumValues() == 1 && "Type mismatch");
1148 DAG.ReplaceAllUsesWith(N, &OpV);
1151 // Push the new node and any users onto the worklist
1152 AddToWorkList(RV.getNode());
1153 AddUsersToWorkList(RV.getNode());
1155 // Add any uses of the old node to the worklist in case this node is the
1156 // last one that uses them. They may become dead after this node is
1158 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1159 AddToWorkList(N->getOperand(i).getNode());
1161 // Finally, if the node is now dead, remove it from the graph. The node
1162 // may not be dead if the replacement process recursively simplified to
1163 // something else needing this node.
1164 if (N->use_empty()) {
1165 // Nodes can be reintroduced into the worklist. Make sure we do not
1166 // process a node that has been replaced.
1167 removeFromWorkList(N);
1169 // Finally, since the node is now dead, remove it from the graph.
1174 // If the root changed (e.g. it was a dead load, update the root).
1175 DAG.setRoot(Dummy.getValue());
1176 DAG.RemoveDeadNodes();
1179 SDValue DAGCombiner::visit(SDNode *N) {
1180 switch (N->getOpcode()) {
1182 case ISD::TokenFactor: return visitTokenFactor(N);
1183 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1184 case ISD::ADD: return visitADD(N);
1185 case ISD::SUB: return visitSUB(N);
1186 case ISD::ADDC: return visitADDC(N);
1187 case ISD::SUBC: return visitSUBC(N);
1188 case ISD::ADDE: return visitADDE(N);
1189 case ISD::SUBE: return visitSUBE(N);
1190 case ISD::MUL: return visitMUL(N);
1191 case ISD::SDIV: return visitSDIV(N);
1192 case ISD::UDIV: return visitUDIV(N);
1193 case ISD::SREM: return visitSREM(N);
1194 case ISD::UREM: return visitUREM(N);
1195 case ISD::MULHU: return visitMULHU(N);
1196 case ISD::MULHS: return visitMULHS(N);
1197 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1198 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1199 case ISD::SMULO: return visitSMULO(N);
1200 case ISD::UMULO: return visitUMULO(N);
1201 case ISD::SDIVREM: return visitSDIVREM(N);
1202 case ISD::UDIVREM: return visitUDIVREM(N);
1203 case ISD::AND: return visitAND(N);
1204 case ISD::OR: return visitOR(N);
1205 case ISD::XOR: return visitXOR(N);
1206 case ISD::SHL: return visitSHL(N);
1207 case ISD::SRA: return visitSRA(N);
1208 case ISD::SRL: return visitSRL(N);
1210 case ISD::ROTL: return visitRotate(N);
1211 case ISD::CTLZ: return visitCTLZ(N);
1212 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1213 case ISD::CTTZ: return visitCTTZ(N);
1214 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1215 case ISD::CTPOP: return visitCTPOP(N);
1216 case ISD::SELECT: return visitSELECT(N);
1217 case ISD::VSELECT: return visitVSELECT(N);
1218 case ISD::SELECT_CC: return visitSELECT_CC(N);
1219 case ISD::SETCC: return visitSETCC(N);
1220 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1221 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1222 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1223 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1224 case ISD::TRUNCATE: return visitTRUNCATE(N);
1225 case ISD::BITCAST: return visitBITCAST(N);
1226 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1227 case ISD::FADD: return visitFADD(N);
1228 case ISD::FSUB: return visitFSUB(N);
1229 case ISD::FMUL: return visitFMUL(N);
1230 case ISD::FMA: return visitFMA(N);
1231 case ISD::FDIV: return visitFDIV(N);
1232 case ISD::FREM: return visitFREM(N);
1233 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1234 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1235 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1236 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1237 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1238 case ISD::FP_ROUND: return visitFP_ROUND(N);
1239 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1240 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1241 case ISD::FNEG: return visitFNEG(N);
1242 case ISD::FABS: return visitFABS(N);
1243 case ISD::FFLOOR: return visitFFLOOR(N);
1244 case ISD::FCEIL: return visitFCEIL(N);
1245 case ISD::FTRUNC: return visitFTRUNC(N);
1246 case ISD::BRCOND: return visitBRCOND(N);
1247 case ISD::BR_CC: return visitBR_CC(N);
1248 case ISD::LOAD: return visitLOAD(N);
1249 case ISD::STORE: return visitSTORE(N);
1250 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1251 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1252 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1253 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1254 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1255 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1256 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1261 SDValue DAGCombiner::combine(SDNode *N) {
1262 SDValue RV = visit(N);
1264 // If nothing happened, try a target-specific DAG combine.
1265 if (!RV.getNode()) {
1266 assert(N->getOpcode() != ISD::DELETED_NODE &&
1267 "Node was deleted but visit returned NULL!");
1269 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1270 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1272 // Expose the DAG combiner to the target combiner impls.
1273 TargetLowering::DAGCombinerInfo
1274 DagCombineInfo(DAG, Level, false, this);
1276 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1280 // If nothing happened still, try promoting the operation.
1281 if (!RV.getNode()) {
1282 switch (N->getOpcode()) {
1290 RV = PromoteIntBinOp(SDValue(N, 0));
1295 RV = PromoteIntShiftOp(SDValue(N, 0));
1297 case ISD::SIGN_EXTEND:
1298 case ISD::ZERO_EXTEND:
1299 case ISD::ANY_EXTEND:
1300 RV = PromoteExtend(SDValue(N, 0));
1303 if (PromoteLoad(SDValue(N, 0)))
1309 // If N is a commutative binary node, try commuting it to enable more
1311 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1312 N->getNumValues() == 1) {
1313 SDValue N0 = N->getOperand(0);
1314 SDValue N1 = N->getOperand(1);
1316 // Constant operands are canonicalized to RHS.
1317 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1318 SDValue Ops[] = { N1, N0 };
1319 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1322 return SDValue(CSENode, 0);
1329 /// getInputChainForNode - Given a node, return its input chain if it has one,
1330 /// otherwise return a null sd operand.
1331 static SDValue getInputChainForNode(SDNode *N) {
1332 if (unsigned NumOps = N->getNumOperands()) {
1333 if (N->getOperand(0).getValueType() == MVT::Other)
1334 return N->getOperand(0);
1335 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1336 return N->getOperand(NumOps-1);
1337 for (unsigned i = 1; i < NumOps-1; ++i)
1338 if (N->getOperand(i).getValueType() == MVT::Other)
1339 return N->getOperand(i);
1344 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1345 // If N has two operands, where one has an input chain equal to the other,
1346 // the 'other' chain is redundant.
1347 if (N->getNumOperands() == 2) {
1348 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1349 return N->getOperand(0);
1350 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1351 return N->getOperand(1);
1354 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1355 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1356 SmallPtrSet<SDNode*, 16> SeenOps;
1357 bool Changed = false; // If we should replace this token factor.
1359 // Start out with this token factor.
1362 // Iterate through token factors. The TFs grows when new token factors are
1364 for (unsigned i = 0; i < TFs.size(); ++i) {
1365 SDNode *TF = TFs[i];
1367 // Check each of the operands.
1368 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1369 SDValue Op = TF->getOperand(i);
1371 switch (Op.getOpcode()) {
1372 case ISD::EntryToken:
1373 // Entry tokens don't need to be added to the list. They are
1378 case ISD::TokenFactor:
1379 if (Op.hasOneUse() &&
1380 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1381 // Queue up for processing.
1382 TFs.push_back(Op.getNode());
1383 // Clean up in case the token factor is removed.
1384 AddToWorkList(Op.getNode());
1391 // Only add if it isn't already in the list.
1392 if (SeenOps.insert(Op.getNode()))
1403 // If we've change things around then replace token factor.
1406 // The entry token is the only possible outcome.
1407 Result = DAG.getEntryNode();
1409 // New and improved token factor.
1410 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1413 // Don't add users to work list.
1414 return CombineTo(N, Result, false);
1420 /// MERGE_VALUES can always be eliminated.
1421 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1422 WorkListRemover DeadNodes(*this);
1423 // Replacing results may cause a different MERGE_VALUES to suddenly
1424 // be CSE'd with N, and carry its uses with it. Iterate until no
1425 // uses remain, to ensure that the node can be safely deleted.
1426 // First add the users of this node to the work list so that they
1427 // can be tried again once they have new operands.
1428 AddUsersToWorkList(N);
1430 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1431 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1432 } while (!N->use_empty());
1433 removeFromWorkList(N);
1435 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1439 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1440 SelectionDAG &DAG) {
1441 EVT VT = N0.getValueType();
1442 SDValue N00 = N0.getOperand(0);
1443 SDValue N01 = N0.getOperand(1);
1444 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1446 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1447 isa<ConstantSDNode>(N00.getOperand(1))) {
1448 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1449 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1450 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1451 N00.getOperand(0), N01),
1452 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1453 N00.getOperand(1), N01));
1454 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1460 SDValue DAGCombiner::visitADD(SDNode *N) {
1461 SDValue N0 = N->getOperand(0);
1462 SDValue N1 = N->getOperand(1);
1463 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1464 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1465 EVT VT = N0.getValueType();
1468 if (VT.isVector()) {
1469 SDValue FoldedVOp = SimplifyVBinOp(N);
1470 if (FoldedVOp.getNode()) return FoldedVOp;
1472 // fold (add x, 0) -> x, vector edition
1473 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1475 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1479 // fold (add x, undef) -> undef
1480 if (N0.getOpcode() == ISD::UNDEF)
1482 if (N1.getOpcode() == ISD::UNDEF)
1484 // fold (add c1, c2) -> c1+c2
1486 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1487 // canonicalize constant to RHS
1489 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1490 // fold (add x, 0) -> x
1491 if (N1C && N1C->isNullValue())
1493 // fold (add Sym, c) -> Sym+c
1494 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1495 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1496 GA->getOpcode() == ISD::GlobalAddress)
1497 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1499 (uint64_t)N1C->getSExtValue());
1500 // fold ((c1-A)+c2) -> (c1+c2)-A
1501 if (N1C && N0.getOpcode() == ISD::SUB)
1502 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1503 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1504 DAG.getConstant(N1C->getAPIntValue()+
1505 N0C->getAPIntValue(), VT),
1508 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1511 // fold ((0-A) + B) -> B-A
1512 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1513 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1514 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1515 // fold (A + (0-B)) -> A-B
1516 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1517 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1518 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1519 // fold (A+(B-A)) -> B
1520 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1521 return N1.getOperand(0);
1522 // fold ((B-A)+A) -> B
1523 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1524 return N0.getOperand(0);
1525 // fold (A+(B-(A+C))) to (B-C)
1526 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1527 N0 == N1.getOperand(1).getOperand(0))
1528 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1529 N1.getOperand(1).getOperand(1));
1530 // fold (A+(B-(C+A))) to (B-C)
1531 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1532 N0 == N1.getOperand(1).getOperand(1))
1533 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1534 N1.getOperand(1).getOperand(0));
1535 // fold (A+((B-A)+or-C)) to (B+or-C)
1536 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1537 N1.getOperand(0).getOpcode() == ISD::SUB &&
1538 N0 == N1.getOperand(0).getOperand(1))
1539 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1540 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1542 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1543 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1544 SDValue N00 = N0.getOperand(0);
1545 SDValue N01 = N0.getOperand(1);
1546 SDValue N10 = N1.getOperand(0);
1547 SDValue N11 = N1.getOperand(1);
1549 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1550 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1551 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1552 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1555 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1556 return SDValue(N, 0);
1558 // fold (a+b) -> (a|b) iff a and b share no bits.
1559 if (VT.isInteger() && !VT.isVector()) {
1560 APInt LHSZero, LHSOne;
1561 APInt RHSZero, RHSOne;
1562 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1564 if (LHSZero.getBoolValue()) {
1565 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1567 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1568 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1569 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1570 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1571 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1576 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1577 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1578 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1579 if (Result.getNode()) return Result;
1581 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1582 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1583 if (Result.getNode()) return Result;
1586 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1587 if (N1.getOpcode() == ISD::SHL &&
1588 N1.getOperand(0).getOpcode() == ISD::SUB)
1589 if (ConstantSDNode *C =
1590 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1591 if (C->getAPIntValue() == 0)
1592 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1593 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1594 N1.getOperand(0).getOperand(1),
1596 if (N0.getOpcode() == ISD::SHL &&
1597 N0.getOperand(0).getOpcode() == ISD::SUB)
1598 if (ConstantSDNode *C =
1599 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1600 if (C->getAPIntValue() == 0)
1601 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1602 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1603 N0.getOperand(0).getOperand(1),
1606 if (N1.getOpcode() == ISD::AND) {
1607 SDValue AndOp0 = N1.getOperand(0);
1608 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1609 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1610 unsigned DestBits = VT.getScalarType().getSizeInBits();
1612 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1613 // and similar xforms where the inner op is either ~0 or 0.
1614 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1616 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1620 // add (sext i1), X -> sub X, (zext i1)
1621 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1622 N0.getOperand(0).getValueType() == MVT::i1 &&
1623 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1625 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1626 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1632 SDValue DAGCombiner::visitADDC(SDNode *N) {
1633 SDValue N0 = N->getOperand(0);
1634 SDValue N1 = N->getOperand(1);
1635 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1636 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1637 EVT VT = N0.getValueType();
1639 // If the flag result is dead, turn this into an ADD.
1640 if (!N->hasAnyUseOfValue(1))
1641 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1642 DAG.getNode(ISD::CARRY_FALSE,
1643 SDLoc(N), MVT::Glue));
1645 // canonicalize constant to RHS.
1647 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1649 // fold (addc x, 0) -> x + no carry out
1650 if (N1C && N1C->isNullValue())
1651 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1652 SDLoc(N), MVT::Glue));
1654 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1655 APInt LHSZero, LHSOne;
1656 APInt RHSZero, RHSOne;
1657 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1659 if (LHSZero.getBoolValue()) {
1660 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1662 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1663 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1664 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1665 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1666 DAG.getNode(ISD::CARRY_FALSE,
1667 SDLoc(N), MVT::Glue));
1673 SDValue DAGCombiner::visitADDE(SDNode *N) {
1674 SDValue N0 = N->getOperand(0);
1675 SDValue N1 = N->getOperand(1);
1676 SDValue CarryIn = N->getOperand(2);
1677 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1678 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1680 // canonicalize constant to RHS
1682 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1685 // fold (adde x, y, false) -> (addc x, y)
1686 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1687 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1692 // Since it may not be valid to emit a fold to zero for vector initializers
1693 // check if we can before folding.
1694 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1696 bool LegalOperations, bool LegalTypes) {
1698 return DAG.getConstant(0, VT);
1699 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1700 return DAG.getConstant(0, VT);
1704 SDValue DAGCombiner::visitSUB(SDNode *N) {
1705 SDValue N0 = N->getOperand(0);
1706 SDValue N1 = N->getOperand(1);
1707 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1708 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1709 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1710 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1711 EVT VT = N0.getValueType();
1714 if (VT.isVector()) {
1715 SDValue FoldedVOp = SimplifyVBinOp(N);
1716 if (FoldedVOp.getNode()) return FoldedVOp;
1718 // fold (sub x, 0) -> x, vector edition
1719 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1723 // fold (sub x, x) -> 0
1724 // FIXME: Refactor this and xor and other similar operations together.
1726 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1727 // fold (sub c1, c2) -> c1-c2
1729 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1730 // fold (sub x, c) -> (add x, -c)
1732 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1733 DAG.getConstant(-N1C->getAPIntValue(), VT));
1734 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1735 if (N0C && N0C->isAllOnesValue())
1736 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1737 // fold A-(A-B) -> B
1738 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1739 return N1.getOperand(1);
1740 // fold (A+B)-A -> B
1741 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1742 return N0.getOperand(1);
1743 // fold (A+B)-B -> A
1744 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1745 return N0.getOperand(0);
1746 // fold C2-(A+C1) -> (C2-C1)-A
1747 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1748 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1750 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1753 // fold ((A+(B+or-C))-B) -> A+or-C
1754 if (N0.getOpcode() == ISD::ADD &&
1755 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1756 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1757 N0.getOperand(1).getOperand(0) == N1)
1758 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1759 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1760 // fold ((A+(C+B))-B) -> A+C
1761 if (N0.getOpcode() == ISD::ADD &&
1762 N0.getOperand(1).getOpcode() == ISD::ADD &&
1763 N0.getOperand(1).getOperand(1) == N1)
1764 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1765 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1766 // fold ((A-(B-C))-C) -> A-B
1767 if (N0.getOpcode() == ISD::SUB &&
1768 N0.getOperand(1).getOpcode() == ISD::SUB &&
1769 N0.getOperand(1).getOperand(1) == N1)
1770 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1771 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1773 // If either operand of a sub is undef, the result is undef
1774 if (N0.getOpcode() == ISD::UNDEF)
1776 if (N1.getOpcode() == ISD::UNDEF)
1779 // If the relocation model supports it, consider symbol offsets.
1780 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1781 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1782 // fold (sub Sym, c) -> Sym-c
1783 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1784 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1786 (uint64_t)N1C->getSExtValue());
1787 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1788 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1789 if (GA->getGlobal() == GB->getGlobal())
1790 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1797 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1798 SDValue N0 = N->getOperand(0);
1799 SDValue N1 = N->getOperand(1);
1800 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1801 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1802 EVT VT = N0.getValueType();
1804 // If the flag result is dead, turn this into an SUB.
1805 if (!N->hasAnyUseOfValue(1))
1806 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1807 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1810 // fold (subc x, x) -> 0 + no borrow
1812 return CombineTo(N, DAG.getConstant(0, VT),
1813 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1816 // fold (subc x, 0) -> x + no borrow
1817 if (N1C && N1C->isNullValue())
1818 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1821 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1822 if (N0C && N0C->isAllOnesValue())
1823 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1824 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1830 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1831 SDValue N0 = N->getOperand(0);
1832 SDValue N1 = N->getOperand(1);
1833 SDValue CarryIn = N->getOperand(2);
1835 // fold (sube x, y, false) -> (subc x, y)
1836 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1837 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1842 SDValue DAGCombiner::visitMUL(SDNode *N) {
1843 SDValue N0 = N->getOperand(0);
1844 SDValue N1 = N->getOperand(1);
1845 EVT VT = N0.getValueType();
1847 // fold (mul x, undef) -> 0
1848 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1849 return DAG.getConstant(0, VT);
1851 bool N0IsConst = false;
1852 bool N1IsConst = false;
1853 APInt ConstValue0, ConstValue1;
1855 if (VT.isVector()) {
1856 SDValue FoldedVOp = SimplifyVBinOp(N);
1857 if (FoldedVOp.getNode()) return FoldedVOp;
1859 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1860 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1862 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1863 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1865 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1866 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1870 // fold (mul c1, c2) -> c1*c2
1871 if (N0IsConst && N1IsConst)
1872 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1874 // canonicalize constant to RHS
1875 if (N0IsConst && !N1IsConst)
1876 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1877 // fold (mul x, 0) -> 0
1878 if (N1IsConst && ConstValue1 == 0)
1880 // We require a splat of the entire scalar bit width for non-contiguous
1883 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1884 // fold (mul x, 1) -> x
1885 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1887 // fold (mul x, -1) -> 0-x
1888 if (N1IsConst && ConstValue1.isAllOnesValue())
1889 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1890 DAG.getConstant(0, VT), N0);
1891 // fold (mul x, (1 << c)) -> x << c
1892 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1893 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1894 DAG.getConstant(ConstValue1.logBase2(),
1895 getShiftAmountTy(N0.getValueType())));
1896 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1897 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1898 unsigned Log2Val = (-ConstValue1).logBase2();
1899 // FIXME: If the input is something that is easily negated (e.g. a
1900 // single-use add), we should put the negate there.
1901 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1902 DAG.getConstant(0, VT),
1903 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1904 DAG.getConstant(Log2Val,
1905 getShiftAmountTy(N0.getValueType()))));
1909 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1910 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1911 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1912 isa<ConstantSDNode>(N0.getOperand(1)))) {
1913 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1914 N1, N0.getOperand(1));
1915 AddToWorkList(C3.getNode());
1916 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1917 N0.getOperand(0), C3);
1920 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1923 SDValue Sh(nullptr,0), Y(nullptr,0);
1924 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1925 if (N0.getOpcode() == ISD::SHL &&
1926 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1927 isa<ConstantSDNode>(N0.getOperand(1))) &&
1928 N0.getNode()->hasOneUse()) {
1930 } else if (N1.getOpcode() == ISD::SHL &&
1931 isa<ConstantSDNode>(N1.getOperand(1)) &&
1932 N1.getNode()->hasOneUse()) {
1937 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1938 Sh.getOperand(0), Y);
1939 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1940 Mul, Sh.getOperand(1));
1944 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1945 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1946 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1947 isa<ConstantSDNode>(N0.getOperand(1))))
1948 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1949 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1950 N0.getOperand(0), N1),
1951 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1952 N0.getOperand(1), N1));
1955 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1962 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1963 SDValue N0 = N->getOperand(0);
1964 SDValue N1 = N->getOperand(1);
1965 ConstantSDNode *N0C = isConstOrConstSplat(N0);
1966 ConstantSDNode *N1C = isConstOrConstSplat(N1);
1967 EVT VT = N->getValueType(0);
1970 if (VT.isVector()) {
1971 SDValue FoldedVOp = SimplifyVBinOp(N);
1972 if (FoldedVOp.getNode()) return FoldedVOp;
1975 // fold (sdiv c1, c2) -> c1/c2
1976 if (N0C && N1C && !N1C->isNullValue())
1977 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1978 // fold (sdiv X, 1) -> X
1979 if (N1C && N1C->getAPIntValue() == 1LL)
1981 // fold (sdiv X, -1) -> 0-X
1982 if (N1C && N1C->isAllOnesValue())
1983 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1984 DAG.getConstant(0, VT), N0);
1985 // If we know the sign bits of both operands are zero, strength reduce to a
1986 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1987 if (!VT.isVector()) {
1988 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1989 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
1993 // fold (sdiv X, pow2) -> simple ops after legalize
1994 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
1995 (-N1C->getAPIntValue()).isPowerOf2())) {
1996 // If dividing by powers of two is cheap, then don't perform the following
1998 if (TLI.isPow2DivCheap())
2001 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2003 // Splat the sign bit into the register
2005 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2006 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2007 getShiftAmountTy(N0.getValueType())));
2008 AddToWorkList(SGN.getNode());
2010 // Add (N0 < 0) ? abs2 - 1 : 0;
2012 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2013 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2014 getShiftAmountTy(SGN.getValueType())));
2015 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2016 AddToWorkList(SRL.getNode());
2017 AddToWorkList(ADD.getNode()); // Divide by pow2
2018 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2019 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2021 // If we're dividing by a positive value, we're done. Otherwise, we must
2022 // negate the result.
2023 if (N1C->getAPIntValue().isNonNegative())
2026 AddToWorkList(SRA.getNode());
2027 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2030 // if integer divide is expensive and we satisfy the requirements, emit an
2031 // alternate sequence.
2032 if (N1C && !TLI.isIntDivCheap()) {
2033 SDValue Op = BuildSDIV(N);
2034 if (Op.getNode()) return Op;
2038 if (N0.getOpcode() == ISD::UNDEF)
2039 return DAG.getConstant(0, VT);
2040 // X / undef -> undef
2041 if (N1.getOpcode() == ISD::UNDEF)
2047 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2048 SDValue N0 = N->getOperand(0);
2049 SDValue N1 = N->getOperand(1);
2050 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2051 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2052 EVT VT = N->getValueType(0);
2055 if (VT.isVector()) {
2056 SDValue FoldedVOp = SimplifyVBinOp(N);
2057 if (FoldedVOp.getNode()) return FoldedVOp;
2060 // fold (udiv c1, c2) -> c1/c2
2061 if (N0C && N1C && !N1C->isNullValue())
2062 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2063 // fold (udiv x, (1 << c)) -> x >>u c
2064 if (N1C && N1C->getAPIntValue().isPowerOf2())
2065 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2066 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2067 getShiftAmountTy(N0.getValueType())));
2068 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2069 if (N1.getOpcode() == ISD::SHL) {
2070 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2071 if (SHC->getAPIntValue().isPowerOf2()) {
2072 EVT ADDVT = N1.getOperand(1).getValueType();
2073 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2075 DAG.getConstant(SHC->getAPIntValue()
2078 AddToWorkList(Add.getNode());
2079 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2083 // fold (udiv x, c) -> alternate
2084 if (N1C && !TLI.isIntDivCheap()) {
2085 SDValue Op = BuildUDIV(N);
2086 if (Op.getNode()) return Op;
2090 if (N0.getOpcode() == ISD::UNDEF)
2091 return DAG.getConstant(0, VT);
2092 // X / undef -> undef
2093 if (N1.getOpcode() == ISD::UNDEF)
2099 SDValue DAGCombiner::visitSREM(SDNode *N) {
2100 SDValue N0 = N->getOperand(0);
2101 SDValue N1 = N->getOperand(1);
2102 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2103 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2104 EVT VT = N->getValueType(0);
2106 // fold (srem c1, c2) -> c1%c2
2107 if (N0C && N1C && !N1C->isNullValue())
2108 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2109 // If we know the sign bits of both operands are zero, strength reduce to a
2110 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2111 if (!VT.isVector()) {
2112 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2113 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2116 // If X/C can be simplified by the division-by-constant logic, lower
2117 // X%C to the equivalent of X-X/C*C.
2118 if (N1C && !N1C->isNullValue()) {
2119 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2120 AddToWorkList(Div.getNode());
2121 SDValue OptimizedDiv = combine(Div.getNode());
2122 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2123 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2125 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2126 AddToWorkList(Mul.getNode());
2132 if (N0.getOpcode() == ISD::UNDEF)
2133 return DAG.getConstant(0, VT);
2134 // X % undef -> undef
2135 if (N1.getOpcode() == ISD::UNDEF)
2141 SDValue DAGCombiner::visitUREM(SDNode *N) {
2142 SDValue N0 = N->getOperand(0);
2143 SDValue N1 = N->getOperand(1);
2144 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2145 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2146 EVT VT = N->getValueType(0);
2148 // fold (urem c1, c2) -> c1%c2
2149 if (N0C && N1C && !N1C->isNullValue())
2150 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2151 // fold (urem x, pow2) -> (and x, pow2-1)
2152 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2153 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2154 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2155 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2156 if (N1.getOpcode() == ISD::SHL) {
2157 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2158 if (SHC->getAPIntValue().isPowerOf2()) {
2160 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2161 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2163 AddToWorkList(Add.getNode());
2164 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2169 // If X/C can be simplified by the division-by-constant logic, lower
2170 // X%C to the equivalent of X-X/C*C.
2171 if (N1C && !N1C->isNullValue()) {
2172 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2173 AddToWorkList(Div.getNode());
2174 SDValue OptimizedDiv = combine(Div.getNode());
2175 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2176 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2178 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2179 AddToWorkList(Mul.getNode());
2185 if (N0.getOpcode() == ISD::UNDEF)
2186 return DAG.getConstant(0, VT);
2187 // X % undef -> undef
2188 if (N1.getOpcode() == ISD::UNDEF)
2194 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2195 SDValue N0 = N->getOperand(0);
2196 SDValue N1 = N->getOperand(1);
2197 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2198 EVT VT = N->getValueType(0);
2201 // fold (mulhs x, 0) -> 0
2202 if (N1C && N1C->isNullValue())
2204 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2205 if (N1C && N1C->getAPIntValue() == 1)
2206 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2207 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2208 getShiftAmountTy(N0.getValueType())));
2209 // fold (mulhs x, undef) -> 0
2210 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2211 return DAG.getConstant(0, VT);
2213 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2215 if (VT.isSimple() && !VT.isVector()) {
2216 MVT Simple = VT.getSimpleVT();
2217 unsigned SimpleSize = Simple.getSizeInBits();
2218 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2219 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2220 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2221 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2222 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2223 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2224 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2225 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2232 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2233 SDValue N0 = N->getOperand(0);
2234 SDValue N1 = N->getOperand(1);
2235 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2236 EVT VT = N->getValueType(0);
2239 // fold (mulhu x, 0) -> 0
2240 if (N1C && N1C->isNullValue())
2242 // fold (mulhu x, 1) -> 0
2243 if (N1C && N1C->getAPIntValue() == 1)
2244 return DAG.getConstant(0, N0.getValueType());
2245 // fold (mulhu x, undef) -> 0
2246 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2247 return DAG.getConstant(0, VT);
2249 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2251 if (VT.isSimple() && !VT.isVector()) {
2252 MVT Simple = VT.getSimpleVT();
2253 unsigned SimpleSize = Simple.getSizeInBits();
2254 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2255 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2256 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2257 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2258 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2259 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2260 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2261 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2268 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2269 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2270 /// that are being performed. Return true if a simplification was made.
2272 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2274 // If the high half is not needed, just compute the low half.
2275 bool HiExists = N->hasAnyUseOfValue(1);
2277 (!LegalOperations ||
2278 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2279 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2280 N->op_begin(), N->getNumOperands());
2281 return CombineTo(N, Res, Res);
2284 // If the low half is not needed, just compute the high half.
2285 bool LoExists = N->hasAnyUseOfValue(0);
2287 (!LegalOperations ||
2288 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2289 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2290 N->op_begin(), N->getNumOperands());
2291 return CombineTo(N, Res, Res);
2294 // If both halves are used, return as it is.
2295 if (LoExists && HiExists)
2298 // If the two computed results can be simplified separately, separate them.
2300 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2301 N->op_begin(), N->getNumOperands());
2302 AddToWorkList(Lo.getNode());
2303 SDValue LoOpt = combine(Lo.getNode());
2304 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2305 (!LegalOperations ||
2306 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2307 return CombineTo(N, LoOpt, LoOpt);
2311 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2312 N->op_begin(), N->getNumOperands());
2313 AddToWorkList(Hi.getNode());
2314 SDValue HiOpt = combine(Hi.getNode());
2315 if (HiOpt.getNode() && HiOpt != Hi &&
2316 (!LegalOperations ||
2317 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2318 return CombineTo(N, HiOpt, HiOpt);
2324 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2325 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2326 if (Res.getNode()) return Res;
2328 EVT VT = N->getValueType(0);
2331 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2333 if (VT.isSimple() && !VT.isVector()) {
2334 MVT Simple = VT.getSimpleVT();
2335 unsigned SimpleSize = Simple.getSizeInBits();
2336 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2337 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2338 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2339 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2340 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2341 // Compute the high part as N1.
2342 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2343 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2344 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2345 // Compute the low part as N0.
2346 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2347 return CombineTo(N, Lo, Hi);
2354 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2355 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2356 if (Res.getNode()) return Res;
2358 EVT VT = N->getValueType(0);
2361 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2363 if (VT.isSimple() && !VT.isVector()) {
2364 MVT Simple = VT.getSimpleVT();
2365 unsigned SimpleSize = Simple.getSizeInBits();
2366 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2367 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2368 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2369 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2370 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2371 // Compute the high part as N1.
2372 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2373 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2374 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2375 // Compute the low part as N0.
2376 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2377 return CombineTo(N, Lo, Hi);
2384 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2385 // (smulo x, 2) -> (saddo x, x)
2386 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2387 if (C2->getAPIntValue() == 2)
2388 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2389 N->getOperand(0), N->getOperand(0));
2394 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2395 // (umulo x, 2) -> (uaddo x, x)
2396 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2397 if (C2->getAPIntValue() == 2)
2398 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2399 N->getOperand(0), N->getOperand(0));
2404 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2405 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2406 if (Res.getNode()) return Res;
2411 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2412 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2413 if (Res.getNode()) return Res;
2418 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2419 /// two operands of the same opcode, try to simplify it.
2420 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2421 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2422 EVT VT = N0.getValueType();
2423 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2425 // Bail early if none of these transforms apply.
2426 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2428 // For each of OP in AND/OR/XOR:
2429 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2430 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2431 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2432 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2434 // do not sink logical op inside of a vector extend, since it may combine
2436 EVT Op0VT = N0.getOperand(0).getValueType();
2437 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2438 N0.getOpcode() == ISD::SIGN_EXTEND ||
2439 // Avoid infinite looping with PromoteIntBinOp.
2440 (N0.getOpcode() == ISD::ANY_EXTEND &&
2441 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2442 (N0.getOpcode() == ISD::TRUNCATE &&
2443 (!TLI.isZExtFree(VT, Op0VT) ||
2444 !TLI.isTruncateFree(Op0VT, VT)) &&
2445 TLI.isTypeLegal(Op0VT))) &&
2447 Op0VT == N1.getOperand(0).getValueType() &&
2448 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2449 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2450 N0.getOperand(0).getValueType(),
2451 N0.getOperand(0), N1.getOperand(0));
2452 AddToWorkList(ORNode.getNode());
2453 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2456 // For each of OP in SHL/SRL/SRA/AND...
2457 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2458 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2459 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2460 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2461 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2462 N0.getOperand(1) == N1.getOperand(1)) {
2463 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2464 N0.getOperand(0).getValueType(),
2465 N0.getOperand(0), N1.getOperand(0));
2466 AddToWorkList(ORNode.getNode());
2467 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2468 ORNode, N0.getOperand(1));
2471 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2472 // Only perform this optimization after type legalization and before
2473 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2474 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2475 // we don't want to undo this promotion.
2476 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2478 if ((N0.getOpcode() == ISD::BITCAST ||
2479 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2480 Level == AfterLegalizeTypes) {
2481 SDValue In0 = N0.getOperand(0);
2482 SDValue In1 = N1.getOperand(0);
2483 EVT In0Ty = In0.getValueType();
2484 EVT In1Ty = In1.getValueType();
2486 // If both incoming values are integers, and the original types are the
2488 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2489 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2490 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2491 AddToWorkList(Op.getNode());
2496 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2497 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2498 // If both shuffles use the same mask, and both shuffle within a single
2499 // vector, then it is worthwhile to move the swizzle after the operation.
2500 // The type-legalizer generates this pattern when loading illegal
2501 // vector types from memory. In many cases this allows additional shuffle
2503 // There are other cases where moving the shuffle after the xor/and/or
2504 // is profitable even if shuffles don't perform a swizzle.
2505 // If both shuffles use the same mask, and both shuffles have the same first
2506 // or second operand, then it might still be profitable to move the shuffle
2507 // after the xor/and/or operation.
2508 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2509 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2510 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2512 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2513 "Inputs to shuffles are not the same type");
2515 // Check that both shuffles use the same mask. The masks are known to be of
2516 // the same length because the result vector type is the same.
2517 // Check also that shuffles have only one use to avoid introducing extra
2519 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2520 SVN0->getMask().equals(SVN1->getMask())) {
2521 SDValue ShOp = N0->getOperand(1);
2523 // Don't try to fold this node if it requires introducing a
2524 // build vector of all zeros that might be illegal at this stage.
2525 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2527 ShOp = DAG.getConstant(0, VT);
2532 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2533 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2534 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2535 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2536 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2537 N0->getOperand(0), N1->getOperand(0));
2538 AddToWorkList(NewNode.getNode());
2539 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2540 &SVN0->getMask()[0]);
2543 // Don't try to fold this node if it requires introducing a
2544 // build vector of all zeros that might be illegal at this stage.
2545 ShOp = N0->getOperand(0);
2546 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2548 ShOp = DAG.getConstant(0, VT);
2553 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2554 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2555 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2556 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2557 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2558 N0->getOperand(1), N1->getOperand(1));
2559 AddToWorkList(NewNode.getNode());
2560 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2561 &SVN0->getMask()[0]);
2569 SDValue DAGCombiner::visitAND(SDNode *N) {
2570 SDValue N0 = N->getOperand(0);
2571 SDValue N1 = N->getOperand(1);
2572 SDValue LL, LR, RL, RR, CC0, CC1;
2573 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2574 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2575 EVT VT = N1.getValueType();
2576 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2579 if (VT.isVector()) {
2580 SDValue FoldedVOp = SimplifyVBinOp(N);
2581 if (FoldedVOp.getNode()) return FoldedVOp;
2583 // fold (and x, 0) -> 0, vector edition
2584 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2586 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2589 // fold (and x, -1) -> x, vector edition
2590 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2592 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2596 // fold (and x, undef) -> 0
2597 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2598 return DAG.getConstant(0, VT);
2599 // fold (and c1, c2) -> c1&c2
2601 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2602 // canonicalize constant to RHS
2604 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2605 // fold (and x, -1) -> x
2606 if (N1C && N1C->isAllOnesValue())
2608 // if (and x, c) is known to be zero, return 0
2609 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2610 APInt::getAllOnesValue(BitWidth)))
2611 return DAG.getConstant(0, VT);
2613 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2616 // fold (and (or x, C), D) -> D if (C & D) == D
2617 if (N1C && N0.getOpcode() == ISD::OR)
2618 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2619 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2621 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2622 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2623 SDValue N0Op0 = N0.getOperand(0);
2624 APInt Mask = ~N1C->getAPIntValue();
2625 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2626 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2627 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2628 N0.getValueType(), N0Op0);
2630 // Replace uses of the AND with uses of the Zero extend node.
2633 // We actually want to replace all uses of the any_extend with the
2634 // zero_extend, to avoid duplicating things. This will later cause this
2635 // AND to be folded.
2636 CombineTo(N0.getNode(), Zext);
2637 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2640 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2641 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2642 // already be zero by virtue of the width of the base type of the load.
2644 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2646 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2647 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2648 N0.getOpcode() == ISD::LOAD) {
2649 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2650 N0 : N0.getOperand(0) );
2652 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2653 // This can be a pure constant or a vector splat, in which case we treat the
2654 // vector as a scalar and use the splat value.
2655 APInt Constant = APInt::getNullValue(1);
2656 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2657 Constant = C->getAPIntValue();
2658 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2659 APInt SplatValue, SplatUndef;
2660 unsigned SplatBitSize;
2662 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2663 SplatBitSize, HasAnyUndefs);
2665 // Undef bits can contribute to a possible optimisation if set, so
2667 SplatValue |= SplatUndef;
2669 // The splat value may be something like "0x00FFFFFF", which means 0 for
2670 // the first vector value and FF for the rest, repeating. We need a mask
2671 // that will apply equally to all members of the vector, so AND all the
2672 // lanes of the constant together.
2673 EVT VT = Vector->getValueType(0);
2674 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2676 // If the splat value has been compressed to a bitlength lower
2677 // than the size of the vector lane, we need to re-expand it to
2679 if (BitWidth > SplatBitSize)
2680 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2681 SplatBitSize < BitWidth;
2682 SplatBitSize = SplatBitSize * 2)
2683 SplatValue |= SplatValue.shl(SplatBitSize);
2685 Constant = APInt::getAllOnesValue(BitWidth);
2686 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2687 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2691 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2692 // actually legal and isn't going to get expanded, else this is a false
2694 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2695 Load->getMemoryVT());
2697 // Resize the constant to the same size as the original memory access before
2698 // extension. If it is still the AllOnesValue then this AND is completely
2701 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2704 switch (Load->getExtensionType()) {
2705 default: B = false; break;
2706 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2708 case ISD::NON_EXTLOAD: B = true; break;
2711 if (B && Constant.isAllOnesValue()) {
2712 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2713 // preserve semantics once we get rid of the AND.
2714 SDValue NewLoad(Load, 0);
2715 if (Load->getExtensionType() == ISD::EXTLOAD) {
2716 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2717 Load->getValueType(0), SDLoc(Load),
2718 Load->getChain(), Load->getBasePtr(),
2719 Load->getOffset(), Load->getMemoryVT(),
2720 Load->getMemOperand());
2721 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2722 if (Load->getNumValues() == 3) {
2723 // PRE/POST_INC loads have 3 values.
2724 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2725 NewLoad.getValue(2) };
2726 CombineTo(Load, To, 3, true);
2728 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2732 // Fold the AND away, taking care not to fold to the old load node if we
2734 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2736 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2739 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2740 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2741 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2742 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2744 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2745 LL.getValueType().isInteger()) {
2746 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2747 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2748 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2749 LR.getValueType(), LL, RL);
2750 AddToWorkList(ORNode.getNode());
2751 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2753 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2754 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2755 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2756 LR.getValueType(), LL, RL);
2757 AddToWorkList(ANDNode.getNode());
2758 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2760 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2761 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2762 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2763 LR.getValueType(), LL, RL);
2764 AddToWorkList(ORNode.getNode());
2765 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2768 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2769 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2770 Op0 == Op1 && LL.getValueType().isInteger() &&
2771 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2772 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2773 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2774 cast<ConstantSDNode>(RR)->isNullValue()))) {
2775 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2776 LL, DAG.getConstant(1, LL.getValueType()));
2777 AddToWorkList(ADDNode.getNode());
2778 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2779 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2781 // canonicalize equivalent to ll == rl
2782 if (LL == RR && LR == RL) {
2783 Op1 = ISD::getSetCCSwappedOperands(Op1);
2786 if (LL == RL && LR == RR) {
2787 bool isInteger = LL.getValueType().isInteger();
2788 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2789 if (Result != ISD::SETCC_INVALID &&
2790 (!LegalOperations ||
2791 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2792 TLI.isOperationLegal(ISD::SETCC,
2793 getSetCCResultType(N0.getSimpleValueType())))))
2794 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2799 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2800 if (N0.getOpcode() == N1.getOpcode()) {
2801 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2802 if (Tmp.getNode()) return Tmp;
2805 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2806 // fold (and (sra)) -> (and (srl)) when possible.
2807 if (!VT.isVector() &&
2808 SimplifyDemandedBits(SDValue(N, 0)))
2809 return SDValue(N, 0);
2811 // fold (zext_inreg (extload x)) -> (zextload x)
2812 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2813 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2814 EVT MemVT = LN0->getMemoryVT();
2815 // If we zero all the possible extended bits, then we can turn this into
2816 // a zextload if we are running before legalize or the operation is legal.
2817 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2818 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2819 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2820 ((!LegalOperations && !LN0->isVolatile()) ||
2821 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2822 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2823 LN0->getChain(), LN0->getBasePtr(),
2824 MemVT, LN0->getMemOperand());
2826 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2827 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2830 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2831 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2833 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2834 EVT MemVT = LN0->getMemoryVT();
2835 // If we zero all the possible extended bits, then we can turn this into
2836 // a zextload if we are running before legalize or the operation is legal.
2837 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2838 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2839 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2840 ((!LegalOperations && !LN0->isVolatile()) ||
2841 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2842 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2843 LN0->getChain(), LN0->getBasePtr(),
2844 MemVT, LN0->getMemOperand());
2846 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2847 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2851 // fold (and (load x), 255) -> (zextload x, i8)
2852 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2853 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2854 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2855 (N0.getOpcode() == ISD::ANY_EXTEND &&
2856 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2857 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2858 LoadSDNode *LN0 = HasAnyExt
2859 ? cast<LoadSDNode>(N0.getOperand(0))
2860 : cast<LoadSDNode>(N0);
2861 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2862 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2863 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2864 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2865 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2866 EVT LoadedVT = LN0->getMemoryVT();
2868 if (ExtVT == LoadedVT &&
2869 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2870 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2873 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2874 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2875 LN0->getMemOperand());
2877 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2878 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2881 // Do not change the width of a volatile load.
2882 // Do not generate loads of non-round integer types since these can
2883 // be expensive (and would be wrong if the type is not byte sized).
2884 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2885 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2886 EVT PtrType = LN0->getOperand(1).getValueType();
2888 unsigned Alignment = LN0->getAlignment();
2889 SDValue NewPtr = LN0->getBasePtr();
2891 // For big endian targets, we need to add an offset to the pointer
2892 // to load the correct bytes. For little endian systems, we merely
2893 // need to read fewer bytes from the same pointer.
2894 if (TLI.isBigEndian()) {
2895 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2896 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2897 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2898 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2899 NewPtr, DAG.getConstant(PtrOff, PtrType));
2900 Alignment = MinAlign(Alignment, PtrOff);
2903 AddToWorkList(NewPtr.getNode());
2905 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2907 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2908 LN0->getChain(), NewPtr,
2909 LN0->getPointerInfo(),
2910 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2911 Alignment, LN0->getTBAAInfo());
2913 CombineTo(LN0, Load, Load.getValue(1));
2914 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2920 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2921 VT.getSizeInBits() <= 64) {
2922 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2923 APInt ADDC = ADDI->getAPIntValue();
2924 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2925 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2926 // immediate for an add, but it is legal if its top c2 bits are set,
2927 // transform the ADD so the immediate doesn't need to be materialized
2929 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2930 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2931 SRLI->getZExtValue());
2932 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2934 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2936 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2937 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2938 CombineTo(N0.getNode(), NewAdd);
2939 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2947 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2948 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2949 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2950 N0.getOperand(1), false);
2951 if (BSwap.getNode())
2958 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2960 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2961 bool DemandHighBits) {
2962 if (!LegalOperations)
2965 EVT VT = N->getValueType(0);
2966 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2968 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2971 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2972 bool LookPassAnd0 = false;
2973 bool LookPassAnd1 = false;
2974 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2976 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2978 if (N0.getOpcode() == ISD::AND) {
2979 if (!N0.getNode()->hasOneUse())
2981 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2982 if (!N01C || N01C->getZExtValue() != 0xFF00)
2984 N0 = N0.getOperand(0);
2985 LookPassAnd0 = true;
2988 if (N1.getOpcode() == ISD::AND) {
2989 if (!N1.getNode()->hasOneUse())
2991 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2992 if (!N11C || N11C->getZExtValue() != 0xFF)
2994 N1 = N1.getOperand(0);
2995 LookPassAnd1 = true;
2998 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3000 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3002 if (!N0.getNode()->hasOneUse() ||
3003 !N1.getNode()->hasOneUse())
3006 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3007 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3010 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3013 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3014 SDValue N00 = N0->getOperand(0);
3015 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3016 if (!N00.getNode()->hasOneUse())
3018 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3019 if (!N001C || N001C->getZExtValue() != 0xFF)
3021 N00 = N00.getOperand(0);
3022 LookPassAnd0 = true;
3025 SDValue N10 = N1->getOperand(0);
3026 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3027 if (!N10.getNode()->hasOneUse())
3029 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3030 if (!N101C || N101C->getZExtValue() != 0xFF00)
3032 N10 = N10.getOperand(0);
3033 LookPassAnd1 = true;
3039 // Make sure everything beyond the low halfword gets set to zero since the SRL
3040 // 16 will clear the top bits.
3041 unsigned OpSizeInBits = VT.getSizeInBits();
3042 if (DemandHighBits && OpSizeInBits > 16) {
3043 // If the left-shift isn't masked out then the only way this is a bswap is
3044 // if all bits beyond the low 8 are 0. In that case the entire pattern
3045 // reduces to a left shift anyway: leave it for other parts of the combiner.
3049 // However, if the right shift isn't masked out then it might be because
3050 // it's not needed. See if we can spot that too.
3051 if (!LookPassAnd1 &&
3052 !DAG.MaskedValueIsZero(
3053 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3057 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3058 if (OpSizeInBits > 16)
3059 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3060 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3064 /// isBSwapHWordElement - Return true if the specified node is an element
3065 /// that makes up a 32-bit packed halfword byteswap. i.e.
3066 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3067 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3068 if (!N.getNode()->hasOneUse())
3071 unsigned Opc = N.getOpcode();
3072 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3075 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3080 switch (N1C->getZExtValue()) {
3083 case 0xFF: Num = 0; break;
3084 case 0xFF00: Num = 1; break;
3085 case 0xFF0000: Num = 2; break;
3086 case 0xFF000000: Num = 3; break;
3089 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3090 SDValue N0 = N.getOperand(0);
3091 if (Opc == ISD::AND) {
3092 if (Num == 0 || Num == 2) {
3094 // (x >> 8) & 0xff0000
3095 if (N0.getOpcode() != ISD::SRL)
3097 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3098 if (!C || C->getZExtValue() != 8)
3101 // (x << 8) & 0xff00
3102 // (x << 8) & 0xff000000
3103 if (N0.getOpcode() != ISD::SHL)
3105 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3106 if (!C || C->getZExtValue() != 8)
3109 } else if (Opc == ISD::SHL) {
3111 // (x & 0xff0000) << 8
3112 if (Num != 0 && Num != 2)
3114 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3115 if (!C || C->getZExtValue() != 8)
3117 } else { // Opc == ISD::SRL
3118 // (x & 0xff00) >> 8
3119 // (x & 0xff000000) >> 8
3120 if (Num != 1 && Num != 3)
3122 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3123 if (!C || C->getZExtValue() != 8)
3130 Parts[Num] = N0.getOperand(0).getNode();
3134 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3135 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3136 /// => (rotl (bswap x), 16)
3137 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3138 if (!LegalOperations)
3141 EVT VT = N->getValueType(0);
3144 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3147 SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3149 // (or (or (and), (and)), (or (and), (and)))
3150 // (or (or (or (and), (and)), (and)), (and))
3151 if (N0.getOpcode() != ISD::OR)
3153 SDValue N00 = N0.getOperand(0);
3154 SDValue N01 = N0.getOperand(1);
3156 if (N1.getOpcode() == ISD::OR &&
3157 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3158 // (or (or (and), (and)), (or (and), (and)))
3159 SDValue N000 = N00.getOperand(0);
3160 if (!isBSwapHWordElement(N000, Parts))
3163 SDValue N001 = N00.getOperand(1);
3164 if (!isBSwapHWordElement(N001, Parts))
3166 SDValue N010 = N01.getOperand(0);
3167 if (!isBSwapHWordElement(N010, Parts))
3169 SDValue N011 = N01.getOperand(1);
3170 if (!isBSwapHWordElement(N011, Parts))
3173 // (or (or (or (and), (and)), (and)), (and))
3174 if (!isBSwapHWordElement(N1, Parts))
3176 if (!isBSwapHWordElement(N01, Parts))
3178 if (N00.getOpcode() != ISD::OR)
3180 SDValue N000 = N00.getOperand(0);
3181 if (!isBSwapHWordElement(N000, Parts))
3183 SDValue N001 = N00.getOperand(1);
3184 if (!isBSwapHWordElement(N001, Parts))
3188 // Make sure the parts are all coming from the same node.
3189 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3192 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3193 SDValue(Parts[0],0));
3195 // Result of the bswap should be rotated by 16. If it's not legal, then
3196 // do (x << 16) | (x >> 16).
3197 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3198 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3199 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3200 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3201 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3202 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3203 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3204 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3207 SDValue DAGCombiner::visitOR(SDNode *N) {
3208 SDValue N0 = N->getOperand(0);
3209 SDValue N1 = N->getOperand(1);
3210 SDValue LL, LR, RL, RR, CC0, CC1;
3211 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3212 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3213 EVT VT = N1.getValueType();
3216 if (VT.isVector()) {
3217 SDValue FoldedVOp = SimplifyVBinOp(N);
3218 if (FoldedVOp.getNode()) return FoldedVOp;
3220 // fold (or x, 0) -> x, vector edition
3221 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3223 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3226 // fold (or x, -1) -> -1, vector edition
3227 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3229 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3232 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3233 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3234 // Do this only if the resulting shuffle is legal.
3235 if (isa<ShuffleVectorSDNode>(N0) &&
3236 isa<ShuffleVectorSDNode>(N1) &&
3237 N0->getOperand(1) == N1->getOperand(1) &&
3238 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3239 bool CanFold = true;
3240 unsigned NumElts = VT.getVectorNumElements();
3241 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3242 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3243 // We construct two shuffle masks:
3244 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3245 // and N1 as the second operand.
3246 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3247 // and N0 as the second operand.
3248 // We do this because OR is commutable and therefore there might be
3249 // two ways to fold this node into a shuffle.
3250 SmallVector<int,4> Mask1;
3251 SmallVector<int,4> Mask2;
3253 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3254 int M0 = SV0->getMaskElt(i);
3255 int M1 = SV1->getMaskElt(i);
3257 // Both shuffle indexes are undef. Propagate Undef.
3258 if (M0 < 0 && M1 < 0) {
3259 Mask1.push_back(M0);
3260 Mask2.push_back(M0);
3264 if (M0 < 0 || M1 < 0 ||
3265 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3266 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3271 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3272 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3276 // Fold this sequence only if the resulting shuffle is 'legal'.
3277 if (TLI.isShuffleMaskLegal(Mask1, VT))
3278 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3279 N1->getOperand(0), &Mask1[0]);
3280 if (TLI.isShuffleMaskLegal(Mask2, VT))
3281 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3282 N0->getOperand(0), &Mask2[0]);
3287 // fold (or x, undef) -> -1
3288 if (!LegalOperations &&
3289 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3290 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3291 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3293 // fold (or c1, c2) -> c1|c2
3295 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3296 // canonicalize constant to RHS
3298 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3299 // fold (or x, 0) -> x
3300 if (N1C && N1C->isNullValue())
3302 // fold (or x, -1) -> -1
3303 if (N1C && N1C->isAllOnesValue())
3305 // fold (or x, c) -> c iff (x & ~c) == 0
3306 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3309 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3310 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3311 if (BSwap.getNode())
3313 BSwap = MatchBSwapHWordLow(N, N0, N1);
3314 if (BSwap.getNode())
3318 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3321 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3322 // iff (c1 & c2) == 0.
3323 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3324 isa<ConstantSDNode>(N0.getOperand(1))) {
3325 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3326 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3327 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3330 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3331 DAG.getNode(ISD::OR, SDLoc(N0), VT,
3332 N0.getOperand(0), N1), COR);
3335 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3336 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3337 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3338 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3340 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3341 LL.getValueType().isInteger()) {
3342 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3343 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3344 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3345 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3346 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3347 LR.getValueType(), LL, RL);
3348 AddToWorkList(ORNode.getNode());
3349 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3351 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3352 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3353 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3354 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3355 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3356 LR.getValueType(), LL, RL);
3357 AddToWorkList(ANDNode.getNode());
3358 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3361 // canonicalize equivalent to ll == rl
3362 if (LL == RR && LR == RL) {
3363 Op1 = ISD::getSetCCSwappedOperands(Op1);
3366 if (LL == RL && LR == RR) {
3367 bool isInteger = LL.getValueType().isInteger();
3368 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3369 if (Result != ISD::SETCC_INVALID &&
3370 (!LegalOperations ||
3371 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3372 TLI.isOperationLegal(ISD::SETCC,
3373 getSetCCResultType(N0.getValueType())))))
3374 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3379 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3380 if (N0.getOpcode() == N1.getOpcode()) {
3381 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3382 if (Tmp.getNode()) return Tmp;
3385 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3386 if (N0.getOpcode() == ISD::AND &&
3387 N1.getOpcode() == ISD::AND &&
3388 N0.getOperand(1).getOpcode() == ISD::Constant &&
3389 N1.getOperand(1).getOpcode() == ISD::Constant &&
3390 // Don't increase # computations.
3391 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3392 // We can only do this xform if we know that bits from X that are set in C2
3393 // but not in C1 are already zero. Likewise for Y.
3394 const APInt &LHSMask =
3395 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3396 const APInt &RHSMask =
3397 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3399 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3400 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3401 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3402 N0.getOperand(0), N1.getOperand(0));
3403 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3404 DAG.getConstant(LHSMask | RHSMask, VT));
3408 // See if this is some rotate idiom.
3409 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3410 return SDValue(Rot, 0);
3412 // Simplify the operands using demanded-bits information.
3413 if (!VT.isVector() &&
3414 SimplifyDemandedBits(SDValue(N, 0)))
3415 return SDValue(N, 0);
3420 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3421 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3422 if (Op.getOpcode() == ISD::AND) {
3423 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3424 Mask = Op.getOperand(1);
3425 Op = Op.getOperand(0);
3431 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3439 // Return true if we can prove that, whenever Neg and Pos are both in the
3440 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3441 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3443 // (or (shift1 X, Neg), (shift2 X, Pos))
3445 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3446 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3447 // to consider shift amounts with defined behavior.
3448 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3449 // If OpSize is a power of 2 then:
3451 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3452 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3454 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3455 // for the stronger condition:
3457 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3459 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3460 // we can just replace Neg with Neg' for the rest of the function.
3462 // In other cases we check for the even stronger condition:
3464 // Neg == OpSize - Pos [B]
3466 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3467 // behavior if Pos == 0 (and consequently Neg == OpSize).
3469 // We could actually use [A] whenever OpSize is a power of 2, but the
3470 // only extra cases that it would match are those uninteresting ones
3471 // where Neg and Pos are never in range at the same time. E.g. for
3472 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3473 // as well as (sub 32, Pos), but:
3475 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3477 // always invokes undefined behavior for 32-bit X.
3479 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3480 unsigned MaskLoBits = 0;
3481 if (Neg.getOpcode() == ISD::AND &&
3482 isPowerOf2_64(OpSize) &&
3483 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3484 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3485 Neg = Neg.getOperand(0);
3486 MaskLoBits = Log2_64(OpSize);
3489 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3490 if (Neg.getOpcode() != ISD::SUB)
3492 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3495 SDValue NegOp1 = Neg.getOperand(1);
3497 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3498 // Pos'. The truncation is redundant for the purpose of the equality.
3500 Pos.getOpcode() == ISD::AND &&
3501 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3502 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3503 Pos = Pos.getOperand(0);
3505 // The condition we need is now:
3507 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3509 // If NegOp1 == Pos then we need:
3511 // OpSize & Mask == NegC & Mask
3513 // (because "x & Mask" is a truncation and distributes through subtraction).
3516 Width = NegC->getAPIntValue();
3517 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3518 // Then the condition we want to prove becomes:
3520 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3522 // which, again because "x & Mask" is a truncation, becomes:
3524 // NegC & Mask == (OpSize - PosC) & Mask
3525 // OpSize & Mask == (NegC + PosC) & Mask
3526 else if (Pos.getOpcode() == ISD::ADD &&
3527 Pos.getOperand(0) == NegOp1 &&
3528 Pos.getOperand(1).getOpcode() == ISD::Constant)
3529 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3530 NegC->getAPIntValue());
3534 // Now we just need to check that OpSize & Mask == Width & Mask.
3536 // Opsize & Mask is 0 since Mask is Opsize - 1.
3537 return Width.getLoBits(MaskLoBits) == 0;
3538 return Width == OpSize;
3541 // A subroutine of MatchRotate used once we have found an OR of two opposite
3542 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3543 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3544 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3545 // Neg with outer conversions stripped away.
3546 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3547 SDValue Neg, SDValue InnerPos,
3548 SDValue InnerNeg, unsigned PosOpcode,
3549 unsigned NegOpcode, SDLoc DL) {
3550 // fold (or (shl x, (*ext y)),
3551 // (srl x, (*ext (sub 32, y)))) ->
3552 // (rotl x, y) or (rotr x, (sub 32, y))
3554 // fold (or (shl x, (*ext (sub 32, y))),
3555 // (srl x, (*ext y))) ->
3556 // (rotr x, y) or (rotl x, (sub 32, y))
3557 EVT VT = Shifted.getValueType();
3558 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3559 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3560 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3561 HasPos ? Pos : Neg).getNode();
3567 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3568 // idioms for rotate, and if the target supports rotation instructions, generate
3570 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3571 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3572 EVT VT = LHS.getValueType();
3573 if (!TLI.isTypeLegal(VT)) return nullptr;
3575 // The target must have at least one rotate flavor.
3576 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3577 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3578 if (!HasROTL && !HasROTR) return nullptr;
3580 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3581 SDValue LHSShift; // The shift.
3582 SDValue LHSMask; // AND value if any.
3583 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3584 return nullptr; // Not part of a rotate.
3586 SDValue RHSShift; // The shift.
3587 SDValue RHSMask; // AND value if any.
3588 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3589 return nullptr; // Not part of a rotate.
3591 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3592 return nullptr; // Not shifting the same value.
3594 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3595 return nullptr; // Shifts must disagree.
3597 // Canonicalize shl to left side in a shl/srl pair.
3598 if (RHSShift.getOpcode() == ISD::SHL) {
3599 std::swap(LHS, RHS);
3600 std::swap(LHSShift, RHSShift);
3601 std::swap(LHSMask , RHSMask );
3604 unsigned OpSizeInBits = VT.getSizeInBits();
3605 SDValue LHSShiftArg = LHSShift.getOperand(0);
3606 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3607 SDValue RHSShiftArg = RHSShift.getOperand(0);
3608 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3610 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3611 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3612 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3613 RHSShiftAmt.getOpcode() == ISD::Constant) {
3614 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3615 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3616 if ((LShVal + RShVal) != OpSizeInBits)
3619 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3620 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3622 // If there is an AND of either shifted operand, apply it to the result.
3623 if (LHSMask.getNode() || RHSMask.getNode()) {
3624 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3626 if (LHSMask.getNode()) {
3627 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3628 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3630 if (RHSMask.getNode()) {
3631 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3632 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3635 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3638 return Rot.getNode();
3641 // If there is a mask here, and we have a variable shift, we can't be sure
3642 // that we're masking out the right stuff.
3643 if (LHSMask.getNode() || RHSMask.getNode())
3646 // If the shift amount is sign/zext/any-extended just peel it off.
3647 SDValue LExtOp0 = LHSShiftAmt;
3648 SDValue RExtOp0 = RHSShiftAmt;
3649 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3650 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3651 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3652 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3653 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3654 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3655 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3656 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3657 LExtOp0 = LHSShiftAmt.getOperand(0);
3658 RExtOp0 = RHSShiftAmt.getOperand(0);
3661 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3662 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3666 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3667 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3674 SDValue DAGCombiner::visitXOR(SDNode *N) {
3675 SDValue N0 = N->getOperand(0);
3676 SDValue N1 = N->getOperand(1);
3677 SDValue LHS, RHS, CC;
3678 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3679 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3680 EVT VT = N0.getValueType();
3683 if (VT.isVector()) {
3684 SDValue FoldedVOp = SimplifyVBinOp(N);
3685 if (FoldedVOp.getNode()) return FoldedVOp;
3687 // fold (xor x, 0) -> x, vector edition
3688 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3690 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3694 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3695 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3696 return DAG.getConstant(0, VT);
3697 // fold (xor x, undef) -> undef
3698 if (N0.getOpcode() == ISD::UNDEF)
3700 if (N1.getOpcode() == ISD::UNDEF)
3702 // fold (xor c1, c2) -> c1^c2
3704 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3705 // canonicalize constant to RHS
3707 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3708 // fold (xor x, 0) -> x
3709 if (N1C && N1C->isNullValue())
3712 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3716 // fold !(x cc y) -> (x !cc y)
3717 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3718 bool isInt = LHS.getValueType().isInteger();
3719 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3722 if (!LegalOperations ||
3723 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3724 switch (N0.getOpcode()) {
3726 llvm_unreachable("Unhandled SetCC Equivalent!");
3728 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3729 case ISD::SELECT_CC:
3730 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3731 N0.getOperand(3), NotCC);
3736 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3737 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3738 N0.getNode()->hasOneUse() &&
3739 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3740 SDValue V = N0.getOperand(0);
3741 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3742 DAG.getConstant(1, V.getValueType()));
3743 AddToWorkList(V.getNode());
3744 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3747 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3748 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3749 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3750 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3751 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3752 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3753 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3754 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3755 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3756 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3759 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3760 if (N1C && N1C->isAllOnesValue() &&
3761 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3762 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3763 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3764 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3765 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3766 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3767 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3768 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3771 // fold (xor (and x, y), y) -> (and (not x), y)
3772 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3773 N0->getOperand(1) == N1) {
3774 SDValue X = N0->getOperand(0);
3775 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3776 AddToWorkList(NotX.getNode());
3777 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3779 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3780 if (N1C && N0.getOpcode() == ISD::XOR) {
3781 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3782 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3784 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3785 DAG.getConstant(N1C->getAPIntValue() ^
3786 N00C->getAPIntValue(), VT));
3788 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3789 DAG.getConstant(N1C->getAPIntValue() ^
3790 N01C->getAPIntValue(), VT));
3792 // fold (xor x, x) -> 0
3794 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3796 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3797 if (N0.getOpcode() == N1.getOpcode()) {
3798 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3799 if (Tmp.getNode()) return Tmp;
3802 // Simplify the expression using non-local knowledge.
3803 if (!VT.isVector() &&
3804 SimplifyDemandedBits(SDValue(N, 0)))
3805 return SDValue(N, 0);
3810 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3811 /// the shift amount is a constant.
3812 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3813 // We can't and shouldn't fold opaque constants.
3814 if (Amt->isOpaque())
3817 SDNode *LHS = N->getOperand(0).getNode();
3818 if (!LHS->hasOneUse()) return SDValue();
3820 // We want to pull some binops through shifts, so that we have (and (shift))
3821 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3822 // thing happens with address calculations, so it's important to canonicalize
3824 bool HighBitSet = false; // Can we transform this if the high bit is set?
3826 switch (LHS->getOpcode()) {
3827 default: return SDValue();
3830 HighBitSet = false; // We can only transform sra if the high bit is clear.
3833 HighBitSet = true; // We can only transform sra if the high bit is set.
3836 if (N->getOpcode() != ISD::SHL)
3837 return SDValue(); // only shl(add) not sr[al](add).
3838 HighBitSet = false; // We can only transform sra if the high bit is clear.
3842 // We require the RHS of the binop to be a constant and not opaque as well.
3843 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3844 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3846 // FIXME: disable this unless the input to the binop is a shift by a constant.
3847 // If it is not a shift, it pessimizes some common cases like:
3849 // void foo(int *X, int i) { X[i & 1235] = 1; }
3850 // int bar(int *X, int i) { return X[i & 255]; }
3851 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3852 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3853 BinOpLHSVal->getOpcode() != ISD::SRA &&
3854 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3855 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3858 EVT VT = N->getValueType(0);
3860 // If this is a signed shift right, and the high bit is modified by the
3861 // logical operation, do not perform the transformation. The highBitSet
3862 // boolean indicates the value of the high bit of the constant which would
3863 // cause it to be modified for this operation.
3864 if (N->getOpcode() == ISD::SRA) {
3865 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3866 if (BinOpRHSSignSet != HighBitSet)
3870 // Fold the constants, shifting the binop RHS by the shift amount.
3871 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3873 LHS->getOperand(1), N->getOperand(1));
3874 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3876 // Create the new shift.
3877 SDValue NewShift = DAG.getNode(N->getOpcode(),
3878 SDLoc(LHS->getOperand(0)),
3879 VT, LHS->getOperand(0), N->getOperand(1));
3881 // Create the new binop.
3882 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3885 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3886 assert(N->getOpcode() == ISD::TRUNCATE);
3887 assert(N->getOperand(0).getOpcode() == ISD::AND);
3889 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3890 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3891 SDValue N01 = N->getOperand(0).getOperand(1);
3893 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3894 EVT TruncVT = N->getValueType(0);
3895 SDValue N00 = N->getOperand(0).getOperand(0);
3896 APInt TruncC = N01C->getAPIntValue();
3897 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3899 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3900 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3901 DAG.getConstant(TruncC, TruncVT));
3908 SDValue DAGCombiner::visitRotate(SDNode *N) {
3909 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3910 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3911 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3912 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3913 if (NewOp1.getNode())
3914 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3915 N->getOperand(0), NewOp1);
3920 SDValue DAGCombiner::visitSHL(SDNode *N) {
3921 SDValue N0 = N->getOperand(0);
3922 SDValue N1 = N->getOperand(1);
3923 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3924 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3925 EVT VT = N0.getValueType();
3926 unsigned OpSizeInBits = VT.getScalarSizeInBits();
3929 if (VT.isVector()) {
3930 SDValue FoldedVOp = SimplifyVBinOp(N);
3931 if (FoldedVOp.getNode()) return FoldedVOp;
3933 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3934 // If setcc produces all-one true value then:
3935 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
3936 if (N1CV && N1CV->isConstant()) {
3937 if (N0.getOpcode() == ISD::AND &&
3938 TLI.getBooleanContents(true) ==
3939 TargetLowering::ZeroOrNegativeOneBooleanContent) {
3940 SDValue N00 = N0->getOperand(0);
3941 SDValue N01 = N0->getOperand(1);
3942 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
3944 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC) {
3945 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3947 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3950 N1C = isConstOrConstSplat(N1);
3955 // fold (shl c1, c2) -> c1<<c2
3957 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3958 // fold (shl 0, x) -> 0
3959 if (N0C && N0C->isNullValue())
3961 // fold (shl x, c >= size(x)) -> undef
3962 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3963 return DAG.getUNDEF(VT);
3964 // fold (shl x, 0) -> x
3965 if (N1C && N1C->isNullValue())
3967 // fold (shl undef, x) -> 0
3968 if (N0.getOpcode() == ISD::UNDEF)
3969 return DAG.getConstant(0, VT);
3970 // if (shl x, c) is known to be zero, return 0
3971 if (DAG.MaskedValueIsZero(SDValue(N, 0),
3972 APInt::getAllOnesValue(OpSizeInBits)))
3973 return DAG.getConstant(0, VT);
3974 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3975 if (N1.getOpcode() == ISD::TRUNCATE &&
3976 N1.getOperand(0).getOpcode() == ISD::AND) {
3977 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
3978 if (NewOp1.getNode())
3979 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
3982 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3983 return SDValue(N, 0);
3985 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3986 if (N1C && N0.getOpcode() == ISD::SHL) {
3987 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
3988 uint64_t c1 = N0C1->getZExtValue();
3989 uint64_t c2 = N1C->getZExtValue();
3990 if (c1 + c2 >= OpSizeInBits)
3991 return DAG.getConstant(0, VT);
3992 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3993 DAG.getConstant(c1 + c2, N1.getValueType()));
3997 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3998 // For this to be valid, the second form must not preserve any of the bits
3999 // that are shifted out by the inner shift in the first form. This means
4000 // the outer shift size must be >= the number of bits added by the ext.
4001 // As a corollary, we don't care what kind of ext it is.
4002 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4003 N0.getOpcode() == ISD::ANY_EXTEND ||
4004 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4005 N0.getOperand(0).getOpcode() == ISD::SHL) {
4006 SDValue N0Op0 = N0.getOperand(0);
4007 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4008 uint64_t c1 = N0Op0C1->getZExtValue();
4009 uint64_t c2 = N1C->getZExtValue();
4010 EVT InnerShiftVT = N0Op0.getValueType();
4011 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4012 if (c2 >= OpSizeInBits - InnerShiftSize) {
4013 if (c1 + c2 >= OpSizeInBits)
4014 return DAG.getConstant(0, VT);
4015 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4016 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4017 N0Op0->getOperand(0)),
4018 DAG.getConstant(c1 + c2, N1.getValueType()));
4023 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4024 // Only fold this if the inner zext has no other uses to avoid increasing
4025 // the total number of instructions.
4026 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4027 N0.getOperand(0).getOpcode() == ISD::SRL) {
4028 SDValue N0Op0 = N0.getOperand(0);
4029 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4030 uint64_t c1 = N0Op0C1->getZExtValue();
4031 if (c1 < VT.getScalarSizeInBits()) {
4032 uint64_t c2 = N1C->getZExtValue();
4034 SDValue NewOp0 = N0.getOperand(0);
4035 EVT CountVT = NewOp0.getOperand(1).getValueType();
4036 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4037 NewOp0, DAG.getConstant(c2, CountVT));
4038 AddToWorkList(NewSHL.getNode());
4039 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4045 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4046 // (and (srl x, (sub c1, c2), MASK)
4047 // Only fold this if the inner shift has no other uses -- if it does, folding
4048 // this will increase the total number of instructions.
4049 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4050 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4051 uint64_t c1 = N0C1->getZExtValue();
4052 if (c1 < OpSizeInBits) {
4053 uint64_t c2 = N1C->getZExtValue();
4054 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4057 Mask = Mask.shl(c2 - c1);
4058 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4059 DAG.getConstant(c2 - c1, N1.getValueType()));
4061 Mask = Mask.lshr(c1 - c2);
4062 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4063 DAG.getConstant(c1 - c2, N1.getValueType()));
4065 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4066 DAG.getConstant(Mask, VT));
4070 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4071 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4072 unsigned BitSize = VT.getScalarSizeInBits();
4073 SDValue HiBitsMask =
4074 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4075 BitSize - N1C->getZExtValue()), VT);
4076 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4081 SDValue NewSHL = visitShiftByConstant(N, N1C);
4082 if (NewSHL.getNode())
4089 SDValue DAGCombiner::visitSRA(SDNode *N) {
4090 SDValue N0 = N->getOperand(0);
4091 SDValue N1 = N->getOperand(1);
4092 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4093 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4094 EVT VT = N0.getValueType();
4095 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4098 if (VT.isVector()) {
4099 SDValue FoldedVOp = SimplifyVBinOp(N);
4100 if (FoldedVOp.getNode()) return FoldedVOp;
4102 N1C = isConstOrConstSplat(N1);
4105 // fold (sra c1, c2) -> (sra c1, c2)
4107 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4108 // fold (sra 0, x) -> 0
4109 if (N0C && N0C->isNullValue())
4111 // fold (sra -1, x) -> -1
4112 if (N0C && N0C->isAllOnesValue())
4114 // fold (sra x, (setge c, size(x))) -> undef
4115 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4116 return DAG.getUNDEF(VT);
4117 // fold (sra x, 0) -> x
4118 if (N1C && N1C->isNullValue())
4120 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4122 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4123 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4124 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4126 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4127 ExtVT, VT.getVectorNumElements());
4128 if ((!LegalOperations ||
4129 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4130 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4131 N0.getOperand(0), DAG.getValueType(ExtVT));
4134 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4135 if (N1C && N0.getOpcode() == ISD::SRA) {
4136 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4137 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4138 if (Sum >= OpSizeInBits)
4139 Sum = OpSizeInBits - 1;
4140 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4141 DAG.getConstant(Sum, N1.getValueType()));
4145 // fold (sra (shl X, m), (sub result_size, n))
4146 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4147 // result_size - n != m.
4148 // If truncate is free for the target sext(shl) is likely to result in better
4150 if (N0.getOpcode() == ISD::SHL && N1C) {
4151 // Get the two constanst of the shifts, CN0 = m, CN = n.
4152 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4154 LLVMContext &Ctx = *DAG.getContext();
4155 // Determine what the truncate's result bitsize and type would be.
4156 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4159 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4161 // Determine the residual right-shift amount.
4162 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4164 // If the shift is not a no-op (in which case this should be just a sign
4165 // extend already), the truncated to type is legal, sign_extend is legal
4166 // on that type, and the truncate to that type is both legal and free,
4167 // perform the transform.
4168 if ((ShiftAmt > 0) &&
4169 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4170 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4171 TLI.isTruncateFree(VT, TruncVT)) {
4173 SDValue Amt = DAG.getConstant(ShiftAmt,
4174 getShiftAmountTy(N0.getOperand(0).getValueType()));
4175 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4176 N0.getOperand(0), Amt);
4177 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4179 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4180 N->getValueType(0), Trunc);
4185 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4186 if (N1.getOpcode() == ISD::TRUNCATE &&
4187 N1.getOperand(0).getOpcode() == ISD::AND) {
4188 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4189 if (NewOp1.getNode())
4190 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4193 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4194 // if c1 is equal to the number of bits the trunc removes
4195 if (N0.getOpcode() == ISD::TRUNCATE &&
4196 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4197 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4198 N0.getOperand(0).hasOneUse() &&
4199 N0.getOperand(0).getOperand(1).hasOneUse() &&
4201 SDValue N0Op0 = N0.getOperand(0);
4202 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4203 unsigned LargeShiftVal = LargeShift->getZExtValue();
4204 EVT LargeVT = N0Op0.getValueType();
4206 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4208 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4209 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4210 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4211 N0Op0.getOperand(0), Amt);
4212 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4217 // Simplify, based on bits shifted out of the LHS.
4218 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4219 return SDValue(N, 0);
4222 // If the sign bit is known to be zero, switch this to a SRL.
4223 if (DAG.SignBitIsZero(N0))
4224 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4227 SDValue NewSRA = visitShiftByConstant(N, N1C);
4228 if (NewSRA.getNode())
4235 SDValue DAGCombiner::visitSRL(SDNode *N) {
4236 SDValue N0 = N->getOperand(0);
4237 SDValue N1 = N->getOperand(1);
4238 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4239 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4240 EVT VT = N0.getValueType();
4241 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4244 if (VT.isVector()) {
4245 SDValue FoldedVOp = SimplifyVBinOp(N);
4246 if (FoldedVOp.getNode()) return FoldedVOp;
4248 N1C = isConstOrConstSplat(N1);
4251 // fold (srl c1, c2) -> c1 >>u c2
4253 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4254 // fold (srl 0, x) -> 0
4255 if (N0C && N0C->isNullValue())
4257 // fold (srl x, c >= size(x)) -> undef
4258 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4259 return DAG.getUNDEF(VT);
4260 // fold (srl x, 0) -> x
4261 if (N1C && N1C->isNullValue())
4263 // if (srl x, c) is known to be zero, return 0
4264 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4265 APInt::getAllOnesValue(OpSizeInBits)))
4266 return DAG.getConstant(0, VT);
4268 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4269 if (N1C && N0.getOpcode() == ISD::SRL) {
4270 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4271 uint64_t c1 = N01C->getZExtValue();
4272 uint64_t c2 = N1C->getZExtValue();
4273 if (c1 + c2 >= OpSizeInBits)
4274 return DAG.getConstant(0, VT);
4275 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4276 DAG.getConstant(c1 + c2, N1.getValueType()));
4280 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4281 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4282 N0.getOperand(0).getOpcode() == ISD::SRL &&
4283 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4285 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4286 uint64_t c2 = N1C->getZExtValue();
4287 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4288 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4289 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4290 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4291 if (c1 + OpSizeInBits == InnerShiftSize) {
4292 if (c1 + c2 >= InnerShiftSize)
4293 return DAG.getConstant(0, VT);
4294 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4295 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4296 N0.getOperand(0)->getOperand(0),
4297 DAG.getConstant(c1 + c2, ShiftCountVT)));
4301 // fold (srl (shl x, c), c) -> (and x, cst2)
4302 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4303 unsigned BitSize = N0.getScalarValueSizeInBits();
4304 if (BitSize <= 64) {
4305 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4306 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4307 DAG.getConstant(~0ULL >> ShAmt, VT));
4311 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4312 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4313 // Shifting in all undef bits?
4314 EVT SmallVT = N0.getOperand(0).getValueType();
4315 unsigned BitSize = SmallVT.getScalarSizeInBits();
4316 if (N1C->getZExtValue() >= BitSize)
4317 return DAG.getUNDEF(VT);
4319 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4320 uint64_t ShiftAmt = N1C->getZExtValue();
4321 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4323 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4324 AddToWorkList(SmallShift.getNode());
4325 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4326 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4327 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4328 DAG.getConstant(Mask, VT));
4332 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4333 // bit, which is unmodified by sra.
4334 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4335 if (N0.getOpcode() == ISD::SRA)
4336 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4339 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4340 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4341 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4342 APInt KnownZero, KnownOne;
4343 DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
4345 // If any of the input bits are KnownOne, then the input couldn't be all
4346 // zeros, thus the result of the srl will always be zero.
4347 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4349 // If all of the bits input the to ctlz node are known to be zero, then
4350 // the result of the ctlz is "32" and the result of the shift is one.
4351 APInt UnknownBits = ~KnownZero;
4352 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4354 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4355 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4356 // Okay, we know that only that the single bit specified by UnknownBits
4357 // could be set on input to the CTLZ node. If this bit is set, the SRL
4358 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4359 // to an SRL/XOR pair, which is likely to simplify more.
4360 unsigned ShAmt = UnknownBits.countTrailingZeros();
4361 SDValue Op = N0.getOperand(0);
4364 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4365 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4366 AddToWorkList(Op.getNode());
4369 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4370 Op, DAG.getConstant(1, VT));
4374 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4375 if (N1.getOpcode() == ISD::TRUNCATE &&
4376 N1.getOperand(0).getOpcode() == ISD::AND) {
4377 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4378 if (NewOp1.getNode())
4379 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4382 // fold operands of srl based on knowledge that the low bits are not
4384 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4385 return SDValue(N, 0);
4388 SDValue NewSRL = visitShiftByConstant(N, N1C);
4389 if (NewSRL.getNode())
4393 // Attempt to convert a srl of a load into a narrower zero-extending load.
4394 SDValue NarrowLoad = ReduceLoadWidth(N);
4395 if (NarrowLoad.getNode())
4398 // Here is a common situation. We want to optimize:
4401 // %b = and i32 %a, 2
4402 // %c = srl i32 %b, 1
4403 // brcond i32 %c ...
4409 // %c = setcc eq %b, 0
4412 // However when after the source operand of SRL is optimized into AND, the SRL
4413 // itself may not be optimized further. Look for it and add the BRCOND into
4415 if (N->hasOneUse()) {
4416 SDNode *Use = *N->use_begin();
4417 if (Use->getOpcode() == ISD::BRCOND)
4419 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4420 // Also look pass the truncate.
4421 Use = *Use->use_begin();
4422 if (Use->getOpcode() == ISD::BRCOND)
4430 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4431 SDValue N0 = N->getOperand(0);
4432 EVT VT = N->getValueType(0);
4434 // fold (ctlz c1) -> c2
4435 if (isa<ConstantSDNode>(N0))
4436 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4440 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4441 SDValue N0 = N->getOperand(0);
4442 EVT VT = N->getValueType(0);
4444 // fold (ctlz_zero_undef c1) -> c2
4445 if (isa<ConstantSDNode>(N0))
4446 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4450 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4451 SDValue N0 = N->getOperand(0);
4452 EVT VT = N->getValueType(0);
4454 // fold (cttz c1) -> c2
4455 if (isa<ConstantSDNode>(N0))
4456 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4460 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4461 SDValue N0 = N->getOperand(0);
4462 EVT VT = N->getValueType(0);
4464 // fold (cttz_zero_undef c1) -> c2
4465 if (isa<ConstantSDNode>(N0))
4466 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4470 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4471 SDValue N0 = N->getOperand(0);
4472 EVT VT = N->getValueType(0);
4474 // fold (ctpop c1) -> c2
4475 if (isa<ConstantSDNode>(N0))
4476 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4480 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4481 SDValue N0 = N->getOperand(0);
4482 SDValue N1 = N->getOperand(1);
4483 SDValue N2 = N->getOperand(2);
4484 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4485 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4486 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4487 EVT VT = N->getValueType(0);
4488 EVT VT0 = N0.getValueType();
4490 // fold (select C, X, X) -> X
4493 // fold (select true, X, Y) -> X
4494 if (N0C && !N0C->isNullValue())
4496 // fold (select false, X, Y) -> Y
4497 if (N0C && N0C->isNullValue())
4499 // fold (select C, 1, X) -> (or C, X)
4500 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4501 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4502 // fold (select C, 0, 1) -> (xor C, 1)
4503 if (VT.isInteger() &&
4506 TLI.getBooleanContents(false) ==
4507 TargetLowering::ZeroOrOneBooleanContent)) &&
4508 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4511 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4512 N0, DAG.getConstant(1, VT0));
4513 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4514 N0, DAG.getConstant(1, VT0));
4515 AddToWorkList(XORNode.getNode());
4517 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4518 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4520 // fold (select C, 0, X) -> (and (not C), X)
4521 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4522 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4523 AddToWorkList(NOTNode.getNode());
4524 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4526 // fold (select C, X, 1) -> (or (not C), X)
4527 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4528 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4529 AddToWorkList(NOTNode.getNode());
4530 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4532 // fold (select C, X, 0) -> (and C, X)
4533 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4534 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4535 // fold (select X, X, Y) -> (or X, Y)
4536 // fold (select X, 1, Y) -> (or X, Y)
4537 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4538 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4539 // fold (select X, Y, X) -> (and X, Y)
4540 // fold (select X, Y, 0) -> (and X, Y)
4541 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4542 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4544 // If we can fold this based on the true/false value, do so.
4545 if (SimplifySelectOps(N, N1, N2))
4546 return SDValue(N, 0); // Don't revisit N.
4548 // fold selects based on a setcc into other things, such as min/max/abs
4549 if (N0.getOpcode() == ISD::SETCC) {
4551 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4552 // having to say they don't support SELECT_CC on every type the DAG knows
4553 // about, since there is no way to mark an opcode illegal at all value types
4554 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4555 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4556 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4557 N0.getOperand(0), N0.getOperand(1),
4558 N1, N2, N0.getOperand(2));
4559 return SimplifySelect(SDLoc(N), N0, N1, N2);
4566 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4569 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4571 // Split the inputs.
4572 SDValue Lo, Hi, LL, LH, RL, RH;
4573 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4574 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4576 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4577 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4579 return std::make_pair(Lo, Hi);
4582 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4583 SDValue N0 = N->getOperand(0);
4584 SDValue N1 = N->getOperand(1);
4585 SDValue N2 = N->getOperand(2);
4588 // Canonicalize integer abs.
4589 // vselect (setg[te] X, 0), X, -X ->
4590 // vselect (setgt X, -1), X, -X ->
4591 // vselect (setl[te] X, 0), -X, X ->
4592 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4593 if (N0.getOpcode() == ISD::SETCC) {
4594 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4595 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4597 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4599 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4600 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4601 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4602 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4603 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4604 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4605 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4608 EVT VT = LHS.getValueType();
4609 SDValue Shift = DAG.getNode(
4610 ISD::SRA, DL, VT, LHS,
4611 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4612 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4613 AddToWorkList(Shift.getNode());
4614 AddToWorkList(Add.getNode());
4615 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4619 // If the VSELECT result requires splitting and the mask is provided by a
4620 // SETCC, then split both nodes and its operands before legalization. This
4621 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4622 // and enables future optimizations (e.g. min/max pattern matching on X86).
4623 if (N0.getOpcode() == ISD::SETCC) {
4624 EVT VT = N->getValueType(0);
4626 // Check if any splitting is required.
4627 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4628 TargetLowering::TypeSplitVector)
4631 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4632 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4633 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4634 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4636 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4637 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4639 // Add the new VSELECT nodes to the work list in case they need to be split
4641 AddToWorkList(Lo.getNode());
4642 AddToWorkList(Hi.getNode());
4644 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4647 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4648 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4650 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4651 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4657 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4658 SDValue N0 = N->getOperand(0);
4659 SDValue N1 = N->getOperand(1);
4660 SDValue N2 = N->getOperand(2);
4661 SDValue N3 = N->getOperand(3);
4662 SDValue N4 = N->getOperand(4);
4663 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4665 // fold select_cc lhs, rhs, x, x, cc -> x
4669 // Determine if the condition we're dealing with is constant
4670 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4671 N0, N1, CC, SDLoc(N), false);
4672 if (SCC.getNode()) {
4673 AddToWorkList(SCC.getNode());
4675 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4676 if (!SCCC->isNullValue())
4677 return N2; // cond always true -> true val
4679 return N3; // cond always false -> false val
4682 // Fold to a simpler select_cc
4683 if (SCC.getOpcode() == ISD::SETCC)
4684 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4685 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4689 // If we can fold this based on the true/false value, do so.
4690 if (SimplifySelectOps(N, N2, N3))
4691 return SDValue(N, 0); // Don't revisit N.
4693 // fold select_cc into other things, such as min/max/abs
4694 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4697 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4698 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4699 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4703 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4704 // dag node into a ConstantSDNode or a build_vector of constants.
4705 // This function is called by the DAGCombiner when visiting sext/zext/aext
4706 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4707 // Vector extends are not folded if operations are legal; this is to
4708 // avoid introducing illegal build_vector dag nodes.
4709 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4710 SelectionDAG &DAG, bool LegalTypes,
4711 bool LegalOperations) {
4712 unsigned Opcode = N->getOpcode();
4713 SDValue N0 = N->getOperand(0);
4714 EVT VT = N->getValueType(0);
4716 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4717 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4719 // fold (sext c1) -> c1
4720 // fold (zext c1) -> c1
4721 // fold (aext c1) -> c1
4722 if (isa<ConstantSDNode>(N0))
4723 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4725 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4726 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4727 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4728 EVT SVT = VT.getScalarType();
4729 if (!(VT.isVector() &&
4730 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4731 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4734 // We can fold this node into a build_vector.
4735 unsigned VTBits = SVT.getSizeInBits();
4736 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4737 unsigned ShAmt = VTBits - EVTBits;
4738 SmallVector<SDValue, 8> Elts;
4739 unsigned NumElts = N0->getNumOperands();
4742 for (unsigned i=0; i != NumElts; ++i) {
4743 SDValue Op = N0->getOperand(i);
4744 if (Op->getOpcode() == ISD::UNDEF) {
4745 Elts.push_back(DAG.getUNDEF(SVT));
4749 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4750 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4751 if (Opcode == ISD::SIGN_EXTEND)
4752 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4755 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4759 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4762 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4763 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4764 // transformation. Returns true if extension are possible and the above
4765 // mentioned transformation is profitable.
4766 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4768 SmallVectorImpl<SDNode *> &ExtendNodes,
4769 const TargetLowering &TLI) {
4770 bool HasCopyToRegUses = false;
4771 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4772 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4773 UE = N0.getNode()->use_end();
4778 if (UI.getUse().getResNo() != N0.getResNo())
4780 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4781 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4782 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4783 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4784 // Sign bits will be lost after a zext.
4787 for (unsigned i = 0; i != 2; ++i) {
4788 SDValue UseOp = User->getOperand(i);
4791 if (!isa<ConstantSDNode>(UseOp))
4796 ExtendNodes.push_back(User);
4799 // If truncates aren't free and there are users we can't
4800 // extend, it isn't worthwhile.
4803 // Remember if this value is live-out.
4804 if (User->getOpcode() == ISD::CopyToReg)
4805 HasCopyToRegUses = true;
4808 if (HasCopyToRegUses) {
4809 bool BothLiveOut = false;
4810 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4812 SDUse &Use = UI.getUse();
4813 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4819 // Both unextended and extended values are live out. There had better be
4820 // a good reason for the transformation.
4821 return ExtendNodes.size();
4826 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4827 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4828 ISD::NodeType ExtType) {
4829 // Extend SetCC uses if necessary.
4830 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4831 SDNode *SetCC = SetCCs[i];
4832 SmallVector<SDValue, 4> Ops;
4834 for (unsigned j = 0; j != 2; ++j) {
4835 SDValue SOp = SetCC->getOperand(j);
4837 Ops.push_back(ExtLoad);
4839 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4842 Ops.push_back(SetCC->getOperand(2));
4843 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
4847 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4848 SDValue N0 = N->getOperand(0);
4849 EVT VT = N->getValueType(0);
4851 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4853 return SDValue(Res, 0);
4855 // fold (sext (sext x)) -> (sext x)
4856 // fold (sext (aext x)) -> (sext x)
4857 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4858 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4861 if (N0.getOpcode() == ISD::TRUNCATE) {
4862 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4863 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4864 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4865 if (NarrowLoad.getNode()) {
4866 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4867 if (NarrowLoad.getNode() != N0.getNode()) {
4868 CombineTo(N0.getNode(), NarrowLoad);
4869 // CombineTo deleted the truncate, if needed, but not what's under it.
4872 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4875 // See if the value being truncated is already sign extended. If so, just
4876 // eliminate the trunc/sext pair.
4877 SDValue Op = N0.getOperand(0);
4878 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4879 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4880 unsigned DestBits = VT.getScalarType().getSizeInBits();
4881 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4883 if (OpBits == DestBits) {
4884 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4885 // bits, it is already ready.
4886 if (NumSignBits > DestBits-MidBits)
4888 } else if (OpBits < DestBits) {
4889 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4890 // bits, just sext from i32.
4891 if (NumSignBits > OpBits-MidBits)
4892 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4894 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4895 // bits, just truncate to i32.
4896 if (NumSignBits > OpBits-MidBits)
4897 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4900 // fold (sext (truncate x)) -> (sextinreg x).
4901 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4902 N0.getValueType())) {
4903 if (OpBits < DestBits)
4904 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4905 else if (OpBits > DestBits)
4906 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4907 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4908 DAG.getValueType(N0.getValueType()));
4912 // fold (sext (load x)) -> (sext (truncate (sextload x)))
4913 // None of the supported targets knows how to perform load and sign extend
4914 // on vectors in one instruction. We only perform this transformation on
4916 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4917 ISD::isUNINDEXEDLoad(N0.getNode()) &&
4918 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4919 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4920 bool DoXform = true;
4921 SmallVector<SDNode*, 4> SetCCs;
4922 if (!N0.hasOneUse())
4923 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4925 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4926 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4928 LN0->getBasePtr(), N0.getValueType(),
4929 LN0->getMemOperand());
4930 CombineTo(N, ExtLoad);
4931 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4932 N0.getValueType(), ExtLoad);
4933 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4934 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4936 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4940 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4941 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4942 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4943 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4944 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4945 EVT MemVT = LN0->getMemoryVT();
4946 if ((!LegalOperations && !LN0->isVolatile()) ||
4947 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4948 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4950 LN0->getBasePtr(), MemVT,
4951 LN0->getMemOperand());
4952 CombineTo(N, ExtLoad);
4953 CombineTo(N0.getNode(),
4954 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4955 N0.getValueType(), ExtLoad),
4956 ExtLoad.getValue(1));
4957 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4961 // fold (sext (and/or/xor (load x), cst)) ->
4962 // (and/or/xor (sextload x), (sext cst))
4963 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4964 N0.getOpcode() == ISD::XOR) &&
4965 isa<LoadSDNode>(N0.getOperand(0)) &&
4966 N0.getOperand(1).getOpcode() == ISD::Constant &&
4967 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4968 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4969 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4970 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
4971 bool DoXform = true;
4972 SmallVector<SDNode*, 4> SetCCs;
4973 if (!N0.hasOneUse())
4974 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4977 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
4978 LN0->getChain(), LN0->getBasePtr(),
4980 LN0->getMemOperand());
4981 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4982 Mask = Mask.sext(VT.getSizeInBits());
4983 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4984 ExtLoad, DAG.getConstant(Mask, VT));
4985 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4986 SDLoc(N0.getOperand(0)),
4987 N0.getOperand(0).getValueType(), ExtLoad);
4989 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4990 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4992 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4997 if (N0.getOpcode() == ISD::SETCC) {
4998 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
4999 // Only do this before legalize for now.
5000 if (VT.isVector() && !LegalOperations &&
5001 TLI.getBooleanContents(true) ==
5002 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5003 EVT N0VT = N0.getOperand(0).getValueType();
5004 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5005 // of the same size as the compared operands. Only optimize sext(setcc())
5006 // if this is the case.
5007 EVT SVT = getSetCCResultType(N0VT);
5009 // We know that the # elements of the results is the same as the
5010 // # elements of the compare (and the # elements of the compare result
5011 // for that matter). Check to see that they are the same size. If so,
5012 // we know that the element size of the sext'd result matches the
5013 // element size of the compare operands.
5014 if (VT.getSizeInBits() == SVT.getSizeInBits())
5015 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5017 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5019 // If the desired elements are smaller or larger than the source
5020 // elements we can use a matching integer vector type and then
5021 // truncate/sign extend
5022 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5023 if (SVT == MatchingVectorType) {
5024 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5025 N0.getOperand(0), N0.getOperand(1),
5026 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5027 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5031 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5032 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5034 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5036 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5037 NegOne, DAG.getConstant(0, VT),
5038 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5039 if (SCC.getNode()) return SCC;
5041 if (!VT.isVector()) {
5042 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5043 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5045 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5046 SDValue SetCC = DAG.getSetCC(DL,
5048 N0.getOperand(0), N0.getOperand(1), CC);
5049 EVT SelectVT = getSetCCResultType(VT);
5050 return DAG.getSelect(DL, VT,
5051 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5052 NegOne, DAG.getConstant(0, VT));
5058 // fold (sext x) -> (zext x) if the sign bit is known zero.
5059 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5060 DAG.SignBitIsZero(N0))
5061 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5066 // isTruncateOf - If N is a truncate of some other value, return true, record
5067 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5068 // This function computes KnownZero to avoid a duplicated call to
5069 // ComputeMaskedBits in the caller.
5070 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5073 if (N->getOpcode() == ISD::TRUNCATE) {
5074 Op = N->getOperand(0);
5075 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5079 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5080 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5083 SDValue Op0 = N->getOperand(0);
5084 SDValue Op1 = N->getOperand(1);
5085 assert(Op0.getValueType() == Op1.getValueType());
5087 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5088 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5089 if (COp0 && COp0->isNullValue())
5091 else if (COp1 && COp1->isNullValue())
5096 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5098 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5104 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5105 SDValue N0 = N->getOperand(0);
5106 EVT VT = N->getValueType(0);
5108 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5110 return SDValue(Res, 0);
5112 // fold (zext (zext x)) -> (zext x)
5113 // fold (zext (aext x)) -> (zext x)
5114 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5115 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5118 // fold (zext (truncate x)) -> (zext x) or
5119 // (zext (truncate x)) -> (truncate x)
5120 // This is valid when the truncated bits of x are already zero.
5121 // FIXME: We should extend this to work for vectors too.
5124 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5125 APInt TruncatedBits =
5126 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5127 APInt(Op.getValueSizeInBits(), 0) :
5128 APInt::getBitsSet(Op.getValueSizeInBits(),
5129 N0.getValueSizeInBits(),
5130 std::min(Op.getValueSizeInBits(),
5131 VT.getSizeInBits()));
5132 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5133 if (VT.bitsGT(Op.getValueType()))
5134 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5135 if (VT.bitsLT(Op.getValueType()))
5136 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5142 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5143 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5144 if (N0.getOpcode() == ISD::TRUNCATE) {
5145 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5146 if (NarrowLoad.getNode()) {
5147 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5148 if (NarrowLoad.getNode() != N0.getNode()) {
5149 CombineTo(N0.getNode(), NarrowLoad);
5150 // CombineTo deleted the truncate, if needed, but not what's under it.
5153 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5157 // fold (zext (truncate x)) -> (and x, mask)
5158 if (N0.getOpcode() == ISD::TRUNCATE &&
5159 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5161 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5162 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5163 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5164 if (NarrowLoad.getNode()) {
5165 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5166 if (NarrowLoad.getNode() != N0.getNode()) {
5167 CombineTo(N0.getNode(), NarrowLoad);
5168 // CombineTo deleted the truncate, if needed, but not what's under it.
5171 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5174 SDValue Op = N0.getOperand(0);
5175 if (Op.getValueType().bitsLT(VT)) {
5176 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5177 AddToWorkList(Op.getNode());
5178 } else if (Op.getValueType().bitsGT(VT)) {
5179 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5180 AddToWorkList(Op.getNode());
5182 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5183 N0.getValueType().getScalarType());
5186 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5187 // if either of the casts is not free.
5188 if (N0.getOpcode() == ISD::AND &&
5189 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5190 N0.getOperand(1).getOpcode() == ISD::Constant &&
5191 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5192 N0.getValueType()) ||
5193 !TLI.isZExtFree(N0.getValueType(), VT))) {
5194 SDValue X = N0.getOperand(0).getOperand(0);
5195 if (X.getValueType().bitsLT(VT)) {
5196 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5197 } else if (X.getValueType().bitsGT(VT)) {
5198 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5200 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5201 Mask = Mask.zext(VT.getSizeInBits());
5202 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5203 X, DAG.getConstant(Mask, VT));
5206 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5207 // None of the supported targets knows how to perform load and vector_zext
5208 // on vectors in one instruction. We only perform this transformation on
5210 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5211 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5212 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5213 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5214 bool DoXform = true;
5215 SmallVector<SDNode*, 4> SetCCs;
5216 if (!N0.hasOneUse())
5217 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5219 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5220 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5222 LN0->getBasePtr(), N0.getValueType(),
5223 LN0->getMemOperand());
5224 CombineTo(N, ExtLoad);
5225 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5226 N0.getValueType(), ExtLoad);
5227 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5229 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5231 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5235 // fold (zext (and/or/xor (load x), cst)) ->
5236 // (and/or/xor (zextload x), (zext cst))
5237 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5238 N0.getOpcode() == ISD::XOR) &&
5239 isa<LoadSDNode>(N0.getOperand(0)) &&
5240 N0.getOperand(1).getOpcode() == ISD::Constant &&
5241 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5242 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5243 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5244 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5245 bool DoXform = true;
5246 SmallVector<SDNode*, 4> SetCCs;
5247 if (!N0.hasOneUse())
5248 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5251 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5252 LN0->getChain(), LN0->getBasePtr(),
5254 LN0->getMemOperand());
5255 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5256 Mask = Mask.zext(VT.getSizeInBits());
5257 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5258 ExtLoad, DAG.getConstant(Mask, VT));
5259 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5260 SDLoc(N0.getOperand(0)),
5261 N0.getOperand(0).getValueType(), ExtLoad);
5263 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5264 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5266 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5271 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5272 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5273 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5274 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5275 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5276 EVT MemVT = LN0->getMemoryVT();
5277 if ((!LegalOperations && !LN0->isVolatile()) ||
5278 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5279 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5281 LN0->getBasePtr(), MemVT,
5282 LN0->getMemOperand());
5283 CombineTo(N, ExtLoad);
5284 CombineTo(N0.getNode(),
5285 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5287 ExtLoad.getValue(1));
5288 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5292 if (N0.getOpcode() == ISD::SETCC) {
5293 if (!LegalOperations && VT.isVector() &&
5294 N0.getValueType().getVectorElementType() == MVT::i1) {
5295 EVT N0VT = N0.getOperand(0).getValueType();
5296 if (getSetCCResultType(N0VT) == N0.getValueType())
5299 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5300 // Only do this before legalize for now.
5301 EVT EltVT = VT.getVectorElementType();
5302 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5303 DAG.getConstant(1, EltVT));
5304 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5305 // We know that the # elements of the results is the same as the
5306 // # elements of the compare (and the # elements of the compare result
5307 // for that matter). Check to see that they are the same size. If so,
5308 // we know that the element size of the sext'd result matches the
5309 // element size of the compare operands.
5310 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5311 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5313 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5314 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5317 // If the desired elements are smaller or larger than the source
5318 // elements we can use a matching integer vector type and then
5319 // truncate/sign extend
5320 EVT MatchingElementType =
5321 EVT::getIntegerVT(*DAG.getContext(),
5322 N0VT.getScalarType().getSizeInBits());
5323 EVT MatchingVectorType =
5324 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5325 N0VT.getVectorNumElements());
5327 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5329 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5330 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5331 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5332 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5335 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5337 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5338 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5339 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5340 if (SCC.getNode()) return SCC;
5343 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5344 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5345 isa<ConstantSDNode>(N0.getOperand(1)) &&
5346 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5348 SDValue ShAmt = N0.getOperand(1);
5349 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5350 if (N0.getOpcode() == ISD::SHL) {
5351 SDValue InnerZExt = N0.getOperand(0);
5352 // If the original shl may be shifting out bits, do not perform this
5354 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5355 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5356 if (ShAmtVal > KnownZeroBits)
5362 // Ensure that the shift amount is wide enough for the shifted value.
5363 if (VT.getSizeInBits() >= 256)
5364 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5366 return DAG.getNode(N0.getOpcode(), DL, VT,
5367 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5374 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5375 SDValue N0 = N->getOperand(0);
5376 EVT VT = N->getValueType(0);
5378 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5380 return SDValue(Res, 0);
5382 // fold (aext (aext x)) -> (aext x)
5383 // fold (aext (zext x)) -> (zext x)
5384 // fold (aext (sext x)) -> (sext x)
5385 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5386 N0.getOpcode() == ISD::ZERO_EXTEND ||
5387 N0.getOpcode() == ISD::SIGN_EXTEND)
5388 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5390 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5391 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5392 if (N0.getOpcode() == ISD::TRUNCATE) {
5393 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5394 if (NarrowLoad.getNode()) {
5395 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5396 if (NarrowLoad.getNode() != N0.getNode()) {
5397 CombineTo(N0.getNode(), NarrowLoad);
5398 // CombineTo deleted the truncate, if needed, but not what's under it.
5401 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5405 // fold (aext (truncate x))
5406 if (N0.getOpcode() == ISD::TRUNCATE) {
5407 SDValue TruncOp = N0.getOperand(0);
5408 if (TruncOp.getValueType() == VT)
5409 return TruncOp; // x iff x size == zext size.
5410 if (TruncOp.getValueType().bitsGT(VT))
5411 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5412 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5415 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5416 // if the trunc is not free.
5417 if (N0.getOpcode() == ISD::AND &&
5418 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5419 N0.getOperand(1).getOpcode() == ISD::Constant &&
5420 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5421 N0.getValueType())) {
5422 SDValue X = N0.getOperand(0).getOperand(0);
5423 if (X.getValueType().bitsLT(VT)) {
5424 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5425 } else if (X.getValueType().bitsGT(VT)) {
5426 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5428 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5429 Mask = Mask.zext(VT.getSizeInBits());
5430 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5431 X, DAG.getConstant(Mask, VT));
5434 // fold (aext (load x)) -> (aext (truncate (extload x)))
5435 // None of the supported targets knows how to perform load and any_ext
5436 // on vectors in one instruction. We only perform this transformation on
5438 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5439 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5440 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5441 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5442 bool DoXform = true;
5443 SmallVector<SDNode*, 4> SetCCs;
5444 if (!N0.hasOneUse())
5445 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5447 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5448 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5450 LN0->getBasePtr(), N0.getValueType(),
5451 LN0->getMemOperand());
5452 CombineTo(N, ExtLoad);
5453 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5454 N0.getValueType(), ExtLoad);
5455 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5456 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5458 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5462 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5463 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5464 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5465 if (N0.getOpcode() == ISD::LOAD &&
5466 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5468 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5469 ISD::LoadExtType ExtType = LN0->getExtensionType();
5470 EVT MemVT = LN0->getMemoryVT();
5471 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5472 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5473 VT, LN0->getChain(), LN0->getBasePtr(),
5474 MemVT, LN0->getMemOperand());
5475 CombineTo(N, ExtLoad);
5476 CombineTo(N0.getNode(),
5477 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5478 N0.getValueType(), ExtLoad),
5479 ExtLoad.getValue(1));
5480 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5484 if (N0.getOpcode() == ISD::SETCC) {
5486 // aext(setcc) -> vsetcc
5487 // aext(setcc) -> truncate(vsetcc)
5488 // aext(setcc) -> aext(vsetcc)
5489 // Only do this before legalize for now.
5490 if (VT.isVector() && !LegalOperations) {
5491 EVT N0VT = N0.getOperand(0).getValueType();
5492 // We know that the # elements of the results is the same as the
5493 // # elements of the compare (and the # elements of the compare result
5494 // for that matter). Check to see that they are the same size. If so,
5495 // we know that the element size of the sext'd result matches the
5496 // element size of the compare operands.
5497 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5498 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5500 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5501 // If the desired elements are smaller or larger than the source
5502 // elements we can use a matching integer vector type and then
5503 // truncate/any extend
5505 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5507 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5509 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5510 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5514 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5516 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5517 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5518 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5526 /// GetDemandedBits - See if the specified operand can be simplified with the
5527 /// knowledge that only the bits specified by Mask are used. If so, return the
5528 /// simpler operand, otherwise return a null SDValue.
5529 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5530 switch (V.getOpcode()) {
5532 case ISD::Constant: {
5533 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5534 assert(CV && "Const value should be ConstSDNode.");
5535 const APInt &CVal = CV->getAPIntValue();
5536 APInt NewVal = CVal & Mask;
5538 return DAG.getConstant(NewVal, V.getValueType());
5543 // If the LHS or RHS don't contribute bits to the or, drop them.
5544 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5545 return V.getOperand(1);
5546 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5547 return V.getOperand(0);
5550 // Only look at single-use SRLs.
5551 if (!V.getNode()->hasOneUse())
5553 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5554 // See if we can recursively simplify the LHS.
5555 unsigned Amt = RHSC->getZExtValue();
5557 // Watch out for shift count overflow though.
5558 if (Amt >= Mask.getBitWidth()) break;
5559 APInt NewMask = Mask << Amt;
5560 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5561 if (SimplifyLHS.getNode())
5562 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5563 SimplifyLHS, V.getOperand(1));
5569 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5570 /// bits and then truncated to a narrower type and where N is a multiple
5571 /// of number of bits of the narrower type, transform it to a narrower load
5572 /// from address + N / num of bits of new type. If the result is to be
5573 /// extended, also fold the extension to form a extending load.
5574 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5575 unsigned Opc = N->getOpcode();
5577 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5578 SDValue N0 = N->getOperand(0);
5579 EVT VT = N->getValueType(0);
5582 // This transformation isn't valid for vector loads.
5586 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5588 if (Opc == ISD::SIGN_EXTEND_INREG) {
5589 ExtType = ISD::SEXTLOAD;
5590 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5591 } else if (Opc == ISD::SRL) {
5592 // Another special-case: SRL is basically zero-extending a narrower value.
5593 ExtType = ISD::ZEXTLOAD;
5595 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5596 if (!N01) return SDValue();
5597 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5598 VT.getSizeInBits() - N01->getZExtValue());
5600 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5603 unsigned EVTBits = ExtVT.getSizeInBits();
5605 // Do not generate loads of non-round integer types since these can
5606 // be expensive (and would be wrong if the type is not byte sized).
5607 if (!ExtVT.isRound())
5611 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5612 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5613 ShAmt = N01->getZExtValue();
5614 // Is the shift amount a multiple of size of VT?
5615 if ((ShAmt & (EVTBits-1)) == 0) {
5616 N0 = N0.getOperand(0);
5617 // Is the load width a multiple of size of VT?
5618 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5622 // At this point, we must have a load or else we can't do the transform.
5623 if (!isa<LoadSDNode>(N0)) return SDValue();
5625 // Because a SRL must be assumed to *need* to zero-extend the high bits
5626 // (as opposed to anyext the high bits), we can't combine the zextload
5627 // lowering of SRL and an sextload.
5628 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5631 // If the shift amount is larger than the input type then we're not
5632 // accessing any of the loaded bytes. If the load was a zextload/extload
5633 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5634 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5639 // If the load is shifted left (and the result isn't shifted back right),
5640 // we can fold the truncate through the shift.
5641 unsigned ShLeftAmt = 0;
5642 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5643 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5644 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5645 ShLeftAmt = N01->getZExtValue();
5646 N0 = N0.getOperand(0);
5650 // If we haven't found a load, we can't narrow it. Don't transform one with
5651 // multiple uses, this would require adding a new load.
5652 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5655 // Don't change the width of a volatile load.
5656 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5657 if (LN0->isVolatile())
5660 // Verify that we are actually reducing a load width here.
5661 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5664 // For the transform to be legal, the load must produce only two values
5665 // (the value loaded and the chain). Don't transform a pre-increment
5666 // load, for example, which produces an extra value. Otherwise the
5667 // transformation is not equivalent, and the downstream logic to replace
5668 // uses gets things wrong.
5669 if (LN0->getNumValues() > 2)
5672 // If the load that we're shrinking is an extload and we're not just
5673 // discarding the extension we can't simply shrink the load. Bail.
5674 // TODO: It would be possible to merge the extensions in some cases.
5675 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5676 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5679 EVT PtrType = N0.getOperand(1).getValueType();
5681 if (PtrType == MVT::Untyped || PtrType.isExtended())
5682 // It's not possible to generate a constant of extended or untyped type.
5685 // For big endian targets, we need to adjust the offset to the pointer to
5686 // load the correct bytes.
5687 if (TLI.isBigEndian()) {
5688 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5689 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5690 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5693 uint64_t PtrOff = ShAmt / 8;
5694 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5695 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5696 PtrType, LN0->getBasePtr(),
5697 DAG.getConstant(PtrOff, PtrType));
5698 AddToWorkList(NewPtr.getNode());
5701 if (ExtType == ISD::NON_EXTLOAD)
5702 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5703 LN0->getPointerInfo().getWithOffset(PtrOff),
5704 LN0->isVolatile(), LN0->isNonTemporal(),
5705 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5707 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5708 LN0->getPointerInfo().getWithOffset(PtrOff),
5709 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5710 NewAlign, LN0->getTBAAInfo());
5712 // Replace the old load's chain with the new load's chain.
5713 WorkListRemover DeadNodes(*this);
5714 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5716 // Shift the result left, if we've swallowed a left shift.
5717 SDValue Result = Load;
5718 if (ShLeftAmt != 0) {
5719 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5720 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5722 // If the shift amount is as large as the result size (but, presumably,
5723 // no larger than the source) then the useful bits of the result are
5724 // zero; we can't simply return the shortened shift, because the result
5725 // of that operation is undefined.
5726 if (ShLeftAmt >= VT.getSizeInBits())
5727 Result = DAG.getConstant(0, VT);
5729 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5730 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5733 // Return the new loaded value.
5737 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5738 SDValue N0 = N->getOperand(0);
5739 SDValue N1 = N->getOperand(1);
5740 EVT VT = N->getValueType(0);
5741 EVT EVT = cast<VTSDNode>(N1)->getVT();
5742 unsigned VTBits = VT.getScalarType().getSizeInBits();
5743 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5745 // fold (sext_in_reg c1) -> c1
5746 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5747 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5749 // If the input is already sign extended, just drop the extension.
5750 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5753 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5754 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5755 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5756 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5757 N0.getOperand(0), N1);
5759 // fold (sext_in_reg (sext x)) -> (sext x)
5760 // fold (sext_in_reg (aext x)) -> (sext x)
5761 // if x is small enough.
5762 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5763 SDValue N00 = N0.getOperand(0);
5764 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5765 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5766 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5769 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5770 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5771 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5773 // fold operands of sext_in_reg based on knowledge that the top bits are not
5775 if (SimplifyDemandedBits(SDValue(N, 0)))
5776 return SDValue(N, 0);
5778 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5779 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5780 SDValue NarrowLoad = ReduceLoadWidth(N);
5781 if (NarrowLoad.getNode())
5784 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5785 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5786 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5787 if (N0.getOpcode() == ISD::SRL) {
5788 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5789 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5790 // We can turn this into an SRA iff the input to the SRL is already sign
5792 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5793 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5794 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5795 N0.getOperand(0), N0.getOperand(1));
5799 // fold (sext_inreg (extload x)) -> (sextload x)
5800 if (ISD::isEXTLoad(N0.getNode()) &&
5801 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5802 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5803 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5804 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5805 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5806 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5808 LN0->getBasePtr(), EVT,
5809 LN0->getMemOperand());
5810 CombineTo(N, ExtLoad);
5811 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5812 AddToWorkList(ExtLoad.getNode());
5813 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5815 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5816 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5818 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5819 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5820 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5821 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5822 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5824 LN0->getBasePtr(), EVT,
5825 LN0->getMemOperand());
5826 CombineTo(N, ExtLoad);
5827 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5828 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5831 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5832 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5833 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5834 N0.getOperand(1), false);
5835 if (BSwap.getNode())
5836 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5840 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5841 // into a build_vector.
5842 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5843 SmallVector<SDValue, 8> Elts;
5844 unsigned NumElts = N0->getNumOperands();
5845 unsigned ShAmt = VTBits - EVTBits;
5847 for (unsigned i = 0; i != NumElts; ++i) {
5848 SDValue Op = N0->getOperand(i);
5849 if (Op->getOpcode() == ISD::UNDEF) {
5854 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5855 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5856 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5857 Op.getValueType()));
5860 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
5866 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5867 SDValue N0 = N->getOperand(0);
5868 EVT VT = N->getValueType(0);
5869 bool isLE = TLI.isLittleEndian();
5872 if (N0.getValueType() == N->getValueType(0))
5874 // fold (truncate c1) -> c1
5875 if (isa<ConstantSDNode>(N0))
5876 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5877 // fold (truncate (truncate x)) -> (truncate x)
5878 if (N0.getOpcode() == ISD::TRUNCATE)
5879 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5880 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5881 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5882 N0.getOpcode() == ISD::SIGN_EXTEND ||
5883 N0.getOpcode() == ISD::ANY_EXTEND) {
5884 if (N0.getOperand(0).getValueType().bitsLT(VT))
5885 // if the source is smaller than the dest, we still need an extend
5886 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5888 if (N0.getOperand(0).getValueType().bitsGT(VT))
5889 // if the source is larger than the dest, than we just need the truncate
5890 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5891 // if the source and dest are the same type, we can drop both the extend
5892 // and the truncate.
5893 return N0.getOperand(0);
5896 // Fold extract-and-trunc into a narrow extract. For example:
5897 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5898 // i32 y = TRUNCATE(i64 x)
5900 // v16i8 b = BITCAST (v2i64 val)
5901 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5903 // Note: We only run this optimization after type legalization (which often
5904 // creates this pattern) and before operation legalization after which
5905 // we need to be more careful about the vector instructions that we generate.
5906 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5907 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
5909 EVT VecTy = N0.getOperand(0).getValueType();
5910 EVT ExTy = N0.getValueType();
5911 EVT TrTy = N->getValueType(0);
5913 unsigned NumElem = VecTy.getVectorNumElements();
5914 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5916 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5917 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5919 SDValue EltNo = N0->getOperand(1);
5920 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5921 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5922 EVT IndexTy = TLI.getVectorIdxTy();
5923 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5925 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5926 NVT, N0.getOperand(0));
5928 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5930 DAG.getConstant(Index, IndexTy));
5934 // Fold a series of buildvector, bitcast, and truncate if possible.
5936 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5937 // (2xi32 (buildvector x, y)).
5938 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5939 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5940 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5941 N0.getOperand(0).hasOneUse()) {
5943 SDValue BuildVect = N0.getOperand(0);
5944 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5945 EVT TruncVecEltTy = VT.getVectorElementType();
5947 // Check that the element types match.
5948 if (BuildVectEltTy == TruncVecEltTy) {
5949 // Now we only need to compute the offset of the truncated elements.
5950 unsigned BuildVecNumElts = BuildVect.getNumOperands();
5951 unsigned TruncVecNumElts = VT.getVectorNumElements();
5952 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5954 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5955 "Invalid number of elements");
5957 SmallVector<SDValue, 8> Opnds;
5958 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5959 Opnds.push_back(BuildVect.getOperand(i));
5961 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
5965 // See if we can simplify the input to this truncate through knowledge that
5966 // only the low bits are being used.
5967 // For example "trunc (or (shl x, 8), y)" // -> trunc y
5968 // Currently we only perform this optimization on scalars because vectors
5969 // may have different active low bits.
5970 if (!VT.isVector()) {
5972 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5973 VT.getSizeInBits()));
5974 if (Shorter.getNode())
5975 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
5977 // fold (truncate (load x)) -> (smaller load x)
5978 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5979 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5980 SDValue Reduced = ReduceLoadWidth(N);
5981 if (Reduced.getNode())
5983 // Handle the case where the load remains an extending load even
5984 // after truncation.
5985 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
5986 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5987 if (!LN0->isVolatile() &&
5988 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
5989 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
5990 VT, LN0->getChain(), LN0->getBasePtr(),
5992 LN0->getMemOperand());
5993 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
5998 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
5999 // where ... are all 'undef'.
6000 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6001 SmallVector<EVT, 8> VTs;
6004 unsigned NumDefs = 0;
6006 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6007 SDValue X = N0.getOperand(i);
6008 if (X.getOpcode() != ISD::UNDEF) {
6013 // Stop if more than one members are non-undef.
6016 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6017 VT.getVectorElementType(),
6018 X.getValueType().getVectorNumElements()));
6022 return DAG.getUNDEF(VT);
6025 assert(V.getNode() && "The single defined operand is empty!");
6026 SmallVector<SDValue, 8> Opnds;
6027 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6029 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6032 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6033 AddToWorkList(NV.getNode());
6034 Opnds.push_back(NV);
6036 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6040 // Simplify the operands using demanded-bits information.
6041 if (!VT.isVector() &&
6042 SimplifyDemandedBits(SDValue(N, 0)))
6043 return SDValue(N, 0);
6048 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6049 SDValue Elt = N->getOperand(i);
6050 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6051 return Elt.getNode();
6052 return Elt.getOperand(Elt.getResNo()).getNode();
6055 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6056 /// if load locations are consecutive.
6057 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6058 assert(N->getOpcode() == ISD::BUILD_PAIR);
6060 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6061 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6062 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6063 LD1->getAddressSpace() != LD2->getAddressSpace())
6065 EVT LD1VT = LD1->getValueType(0);
6067 if (ISD::isNON_EXTLoad(LD2) &&
6069 // If both are volatile this would reduce the number of volatile loads.
6070 // If one is volatile it might be ok, but play conservative and bail out.
6071 !LD1->isVolatile() &&
6072 !LD2->isVolatile() &&
6073 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6074 unsigned Align = LD1->getAlignment();
6075 unsigned NewAlign = TLI.getDataLayout()->
6076 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6078 if (NewAlign <= Align &&
6079 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6080 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6081 LD1->getBasePtr(), LD1->getPointerInfo(),
6082 false, false, false, Align);
6088 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6089 SDValue N0 = N->getOperand(0);
6090 EVT VT = N->getValueType(0);
6092 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6093 // Only do this before legalize, since afterward the target may be depending
6094 // on the bitconvert.
6095 // First check to see if this is all constant.
6097 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6099 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6101 EVT DestEltVT = N->getValueType(0).getVectorElementType();
6102 assert(!DestEltVT.isVector() &&
6103 "Element type of vector ValueType must not be vector!");
6105 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6108 // If the input is a constant, let getNode fold it.
6109 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6110 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6111 if (Res.getNode() != N) {
6112 if (!LegalOperations ||
6113 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6116 // Folding it resulted in an illegal node, and it's too late to
6117 // do that. Clean up the old node and forego the transformation.
6118 // Ideally this won't happen very often, because instcombine
6119 // and the earlier dagcombine runs (where illegal nodes are
6120 // permitted) should have folded most of them already.
6121 DAG.DeleteNode(Res.getNode());
6125 // (conv (conv x, t1), t2) -> (conv x, t2)
6126 if (N0.getOpcode() == ISD::BITCAST)
6127 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6130 // fold (conv (load x)) -> (load (conv*)x)
6131 // If the resultant load doesn't need a higher alignment than the original!
6132 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6133 // Do not change the width of a volatile load.
6134 !cast<LoadSDNode>(N0)->isVolatile() &&
6135 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6136 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6137 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6138 unsigned Align = TLI.getDataLayout()->
6139 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6140 unsigned OrigAlign = LN0->getAlignment();
6142 if (Align <= OrigAlign) {
6143 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6144 LN0->getBasePtr(), LN0->getPointerInfo(),
6145 LN0->isVolatile(), LN0->isNonTemporal(),
6146 LN0->isInvariant(), OrigAlign,
6147 LN0->getTBAAInfo());
6149 CombineTo(N0.getNode(),
6150 DAG.getNode(ISD::BITCAST, SDLoc(N0),
6151 N0.getValueType(), Load),
6157 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6158 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6159 // This often reduces constant pool loads.
6160 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6161 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6162 N0.getNode()->hasOneUse() && VT.isInteger() &&
6163 !VT.isVector() && !N0.getValueType().isVector()) {
6164 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6166 AddToWorkList(NewConv.getNode());
6168 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6169 if (N0.getOpcode() == ISD::FNEG)
6170 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6171 NewConv, DAG.getConstant(SignBit, VT));
6172 assert(N0.getOpcode() == ISD::FABS);
6173 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6174 NewConv, DAG.getConstant(~SignBit, VT));
6177 // fold (bitconvert (fcopysign cst, x)) ->
6178 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6179 // Note that we don't handle (copysign x, cst) because this can always be
6180 // folded to an fneg or fabs.
6181 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6182 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6183 VT.isInteger() && !VT.isVector()) {
6184 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6185 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6186 if (isTypeLegal(IntXVT)) {
6187 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6188 IntXVT, N0.getOperand(1));
6189 AddToWorkList(X.getNode());
6191 // If X has a different width than the result/lhs, sext it or truncate it.
6192 unsigned VTWidth = VT.getSizeInBits();
6193 if (OrigXWidth < VTWidth) {
6194 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6195 AddToWorkList(X.getNode());
6196 } else if (OrigXWidth > VTWidth) {
6197 // To get the sign bit in the right place, we have to shift it right
6198 // before truncating.
6199 X = DAG.getNode(ISD::SRL, SDLoc(X),
6200 X.getValueType(), X,
6201 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6202 AddToWorkList(X.getNode());
6203 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6204 AddToWorkList(X.getNode());
6207 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6208 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6209 X, DAG.getConstant(SignBit, VT));
6210 AddToWorkList(X.getNode());
6212 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6213 VT, N0.getOperand(0));
6214 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6215 Cst, DAG.getConstant(~SignBit, VT));
6216 AddToWorkList(Cst.getNode());
6218 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6222 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6223 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6224 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6225 if (CombineLD.getNode())
6232 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6233 EVT VT = N->getValueType(0);
6234 return CombineConsecutiveLoads(N, VT);
6237 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6238 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
6239 /// destination element value type.
6240 SDValue DAGCombiner::
6241 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6242 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6244 // If this is already the right type, we're done.
6245 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6247 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6248 unsigned DstBitSize = DstEltVT.getSizeInBits();
6250 // If this is a conversion of N elements of one type to N elements of another
6251 // type, convert each element. This handles FP<->INT cases.
6252 if (SrcBitSize == DstBitSize) {
6253 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6254 BV->getValueType(0).getVectorNumElements());
6256 // Due to the FP element handling below calling this routine recursively,
6257 // we can end up with a scalar-to-vector node here.
6258 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6259 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6260 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6261 DstEltVT, BV->getOperand(0)));
6263 SmallVector<SDValue, 8> Ops;
6264 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6265 SDValue Op = BV->getOperand(i);
6266 // If the vector element type is not legal, the BUILD_VECTOR operands
6267 // are promoted and implicitly truncated. Make that explicit here.
6268 if (Op.getValueType() != SrcEltVT)
6269 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6270 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6272 AddToWorkList(Ops.back().getNode());
6274 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6277 // Otherwise, we're growing or shrinking the elements. To avoid having to
6278 // handle annoying details of growing/shrinking FP values, we convert them to
6280 if (SrcEltVT.isFloatingPoint()) {
6281 // Convert the input float vector to a int vector where the elements are the
6283 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6284 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6285 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6289 // Now we know the input is an integer vector. If the output is a FP type,
6290 // convert to integer first, then to FP of the right size.
6291 if (DstEltVT.isFloatingPoint()) {
6292 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6293 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6294 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6296 // Next, convert to FP elements of the same size.
6297 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6300 // Okay, we know the src/dst types are both integers of differing types.
6301 // Handling growing first.
6302 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6303 if (SrcBitSize < DstBitSize) {
6304 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6306 SmallVector<SDValue, 8> Ops;
6307 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6308 i += NumInputsPerOutput) {
6309 bool isLE = TLI.isLittleEndian();
6310 APInt NewBits = APInt(DstBitSize, 0);
6311 bool EltIsUndef = true;
6312 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6313 // Shift the previously computed bits over.
6314 NewBits <<= SrcBitSize;
6315 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6316 if (Op.getOpcode() == ISD::UNDEF) continue;
6319 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6320 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6324 Ops.push_back(DAG.getUNDEF(DstEltVT));
6326 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6329 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6330 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6333 // Finally, this must be the case where we are shrinking elements: each input
6334 // turns into multiple outputs.
6335 bool isS2V = ISD::isScalarToVector(BV);
6336 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6337 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6338 NumOutputsPerInput*BV->getNumOperands());
6339 SmallVector<SDValue, 8> Ops;
6341 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6342 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6343 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6344 Ops.push_back(DAG.getUNDEF(DstEltVT));
6348 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6349 getAPIntValue().zextOrTrunc(SrcBitSize);
6351 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6352 APInt ThisVal = OpVal.trunc(DstBitSize);
6353 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6354 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6355 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6356 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6358 OpVal = OpVal.lshr(DstBitSize);
6361 // For big endian targets, swap the order of the pieces of each element.
6362 if (TLI.isBigEndian())
6363 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6366 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6369 SDValue DAGCombiner::visitFADD(SDNode *N) {
6370 SDValue N0 = N->getOperand(0);
6371 SDValue N1 = N->getOperand(1);
6372 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6373 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6374 EVT VT = N->getValueType(0);
6377 if (VT.isVector()) {
6378 SDValue FoldedVOp = SimplifyVBinOp(N);
6379 if (FoldedVOp.getNode()) return FoldedVOp;
6382 // fold (fadd c1, c2) -> c1 + c2
6384 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6385 // canonicalize constant to RHS
6386 if (N0CFP && !N1CFP)
6387 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6388 // fold (fadd A, 0) -> A
6389 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6390 N1CFP->getValueAPF().isZero())
6392 // fold (fadd A, (fneg B)) -> (fsub A, B)
6393 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6394 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6395 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6396 GetNegatedExpression(N1, DAG, LegalOperations));
6397 // fold (fadd (fneg A), B) -> (fsub B, A)
6398 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6399 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6400 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6401 GetNegatedExpression(N0, DAG, LegalOperations));
6403 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6404 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6405 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6406 isa<ConstantFPSDNode>(N0.getOperand(1)))
6407 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6408 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6409 N0.getOperand(1), N1));
6411 // No FP constant should be created after legalization as Instruction
6412 // Selection pass has hard time in dealing with FP constant.
6414 // We don't need test this condition for transformation like following, as
6415 // the DAG being transformed implies it is legal to take FP constant as
6418 // (fadd (fmul c, x), x) -> (fmul c+1, x)
6420 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6422 // If allow, fold (fadd (fneg x), x) -> 0.0
6423 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6424 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6425 return DAG.getConstantFP(0.0, VT);
6427 // If allow, fold (fadd x, (fneg x)) -> 0.0
6428 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6429 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6430 return DAG.getConstantFP(0.0, VT);
6432 // In unsafe math mode, we can fold chains of FADD's of the same value
6433 // into multiplications. This transform is not safe in general because
6434 // we are reducing the number of rounding steps.
6435 if (DAG.getTarget().Options.UnsafeFPMath &&
6436 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6438 if (N0.getOpcode() == ISD::FMUL) {
6439 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6440 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6442 // (fadd (fmul c, x), x) -> (fmul x, c+1)
6443 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6444 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6446 DAG.getConstantFP(1.0, VT));
6447 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6451 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6452 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6453 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6455 DAG.getConstantFP(1.0, VT));
6456 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6460 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6461 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6462 N1.getOperand(0) == N1.getOperand(1) &&
6463 N0.getOperand(1) == N1.getOperand(0)) {
6464 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6466 DAG.getConstantFP(2.0, VT));
6467 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6468 N0.getOperand(1), NewCFP);
6471 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6472 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6473 N1.getOperand(0) == N1.getOperand(1) &&
6474 N0.getOperand(0) == N1.getOperand(0)) {
6475 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6477 DAG.getConstantFP(2.0, VT));
6478 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6479 N0.getOperand(0), NewCFP);
6483 if (N1.getOpcode() == ISD::FMUL) {
6484 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6485 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6487 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6488 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6489 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6491 DAG.getConstantFP(1.0, VT));
6492 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6496 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6497 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6498 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6500 DAG.getConstantFP(1.0, VT));
6501 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6506 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6507 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6508 N0.getOperand(0) == N0.getOperand(1) &&
6509 N1.getOperand(1) == N0.getOperand(0)) {
6510 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6512 DAG.getConstantFP(2.0, VT));
6513 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6514 N1.getOperand(1), NewCFP);
6517 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6518 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6519 N0.getOperand(0) == N0.getOperand(1) &&
6520 N1.getOperand(0) == N0.getOperand(0)) {
6521 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6523 DAG.getConstantFP(2.0, VT));
6524 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6525 N1.getOperand(0), NewCFP);
6529 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6530 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6531 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6532 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6533 (N0.getOperand(0) == N1))
6534 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6535 N1, DAG.getConstantFP(3.0, VT));
6538 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6539 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6540 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6541 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6542 N1.getOperand(0) == N0)
6543 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6544 N0, DAG.getConstantFP(3.0, VT));
6547 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6548 if (AllowNewFpConst &&
6549 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6550 N0.getOperand(0) == N0.getOperand(1) &&
6551 N1.getOperand(0) == N1.getOperand(1) &&
6552 N0.getOperand(0) == N1.getOperand(0))
6553 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6555 DAG.getConstantFP(4.0, VT));
6558 // FADD -> FMA combines:
6559 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6560 DAG.getTarget().Options.UnsafeFPMath) &&
6561 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6562 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6564 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6565 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6566 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6567 N0.getOperand(0), N0.getOperand(1), N1);
6569 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6570 // Note: Commutes FADD operands.
6571 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6572 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6573 N1.getOperand(0), N1.getOperand(1), N0);
6579 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6580 SDValue N0 = N->getOperand(0);
6581 SDValue N1 = N->getOperand(1);
6582 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6583 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6584 EVT VT = N->getValueType(0);
6588 if (VT.isVector()) {
6589 SDValue FoldedVOp = SimplifyVBinOp(N);
6590 if (FoldedVOp.getNode()) return FoldedVOp;
6593 // fold (fsub c1, c2) -> c1-c2
6595 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6596 // fold (fsub A, 0) -> A
6597 if (DAG.getTarget().Options.UnsafeFPMath &&
6598 N1CFP && N1CFP->getValueAPF().isZero())
6600 // fold (fsub 0, B) -> -B
6601 if (DAG.getTarget().Options.UnsafeFPMath &&
6602 N0CFP && N0CFP->getValueAPF().isZero()) {
6603 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6604 return GetNegatedExpression(N1, DAG, LegalOperations);
6605 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6606 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6608 // fold (fsub A, (fneg B)) -> (fadd A, B)
6609 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6610 return DAG.getNode(ISD::FADD, dl, VT, N0,
6611 GetNegatedExpression(N1, DAG, LegalOperations));
6613 // If 'unsafe math' is enabled, fold
6614 // (fsub x, x) -> 0.0 &
6615 // (fsub x, (fadd x, y)) -> (fneg y) &
6616 // (fsub x, (fadd y, x)) -> (fneg y)
6617 if (DAG.getTarget().Options.UnsafeFPMath) {
6619 return DAG.getConstantFP(0.0f, VT);
6621 if (N1.getOpcode() == ISD::FADD) {
6622 SDValue N10 = N1->getOperand(0);
6623 SDValue N11 = N1->getOperand(1);
6625 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6626 &DAG.getTarget().Options))
6627 return GetNegatedExpression(N11, DAG, LegalOperations);
6629 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6630 &DAG.getTarget().Options))
6631 return GetNegatedExpression(N10, DAG, LegalOperations);
6635 // FSUB -> FMA combines:
6636 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6637 DAG.getTarget().Options.UnsafeFPMath) &&
6638 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6639 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6641 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6642 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6643 return DAG.getNode(ISD::FMA, dl, VT,
6644 N0.getOperand(0), N0.getOperand(1),
6645 DAG.getNode(ISD::FNEG, dl, VT, N1));
6647 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6648 // Note: Commutes FSUB operands.
6649 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6650 return DAG.getNode(ISD::FMA, dl, VT,
6651 DAG.getNode(ISD::FNEG, dl, VT,
6653 N1.getOperand(1), N0);
6655 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6656 if (N0.getOpcode() == ISD::FNEG &&
6657 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6658 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6659 SDValue N00 = N0.getOperand(0).getOperand(0);
6660 SDValue N01 = N0.getOperand(0).getOperand(1);
6661 return DAG.getNode(ISD::FMA, dl, VT,
6662 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6663 DAG.getNode(ISD::FNEG, dl, VT, N1));
6670 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6671 SDValue N0 = N->getOperand(0);
6672 SDValue N1 = N->getOperand(1);
6673 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6674 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6675 EVT VT = N->getValueType(0);
6676 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6679 if (VT.isVector()) {
6680 SDValue FoldedVOp = SimplifyVBinOp(N);
6681 if (FoldedVOp.getNode()) return FoldedVOp;
6684 // fold (fmul c1, c2) -> c1*c2
6686 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6687 // canonicalize constant to RHS
6688 if (N0CFP && !N1CFP)
6689 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6690 // fold (fmul A, 0) -> 0
6691 if (DAG.getTarget().Options.UnsafeFPMath &&
6692 N1CFP && N1CFP->getValueAPF().isZero())
6694 // fold (fmul A, 0) -> 0, vector edition.
6695 if (DAG.getTarget().Options.UnsafeFPMath &&
6696 ISD::isBuildVectorAllZeros(N1.getNode()))
6698 // fold (fmul A, 1.0) -> A
6699 if (N1CFP && N1CFP->isExactlyValue(1.0))
6701 // fold (fmul X, 2.0) -> (fadd X, X)
6702 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6703 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6704 // fold (fmul X, -1.0) -> (fneg X)
6705 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6706 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6707 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6709 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6710 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6711 &DAG.getTarget().Options)) {
6712 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6713 &DAG.getTarget().Options)) {
6714 // Both can be negated for free, check to see if at least one is cheaper
6716 if (LHSNeg == 2 || RHSNeg == 2)
6717 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6718 GetNegatedExpression(N0, DAG, LegalOperations),
6719 GetNegatedExpression(N1, DAG, LegalOperations));
6723 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6724 if (DAG.getTarget().Options.UnsafeFPMath &&
6725 N1CFP && N0.getOpcode() == ISD::FMUL &&
6726 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6727 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6728 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6729 N0.getOperand(1), N1));
6734 SDValue DAGCombiner::visitFMA(SDNode *N) {
6735 SDValue N0 = N->getOperand(0);
6736 SDValue N1 = N->getOperand(1);
6737 SDValue N2 = N->getOperand(2);
6738 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6739 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6740 EVT VT = N->getValueType(0);
6743 if (DAG.getTarget().Options.UnsafeFPMath) {
6744 if (N0CFP && N0CFP->isZero())
6746 if (N1CFP && N1CFP->isZero())
6749 if (N0CFP && N0CFP->isExactlyValue(1.0))
6750 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6751 if (N1CFP && N1CFP->isExactlyValue(1.0))
6752 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6754 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6755 if (N0CFP && !N1CFP)
6756 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6758 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6759 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6760 N2.getOpcode() == ISD::FMUL &&
6761 N0 == N2.getOperand(0) &&
6762 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6763 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6764 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6768 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6769 if (DAG.getTarget().Options.UnsafeFPMath &&
6770 N0.getOpcode() == ISD::FMUL && N1CFP &&
6771 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6772 return DAG.getNode(ISD::FMA, dl, VT,
6774 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6778 // (fma x, 1, y) -> (fadd x, y)
6779 // (fma x, -1, y) -> (fadd (fneg x), y)
6781 if (N1CFP->isExactlyValue(1.0))
6782 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6784 if (N1CFP->isExactlyValue(-1.0) &&
6785 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6786 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6787 AddToWorkList(RHSNeg.getNode());
6788 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6792 // (fma x, c, x) -> (fmul x, (c+1))
6793 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6794 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6795 DAG.getNode(ISD::FADD, dl, VT,
6796 N1, DAG.getConstantFP(1.0, VT)));
6798 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6799 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6800 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6801 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6802 DAG.getNode(ISD::FADD, dl, VT,
6803 N1, DAG.getConstantFP(-1.0, VT)));
6809 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6810 SDValue N0 = N->getOperand(0);
6811 SDValue N1 = N->getOperand(1);
6812 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6813 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6814 EVT VT = N->getValueType(0);
6815 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6818 if (VT.isVector()) {
6819 SDValue FoldedVOp = SimplifyVBinOp(N);
6820 if (FoldedVOp.getNode()) return FoldedVOp;
6823 // fold (fdiv c1, c2) -> c1/c2
6825 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6827 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6828 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6829 // Compute the reciprocal 1.0 / c2.
6830 APFloat N1APF = N1CFP->getValueAPF();
6831 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6832 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6833 // Only do the transform if the reciprocal is a legal fp immediate that
6834 // isn't too nasty (eg NaN, denormal, ...).
6835 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6836 (!LegalOperations ||
6837 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6838 // backend)... we should handle this gracefully after Legalize.
6839 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6840 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6841 TLI.isFPImmLegal(Recip, VT)))
6842 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6843 DAG.getConstantFP(Recip, VT));
6846 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6847 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6848 &DAG.getTarget().Options)) {
6849 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6850 &DAG.getTarget().Options)) {
6851 // Both can be negated for free, check to see if at least one is cheaper
6853 if (LHSNeg == 2 || RHSNeg == 2)
6854 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6855 GetNegatedExpression(N0, DAG, LegalOperations),
6856 GetNegatedExpression(N1, DAG, LegalOperations));
6863 SDValue DAGCombiner::visitFREM(SDNode *N) {
6864 SDValue N0 = N->getOperand(0);
6865 SDValue N1 = N->getOperand(1);
6866 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6867 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6868 EVT VT = N->getValueType(0);
6870 // fold (frem c1, c2) -> fmod(c1,c2)
6872 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6877 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6878 SDValue N0 = N->getOperand(0);
6879 SDValue N1 = N->getOperand(1);
6880 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6881 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6882 EVT VT = N->getValueType(0);
6884 if (N0CFP && N1CFP) // Constant fold
6885 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6888 const APFloat& V = N1CFP->getValueAPF();
6889 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6890 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6891 if (!V.isNegative()) {
6892 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6893 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6895 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6896 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6897 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6901 // copysign(fabs(x), y) -> copysign(x, y)
6902 // copysign(fneg(x), y) -> copysign(x, y)
6903 // copysign(copysign(x,z), y) -> copysign(x, y)
6904 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6905 N0.getOpcode() == ISD::FCOPYSIGN)
6906 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6907 N0.getOperand(0), N1);
6909 // copysign(x, abs(y)) -> abs(x)
6910 if (N1.getOpcode() == ISD::FABS)
6911 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6913 // copysign(x, copysign(y,z)) -> copysign(x, z)
6914 if (N1.getOpcode() == ISD::FCOPYSIGN)
6915 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6916 N0, N1.getOperand(1));
6918 // copysign(x, fp_extend(y)) -> copysign(x, y)
6919 // copysign(x, fp_round(y)) -> copysign(x, y)
6920 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6921 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6922 N0, N1.getOperand(0));
6927 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6928 SDValue N0 = N->getOperand(0);
6929 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6930 EVT VT = N->getValueType(0);
6931 EVT OpVT = N0.getValueType();
6933 // fold (sint_to_fp c1) -> c1fp
6935 // ...but only if the target supports immediate floating-point values
6936 (!LegalOperations ||
6937 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6938 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6940 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6941 // but UINT_TO_FP is legal on this target, try to convert.
6942 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6943 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6944 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6945 if (DAG.SignBitIsZero(N0))
6946 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6949 // The next optimizations are desirable only if SELECT_CC can be lowered.
6950 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6951 // having to say they don't support SELECT_CC on every type the DAG knows
6952 // about, since there is no way to mark an opcode illegal at all value types
6953 // (See also visitSELECT)
6954 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6955 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6956 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6958 (!LegalOperations ||
6959 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6961 { N0.getOperand(0), N0.getOperand(1),
6962 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6964 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
6967 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6968 // (select_cc x, y, 1.0, 0.0,, cc)
6969 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6970 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6971 (!LegalOperations ||
6972 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6974 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6975 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6976 N0.getOperand(0).getOperand(2) };
6977 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
6984 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6985 SDValue N0 = N->getOperand(0);
6986 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6987 EVT VT = N->getValueType(0);
6988 EVT OpVT = N0.getValueType();
6990 // fold (uint_to_fp c1) -> c1fp
6992 // ...but only if the target supports immediate floating-point values
6993 (!LegalOperations ||
6994 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6995 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6997 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6998 // but SINT_TO_FP is legal on this target, try to convert.
6999 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7000 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7001 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7002 if (DAG.SignBitIsZero(N0))
7003 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7006 // The next optimizations are desirable only if SELECT_CC can be lowered.
7007 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
7008 // having to say they don't support SELECT_CC on every type the DAG knows
7009 // about, since there is no way to mark an opcode illegal at all value types
7010 // (See also visitSELECT)
7011 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
7012 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7014 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7015 (!LegalOperations ||
7016 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7018 { N0.getOperand(0), N0.getOperand(1),
7019 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7021 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7028 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7029 SDValue N0 = N->getOperand(0);
7030 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7031 EVT VT = N->getValueType(0);
7033 // fold (fp_to_sint c1fp) -> c1
7035 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7040 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7041 SDValue N0 = N->getOperand(0);
7042 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7043 EVT VT = N->getValueType(0);
7045 // fold (fp_to_uint c1fp) -> c1
7047 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7052 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7053 SDValue N0 = N->getOperand(0);
7054 SDValue N1 = N->getOperand(1);
7055 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7056 EVT VT = N->getValueType(0);
7058 // fold (fp_round c1fp) -> c1fp
7060 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7062 // fold (fp_round (fp_extend x)) -> x
7063 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7064 return N0.getOperand(0);
7066 // fold (fp_round (fp_round x)) -> (fp_round x)
7067 if (N0.getOpcode() == ISD::FP_ROUND) {
7068 // This is a value preserving truncation if both round's are.
7069 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7070 N0.getNode()->getConstantOperandVal(1) == 1;
7071 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7072 DAG.getIntPtrConstant(IsTrunc));
7075 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7076 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7077 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7078 N0.getOperand(0), N1);
7079 AddToWorkList(Tmp.getNode());
7080 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7081 Tmp, N0.getOperand(1));
7087 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7088 SDValue N0 = N->getOperand(0);
7089 EVT VT = N->getValueType(0);
7090 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7091 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7093 // fold (fp_round_inreg c1fp) -> c1fp
7094 if (N0CFP && isTypeLegal(EVT)) {
7095 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7096 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7102 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7103 SDValue N0 = N->getOperand(0);
7104 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7105 EVT VT = N->getValueType(0);
7107 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7108 if (N->hasOneUse() &&
7109 N->use_begin()->getOpcode() == ISD::FP_ROUND)
7112 // fold (fp_extend c1fp) -> c1fp
7114 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7116 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7118 if (N0.getOpcode() == ISD::FP_ROUND
7119 && N0.getNode()->getConstantOperandVal(1) == 1) {
7120 SDValue In = N0.getOperand(0);
7121 if (In.getValueType() == VT) return In;
7122 if (VT.bitsLT(In.getValueType()))
7123 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7124 In, N0.getOperand(1));
7125 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7128 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7129 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7130 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7131 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
7132 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7133 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7135 LN0->getBasePtr(), N0.getValueType(),
7136 LN0->getMemOperand());
7137 CombineTo(N, ExtLoad);
7138 CombineTo(N0.getNode(),
7139 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7140 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7141 ExtLoad.getValue(1));
7142 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7148 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7149 SDValue N0 = N->getOperand(0);
7150 EVT VT = N->getValueType(0);
7152 if (VT.isVector()) {
7153 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7154 if (FoldedVOp.getNode()) return FoldedVOp;
7157 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7158 &DAG.getTarget().Options))
7159 return GetNegatedExpression(N0, DAG, LegalOperations);
7161 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7162 // constant pool values.
7163 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7165 N0.getNode()->hasOneUse() &&
7166 N0.getOperand(0).getValueType().isInteger()) {
7167 SDValue Int = N0.getOperand(0);
7168 EVT IntVT = Int.getValueType();
7169 if (IntVT.isInteger() && !IntVT.isVector()) {
7170 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7171 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7172 AddToWorkList(Int.getNode());
7173 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7178 // (fneg (fmul c, x)) -> (fmul -c, x)
7179 if (N0.getOpcode() == ISD::FMUL) {
7180 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7182 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7184 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7191 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7192 SDValue N0 = N->getOperand(0);
7193 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7194 EVT VT = N->getValueType(0);
7196 // fold (fceil c1) -> fceil(c1)
7198 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7203 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7204 SDValue N0 = N->getOperand(0);
7205 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7206 EVT VT = N->getValueType(0);
7208 // fold (ftrunc c1) -> ftrunc(c1)
7210 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7215 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7216 SDValue N0 = N->getOperand(0);
7217 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7218 EVT VT = N->getValueType(0);
7220 // fold (ffloor c1) -> ffloor(c1)
7222 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7227 SDValue DAGCombiner::visitFABS(SDNode *N) {
7228 SDValue N0 = N->getOperand(0);
7229 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7230 EVT VT = N->getValueType(0);
7232 if (VT.isVector()) {
7233 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7234 if (FoldedVOp.getNode()) return FoldedVOp;
7237 // fold (fabs c1) -> fabs(c1)
7239 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7240 // fold (fabs (fabs x)) -> (fabs x)
7241 if (N0.getOpcode() == ISD::FABS)
7242 return N->getOperand(0);
7243 // fold (fabs (fneg x)) -> (fabs x)
7244 // fold (fabs (fcopysign x, y)) -> (fabs x)
7245 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7246 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7248 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7249 // constant pool values.
7250 if (!TLI.isFAbsFree(VT) &&
7251 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7252 N0.getOperand(0).getValueType().isInteger() &&
7253 !N0.getOperand(0).getValueType().isVector()) {
7254 SDValue Int = N0.getOperand(0);
7255 EVT IntVT = Int.getValueType();
7256 if (IntVT.isInteger() && !IntVT.isVector()) {
7257 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7258 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7259 AddToWorkList(Int.getNode());
7260 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7261 N->getValueType(0), Int);
7268 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7269 SDValue Chain = N->getOperand(0);
7270 SDValue N1 = N->getOperand(1);
7271 SDValue N2 = N->getOperand(2);
7273 // If N is a constant we could fold this into a fallthrough or unconditional
7274 // branch. However that doesn't happen very often in normal code, because
7275 // Instcombine/SimplifyCFG should have handled the available opportunities.
7276 // If we did this folding here, it would be necessary to update the
7277 // MachineBasicBlock CFG, which is awkward.
7279 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7281 if (N1.getOpcode() == ISD::SETCC &&
7282 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7283 N1.getOperand(0).getValueType())) {
7284 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7285 Chain, N1.getOperand(2),
7286 N1.getOperand(0), N1.getOperand(1), N2);
7289 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7290 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7291 (N1.getOperand(0).hasOneUse() &&
7292 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7293 SDNode *Trunc = nullptr;
7294 if (N1.getOpcode() == ISD::TRUNCATE) {
7295 // Look pass the truncate.
7296 Trunc = N1.getNode();
7297 N1 = N1.getOperand(0);
7300 // Match this pattern so that we can generate simpler code:
7303 // %b = and i32 %a, 2
7304 // %c = srl i32 %b, 1
7305 // brcond i32 %c ...
7310 // %b = and i32 %a, 2
7311 // %c = setcc eq %b, 0
7314 // This applies only when the AND constant value has one bit set and the
7315 // SRL constant is equal to the log2 of the AND constant. The back-end is
7316 // smart enough to convert the result into a TEST/JMP sequence.
7317 SDValue Op0 = N1.getOperand(0);
7318 SDValue Op1 = N1.getOperand(1);
7320 if (Op0.getOpcode() == ISD::AND &&
7321 Op1.getOpcode() == ISD::Constant) {
7322 SDValue AndOp1 = Op0.getOperand(1);
7324 if (AndOp1.getOpcode() == ISD::Constant) {
7325 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7327 if (AndConst.isPowerOf2() &&
7328 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7330 DAG.getSetCC(SDLoc(N),
7331 getSetCCResultType(Op0.getValueType()),
7332 Op0, DAG.getConstant(0, Op0.getValueType()),
7335 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7336 MVT::Other, Chain, SetCC, N2);
7337 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7338 // will convert it back to (X & C1) >> C2.
7339 CombineTo(N, NewBRCond, false);
7340 // Truncate is dead.
7342 removeFromWorkList(Trunc);
7343 DAG.DeleteNode(Trunc);
7345 // Replace the uses of SRL with SETCC
7346 WorkListRemover DeadNodes(*this);
7347 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7348 removeFromWorkList(N1.getNode());
7349 DAG.DeleteNode(N1.getNode());
7350 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7356 // Restore N1 if the above transformation doesn't match.
7357 N1 = N->getOperand(1);
7360 // Transform br(xor(x, y)) -> br(x != y)
7361 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7362 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7363 SDNode *TheXor = N1.getNode();
7364 SDValue Op0 = TheXor->getOperand(0);
7365 SDValue Op1 = TheXor->getOperand(1);
7366 if (Op0.getOpcode() == Op1.getOpcode()) {
7367 // Avoid missing important xor optimizations.
7368 SDValue Tmp = visitXOR(TheXor);
7369 if (Tmp.getNode()) {
7370 if (Tmp.getNode() != TheXor) {
7371 DEBUG(dbgs() << "\nReplacing.8 ";
7373 dbgs() << "\nWith: ";
7374 Tmp.getNode()->dump(&DAG);
7376 WorkListRemover DeadNodes(*this);
7377 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7378 removeFromWorkList(TheXor);
7379 DAG.DeleteNode(TheXor);
7380 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7381 MVT::Other, Chain, Tmp, N2);
7384 // visitXOR has changed XOR's operands or replaced the XOR completely,
7386 return SDValue(N, 0);
7390 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7392 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7393 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7394 Op0.getOpcode() == ISD::XOR) {
7395 TheXor = Op0.getNode();
7399 EVT SetCCVT = N1.getValueType();
7401 SetCCVT = getSetCCResultType(SetCCVT);
7402 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7405 Equal ? ISD::SETEQ : ISD::SETNE);
7406 // Replace the uses of XOR with SETCC
7407 WorkListRemover DeadNodes(*this);
7408 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7409 removeFromWorkList(N1.getNode());
7410 DAG.DeleteNode(N1.getNode());
7411 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7412 MVT::Other, Chain, SetCC, N2);
7419 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7421 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7422 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7423 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7425 // If N is a constant we could fold this into a fallthrough or unconditional
7426 // branch. However that doesn't happen very often in normal code, because
7427 // Instcombine/SimplifyCFG should have handled the available opportunities.
7428 // If we did this folding here, it would be necessary to update the
7429 // MachineBasicBlock CFG, which is awkward.
7431 // Use SimplifySetCC to simplify SETCC's.
7432 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7433 CondLHS, CondRHS, CC->get(), SDLoc(N),
7435 if (Simp.getNode()) AddToWorkList(Simp.getNode());
7437 // fold to a simpler setcc
7438 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7439 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7440 N->getOperand(0), Simp.getOperand(2),
7441 Simp.getOperand(0), Simp.getOperand(1),
7447 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7448 /// uses N as its base pointer and that N may be folded in the load / store
7449 /// addressing mode.
7450 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7452 const TargetLowering &TLI) {
7454 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7455 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7457 VT = Use->getValueType(0);
7458 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7459 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7461 VT = ST->getValue().getValueType();
7465 TargetLowering::AddrMode AM;
7466 if (N->getOpcode() == ISD::ADD) {
7467 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7470 AM.BaseOffs = Offset->getSExtValue();
7474 } else if (N->getOpcode() == ISD::SUB) {
7475 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7478 AM.BaseOffs = -Offset->getSExtValue();
7485 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7488 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7489 /// pre-indexed load / store when the base pointer is an add or subtract
7490 /// and it has other uses besides the load / store. After the
7491 /// transformation, the new indexed load / store has effectively folded
7492 /// the add / subtract in and all of its other uses are redirected to the
7493 /// new load / store.
7494 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7495 if (Level < AfterLegalizeDAG)
7501 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7502 if (LD->isIndexed())
7504 VT = LD->getMemoryVT();
7505 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7506 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7508 Ptr = LD->getBasePtr();
7509 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7510 if (ST->isIndexed())
7512 VT = ST->getMemoryVT();
7513 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7514 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7516 Ptr = ST->getBasePtr();
7522 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7523 // out. There is no reason to make this a preinc/predec.
7524 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7525 Ptr.getNode()->hasOneUse())
7528 // Ask the target to do addressing mode selection.
7531 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7532 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7535 // Backends without true r+i pre-indexed forms may need to pass a
7536 // constant base with a variable offset so that constant coercion
7537 // will work with the patterns in canonical form.
7538 bool Swapped = false;
7539 if (isa<ConstantSDNode>(BasePtr)) {
7540 std::swap(BasePtr, Offset);
7544 // Don't create a indexed load / store with zero offset.
7545 if (isa<ConstantSDNode>(Offset) &&
7546 cast<ConstantSDNode>(Offset)->isNullValue())
7549 // Try turning it into a pre-indexed load / store except when:
7550 // 1) The new base ptr is a frame index.
7551 // 2) If N is a store and the new base ptr is either the same as or is a
7552 // predecessor of the value being stored.
7553 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7554 // that would create a cycle.
7555 // 4) All uses are load / store ops that use it as old base ptr.
7557 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7558 // (plus the implicit offset) to a register to preinc anyway.
7559 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7564 SDValue Val = cast<StoreSDNode>(N)->getValue();
7565 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7569 // If the offset is a constant, there may be other adds of constants that
7570 // can be folded with this one. We should do this to avoid having to keep
7571 // a copy of the original base pointer.
7572 SmallVector<SDNode *, 16> OtherUses;
7573 if (isa<ConstantSDNode>(Offset))
7574 for (SDNode *Use : BasePtr.getNode()->uses()) {
7575 if (Use == Ptr.getNode())
7578 if (Use->isPredecessorOf(N))
7581 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7586 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7587 if (Op1.getNode() == BasePtr.getNode())
7588 std::swap(Op0, Op1);
7589 assert(Op0.getNode() == BasePtr.getNode() &&
7590 "Use of ADD/SUB but not an operand");
7592 if (!isa<ConstantSDNode>(Op1)) {
7597 // FIXME: In some cases, we can be smarter about this.
7598 if (Op1.getValueType() != Offset.getValueType()) {
7603 OtherUses.push_back(Use);
7607 std::swap(BasePtr, Offset);
7609 // Now check for #3 and #4.
7610 bool RealUse = false;
7612 // Caches for hasPredecessorHelper
7613 SmallPtrSet<const SDNode *, 32> Visited;
7614 SmallVector<const SDNode *, 16> Worklist;
7616 for (SDNode *Use : Ptr.getNode()->uses()) {
7619 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7622 // If Ptr may be folded in addressing mode of other use, then it's
7623 // not profitable to do this transformation.
7624 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7633 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7634 BasePtr, Offset, AM);
7636 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7637 BasePtr, Offset, AM);
7640 DEBUG(dbgs() << "\nReplacing.4 ";
7642 dbgs() << "\nWith: ";
7643 Result.getNode()->dump(&DAG);
7645 WorkListRemover DeadNodes(*this);
7647 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7648 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7650 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7653 // Finally, since the node is now dead, remove it from the graph.
7657 std::swap(BasePtr, Offset);
7659 // Replace other uses of BasePtr that can be updated to use Ptr
7660 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7661 unsigned OffsetIdx = 1;
7662 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7664 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7665 BasePtr.getNode() && "Expected BasePtr operand");
7667 // We need to replace ptr0 in the following expression:
7668 // x0 * offset0 + y0 * ptr0 = t0
7670 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7672 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7673 // indexed load/store and the expresion that needs to be re-written.
7675 // Therefore, we have:
7676 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7678 ConstantSDNode *CN =
7679 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7681 APInt Offset0 = CN->getAPIntValue();
7682 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7684 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7685 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7686 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7687 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7689 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7691 APInt CNV = Offset0;
7692 if (X0 < 0) CNV = -CNV;
7693 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7694 else CNV = CNV - Offset1;
7696 // We can now generate the new expression.
7697 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7698 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7700 SDValue NewUse = DAG.getNode(Opcode,
7701 SDLoc(OtherUses[i]),
7702 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7703 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7704 removeFromWorkList(OtherUses[i]);
7705 DAG.DeleteNode(OtherUses[i]);
7708 // Replace the uses of Ptr with uses of the updated base value.
7709 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7710 removeFromWorkList(Ptr.getNode());
7711 DAG.DeleteNode(Ptr.getNode());
7716 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7717 /// add / sub of the base pointer node into a post-indexed load / store.
7718 /// The transformation folded the add / subtract into the new indexed
7719 /// load / store effectively and all of its uses are redirected to the
7720 /// new load / store.
7721 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7722 if (Level < AfterLegalizeDAG)
7728 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7729 if (LD->isIndexed())
7731 VT = LD->getMemoryVT();
7732 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7733 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7735 Ptr = LD->getBasePtr();
7736 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7737 if (ST->isIndexed())
7739 VT = ST->getMemoryVT();
7740 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7741 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7743 Ptr = ST->getBasePtr();
7749 if (Ptr.getNode()->hasOneUse())
7752 for (SDNode *Op : Ptr.getNode()->uses()) {
7754 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7759 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7760 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7761 // Don't create a indexed load / store with zero offset.
7762 if (isa<ConstantSDNode>(Offset) &&
7763 cast<ConstantSDNode>(Offset)->isNullValue())
7766 // Try turning it into a post-indexed load / store except when
7767 // 1) All uses are load / store ops that use it as base ptr (and
7768 // it may be folded as addressing mmode).
7769 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7770 // nor a successor of N. Otherwise, if Op is folded that would
7773 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7777 bool TryNext = false;
7778 for (SDNode *Use : BasePtr.getNode()->uses()) {
7779 if (Use == Ptr.getNode())
7782 // If all the uses are load / store addresses, then don't do the
7784 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7785 bool RealUse = false;
7786 for (SDNode *UseUse : Use->uses()) {
7787 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7802 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7803 SDValue Result = isLoad
7804 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7805 BasePtr, Offset, AM)
7806 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7807 BasePtr, Offset, AM);
7810 DEBUG(dbgs() << "\nReplacing.5 ";
7812 dbgs() << "\nWith: ";
7813 Result.getNode()->dump(&DAG);
7815 WorkListRemover DeadNodes(*this);
7817 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7818 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7820 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7823 // Finally, since the node is now dead, remove it from the graph.
7826 // Replace the uses of Use with uses of the updated base value.
7827 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7828 Result.getValue(isLoad ? 1 : 0));
7829 removeFromWorkList(Op);
7839 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7840 LoadSDNode *LD = cast<LoadSDNode>(N);
7841 SDValue Chain = LD->getChain();
7842 SDValue Ptr = LD->getBasePtr();
7844 // If load is not volatile and there are no uses of the loaded value (and
7845 // the updated indexed value in case of indexed loads), change uses of the
7846 // chain value into uses of the chain input (i.e. delete the dead load).
7847 if (!LD->isVolatile()) {
7848 if (N->getValueType(1) == MVT::Other) {
7850 if (!N->hasAnyUseOfValue(0)) {
7851 // It's not safe to use the two value CombineTo variant here. e.g.
7852 // v1, chain2 = load chain1, loc
7853 // v2, chain3 = load chain2, loc
7855 // Now we replace use of chain2 with chain1. This makes the second load
7856 // isomorphic to the one we are deleting, and thus makes this load live.
7857 DEBUG(dbgs() << "\nReplacing.6 ";
7859 dbgs() << "\nWith chain: ";
7860 Chain.getNode()->dump(&DAG);
7862 WorkListRemover DeadNodes(*this);
7863 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7865 if (N->use_empty()) {
7866 removeFromWorkList(N);
7870 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7874 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7875 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7876 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7877 DEBUG(dbgs() << "\nReplacing.7 ";
7879 dbgs() << "\nWith: ";
7880 Undef.getNode()->dump(&DAG);
7881 dbgs() << " and 2 other values\n");
7882 WorkListRemover DeadNodes(*this);
7883 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7884 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7885 DAG.getUNDEF(N->getValueType(1)));
7886 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7887 removeFromWorkList(N);
7889 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7894 // If this load is directly stored, replace the load value with the stored
7896 // TODO: Handle store large -> read small portion.
7897 // TODO: Handle TRUNCSTORE/LOADEXT
7898 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7899 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7900 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7901 if (PrevST->getBasePtr() == Ptr &&
7902 PrevST->getValue().getValueType() == N->getValueType(0))
7903 return CombineTo(N, Chain.getOperand(1), Chain);
7907 // Try to infer better alignment information than the load already has.
7908 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7909 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7910 if (Align > LD->getMemOperand()->getBaseAlignment()) {
7912 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7913 LD->getValueType(0),
7914 Chain, Ptr, LD->getPointerInfo(),
7916 LD->isVolatile(), LD->isNonTemporal(), Align,
7918 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7923 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7924 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7926 if (CombinerAAOnlyFunc.getNumOccurrences() &&
7927 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
7930 if (UseAA && LD->isUnindexed()) {
7931 // Walk up chain skipping non-aliasing memory nodes.
7932 SDValue BetterChain = FindBetterChain(N, Chain);
7934 // If there is a better chain.
7935 if (Chain != BetterChain) {
7938 // Replace the chain to void dependency.
7939 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7940 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7941 BetterChain, Ptr, LD->getMemOperand());
7943 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7944 LD->getValueType(0),
7945 BetterChain, Ptr, LD->getMemoryVT(),
7946 LD->getMemOperand());
7949 // Create token factor to keep old chain connected.
7950 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7951 MVT::Other, Chain, ReplLoad.getValue(1));
7953 // Make sure the new and old chains are cleaned up.
7954 AddToWorkList(Token.getNode());
7956 // Replace uses with load result and token factor. Don't add users
7958 return CombineTo(N, ReplLoad.getValue(0), Token, false);
7962 // Try transforming N to an indexed load.
7963 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7964 return SDValue(N, 0);
7966 // Try to slice up N to more direct loads if the slices are mapped to
7967 // different register banks or pairing can take place.
7969 return SDValue(N, 0);
7975 /// \brief Helper structure used to slice a load in smaller loads.
7976 /// Basically a slice is obtained from the following sequence:
7977 /// Origin = load Ty1, Base
7978 /// Shift = srl Ty1 Origin, CstTy Amount
7979 /// Inst = trunc Shift to Ty2
7981 /// Then, it will be rewriten into:
7982 /// Slice = load SliceTy, Base + SliceOffset
7983 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
7985 /// SliceTy is deduced from the number of bits that are actually used to
7987 struct LoadedSlice {
7988 /// \brief Helper structure used to compute the cost of a slice.
7990 /// Are we optimizing for code size.
7995 unsigned CrossRegisterBanksCopies;
7999 Cost(bool ForCodeSize = false)
8000 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8001 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8003 /// \brief Get the cost of one isolated slice.
8004 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8005 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8006 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8007 EVT TruncType = LS.Inst->getValueType(0);
8008 EVT LoadedType = LS.getLoadedType();
8009 if (TruncType != LoadedType &&
8010 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8014 /// \brief Account for slicing gain in the current cost.
8015 /// Slicing provide a few gains like removing a shift or a
8016 /// truncate. This method allows to grow the cost of the original
8017 /// load with the gain from this slice.
8018 void addSliceGain(const LoadedSlice &LS) {
8019 // Each slice saves a truncate.
8020 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8021 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8022 LS.Inst->getOperand(0).getValueType()))
8024 // If there is a shift amount, this slice gets rid of it.
8027 // If this slice can merge a cross register bank copy, account for it.
8028 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8029 ++CrossRegisterBanksCopies;
8032 Cost &operator+=(const Cost &RHS) {
8034 Truncates += RHS.Truncates;
8035 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8041 bool operator==(const Cost &RHS) const {
8042 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8043 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8044 ZExts == RHS.ZExts && Shift == RHS.Shift;
8047 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8049 bool operator<(const Cost &RHS) const {
8050 // Assume cross register banks copies are as expensive as loads.
8051 // FIXME: Do we want some more target hooks?
8052 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8053 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8054 // Unless we are optimizing for code size, consider the
8055 // expensive operation first.
8056 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8057 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8058 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8059 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8062 bool operator>(const Cost &RHS) const { return RHS < *this; }
8064 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8066 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8068 // The last instruction that represent the slice. This should be a
8069 // truncate instruction.
8071 // The original load instruction.
8073 // The right shift amount in bits from the original load.
8075 // The DAG from which Origin came from.
8076 // This is used to get some contextual information about legal types, etc.
8079 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8080 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8081 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8083 LoadedSlice(const LoadedSlice &LS)
8084 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8086 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8087 /// \return Result is \p BitWidth and has used bits set to 1 and
8088 /// not used bits set to 0.
8089 APInt getUsedBits() const {
8090 // Reproduce the trunc(lshr) sequence:
8091 // - Start from the truncated value.
8092 // - Zero extend to the desired bit width.
8094 assert(Origin && "No original load to compare against.");
8095 unsigned BitWidth = Origin->getValueSizeInBits(0);
8096 assert(Inst && "This slice is not bound to an instruction");
8097 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8098 "Extracted slice is bigger than the whole type!");
8099 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8100 UsedBits.setAllBits();
8101 UsedBits = UsedBits.zext(BitWidth);
8106 /// \brief Get the size of the slice to be loaded in bytes.
8107 unsigned getLoadedSize() const {
8108 unsigned SliceSize = getUsedBits().countPopulation();
8109 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8110 return SliceSize / 8;
8113 /// \brief Get the type that will be loaded for this slice.
8114 /// Note: This may not be the final type for the slice.
8115 EVT getLoadedType() const {
8116 assert(DAG && "Missing context");
8117 LLVMContext &Ctxt = *DAG->getContext();
8118 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8121 /// \brief Get the alignment of the load used for this slice.
8122 unsigned getAlignment() const {
8123 unsigned Alignment = Origin->getAlignment();
8124 unsigned Offset = getOffsetFromBase();
8126 Alignment = MinAlign(Alignment, Alignment + Offset);
8130 /// \brief Check if this slice can be rewritten with legal operations.
8131 bool isLegal() const {
8132 // An invalid slice is not legal.
8133 if (!Origin || !Inst || !DAG)
8136 // Offsets are for indexed load only, we do not handle that.
8137 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8140 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8142 // Check that the type is legal.
8143 EVT SliceType = getLoadedType();
8144 if (!TLI.isTypeLegal(SliceType))
8147 // Check that the load is legal for this type.
8148 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8151 // Check that the offset can be computed.
8152 // 1. Check its type.
8153 EVT PtrType = Origin->getBasePtr().getValueType();
8154 if (PtrType == MVT::Untyped || PtrType.isExtended())
8157 // 2. Check that it fits in the immediate.
8158 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8161 // 3. Check that the computation is legal.
8162 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8165 // Check that the zext is legal if it needs one.
8166 EVT TruncateType = Inst->getValueType(0);
8167 if (TruncateType != SliceType &&
8168 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8174 /// \brief Get the offset in bytes of this slice in the original chunk of
8176 /// \pre DAG != nullptr.
8177 uint64_t getOffsetFromBase() const {
8178 assert(DAG && "Missing context.");
8180 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8181 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8182 uint64_t Offset = Shift / 8;
8183 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8184 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8185 "The size of the original loaded type is not a multiple of a"
8187 // If Offset is bigger than TySizeInBytes, it means we are loading all
8188 // zeros. This should have been optimized before in the process.
8189 assert(TySizeInBytes > Offset &&
8190 "Invalid shift amount for given loaded size");
8192 Offset = TySizeInBytes - Offset - getLoadedSize();
8196 /// \brief Generate the sequence of instructions to load the slice
8197 /// represented by this object and redirect the uses of this slice to
8198 /// this new sequence of instructions.
8199 /// \pre this->Inst && this->Origin are valid Instructions and this
8200 /// object passed the legal check: LoadedSlice::isLegal returned true.
8201 /// \return The last instruction of the sequence used to load the slice.
8202 SDValue loadSlice() const {
8203 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8204 const SDValue &OldBaseAddr = Origin->getBasePtr();
8205 SDValue BaseAddr = OldBaseAddr;
8206 // Get the offset in that chunk of bytes w.r.t. the endianess.
8207 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8208 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8210 // BaseAddr = BaseAddr + Offset.
8211 EVT ArithType = BaseAddr.getValueType();
8212 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8213 DAG->getConstant(Offset, ArithType));
8216 // Create the type of the loaded slice according to its size.
8217 EVT SliceType = getLoadedType();
8219 // Create the load for the slice.
8220 SDValue LastInst = DAG->getLoad(
8221 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8222 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8223 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8224 // If the final type is not the same as the loaded type, this means that
8225 // we have to pad with zero. Create a zero extend for that.
8226 EVT FinalType = Inst->getValueType(0);
8227 if (SliceType != FinalType)
8229 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8233 /// \brief Check if this slice can be merged with an expensive cross register
8234 /// bank copy. E.g.,
8236 /// f = bitcast i32 i to float
8237 bool canMergeExpensiveCrossRegisterBankCopy() const {
8238 if (!Inst || !Inst->hasOneUse())
8240 SDNode *Use = *Inst->use_begin();
8241 if (Use->getOpcode() != ISD::BITCAST)
8243 assert(DAG && "Missing context");
8244 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8245 EVT ResVT = Use->getValueType(0);
8246 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8247 const TargetRegisterClass *ArgRC =
8248 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8249 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8252 // At this point, we know that we perform a cross-register-bank copy.
8253 // Check if it is expensive.
8254 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8255 // Assume bitcasts are cheap, unless both register classes do not
8256 // explicitly share a common sub class.
8257 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8260 // Check if it will be merged with the load.
8261 // 1. Check the alignment constraint.
8262 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8263 ResVT.getTypeForEVT(*DAG->getContext()));
8265 if (RequiredAlignment > getAlignment())
8268 // 2. Check that the load is a legal operation for that type.
8269 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8272 // 3. Check that we do not have a zext in the way.
8273 if (Inst->getValueType(0) != getLoadedType())
8281 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8282 /// \p UsedBits looks like 0..0 1..1 0..0.
8283 static bool areUsedBitsDense(const APInt &UsedBits) {
8284 // If all the bits are one, this is dense!
8285 if (UsedBits.isAllOnesValue())
8288 // Get rid of the unused bits on the right.
8289 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8290 // Get rid of the unused bits on the left.
8291 if (NarrowedUsedBits.countLeadingZeros())
8292 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8293 // Check that the chunk of bits is completely used.
8294 return NarrowedUsedBits.isAllOnesValue();
8297 /// \brief Check whether or not \p First and \p Second are next to each other
8298 /// in memory. This means that there is no hole between the bits loaded
8299 /// by \p First and the bits loaded by \p Second.
8300 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8301 const LoadedSlice &Second) {
8302 assert(First.Origin == Second.Origin && First.Origin &&
8303 "Unable to match different memory origins.");
8304 APInt UsedBits = First.getUsedBits();
8305 assert((UsedBits & Second.getUsedBits()) == 0 &&
8306 "Slices are not supposed to overlap.");
8307 UsedBits |= Second.getUsedBits();
8308 return areUsedBitsDense(UsedBits);
8311 /// \brief Adjust the \p GlobalLSCost according to the target
8312 /// paring capabilities and the layout of the slices.
8313 /// \pre \p GlobalLSCost should account for at least as many loads as
8314 /// there is in the slices in \p LoadedSlices.
8315 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8316 LoadedSlice::Cost &GlobalLSCost) {
8317 unsigned NumberOfSlices = LoadedSlices.size();
8318 // If there is less than 2 elements, no pairing is possible.
8319 if (NumberOfSlices < 2)
8322 // Sort the slices so that elements that are likely to be next to each
8323 // other in memory are next to each other in the list.
8324 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8325 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8326 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8327 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8329 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8330 // First (resp. Second) is the first (resp. Second) potentially candidate
8331 // to be placed in a paired load.
8332 const LoadedSlice *First = nullptr;
8333 const LoadedSlice *Second = nullptr;
8334 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8335 // Set the beginning of the pair.
8338 Second = &LoadedSlices[CurrSlice];
8340 // If First is NULL, it means we start a new pair.
8341 // Get to the next slice.
8345 EVT LoadedType = First->getLoadedType();
8347 // If the types of the slices are different, we cannot pair them.
8348 if (LoadedType != Second->getLoadedType())
8351 // Check if the target supplies paired loads for this type.
8352 unsigned RequiredAlignment = 0;
8353 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8354 // move to the next pair, this type is hopeless.
8358 // Check if we meet the alignment requirement.
8359 if (RequiredAlignment > First->getAlignment())
8362 // Check that both loads are next to each other in memory.
8363 if (!areSlicesNextToEachOther(*First, *Second))
8366 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8367 --GlobalLSCost.Loads;
8368 // Move to the next pair.
8373 /// \brief Check the profitability of all involved LoadedSlice.
8374 /// Currently, it is considered profitable if there is exactly two
8375 /// involved slices (1) which are (2) next to each other in memory, and
8376 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8378 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8379 /// the elements themselves.
8381 /// FIXME: When the cost model will be mature enough, we can relax
8382 /// constraints (1) and (2).
8383 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8384 const APInt &UsedBits, bool ForCodeSize) {
8385 unsigned NumberOfSlices = LoadedSlices.size();
8386 if (StressLoadSlicing)
8387 return NumberOfSlices > 1;
8390 if (NumberOfSlices != 2)
8394 if (!areUsedBitsDense(UsedBits))
8398 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8399 // The original code has one big load.
8401 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8402 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8403 // Accumulate the cost of all the slices.
8404 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8405 GlobalSlicingCost += SliceCost;
8407 // Account as cost in the original configuration the gain obtained
8408 // with the current slices.
8409 OrigCost.addSliceGain(LS);
8412 // If the target supports paired load, adjust the cost accordingly.
8413 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8414 return OrigCost > GlobalSlicingCost;
8417 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8418 /// operations, split it in the various pieces being extracted.
8420 /// This sort of thing is introduced by SROA.
8421 /// This slicing takes care not to insert overlapping loads.
8422 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8423 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8424 if (Level < AfterLegalizeDAG)
8427 LoadSDNode *LD = cast<LoadSDNode>(N);
8428 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8429 !LD->getValueType(0).isInteger())
8432 // Keep track of already used bits to detect overlapping values.
8433 // In that case, we will just abort the transformation.
8434 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8436 SmallVector<LoadedSlice, 4> LoadedSlices;
8438 // Check if this load is used as several smaller chunks of bits.
8439 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8440 // of computation for each trunc.
8441 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8442 UI != UIEnd; ++UI) {
8443 // Skip the uses of the chain.
8444 if (UI.getUse().getResNo() != 0)
8450 // Check if this is a trunc(lshr).
8451 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8452 isa<ConstantSDNode>(User->getOperand(1))) {
8453 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8454 User = *User->use_begin();
8457 // At this point, User is a Truncate, iff we encountered, trunc or
8459 if (User->getOpcode() != ISD::TRUNCATE)
8462 // The width of the type must be a power of 2 and greater than 8-bits.
8463 // Otherwise the load cannot be represented in LLVM IR.
8464 // Moreover, if we shifted with a non-8-bits multiple, the slice
8465 // will be across several bytes. We do not support that.
8466 unsigned Width = User->getValueSizeInBits(0);
8467 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8470 // Build the slice for this chain of computations.
8471 LoadedSlice LS(User, LD, Shift, &DAG);
8472 APInt CurrentUsedBits = LS.getUsedBits();
8474 // Check if this slice overlaps with another.
8475 if ((CurrentUsedBits & UsedBits) != 0)
8477 // Update the bits used globally.
8478 UsedBits |= CurrentUsedBits;
8480 // Check if the new slice would be legal.
8484 // Record the slice.
8485 LoadedSlices.push_back(LS);
8488 // Abort slicing if it does not seem to be profitable.
8489 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8494 // Rewrite each chain to use an independent load.
8495 // By construction, each chain can be represented by a unique load.
8497 // Prepare the argument for the new token factor for all the slices.
8498 SmallVector<SDValue, 8> ArgChains;
8499 for (SmallVectorImpl<LoadedSlice>::const_iterator
8500 LSIt = LoadedSlices.begin(),
8501 LSItEnd = LoadedSlices.end();
8502 LSIt != LSItEnd; ++LSIt) {
8503 SDValue SliceInst = LSIt->loadSlice();
8504 CombineTo(LSIt->Inst, SliceInst, true);
8505 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8506 SliceInst = SliceInst.getOperand(0);
8507 assert(SliceInst->getOpcode() == ISD::LOAD &&
8508 "It takes more than a zext to get to the loaded slice!!");
8509 ArgChains.push_back(SliceInst.getValue(1));
8512 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8514 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8518 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8519 /// load is having specific bytes cleared out. If so, return the byte size
8520 /// being masked out and the shift amount.
8521 static std::pair<unsigned, unsigned>
8522 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8523 std::pair<unsigned, unsigned> Result(0, 0);
8525 // Check for the structure we're looking for.
8526 if (V->getOpcode() != ISD::AND ||
8527 !isa<ConstantSDNode>(V->getOperand(1)) ||
8528 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8531 // Check the chain and pointer.
8532 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8533 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
8535 // The store should be chained directly to the load or be an operand of a
8537 if (LD == Chain.getNode())
8539 else if (Chain->getOpcode() != ISD::TokenFactor)
8540 return Result; // Fail.
8543 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8544 if (Chain->getOperand(i).getNode() == LD) {
8548 if (!isOk) return Result;
8551 // This only handles simple types.
8552 if (V.getValueType() != MVT::i16 &&
8553 V.getValueType() != MVT::i32 &&
8554 V.getValueType() != MVT::i64)
8557 // Check the constant mask. Invert it so that the bits being masked out are
8558 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8559 // follow the sign bit for uniformity.
8560 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8561 unsigned NotMaskLZ = countLeadingZeros(NotMask);
8562 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
8563 unsigned NotMaskTZ = countTrailingZeros(NotMask);
8564 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8565 if (NotMaskLZ == 64) return Result; // All zero mask.
8567 // See if we have a continuous run of bits. If so, we have 0*1+0*
8568 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8571 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8572 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8573 NotMaskLZ -= 64-V.getValueSizeInBits();
8575 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8576 switch (MaskedBytes) {
8580 default: return Result; // All one mask, or 5-byte mask.
8583 // Verify that the first bit starts at a multiple of mask so that the access
8584 // is aligned the same as the access width.
8585 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8587 Result.first = MaskedBytes;
8588 Result.second = NotMaskTZ/8;
8593 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8594 /// provides a value as specified by MaskInfo. If so, replace the specified
8595 /// store with a narrower store of truncated IVal.
8597 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8598 SDValue IVal, StoreSDNode *St,
8600 unsigned NumBytes = MaskInfo.first;
8601 unsigned ByteShift = MaskInfo.second;
8602 SelectionDAG &DAG = DC->getDAG();
8604 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8605 // that uses this. If not, this is not a replacement.
8606 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8607 ByteShift*8, (ByteShift+NumBytes)*8);
8608 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8610 // Check that it is legal on the target to do this. It is legal if the new
8611 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8613 MVT VT = MVT::getIntegerVT(NumBytes*8);
8614 if (!DC->isTypeLegal(VT))
8617 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8618 // shifted by ByteShift and truncated down to NumBytes.
8620 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8621 DAG.getConstant(ByteShift*8,
8622 DC->getShiftAmountTy(IVal.getValueType())));
8624 // Figure out the offset for the store and the alignment of the access.
8626 unsigned NewAlign = St->getAlignment();
8628 if (DAG.getTargetLoweringInfo().isLittleEndian())
8629 StOffset = ByteShift;
8631 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8633 SDValue Ptr = St->getBasePtr();
8635 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8636 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8637 NewAlign = MinAlign(NewAlign, StOffset);
8640 // Truncate down to the new size.
8641 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8644 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8645 St->getPointerInfo().getWithOffset(StOffset),
8646 false, false, NewAlign).getNode();
8650 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8651 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8652 /// of the loaded bits, try narrowing the load and store if it would end up
8653 /// being a win for performance or code size.
8654 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8655 StoreSDNode *ST = cast<StoreSDNode>(N);
8656 if (ST->isVolatile())
8659 SDValue Chain = ST->getChain();
8660 SDValue Value = ST->getValue();
8661 SDValue Ptr = ST->getBasePtr();
8662 EVT VT = Value.getValueType();
8664 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8667 unsigned Opc = Value.getOpcode();
8669 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8670 // is a byte mask indicating a consecutive number of bytes, check to see if
8671 // Y is known to provide just those bytes. If so, we try to replace the
8672 // load + replace + store sequence with a single (narrower) store, which makes
8674 if (Opc == ISD::OR) {
8675 std::pair<unsigned, unsigned> MaskedLoad;
8676 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8677 if (MaskedLoad.first)
8678 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8679 Value.getOperand(1), ST,this))
8680 return SDValue(NewST, 0);
8682 // Or is commutative, so try swapping X and Y.
8683 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8684 if (MaskedLoad.first)
8685 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8686 Value.getOperand(0), ST,this))
8687 return SDValue(NewST, 0);
8690 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8691 Value.getOperand(1).getOpcode() != ISD::Constant)
8694 SDValue N0 = Value.getOperand(0);
8695 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8696 Chain == SDValue(N0.getNode(), 1)) {
8697 LoadSDNode *LD = cast<LoadSDNode>(N0);
8698 if (LD->getBasePtr() != Ptr ||
8699 LD->getPointerInfo().getAddrSpace() !=
8700 ST->getPointerInfo().getAddrSpace())
8703 // Find the type to narrow it the load / op / store to.
8704 SDValue N1 = Value.getOperand(1);
8705 unsigned BitWidth = N1.getValueSizeInBits();
8706 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8707 if (Opc == ISD::AND)
8708 Imm ^= APInt::getAllOnesValue(BitWidth);
8709 if (Imm == 0 || Imm.isAllOnesValue())
8711 unsigned ShAmt = Imm.countTrailingZeros();
8712 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8713 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8714 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8715 while (NewBW < BitWidth &&
8716 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8717 TLI.isNarrowingProfitable(VT, NewVT))) {
8718 NewBW = NextPowerOf2(NewBW);
8719 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8721 if (NewBW >= BitWidth)
8724 // If the lsb changed does not start at the type bitwidth boundary,
8725 // start at the previous one.
8727 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8728 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8729 std::min(BitWidth, ShAmt + NewBW));
8730 if ((Imm & Mask) == Imm) {
8731 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8732 if (Opc == ISD::AND)
8733 NewImm ^= APInt::getAllOnesValue(NewBW);
8734 uint64_t PtrOff = ShAmt / 8;
8735 // For big endian targets, we need to adjust the offset to the pointer to
8736 // load the correct bytes.
8737 if (TLI.isBigEndian())
8738 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8740 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8741 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8742 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8745 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8746 Ptr.getValueType(), Ptr,
8747 DAG.getConstant(PtrOff, Ptr.getValueType()));
8748 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8749 LD->getChain(), NewPtr,
8750 LD->getPointerInfo().getWithOffset(PtrOff),
8751 LD->isVolatile(), LD->isNonTemporal(),
8752 LD->isInvariant(), NewAlign,
8754 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8755 DAG.getConstant(NewImm, NewVT));
8756 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8758 ST->getPointerInfo().getWithOffset(PtrOff),
8759 false, false, NewAlign);
8761 AddToWorkList(NewPtr.getNode());
8762 AddToWorkList(NewLD.getNode());
8763 AddToWorkList(NewVal.getNode());
8764 WorkListRemover DeadNodes(*this);
8765 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8774 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8775 /// if the load value isn't used by any other operations, then consider
8776 /// transforming the pair to integer load / store operations if the target
8777 /// deems the transformation profitable.
8778 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8779 StoreSDNode *ST = cast<StoreSDNode>(N);
8780 SDValue Chain = ST->getChain();
8781 SDValue Value = ST->getValue();
8782 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8783 Value.hasOneUse() &&
8784 Chain == SDValue(Value.getNode(), 1)) {
8785 LoadSDNode *LD = cast<LoadSDNode>(Value);
8786 EVT VT = LD->getMemoryVT();
8787 if (!VT.isFloatingPoint() ||
8788 VT != ST->getMemoryVT() ||
8789 LD->isNonTemporal() ||
8790 ST->isNonTemporal() ||
8791 LD->getPointerInfo().getAddrSpace() != 0 ||
8792 ST->getPointerInfo().getAddrSpace() != 0)
8795 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8796 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8797 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8798 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8799 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8802 unsigned LDAlign = LD->getAlignment();
8803 unsigned STAlign = ST->getAlignment();
8804 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8805 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8806 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8809 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8810 LD->getChain(), LD->getBasePtr(),
8811 LD->getPointerInfo(),
8812 false, false, false, LDAlign);
8814 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8815 NewLD, ST->getBasePtr(),
8816 ST->getPointerInfo(),
8817 false, false, STAlign);
8819 AddToWorkList(NewLD.getNode());
8820 AddToWorkList(NewST.getNode());
8821 WorkListRemover DeadNodes(*this);
8822 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8830 /// Helper struct to parse and store a memory address as base + index + offset.
8831 /// We ignore sign extensions when it is safe to do so.
8832 /// The following two expressions are not equivalent. To differentiate we need
8833 /// to store whether there was a sign extension involved in the index
8835 /// (load (i64 add (i64 copyfromreg %c)
8836 /// (i64 signextend (add (i8 load %index)
8840 /// (load (i64 add (i64 copyfromreg %c)
8841 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8843 struct BaseIndexOffset {
8847 bool IsIndexSignExt;
8849 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8851 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8852 bool IsIndexSignExt) :
8853 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8855 bool equalBaseIndex(const BaseIndexOffset &Other) {
8856 return Other.Base == Base && Other.Index == Index &&
8857 Other.IsIndexSignExt == IsIndexSignExt;
8860 /// Parses tree in Ptr for base, index, offset addresses.
8861 static BaseIndexOffset match(SDValue Ptr) {
8862 bool IsIndexSignExt = false;
8864 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8865 // instruction, then it could be just the BASE or everything else we don't
8866 // know how to handle. Just use Ptr as BASE and give up.
8867 if (Ptr->getOpcode() != ISD::ADD)
8868 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8870 // We know that we have at least an ADD instruction. Try to pattern match
8871 // the simple case of BASE + OFFSET.
8872 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8873 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8874 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8878 // Inside a loop the current BASE pointer is calculated using an ADD and a
8879 // MUL instruction. In this case Ptr is the actual BASE pointer.
8880 // (i64 add (i64 %array_ptr)
8881 // (i64 mul (i64 %induction_var)
8882 // (i64 %element_size)))
8883 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8884 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8886 // Look at Base + Index + Offset cases.
8887 SDValue Base = Ptr->getOperand(0);
8888 SDValue IndexOffset = Ptr->getOperand(1);
8890 // Skip signextends.
8891 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8892 IndexOffset = IndexOffset->getOperand(0);
8893 IsIndexSignExt = true;
8896 // Either the case of Base + Index (no offset) or something else.
8897 if (IndexOffset->getOpcode() != ISD::ADD)
8898 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8900 // Now we have the case of Base + Index + offset.
8901 SDValue Index = IndexOffset->getOperand(0);
8902 SDValue Offset = IndexOffset->getOperand(1);
8904 if (!isa<ConstantSDNode>(Offset))
8905 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8907 // Ignore signextends.
8908 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8909 Index = Index->getOperand(0);
8910 IsIndexSignExt = true;
8911 } else IsIndexSignExt = false;
8913 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8914 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8918 /// Holds a pointer to an LSBaseSDNode as well as information on where it
8919 /// is located in a sequence of memory operations connected by a chain.
8921 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8922 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8923 // Ptr to the mem node.
8924 LSBaseSDNode *MemNode;
8925 // Offset from the base ptr.
8926 int64_t OffsetFromBase;
8927 // What is the sequence number of this mem node.
8928 // Lowest mem operand in the DAG starts at zero.
8929 unsigned SequenceNum;
8932 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8933 EVT MemVT = St->getMemoryVT();
8934 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
8935 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8936 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
8938 // Don't merge vectors into wider inputs.
8939 if (MemVT.isVector() || !MemVT.isSimple())
8942 // Perform an early exit check. Do not bother looking at stored values that
8943 // are not constants or loads.
8944 SDValue StoredVal = St->getValue();
8945 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8946 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8950 // Only look at ends of store sequences.
8951 SDValue Chain = SDValue(St, 1);
8952 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8955 // This holds the base pointer, index, and the offset in bytes from the base
8957 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
8959 // We must have a base and an offset.
8960 if (!BasePtr.Base.getNode())
8963 // Do not handle stores to undef base pointers.
8964 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
8967 // Save the LoadSDNodes that we find in the chain.
8968 // We need to make sure that these nodes do not interfere with
8969 // any of the store nodes.
8970 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8972 // Save the StoreSDNodes that we find in the chain.
8973 SmallVector<MemOpLink, 8> StoreNodes;
8975 // Walk up the chain and look for nodes with offsets from the same
8976 // base pointer. Stop when reaching an instruction with a different kind
8977 // or instruction which has a different base pointer.
8979 StoreSDNode *Index = St;
8981 // If the chain has more than one use, then we can't reorder the mem ops.
8982 if (Index != St && !SDValue(Index, 1)->hasOneUse())
8985 // Find the base pointer and offset for this memory node.
8986 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
8988 // Check that the base pointer is the same as the original one.
8989 if (!Ptr.equalBaseIndex(BasePtr))
8992 // Check that the alignment is the same.
8993 if (Index->getAlignment() != St->getAlignment())
8996 // The memory operands must not be volatile.
8997 if (Index->isVolatile() || Index->isIndexed())
9001 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9002 if (St->isTruncatingStore())
9005 // The stored memory type must be the same.
9006 if (Index->getMemoryVT() != MemVT)
9009 // We do not allow unaligned stores because we want to prevent overriding
9011 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9014 // We found a potential memory operand to merge.
9015 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9017 // Find the next memory operand in the chain. If the next operand in the
9018 // chain is a store then move up and continue the scan with the next
9019 // memory operand. If the next operand is a load save it and use alias
9020 // information to check if it interferes with anything.
9021 SDNode *NextInChain = Index->getChain().getNode();
9023 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9024 // We found a store node. Use it for the next iteration.
9027 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9028 if (Ldn->isVolatile()) {
9033 // Save the load node for later. Continue the scan.
9034 AliasLoadNodes.push_back(Ldn);
9035 NextInChain = Ldn->getChain().getNode();
9044 // Check if there is anything to merge.
9045 if (StoreNodes.size() < 2)
9048 // Sort the memory operands according to their distance from the base pointer.
9049 std::sort(StoreNodes.begin(), StoreNodes.end(),
9050 [](MemOpLink LHS, MemOpLink RHS) {
9051 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9052 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9053 LHS.SequenceNum > RHS.SequenceNum);
9056 // Scan the memory operations on the chain and find the first non-consecutive
9057 // store memory address.
9058 unsigned LastConsecutiveStore = 0;
9059 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9060 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9062 // Check that the addresses are consecutive starting from the second
9063 // element in the list of stores.
9065 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9066 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9071 // Check if this store interferes with any of the loads that we found.
9072 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9073 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9077 // We found a load that alias with this store. Stop the sequence.
9081 // Mark this node as useful.
9082 LastConsecutiveStore = i;
9085 // The node with the lowest store address.
9086 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9088 // Store the constants into memory as one consecutive store.
9090 unsigned LastLegalType = 0;
9091 unsigned LastLegalVectorType = 0;
9092 bool NonZero = false;
9093 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9094 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9095 SDValue StoredVal = St->getValue();
9097 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9098 NonZero |= !C->isNullValue();
9099 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9100 NonZero |= !C->getConstantFPValue()->isNullValue();
9106 // Find a legal type for the constant store.
9107 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9108 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9109 if (TLI.isTypeLegal(StoreTy))
9110 LastLegalType = i+1;
9111 // Or check whether a truncstore is legal.
9112 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9113 TargetLowering::TypePromoteInteger) {
9114 EVT LegalizedStoredValueTy =
9115 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9116 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9117 LastLegalType = i+1;
9120 // Find a legal type for the vector store.
9121 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9122 if (TLI.isTypeLegal(Ty))
9123 LastLegalVectorType = i + 1;
9126 // We only use vectors if the constant is known to be zero and the
9127 // function is not marked with the noimplicitfloat attribute.
9128 if (NonZero || NoVectors)
9129 LastLegalVectorType = 0;
9131 // Check if we found a legal integer type to store.
9132 if (LastLegalType == 0 && LastLegalVectorType == 0)
9135 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9136 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9138 // Make sure we have something to merge.
9142 unsigned EarliestNodeUsed = 0;
9143 for (unsigned i=0; i < NumElem; ++i) {
9144 // Find a chain for the new wide-store operand. Notice that some
9145 // of the store nodes that we found may not be selected for inclusion
9146 // in the wide store. The chain we use needs to be the chain of the
9147 // earliest store node which is *used* and replaced by the wide store.
9148 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9149 EarliestNodeUsed = i;
9152 // The earliest Node in the DAG.
9153 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9154 SDLoc DL(StoreNodes[0].MemNode);
9158 // Find a legal type for the vector store.
9159 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9160 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9161 StoredVal = DAG.getConstant(0, Ty);
9163 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9164 APInt StoreInt(StoreBW, 0);
9166 // Construct a single integer constant which is made of the smaller
9168 bool IsLE = TLI.isLittleEndian();
9169 for (unsigned i = 0; i < NumElem ; ++i) {
9170 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9171 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9172 SDValue Val = St->getValue();
9173 StoreInt<<=ElementSizeBytes*8;
9174 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9175 StoreInt|=C->getAPIntValue().zext(StoreBW);
9176 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9177 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9179 assert(false && "Invalid constant element type");
9183 // Create the new Load and Store operations.
9184 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9185 StoredVal = DAG.getConstant(StoreInt, StoreTy);
9188 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9189 FirstInChain->getBasePtr(),
9190 FirstInChain->getPointerInfo(),
9192 FirstInChain->getAlignment());
9194 // Replace the first store with the new store
9195 CombineTo(EarliestOp, NewStore);
9196 // Erase all other stores.
9197 for (unsigned i = 0; i < NumElem ; ++i) {
9198 if (StoreNodes[i].MemNode == EarliestOp)
9200 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9201 // ReplaceAllUsesWith will replace all uses that existed when it was
9202 // called, but graph optimizations may cause new ones to appear. For
9203 // example, the case in pr14333 looks like
9205 // St's chain -> St -> another store -> X
9207 // And the only difference from St to the other store is the chain.
9208 // When we change it's chain to be St's chain they become identical,
9209 // get CSEed and the net result is that X is now a use of St.
9210 // Since we know that St is redundant, just iterate.
9211 while (!St->use_empty())
9212 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9213 removeFromWorkList(St);
9220 // Below we handle the case of multiple consecutive stores that
9221 // come from multiple consecutive loads. We merge them into a single
9222 // wide load and a single wide store.
9224 // Look for load nodes which are used by the stored values.
9225 SmallVector<MemOpLink, 8> LoadNodes;
9227 // Find acceptable loads. Loads need to have the same chain (token factor),
9228 // must not be zext, volatile, indexed, and they must be consecutive.
9229 BaseIndexOffset LdBasePtr;
9230 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9231 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9232 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9235 // Loads must only have one use.
9236 if (!Ld->hasNUsesOfValue(1, 0))
9239 // Check that the alignment is the same as the stores.
9240 if (Ld->getAlignment() != St->getAlignment())
9243 // The memory operands must not be volatile.
9244 if (Ld->isVolatile() || Ld->isIndexed())
9247 // We do not accept ext loads.
9248 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9251 // The stored memory type must be the same.
9252 if (Ld->getMemoryVT() != MemVT)
9255 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9256 // If this is not the first ptr that we check.
9257 if (LdBasePtr.Base.getNode()) {
9258 // The base ptr must be the same.
9259 if (!LdPtr.equalBaseIndex(LdBasePtr))
9262 // Check that all other base pointers are the same as this one.
9266 // We found a potential memory operand to merge.
9267 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9270 if (LoadNodes.size() < 2)
9273 // Scan the memory operations on the chain and find the first non-consecutive
9274 // load memory address. These variables hold the index in the store node
9276 unsigned LastConsecutiveLoad = 0;
9277 // This variable refers to the size and not index in the array.
9278 unsigned LastLegalVectorType = 0;
9279 unsigned LastLegalIntegerType = 0;
9280 StartAddress = LoadNodes[0].OffsetFromBase;
9281 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9282 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9283 // All loads much share the same chain.
9284 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9287 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9288 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9290 LastConsecutiveLoad = i;
9292 // Find a legal type for the vector store.
9293 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9294 if (TLI.isTypeLegal(StoreTy))
9295 LastLegalVectorType = i + 1;
9297 // Find a legal type for the integer store.
9298 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9299 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9300 if (TLI.isTypeLegal(StoreTy))
9301 LastLegalIntegerType = i + 1;
9302 // Or check whether a truncstore and extload is legal.
9303 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9304 TargetLowering::TypePromoteInteger) {
9305 EVT LegalizedStoredValueTy =
9306 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9307 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9308 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9309 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9310 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9311 LastLegalIntegerType = i+1;
9315 // Only use vector types if the vector type is larger than the integer type.
9316 // If they are the same, use integers.
9317 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9318 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9320 // We add +1 here because the LastXXX variables refer to location while
9321 // the NumElem refers to array/index size.
9322 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9323 NumElem = std::min(LastLegalType, NumElem);
9328 // The earliest Node in the DAG.
9329 unsigned EarliestNodeUsed = 0;
9330 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9331 for (unsigned i=1; i<NumElem; ++i) {
9332 // Find a chain for the new wide-store operand. Notice that some
9333 // of the store nodes that we found may not be selected for inclusion
9334 // in the wide store. The chain we use needs to be the chain of the
9335 // earliest store node which is *used* and replaced by the wide store.
9336 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9337 EarliestNodeUsed = i;
9340 // Find if it is better to use vectors or integers to load and store
9344 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9346 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9347 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9350 SDLoc LoadDL(LoadNodes[0].MemNode);
9351 SDLoc StoreDL(StoreNodes[0].MemNode);
9353 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9354 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9355 FirstLoad->getChain(),
9356 FirstLoad->getBasePtr(),
9357 FirstLoad->getPointerInfo(),
9358 false, false, false,
9359 FirstLoad->getAlignment());
9361 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9362 FirstInChain->getBasePtr(),
9363 FirstInChain->getPointerInfo(), false, false,
9364 FirstInChain->getAlignment());
9366 // Replace one of the loads with the new load.
9367 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9368 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9369 SDValue(NewLoad.getNode(), 1));
9371 // Remove the rest of the load chains.
9372 for (unsigned i = 1; i < NumElem ; ++i) {
9373 // Replace all chain users of the old load nodes with the chain of the new
9375 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9376 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9379 // Replace the first store with the new store.
9380 CombineTo(EarliestOp, NewStore);
9381 // Erase all other stores.
9382 for (unsigned i = 0; i < NumElem ; ++i) {
9383 // Remove all Store nodes.
9384 if (StoreNodes[i].MemNode == EarliestOp)
9386 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9387 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9388 removeFromWorkList(St);
9395 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9396 StoreSDNode *ST = cast<StoreSDNode>(N);
9397 SDValue Chain = ST->getChain();
9398 SDValue Value = ST->getValue();
9399 SDValue Ptr = ST->getBasePtr();
9401 // If this is a store of a bit convert, store the input value if the
9402 // resultant store does not need a higher alignment than the original.
9403 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9404 ST->isUnindexed()) {
9405 unsigned OrigAlign = ST->getAlignment();
9406 EVT SVT = Value.getOperand(0).getValueType();
9407 unsigned Align = TLI.getDataLayout()->
9408 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9409 if (Align <= OrigAlign &&
9410 ((!LegalOperations && !ST->isVolatile()) ||
9411 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9412 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9413 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9414 ST->isNonTemporal(), OrigAlign,
9418 // Turn 'store undef, Ptr' -> nothing.
9419 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9422 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9423 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9424 // NOTE: If the original store is volatile, this transform must not increase
9425 // the number of stores. For example, on x86-32 an f64 can be stored in one
9426 // processor operation but an i64 (which is not legal) requires two. So the
9427 // transform should not be done in this case.
9428 if (Value.getOpcode() != ISD::TargetConstantFP) {
9430 switch (CFP->getSimpleValueType(0).SimpleTy) {
9431 default: llvm_unreachable("Unknown FP type");
9432 case MVT::f16: // We don't do this for these yet.
9438 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9439 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9440 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9441 bitcastToAPInt().getZExtValue(), MVT::i32);
9442 return DAG.getStore(Chain, SDLoc(N), Tmp,
9443 Ptr, ST->getMemOperand());
9447 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9448 !ST->isVolatile()) ||
9449 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9450 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9451 getZExtValue(), MVT::i64);
9452 return DAG.getStore(Chain, SDLoc(N), Tmp,
9453 Ptr, ST->getMemOperand());
9456 if (!ST->isVolatile() &&
9457 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9458 // Many FP stores are not made apparent until after legalize, e.g. for
9459 // argument passing. Since this is so common, custom legalize the
9460 // 64-bit integer store into two 32-bit stores.
9461 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9462 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9463 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9464 if (TLI.isBigEndian()) std::swap(Lo, Hi);
9466 unsigned Alignment = ST->getAlignment();
9467 bool isVolatile = ST->isVolatile();
9468 bool isNonTemporal = ST->isNonTemporal();
9469 const MDNode *TBAAInfo = ST->getTBAAInfo();
9471 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9472 Ptr, ST->getPointerInfo(),
9473 isVolatile, isNonTemporal,
9474 ST->getAlignment(), TBAAInfo);
9475 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9476 DAG.getConstant(4, Ptr.getValueType()));
9477 Alignment = MinAlign(Alignment, 4U);
9478 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9479 Ptr, ST->getPointerInfo().getWithOffset(4),
9480 isVolatile, isNonTemporal,
9481 Alignment, TBAAInfo);
9482 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9491 // Try to infer better alignment information than the store already has.
9492 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9493 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9494 if (Align > ST->getAlignment())
9495 return DAG.getTruncStore(Chain, SDLoc(N), Value,
9496 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9497 ST->isVolatile(), ST->isNonTemporal(), Align,
9502 // Try transforming a pair floating point load / store ops to integer
9503 // load / store ops.
9504 SDValue NewST = TransformFPLoadStorePair(N);
9505 if (NewST.getNode())
9508 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9509 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9511 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9512 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9515 if (UseAA && ST->isUnindexed()) {
9516 // Walk up chain skipping non-aliasing memory nodes.
9517 SDValue BetterChain = FindBetterChain(N, Chain);
9519 // If there is a better chain.
9520 if (Chain != BetterChain) {
9523 // Replace the chain to avoid dependency.
9524 if (ST->isTruncatingStore()) {
9525 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9526 ST->getMemoryVT(), ST->getMemOperand());
9528 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9529 ST->getMemOperand());
9532 // Create token to keep both nodes around.
9533 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9534 MVT::Other, Chain, ReplStore);
9536 // Make sure the new and old chains are cleaned up.
9537 AddToWorkList(Token.getNode());
9539 // Don't add users to work list.
9540 return CombineTo(N, Token, false);
9544 // Try transforming N to an indexed store.
9545 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9546 return SDValue(N, 0);
9548 // FIXME: is there such a thing as a truncating indexed store?
9549 if (ST->isTruncatingStore() && ST->isUnindexed() &&
9550 Value.getValueType().isInteger()) {
9551 // See if we can simplify the input to this truncstore with knowledge that
9552 // only the low bits are being used. For example:
9553 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
9555 GetDemandedBits(Value,
9556 APInt::getLowBitsSet(
9557 Value.getValueType().getScalarType().getSizeInBits(),
9558 ST->getMemoryVT().getScalarType().getSizeInBits()));
9559 AddToWorkList(Value.getNode());
9560 if (Shorter.getNode())
9561 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9562 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9564 // Otherwise, see if we can simplify the operation with
9565 // SimplifyDemandedBits, which only works if the value has a single use.
9566 if (SimplifyDemandedBits(Value,
9567 APInt::getLowBitsSet(
9568 Value.getValueType().getScalarType().getSizeInBits(),
9569 ST->getMemoryVT().getScalarType().getSizeInBits())))
9570 return SDValue(N, 0);
9573 // If this is a load followed by a store to the same location, then the store
9575 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9576 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9577 ST->isUnindexed() && !ST->isVolatile() &&
9578 // There can't be any side effects between the load and store, such as
9580 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9581 // The store is dead, remove it.
9586 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9587 // truncating store. We can do this even if this is already a truncstore.
9588 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9589 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9590 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9591 ST->getMemoryVT())) {
9592 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9593 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9596 // Only perform this optimization before the types are legal, because we
9597 // don't want to perform this optimization on every DAGCombine invocation.
9599 bool EverChanged = false;
9602 // There can be multiple store sequences on the same chain.
9603 // Keep trying to merge store sequences until we are unable to do so
9604 // or until we merge the last store on the chain.
9605 bool Changed = MergeConsecutiveStores(ST);
9606 EverChanged |= Changed;
9607 if (!Changed) break;
9608 } while (ST->getOpcode() != ISD::DELETED_NODE);
9611 return SDValue(N, 0);
9614 return ReduceLoadOpStoreWidth(N);
9617 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9618 SDValue InVec = N->getOperand(0);
9619 SDValue InVal = N->getOperand(1);
9620 SDValue EltNo = N->getOperand(2);
9623 // If the inserted element is an UNDEF, just use the input vector.
9624 if (InVal.getOpcode() == ISD::UNDEF)
9627 EVT VT = InVec.getValueType();
9629 // If we can't generate a legal BUILD_VECTOR, exit
9630 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9633 // Check that we know which element is being inserted
9634 if (!isa<ConstantSDNode>(EltNo))
9636 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9638 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9639 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9641 SmallVector<SDValue, 8> Ops;
9642 // Do not combine these two vectors if the output vector will not replace
9643 // the input vector.
9644 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9645 Ops.append(InVec.getNode()->op_begin(),
9646 InVec.getNode()->op_end());
9647 } else if (InVec.getOpcode() == ISD::UNDEF) {
9648 unsigned NElts = VT.getVectorNumElements();
9649 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9654 // Insert the element
9655 if (Elt < Ops.size()) {
9656 // All the operands of BUILD_VECTOR must have the same type;
9657 // we enforce that here.
9658 EVT OpVT = Ops[0].getValueType();
9659 if (InVal.getValueType() != OpVT)
9660 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9661 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9662 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9666 // Return the new vector
9667 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
9670 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9671 // (vextract (scalar_to_vector val, 0) -> val
9672 SDValue InVec = N->getOperand(0);
9673 EVT VT = InVec.getValueType();
9674 EVT NVT = N->getValueType(0);
9676 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9677 // Check if the result type doesn't match the inserted element type. A
9678 // SCALAR_TO_VECTOR may truncate the inserted element and the
9679 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9680 SDValue InOp = InVec.getOperand(0);
9681 if (InOp.getValueType() != NVT) {
9682 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9683 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9688 SDValue EltNo = N->getOperand(1);
9689 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9691 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9692 // We only perform this optimization before the op legalization phase because
9693 // we may introduce new vector instructions which are not backed by TD
9694 // patterns. For example on AVX, extracting elements from a wide vector
9695 // without using extract_subvector. However, if we can find an underlying
9696 // scalar value, then we can always use that.
9697 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9699 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9700 int NumElem = VT.getVectorNumElements();
9701 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9702 // Find the new index to extract from.
9703 int OrigElt = SVOp->getMaskElt(Elt);
9705 // Extracting an undef index is undef.
9707 return DAG.getUNDEF(NVT);
9709 // Select the right vector half to extract from.
9711 if (OrigElt < NumElem) {
9712 SVInVec = InVec->getOperand(0);
9714 SVInVec = InVec->getOperand(1);
9718 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9719 SDValue InOp = SVInVec.getOperand(OrigElt);
9720 if (InOp.getValueType() != NVT) {
9721 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9722 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9728 // FIXME: We should handle recursing on other vector shuffles and
9729 // scalar_to_vector here as well.
9731 if (!LegalOperations) {
9732 EVT IndexTy = TLI.getVectorIdxTy();
9733 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9734 SVInVec, DAG.getConstant(OrigElt, IndexTy));
9738 // Perform only after legalization to ensure build_vector / vector_shuffle
9739 // optimizations have already been done.
9740 if (!LegalOperations) return SDValue();
9742 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9743 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9744 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9747 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9748 bool NewLoad = false;
9749 bool BCNumEltsChanged = false;
9750 EVT ExtVT = VT.getVectorElementType();
9753 // If the result of load has to be truncated, then it's not necessarily
9755 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9758 if (InVec.getOpcode() == ISD::BITCAST) {
9759 // Don't duplicate a load with other uses.
9760 if (!InVec.hasOneUse())
9763 EVT BCVT = InVec.getOperand(0).getValueType();
9764 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9766 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9767 BCNumEltsChanged = true;
9768 InVec = InVec.getOperand(0);
9769 ExtVT = BCVT.getVectorElementType();
9773 LoadSDNode *LN0 = nullptr;
9774 const ShuffleVectorSDNode *SVN = nullptr;
9775 if (ISD::isNormalLoad(InVec.getNode())) {
9776 LN0 = cast<LoadSDNode>(InVec);
9777 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9778 InVec.getOperand(0).getValueType() == ExtVT &&
9779 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9780 // Don't duplicate a load with other uses.
9781 if (!InVec.hasOneUse())
9784 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9785 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9786 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9788 // (load $addr+1*size)
9790 // Don't duplicate a load with other uses.
9791 if (!InVec.hasOneUse())
9794 // If the bit convert changed the number of elements, it is unsafe
9795 // to examine the mask.
9796 if (BCNumEltsChanged)
9799 // Select the input vector, guarding against out of range extract vector.
9800 unsigned NumElems = VT.getVectorNumElements();
9801 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9802 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9804 if (InVec.getOpcode() == ISD::BITCAST) {
9805 // Don't duplicate a load with other uses.
9806 if (!InVec.hasOneUse())
9809 InVec = InVec.getOperand(0);
9811 if (ISD::isNormalLoad(InVec.getNode())) {
9812 LN0 = cast<LoadSDNode>(InVec);
9813 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9817 // Make sure we found a non-volatile load and the extractelement is
9819 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9822 // If Idx was -1 above, Elt is going to be -1, so just return undef.
9824 return DAG.getUNDEF(LVT);
9826 unsigned Align = LN0->getAlignment();
9828 // Check the resultant load doesn't need a higher alignment than the
9832 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9834 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9840 SDValue NewPtr = LN0->getBasePtr();
9841 unsigned PtrOff = 0;
9844 PtrOff = LVT.getSizeInBits() * Elt / 8;
9845 EVT PtrType = NewPtr.getValueType();
9846 if (TLI.isBigEndian())
9847 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9848 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9849 DAG.getConstant(PtrOff, PtrType));
9852 // The replacement we need to do here is a little tricky: we need to
9853 // replace an extractelement of a load with a load.
9854 // Use ReplaceAllUsesOfValuesWith to do the replacement.
9855 // Note that this replacement assumes that the extractvalue is the only
9856 // use of the load; that's okay because we don't want to perform this
9857 // transformation in other cases anyway.
9860 if (NVT.bitsGT(LVT)) {
9861 // If the result type of vextract is wider than the load, then issue an
9862 // extending load instead.
9863 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9864 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9865 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9866 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9867 LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9868 Align, LN0->getTBAAInfo());
9869 Chain = Load.getValue(1);
9871 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9872 LN0->getPointerInfo().getWithOffset(PtrOff),
9873 LN0->isVolatile(), LN0->isNonTemporal(),
9874 LN0->isInvariant(), Align, LN0->getTBAAInfo());
9875 Chain = Load.getValue(1);
9876 if (NVT.bitsLT(LVT))
9877 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
9879 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
9881 WorkListRemover DeadNodes(*this);
9882 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
9883 SDValue To[] = { Load, Chain };
9884 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9885 // Since we're explcitly calling ReplaceAllUses, add the new node to the
9886 // worklist explicitly as well.
9887 AddToWorkList(Load.getNode());
9888 AddUsersToWorkList(Load.getNode()); // Add users too
9889 // Make sure to revisit this node to clean it up; it will usually be dead.
9891 return SDValue(N, 0);
9897 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
9898 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9899 // We perform this optimization post type-legalization because
9900 // the type-legalizer often scalarizes integer-promoted vectors.
9901 // Performing this optimization before may create bit-casts which
9902 // will be type-legalized to complex code sequences.
9903 // We perform this optimization only before the operation legalizer because we
9904 // may introduce illegal operations.
9905 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9908 unsigned NumInScalars = N->getNumOperands();
9910 EVT VT = N->getValueType(0);
9912 // Check to see if this is a BUILD_VECTOR of a bunch of values
9913 // which come from any_extend or zero_extend nodes. If so, we can create
9914 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
9915 // optimizations. We do not handle sign-extend because we can't fill the sign
9917 EVT SourceType = MVT::Other;
9918 bool AllAnyExt = true;
9920 for (unsigned i = 0; i != NumInScalars; ++i) {
9921 SDValue In = N->getOperand(i);
9922 // Ignore undef inputs.
9923 if (In.getOpcode() == ISD::UNDEF) continue;
9925 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
9926 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9928 // Abort if the element is not an extension.
9929 if (!ZeroExt && !AnyExt) {
9930 SourceType = MVT::Other;
9934 // The input is a ZeroExt or AnyExt. Check the original type.
9935 EVT InTy = In.getOperand(0).getValueType();
9937 // Check that all of the widened source types are the same.
9938 if (SourceType == MVT::Other)
9941 else if (InTy != SourceType) {
9942 // Multiple income types. Abort.
9943 SourceType = MVT::Other;
9947 // Check if all of the extends are ANY_EXTENDs.
9948 AllAnyExt &= AnyExt;
9951 // In order to have valid types, all of the inputs must be extended from the
9952 // same source type and all of the inputs must be any or zero extend.
9953 // Scalar sizes must be a power of two.
9954 EVT OutScalarTy = VT.getScalarType();
9955 bool ValidTypes = SourceType != MVT::Other &&
9956 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9957 isPowerOf2_32(SourceType.getSizeInBits());
9959 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9960 // turn into a single shuffle instruction.
9964 bool isLE = TLI.isLittleEndian();
9965 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
9966 assert(ElemRatio > 1 && "Invalid element size ratio");
9967 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
9968 DAG.getConstant(0, SourceType);
9970 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
9971 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
9973 // Populate the new build_vector
9974 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9975 SDValue Cast = N->getOperand(i);
9976 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
9977 Cast.getOpcode() == ISD::ZERO_EXTEND ||
9978 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
9980 if (Cast.getOpcode() == ISD::UNDEF)
9981 In = DAG.getUNDEF(SourceType);
9983 In = Cast->getOperand(0);
9984 unsigned Index = isLE ? (i * ElemRatio) :
9985 (i * ElemRatio + (ElemRatio - 1));
9987 assert(Index < Ops.size() && "Invalid index");
9991 // The type of the new BUILD_VECTOR node.
9992 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
9993 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
9994 "Invalid vector size");
9995 // Check if the new vector type is legal.
9996 if (!isTypeLegal(VecVT)) return SDValue();
9998 // Make the new BUILD_VECTOR.
9999 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10001 // The new BUILD_VECTOR node has the potential to be further optimized.
10002 AddToWorkList(BV.getNode());
10003 // Bitcast to the desired type.
10004 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10007 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10008 EVT VT = N->getValueType(0);
10010 unsigned NumInScalars = N->getNumOperands();
10013 EVT SrcVT = MVT::Other;
10014 unsigned Opcode = ISD::DELETED_NODE;
10015 unsigned NumDefs = 0;
10017 for (unsigned i = 0; i != NumInScalars; ++i) {
10018 SDValue In = N->getOperand(i);
10019 unsigned Opc = In.getOpcode();
10021 if (Opc == ISD::UNDEF)
10024 // If all scalar values are floats and converted from integers.
10025 if (Opcode == ISD::DELETED_NODE &&
10026 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10033 EVT InVT = In.getOperand(0).getValueType();
10035 // If all scalar values are typed differently, bail out. It's chosen to
10036 // simplify BUILD_VECTOR of integer types.
10037 if (SrcVT == MVT::Other)
10044 // If the vector has just one element defined, it's not worth to fold it into
10045 // a vectorized one.
10049 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10050 && "Should only handle conversion from integer to float.");
10051 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10053 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10055 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10058 SmallVector<SDValue, 8> Opnds;
10059 for (unsigned i = 0; i != NumInScalars; ++i) {
10060 SDValue In = N->getOperand(i);
10062 if (In.getOpcode() == ISD::UNDEF)
10063 Opnds.push_back(DAG.getUNDEF(SrcVT));
10065 Opnds.push_back(In.getOperand(0));
10067 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10068 AddToWorkList(BV.getNode());
10070 return DAG.getNode(Opcode, dl, VT, BV);
10073 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10074 unsigned NumInScalars = N->getNumOperands();
10076 EVT VT = N->getValueType(0);
10078 // A vector built entirely of undefs is undef.
10079 if (ISD::allOperandsUndef(N))
10080 return DAG.getUNDEF(VT);
10082 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10086 V = reduceBuildVecConvertToConvertBuildVec(N);
10090 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10091 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10092 // at most two distinct vectors, turn this into a shuffle node.
10094 // May only combine to shuffle after legalize if shuffle is legal.
10095 if (LegalOperations &&
10096 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10099 SDValue VecIn1, VecIn2;
10100 for (unsigned i = 0; i != NumInScalars; ++i) {
10101 // Ignore undef inputs.
10102 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10104 // If this input is something other than a EXTRACT_VECTOR_ELT with a
10105 // constant index, bail out.
10106 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10107 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10108 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10112 // We allow up to two distinct input vectors.
10113 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10114 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10117 if (!VecIn1.getNode()) {
10118 VecIn1 = ExtractedFromVec;
10119 } else if (!VecIn2.getNode()) {
10120 VecIn2 = ExtractedFromVec;
10122 // Too many inputs.
10123 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10128 // If everything is good, we can make a shuffle operation.
10129 if (VecIn1.getNode()) {
10130 SmallVector<int, 8> Mask;
10131 for (unsigned i = 0; i != NumInScalars; ++i) {
10132 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10133 Mask.push_back(-1);
10137 // If extracting from the first vector, just use the index directly.
10138 SDValue Extract = N->getOperand(i);
10139 SDValue ExtVal = Extract.getOperand(1);
10140 if (Extract.getOperand(0) == VecIn1) {
10141 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10142 if (ExtIndex > VT.getVectorNumElements())
10145 Mask.push_back(ExtIndex);
10149 // Otherwise, use InIdx + VecSize
10150 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10151 Mask.push_back(Idx+NumInScalars);
10154 // We can't generate a shuffle node with mismatched input and output types.
10155 // Attempt to transform a single input vector to the correct type.
10156 if ((VT != VecIn1.getValueType())) {
10157 // We don't support shuffeling between TWO values of different types.
10158 if (VecIn2.getNode())
10161 // We only support widening of vectors which are half the size of the
10162 // output registers. For example XMM->YMM widening on X86 with AVX.
10163 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10166 // If the input vector type has a different base type to the output
10167 // vector type, bail out.
10168 if (VecIn1.getValueType().getVectorElementType() !=
10169 VT.getVectorElementType())
10172 // Widen the input vector by adding undef values.
10173 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10174 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10177 // If VecIn2 is unused then change it to undef.
10178 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10180 // Check that we were able to transform all incoming values to the same
10182 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10183 VecIn1.getValueType() != VT)
10186 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10187 if (!isTypeLegal(VT))
10190 // Return the new VECTOR_SHUFFLE node.
10194 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10200 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10201 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10202 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10203 // inputs come from at most two distinct vectors, turn this into a shuffle
10206 // If we only have one input vector, we don't need to do any concatenation.
10207 if (N->getNumOperands() == 1)
10208 return N->getOperand(0);
10210 // Check if all of the operands are undefs.
10211 EVT VT = N->getValueType(0);
10212 if (ISD::allOperandsUndef(N))
10213 return DAG.getUNDEF(VT);
10215 // Optimize concat_vectors where one of the vectors is undef.
10216 if (N->getNumOperands() == 2 &&
10217 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10218 SDValue In = N->getOperand(0);
10219 assert(In.getValueType().isVector() && "Must concat vectors");
10221 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10222 if (In->getOpcode() == ISD::BITCAST &&
10223 !In->getOperand(0)->getValueType(0).isVector()) {
10224 SDValue Scalar = In->getOperand(0);
10225 EVT SclTy = Scalar->getValueType(0);
10227 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10230 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10231 VT.getSizeInBits() / SclTy.getSizeInBits());
10232 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10235 SDLoc dl = SDLoc(N);
10236 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10237 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10241 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10242 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10243 if (N->getNumOperands() == 2 &&
10244 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10245 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10246 EVT VT = N->getValueType(0);
10247 SDValue N0 = N->getOperand(0);
10248 SDValue N1 = N->getOperand(1);
10249 SmallVector<SDValue, 8> Opnds;
10250 unsigned BuildVecNumElts = N0.getNumOperands();
10252 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10253 Opnds.push_back(N0.getOperand(i));
10254 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10255 Opnds.push_back(N1.getOperand(i));
10257 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10260 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10261 // nodes often generate nop CONCAT_VECTOR nodes.
10262 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10263 // place the incoming vectors at the exact same location.
10264 SDValue SingleSource = SDValue();
10265 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10267 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10268 SDValue Op = N->getOperand(i);
10270 if (Op.getOpcode() == ISD::UNDEF)
10273 // Check if this is the identity extract:
10274 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10277 // Find the single incoming vector for the extract_subvector.
10278 if (SingleSource.getNode()) {
10279 if (Op.getOperand(0) != SingleSource)
10282 SingleSource = Op.getOperand(0);
10284 // Check the source type is the same as the type of the result.
10285 // If not, this concat may extend the vector, so we can not
10286 // optimize it away.
10287 if (SingleSource.getValueType() != N->getValueType(0))
10291 unsigned IdentityIndex = i * PartNumElem;
10292 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10293 // The extract index must be constant.
10297 // Check that we are reading from the identity index.
10298 if (CS->getZExtValue() != IdentityIndex)
10302 if (SingleSource.getNode())
10303 return SingleSource;
10308 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10309 EVT NVT = N->getValueType(0);
10310 SDValue V = N->getOperand(0);
10312 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10314 // (extract_subvec (concat V1, V2, ...), i)
10317 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10319 if (V->getOperand(0).getValueType() != NVT)
10321 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10322 unsigned NumElems = NVT.getVectorNumElements();
10323 assert((Idx % NumElems) == 0 &&
10324 "IDX in concat is not a multiple of the result vector length.");
10325 return V->getOperand(Idx / NumElems);
10329 if (V->getOpcode() == ISD::BITCAST)
10330 V = V.getOperand(0);
10332 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10334 // Handle only simple case where vector being inserted and vector
10335 // being extracted are of same type, and are half size of larger vectors.
10336 EVT BigVT = V->getOperand(0).getValueType();
10337 EVT SmallVT = V->getOperand(1).getValueType();
10338 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10341 // Only handle cases where both indexes are constants with the same type.
10342 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10343 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10345 if (InsIdx && ExtIdx &&
10346 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10347 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10349 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10351 // indices are equal or bit offsets are equal => V1
10352 // otherwise => (extract_subvec V1, ExtIdx)
10353 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10354 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10355 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10356 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10357 DAG.getNode(ISD::BITCAST, dl,
10358 N->getOperand(0).getValueType(),
10359 V->getOperand(0)), N->getOperand(1));
10366 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10367 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10368 EVT VT = N->getValueType(0);
10369 unsigned NumElts = VT.getVectorNumElements();
10371 SDValue N0 = N->getOperand(0);
10372 SDValue N1 = N->getOperand(1);
10373 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10375 SmallVector<SDValue, 4> Ops;
10376 EVT ConcatVT = N0.getOperand(0).getValueType();
10377 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10378 unsigned NumConcats = NumElts / NumElemsPerConcat;
10380 // Look at every vector that's inserted. We're looking for exact
10381 // subvector-sized copies from a concatenated vector
10382 for (unsigned I = 0; I != NumConcats; ++I) {
10383 // Make sure we're dealing with a copy.
10384 unsigned Begin = I * NumElemsPerConcat;
10385 bool AllUndef = true, NoUndef = true;
10386 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10387 if (SVN->getMaskElt(J) >= 0)
10394 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10397 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10398 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10401 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10402 if (FirstElt < N0.getNumOperands())
10403 Ops.push_back(N0.getOperand(FirstElt));
10405 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10407 } else if (AllUndef) {
10408 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10409 } else { // Mixed with general masks and undefs, can't do optimization.
10414 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10417 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10418 EVT VT = N->getValueType(0);
10419 unsigned NumElts = VT.getVectorNumElements();
10421 SDValue N0 = N->getOperand(0);
10422 SDValue N1 = N->getOperand(1);
10424 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10426 // Canonicalize shuffle undef, undef -> undef
10427 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10428 return DAG.getUNDEF(VT);
10430 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10432 // Canonicalize shuffle v, v -> v, undef
10434 SmallVector<int, 8> NewMask;
10435 for (unsigned i = 0; i != NumElts; ++i) {
10436 int Idx = SVN->getMaskElt(i);
10437 if (Idx >= (int)NumElts) Idx -= NumElts;
10438 NewMask.push_back(Idx);
10440 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10444 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10445 if (N0.getOpcode() == ISD::UNDEF) {
10446 SmallVector<int, 8> NewMask;
10447 for (unsigned i = 0; i != NumElts; ++i) {
10448 int Idx = SVN->getMaskElt(i);
10450 if (Idx >= (int)NumElts)
10453 Idx = -1; // remove reference to lhs
10455 NewMask.push_back(Idx);
10457 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10461 // Remove references to rhs if it is undef
10462 if (N1.getOpcode() == ISD::UNDEF) {
10463 bool Changed = false;
10464 SmallVector<int, 8> NewMask;
10465 for (unsigned i = 0; i != NumElts; ++i) {
10466 int Idx = SVN->getMaskElt(i);
10467 if (Idx >= (int)NumElts) {
10471 NewMask.push_back(Idx);
10474 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10477 // If it is a splat, check if the argument vector is another splat or a
10478 // build_vector with all scalar elements the same.
10479 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10480 SDNode *V = N0.getNode();
10482 // If this is a bit convert that changes the element type of the vector but
10483 // not the number of vector elements, look through it. Be careful not to
10484 // look though conversions that change things like v4f32 to v2f64.
10485 if (V->getOpcode() == ISD::BITCAST) {
10486 SDValue ConvInput = V->getOperand(0);
10487 if (ConvInput.getValueType().isVector() &&
10488 ConvInput.getValueType().getVectorNumElements() == NumElts)
10489 V = ConvInput.getNode();
10492 if (V->getOpcode() == ISD::BUILD_VECTOR) {
10493 assert(V->getNumOperands() == NumElts &&
10494 "BUILD_VECTOR has wrong number of operands");
10496 bool AllSame = true;
10497 for (unsigned i = 0; i != NumElts; ++i) {
10498 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10499 Base = V->getOperand(i);
10503 // Splat of <u, u, u, u>, return <u, u, u, u>
10504 if (!Base.getNode())
10506 for (unsigned i = 0; i != NumElts; ++i) {
10507 if (V->getOperand(i) != Base) {
10512 // Splat of <x, x, x, x>, return <x, x, x, x>
10518 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10519 Level < AfterLegalizeVectorOps &&
10520 (N1.getOpcode() == ISD::UNDEF ||
10521 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10522 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10523 SDValue V = partitionShuffleOfConcats(N, DAG);
10529 // If this shuffle node is simply a swizzle of another shuffle node,
10530 // and it reverses the swizzle of the previous shuffle then we can
10531 // optimize shuffle(shuffle(x, undef), undef) -> x.
10532 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10533 N1.getOpcode() == ISD::UNDEF) {
10535 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10537 // Shuffle nodes can only reverse shuffles with a single non-undef value.
10538 if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10541 // The incoming shuffle must be of the same type as the result of the
10542 // current shuffle.
10543 assert(OtherSV->getOperand(0).getValueType() == VT &&
10544 "Shuffle types don't match");
10546 for (unsigned i = 0; i != NumElts; ++i) {
10547 int Idx = SVN->getMaskElt(i);
10548 assert(Idx < (int)NumElts && "Index references undef operand");
10549 // Next, this index comes from the first value, which is the incoming
10550 // shuffle. Adopt the incoming index.
10552 Idx = OtherSV->getMaskElt(Idx);
10554 // The combined shuffle must map each index to itself.
10555 if (Idx >= 0 && (unsigned)Idx != i)
10559 return OtherSV->getOperand(0);
10565 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10566 SDValue N0 = N->getOperand(0);
10567 SDValue N2 = N->getOperand(2);
10569 // If the input vector is a concatenation, and the insert replaces
10570 // one of the halves, we can optimize into a single concat_vectors.
10571 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10572 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10573 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10574 EVT VT = N->getValueType(0);
10576 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10577 // (concat_vectors Z, Y)
10579 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10580 N->getOperand(1), N0.getOperand(1));
10582 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10583 // (concat_vectors X, Z)
10584 if (InsIdx == VT.getVectorNumElements()/2)
10585 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10586 N0.getOperand(0), N->getOperand(1));
10592 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10593 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10594 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10595 /// vector_shuffle V, Zero, <0, 4, 2, 4>
10596 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10597 EVT VT = N->getValueType(0);
10599 SDValue LHS = N->getOperand(0);
10600 SDValue RHS = N->getOperand(1);
10601 if (N->getOpcode() == ISD::AND) {
10602 if (RHS.getOpcode() == ISD::BITCAST)
10603 RHS = RHS.getOperand(0);
10604 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10605 SmallVector<int, 8> Indices;
10606 unsigned NumElts = RHS.getNumOperands();
10607 for (unsigned i = 0; i != NumElts; ++i) {
10608 SDValue Elt = RHS.getOperand(i);
10609 if (!isa<ConstantSDNode>(Elt))
10612 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10613 Indices.push_back(i);
10614 else if (cast<ConstantSDNode>(Elt)->isNullValue())
10615 Indices.push_back(NumElts);
10620 // Let's see if the target supports this vector_shuffle.
10621 EVT RVT = RHS.getValueType();
10622 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10625 // Return the new VECTOR_SHUFFLE node.
10626 EVT EltVT = RVT.getVectorElementType();
10627 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10628 DAG.getConstant(0, EltVT));
10629 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
10630 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10631 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10632 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10639 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10640 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10641 assert(N->getValueType(0).isVector() &&
10642 "SimplifyVBinOp only works on vectors!");
10644 SDValue LHS = N->getOperand(0);
10645 SDValue RHS = N->getOperand(1);
10646 SDValue Shuffle = XformToShuffleWithZero(N);
10647 if (Shuffle.getNode()) return Shuffle;
10649 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10651 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10652 RHS.getOpcode() == ISD::BUILD_VECTOR) {
10653 // Check if both vectors are constants. If not bail out.
10654 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10655 cast<BuildVectorSDNode>(RHS)->isConstant()))
10658 SmallVector<SDValue, 8> Ops;
10659 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10660 SDValue LHSOp = LHS.getOperand(i);
10661 SDValue RHSOp = RHS.getOperand(i);
10663 // Can't fold divide by zero.
10664 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10665 N->getOpcode() == ISD::FDIV) {
10666 if ((RHSOp.getOpcode() == ISD::Constant &&
10667 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10668 (RHSOp.getOpcode() == ISD::ConstantFP &&
10669 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10673 EVT VT = LHSOp.getValueType();
10674 EVT RVT = RHSOp.getValueType();
10676 // Integer BUILD_VECTOR operands may have types larger than the element
10677 // size (e.g., when the element type is not legal). Prior to type
10678 // legalization, the types may not match between the two BUILD_VECTORS.
10679 // Truncate one of the operands to make them match.
10680 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10681 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10683 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10687 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10689 if (FoldOp.getOpcode() != ISD::UNDEF &&
10690 FoldOp.getOpcode() != ISD::Constant &&
10691 FoldOp.getOpcode() != ISD::ConstantFP)
10693 Ops.push_back(FoldOp);
10694 AddToWorkList(FoldOp.getNode());
10697 if (Ops.size() == LHS.getNumOperands())
10698 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
10704 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10705 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10706 assert(N->getValueType(0).isVector() &&
10707 "SimplifyVUnaryOp only works on vectors!");
10709 SDValue N0 = N->getOperand(0);
10711 if (N0.getOpcode() != ISD::BUILD_VECTOR)
10714 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10715 SmallVector<SDValue, 8> Ops;
10716 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10717 SDValue Op = N0.getOperand(i);
10718 if (Op.getOpcode() != ISD::UNDEF &&
10719 Op.getOpcode() != ISD::ConstantFP)
10721 EVT EltVT = Op.getValueType();
10722 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
10723 if (FoldOp.getOpcode() != ISD::UNDEF &&
10724 FoldOp.getOpcode() != ISD::ConstantFP)
10726 Ops.push_back(FoldOp);
10727 AddToWorkList(FoldOp.getNode());
10730 if (Ops.size() != N0.getNumOperands())
10733 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
10736 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10737 SDValue N1, SDValue N2){
10738 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10740 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
10741 cast<CondCodeSDNode>(N0.getOperand(2))->get());
10743 // If we got a simplified select_cc node back from SimplifySelectCC, then
10744 // break it down into a new SETCC node, and a new SELECT node, and then return
10745 // the SELECT node, since we were called with a SELECT node.
10746 if (SCC.getNode()) {
10747 // Check to see if we got a select_cc back (to turn into setcc/select).
10748 // Otherwise, just return whatever node we got back, like fabs.
10749 if (SCC.getOpcode() == ISD::SELECT_CC) {
10750 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
10752 SCC.getOperand(0), SCC.getOperand(1),
10753 SCC.getOperand(4));
10754 AddToWorkList(SETCC.getNode());
10755 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10756 SCC.getOperand(2), SCC.getOperand(3), SETCC);
10764 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10765 /// are the two values being selected between, see if we can simplify the
10766 /// select. Callers of this should assume that TheSelect is deleted if this
10767 /// returns true. As such, they should return the appropriate thing (e.g. the
10768 /// node) back to the top-level of the DAG combiner loop to avoid it being
10770 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
10773 // Cannot simplify select with vector condition
10774 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10776 // If this is a select from two identical things, try to pull the operation
10777 // through the select.
10778 if (LHS.getOpcode() != RHS.getOpcode() ||
10779 !LHS.hasOneUse() || !RHS.hasOneUse())
10782 // If this is a load and the token chain is identical, replace the select
10783 // of two loads with a load through a select of the address to load from.
10784 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10785 // constants have been dropped into the constant pool.
10786 if (LHS.getOpcode() == ISD::LOAD) {
10787 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10788 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
10790 // Token chains must be identical.
10791 if (LHS.getOperand(0) != RHS.getOperand(0) ||
10792 // Do not let this transformation reduce the number of volatile loads.
10793 LLD->isVolatile() || RLD->isVolatile() ||
10794 // If this is an EXTLOAD, the VT's must match.
10795 LLD->getMemoryVT() != RLD->getMemoryVT() ||
10796 // If this is an EXTLOAD, the kind of extension must match.
10797 (LLD->getExtensionType() != RLD->getExtensionType() &&
10798 // The only exception is if one of the extensions is anyext.
10799 LLD->getExtensionType() != ISD::EXTLOAD &&
10800 RLD->getExtensionType() != ISD::EXTLOAD) ||
10801 // FIXME: this discards src value information. This is
10802 // over-conservative. It would be beneficial to be able to remember
10803 // both potential memory locations. Since we are discarding
10804 // src value info, don't do the transformation if the memory
10805 // locations are not in the default address space.
10806 LLD->getPointerInfo().getAddrSpace() != 0 ||
10807 RLD->getPointerInfo().getAddrSpace() != 0 ||
10808 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10809 LLD->getBasePtr().getValueType()))
10812 // Check that the select condition doesn't reach either load. If so,
10813 // folding this will induce a cycle into the DAG. If not, this is safe to
10814 // xform, so create a select of the addresses.
10816 if (TheSelect->getOpcode() == ISD::SELECT) {
10817 SDNode *CondNode = TheSelect->getOperand(0).getNode();
10818 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10819 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10821 // The loads must not depend on one another.
10822 if (LLD->isPredecessorOf(RLD) ||
10823 RLD->isPredecessorOf(LLD))
10825 Addr = DAG.getSelect(SDLoc(TheSelect),
10826 LLD->getBasePtr().getValueType(),
10827 TheSelect->getOperand(0), LLD->getBasePtr(),
10828 RLD->getBasePtr());
10829 } else { // Otherwise SELECT_CC
10830 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10831 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10833 if ((LLD->hasAnyUseOfValue(1) &&
10834 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
10835 (RLD->hasAnyUseOfValue(1) &&
10836 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
10839 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
10840 LLD->getBasePtr().getValueType(),
10841 TheSelect->getOperand(0),
10842 TheSelect->getOperand(1),
10843 LLD->getBasePtr(), RLD->getBasePtr(),
10844 TheSelect->getOperand(4));
10848 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10849 Load = DAG.getLoad(TheSelect->getValueType(0),
10851 // FIXME: Discards pointer and TBAA info.
10852 LLD->getChain(), Addr, MachinePointerInfo(),
10853 LLD->isVolatile(), LLD->isNonTemporal(),
10854 LLD->isInvariant(), LLD->getAlignment());
10856 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10857 RLD->getExtensionType() : LLD->getExtensionType(),
10859 TheSelect->getValueType(0),
10860 // FIXME: Discards pointer and TBAA info.
10861 LLD->getChain(), Addr, MachinePointerInfo(),
10862 LLD->getMemoryVT(), LLD->isVolatile(),
10863 LLD->isNonTemporal(), LLD->getAlignment());
10866 // Users of the select now use the result of the load.
10867 CombineTo(TheSelect, Load);
10869 // Users of the old loads now use the new load's chain. We know the
10870 // old-load value is dead now.
10871 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10872 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10879 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10880 /// where 'cond' is the comparison specified by CC.
10881 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
10882 SDValue N2, SDValue N3,
10883 ISD::CondCode CC, bool NotExtCompare) {
10884 // (x ? y : y) -> y.
10885 if (N2 == N3) return N2;
10887 EVT VT = N2.getValueType();
10888 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10889 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10890 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
10892 // Determine if the condition we're dealing with is constant
10893 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
10894 N0, N1, CC, DL, false);
10895 if (SCC.getNode()) AddToWorkList(SCC.getNode());
10896 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
10898 // fold select_cc true, x, y -> x
10899 if (SCCC && !SCCC->isNullValue())
10901 // fold select_cc false, x, y -> y
10902 if (SCCC && SCCC->isNullValue())
10905 // Check to see if we can simplify the select into an fabs node
10906 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10907 // Allow either -0.0 or 0.0
10908 if (CFP->getValueAPF().isZero()) {
10909 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10910 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10911 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10912 N2 == N3.getOperand(0))
10913 return DAG.getNode(ISD::FABS, DL, VT, N0);
10915 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10916 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10917 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10918 N2.getOperand(0) == N3)
10919 return DAG.getNode(ISD::FABS, DL, VT, N3);
10923 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10924 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10925 // in it. This is a win when the constant is not otherwise available because
10926 // it replaces two constant pool loads with one. We only do this if the FP
10927 // type is known to be legal, because if it isn't, then we are before legalize
10928 // types an we want the other legalization to happen first (e.g. to avoid
10929 // messing with soft float) and if the ConstantFP is not legal, because if
10930 // it is legal, we may not need to store the FP constant in a constant pool.
10931 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10932 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10933 if (TLI.isTypeLegal(N2.getValueType()) &&
10934 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10935 TargetLowering::Legal &&
10936 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
10937 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
10938 // If both constants have multiple uses, then we won't need to do an
10939 // extra load, they are likely around in registers for other users.
10940 (TV->hasOneUse() || FV->hasOneUse())) {
10941 Constant *Elts[] = {
10942 const_cast<ConstantFP*>(FV->getConstantFPValue()),
10943 const_cast<ConstantFP*>(TV->getConstantFPValue())
10945 Type *FPTy = Elts[0]->getType();
10946 const DataLayout &TD = *TLI.getDataLayout();
10948 // Create a ConstantArray of the two constants.
10949 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
10950 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10951 TD.getPrefTypeAlignment(FPTy));
10952 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10954 // Get the offsets to the 0 and 1 element of the array so that we can
10955 // select between them.
10956 SDValue Zero = DAG.getIntPtrConstant(0);
10957 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
10958 SDValue One = DAG.getIntPtrConstant(EltSize);
10960 SDValue Cond = DAG.getSetCC(DL,
10961 getSetCCResultType(N0.getValueType()),
10963 AddToWorkList(Cond.getNode());
10964 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
10966 AddToWorkList(CstOffset.getNode());
10967 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
10969 AddToWorkList(CPIdx.getNode());
10970 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
10971 MachinePointerInfo::getConstantPool(), false,
10972 false, false, Alignment);
10977 // Check to see if we can perform the "gzip trick", transforming
10978 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
10979 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
10980 (N1C->isNullValue() || // (a < 0) ? b : 0
10981 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
10982 EVT XType = N0.getValueType();
10983 EVT AType = N2.getValueType();
10984 if (XType.bitsGE(AType)) {
10985 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
10986 // single-bit constant.
10987 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
10988 unsigned ShCtV = N2C->getAPIntValue().logBase2();
10989 ShCtV = XType.getSizeInBits()-ShCtV-1;
10990 SDValue ShCt = DAG.getConstant(ShCtV,
10991 getShiftAmountTy(N0.getValueType()));
10992 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
10994 AddToWorkList(Shift.getNode());
10996 if (XType.bitsGT(AType)) {
10997 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
10998 AddToWorkList(Shift.getNode());
11001 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11004 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11006 DAG.getConstant(XType.getSizeInBits()-1,
11007 getShiftAmountTy(N0.getValueType())));
11008 AddToWorkList(Shift.getNode());
11010 if (XType.bitsGT(AType)) {
11011 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11012 AddToWorkList(Shift.getNode());
11015 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11019 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11020 // where y is has a single bit set.
11021 // A plaintext description would be, we can turn the SELECT_CC into an AND
11022 // when the condition can be materialized as an all-ones register. Any
11023 // single bit-test can be materialized as an all-ones register with
11024 // shift-left and shift-right-arith.
11025 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11026 N0->getValueType(0) == VT &&
11027 N1C && N1C->isNullValue() &&
11028 N2C && N2C->isNullValue()) {
11029 SDValue AndLHS = N0->getOperand(0);
11030 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11031 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11032 // Shift the tested bit over the sign bit.
11033 APInt AndMask = ConstAndRHS->getAPIntValue();
11035 DAG.getConstant(AndMask.countLeadingZeros(),
11036 getShiftAmountTy(AndLHS.getValueType()));
11037 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11039 // Now arithmetic right shift it all the way over, so the result is either
11040 // all-ones, or zero.
11042 DAG.getConstant(AndMask.getBitWidth()-1,
11043 getShiftAmountTy(Shl.getValueType()));
11044 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11046 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11050 // fold select C, 16, 0 -> shl C, 4
11051 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11052 TLI.getBooleanContents(N0.getValueType().isVector()) ==
11053 TargetLowering::ZeroOrOneBooleanContent) {
11055 // If the caller doesn't want us to simplify this into a zext of a compare,
11057 if (NotExtCompare && N2C->getAPIntValue() == 1)
11060 // Get a SetCC of the condition
11061 // NOTE: Don't create a SETCC if it's not legal on this target.
11062 if (!LegalOperations ||
11063 TLI.isOperationLegal(ISD::SETCC,
11064 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11066 // cast from setcc result type to select result type
11068 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11070 if (N2.getValueType().bitsLT(SCC.getValueType()))
11071 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11072 N2.getValueType());
11074 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11075 N2.getValueType(), SCC);
11077 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11078 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11079 N2.getValueType(), SCC);
11082 AddToWorkList(SCC.getNode());
11083 AddToWorkList(Temp.getNode());
11085 if (N2C->getAPIntValue() == 1)
11088 // shl setcc result by log2 n2c
11089 return DAG.getNode(
11090 ISD::SHL, DL, N2.getValueType(), Temp,
11091 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11092 getShiftAmountTy(Temp.getValueType())));
11096 // Check to see if this is the equivalent of setcc
11097 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11098 // otherwise, go ahead with the folds.
11099 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11100 EVT XType = N0.getValueType();
11101 if (!LegalOperations ||
11102 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11103 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11104 if (Res.getValueType() != VT)
11105 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11109 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11110 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11111 (!LegalOperations ||
11112 TLI.isOperationLegal(ISD::CTLZ, XType))) {
11113 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11114 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11115 DAG.getConstant(Log2_32(XType.getSizeInBits()),
11116 getShiftAmountTy(Ctlz.getValueType())));
11118 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11119 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11120 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11121 XType, DAG.getConstant(0, XType), N0);
11122 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11123 return DAG.getNode(ISD::SRL, DL, XType,
11124 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11125 DAG.getConstant(XType.getSizeInBits()-1,
11126 getShiftAmountTy(XType)));
11128 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11129 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11130 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11131 DAG.getConstant(XType.getSizeInBits()-1,
11132 getShiftAmountTy(N0.getValueType())));
11133 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11137 // Check to see if this is an integer abs.
11138 // select_cc setg[te] X, 0, X, -X ->
11139 // select_cc setgt X, -1, X, -X ->
11140 // select_cc setl[te] X, 0, -X, X ->
11141 // select_cc setlt X, 1, -X, X ->
11142 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11144 ConstantSDNode *SubC = nullptr;
11145 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11146 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11147 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11148 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11149 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11150 (N1C->isOne() && CC == ISD::SETLT)) &&
11151 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11152 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11154 EVT XType = N0.getValueType();
11155 if (SubC && SubC->isNullValue() && XType.isInteger()) {
11156 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11158 DAG.getConstant(XType.getSizeInBits()-1,
11159 getShiftAmountTy(N0.getValueType())));
11160 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11162 AddToWorkList(Shift.getNode());
11163 AddToWorkList(Add.getNode());
11164 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11171 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11172 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11173 SDValue N1, ISD::CondCode Cond,
11174 SDLoc DL, bool foldBooleans) {
11175 TargetLowering::DAGCombinerInfo
11176 DagCombineInfo(DAG, Level, false, this);
11177 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11180 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11181 /// return a DAG expression to select that will generate the same value by
11182 /// multiplying by a magic number. See:
11183 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11184 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11185 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11189 // Avoid division by zero.
11190 if (!C->getAPIntValue())
11193 std::vector<SDNode*> Built;
11195 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11197 for (SDNode *N : Built)
11202 /// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant,
11203 /// return a DAG expression to select that will generate the same value by
11204 /// multiplying by a magic number. See:
11205 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11206 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11207 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11211 // Avoid division by zero.
11212 if (!C->getAPIntValue())
11215 std::vector<SDNode*> Built;
11217 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11219 for (SDNode *N : Built)
11224 /// FindBaseOffset - Return true if base is a frame index, which is known not
11225 // to alias with anything but itself. Provides base object and offset as
11227 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11228 const GlobalValue *&GV, const void *&CV) {
11229 // Assume it is a primitive operation.
11230 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11232 // If it's an adding a simple constant then integrate the offset.
11233 if (Base.getOpcode() == ISD::ADD) {
11234 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11235 Base = Base.getOperand(0);
11236 Offset += C->getZExtValue();
11240 // Return the underlying GlobalValue, and update the Offset. Return false
11241 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11242 // by multiple nodes with different offsets.
11243 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11244 GV = G->getGlobal();
11245 Offset += G->getOffset();
11249 // Return the underlying Constant value, and update the Offset. Return false
11250 // for ConstantSDNodes since the same constant pool entry may be represented
11251 // by multiple nodes with different offsets.
11252 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11253 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11254 : (const void *)C->getConstVal();
11255 Offset += C->getOffset();
11258 // If it's any of the following then it can't alias with anything but itself.
11259 return isa<FrameIndexSDNode>(Base);
11262 /// isAlias - Return true if there is any possibility that the two addresses
11264 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11265 // If they are the same then they must be aliases.
11266 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11268 // If they are both volatile then they cannot be reordered.
11269 if (Op0->isVolatile() && Op1->isVolatile()) return true;
11271 // Gather base node and offset information.
11272 SDValue Base1, Base2;
11273 int64_t Offset1, Offset2;
11274 const GlobalValue *GV1, *GV2;
11275 const void *CV1, *CV2;
11276 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11277 Base1, Offset1, GV1, CV1);
11278 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11279 Base2, Offset2, GV2, CV2);
11281 // If they have a same base address then check to see if they overlap.
11282 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11283 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11284 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11286 // It is possible for different frame indices to alias each other, mostly
11287 // when tail call optimization reuses return address slots for arguments.
11288 // To catch this case, look up the actual index of frame indices to compute
11289 // the real alias relationship.
11290 if (isFrameIndex1 && isFrameIndex2) {
11291 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11292 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11293 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11294 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11295 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11298 // Otherwise, if we know what the bases are, and they aren't identical, then
11299 // we know they cannot alias.
11300 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11303 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11304 // compared to the size and offset of the access, we may be able to prove they
11305 // do not alias. This check is conservative for now to catch cases created by
11306 // splitting vector types.
11307 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11308 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11309 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11310 Op1->getMemoryVT().getSizeInBits() >> 3) &&
11311 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11312 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11313 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11315 // There is no overlap between these relatively aligned accesses of similar
11316 // size, return no alias.
11317 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11318 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11322 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11323 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11325 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11326 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11330 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11331 // Use alias analysis information.
11332 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11333 Op1->getSrcValueOffset());
11334 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11335 Op0->getSrcValueOffset() - MinOffset;
11336 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11337 Op1->getSrcValueOffset() - MinOffset;
11338 AliasAnalysis::AliasResult AAResult =
11339 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11341 UseTBAA ? Op0->getTBAAInfo() : nullptr),
11342 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11344 UseTBAA ? Op1->getTBAAInfo() : nullptr));
11345 if (AAResult == AliasAnalysis::NoAlias)
11349 // Otherwise we have to assume they alias.
11353 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11354 /// looking for aliasing nodes and adding them to the Aliases vector.
11355 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11356 SmallVectorImpl<SDValue> &Aliases) {
11357 SmallVector<SDValue, 8> Chains; // List of chains to visit.
11358 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
11360 // Get alias information for node.
11361 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11364 Chains.push_back(OriginalChain);
11365 unsigned Depth = 0;
11367 // Look at each chain and determine if it is an alias. If so, add it to the
11368 // aliases list. If not, then continue up the chain looking for the next
11370 while (!Chains.empty()) {
11371 SDValue Chain = Chains.back();
11374 // For TokenFactor nodes, look at each operand and only continue up the
11375 // chain until we find two aliases. If we've seen two aliases, assume we'll
11376 // find more and revert to original chain since the xform is unlikely to be
11379 // FIXME: The depth check could be made to return the last non-aliasing
11380 // chain we found before we hit a tokenfactor rather than the original
11382 if (Depth > 6 || Aliases.size() == 2) {
11384 Aliases.push_back(OriginalChain);
11388 // Don't bother if we've been before.
11389 if (!Visited.insert(Chain.getNode()))
11392 switch (Chain.getOpcode()) {
11393 case ISD::EntryToken:
11394 // Entry token is ideal chain operand, but handled in FindBetterChain.
11399 // Get alias information for Chain.
11400 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11401 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11403 // If chain is alias then stop here.
11404 if (!(IsLoad && IsOpLoad) &&
11405 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11406 Aliases.push_back(Chain);
11408 // Look further up the chain.
11409 Chains.push_back(Chain.getOperand(0));
11415 case ISD::TokenFactor:
11416 // We have to check each of the operands of the token factor for "small"
11417 // token factors, so we queue them up. Adding the operands to the queue
11418 // (stack) in reverse order maintains the original order and increases the
11419 // likelihood that getNode will find a matching token factor (CSE.)
11420 if (Chain.getNumOperands() > 16) {
11421 Aliases.push_back(Chain);
11424 for (unsigned n = Chain.getNumOperands(); n;)
11425 Chains.push_back(Chain.getOperand(--n));
11430 // For all other instructions we will just have to take what we can get.
11431 Aliases.push_back(Chain);
11436 // We need to be careful here to also search for aliases through the
11437 // value operand of a store, etc. Consider the following situation:
11439 // L1 = load Token1, %52
11440 // S1 = store Token1, L1, %51
11441 // L2 = load Token1, %52+8
11442 // S2 = store Token1, L2, %51+8
11443 // Token2 = Token(S1, S2)
11444 // L3 = load Token2, %53
11445 // S3 = store Token2, L3, %52
11446 // L4 = load Token2, %53+8
11447 // S4 = store Token2, L4, %52+8
11448 // If we search for aliases of S3 (which loads address %52), and we look
11449 // only through the chain, then we'll miss the trivial dependence on L1
11450 // (which also loads from %52). We then might change all loads and
11451 // stores to use Token1 as their chain operand, which could result in
11452 // copying %53 into %52 before copying %52 into %51 (which should
11455 // The problem is, however, that searching for such data dependencies
11456 // can become expensive, and the cost is not directly related to the
11457 // chain depth. Instead, we'll rule out such configurations here by
11458 // insisting that we've visited all chain users (except for users
11459 // of the original chain, which is not necessary). When doing this,
11460 // we need to look through nodes we don't care about (otherwise, things
11461 // like register copies will interfere with trivial cases).
11463 SmallVector<const SDNode *, 16> Worklist;
11464 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11465 IE = Visited.end(); I != IE; ++I)
11466 if (*I != OriginalChain.getNode())
11467 Worklist.push_back(*I);
11469 while (!Worklist.empty()) {
11470 const SDNode *M = Worklist.pop_back_val();
11472 // We have already visited M, and want to make sure we've visited any uses
11473 // of M that we care about. For uses that we've not visisted, and don't
11474 // care about, queue them to the worklist.
11476 for (SDNode::use_iterator UI = M->use_begin(),
11477 UIE = M->use_end(); UI != UIE; ++UI)
11478 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11479 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11480 // We've not visited this use, and we care about it (it could have an
11481 // ordering dependency with the original node).
11483 Aliases.push_back(OriginalChain);
11487 // We've not visited this use, but we don't care about it. Mark it as
11488 // visited and enqueue it to the worklist.
11489 Worklist.push_back(*UI);
11494 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11495 /// for a better chain (aliasing node.)
11496 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11497 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
11499 // Accumulate all the aliases to this node.
11500 GatherAllAliases(N, OldChain, Aliases);
11502 // If no operands then chain to entry token.
11503 if (Aliases.size() == 0)
11504 return DAG.getEntryNode();
11506 // If a single operand then chain to it. We don't need to revisit it.
11507 if (Aliases.size() == 1)
11510 // Construct a custom tailored token factor.
11511 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
11514 // SelectionDAG::Combine - This is the entry point for the file.
11516 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11517 CodeGenOpt::Level OptLevel) {
11518 /// run - This is the main entry point to this class.
11520 DAGCombiner(*this, AA, OptLevel).Run(Level);