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 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
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 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
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 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
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 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
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 if (!TLI.isDesirableToCommuteWithShift(LHS))
3873 // Fold the constants, shifting the binop RHS by the shift amount.
3874 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3876 LHS->getOperand(1), N->getOperand(1));
3877 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3879 // Create the new shift.
3880 SDValue NewShift = DAG.getNode(N->getOpcode(),
3881 SDLoc(LHS->getOperand(0)),
3882 VT, LHS->getOperand(0), N->getOperand(1));
3884 // Create the new binop.
3885 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3888 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3889 assert(N->getOpcode() == ISD::TRUNCATE);
3890 assert(N->getOperand(0).getOpcode() == ISD::AND);
3892 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3893 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3894 SDValue N01 = N->getOperand(0).getOperand(1);
3896 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3897 EVT TruncVT = N->getValueType(0);
3898 SDValue N00 = N->getOperand(0).getOperand(0);
3899 APInt TruncC = N01C->getAPIntValue();
3900 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3902 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3903 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3904 DAG.getConstant(TruncC, TruncVT));
3911 SDValue DAGCombiner::visitRotate(SDNode *N) {
3912 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3913 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3914 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3915 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3916 if (NewOp1.getNode())
3917 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3918 N->getOperand(0), NewOp1);
3923 SDValue DAGCombiner::visitSHL(SDNode *N) {
3924 SDValue N0 = N->getOperand(0);
3925 SDValue N1 = N->getOperand(1);
3926 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3927 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3928 EVT VT = N0.getValueType();
3929 unsigned OpSizeInBits = VT.getScalarSizeInBits();
3932 if (VT.isVector()) {
3933 SDValue FoldedVOp = SimplifyVBinOp(N);
3934 if (FoldedVOp.getNode()) return FoldedVOp;
3936 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3937 // If setcc produces all-one true value then:
3938 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
3939 if (N1CV && N1CV->isConstant()) {
3940 if (N0.getOpcode() == ISD::AND &&
3941 TLI.getBooleanContents(true) ==
3942 TargetLowering::ZeroOrNegativeOneBooleanContent) {
3943 SDValue N00 = N0->getOperand(0);
3944 SDValue N01 = N0->getOperand(1);
3945 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
3947 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC) {
3948 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3950 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3953 N1C = isConstOrConstSplat(N1);
3958 // fold (shl c1, c2) -> c1<<c2
3960 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3961 // fold (shl 0, x) -> 0
3962 if (N0C && N0C->isNullValue())
3964 // fold (shl x, c >= size(x)) -> undef
3965 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3966 return DAG.getUNDEF(VT);
3967 // fold (shl x, 0) -> x
3968 if (N1C && N1C->isNullValue())
3970 // fold (shl undef, x) -> 0
3971 if (N0.getOpcode() == ISD::UNDEF)
3972 return DAG.getConstant(0, VT);
3973 // if (shl x, c) is known to be zero, return 0
3974 if (DAG.MaskedValueIsZero(SDValue(N, 0),
3975 APInt::getAllOnesValue(OpSizeInBits)))
3976 return DAG.getConstant(0, VT);
3977 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3978 if (N1.getOpcode() == ISD::TRUNCATE &&
3979 N1.getOperand(0).getOpcode() == ISD::AND) {
3980 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
3981 if (NewOp1.getNode())
3982 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
3985 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3986 return SDValue(N, 0);
3988 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3989 if (N1C && N0.getOpcode() == ISD::SHL) {
3990 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
3991 uint64_t c1 = N0C1->getZExtValue();
3992 uint64_t c2 = N1C->getZExtValue();
3993 if (c1 + c2 >= OpSizeInBits)
3994 return DAG.getConstant(0, VT);
3995 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3996 DAG.getConstant(c1 + c2, N1.getValueType()));
4000 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4001 // For this to be valid, the second form must not preserve any of the bits
4002 // that are shifted out by the inner shift in the first form. This means
4003 // the outer shift size must be >= the number of bits added by the ext.
4004 // As a corollary, we don't care what kind of ext it is.
4005 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4006 N0.getOpcode() == ISD::ANY_EXTEND ||
4007 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4008 N0.getOperand(0).getOpcode() == ISD::SHL) {
4009 SDValue N0Op0 = N0.getOperand(0);
4010 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4011 uint64_t c1 = N0Op0C1->getZExtValue();
4012 uint64_t c2 = N1C->getZExtValue();
4013 EVT InnerShiftVT = N0Op0.getValueType();
4014 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4015 if (c2 >= OpSizeInBits - InnerShiftSize) {
4016 if (c1 + c2 >= OpSizeInBits)
4017 return DAG.getConstant(0, VT);
4018 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4019 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4020 N0Op0->getOperand(0)),
4021 DAG.getConstant(c1 + c2, N1.getValueType()));
4026 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4027 // Only fold this if the inner zext has no other uses to avoid increasing
4028 // the total number of instructions.
4029 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4030 N0.getOperand(0).getOpcode() == ISD::SRL) {
4031 SDValue N0Op0 = N0.getOperand(0);
4032 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4033 uint64_t c1 = N0Op0C1->getZExtValue();
4034 if (c1 < VT.getScalarSizeInBits()) {
4035 uint64_t c2 = N1C->getZExtValue();
4037 SDValue NewOp0 = N0.getOperand(0);
4038 EVT CountVT = NewOp0.getOperand(1).getValueType();
4039 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4040 NewOp0, DAG.getConstant(c2, CountVT));
4041 AddToWorkList(NewSHL.getNode());
4042 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4048 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4049 // (and (srl x, (sub c1, c2), MASK)
4050 // Only fold this if the inner shift has no other uses -- if it does, folding
4051 // this will increase the total number of instructions.
4052 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4053 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4054 uint64_t c1 = N0C1->getZExtValue();
4055 if (c1 < OpSizeInBits) {
4056 uint64_t c2 = N1C->getZExtValue();
4057 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4060 Mask = Mask.shl(c2 - c1);
4061 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4062 DAG.getConstant(c2 - c1, N1.getValueType()));
4064 Mask = Mask.lshr(c1 - c2);
4065 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4066 DAG.getConstant(c1 - c2, N1.getValueType()));
4068 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4069 DAG.getConstant(Mask, VT));
4073 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4074 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4075 unsigned BitSize = VT.getScalarSizeInBits();
4076 SDValue HiBitsMask =
4077 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4078 BitSize - N1C->getZExtValue()), VT);
4079 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4084 SDValue NewSHL = visitShiftByConstant(N, N1C);
4085 if (NewSHL.getNode())
4092 SDValue DAGCombiner::visitSRA(SDNode *N) {
4093 SDValue N0 = N->getOperand(0);
4094 SDValue N1 = N->getOperand(1);
4095 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4096 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4097 EVT VT = N0.getValueType();
4098 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4101 if (VT.isVector()) {
4102 SDValue FoldedVOp = SimplifyVBinOp(N);
4103 if (FoldedVOp.getNode()) return FoldedVOp;
4105 N1C = isConstOrConstSplat(N1);
4108 // fold (sra c1, c2) -> (sra c1, c2)
4110 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4111 // fold (sra 0, x) -> 0
4112 if (N0C && N0C->isNullValue())
4114 // fold (sra -1, x) -> -1
4115 if (N0C && N0C->isAllOnesValue())
4117 // fold (sra x, (setge c, size(x))) -> undef
4118 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4119 return DAG.getUNDEF(VT);
4120 // fold (sra x, 0) -> x
4121 if (N1C && N1C->isNullValue())
4123 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4125 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4126 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4127 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4129 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4130 ExtVT, VT.getVectorNumElements());
4131 if ((!LegalOperations ||
4132 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4133 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4134 N0.getOperand(0), DAG.getValueType(ExtVT));
4137 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4138 if (N1C && N0.getOpcode() == ISD::SRA) {
4139 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4140 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4141 if (Sum >= OpSizeInBits)
4142 Sum = OpSizeInBits - 1;
4143 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4144 DAG.getConstant(Sum, N1.getValueType()));
4148 // fold (sra (shl X, m), (sub result_size, n))
4149 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4150 // result_size - n != m.
4151 // If truncate is free for the target sext(shl) is likely to result in better
4153 if (N0.getOpcode() == ISD::SHL && N1C) {
4154 // Get the two constanst of the shifts, CN0 = m, CN = n.
4155 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4157 LLVMContext &Ctx = *DAG.getContext();
4158 // Determine what the truncate's result bitsize and type would be.
4159 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4162 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4164 // Determine the residual right-shift amount.
4165 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4167 // If the shift is not a no-op (in which case this should be just a sign
4168 // extend already), the truncated to type is legal, sign_extend is legal
4169 // on that type, and the truncate to that type is both legal and free,
4170 // perform the transform.
4171 if ((ShiftAmt > 0) &&
4172 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4173 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4174 TLI.isTruncateFree(VT, TruncVT)) {
4176 SDValue Amt = DAG.getConstant(ShiftAmt,
4177 getShiftAmountTy(N0.getOperand(0).getValueType()));
4178 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4179 N0.getOperand(0), Amt);
4180 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4182 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4183 N->getValueType(0), Trunc);
4188 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4189 if (N1.getOpcode() == ISD::TRUNCATE &&
4190 N1.getOperand(0).getOpcode() == ISD::AND) {
4191 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4192 if (NewOp1.getNode())
4193 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4196 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4197 // if c1 is equal to the number of bits the trunc removes
4198 if (N0.getOpcode() == ISD::TRUNCATE &&
4199 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4200 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4201 N0.getOperand(0).hasOneUse() &&
4202 N0.getOperand(0).getOperand(1).hasOneUse() &&
4204 SDValue N0Op0 = N0.getOperand(0);
4205 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4206 unsigned LargeShiftVal = LargeShift->getZExtValue();
4207 EVT LargeVT = N0Op0.getValueType();
4209 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4211 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4212 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4213 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4214 N0Op0.getOperand(0), Amt);
4215 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4220 // Simplify, based on bits shifted out of the LHS.
4221 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4222 return SDValue(N, 0);
4225 // If the sign bit is known to be zero, switch this to a SRL.
4226 if (DAG.SignBitIsZero(N0))
4227 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4230 SDValue NewSRA = visitShiftByConstant(N, N1C);
4231 if (NewSRA.getNode())
4238 SDValue DAGCombiner::visitSRL(SDNode *N) {
4239 SDValue N0 = N->getOperand(0);
4240 SDValue N1 = N->getOperand(1);
4241 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4242 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4243 EVT VT = N0.getValueType();
4244 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4247 if (VT.isVector()) {
4248 SDValue FoldedVOp = SimplifyVBinOp(N);
4249 if (FoldedVOp.getNode()) return FoldedVOp;
4251 N1C = isConstOrConstSplat(N1);
4254 // fold (srl c1, c2) -> c1 >>u c2
4256 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4257 // fold (srl 0, x) -> 0
4258 if (N0C && N0C->isNullValue())
4260 // fold (srl x, c >= size(x)) -> undef
4261 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4262 return DAG.getUNDEF(VT);
4263 // fold (srl x, 0) -> x
4264 if (N1C && N1C->isNullValue())
4266 // if (srl x, c) is known to be zero, return 0
4267 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4268 APInt::getAllOnesValue(OpSizeInBits)))
4269 return DAG.getConstant(0, VT);
4271 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4272 if (N1C && N0.getOpcode() == ISD::SRL) {
4273 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4274 uint64_t c1 = N01C->getZExtValue();
4275 uint64_t c2 = N1C->getZExtValue();
4276 if (c1 + c2 >= OpSizeInBits)
4277 return DAG.getConstant(0, VT);
4278 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4279 DAG.getConstant(c1 + c2, N1.getValueType()));
4283 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4284 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4285 N0.getOperand(0).getOpcode() == ISD::SRL &&
4286 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4288 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4289 uint64_t c2 = N1C->getZExtValue();
4290 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4291 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4292 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4293 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4294 if (c1 + OpSizeInBits == InnerShiftSize) {
4295 if (c1 + c2 >= InnerShiftSize)
4296 return DAG.getConstant(0, VT);
4297 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4298 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4299 N0.getOperand(0)->getOperand(0),
4300 DAG.getConstant(c1 + c2, ShiftCountVT)));
4304 // fold (srl (shl x, c), c) -> (and x, cst2)
4305 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4306 unsigned BitSize = N0.getScalarValueSizeInBits();
4307 if (BitSize <= 64) {
4308 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4309 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4310 DAG.getConstant(~0ULL >> ShAmt, VT));
4314 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4315 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4316 // Shifting in all undef bits?
4317 EVT SmallVT = N0.getOperand(0).getValueType();
4318 unsigned BitSize = SmallVT.getScalarSizeInBits();
4319 if (N1C->getZExtValue() >= BitSize)
4320 return DAG.getUNDEF(VT);
4322 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4323 uint64_t ShiftAmt = N1C->getZExtValue();
4324 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4326 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4327 AddToWorkList(SmallShift.getNode());
4328 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4329 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4330 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4331 DAG.getConstant(Mask, VT));
4335 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4336 // bit, which is unmodified by sra.
4337 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4338 if (N0.getOpcode() == ISD::SRA)
4339 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4342 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4343 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4344 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4345 APInt KnownZero, KnownOne;
4346 DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
4348 // If any of the input bits are KnownOne, then the input couldn't be all
4349 // zeros, thus the result of the srl will always be zero.
4350 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4352 // If all of the bits input the to ctlz node are known to be zero, then
4353 // the result of the ctlz is "32" and the result of the shift is one.
4354 APInt UnknownBits = ~KnownZero;
4355 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4357 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4358 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4359 // Okay, we know that only that the single bit specified by UnknownBits
4360 // could be set on input to the CTLZ node. If this bit is set, the SRL
4361 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4362 // to an SRL/XOR pair, which is likely to simplify more.
4363 unsigned ShAmt = UnknownBits.countTrailingZeros();
4364 SDValue Op = N0.getOperand(0);
4367 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4368 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4369 AddToWorkList(Op.getNode());
4372 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4373 Op, DAG.getConstant(1, VT));
4377 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4378 if (N1.getOpcode() == ISD::TRUNCATE &&
4379 N1.getOperand(0).getOpcode() == ISD::AND) {
4380 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4381 if (NewOp1.getNode())
4382 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4385 // fold operands of srl based on knowledge that the low bits are not
4387 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4388 return SDValue(N, 0);
4391 SDValue NewSRL = visitShiftByConstant(N, N1C);
4392 if (NewSRL.getNode())
4396 // Attempt to convert a srl of a load into a narrower zero-extending load.
4397 SDValue NarrowLoad = ReduceLoadWidth(N);
4398 if (NarrowLoad.getNode())
4401 // Here is a common situation. We want to optimize:
4404 // %b = and i32 %a, 2
4405 // %c = srl i32 %b, 1
4406 // brcond i32 %c ...
4412 // %c = setcc eq %b, 0
4415 // However when after the source operand of SRL is optimized into AND, the SRL
4416 // itself may not be optimized further. Look for it and add the BRCOND into
4418 if (N->hasOneUse()) {
4419 SDNode *Use = *N->use_begin();
4420 if (Use->getOpcode() == ISD::BRCOND)
4422 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4423 // Also look pass the truncate.
4424 Use = *Use->use_begin();
4425 if (Use->getOpcode() == ISD::BRCOND)
4433 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4434 SDValue N0 = N->getOperand(0);
4435 EVT VT = N->getValueType(0);
4437 // fold (ctlz c1) -> c2
4438 if (isa<ConstantSDNode>(N0))
4439 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4443 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4444 SDValue N0 = N->getOperand(0);
4445 EVT VT = N->getValueType(0);
4447 // fold (ctlz_zero_undef c1) -> c2
4448 if (isa<ConstantSDNode>(N0))
4449 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4453 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4454 SDValue N0 = N->getOperand(0);
4455 EVT VT = N->getValueType(0);
4457 // fold (cttz c1) -> c2
4458 if (isa<ConstantSDNode>(N0))
4459 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4463 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4464 SDValue N0 = N->getOperand(0);
4465 EVT VT = N->getValueType(0);
4467 // fold (cttz_zero_undef c1) -> c2
4468 if (isa<ConstantSDNode>(N0))
4469 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4473 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4474 SDValue N0 = N->getOperand(0);
4475 EVT VT = N->getValueType(0);
4477 // fold (ctpop c1) -> c2
4478 if (isa<ConstantSDNode>(N0))
4479 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4483 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4484 SDValue N0 = N->getOperand(0);
4485 SDValue N1 = N->getOperand(1);
4486 SDValue N2 = N->getOperand(2);
4487 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4488 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4489 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4490 EVT VT = N->getValueType(0);
4491 EVT VT0 = N0.getValueType();
4493 // fold (select C, X, X) -> X
4496 // fold (select true, X, Y) -> X
4497 if (N0C && !N0C->isNullValue())
4499 // fold (select false, X, Y) -> Y
4500 if (N0C && N0C->isNullValue())
4502 // fold (select C, 1, X) -> (or C, X)
4503 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4504 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4505 // fold (select C, 0, 1) -> (xor C, 1)
4506 if (VT.isInteger() &&
4509 TLI.getBooleanContents(false) ==
4510 TargetLowering::ZeroOrOneBooleanContent)) &&
4511 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4514 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4515 N0, DAG.getConstant(1, VT0));
4516 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4517 N0, DAG.getConstant(1, VT0));
4518 AddToWorkList(XORNode.getNode());
4520 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4521 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4523 // fold (select C, 0, X) -> (and (not C), X)
4524 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4525 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4526 AddToWorkList(NOTNode.getNode());
4527 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4529 // fold (select C, X, 1) -> (or (not C), X)
4530 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4531 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4532 AddToWorkList(NOTNode.getNode());
4533 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4535 // fold (select C, X, 0) -> (and C, X)
4536 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4537 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4538 // fold (select X, X, Y) -> (or X, Y)
4539 // fold (select X, 1, Y) -> (or X, Y)
4540 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4541 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4542 // fold (select X, Y, X) -> (and X, Y)
4543 // fold (select X, Y, 0) -> (and X, Y)
4544 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4545 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4547 // If we can fold this based on the true/false value, do so.
4548 if (SimplifySelectOps(N, N1, N2))
4549 return SDValue(N, 0); // Don't revisit N.
4551 // fold selects based on a setcc into other things, such as min/max/abs
4552 if (N0.getOpcode() == ISD::SETCC) {
4554 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4555 // having to say they don't support SELECT_CC on every type the DAG knows
4556 // about, since there is no way to mark an opcode illegal at all value types
4557 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4558 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4559 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4560 N0.getOperand(0), N0.getOperand(1),
4561 N1, N2, N0.getOperand(2));
4562 return SimplifySelect(SDLoc(N), N0, N1, N2);
4569 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4572 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4574 // Split the inputs.
4575 SDValue Lo, Hi, LL, LH, RL, RH;
4576 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4577 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4579 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4580 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4582 return std::make_pair(Lo, Hi);
4585 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4586 SDValue N0 = N->getOperand(0);
4587 SDValue N1 = N->getOperand(1);
4588 SDValue N2 = N->getOperand(2);
4591 // Canonicalize integer abs.
4592 // vselect (setg[te] X, 0), X, -X ->
4593 // vselect (setgt X, -1), X, -X ->
4594 // vselect (setl[te] X, 0), -X, X ->
4595 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4596 if (N0.getOpcode() == ISD::SETCC) {
4597 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4598 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4600 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4602 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4603 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4604 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4605 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4606 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4607 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4608 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4611 EVT VT = LHS.getValueType();
4612 SDValue Shift = DAG.getNode(
4613 ISD::SRA, DL, VT, LHS,
4614 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4615 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4616 AddToWorkList(Shift.getNode());
4617 AddToWorkList(Add.getNode());
4618 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4622 // If the VSELECT result requires splitting and the mask is provided by a
4623 // SETCC, then split both nodes and its operands before legalization. This
4624 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4625 // and enables future optimizations (e.g. min/max pattern matching on X86).
4626 if (N0.getOpcode() == ISD::SETCC) {
4627 EVT VT = N->getValueType(0);
4629 // Check if any splitting is required.
4630 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4631 TargetLowering::TypeSplitVector)
4634 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4635 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4636 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4637 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4639 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4640 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4642 // Add the new VSELECT nodes to the work list in case they need to be split
4644 AddToWorkList(Lo.getNode());
4645 AddToWorkList(Hi.getNode());
4647 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4650 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4651 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4653 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4654 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4660 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4661 SDValue N0 = N->getOperand(0);
4662 SDValue N1 = N->getOperand(1);
4663 SDValue N2 = N->getOperand(2);
4664 SDValue N3 = N->getOperand(3);
4665 SDValue N4 = N->getOperand(4);
4666 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4668 // fold select_cc lhs, rhs, x, x, cc -> x
4672 // Determine if the condition we're dealing with is constant
4673 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4674 N0, N1, CC, SDLoc(N), false);
4675 if (SCC.getNode()) {
4676 AddToWorkList(SCC.getNode());
4678 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4679 if (!SCCC->isNullValue())
4680 return N2; // cond always true -> true val
4682 return N3; // cond always false -> false val
4685 // Fold to a simpler select_cc
4686 if (SCC.getOpcode() == ISD::SETCC)
4687 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4688 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4692 // If we can fold this based on the true/false value, do so.
4693 if (SimplifySelectOps(N, N2, N3))
4694 return SDValue(N, 0); // Don't revisit N.
4696 // fold select_cc into other things, such as min/max/abs
4697 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4700 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4701 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4702 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4706 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4707 // dag node into a ConstantSDNode or a build_vector of constants.
4708 // This function is called by the DAGCombiner when visiting sext/zext/aext
4709 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4710 // Vector extends are not folded if operations are legal; this is to
4711 // avoid introducing illegal build_vector dag nodes.
4712 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4713 SelectionDAG &DAG, bool LegalTypes,
4714 bool LegalOperations) {
4715 unsigned Opcode = N->getOpcode();
4716 SDValue N0 = N->getOperand(0);
4717 EVT VT = N->getValueType(0);
4719 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4720 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4722 // fold (sext c1) -> c1
4723 // fold (zext c1) -> c1
4724 // fold (aext c1) -> c1
4725 if (isa<ConstantSDNode>(N0))
4726 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4728 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4729 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4730 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4731 EVT SVT = VT.getScalarType();
4732 if (!(VT.isVector() &&
4733 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4734 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4737 // We can fold this node into a build_vector.
4738 unsigned VTBits = SVT.getSizeInBits();
4739 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4740 unsigned ShAmt = VTBits - EVTBits;
4741 SmallVector<SDValue, 8> Elts;
4742 unsigned NumElts = N0->getNumOperands();
4745 for (unsigned i=0; i != NumElts; ++i) {
4746 SDValue Op = N0->getOperand(i);
4747 if (Op->getOpcode() == ISD::UNDEF) {
4748 Elts.push_back(DAG.getUNDEF(SVT));
4752 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4753 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4754 if (Opcode == ISD::SIGN_EXTEND)
4755 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4758 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4762 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4765 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4766 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4767 // transformation. Returns true if extension are possible and the above
4768 // mentioned transformation is profitable.
4769 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4771 SmallVectorImpl<SDNode *> &ExtendNodes,
4772 const TargetLowering &TLI) {
4773 bool HasCopyToRegUses = false;
4774 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4775 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4776 UE = N0.getNode()->use_end();
4781 if (UI.getUse().getResNo() != N0.getResNo())
4783 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4784 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4785 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4786 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4787 // Sign bits will be lost after a zext.
4790 for (unsigned i = 0; i != 2; ++i) {
4791 SDValue UseOp = User->getOperand(i);
4794 if (!isa<ConstantSDNode>(UseOp))
4799 ExtendNodes.push_back(User);
4802 // If truncates aren't free and there are users we can't
4803 // extend, it isn't worthwhile.
4806 // Remember if this value is live-out.
4807 if (User->getOpcode() == ISD::CopyToReg)
4808 HasCopyToRegUses = true;
4811 if (HasCopyToRegUses) {
4812 bool BothLiveOut = false;
4813 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4815 SDUse &Use = UI.getUse();
4816 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4822 // Both unextended and extended values are live out. There had better be
4823 // a good reason for the transformation.
4824 return ExtendNodes.size();
4829 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4830 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4831 ISD::NodeType ExtType) {
4832 // Extend SetCC uses if necessary.
4833 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4834 SDNode *SetCC = SetCCs[i];
4835 SmallVector<SDValue, 4> Ops;
4837 for (unsigned j = 0; j != 2; ++j) {
4838 SDValue SOp = SetCC->getOperand(j);
4840 Ops.push_back(ExtLoad);
4842 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4845 Ops.push_back(SetCC->getOperand(2));
4846 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
4850 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4851 SDValue N0 = N->getOperand(0);
4852 EVT VT = N->getValueType(0);
4854 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4856 return SDValue(Res, 0);
4858 // fold (sext (sext x)) -> (sext x)
4859 // fold (sext (aext x)) -> (sext x)
4860 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4861 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4864 if (N0.getOpcode() == ISD::TRUNCATE) {
4865 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4866 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4867 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4868 if (NarrowLoad.getNode()) {
4869 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4870 if (NarrowLoad.getNode() != N0.getNode()) {
4871 CombineTo(N0.getNode(), NarrowLoad);
4872 // CombineTo deleted the truncate, if needed, but not what's under it.
4875 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4878 // See if the value being truncated is already sign extended. If so, just
4879 // eliminate the trunc/sext pair.
4880 SDValue Op = N0.getOperand(0);
4881 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4882 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4883 unsigned DestBits = VT.getScalarType().getSizeInBits();
4884 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4886 if (OpBits == DestBits) {
4887 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4888 // bits, it is already ready.
4889 if (NumSignBits > DestBits-MidBits)
4891 } else if (OpBits < DestBits) {
4892 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4893 // bits, just sext from i32.
4894 if (NumSignBits > OpBits-MidBits)
4895 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4897 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4898 // bits, just truncate to i32.
4899 if (NumSignBits > OpBits-MidBits)
4900 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4903 // fold (sext (truncate x)) -> (sextinreg x).
4904 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4905 N0.getValueType())) {
4906 if (OpBits < DestBits)
4907 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4908 else if (OpBits > DestBits)
4909 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4910 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4911 DAG.getValueType(N0.getValueType()));
4915 // fold (sext (load x)) -> (sext (truncate (sextload x)))
4916 // None of the supported targets knows how to perform load and sign extend
4917 // on vectors in one instruction. We only perform this transformation on
4919 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4920 ISD::isUNINDEXEDLoad(N0.getNode()) &&
4921 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4922 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4923 bool DoXform = true;
4924 SmallVector<SDNode*, 4> SetCCs;
4925 if (!N0.hasOneUse())
4926 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4928 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4929 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4931 LN0->getBasePtr(), N0.getValueType(),
4932 LN0->getMemOperand());
4933 CombineTo(N, ExtLoad);
4934 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4935 N0.getValueType(), ExtLoad);
4936 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4937 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4939 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4943 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4944 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4945 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4946 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4947 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4948 EVT MemVT = LN0->getMemoryVT();
4949 if ((!LegalOperations && !LN0->isVolatile()) ||
4950 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4951 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4953 LN0->getBasePtr(), MemVT,
4954 LN0->getMemOperand());
4955 CombineTo(N, ExtLoad);
4956 CombineTo(N0.getNode(),
4957 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4958 N0.getValueType(), ExtLoad),
4959 ExtLoad.getValue(1));
4960 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4964 // fold (sext (and/or/xor (load x), cst)) ->
4965 // (and/or/xor (sextload x), (sext cst))
4966 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4967 N0.getOpcode() == ISD::XOR) &&
4968 isa<LoadSDNode>(N0.getOperand(0)) &&
4969 N0.getOperand(1).getOpcode() == ISD::Constant &&
4970 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4971 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4972 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4973 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
4974 bool DoXform = true;
4975 SmallVector<SDNode*, 4> SetCCs;
4976 if (!N0.hasOneUse())
4977 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4980 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
4981 LN0->getChain(), LN0->getBasePtr(),
4983 LN0->getMemOperand());
4984 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4985 Mask = Mask.sext(VT.getSizeInBits());
4986 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4987 ExtLoad, DAG.getConstant(Mask, VT));
4988 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4989 SDLoc(N0.getOperand(0)),
4990 N0.getOperand(0).getValueType(), ExtLoad);
4992 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4993 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4995 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5000 if (N0.getOpcode() == ISD::SETCC) {
5001 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5002 // Only do this before legalize for now.
5003 if (VT.isVector() && !LegalOperations &&
5004 TLI.getBooleanContents(true) ==
5005 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5006 EVT N0VT = N0.getOperand(0).getValueType();
5007 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5008 // of the same size as the compared operands. Only optimize sext(setcc())
5009 // if this is the case.
5010 EVT SVT = getSetCCResultType(N0VT);
5012 // We know that the # elements of the results is the same as the
5013 // # elements of the compare (and the # elements of the compare result
5014 // for that matter). Check to see that they are the same size. If so,
5015 // we know that the element size of the sext'd result matches the
5016 // element size of the compare operands.
5017 if (VT.getSizeInBits() == SVT.getSizeInBits())
5018 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5020 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5022 // If the desired elements are smaller or larger than the source
5023 // elements we can use a matching integer vector type and then
5024 // truncate/sign extend
5025 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5026 if (SVT == MatchingVectorType) {
5027 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5028 N0.getOperand(0), N0.getOperand(1),
5029 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5030 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5034 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5035 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5037 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5039 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5040 NegOne, DAG.getConstant(0, VT),
5041 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5042 if (SCC.getNode()) return SCC;
5044 if (!VT.isVector()) {
5045 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5046 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5048 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5049 SDValue SetCC = DAG.getSetCC(DL,
5051 N0.getOperand(0), N0.getOperand(1), CC);
5052 EVT SelectVT = getSetCCResultType(VT);
5053 return DAG.getSelect(DL, VT,
5054 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5055 NegOne, DAG.getConstant(0, VT));
5061 // fold (sext x) -> (zext x) if the sign bit is known zero.
5062 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5063 DAG.SignBitIsZero(N0))
5064 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5069 // isTruncateOf - If N is a truncate of some other value, return true, record
5070 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5071 // This function computes KnownZero to avoid a duplicated call to
5072 // ComputeMaskedBits in the caller.
5073 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5076 if (N->getOpcode() == ISD::TRUNCATE) {
5077 Op = N->getOperand(0);
5078 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5082 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5083 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5086 SDValue Op0 = N->getOperand(0);
5087 SDValue Op1 = N->getOperand(1);
5088 assert(Op0.getValueType() == Op1.getValueType());
5090 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5091 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5092 if (COp0 && COp0->isNullValue())
5094 else if (COp1 && COp1->isNullValue())
5099 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5101 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5107 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5108 SDValue N0 = N->getOperand(0);
5109 EVT VT = N->getValueType(0);
5111 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5113 return SDValue(Res, 0);
5115 // fold (zext (zext x)) -> (zext x)
5116 // fold (zext (aext x)) -> (zext x)
5117 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5118 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5121 // fold (zext (truncate x)) -> (zext x) or
5122 // (zext (truncate x)) -> (truncate x)
5123 // This is valid when the truncated bits of x are already zero.
5124 // FIXME: We should extend this to work for vectors too.
5127 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5128 APInt TruncatedBits =
5129 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5130 APInt(Op.getValueSizeInBits(), 0) :
5131 APInt::getBitsSet(Op.getValueSizeInBits(),
5132 N0.getValueSizeInBits(),
5133 std::min(Op.getValueSizeInBits(),
5134 VT.getSizeInBits()));
5135 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5136 if (VT.bitsGT(Op.getValueType()))
5137 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5138 if (VT.bitsLT(Op.getValueType()))
5139 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5145 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5146 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5147 if (N0.getOpcode() == ISD::TRUNCATE) {
5148 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5149 if (NarrowLoad.getNode()) {
5150 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5151 if (NarrowLoad.getNode() != N0.getNode()) {
5152 CombineTo(N0.getNode(), NarrowLoad);
5153 // CombineTo deleted the truncate, if needed, but not what's under it.
5156 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5160 // fold (zext (truncate x)) -> (and x, mask)
5161 if (N0.getOpcode() == ISD::TRUNCATE &&
5162 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5164 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5165 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5166 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5167 if (NarrowLoad.getNode()) {
5168 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5169 if (NarrowLoad.getNode() != N0.getNode()) {
5170 CombineTo(N0.getNode(), NarrowLoad);
5171 // CombineTo deleted the truncate, if needed, but not what's under it.
5174 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5177 SDValue Op = N0.getOperand(0);
5178 if (Op.getValueType().bitsLT(VT)) {
5179 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5180 AddToWorkList(Op.getNode());
5181 } else if (Op.getValueType().bitsGT(VT)) {
5182 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5183 AddToWorkList(Op.getNode());
5185 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5186 N0.getValueType().getScalarType());
5189 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5190 // if either of the casts is not free.
5191 if (N0.getOpcode() == ISD::AND &&
5192 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5193 N0.getOperand(1).getOpcode() == ISD::Constant &&
5194 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5195 N0.getValueType()) ||
5196 !TLI.isZExtFree(N0.getValueType(), VT))) {
5197 SDValue X = N0.getOperand(0).getOperand(0);
5198 if (X.getValueType().bitsLT(VT)) {
5199 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5200 } else if (X.getValueType().bitsGT(VT)) {
5201 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5203 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5204 Mask = Mask.zext(VT.getSizeInBits());
5205 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5206 X, DAG.getConstant(Mask, VT));
5209 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5210 // None of the supported targets knows how to perform load and vector_zext
5211 // on vectors in one instruction. We only perform this transformation on
5213 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5214 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5215 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5216 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5217 bool DoXform = true;
5218 SmallVector<SDNode*, 4> SetCCs;
5219 if (!N0.hasOneUse())
5220 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5222 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5223 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5225 LN0->getBasePtr(), N0.getValueType(),
5226 LN0->getMemOperand());
5227 CombineTo(N, ExtLoad);
5228 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5229 N0.getValueType(), ExtLoad);
5230 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5232 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5234 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5238 // fold (zext (and/or/xor (load x), cst)) ->
5239 // (and/or/xor (zextload x), (zext cst))
5240 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5241 N0.getOpcode() == ISD::XOR) &&
5242 isa<LoadSDNode>(N0.getOperand(0)) &&
5243 N0.getOperand(1).getOpcode() == ISD::Constant &&
5244 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5245 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5246 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5247 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5248 bool DoXform = true;
5249 SmallVector<SDNode*, 4> SetCCs;
5250 if (!N0.hasOneUse())
5251 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5254 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5255 LN0->getChain(), LN0->getBasePtr(),
5257 LN0->getMemOperand());
5258 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5259 Mask = Mask.zext(VT.getSizeInBits());
5260 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5261 ExtLoad, DAG.getConstant(Mask, VT));
5262 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5263 SDLoc(N0.getOperand(0)),
5264 N0.getOperand(0).getValueType(), ExtLoad);
5266 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5267 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5269 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5274 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5275 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5276 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5277 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5278 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5279 EVT MemVT = LN0->getMemoryVT();
5280 if ((!LegalOperations && !LN0->isVolatile()) ||
5281 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5282 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5284 LN0->getBasePtr(), MemVT,
5285 LN0->getMemOperand());
5286 CombineTo(N, ExtLoad);
5287 CombineTo(N0.getNode(),
5288 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5290 ExtLoad.getValue(1));
5291 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5295 if (N0.getOpcode() == ISD::SETCC) {
5296 if (!LegalOperations && VT.isVector() &&
5297 N0.getValueType().getVectorElementType() == MVT::i1) {
5298 EVT N0VT = N0.getOperand(0).getValueType();
5299 if (getSetCCResultType(N0VT) == N0.getValueType())
5302 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5303 // Only do this before legalize for now.
5304 EVT EltVT = VT.getVectorElementType();
5305 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5306 DAG.getConstant(1, EltVT));
5307 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5308 // We know that the # elements of the results is the same as the
5309 // # elements of the compare (and the # elements of the compare result
5310 // for that matter). Check to see that they are the same size. If so,
5311 // we know that the element size of the sext'd result matches the
5312 // element size of the compare operands.
5313 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5314 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5316 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5317 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5320 // If the desired elements are smaller or larger than the source
5321 // elements we can use a matching integer vector type and then
5322 // truncate/sign extend
5323 EVT MatchingElementType =
5324 EVT::getIntegerVT(*DAG.getContext(),
5325 N0VT.getScalarType().getSizeInBits());
5326 EVT MatchingVectorType =
5327 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5328 N0VT.getVectorNumElements());
5330 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5332 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5333 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5334 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5335 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5338 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5340 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5341 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5342 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5343 if (SCC.getNode()) return SCC;
5346 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5347 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5348 isa<ConstantSDNode>(N0.getOperand(1)) &&
5349 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5351 SDValue ShAmt = N0.getOperand(1);
5352 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5353 if (N0.getOpcode() == ISD::SHL) {
5354 SDValue InnerZExt = N0.getOperand(0);
5355 // If the original shl may be shifting out bits, do not perform this
5357 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5358 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5359 if (ShAmtVal > KnownZeroBits)
5365 // Ensure that the shift amount is wide enough for the shifted value.
5366 if (VT.getSizeInBits() >= 256)
5367 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5369 return DAG.getNode(N0.getOpcode(), DL, VT,
5370 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5377 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5378 SDValue N0 = N->getOperand(0);
5379 EVT VT = N->getValueType(0);
5381 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5383 return SDValue(Res, 0);
5385 // fold (aext (aext x)) -> (aext x)
5386 // fold (aext (zext x)) -> (zext x)
5387 // fold (aext (sext x)) -> (sext x)
5388 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5389 N0.getOpcode() == ISD::ZERO_EXTEND ||
5390 N0.getOpcode() == ISD::SIGN_EXTEND)
5391 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5393 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5394 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5395 if (N0.getOpcode() == ISD::TRUNCATE) {
5396 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5397 if (NarrowLoad.getNode()) {
5398 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5399 if (NarrowLoad.getNode() != N0.getNode()) {
5400 CombineTo(N0.getNode(), NarrowLoad);
5401 // CombineTo deleted the truncate, if needed, but not what's under it.
5404 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5408 // fold (aext (truncate x))
5409 if (N0.getOpcode() == ISD::TRUNCATE) {
5410 SDValue TruncOp = N0.getOperand(0);
5411 if (TruncOp.getValueType() == VT)
5412 return TruncOp; // x iff x size == zext size.
5413 if (TruncOp.getValueType().bitsGT(VT))
5414 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5415 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5418 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5419 // if the trunc is not free.
5420 if (N0.getOpcode() == ISD::AND &&
5421 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5422 N0.getOperand(1).getOpcode() == ISD::Constant &&
5423 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5424 N0.getValueType())) {
5425 SDValue X = N0.getOperand(0).getOperand(0);
5426 if (X.getValueType().bitsLT(VT)) {
5427 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5428 } else if (X.getValueType().bitsGT(VT)) {
5429 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5431 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5432 Mask = Mask.zext(VT.getSizeInBits());
5433 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5434 X, DAG.getConstant(Mask, VT));
5437 // fold (aext (load x)) -> (aext (truncate (extload x)))
5438 // None of the supported targets knows how to perform load and any_ext
5439 // on vectors in one instruction. We only perform this transformation on
5441 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5442 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5443 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5444 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5445 bool DoXform = true;
5446 SmallVector<SDNode*, 4> SetCCs;
5447 if (!N0.hasOneUse())
5448 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5450 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5451 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5453 LN0->getBasePtr(), N0.getValueType(),
5454 LN0->getMemOperand());
5455 CombineTo(N, ExtLoad);
5456 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5457 N0.getValueType(), ExtLoad);
5458 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5459 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5461 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5465 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5466 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5467 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5468 if (N0.getOpcode() == ISD::LOAD &&
5469 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5471 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5472 ISD::LoadExtType ExtType = LN0->getExtensionType();
5473 EVT MemVT = LN0->getMemoryVT();
5474 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5475 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5476 VT, LN0->getChain(), LN0->getBasePtr(),
5477 MemVT, LN0->getMemOperand());
5478 CombineTo(N, ExtLoad);
5479 CombineTo(N0.getNode(),
5480 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5481 N0.getValueType(), ExtLoad),
5482 ExtLoad.getValue(1));
5483 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5487 if (N0.getOpcode() == ISD::SETCC) {
5489 // aext(setcc) -> vsetcc
5490 // aext(setcc) -> truncate(vsetcc)
5491 // aext(setcc) -> aext(vsetcc)
5492 // Only do this before legalize for now.
5493 if (VT.isVector() && !LegalOperations) {
5494 EVT N0VT = N0.getOperand(0).getValueType();
5495 // We know that the # elements of the results is the same as the
5496 // # elements of the compare (and the # elements of the compare result
5497 // for that matter). Check to see that they are the same size. If so,
5498 // we know that the element size of the sext'd result matches the
5499 // element size of the compare operands.
5500 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5501 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5503 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5504 // If the desired elements are smaller or larger than the source
5505 // elements we can use a matching integer vector type and then
5506 // truncate/any extend
5508 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5510 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5512 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5513 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5517 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5519 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5520 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5521 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5529 /// GetDemandedBits - See if the specified operand can be simplified with the
5530 /// knowledge that only the bits specified by Mask are used. If so, return the
5531 /// simpler operand, otherwise return a null SDValue.
5532 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5533 switch (V.getOpcode()) {
5535 case ISD::Constant: {
5536 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5537 assert(CV && "Const value should be ConstSDNode.");
5538 const APInt &CVal = CV->getAPIntValue();
5539 APInt NewVal = CVal & Mask;
5541 return DAG.getConstant(NewVal, V.getValueType());
5546 // If the LHS or RHS don't contribute bits to the or, drop them.
5547 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5548 return V.getOperand(1);
5549 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5550 return V.getOperand(0);
5553 // Only look at single-use SRLs.
5554 if (!V.getNode()->hasOneUse())
5556 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5557 // See if we can recursively simplify the LHS.
5558 unsigned Amt = RHSC->getZExtValue();
5560 // Watch out for shift count overflow though.
5561 if (Amt >= Mask.getBitWidth()) break;
5562 APInt NewMask = Mask << Amt;
5563 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5564 if (SimplifyLHS.getNode())
5565 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5566 SimplifyLHS, V.getOperand(1));
5572 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5573 /// bits and then truncated to a narrower type and where N is a multiple
5574 /// of number of bits of the narrower type, transform it to a narrower load
5575 /// from address + N / num of bits of new type. If the result is to be
5576 /// extended, also fold the extension to form a extending load.
5577 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5578 unsigned Opc = N->getOpcode();
5580 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5581 SDValue N0 = N->getOperand(0);
5582 EVT VT = N->getValueType(0);
5585 // This transformation isn't valid for vector loads.
5589 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5591 if (Opc == ISD::SIGN_EXTEND_INREG) {
5592 ExtType = ISD::SEXTLOAD;
5593 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5594 } else if (Opc == ISD::SRL) {
5595 // Another special-case: SRL is basically zero-extending a narrower value.
5596 ExtType = ISD::ZEXTLOAD;
5598 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5599 if (!N01) return SDValue();
5600 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5601 VT.getSizeInBits() - N01->getZExtValue());
5603 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5606 unsigned EVTBits = ExtVT.getSizeInBits();
5608 // Do not generate loads of non-round integer types since these can
5609 // be expensive (and would be wrong if the type is not byte sized).
5610 if (!ExtVT.isRound())
5614 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5615 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5616 ShAmt = N01->getZExtValue();
5617 // Is the shift amount a multiple of size of VT?
5618 if ((ShAmt & (EVTBits-1)) == 0) {
5619 N0 = N0.getOperand(0);
5620 // Is the load width a multiple of size of VT?
5621 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5625 // At this point, we must have a load or else we can't do the transform.
5626 if (!isa<LoadSDNode>(N0)) return SDValue();
5628 // Because a SRL must be assumed to *need* to zero-extend the high bits
5629 // (as opposed to anyext the high bits), we can't combine the zextload
5630 // lowering of SRL and an sextload.
5631 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5634 // If the shift amount is larger than the input type then we're not
5635 // accessing any of the loaded bytes. If the load was a zextload/extload
5636 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5637 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5642 // If the load is shifted left (and the result isn't shifted back right),
5643 // we can fold the truncate through the shift.
5644 unsigned ShLeftAmt = 0;
5645 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5646 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5647 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5648 ShLeftAmt = N01->getZExtValue();
5649 N0 = N0.getOperand(0);
5653 // If we haven't found a load, we can't narrow it. Don't transform one with
5654 // multiple uses, this would require adding a new load.
5655 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5658 // Don't change the width of a volatile load.
5659 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5660 if (LN0->isVolatile())
5663 // Verify that we are actually reducing a load width here.
5664 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5667 // For the transform to be legal, the load must produce only two values
5668 // (the value loaded and the chain). Don't transform a pre-increment
5669 // load, for example, which produces an extra value. Otherwise the
5670 // transformation is not equivalent, and the downstream logic to replace
5671 // uses gets things wrong.
5672 if (LN0->getNumValues() > 2)
5675 // If the load that we're shrinking is an extload and we're not just
5676 // discarding the extension we can't simply shrink the load. Bail.
5677 // TODO: It would be possible to merge the extensions in some cases.
5678 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5679 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5682 EVT PtrType = N0.getOperand(1).getValueType();
5684 if (PtrType == MVT::Untyped || PtrType.isExtended())
5685 // It's not possible to generate a constant of extended or untyped type.
5688 // For big endian targets, we need to adjust the offset to the pointer to
5689 // load the correct bytes.
5690 if (TLI.isBigEndian()) {
5691 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5692 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5693 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5696 uint64_t PtrOff = ShAmt / 8;
5697 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5698 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5699 PtrType, LN0->getBasePtr(),
5700 DAG.getConstant(PtrOff, PtrType));
5701 AddToWorkList(NewPtr.getNode());
5704 if (ExtType == ISD::NON_EXTLOAD)
5705 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5706 LN0->getPointerInfo().getWithOffset(PtrOff),
5707 LN0->isVolatile(), LN0->isNonTemporal(),
5708 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5710 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5711 LN0->getPointerInfo().getWithOffset(PtrOff),
5712 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5713 NewAlign, LN0->getTBAAInfo());
5715 // Replace the old load's chain with the new load's chain.
5716 WorkListRemover DeadNodes(*this);
5717 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5719 // Shift the result left, if we've swallowed a left shift.
5720 SDValue Result = Load;
5721 if (ShLeftAmt != 0) {
5722 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5723 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5725 // If the shift amount is as large as the result size (but, presumably,
5726 // no larger than the source) then the useful bits of the result are
5727 // zero; we can't simply return the shortened shift, because the result
5728 // of that operation is undefined.
5729 if (ShLeftAmt >= VT.getSizeInBits())
5730 Result = DAG.getConstant(0, VT);
5732 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5733 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5736 // Return the new loaded value.
5740 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5741 SDValue N0 = N->getOperand(0);
5742 SDValue N1 = N->getOperand(1);
5743 EVT VT = N->getValueType(0);
5744 EVT EVT = cast<VTSDNode>(N1)->getVT();
5745 unsigned VTBits = VT.getScalarType().getSizeInBits();
5746 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5748 // fold (sext_in_reg c1) -> c1
5749 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5750 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5752 // If the input is already sign extended, just drop the extension.
5753 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5756 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5757 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5758 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5759 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5760 N0.getOperand(0), N1);
5762 // fold (sext_in_reg (sext x)) -> (sext x)
5763 // fold (sext_in_reg (aext x)) -> (sext x)
5764 // if x is small enough.
5765 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5766 SDValue N00 = N0.getOperand(0);
5767 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5768 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5769 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5772 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5773 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5774 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5776 // fold operands of sext_in_reg based on knowledge that the top bits are not
5778 if (SimplifyDemandedBits(SDValue(N, 0)))
5779 return SDValue(N, 0);
5781 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5782 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5783 SDValue NarrowLoad = ReduceLoadWidth(N);
5784 if (NarrowLoad.getNode())
5787 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5788 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5789 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5790 if (N0.getOpcode() == ISD::SRL) {
5791 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5792 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5793 // We can turn this into an SRA iff the input to the SRL is already sign
5795 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5796 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5797 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5798 N0.getOperand(0), N0.getOperand(1));
5802 // fold (sext_inreg (extload x)) -> (sextload x)
5803 if (ISD::isEXTLoad(N0.getNode()) &&
5804 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5805 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5806 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5807 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5808 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5809 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5811 LN0->getBasePtr(), EVT,
5812 LN0->getMemOperand());
5813 CombineTo(N, ExtLoad);
5814 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5815 AddToWorkList(ExtLoad.getNode());
5816 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5818 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5819 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5821 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5822 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5823 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5824 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5825 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5827 LN0->getBasePtr(), EVT,
5828 LN0->getMemOperand());
5829 CombineTo(N, ExtLoad);
5830 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5831 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5834 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5835 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5836 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5837 N0.getOperand(1), false);
5838 if (BSwap.getNode())
5839 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5843 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5844 // into a build_vector.
5845 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5846 SmallVector<SDValue, 8> Elts;
5847 unsigned NumElts = N0->getNumOperands();
5848 unsigned ShAmt = VTBits - EVTBits;
5850 for (unsigned i = 0; i != NumElts; ++i) {
5851 SDValue Op = N0->getOperand(i);
5852 if (Op->getOpcode() == ISD::UNDEF) {
5857 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5858 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5859 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5860 Op.getValueType()));
5863 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
5869 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5870 SDValue N0 = N->getOperand(0);
5871 EVT VT = N->getValueType(0);
5872 bool isLE = TLI.isLittleEndian();
5875 if (N0.getValueType() == N->getValueType(0))
5877 // fold (truncate c1) -> c1
5878 if (isa<ConstantSDNode>(N0))
5879 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5880 // fold (truncate (truncate x)) -> (truncate x)
5881 if (N0.getOpcode() == ISD::TRUNCATE)
5882 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5883 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5884 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5885 N0.getOpcode() == ISD::SIGN_EXTEND ||
5886 N0.getOpcode() == ISD::ANY_EXTEND) {
5887 if (N0.getOperand(0).getValueType().bitsLT(VT))
5888 // if the source is smaller than the dest, we still need an extend
5889 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5891 if (N0.getOperand(0).getValueType().bitsGT(VT))
5892 // if the source is larger than the dest, than we just need the truncate
5893 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5894 // if the source and dest are the same type, we can drop both the extend
5895 // and the truncate.
5896 return N0.getOperand(0);
5899 // Fold extract-and-trunc into a narrow extract. For example:
5900 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5901 // i32 y = TRUNCATE(i64 x)
5903 // v16i8 b = BITCAST (v2i64 val)
5904 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5906 // Note: We only run this optimization after type legalization (which often
5907 // creates this pattern) and before operation legalization after which
5908 // we need to be more careful about the vector instructions that we generate.
5909 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5910 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
5912 EVT VecTy = N0.getOperand(0).getValueType();
5913 EVT ExTy = N0.getValueType();
5914 EVT TrTy = N->getValueType(0);
5916 unsigned NumElem = VecTy.getVectorNumElements();
5917 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5919 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5920 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5922 SDValue EltNo = N0->getOperand(1);
5923 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5924 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5925 EVT IndexTy = TLI.getVectorIdxTy();
5926 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5928 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5929 NVT, N0.getOperand(0));
5931 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5933 DAG.getConstant(Index, IndexTy));
5937 // Fold a series of buildvector, bitcast, and truncate if possible.
5939 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5940 // (2xi32 (buildvector x, y)).
5941 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5942 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5943 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5944 N0.getOperand(0).hasOneUse()) {
5946 SDValue BuildVect = N0.getOperand(0);
5947 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5948 EVT TruncVecEltTy = VT.getVectorElementType();
5950 // Check that the element types match.
5951 if (BuildVectEltTy == TruncVecEltTy) {
5952 // Now we only need to compute the offset of the truncated elements.
5953 unsigned BuildVecNumElts = BuildVect.getNumOperands();
5954 unsigned TruncVecNumElts = VT.getVectorNumElements();
5955 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5957 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5958 "Invalid number of elements");
5960 SmallVector<SDValue, 8> Opnds;
5961 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5962 Opnds.push_back(BuildVect.getOperand(i));
5964 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
5968 // See if we can simplify the input to this truncate through knowledge that
5969 // only the low bits are being used.
5970 // For example "trunc (or (shl x, 8), y)" // -> trunc y
5971 // Currently we only perform this optimization on scalars because vectors
5972 // may have different active low bits.
5973 if (!VT.isVector()) {
5975 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5976 VT.getSizeInBits()));
5977 if (Shorter.getNode())
5978 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
5980 // fold (truncate (load x)) -> (smaller load x)
5981 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5982 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5983 SDValue Reduced = ReduceLoadWidth(N);
5984 if (Reduced.getNode())
5986 // Handle the case where the load remains an extending load even
5987 // after truncation.
5988 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
5989 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5990 if (!LN0->isVolatile() &&
5991 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
5992 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
5993 VT, LN0->getChain(), LN0->getBasePtr(),
5995 LN0->getMemOperand());
5996 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6001 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6002 // where ... are all 'undef'.
6003 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6004 SmallVector<EVT, 8> VTs;
6007 unsigned NumDefs = 0;
6009 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6010 SDValue X = N0.getOperand(i);
6011 if (X.getOpcode() != ISD::UNDEF) {
6016 // Stop if more than one members are non-undef.
6019 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6020 VT.getVectorElementType(),
6021 X.getValueType().getVectorNumElements()));
6025 return DAG.getUNDEF(VT);
6028 assert(V.getNode() && "The single defined operand is empty!");
6029 SmallVector<SDValue, 8> Opnds;
6030 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6032 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6035 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6036 AddToWorkList(NV.getNode());
6037 Opnds.push_back(NV);
6039 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6043 // Simplify the operands using demanded-bits information.
6044 if (!VT.isVector() &&
6045 SimplifyDemandedBits(SDValue(N, 0)))
6046 return SDValue(N, 0);
6051 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6052 SDValue Elt = N->getOperand(i);
6053 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6054 return Elt.getNode();
6055 return Elt.getOperand(Elt.getResNo()).getNode();
6058 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6059 /// if load locations are consecutive.
6060 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6061 assert(N->getOpcode() == ISD::BUILD_PAIR);
6063 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6064 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6065 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6066 LD1->getAddressSpace() != LD2->getAddressSpace())
6068 EVT LD1VT = LD1->getValueType(0);
6070 if (ISD::isNON_EXTLoad(LD2) &&
6072 // If both are volatile this would reduce the number of volatile loads.
6073 // If one is volatile it might be ok, but play conservative and bail out.
6074 !LD1->isVolatile() &&
6075 !LD2->isVolatile() &&
6076 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6077 unsigned Align = LD1->getAlignment();
6078 unsigned NewAlign = TLI.getDataLayout()->
6079 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6081 if (NewAlign <= Align &&
6082 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6083 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6084 LD1->getBasePtr(), LD1->getPointerInfo(),
6085 false, false, false, Align);
6091 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6092 SDValue N0 = N->getOperand(0);
6093 EVT VT = N->getValueType(0);
6095 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6096 // Only do this before legalize, since afterward the target may be depending
6097 // on the bitconvert.
6098 // First check to see if this is all constant.
6100 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6102 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6104 EVT DestEltVT = N->getValueType(0).getVectorElementType();
6105 assert(!DestEltVT.isVector() &&
6106 "Element type of vector ValueType must not be vector!");
6108 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6111 // If the input is a constant, let getNode fold it.
6112 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6113 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6114 if (Res.getNode() != N) {
6115 if (!LegalOperations ||
6116 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6119 // Folding it resulted in an illegal node, and it's too late to
6120 // do that. Clean up the old node and forego the transformation.
6121 // Ideally this won't happen very often, because instcombine
6122 // and the earlier dagcombine runs (where illegal nodes are
6123 // permitted) should have folded most of them already.
6124 DAG.DeleteNode(Res.getNode());
6128 // (conv (conv x, t1), t2) -> (conv x, t2)
6129 if (N0.getOpcode() == ISD::BITCAST)
6130 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6133 // fold (conv (load x)) -> (load (conv*)x)
6134 // If the resultant load doesn't need a higher alignment than the original!
6135 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6136 // Do not change the width of a volatile load.
6137 !cast<LoadSDNode>(N0)->isVolatile() &&
6138 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6139 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6140 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6141 unsigned Align = TLI.getDataLayout()->
6142 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6143 unsigned OrigAlign = LN0->getAlignment();
6145 if (Align <= OrigAlign) {
6146 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6147 LN0->getBasePtr(), LN0->getPointerInfo(),
6148 LN0->isVolatile(), LN0->isNonTemporal(),
6149 LN0->isInvariant(), OrigAlign,
6150 LN0->getTBAAInfo());
6152 CombineTo(N0.getNode(),
6153 DAG.getNode(ISD::BITCAST, SDLoc(N0),
6154 N0.getValueType(), Load),
6160 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6161 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6162 // This often reduces constant pool loads.
6163 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6164 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6165 N0.getNode()->hasOneUse() && VT.isInteger() &&
6166 !VT.isVector() && !N0.getValueType().isVector()) {
6167 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6169 AddToWorkList(NewConv.getNode());
6171 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6172 if (N0.getOpcode() == ISD::FNEG)
6173 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6174 NewConv, DAG.getConstant(SignBit, VT));
6175 assert(N0.getOpcode() == ISD::FABS);
6176 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6177 NewConv, DAG.getConstant(~SignBit, VT));
6180 // fold (bitconvert (fcopysign cst, x)) ->
6181 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6182 // Note that we don't handle (copysign x, cst) because this can always be
6183 // folded to an fneg or fabs.
6184 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6185 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6186 VT.isInteger() && !VT.isVector()) {
6187 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6188 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6189 if (isTypeLegal(IntXVT)) {
6190 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6191 IntXVT, N0.getOperand(1));
6192 AddToWorkList(X.getNode());
6194 // If X has a different width than the result/lhs, sext it or truncate it.
6195 unsigned VTWidth = VT.getSizeInBits();
6196 if (OrigXWidth < VTWidth) {
6197 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6198 AddToWorkList(X.getNode());
6199 } else if (OrigXWidth > VTWidth) {
6200 // To get the sign bit in the right place, we have to shift it right
6201 // before truncating.
6202 X = DAG.getNode(ISD::SRL, SDLoc(X),
6203 X.getValueType(), X,
6204 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6205 AddToWorkList(X.getNode());
6206 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6207 AddToWorkList(X.getNode());
6210 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6211 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6212 X, DAG.getConstant(SignBit, VT));
6213 AddToWorkList(X.getNode());
6215 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6216 VT, N0.getOperand(0));
6217 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6218 Cst, DAG.getConstant(~SignBit, VT));
6219 AddToWorkList(Cst.getNode());
6221 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6225 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6226 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6227 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6228 if (CombineLD.getNode())
6235 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6236 EVT VT = N->getValueType(0);
6237 return CombineConsecutiveLoads(N, VT);
6240 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6241 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
6242 /// destination element value type.
6243 SDValue DAGCombiner::
6244 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6245 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6247 // If this is already the right type, we're done.
6248 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6250 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6251 unsigned DstBitSize = DstEltVT.getSizeInBits();
6253 // If this is a conversion of N elements of one type to N elements of another
6254 // type, convert each element. This handles FP<->INT cases.
6255 if (SrcBitSize == DstBitSize) {
6256 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6257 BV->getValueType(0).getVectorNumElements());
6259 // Due to the FP element handling below calling this routine recursively,
6260 // we can end up with a scalar-to-vector node here.
6261 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6262 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6263 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6264 DstEltVT, BV->getOperand(0)));
6266 SmallVector<SDValue, 8> Ops;
6267 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6268 SDValue Op = BV->getOperand(i);
6269 // If the vector element type is not legal, the BUILD_VECTOR operands
6270 // are promoted and implicitly truncated. Make that explicit here.
6271 if (Op.getValueType() != SrcEltVT)
6272 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6273 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6275 AddToWorkList(Ops.back().getNode());
6277 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6280 // Otherwise, we're growing or shrinking the elements. To avoid having to
6281 // handle annoying details of growing/shrinking FP values, we convert them to
6283 if (SrcEltVT.isFloatingPoint()) {
6284 // Convert the input float vector to a int vector where the elements are the
6286 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6287 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6288 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6292 // Now we know the input is an integer vector. If the output is a FP type,
6293 // convert to integer first, then to FP of the right size.
6294 if (DstEltVT.isFloatingPoint()) {
6295 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6296 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6297 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6299 // Next, convert to FP elements of the same size.
6300 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6303 // Okay, we know the src/dst types are both integers of differing types.
6304 // Handling growing first.
6305 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6306 if (SrcBitSize < DstBitSize) {
6307 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6309 SmallVector<SDValue, 8> Ops;
6310 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6311 i += NumInputsPerOutput) {
6312 bool isLE = TLI.isLittleEndian();
6313 APInt NewBits = APInt(DstBitSize, 0);
6314 bool EltIsUndef = true;
6315 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6316 // Shift the previously computed bits over.
6317 NewBits <<= SrcBitSize;
6318 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6319 if (Op.getOpcode() == ISD::UNDEF) continue;
6322 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6323 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6327 Ops.push_back(DAG.getUNDEF(DstEltVT));
6329 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6332 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6333 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6336 // Finally, this must be the case where we are shrinking elements: each input
6337 // turns into multiple outputs.
6338 bool isS2V = ISD::isScalarToVector(BV);
6339 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6340 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6341 NumOutputsPerInput*BV->getNumOperands());
6342 SmallVector<SDValue, 8> Ops;
6344 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6345 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6346 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6347 Ops.push_back(DAG.getUNDEF(DstEltVT));
6351 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6352 getAPIntValue().zextOrTrunc(SrcBitSize);
6354 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6355 APInt ThisVal = OpVal.trunc(DstBitSize);
6356 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6357 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6358 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6359 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6361 OpVal = OpVal.lshr(DstBitSize);
6364 // For big endian targets, swap the order of the pieces of each element.
6365 if (TLI.isBigEndian())
6366 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6369 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6372 SDValue DAGCombiner::visitFADD(SDNode *N) {
6373 SDValue N0 = N->getOperand(0);
6374 SDValue N1 = N->getOperand(1);
6375 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6376 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6377 EVT VT = N->getValueType(0);
6380 if (VT.isVector()) {
6381 SDValue FoldedVOp = SimplifyVBinOp(N);
6382 if (FoldedVOp.getNode()) return FoldedVOp;
6385 // fold (fadd c1, c2) -> c1 + c2
6387 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6388 // canonicalize constant to RHS
6389 if (N0CFP && !N1CFP)
6390 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6391 // fold (fadd A, 0) -> A
6392 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6393 N1CFP->getValueAPF().isZero())
6395 // fold (fadd A, (fneg B)) -> (fsub A, B)
6396 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6397 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6398 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6399 GetNegatedExpression(N1, DAG, LegalOperations));
6400 // fold (fadd (fneg A), B) -> (fsub B, A)
6401 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6402 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6403 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6404 GetNegatedExpression(N0, DAG, LegalOperations));
6406 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6407 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6408 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6409 isa<ConstantFPSDNode>(N0.getOperand(1)))
6410 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6411 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6412 N0.getOperand(1), N1));
6414 // No FP constant should be created after legalization as Instruction
6415 // Selection pass has hard time in dealing with FP constant.
6417 // We don't need test this condition for transformation like following, as
6418 // the DAG being transformed implies it is legal to take FP constant as
6421 // (fadd (fmul c, x), x) -> (fmul c+1, x)
6423 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6425 // If allow, fold (fadd (fneg x), x) -> 0.0
6426 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6427 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6428 return DAG.getConstantFP(0.0, VT);
6430 // If allow, fold (fadd x, (fneg x)) -> 0.0
6431 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6432 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6433 return DAG.getConstantFP(0.0, VT);
6435 // In unsafe math mode, we can fold chains of FADD's of the same value
6436 // into multiplications. This transform is not safe in general because
6437 // we are reducing the number of rounding steps.
6438 if (DAG.getTarget().Options.UnsafeFPMath &&
6439 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6441 if (N0.getOpcode() == ISD::FMUL) {
6442 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6443 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6445 // (fadd (fmul c, x), x) -> (fmul x, c+1)
6446 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6447 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6449 DAG.getConstantFP(1.0, VT));
6450 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6454 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6455 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6456 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6458 DAG.getConstantFP(1.0, VT));
6459 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6463 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6464 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6465 N1.getOperand(0) == N1.getOperand(1) &&
6466 N0.getOperand(1) == N1.getOperand(0)) {
6467 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6469 DAG.getConstantFP(2.0, VT));
6470 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6471 N0.getOperand(1), NewCFP);
6474 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6475 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6476 N1.getOperand(0) == N1.getOperand(1) &&
6477 N0.getOperand(0) == N1.getOperand(0)) {
6478 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6480 DAG.getConstantFP(2.0, VT));
6481 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6482 N0.getOperand(0), NewCFP);
6486 if (N1.getOpcode() == ISD::FMUL) {
6487 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6488 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6490 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6491 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6492 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6494 DAG.getConstantFP(1.0, VT));
6495 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6499 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6500 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6501 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6503 DAG.getConstantFP(1.0, VT));
6504 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6509 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6510 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6511 N0.getOperand(0) == N0.getOperand(1) &&
6512 N1.getOperand(1) == N0.getOperand(0)) {
6513 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6515 DAG.getConstantFP(2.0, VT));
6516 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6517 N1.getOperand(1), NewCFP);
6520 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6521 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6522 N0.getOperand(0) == N0.getOperand(1) &&
6523 N1.getOperand(0) == N0.getOperand(0)) {
6524 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6526 DAG.getConstantFP(2.0, VT));
6527 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6528 N1.getOperand(0), NewCFP);
6532 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6533 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6534 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6535 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6536 (N0.getOperand(0) == N1))
6537 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6538 N1, DAG.getConstantFP(3.0, VT));
6541 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6542 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6543 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6544 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6545 N1.getOperand(0) == N0)
6546 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6547 N0, DAG.getConstantFP(3.0, VT));
6550 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6551 if (AllowNewFpConst &&
6552 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6553 N0.getOperand(0) == N0.getOperand(1) &&
6554 N1.getOperand(0) == N1.getOperand(1) &&
6555 N0.getOperand(0) == N1.getOperand(0))
6556 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6558 DAG.getConstantFP(4.0, VT));
6561 // FADD -> FMA combines:
6562 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6563 DAG.getTarget().Options.UnsafeFPMath) &&
6564 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6565 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6567 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6568 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6569 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6570 N0.getOperand(0), N0.getOperand(1), N1);
6572 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6573 // Note: Commutes FADD operands.
6574 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6575 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6576 N1.getOperand(0), N1.getOperand(1), N0);
6582 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6583 SDValue N0 = N->getOperand(0);
6584 SDValue N1 = N->getOperand(1);
6585 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6586 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6587 EVT VT = N->getValueType(0);
6591 if (VT.isVector()) {
6592 SDValue FoldedVOp = SimplifyVBinOp(N);
6593 if (FoldedVOp.getNode()) return FoldedVOp;
6596 // fold (fsub c1, c2) -> c1-c2
6598 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6599 // fold (fsub A, 0) -> A
6600 if (DAG.getTarget().Options.UnsafeFPMath &&
6601 N1CFP && N1CFP->getValueAPF().isZero())
6603 // fold (fsub 0, B) -> -B
6604 if (DAG.getTarget().Options.UnsafeFPMath &&
6605 N0CFP && N0CFP->getValueAPF().isZero()) {
6606 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6607 return GetNegatedExpression(N1, DAG, LegalOperations);
6608 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6609 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6611 // fold (fsub A, (fneg B)) -> (fadd A, B)
6612 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6613 return DAG.getNode(ISD::FADD, dl, VT, N0,
6614 GetNegatedExpression(N1, DAG, LegalOperations));
6616 // If 'unsafe math' is enabled, fold
6617 // (fsub x, x) -> 0.0 &
6618 // (fsub x, (fadd x, y)) -> (fneg y) &
6619 // (fsub x, (fadd y, x)) -> (fneg y)
6620 if (DAG.getTarget().Options.UnsafeFPMath) {
6622 return DAG.getConstantFP(0.0f, VT);
6624 if (N1.getOpcode() == ISD::FADD) {
6625 SDValue N10 = N1->getOperand(0);
6626 SDValue N11 = N1->getOperand(1);
6628 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6629 &DAG.getTarget().Options))
6630 return GetNegatedExpression(N11, DAG, LegalOperations);
6632 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6633 &DAG.getTarget().Options))
6634 return GetNegatedExpression(N10, DAG, LegalOperations);
6638 // FSUB -> FMA combines:
6639 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6640 DAG.getTarget().Options.UnsafeFPMath) &&
6641 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6642 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6644 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6645 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6646 return DAG.getNode(ISD::FMA, dl, VT,
6647 N0.getOperand(0), N0.getOperand(1),
6648 DAG.getNode(ISD::FNEG, dl, VT, N1));
6650 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6651 // Note: Commutes FSUB operands.
6652 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6653 return DAG.getNode(ISD::FMA, dl, VT,
6654 DAG.getNode(ISD::FNEG, dl, VT,
6656 N1.getOperand(1), N0);
6658 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6659 if (N0.getOpcode() == ISD::FNEG &&
6660 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6661 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6662 SDValue N00 = N0.getOperand(0).getOperand(0);
6663 SDValue N01 = N0.getOperand(0).getOperand(1);
6664 return DAG.getNode(ISD::FMA, dl, VT,
6665 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6666 DAG.getNode(ISD::FNEG, dl, VT, N1));
6673 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6674 SDValue N0 = N->getOperand(0);
6675 SDValue N1 = N->getOperand(1);
6676 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6677 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6678 EVT VT = N->getValueType(0);
6679 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6682 if (VT.isVector()) {
6683 SDValue FoldedVOp = SimplifyVBinOp(N);
6684 if (FoldedVOp.getNode()) return FoldedVOp;
6687 // fold (fmul c1, c2) -> c1*c2
6689 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6690 // canonicalize constant to RHS
6691 if (N0CFP && !N1CFP)
6692 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6693 // fold (fmul A, 0) -> 0
6694 if (DAG.getTarget().Options.UnsafeFPMath &&
6695 N1CFP && N1CFP->getValueAPF().isZero())
6697 // fold (fmul A, 0) -> 0, vector edition.
6698 if (DAG.getTarget().Options.UnsafeFPMath &&
6699 ISD::isBuildVectorAllZeros(N1.getNode()))
6701 // fold (fmul A, 1.0) -> A
6702 if (N1CFP && N1CFP->isExactlyValue(1.0))
6704 // fold (fmul X, 2.0) -> (fadd X, X)
6705 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6706 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6707 // fold (fmul X, -1.0) -> (fneg X)
6708 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6709 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6710 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6712 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6713 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6714 &DAG.getTarget().Options)) {
6715 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6716 &DAG.getTarget().Options)) {
6717 // Both can be negated for free, check to see if at least one is cheaper
6719 if (LHSNeg == 2 || RHSNeg == 2)
6720 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6721 GetNegatedExpression(N0, DAG, LegalOperations),
6722 GetNegatedExpression(N1, DAG, LegalOperations));
6726 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6727 if (DAG.getTarget().Options.UnsafeFPMath &&
6728 N1CFP && N0.getOpcode() == ISD::FMUL &&
6729 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6730 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6731 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6732 N0.getOperand(1), N1));
6737 SDValue DAGCombiner::visitFMA(SDNode *N) {
6738 SDValue N0 = N->getOperand(0);
6739 SDValue N1 = N->getOperand(1);
6740 SDValue N2 = N->getOperand(2);
6741 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6742 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6743 EVT VT = N->getValueType(0);
6746 if (DAG.getTarget().Options.UnsafeFPMath) {
6747 if (N0CFP && N0CFP->isZero())
6749 if (N1CFP && N1CFP->isZero())
6752 if (N0CFP && N0CFP->isExactlyValue(1.0))
6753 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6754 if (N1CFP && N1CFP->isExactlyValue(1.0))
6755 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6757 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6758 if (N0CFP && !N1CFP)
6759 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6761 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6762 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6763 N2.getOpcode() == ISD::FMUL &&
6764 N0 == N2.getOperand(0) &&
6765 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6766 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6767 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6771 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6772 if (DAG.getTarget().Options.UnsafeFPMath &&
6773 N0.getOpcode() == ISD::FMUL && N1CFP &&
6774 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6775 return DAG.getNode(ISD::FMA, dl, VT,
6777 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6781 // (fma x, 1, y) -> (fadd x, y)
6782 // (fma x, -1, y) -> (fadd (fneg x), y)
6784 if (N1CFP->isExactlyValue(1.0))
6785 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6787 if (N1CFP->isExactlyValue(-1.0) &&
6788 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6789 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6790 AddToWorkList(RHSNeg.getNode());
6791 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6795 // (fma x, c, x) -> (fmul x, (c+1))
6796 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6797 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6798 DAG.getNode(ISD::FADD, dl, VT,
6799 N1, DAG.getConstantFP(1.0, VT)));
6801 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6802 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6803 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6804 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6805 DAG.getNode(ISD::FADD, dl, VT,
6806 N1, DAG.getConstantFP(-1.0, VT)));
6812 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6813 SDValue N0 = N->getOperand(0);
6814 SDValue N1 = N->getOperand(1);
6815 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6816 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6817 EVT VT = N->getValueType(0);
6818 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6821 if (VT.isVector()) {
6822 SDValue FoldedVOp = SimplifyVBinOp(N);
6823 if (FoldedVOp.getNode()) return FoldedVOp;
6826 // fold (fdiv c1, c2) -> c1/c2
6828 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6830 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6831 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6832 // Compute the reciprocal 1.0 / c2.
6833 APFloat N1APF = N1CFP->getValueAPF();
6834 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6835 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6836 // Only do the transform if the reciprocal is a legal fp immediate that
6837 // isn't too nasty (eg NaN, denormal, ...).
6838 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6839 (!LegalOperations ||
6840 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6841 // backend)... we should handle this gracefully after Legalize.
6842 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6843 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6844 TLI.isFPImmLegal(Recip, VT)))
6845 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6846 DAG.getConstantFP(Recip, VT));
6849 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6850 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6851 &DAG.getTarget().Options)) {
6852 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6853 &DAG.getTarget().Options)) {
6854 // Both can be negated for free, check to see if at least one is cheaper
6856 if (LHSNeg == 2 || RHSNeg == 2)
6857 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6858 GetNegatedExpression(N0, DAG, LegalOperations),
6859 GetNegatedExpression(N1, DAG, LegalOperations));
6866 SDValue DAGCombiner::visitFREM(SDNode *N) {
6867 SDValue N0 = N->getOperand(0);
6868 SDValue N1 = N->getOperand(1);
6869 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6870 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6871 EVT VT = N->getValueType(0);
6873 // fold (frem c1, c2) -> fmod(c1,c2)
6875 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6880 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6881 SDValue N0 = N->getOperand(0);
6882 SDValue N1 = N->getOperand(1);
6883 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6884 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6885 EVT VT = N->getValueType(0);
6887 if (N0CFP && N1CFP) // Constant fold
6888 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6891 const APFloat& V = N1CFP->getValueAPF();
6892 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6893 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6894 if (!V.isNegative()) {
6895 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6896 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6898 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6899 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6900 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6904 // copysign(fabs(x), y) -> copysign(x, y)
6905 // copysign(fneg(x), y) -> copysign(x, y)
6906 // copysign(copysign(x,z), y) -> copysign(x, y)
6907 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6908 N0.getOpcode() == ISD::FCOPYSIGN)
6909 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6910 N0.getOperand(0), N1);
6912 // copysign(x, abs(y)) -> abs(x)
6913 if (N1.getOpcode() == ISD::FABS)
6914 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6916 // copysign(x, copysign(y,z)) -> copysign(x, z)
6917 if (N1.getOpcode() == ISD::FCOPYSIGN)
6918 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6919 N0, N1.getOperand(1));
6921 // copysign(x, fp_extend(y)) -> copysign(x, y)
6922 // copysign(x, fp_round(y)) -> copysign(x, y)
6923 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6924 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6925 N0, N1.getOperand(0));
6930 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6931 SDValue N0 = N->getOperand(0);
6932 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6933 EVT VT = N->getValueType(0);
6934 EVT OpVT = N0.getValueType();
6936 // fold (sint_to_fp c1) -> c1fp
6938 // ...but only if the target supports immediate floating-point values
6939 (!LegalOperations ||
6940 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6941 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6943 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6944 // but UINT_TO_FP is legal on this target, try to convert.
6945 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6946 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6947 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6948 if (DAG.SignBitIsZero(N0))
6949 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6952 // The next optimizations are desirable only if SELECT_CC can be lowered.
6953 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6954 // having to say they don't support SELECT_CC on every type the DAG knows
6955 // about, since there is no way to mark an opcode illegal at all value types
6956 // (See also visitSELECT)
6957 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6958 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6959 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6961 (!LegalOperations ||
6962 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6964 { N0.getOperand(0), N0.getOperand(1),
6965 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6967 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
6970 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6971 // (select_cc x, y, 1.0, 0.0,, cc)
6972 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6973 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6974 (!LegalOperations ||
6975 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6977 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6978 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6979 N0.getOperand(0).getOperand(2) };
6980 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
6987 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6988 SDValue N0 = N->getOperand(0);
6989 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6990 EVT VT = N->getValueType(0);
6991 EVT OpVT = N0.getValueType();
6993 // fold (uint_to_fp c1) -> c1fp
6995 // ...but only if the target supports immediate floating-point values
6996 (!LegalOperations ||
6997 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6998 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7000 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7001 // but SINT_TO_FP is legal on this target, try to convert.
7002 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7003 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7004 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7005 if (DAG.SignBitIsZero(N0))
7006 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7009 // The next optimizations are desirable only if SELECT_CC can be lowered.
7010 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
7011 // having to say they don't support SELECT_CC on every type the DAG knows
7012 // about, since there is no way to mark an opcode illegal at all value types
7013 // (See also visitSELECT)
7014 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
7015 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7017 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7018 (!LegalOperations ||
7019 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7021 { N0.getOperand(0), N0.getOperand(1),
7022 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7024 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7031 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7032 SDValue N0 = N->getOperand(0);
7033 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7034 EVT VT = N->getValueType(0);
7036 // fold (fp_to_sint c1fp) -> c1
7038 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7043 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7044 SDValue N0 = N->getOperand(0);
7045 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7046 EVT VT = N->getValueType(0);
7048 // fold (fp_to_uint c1fp) -> c1
7050 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7055 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7056 SDValue N0 = N->getOperand(0);
7057 SDValue N1 = N->getOperand(1);
7058 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7059 EVT VT = N->getValueType(0);
7061 // fold (fp_round c1fp) -> c1fp
7063 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7065 // fold (fp_round (fp_extend x)) -> x
7066 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7067 return N0.getOperand(0);
7069 // fold (fp_round (fp_round x)) -> (fp_round x)
7070 if (N0.getOpcode() == ISD::FP_ROUND) {
7071 // This is a value preserving truncation if both round's are.
7072 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7073 N0.getNode()->getConstantOperandVal(1) == 1;
7074 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7075 DAG.getIntPtrConstant(IsTrunc));
7078 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7079 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7080 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7081 N0.getOperand(0), N1);
7082 AddToWorkList(Tmp.getNode());
7083 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7084 Tmp, N0.getOperand(1));
7090 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7091 SDValue N0 = N->getOperand(0);
7092 EVT VT = N->getValueType(0);
7093 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7094 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7096 // fold (fp_round_inreg c1fp) -> c1fp
7097 if (N0CFP && isTypeLegal(EVT)) {
7098 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7099 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7105 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7106 SDValue N0 = N->getOperand(0);
7107 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7108 EVT VT = N->getValueType(0);
7110 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7111 if (N->hasOneUse() &&
7112 N->use_begin()->getOpcode() == ISD::FP_ROUND)
7115 // fold (fp_extend c1fp) -> c1fp
7117 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7119 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7121 if (N0.getOpcode() == ISD::FP_ROUND
7122 && N0.getNode()->getConstantOperandVal(1) == 1) {
7123 SDValue In = N0.getOperand(0);
7124 if (In.getValueType() == VT) return In;
7125 if (VT.bitsLT(In.getValueType()))
7126 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7127 In, N0.getOperand(1));
7128 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7131 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7132 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7133 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7134 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
7135 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7136 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7138 LN0->getBasePtr(), N0.getValueType(),
7139 LN0->getMemOperand());
7140 CombineTo(N, ExtLoad);
7141 CombineTo(N0.getNode(),
7142 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7143 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7144 ExtLoad.getValue(1));
7145 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7151 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7152 SDValue N0 = N->getOperand(0);
7153 EVT VT = N->getValueType(0);
7155 if (VT.isVector()) {
7156 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7157 if (FoldedVOp.getNode()) return FoldedVOp;
7160 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7161 &DAG.getTarget().Options))
7162 return GetNegatedExpression(N0, DAG, LegalOperations);
7164 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7165 // constant pool values.
7166 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7168 N0.getNode()->hasOneUse() &&
7169 N0.getOperand(0).getValueType().isInteger()) {
7170 SDValue Int = N0.getOperand(0);
7171 EVT IntVT = Int.getValueType();
7172 if (IntVT.isInteger() && !IntVT.isVector()) {
7173 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7174 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7175 AddToWorkList(Int.getNode());
7176 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7181 // (fneg (fmul c, x)) -> (fmul -c, x)
7182 if (N0.getOpcode() == ISD::FMUL) {
7183 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7185 APFloat CVal = CFP1->getValueAPF();
7187 if (Level >= AfterLegalizeDAG &&
7188 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7189 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7191 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7192 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7199 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7200 SDValue N0 = N->getOperand(0);
7201 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7202 EVT VT = N->getValueType(0);
7204 // fold (fceil c1) -> fceil(c1)
7206 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7211 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7212 SDValue N0 = N->getOperand(0);
7213 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7214 EVT VT = N->getValueType(0);
7216 // fold (ftrunc c1) -> ftrunc(c1)
7218 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7223 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7224 SDValue N0 = N->getOperand(0);
7225 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7226 EVT VT = N->getValueType(0);
7228 // fold (ffloor c1) -> ffloor(c1)
7230 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7235 SDValue DAGCombiner::visitFABS(SDNode *N) {
7236 SDValue N0 = N->getOperand(0);
7237 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7238 EVT VT = N->getValueType(0);
7240 if (VT.isVector()) {
7241 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7242 if (FoldedVOp.getNode()) return FoldedVOp;
7245 // fold (fabs c1) -> fabs(c1)
7247 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7248 // fold (fabs (fabs x)) -> (fabs x)
7249 if (N0.getOpcode() == ISD::FABS)
7250 return N->getOperand(0);
7251 // fold (fabs (fneg x)) -> (fabs x)
7252 // fold (fabs (fcopysign x, y)) -> (fabs x)
7253 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7254 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7256 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7257 // constant pool values.
7258 if (!TLI.isFAbsFree(VT) &&
7259 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7260 N0.getOperand(0).getValueType().isInteger() &&
7261 !N0.getOperand(0).getValueType().isVector()) {
7262 SDValue Int = N0.getOperand(0);
7263 EVT IntVT = Int.getValueType();
7264 if (IntVT.isInteger() && !IntVT.isVector()) {
7265 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7266 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7267 AddToWorkList(Int.getNode());
7268 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7269 N->getValueType(0), Int);
7276 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7277 SDValue Chain = N->getOperand(0);
7278 SDValue N1 = N->getOperand(1);
7279 SDValue N2 = N->getOperand(2);
7281 // If N is a constant we could fold this into a fallthrough or unconditional
7282 // branch. However that doesn't happen very often in normal code, because
7283 // Instcombine/SimplifyCFG should have handled the available opportunities.
7284 // If we did this folding here, it would be necessary to update the
7285 // MachineBasicBlock CFG, which is awkward.
7287 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7289 if (N1.getOpcode() == ISD::SETCC &&
7290 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7291 N1.getOperand(0).getValueType())) {
7292 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7293 Chain, N1.getOperand(2),
7294 N1.getOperand(0), N1.getOperand(1), N2);
7297 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7298 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7299 (N1.getOperand(0).hasOneUse() &&
7300 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7301 SDNode *Trunc = nullptr;
7302 if (N1.getOpcode() == ISD::TRUNCATE) {
7303 // Look pass the truncate.
7304 Trunc = N1.getNode();
7305 N1 = N1.getOperand(0);
7308 // Match this pattern so that we can generate simpler code:
7311 // %b = and i32 %a, 2
7312 // %c = srl i32 %b, 1
7313 // brcond i32 %c ...
7318 // %b = and i32 %a, 2
7319 // %c = setcc eq %b, 0
7322 // This applies only when the AND constant value has one bit set and the
7323 // SRL constant is equal to the log2 of the AND constant. The back-end is
7324 // smart enough to convert the result into a TEST/JMP sequence.
7325 SDValue Op0 = N1.getOperand(0);
7326 SDValue Op1 = N1.getOperand(1);
7328 if (Op0.getOpcode() == ISD::AND &&
7329 Op1.getOpcode() == ISD::Constant) {
7330 SDValue AndOp1 = Op0.getOperand(1);
7332 if (AndOp1.getOpcode() == ISD::Constant) {
7333 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7335 if (AndConst.isPowerOf2() &&
7336 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7338 DAG.getSetCC(SDLoc(N),
7339 getSetCCResultType(Op0.getValueType()),
7340 Op0, DAG.getConstant(0, Op0.getValueType()),
7343 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7344 MVT::Other, Chain, SetCC, N2);
7345 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7346 // will convert it back to (X & C1) >> C2.
7347 CombineTo(N, NewBRCond, false);
7348 // Truncate is dead.
7350 removeFromWorkList(Trunc);
7351 DAG.DeleteNode(Trunc);
7353 // Replace the uses of SRL with SETCC
7354 WorkListRemover DeadNodes(*this);
7355 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7356 removeFromWorkList(N1.getNode());
7357 DAG.DeleteNode(N1.getNode());
7358 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7364 // Restore N1 if the above transformation doesn't match.
7365 N1 = N->getOperand(1);
7368 // Transform br(xor(x, y)) -> br(x != y)
7369 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7370 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7371 SDNode *TheXor = N1.getNode();
7372 SDValue Op0 = TheXor->getOperand(0);
7373 SDValue Op1 = TheXor->getOperand(1);
7374 if (Op0.getOpcode() == Op1.getOpcode()) {
7375 // Avoid missing important xor optimizations.
7376 SDValue Tmp = visitXOR(TheXor);
7377 if (Tmp.getNode()) {
7378 if (Tmp.getNode() != TheXor) {
7379 DEBUG(dbgs() << "\nReplacing.8 ";
7381 dbgs() << "\nWith: ";
7382 Tmp.getNode()->dump(&DAG);
7384 WorkListRemover DeadNodes(*this);
7385 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7386 removeFromWorkList(TheXor);
7387 DAG.DeleteNode(TheXor);
7388 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7389 MVT::Other, Chain, Tmp, N2);
7392 // visitXOR has changed XOR's operands or replaced the XOR completely,
7394 return SDValue(N, 0);
7398 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7400 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7401 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7402 Op0.getOpcode() == ISD::XOR) {
7403 TheXor = Op0.getNode();
7407 EVT SetCCVT = N1.getValueType();
7409 SetCCVT = getSetCCResultType(SetCCVT);
7410 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7413 Equal ? ISD::SETEQ : ISD::SETNE);
7414 // Replace the uses of XOR with SETCC
7415 WorkListRemover DeadNodes(*this);
7416 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7417 removeFromWorkList(N1.getNode());
7418 DAG.DeleteNode(N1.getNode());
7419 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7420 MVT::Other, Chain, SetCC, N2);
7427 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7429 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7430 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7431 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7433 // If N is a constant we could fold this into a fallthrough or unconditional
7434 // branch. However that doesn't happen very often in normal code, because
7435 // Instcombine/SimplifyCFG should have handled the available opportunities.
7436 // If we did this folding here, it would be necessary to update the
7437 // MachineBasicBlock CFG, which is awkward.
7439 // Use SimplifySetCC to simplify SETCC's.
7440 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7441 CondLHS, CondRHS, CC->get(), SDLoc(N),
7443 if (Simp.getNode()) AddToWorkList(Simp.getNode());
7445 // fold to a simpler setcc
7446 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7447 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7448 N->getOperand(0), Simp.getOperand(2),
7449 Simp.getOperand(0), Simp.getOperand(1),
7455 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7456 /// uses N as its base pointer and that N may be folded in the load / store
7457 /// addressing mode.
7458 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7460 const TargetLowering &TLI) {
7462 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7463 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7465 VT = Use->getValueType(0);
7466 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7467 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7469 VT = ST->getValue().getValueType();
7473 TargetLowering::AddrMode AM;
7474 if (N->getOpcode() == ISD::ADD) {
7475 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7478 AM.BaseOffs = Offset->getSExtValue();
7482 } else if (N->getOpcode() == ISD::SUB) {
7483 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7486 AM.BaseOffs = -Offset->getSExtValue();
7493 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7496 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7497 /// pre-indexed load / store when the base pointer is an add or subtract
7498 /// and it has other uses besides the load / store. After the
7499 /// transformation, the new indexed load / store has effectively folded
7500 /// the add / subtract in and all of its other uses are redirected to the
7501 /// new load / store.
7502 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7503 if (Level < AfterLegalizeDAG)
7509 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7510 if (LD->isIndexed())
7512 VT = LD->getMemoryVT();
7513 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7514 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7516 Ptr = LD->getBasePtr();
7517 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7518 if (ST->isIndexed())
7520 VT = ST->getMemoryVT();
7521 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7522 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7524 Ptr = ST->getBasePtr();
7530 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7531 // out. There is no reason to make this a preinc/predec.
7532 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7533 Ptr.getNode()->hasOneUse())
7536 // Ask the target to do addressing mode selection.
7539 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7540 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7543 // Backends without true r+i pre-indexed forms may need to pass a
7544 // constant base with a variable offset so that constant coercion
7545 // will work with the patterns in canonical form.
7546 bool Swapped = false;
7547 if (isa<ConstantSDNode>(BasePtr)) {
7548 std::swap(BasePtr, Offset);
7552 // Don't create a indexed load / store with zero offset.
7553 if (isa<ConstantSDNode>(Offset) &&
7554 cast<ConstantSDNode>(Offset)->isNullValue())
7557 // Try turning it into a pre-indexed load / store except when:
7558 // 1) The new base ptr is a frame index.
7559 // 2) If N is a store and the new base ptr is either the same as or is a
7560 // predecessor of the value being stored.
7561 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7562 // that would create a cycle.
7563 // 4) All uses are load / store ops that use it as old base ptr.
7565 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7566 // (plus the implicit offset) to a register to preinc anyway.
7567 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7572 SDValue Val = cast<StoreSDNode>(N)->getValue();
7573 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7577 // If the offset is a constant, there may be other adds of constants that
7578 // can be folded with this one. We should do this to avoid having to keep
7579 // a copy of the original base pointer.
7580 SmallVector<SDNode *, 16> OtherUses;
7581 if (isa<ConstantSDNode>(Offset))
7582 for (SDNode *Use : BasePtr.getNode()->uses()) {
7583 if (Use == Ptr.getNode())
7586 if (Use->isPredecessorOf(N))
7589 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7594 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7595 if (Op1.getNode() == BasePtr.getNode())
7596 std::swap(Op0, Op1);
7597 assert(Op0.getNode() == BasePtr.getNode() &&
7598 "Use of ADD/SUB but not an operand");
7600 if (!isa<ConstantSDNode>(Op1)) {
7605 // FIXME: In some cases, we can be smarter about this.
7606 if (Op1.getValueType() != Offset.getValueType()) {
7611 OtherUses.push_back(Use);
7615 std::swap(BasePtr, Offset);
7617 // Now check for #3 and #4.
7618 bool RealUse = false;
7620 // Caches for hasPredecessorHelper
7621 SmallPtrSet<const SDNode *, 32> Visited;
7622 SmallVector<const SDNode *, 16> Worklist;
7624 for (SDNode *Use : Ptr.getNode()->uses()) {
7627 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7630 // If Ptr may be folded in addressing mode of other use, then it's
7631 // not profitable to do this transformation.
7632 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7641 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7642 BasePtr, Offset, AM);
7644 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7645 BasePtr, Offset, AM);
7648 DEBUG(dbgs() << "\nReplacing.4 ";
7650 dbgs() << "\nWith: ";
7651 Result.getNode()->dump(&DAG);
7653 WorkListRemover DeadNodes(*this);
7655 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7656 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7658 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7661 // Finally, since the node is now dead, remove it from the graph.
7665 std::swap(BasePtr, Offset);
7667 // Replace other uses of BasePtr that can be updated to use Ptr
7668 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7669 unsigned OffsetIdx = 1;
7670 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7672 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7673 BasePtr.getNode() && "Expected BasePtr operand");
7675 // We need to replace ptr0 in the following expression:
7676 // x0 * offset0 + y0 * ptr0 = t0
7678 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7680 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7681 // indexed load/store and the expresion that needs to be re-written.
7683 // Therefore, we have:
7684 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7686 ConstantSDNode *CN =
7687 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7689 APInt Offset0 = CN->getAPIntValue();
7690 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7692 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7693 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7694 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7695 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7697 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7699 APInt CNV = Offset0;
7700 if (X0 < 0) CNV = -CNV;
7701 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7702 else CNV = CNV - Offset1;
7704 // We can now generate the new expression.
7705 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7706 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7708 SDValue NewUse = DAG.getNode(Opcode,
7709 SDLoc(OtherUses[i]),
7710 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7711 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7712 removeFromWorkList(OtherUses[i]);
7713 DAG.DeleteNode(OtherUses[i]);
7716 // Replace the uses of Ptr with uses of the updated base value.
7717 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7718 removeFromWorkList(Ptr.getNode());
7719 DAG.DeleteNode(Ptr.getNode());
7724 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7725 /// add / sub of the base pointer node into a post-indexed load / store.
7726 /// The transformation folded the add / subtract into the new indexed
7727 /// load / store effectively and all of its uses are redirected to the
7728 /// new load / store.
7729 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7730 if (Level < AfterLegalizeDAG)
7736 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7737 if (LD->isIndexed())
7739 VT = LD->getMemoryVT();
7740 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7741 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7743 Ptr = LD->getBasePtr();
7744 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7745 if (ST->isIndexed())
7747 VT = ST->getMemoryVT();
7748 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7749 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7751 Ptr = ST->getBasePtr();
7757 if (Ptr.getNode()->hasOneUse())
7760 for (SDNode *Op : Ptr.getNode()->uses()) {
7762 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7767 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7768 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7769 // Don't create a indexed load / store with zero offset.
7770 if (isa<ConstantSDNode>(Offset) &&
7771 cast<ConstantSDNode>(Offset)->isNullValue())
7774 // Try turning it into a post-indexed load / store except when
7775 // 1) All uses are load / store ops that use it as base ptr (and
7776 // it may be folded as addressing mmode).
7777 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7778 // nor a successor of N. Otherwise, if Op is folded that would
7781 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7785 bool TryNext = false;
7786 for (SDNode *Use : BasePtr.getNode()->uses()) {
7787 if (Use == Ptr.getNode())
7790 // If all the uses are load / store addresses, then don't do the
7792 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7793 bool RealUse = false;
7794 for (SDNode *UseUse : Use->uses()) {
7795 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7810 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7811 SDValue Result = isLoad
7812 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7813 BasePtr, Offset, AM)
7814 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7815 BasePtr, Offset, AM);
7818 DEBUG(dbgs() << "\nReplacing.5 ";
7820 dbgs() << "\nWith: ";
7821 Result.getNode()->dump(&DAG);
7823 WorkListRemover DeadNodes(*this);
7825 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7826 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7828 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7831 // Finally, since the node is now dead, remove it from the graph.
7834 // Replace the uses of Use with uses of the updated base value.
7835 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7836 Result.getValue(isLoad ? 1 : 0));
7837 removeFromWorkList(Op);
7847 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7848 LoadSDNode *LD = cast<LoadSDNode>(N);
7849 SDValue Chain = LD->getChain();
7850 SDValue Ptr = LD->getBasePtr();
7852 // If load is not volatile and there are no uses of the loaded value (and
7853 // the updated indexed value in case of indexed loads), change uses of the
7854 // chain value into uses of the chain input (i.e. delete the dead load).
7855 if (!LD->isVolatile()) {
7856 if (N->getValueType(1) == MVT::Other) {
7858 if (!N->hasAnyUseOfValue(0)) {
7859 // It's not safe to use the two value CombineTo variant here. e.g.
7860 // v1, chain2 = load chain1, loc
7861 // v2, chain3 = load chain2, loc
7863 // Now we replace use of chain2 with chain1. This makes the second load
7864 // isomorphic to the one we are deleting, and thus makes this load live.
7865 DEBUG(dbgs() << "\nReplacing.6 ";
7867 dbgs() << "\nWith chain: ";
7868 Chain.getNode()->dump(&DAG);
7870 WorkListRemover DeadNodes(*this);
7871 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7873 if (N->use_empty()) {
7874 removeFromWorkList(N);
7878 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7882 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7883 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7884 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7885 DEBUG(dbgs() << "\nReplacing.7 ";
7887 dbgs() << "\nWith: ";
7888 Undef.getNode()->dump(&DAG);
7889 dbgs() << " and 2 other values\n");
7890 WorkListRemover DeadNodes(*this);
7891 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7892 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7893 DAG.getUNDEF(N->getValueType(1)));
7894 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7895 removeFromWorkList(N);
7897 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7902 // If this load is directly stored, replace the load value with the stored
7904 // TODO: Handle store large -> read small portion.
7905 // TODO: Handle TRUNCSTORE/LOADEXT
7906 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7907 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7908 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7909 if (PrevST->getBasePtr() == Ptr &&
7910 PrevST->getValue().getValueType() == N->getValueType(0))
7911 return CombineTo(N, Chain.getOperand(1), Chain);
7915 // Try to infer better alignment information than the load already has.
7916 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7917 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7918 if (Align > LD->getMemOperand()->getBaseAlignment()) {
7920 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7921 LD->getValueType(0),
7922 Chain, Ptr, LD->getPointerInfo(),
7924 LD->isVolatile(), LD->isNonTemporal(), Align,
7926 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7931 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7932 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7934 if (CombinerAAOnlyFunc.getNumOccurrences() &&
7935 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
7938 if (UseAA && LD->isUnindexed()) {
7939 // Walk up chain skipping non-aliasing memory nodes.
7940 SDValue BetterChain = FindBetterChain(N, Chain);
7942 // If there is a better chain.
7943 if (Chain != BetterChain) {
7946 // Replace the chain to void dependency.
7947 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7948 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7949 BetterChain, Ptr, LD->getMemOperand());
7951 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7952 LD->getValueType(0),
7953 BetterChain, Ptr, LD->getMemoryVT(),
7954 LD->getMemOperand());
7957 // Create token factor to keep old chain connected.
7958 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7959 MVT::Other, Chain, ReplLoad.getValue(1));
7961 // Make sure the new and old chains are cleaned up.
7962 AddToWorkList(Token.getNode());
7964 // Replace uses with load result and token factor. Don't add users
7966 return CombineTo(N, ReplLoad.getValue(0), Token, false);
7970 // Try transforming N to an indexed load.
7971 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7972 return SDValue(N, 0);
7974 // Try to slice up N to more direct loads if the slices are mapped to
7975 // different register banks or pairing can take place.
7977 return SDValue(N, 0);
7983 /// \brief Helper structure used to slice a load in smaller loads.
7984 /// Basically a slice is obtained from the following sequence:
7985 /// Origin = load Ty1, Base
7986 /// Shift = srl Ty1 Origin, CstTy Amount
7987 /// Inst = trunc Shift to Ty2
7989 /// Then, it will be rewriten into:
7990 /// Slice = load SliceTy, Base + SliceOffset
7991 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
7993 /// SliceTy is deduced from the number of bits that are actually used to
7995 struct LoadedSlice {
7996 /// \brief Helper structure used to compute the cost of a slice.
7998 /// Are we optimizing for code size.
8003 unsigned CrossRegisterBanksCopies;
8007 Cost(bool ForCodeSize = false)
8008 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8009 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8011 /// \brief Get the cost of one isolated slice.
8012 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8013 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8014 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8015 EVT TruncType = LS.Inst->getValueType(0);
8016 EVT LoadedType = LS.getLoadedType();
8017 if (TruncType != LoadedType &&
8018 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8022 /// \brief Account for slicing gain in the current cost.
8023 /// Slicing provide a few gains like removing a shift or a
8024 /// truncate. This method allows to grow the cost of the original
8025 /// load with the gain from this slice.
8026 void addSliceGain(const LoadedSlice &LS) {
8027 // Each slice saves a truncate.
8028 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8029 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8030 LS.Inst->getOperand(0).getValueType()))
8032 // If there is a shift amount, this slice gets rid of it.
8035 // If this slice can merge a cross register bank copy, account for it.
8036 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8037 ++CrossRegisterBanksCopies;
8040 Cost &operator+=(const Cost &RHS) {
8042 Truncates += RHS.Truncates;
8043 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8049 bool operator==(const Cost &RHS) const {
8050 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8051 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8052 ZExts == RHS.ZExts && Shift == RHS.Shift;
8055 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8057 bool operator<(const Cost &RHS) const {
8058 // Assume cross register banks copies are as expensive as loads.
8059 // FIXME: Do we want some more target hooks?
8060 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8061 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8062 // Unless we are optimizing for code size, consider the
8063 // expensive operation first.
8064 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8065 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8066 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8067 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8070 bool operator>(const Cost &RHS) const { return RHS < *this; }
8072 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8074 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8076 // The last instruction that represent the slice. This should be a
8077 // truncate instruction.
8079 // The original load instruction.
8081 // The right shift amount in bits from the original load.
8083 // The DAG from which Origin came from.
8084 // This is used to get some contextual information about legal types, etc.
8087 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8088 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8089 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8091 LoadedSlice(const LoadedSlice &LS)
8092 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8094 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8095 /// \return Result is \p BitWidth and has used bits set to 1 and
8096 /// not used bits set to 0.
8097 APInt getUsedBits() const {
8098 // Reproduce the trunc(lshr) sequence:
8099 // - Start from the truncated value.
8100 // - Zero extend to the desired bit width.
8102 assert(Origin && "No original load to compare against.");
8103 unsigned BitWidth = Origin->getValueSizeInBits(0);
8104 assert(Inst && "This slice is not bound to an instruction");
8105 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8106 "Extracted slice is bigger than the whole type!");
8107 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8108 UsedBits.setAllBits();
8109 UsedBits = UsedBits.zext(BitWidth);
8114 /// \brief Get the size of the slice to be loaded in bytes.
8115 unsigned getLoadedSize() const {
8116 unsigned SliceSize = getUsedBits().countPopulation();
8117 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8118 return SliceSize / 8;
8121 /// \brief Get the type that will be loaded for this slice.
8122 /// Note: This may not be the final type for the slice.
8123 EVT getLoadedType() const {
8124 assert(DAG && "Missing context");
8125 LLVMContext &Ctxt = *DAG->getContext();
8126 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8129 /// \brief Get the alignment of the load used for this slice.
8130 unsigned getAlignment() const {
8131 unsigned Alignment = Origin->getAlignment();
8132 unsigned Offset = getOffsetFromBase();
8134 Alignment = MinAlign(Alignment, Alignment + Offset);
8138 /// \brief Check if this slice can be rewritten with legal operations.
8139 bool isLegal() const {
8140 // An invalid slice is not legal.
8141 if (!Origin || !Inst || !DAG)
8144 // Offsets are for indexed load only, we do not handle that.
8145 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8148 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8150 // Check that the type is legal.
8151 EVT SliceType = getLoadedType();
8152 if (!TLI.isTypeLegal(SliceType))
8155 // Check that the load is legal for this type.
8156 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8159 // Check that the offset can be computed.
8160 // 1. Check its type.
8161 EVT PtrType = Origin->getBasePtr().getValueType();
8162 if (PtrType == MVT::Untyped || PtrType.isExtended())
8165 // 2. Check that it fits in the immediate.
8166 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8169 // 3. Check that the computation is legal.
8170 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8173 // Check that the zext is legal if it needs one.
8174 EVT TruncateType = Inst->getValueType(0);
8175 if (TruncateType != SliceType &&
8176 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8182 /// \brief Get the offset in bytes of this slice in the original chunk of
8184 /// \pre DAG != nullptr.
8185 uint64_t getOffsetFromBase() const {
8186 assert(DAG && "Missing context.");
8188 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8189 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8190 uint64_t Offset = Shift / 8;
8191 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8192 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8193 "The size of the original loaded type is not a multiple of a"
8195 // If Offset is bigger than TySizeInBytes, it means we are loading all
8196 // zeros. This should have been optimized before in the process.
8197 assert(TySizeInBytes > Offset &&
8198 "Invalid shift amount for given loaded size");
8200 Offset = TySizeInBytes - Offset - getLoadedSize();
8204 /// \brief Generate the sequence of instructions to load the slice
8205 /// represented by this object and redirect the uses of this slice to
8206 /// this new sequence of instructions.
8207 /// \pre this->Inst && this->Origin are valid Instructions and this
8208 /// object passed the legal check: LoadedSlice::isLegal returned true.
8209 /// \return The last instruction of the sequence used to load the slice.
8210 SDValue loadSlice() const {
8211 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8212 const SDValue &OldBaseAddr = Origin->getBasePtr();
8213 SDValue BaseAddr = OldBaseAddr;
8214 // Get the offset in that chunk of bytes w.r.t. the endianess.
8215 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8216 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8218 // BaseAddr = BaseAddr + Offset.
8219 EVT ArithType = BaseAddr.getValueType();
8220 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8221 DAG->getConstant(Offset, ArithType));
8224 // Create the type of the loaded slice according to its size.
8225 EVT SliceType = getLoadedType();
8227 // Create the load for the slice.
8228 SDValue LastInst = DAG->getLoad(
8229 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8230 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8231 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8232 // If the final type is not the same as the loaded type, this means that
8233 // we have to pad with zero. Create a zero extend for that.
8234 EVT FinalType = Inst->getValueType(0);
8235 if (SliceType != FinalType)
8237 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8241 /// \brief Check if this slice can be merged with an expensive cross register
8242 /// bank copy. E.g.,
8244 /// f = bitcast i32 i to float
8245 bool canMergeExpensiveCrossRegisterBankCopy() const {
8246 if (!Inst || !Inst->hasOneUse())
8248 SDNode *Use = *Inst->use_begin();
8249 if (Use->getOpcode() != ISD::BITCAST)
8251 assert(DAG && "Missing context");
8252 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8253 EVT ResVT = Use->getValueType(0);
8254 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8255 const TargetRegisterClass *ArgRC =
8256 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8257 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8260 // At this point, we know that we perform a cross-register-bank copy.
8261 // Check if it is expensive.
8262 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8263 // Assume bitcasts are cheap, unless both register classes do not
8264 // explicitly share a common sub class.
8265 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8268 // Check if it will be merged with the load.
8269 // 1. Check the alignment constraint.
8270 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8271 ResVT.getTypeForEVT(*DAG->getContext()));
8273 if (RequiredAlignment > getAlignment())
8276 // 2. Check that the load is a legal operation for that type.
8277 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8280 // 3. Check that we do not have a zext in the way.
8281 if (Inst->getValueType(0) != getLoadedType())
8289 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8290 /// \p UsedBits looks like 0..0 1..1 0..0.
8291 static bool areUsedBitsDense(const APInt &UsedBits) {
8292 // If all the bits are one, this is dense!
8293 if (UsedBits.isAllOnesValue())
8296 // Get rid of the unused bits on the right.
8297 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8298 // Get rid of the unused bits on the left.
8299 if (NarrowedUsedBits.countLeadingZeros())
8300 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8301 // Check that the chunk of bits is completely used.
8302 return NarrowedUsedBits.isAllOnesValue();
8305 /// \brief Check whether or not \p First and \p Second are next to each other
8306 /// in memory. This means that there is no hole between the bits loaded
8307 /// by \p First and the bits loaded by \p Second.
8308 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8309 const LoadedSlice &Second) {
8310 assert(First.Origin == Second.Origin && First.Origin &&
8311 "Unable to match different memory origins.");
8312 APInt UsedBits = First.getUsedBits();
8313 assert((UsedBits & Second.getUsedBits()) == 0 &&
8314 "Slices are not supposed to overlap.");
8315 UsedBits |= Second.getUsedBits();
8316 return areUsedBitsDense(UsedBits);
8319 /// \brief Adjust the \p GlobalLSCost according to the target
8320 /// paring capabilities and the layout of the slices.
8321 /// \pre \p GlobalLSCost should account for at least as many loads as
8322 /// there is in the slices in \p LoadedSlices.
8323 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8324 LoadedSlice::Cost &GlobalLSCost) {
8325 unsigned NumberOfSlices = LoadedSlices.size();
8326 // If there is less than 2 elements, no pairing is possible.
8327 if (NumberOfSlices < 2)
8330 // Sort the slices so that elements that are likely to be next to each
8331 // other in memory are next to each other in the list.
8332 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8333 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8334 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8335 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8337 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8338 // First (resp. Second) is the first (resp. Second) potentially candidate
8339 // to be placed in a paired load.
8340 const LoadedSlice *First = nullptr;
8341 const LoadedSlice *Second = nullptr;
8342 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8343 // Set the beginning of the pair.
8346 Second = &LoadedSlices[CurrSlice];
8348 // If First is NULL, it means we start a new pair.
8349 // Get to the next slice.
8353 EVT LoadedType = First->getLoadedType();
8355 // If the types of the slices are different, we cannot pair them.
8356 if (LoadedType != Second->getLoadedType())
8359 // Check if the target supplies paired loads for this type.
8360 unsigned RequiredAlignment = 0;
8361 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8362 // move to the next pair, this type is hopeless.
8366 // Check if we meet the alignment requirement.
8367 if (RequiredAlignment > First->getAlignment())
8370 // Check that both loads are next to each other in memory.
8371 if (!areSlicesNextToEachOther(*First, *Second))
8374 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8375 --GlobalLSCost.Loads;
8376 // Move to the next pair.
8381 /// \brief Check the profitability of all involved LoadedSlice.
8382 /// Currently, it is considered profitable if there is exactly two
8383 /// involved slices (1) which are (2) next to each other in memory, and
8384 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8386 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8387 /// the elements themselves.
8389 /// FIXME: When the cost model will be mature enough, we can relax
8390 /// constraints (1) and (2).
8391 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8392 const APInt &UsedBits, bool ForCodeSize) {
8393 unsigned NumberOfSlices = LoadedSlices.size();
8394 if (StressLoadSlicing)
8395 return NumberOfSlices > 1;
8398 if (NumberOfSlices != 2)
8402 if (!areUsedBitsDense(UsedBits))
8406 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8407 // The original code has one big load.
8409 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8410 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8411 // Accumulate the cost of all the slices.
8412 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8413 GlobalSlicingCost += SliceCost;
8415 // Account as cost in the original configuration the gain obtained
8416 // with the current slices.
8417 OrigCost.addSliceGain(LS);
8420 // If the target supports paired load, adjust the cost accordingly.
8421 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8422 return OrigCost > GlobalSlicingCost;
8425 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8426 /// operations, split it in the various pieces being extracted.
8428 /// This sort of thing is introduced by SROA.
8429 /// This slicing takes care not to insert overlapping loads.
8430 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8431 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8432 if (Level < AfterLegalizeDAG)
8435 LoadSDNode *LD = cast<LoadSDNode>(N);
8436 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8437 !LD->getValueType(0).isInteger())
8440 // Keep track of already used bits to detect overlapping values.
8441 // In that case, we will just abort the transformation.
8442 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8444 SmallVector<LoadedSlice, 4> LoadedSlices;
8446 // Check if this load is used as several smaller chunks of bits.
8447 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8448 // of computation for each trunc.
8449 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8450 UI != UIEnd; ++UI) {
8451 // Skip the uses of the chain.
8452 if (UI.getUse().getResNo() != 0)
8458 // Check if this is a trunc(lshr).
8459 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8460 isa<ConstantSDNode>(User->getOperand(1))) {
8461 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8462 User = *User->use_begin();
8465 // At this point, User is a Truncate, iff we encountered, trunc or
8467 if (User->getOpcode() != ISD::TRUNCATE)
8470 // The width of the type must be a power of 2 and greater than 8-bits.
8471 // Otherwise the load cannot be represented in LLVM IR.
8472 // Moreover, if we shifted with a non-8-bits multiple, the slice
8473 // will be across several bytes. We do not support that.
8474 unsigned Width = User->getValueSizeInBits(0);
8475 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8478 // Build the slice for this chain of computations.
8479 LoadedSlice LS(User, LD, Shift, &DAG);
8480 APInt CurrentUsedBits = LS.getUsedBits();
8482 // Check if this slice overlaps with another.
8483 if ((CurrentUsedBits & UsedBits) != 0)
8485 // Update the bits used globally.
8486 UsedBits |= CurrentUsedBits;
8488 // Check if the new slice would be legal.
8492 // Record the slice.
8493 LoadedSlices.push_back(LS);
8496 // Abort slicing if it does not seem to be profitable.
8497 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8502 // Rewrite each chain to use an independent load.
8503 // By construction, each chain can be represented by a unique load.
8505 // Prepare the argument for the new token factor for all the slices.
8506 SmallVector<SDValue, 8> ArgChains;
8507 for (SmallVectorImpl<LoadedSlice>::const_iterator
8508 LSIt = LoadedSlices.begin(),
8509 LSItEnd = LoadedSlices.end();
8510 LSIt != LSItEnd; ++LSIt) {
8511 SDValue SliceInst = LSIt->loadSlice();
8512 CombineTo(LSIt->Inst, SliceInst, true);
8513 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8514 SliceInst = SliceInst.getOperand(0);
8515 assert(SliceInst->getOpcode() == ISD::LOAD &&
8516 "It takes more than a zext to get to the loaded slice!!");
8517 ArgChains.push_back(SliceInst.getValue(1));
8520 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8522 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8526 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8527 /// load is having specific bytes cleared out. If so, return the byte size
8528 /// being masked out and the shift amount.
8529 static std::pair<unsigned, unsigned>
8530 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8531 std::pair<unsigned, unsigned> Result(0, 0);
8533 // Check for the structure we're looking for.
8534 if (V->getOpcode() != ISD::AND ||
8535 !isa<ConstantSDNode>(V->getOperand(1)) ||
8536 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8539 // Check the chain and pointer.
8540 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8541 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
8543 // The store should be chained directly to the load or be an operand of a
8545 if (LD == Chain.getNode())
8547 else if (Chain->getOpcode() != ISD::TokenFactor)
8548 return Result; // Fail.
8551 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8552 if (Chain->getOperand(i).getNode() == LD) {
8556 if (!isOk) return Result;
8559 // This only handles simple types.
8560 if (V.getValueType() != MVT::i16 &&
8561 V.getValueType() != MVT::i32 &&
8562 V.getValueType() != MVT::i64)
8565 // Check the constant mask. Invert it so that the bits being masked out are
8566 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8567 // follow the sign bit for uniformity.
8568 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8569 unsigned NotMaskLZ = countLeadingZeros(NotMask);
8570 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
8571 unsigned NotMaskTZ = countTrailingZeros(NotMask);
8572 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8573 if (NotMaskLZ == 64) return Result; // All zero mask.
8575 // See if we have a continuous run of bits. If so, we have 0*1+0*
8576 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8579 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8580 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8581 NotMaskLZ -= 64-V.getValueSizeInBits();
8583 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8584 switch (MaskedBytes) {
8588 default: return Result; // All one mask, or 5-byte mask.
8591 // Verify that the first bit starts at a multiple of mask so that the access
8592 // is aligned the same as the access width.
8593 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8595 Result.first = MaskedBytes;
8596 Result.second = NotMaskTZ/8;
8601 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8602 /// provides a value as specified by MaskInfo. If so, replace the specified
8603 /// store with a narrower store of truncated IVal.
8605 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8606 SDValue IVal, StoreSDNode *St,
8608 unsigned NumBytes = MaskInfo.first;
8609 unsigned ByteShift = MaskInfo.second;
8610 SelectionDAG &DAG = DC->getDAG();
8612 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8613 // that uses this. If not, this is not a replacement.
8614 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8615 ByteShift*8, (ByteShift+NumBytes)*8);
8616 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8618 // Check that it is legal on the target to do this. It is legal if the new
8619 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8621 MVT VT = MVT::getIntegerVT(NumBytes*8);
8622 if (!DC->isTypeLegal(VT))
8625 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8626 // shifted by ByteShift and truncated down to NumBytes.
8628 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8629 DAG.getConstant(ByteShift*8,
8630 DC->getShiftAmountTy(IVal.getValueType())));
8632 // Figure out the offset for the store and the alignment of the access.
8634 unsigned NewAlign = St->getAlignment();
8636 if (DAG.getTargetLoweringInfo().isLittleEndian())
8637 StOffset = ByteShift;
8639 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8641 SDValue Ptr = St->getBasePtr();
8643 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8644 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8645 NewAlign = MinAlign(NewAlign, StOffset);
8648 // Truncate down to the new size.
8649 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8652 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8653 St->getPointerInfo().getWithOffset(StOffset),
8654 false, false, NewAlign).getNode();
8658 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8659 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8660 /// of the loaded bits, try narrowing the load and store if it would end up
8661 /// being a win for performance or code size.
8662 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8663 StoreSDNode *ST = cast<StoreSDNode>(N);
8664 if (ST->isVolatile())
8667 SDValue Chain = ST->getChain();
8668 SDValue Value = ST->getValue();
8669 SDValue Ptr = ST->getBasePtr();
8670 EVT VT = Value.getValueType();
8672 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8675 unsigned Opc = Value.getOpcode();
8677 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8678 // is a byte mask indicating a consecutive number of bytes, check to see if
8679 // Y is known to provide just those bytes. If so, we try to replace the
8680 // load + replace + store sequence with a single (narrower) store, which makes
8682 if (Opc == ISD::OR) {
8683 std::pair<unsigned, unsigned> MaskedLoad;
8684 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8685 if (MaskedLoad.first)
8686 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8687 Value.getOperand(1), ST,this))
8688 return SDValue(NewST, 0);
8690 // Or is commutative, so try swapping X and Y.
8691 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8692 if (MaskedLoad.first)
8693 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8694 Value.getOperand(0), ST,this))
8695 return SDValue(NewST, 0);
8698 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8699 Value.getOperand(1).getOpcode() != ISD::Constant)
8702 SDValue N0 = Value.getOperand(0);
8703 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8704 Chain == SDValue(N0.getNode(), 1)) {
8705 LoadSDNode *LD = cast<LoadSDNode>(N0);
8706 if (LD->getBasePtr() != Ptr ||
8707 LD->getPointerInfo().getAddrSpace() !=
8708 ST->getPointerInfo().getAddrSpace())
8711 // Find the type to narrow it the load / op / store to.
8712 SDValue N1 = Value.getOperand(1);
8713 unsigned BitWidth = N1.getValueSizeInBits();
8714 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8715 if (Opc == ISD::AND)
8716 Imm ^= APInt::getAllOnesValue(BitWidth);
8717 if (Imm == 0 || Imm.isAllOnesValue())
8719 unsigned ShAmt = Imm.countTrailingZeros();
8720 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8721 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8722 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8723 while (NewBW < BitWidth &&
8724 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8725 TLI.isNarrowingProfitable(VT, NewVT))) {
8726 NewBW = NextPowerOf2(NewBW);
8727 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8729 if (NewBW >= BitWidth)
8732 // If the lsb changed does not start at the type bitwidth boundary,
8733 // start at the previous one.
8735 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8736 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8737 std::min(BitWidth, ShAmt + NewBW));
8738 if ((Imm & Mask) == Imm) {
8739 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8740 if (Opc == ISD::AND)
8741 NewImm ^= APInt::getAllOnesValue(NewBW);
8742 uint64_t PtrOff = ShAmt / 8;
8743 // For big endian targets, we need to adjust the offset to the pointer to
8744 // load the correct bytes.
8745 if (TLI.isBigEndian())
8746 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8748 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8749 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8750 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8753 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8754 Ptr.getValueType(), Ptr,
8755 DAG.getConstant(PtrOff, Ptr.getValueType()));
8756 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8757 LD->getChain(), NewPtr,
8758 LD->getPointerInfo().getWithOffset(PtrOff),
8759 LD->isVolatile(), LD->isNonTemporal(),
8760 LD->isInvariant(), NewAlign,
8762 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8763 DAG.getConstant(NewImm, NewVT));
8764 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8766 ST->getPointerInfo().getWithOffset(PtrOff),
8767 false, false, NewAlign);
8769 AddToWorkList(NewPtr.getNode());
8770 AddToWorkList(NewLD.getNode());
8771 AddToWorkList(NewVal.getNode());
8772 WorkListRemover DeadNodes(*this);
8773 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8782 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8783 /// if the load value isn't used by any other operations, then consider
8784 /// transforming the pair to integer load / store operations if the target
8785 /// deems the transformation profitable.
8786 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8787 StoreSDNode *ST = cast<StoreSDNode>(N);
8788 SDValue Chain = ST->getChain();
8789 SDValue Value = ST->getValue();
8790 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8791 Value.hasOneUse() &&
8792 Chain == SDValue(Value.getNode(), 1)) {
8793 LoadSDNode *LD = cast<LoadSDNode>(Value);
8794 EVT VT = LD->getMemoryVT();
8795 if (!VT.isFloatingPoint() ||
8796 VT != ST->getMemoryVT() ||
8797 LD->isNonTemporal() ||
8798 ST->isNonTemporal() ||
8799 LD->getPointerInfo().getAddrSpace() != 0 ||
8800 ST->getPointerInfo().getAddrSpace() != 0)
8803 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8804 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8805 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8806 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8807 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8810 unsigned LDAlign = LD->getAlignment();
8811 unsigned STAlign = ST->getAlignment();
8812 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8813 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8814 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8817 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8818 LD->getChain(), LD->getBasePtr(),
8819 LD->getPointerInfo(),
8820 false, false, false, LDAlign);
8822 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8823 NewLD, ST->getBasePtr(),
8824 ST->getPointerInfo(),
8825 false, false, STAlign);
8827 AddToWorkList(NewLD.getNode());
8828 AddToWorkList(NewST.getNode());
8829 WorkListRemover DeadNodes(*this);
8830 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8838 /// Helper struct to parse and store a memory address as base + index + offset.
8839 /// We ignore sign extensions when it is safe to do so.
8840 /// The following two expressions are not equivalent. To differentiate we need
8841 /// to store whether there was a sign extension involved in the index
8843 /// (load (i64 add (i64 copyfromreg %c)
8844 /// (i64 signextend (add (i8 load %index)
8848 /// (load (i64 add (i64 copyfromreg %c)
8849 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8851 struct BaseIndexOffset {
8855 bool IsIndexSignExt;
8857 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8859 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8860 bool IsIndexSignExt) :
8861 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8863 bool equalBaseIndex(const BaseIndexOffset &Other) {
8864 return Other.Base == Base && Other.Index == Index &&
8865 Other.IsIndexSignExt == IsIndexSignExt;
8868 /// Parses tree in Ptr for base, index, offset addresses.
8869 static BaseIndexOffset match(SDValue Ptr) {
8870 bool IsIndexSignExt = false;
8872 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8873 // instruction, then it could be just the BASE or everything else we don't
8874 // know how to handle. Just use Ptr as BASE and give up.
8875 if (Ptr->getOpcode() != ISD::ADD)
8876 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8878 // We know that we have at least an ADD instruction. Try to pattern match
8879 // the simple case of BASE + OFFSET.
8880 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8881 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8882 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8886 // Inside a loop the current BASE pointer is calculated using an ADD and a
8887 // MUL instruction. In this case Ptr is the actual BASE pointer.
8888 // (i64 add (i64 %array_ptr)
8889 // (i64 mul (i64 %induction_var)
8890 // (i64 %element_size)))
8891 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8892 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8894 // Look at Base + Index + Offset cases.
8895 SDValue Base = Ptr->getOperand(0);
8896 SDValue IndexOffset = Ptr->getOperand(1);
8898 // Skip signextends.
8899 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8900 IndexOffset = IndexOffset->getOperand(0);
8901 IsIndexSignExt = true;
8904 // Either the case of Base + Index (no offset) or something else.
8905 if (IndexOffset->getOpcode() != ISD::ADD)
8906 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8908 // Now we have the case of Base + Index + offset.
8909 SDValue Index = IndexOffset->getOperand(0);
8910 SDValue Offset = IndexOffset->getOperand(1);
8912 if (!isa<ConstantSDNode>(Offset))
8913 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8915 // Ignore signextends.
8916 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8917 Index = Index->getOperand(0);
8918 IsIndexSignExt = true;
8919 } else IsIndexSignExt = false;
8921 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8922 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8926 /// Holds a pointer to an LSBaseSDNode as well as information on where it
8927 /// is located in a sequence of memory operations connected by a chain.
8929 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8930 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8931 // Ptr to the mem node.
8932 LSBaseSDNode *MemNode;
8933 // Offset from the base ptr.
8934 int64_t OffsetFromBase;
8935 // What is the sequence number of this mem node.
8936 // Lowest mem operand in the DAG starts at zero.
8937 unsigned SequenceNum;
8940 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8941 EVT MemVT = St->getMemoryVT();
8942 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
8943 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8944 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
8946 // Don't merge vectors into wider inputs.
8947 if (MemVT.isVector() || !MemVT.isSimple())
8950 // Perform an early exit check. Do not bother looking at stored values that
8951 // are not constants or loads.
8952 SDValue StoredVal = St->getValue();
8953 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8954 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8958 // Only look at ends of store sequences.
8959 SDValue Chain = SDValue(St, 1);
8960 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8963 // This holds the base pointer, index, and the offset in bytes from the base
8965 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
8967 // We must have a base and an offset.
8968 if (!BasePtr.Base.getNode())
8971 // Do not handle stores to undef base pointers.
8972 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
8975 // Save the LoadSDNodes that we find in the chain.
8976 // We need to make sure that these nodes do not interfere with
8977 // any of the store nodes.
8978 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8980 // Save the StoreSDNodes that we find in the chain.
8981 SmallVector<MemOpLink, 8> StoreNodes;
8983 // Walk up the chain and look for nodes with offsets from the same
8984 // base pointer. Stop when reaching an instruction with a different kind
8985 // or instruction which has a different base pointer.
8987 StoreSDNode *Index = St;
8989 // If the chain has more than one use, then we can't reorder the mem ops.
8990 if (Index != St && !SDValue(Index, 1)->hasOneUse())
8993 // Find the base pointer and offset for this memory node.
8994 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
8996 // Check that the base pointer is the same as the original one.
8997 if (!Ptr.equalBaseIndex(BasePtr))
9000 // Check that the alignment is the same.
9001 if (Index->getAlignment() != St->getAlignment())
9004 // The memory operands must not be volatile.
9005 if (Index->isVolatile() || Index->isIndexed())
9009 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9010 if (St->isTruncatingStore())
9013 // The stored memory type must be the same.
9014 if (Index->getMemoryVT() != MemVT)
9017 // We do not allow unaligned stores because we want to prevent overriding
9019 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9022 // We found a potential memory operand to merge.
9023 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9025 // Find the next memory operand in the chain. If the next operand in the
9026 // chain is a store then move up and continue the scan with the next
9027 // memory operand. If the next operand is a load save it and use alias
9028 // information to check if it interferes with anything.
9029 SDNode *NextInChain = Index->getChain().getNode();
9031 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9032 // We found a store node. Use it for the next iteration.
9035 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9036 if (Ldn->isVolatile()) {
9041 // Save the load node for later. Continue the scan.
9042 AliasLoadNodes.push_back(Ldn);
9043 NextInChain = Ldn->getChain().getNode();
9052 // Check if there is anything to merge.
9053 if (StoreNodes.size() < 2)
9056 // Sort the memory operands according to their distance from the base pointer.
9057 std::sort(StoreNodes.begin(), StoreNodes.end(),
9058 [](MemOpLink LHS, MemOpLink RHS) {
9059 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9060 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9061 LHS.SequenceNum > RHS.SequenceNum);
9064 // Scan the memory operations on the chain and find the first non-consecutive
9065 // store memory address.
9066 unsigned LastConsecutiveStore = 0;
9067 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9068 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9070 // Check that the addresses are consecutive starting from the second
9071 // element in the list of stores.
9073 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9074 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9079 // Check if this store interferes with any of the loads that we found.
9080 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9081 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9085 // We found a load that alias with this store. Stop the sequence.
9089 // Mark this node as useful.
9090 LastConsecutiveStore = i;
9093 // The node with the lowest store address.
9094 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9096 // Store the constants into memory as one consecutive store.
9098 unsigned LastLegalType = 0;
9099 unsigned LastLegalVectorType = 0;
9100 bool NonZero = false;
9101 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9102 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9103 SDValue StoredVal = St->getValue();
9105 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9106 NonZero |= !C->isNullValue();
9107 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9108 NonZero |= !C->getConstantFPValue()->isNullValue();
9114 // Find a legal type for the constant store.
9115 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9116 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9117 if (TLI.isTypeLegal(StoreTy))
9118 LastLegalType = i+1;
9119 // Or check whether a truncstore is legal.
9120 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9121 TargetLowering::TypePromoteInteger) {
9122 EVT LegalizedStoredValueTy =
9123 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9124 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9125 LastLegalType = i+1;
9128 // Find a legal type for the vector store.
9129 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9130 if (TLI.isTypeLegal(Ty))
9131 LastLegalVectorType = i + 1;
9134 // We only use vectors if the constant is known to be zero and the
9135 // function is not marked with the noimplicitfloat attribute.
9136 if (NonZero || NoVectors)
9137 LastLegalVectorType = 0;
9139 // Check if we found a legal integer type to store.
9140 if (LastLegalType == 0 && LastLegalVectorType == 0)
9143 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9144 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9146 // Make sure we have something to merge.
9150 unsigned EarliestNodeUsed = 0;
9151 for (unsigned i=0; i < NumElem; ++i) {
9152 // Find a chain for the new wide-store operand. Notice that some
9153 // of the store nodes that we found may not be selected for inclusion
9154 // in the wide store. The chain we use needs to be the chain of the
9155 // earliest store node which is *used* and replaced by the wide store.
9156 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9157 EarliestNodeUsed = i;
9160 // The earliest Node in the DAG.
9161 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9162 SDLoc DL(StoreNodes[0].MemNode);
9166 // Find a legal type for the vector store.
9167 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9168 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9169 StoredVal = DAG.getConstant(0, Ty);
9171 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9172 APInt StoreInt(StoreBW, 0);
9174 // Construct a single integer constant which is made of the smaller
9176 bool IsLE = TLI.isLittleEndian();
9177 for (unsigned i = 0; i < NumElem ; ++i) {
9178 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9179 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9180 SDValue Val = St->getValue();
9181 StoreInt<<=ElementSizeBytes*8;
9182 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9183 StoreInt|=C->getAPIntValue().zext(StoreBW);
9184 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9185 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9187 assert(false && "Invalid constant element type");
9191 // Create the new Load and Store operations.
9192 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9193 StoredVal = DAG.getConstant(StoreInt, StoreTy);
9196 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9197 FirstInChain->getBasePtr(),
9198 FirstInChain->getPointerInfo(),
9200 FirstInChain->getAlignment());
9202 // Replace the first store with the new store
9203 CombineTo(EarliestOp, NewStore);
9204 // Erase all other stores.
9205 for (unsigned i = 0; i < NumElem ; ++i) {
9206 if (StoreNodes[i].MemNode == EarliestOp)
9208 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9209 // ReplaceAllUsesWith will replace all uses that existed when it was
9210 // called, but graph optimizations may cause new ones to appear. For
9211 // example, the case in pr14333 looks like
9213 // St's chain -> St -> another store -> X
9215 // And the only difference from St to the other store is the chain.
9216 // When we change it's chain to be St's chain they become identical,
9217 // get CSEed and the net result is that X is now a use of St.
9218 // Since we know that St is redundant, just iterate.
9219 while (!St->use_empty())
9220 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9221 removeFromWorkList(St);
9228 // Below we handle the case of multiple consecutive stores that
9229 // come from multiple consecutive loads. We merge them into a single
9230 // wide load and a single wide store.
9232 // Look for load nodes which are used by the stored values.
9233 SmallVector<MemOpLink, 8> LoadNodes;
9235 // Find acceptable loads. Loads need to have the same chain (token factor),
9236 // must not be zext, volatile, indexed, and they must be consecutive.
9237 BaseIndexOffset LdBasePtr;
9238 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9239 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9240 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9243 // Loads must only have one use.
9244 if (!Ld->hasNUsesOfValue(1, 0))
9247 // Check that the alignment is the same as the stores.
9248 if (Ld->getAlignment() != St->getAlignment())
9251 // The memory operands must not be volatile.
9252 if (Ld->isVolatile() || Ld->isIndexed())
9255 // We do not accept ext loads.
9256 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9259 // The stored memory type must be the same.
9260 if (Ld->getMemoryVT() != MemVT)
9263 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9264 // If this is not the first ptr that we check.
9265 if (LdBasePtr.Base.getNode()) {
9266 // The base ptr must be the same.
9267 if (!LdPtr.equalBaseIndex(LdBasePtr))
9270 // Check that all other base pointers are the same as this one.
9274 // We found a potential memory operand to merge.
9275 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9278 if (LoadNodes.size() < 2)
9281 // Scan the memory operations on the chain and find the first non-consecutive
9282 // load memory address. These variables hold the index in the store node
9284 unsigned LastConsecutiveLoad = 0;
9285 // This variable refers to the size and not index in the array.
9286 unsigned LastLegalVectorType = 0;
9287 unsigned LastLegalIntegerType = 0;
9288 StartAddress = LoadNodes[0].OffsetFromBase;
9289 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9290 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9291 // All loads much share the same chain.
9292 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9295 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9296 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9298 LastConsecutiveLoad = i;
9300 // Find a legal type for the vector store.
9301 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9302 if (TLI.isTypeLegal(StoreTy))
9303 LastLegalVectorType = i + 1;
9305 // Find a legal type for the integer store.
9306 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9307 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9308 if (TLI.isTypeLegal(StoreTy))
9309 LastLegalIntegerType = i + 1;
9310 // Or check whether a truncstore and extload is legal.
9311 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9312 TargetLowering::TypePromoteInteger) {
9313 EVT LegalizedStoredValueTy =
9314 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9315 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9316 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9317 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9318 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9319 LastLegalIntegerType = i+1;
9323 // Only use vector types if the vector type is larger than the integer type.
9324 // If they are the same, use integers.
9325 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9326 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9328 // We add +1 here because the LastXXX variables refer to location while
9329 // the NumElem refers to array/index size.
9330 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9331 NumElem = std::min(LastLegalType, NumElem);
9336 // The earliest Node in the DAG.
9337 unsigned EarliestNodeUsed = 0;
9338 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9339 for (unsigned i=1; i<NumElem; ++i) {
9340 // Find a chain for the new wide-store operand. Notice that some
9341 // of the store nodes that we found may not be selected for inclusion
9342 // in the wide store. The chain we use needs to be the chain of the
9343 // earliest store node which is *used* and replaced by the wide store.
9344 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9345 EarliestNodeUsed = i;
9348 // Find if it is better to use vectors or integers to load and store
9352 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9354 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9355 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9358 SDLoc LoadDL(LoadNodes[0].MemNode);
9359 SDLoc StoreDL(StoreNodes[0].MemNode);
9361 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9362 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9363 FirstLoad->getChain(),
9364 FirstLoad->getBasePtr(),
9365 FirstLoad->getPointerInfo(),
9366 false, false, false,
9367 FirstLoad->getAlignment());
9369 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9370 FirstInChain->getBasePtr(),
9371 FirstInChain->getPointerInfo(), false, false,
9372 FirstInChain->getAlignment());
9374 // Replace one of the loads with the new load.
9375 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9376 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9377 SDValue(NewLoad.getNode(), 1));
9379 // Remove the rest of the load chains.
9380 for (unsigned i = 1; i < NumElem ; ++i) {
9381 // Replace all chain users of the old load nodes with the chain of the new
9383 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9384 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9387 // Replace the first store with the new store.
9388 CombineTo(EarliestOp, NewStore);
9389 // Erase all other stores.
9390 for (unsigned i = 0; i < NumElem ; ++i) {
9391 // Remove all Store nodes.
9392 if (StoreNodes[i].MemNode == EarliestOp)
9394 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9395 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9396 removeFromWorkList(St);
9403 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9404 StoreSDNode *ST = cast<StoreSDNode>(N);
9405 SDValue Chain = ST->getChain();
9406 SDValue Value = ST->getValue();
9407 SDValue Ptr = ST->getBasePtr();
9409 // If this is a store of a bit convert, store the input value if the
9410 // resultant store does not need a higher alignment than the original.
9411 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9412 ST->isUnindexed()) {
9413 unsigned OrigAlign = ST->getAlignment();
9414 EVT SVT = Value.getOperand(0).getValueType();
9415 unsigned Align = TLI.getDataLayout()->
9416 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9417 if (Align <= OrigAlign &&
9418 ((!LegalOperations && !ST->isVolatile()) ||
9419 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9420 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9421 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9422 ST->isNonTemporal(), OrigAlign,
9426 // Turn 'store undef, Ptr' -> nothing.
9427 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9430 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9431 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9432 // NOTE: If the original store is volatile, this transform must not increase
9433 // the number of stores. For example, on x86-32 an f64 can be stored in one
9434 // processor operation but an i64 (which is not legal) requires two. So the
9435 // transform should not be done in this case.
9436 if (Value.getOpcode() != ISD::TargetConstantFP) {
9438 switch (CFP->getSimpleValueType(0).SimpleTy) {
9439 default: llvm_unreachable("Unknown FP type");
9440 case MVT::f16: // We don't do this for these yet.
9446 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9447 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9448 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9449 bitcastToAPInt().getZExtValue(), MVT::i32);
9450 return DAG.getStore(Chain, SDLoc(N), Tmp,
9451 Ptr, ST->getMemOperand());
9455 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9456 !ST->isVolatile()) ||
9457 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9458 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9459 getZExtValue(), MVT::i64);
9460 return DAG.getStore(Chain, SDLoc(N), Tmp,
9461 Ptr, ST->getMemOperand());
9464 if (!ST->isVolatile() &&
9465 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9466 // Many FP stores are not made apparent until after legalize, e.g. for
9467 // argument passing. Since this is so common, custom legalize the
9468 // 64-bit integer store into two 32-bit stores.
9469 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9470 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9471 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9472 if (TLI.isBigEndian()) std::swap(Lo, Hi);
9474 unsigned Alignment = ST->getAlignment();
9475 bool isVolatile = ST->isVolatile();
9476 bool isNonTemporal = ST->isNonTemporal();
9477 const MDNode *TBAAInfo = ST->getTBAAInfo();
9479 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9480 Ptr, ST->getPointerInfo(),
9481 isVolatile, isNonTemporal,
9482 ST->getAlignment(), TBAAInfo);
9483 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9484 DAG.getConstant(4, Ptr.getValueType()));
9485 Alignment = MinAlign(Alignment, 4U);
9486 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9487 Ptr, ST->getPointerInfo().getWithOffset(4),
9488 isVolatile, isNonTemporal,
9489 Alignment, TBAAInfo);
9490 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9499 // Try to infer better alignment information than the store already has.
9500 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9501 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9502 if (Align > ST->getAlignment())
9503 return DAG.getTruncStore(Chain, SDLoc(N), Value,
9504 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9505 ST->isVolatile(), ST->isNonTemporal(), Align,
9510 // Try transforming a pair floating point load / store ops to integer
9511 // load / store ops.
9512 SDValue NewST = TransformFPLoadStorePair(N);
9513 if (NewST.getNode())
9516 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9517 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9519 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9520 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9523 if (UseAA && ST->isUnindexed()) {
9524 // Walk up chain skipping non-aliasing memory nodes.
9525 SDValue BetterChain = FindBetterChain(N, Chain);
9527 // If there is a better chain.
9528 if (Chain != BetterChain) {
9531 // Replace the chain to avoid dependency.
9532 if (ST->isTruncatingStore()) {
9533 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9534 ST->getMemoryVT(), ST->getMemOperand());
9536 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9537 ST->getMemOperand());
9540 // Create token to keep both nodes around.
9541 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9542 MVT::Other, Chain, ReplStore);
9544 // Make sure the new and old chains are cleaned up.
9545 AddToWorkList(Token.getNode());
9547 // Don't add users to work list.
9548 return CombineTo(N, Token, false);
9552 // Try transforming N to an indexed store.
9553 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9554 return SDValue(N, 0);
9556 // FIXME: is there such a thing as a truncating indexed store?
9557 if (ST->isTruncatingStore() && ST->isUnindexed() &&
9558 Value.getValueType().isInteger()) {
9559 // See if we can simplify the input to this truncstore with knowledge that
9560 // only the low bits are being used. For example:
9561 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
9563 GetDemandedBits(Value,
9564 APInt::getLowBitsSet(
9565 Value.getValueType().getScalarType().getSizeInBits(),
9566 ST->getMemoryVT().getScalarType().getSizeInBits()));
9567 AddToWorkList(Value.getNode());
9568 if (Shorter.getNode())
9569 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9570 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9572 // Otherwise, see if we can simplify the operation with
9573 // SimplifyDemandedBits, which only works if the value has a single use.
9574 if (SimplifyDemandedBits(Value,
9575 APInt::getLowBitsSet(
9576 Value.getValueType().getScalarType().getSizeInBits(),
9577 ST->getMemoryVT().getScalarType().getSizeInBits())))
9578 return SDValue(N, 0);
9581 // If this is a load followed by a store to the same location, then the store
9583 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9584 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9585 ST->isUnindexed() && !ST->isVolatile() &&
9586 // There can't be any side effects between the load and store, such as
9588 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9589 // The store is dead, remove it.
9594 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9595 // truncating store. We can do this even if this is already a truncstore.
9596 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9597 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9598 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9599 ST->getMemoryVT())) {
9600 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9601 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9604 // Only perform this optimization before the types are legal, because we
9605 // don't want to perform this optimization on every DAGCombine invocation.
9607 bool EverChanged = false;
9610 // There can be multiple store sequences on the same chain.
9611 // Keep trying to merge store sequences until we are unable to do so
9612 // or until we merge the last store on the chain.
9613 bool Changed = MergeConsecutiveStores(ST);
9614 EverChanged |= Changed;
9615 if (!Changed) break;
9616 } while (ST->getOpcode() != ISD::DELETED_NODE);
9619 return SDValue(N, 0);
9622 return ReduceLoadOpStoreWidth(N);
9625 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9626 SDValue InVec = N->getOperand(0);
9627 SDValue InVal = N->getOperand(1);
9628 SDValue EltNo = N->getOperand(2);
9631 // If the inserted element is an UNDEF, just use the input vector.
9632 if (InVal.getOpcode() == ISD::UNDEF)
9635 EVT VT = InVec.getValueType();
9637 // If we can't generate a legal BUILD_VECTOR, exit
9638 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9641 // Check that we know which element is being inserted
9642 if (!isa<ConstantSDNode>(EltNo))
9644 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9646 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9647 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9649 SmallVector<SDValue, 8> Ops;
9650 // Do not combine these two vectors if the output vector will not replace
9651 // the input vector.
9652 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9653 Ops.append(InVec.getNode()->op_begin(),
9654 InVec.getNode()->op_end());
9655 } else if (InVec.getOpcode() == ISD::UNDEF) {
9656 unsigned NElts = VT.getVectorNumElements();
9657 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9662 // Insert the element
9663 if (Elt < Ops.size()) {
9664 // All the operands of BUILD_VECTOR must have the same type;
9665 // we enforce that here.
9666 EVT OpVT = Ops[0].getValueType();
9667 if (InVal.getValueType() != OpVT)
9668 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9669 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9670 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9674 // Return the new vector
9675 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
9678 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9679 // (vextract (scalar_to_vector val, 0) -> val
9680 SDValue InVec = N->getOperand(0);
9681 EVT VT = InVec.getValueType();
9682 EVT NVT = N->getValueType(0);
9684 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9685 // Check if the result type doesn't match the inserted element type. A
9686 // SCALAR_TO_VECTOR may truncate the inserted element and the
9687 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9688 SDValue InOp = InVec.getOperand(0);
9689 if (InOp.getValueType() != NVT) {
9690 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9691 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9696 SDValue EltNo = N->getOperand(1);
9697 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9699 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9700 // We only perform this optimization before the op legalization phase because
9701 // we may introduce new vector instructions which are not backed by TD
9702 // patterns. For example on AVX, extracting elements from a wide vector
9703 // without using extract_subvector. However, if we can find an underlying
9704 // scalar value, then we can always use that.
9705 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9707 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9708 int NumElem = VT.getVectorNumElements();
9709 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9710 // Find the new index to extract from.
9711 int OrigElt = SVOp->getMaskElt(Elt);
9713 // Extracting an undef index is undef.
9715 return DAG.getUNDEF(NVT);
9717 // Select the right vector half to extract from.
9719 if (OrigElt < NumElem) {
9720 SVInVec = InVec->getOperand(0);
9722 SVInVec = InVec->getOperand(1);
9726 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9727 SDValue InOp = SVInVec.getOperand(OrigElt);
9728 if (InOp.getValueType() != NVT) {
9729 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9730 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9736 // FIXME: We should handle recursing on other vector shuffles and
9737 // scalar_to_vector here as well.
9739 if (!LegalOperations) {
9740 EVT IndexTy = TLI.getVectorIdxTy();
9741 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9742 SVInVec, DAG.getConstant(OrigElt, IndexTy));
9746 // Perform only after legalization to ensure build_vector / vector_shuffle
9747 // optimizations have already been done.
9748 if (!LegalOperations) return SDValue();
9750 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9751 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9752 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9755 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9756 bool NewLoad = false;
9757 bool BCNumEltsChanged = false;
9758 EVT ExtVT = VT.getVectorElementType();
9761 // If the result of load has to be truncated, then it's not necessarily
9763 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9766 if (InVec.getOpcode() == ISD::BITCAST) {
9767 // Don't duplicate a load with other uses.
9768 if (!InVec.hasOneUse())
9771 EVT BCVT = InVec.getOperand(0).getValueType();
9772 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9774 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9775 BCNumEltsChanged = true;
9776 InVec = InVec.getOperand(0);
9777 ExtVT = BCVT.getVectorElementType();
9781 LoadSDNode *LN0 = nullptr;
9782 const ShuffleVectorSDNode *SVN = nullptr;
9783 if (ISD::isNormalLoad(InVec.getNode())) {
9784 LN0 = cast<LoadSDNode>(InVec);
9785 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9786 InVec.getOperand(0).getValueType() == ExtVT &&
9787 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9788 // Don't duplicate a load with other uses.
9789 if (!InVec.hasOneUse())
9792 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9793 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9794 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9796 // (load $addr+1*size)
9798 // Don't duplicate a load with other uses.
9799 if (!InVec.hasOneUse())
9802 // If the bit convert changed the number of elements, it is unsafe
9803 // to examine the mask.
9804 if (BCNumEltsChanged)
9807 // Select the input vector, guarding against out of range extract vector.
9808 unsigned NumElems = VT.getVectorNumElements();
9809 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9810 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9812 if (InVec.getOpcode() == ISD::BITCAST) {
9813 // Don't duplicate a load with other uses.
9814 if (!InVec.hasOneUse())
9817 InVec = InVec.getOperand(0);
9819 if (ISD::isNormalLoad(InVec.getNode())) {
9820 LN0 = cast<LoadSDNode>(InVec);
9821 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9825 // Make sure we found a non-volatile load and the extractelement is
9827 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9830 // If Idx was -1 above, Elt is going to be -1, so just return undef.
9832 return DAG.getUNDEF(LVT);
9834 unsigned Align = LN0->getAlignment();
9836 // Check the resultant load doesn't need a higher alignment than the
9840 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9842 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9848 SDValue NewPtr = LN0->getBasePtr();
9849 unsigned PtrOff = 0;
9852 PtrOff = LVT.getSizeInBits() * Elt / 8;
9853 EVT PtrType = NewPtr.getValueType();
9854 if (TLI.isBigEndian())
9855 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9856 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9857 DAG.getConstant(PtrOff, PtrType));
9860 // The replacement we need to do here is a little tricky: we need to
9861 // replace an extractelement of a load with a load.
9862 // Use ReplaceAllUsesOfValuesWith to do the replacement.
9863 // Note that this replacement assumes that the extractvalue is the only
9864 // use of the load; that's okay because we don't want to perform this
9865 // transformation in other cases anyway.
9868 if (NVT.bitsGT(LVT)) {
9869 // If the result type of vextract is wider than the load, then issue an
9870 // extending load instead.
9871 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9872 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9873 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9874 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9875 LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9876 Align, LN0->getTBAAInfo());
9877 Chain = Load.getValue(1);
9879 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9880 LN0->getPointerInfo().getWithOffset(PtrOff),
9881 LN0->isVolatile(), LN0->isNonTemporal(),
9882 LN0->isInvariant(), Align, LN0->getTBAAInfo());
9883 Chain = Load.getValue(1);
9884 if (NVT.bitsLT(LVT))
9885 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
9887 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
9889 WorkListRemover DeadNodes(*this);
9890 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
9891 SDValue To[] = { Load, Chain };
9892 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9893 // Since we're explcitly calling ReplaceAllUses, add the new node to the
9894 // worklist explicitly as well.
9895 AddToWorkList(Load.getNode());
9896 AddUsersToWorkList(Load.getNode()); // Add users too
9897 // Make sure to revisit this node to clean it up; it will usually be dead.
9899 return SDValue(N, 0);
9905 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
9906 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9907 // We perform this optimization post type-legalization because
9908 // the type-legalizer often scalarizes integer-promoted vectors.
9909 // Performing this optimization before may create bit-casts which
9910 // will be type-legalized to complex code sequences.
9911 // We perform this optimization only before the operation legalizer because we
9912 // may introduce illegal operations.
9913 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9916 unsigned NumInScalars = N->getNumOperands();
9918 EVT VT = N->getValueType(0);
9920 // Check to see if this is a BUILD_VECTOR of a bunch of values
9921 // which come from any_extend or zero_extend nodes. If so, we can create
9922 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
9923 // optimizations. We do not handle sign-extend because we can't fill the sign
9925 EVT SourceType = MVT::Other;
9926 bool AllAnyExt = true;
9928 for (unsigned i = 0; i != NumInScalars; ++i) {
9929 SDValue In = N->getOperand(i);
9930 // Ignore undef inputs.
9931 if (In.getOpcode() == ISD::UNDEF) continue;
9933 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
9934 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9936 // Abort if the element is not an extension.
9937 if (!ZeroExt && !AnyExt) {
9938 SourceType = MVT::Other;
9942 // The input is a ZeroExt or AnyExt. Check the original type.
9943 EVT InTy = In.getOperand(0).getValueType();
9945 // Check that all of the widened source types are the same.
9946 if (SourceType == MVT::Other)
9949 else if (InTy != SourceType) {
9950 // Multiple income types. Abort.
9951 SourceType = MVT::Other;
9955 // Check if all of the extends are ANY_EXTENDs.
9956 AllAnyExt &= AnyExt;
9959 // In order to have valid types, all of the inputs must be extended from the
9960 // same source type and all of the inputs must be any or zero extend.
9961 // Scalar sizes must be a power of two.
9962 EVT OutScalarTy = VT.getScalarType();
9963 bool ValidTypes = SourceType != MVT::Other &&
9964 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9965 isPowerOf2_32(SourceType.getSizeInBits());
9967 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9968 // turn into a single shuffle instruction.
9972 bool isLE = TLI.isLittleEndian();
9973 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
9974 assert(ElemRatio > 1 && "Invalid element size ratio");
9975 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
9976 DAG.getConstant(0, SourceType);
9978 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
9979 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
9981 // Populate the new build_vector
9982 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9983 SDValue Cast = N->getOperand(i);
9984 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
9985 Cast.getOpcode() == ISD::ZERO_EXTEND ||
9986 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
9988 if (Cast.getOpcode() == ISD::UNDEF)
9989 In = DAG.getUNDEF(SourceType);
9991 In = Cast->getOperand(0);
9992 unsigned Index = isLE ? (i * ElemRatio) :
9993 (i * ElemRatio + (ElemRatio - 1));
9995 assert(Index < Ops.size() && "Invalid index");
9999 // The type of the new BUILD_VECTOR node.
10000 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10001 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10002 "Invalid vector size");
10003 // Check if the new vector type is legal.
10004 if (!isTypeLegal(VecVT)) return SDValue();
10006 // Make the new BUILD_VECTOR.
10007 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10009 // The new BUILD_VECTOR node has the potential to be further optimized.
10010 AddToWorkList(BV.getNode());
10011 // Bitcast to the desired type.
10012 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10015 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10016 EVT VT = N->getValueType(0);
10018 unsigned NumInScalars = N->getNumOperands();
10021 EVT SrcVT = MVT::Other;
10022 unsigned Opcode = ISD::DELETED_NODE;
10023 unsigned NumDefs = 0;
10025 for (unsigned i = 0; i != NumInScalars; ++i) {
10026 SDValue In = N->getOperand(i);
10027 unsigned Opc = In.getOpcode();
10029 if (Opc == ISD::UNDEF)
10032 // If all scalar values are floats and converted from integers.
10033 if (Opcode == ISD::DELETED_NODE &&
10034 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10041 EVT InVT = In.getOperand(0).getValueType();
10043 // If all scalar values are typed differently, bail out. It's chosen to
10044 // simplify BUILD_VECTOR of integer types.
10045 if (SrcVT == MVT::Other)
10052 // If the vector has just one element defined, it's not worth to fold it into
10053 // a vectorized one.
10057 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10058 && "Should only handle conversion from integer to float.");
10059 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10061 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10063 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10066 SmallVector<SDValue, 8> Opnds;
10067 for (unsigned i = 0; i != NumInScalars; ++i) {
10068 SDValue In = N->getOperand(i);
10070 if (In.getOpcode() == ISD::UNDEF)
10071 Opnds.push_back(DAG.getUNDEF(SrcVT));
10073 Opnds.push_back(In.getOperand(0));
10075 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10076 AddToWorkList(BV.getNode());
10078 return DAG.getNode(Opcode, dl, VT, BV);
10081 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10082 unsigned NumInScalars = N->getNumOperands();
10084 EVT VT = N->getValueType(0);
10086 // A vector built entirely of undefs is undef.
10087 if (ISD::allOperandsUndef(N))
10088 return DAG.getUNDEF(VT);
10090 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10094 V = reduceBuildVecConvertToConvertBuildVec(N);
10098 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10099 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10100 // at most two distinct vectors, turn this into a shuffle node.
10102 // May only combine to shuffle after legalize if shuffle is legal.
10103 if (LegalOperations &&
10104 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10107 SDValue VecIn1, VecIn2;
10108 for (unsigned i = 0; i != NumInScalars; ++i) {
10109 // Ignore undef inputs.
10110 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10112 // If this input is something other than a EXTRACT_VECTOR_ELT with a
10113 // constant index, bail out.
10114 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10115 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10116 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10120 // We allow up to two distinct input vectors.
10121 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10122 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10125 if (!VecIn1.getNode()) {
10126 VecIn1 = ExtractedFromVec;
10127 } else if (!VecIn2.getNode()) {
10128 VecIn2 = ExtractedFromVec;
10130 // Too many inputs.
10131 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10136 // If everything is good, we can make a shuffle operation.
10137 if (VecIn1.getNode()) {
10138 SmallVector<int, 8> Mask;
10139 for (unsigned i = 0; i != NumInScalars; ++i) {
10140 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10141 Mask.push_back(-1);
10145 // If extracting from the first vector, just use the index directly.
10146 SDValue Extract = N->getOperand(i);
10147 SDValue ExtVal = Extract.getOperand(1);
10148 if (Extract.getOperand(0) == VecIn1) {
10149 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10150 if (ExtIndex > VT.getVectorNumElements())
10153 Mask.push_back(ExtIndex);
10157 // Otherwise, use InIdx + VecSize
10158 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10159 Mask.push_back(Idx+NumInScalars);
10162 // We can't generate a shuffle node with mismatched input and output types.
10163 // Attempt to transform a single input vector to the correct type.
10164 if ((VT != VecIn1.getValueType())) {
10165 // We don't support shuffeling between TWO values of different types.
10166 if (VecIn2.getNode())
10169 // We only support widening of vectors which are half the size of the
10170 // output registers. For example XMM->YMM widening on X86 with AVX.
10171 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10174 // If the input vector type has a different base type to the output
10175 // vector type, bail out.
10176 if (VecIn1.getValueType().getVectorElementType() !=
10177 VT.getVectorElementType())
10180 // Widen the input vector by adding undef values.
10181 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10182 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10185 // If VecIn2 is unused then change it to undef.
10186 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10188 // Check that we were able to transform all incoming values to the same
10190 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10191 VecIn1.getValueType() != VT)
10194 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10195 if (!isTypeLegal(VT))
10198 // Return the new VECTOR_SHUFFLE node.
10202 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10208 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10209 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10210 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10211 // inputs come from at most two distinct vectors, turn this into a shuffle
10214 // If we only have one input vector, we don't need to do any concatenation.
10215 if (N->getNumOperands() == 1)
10216 return N->getOperand(0);
10218 // Check if all of the operands are undefs.
10219 EVT VT = N->getValueType(0);
10220 if (ISD::allOperandsUndef(N))
10221 return DAG.getUNDEF(VT);
10223 // Optimize concat_vectors where one of the vectors is undef.
10224 if (N->getNumOperands() == 2 &&
10225 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10226 SDValue In = N->getOperand(0);
10227 assert(In.getValueType().isVector() && "Must concat vectors");
10229 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10230 if (In->getOpcode() == ISD::BITCAST &&
10231 !In->getOperand(0)->getValueType(0).isVector()) {
10232 SDValue Scalar = In->getOperand(0);
10233 EVT SclTy = Scalar->getValueType(0);
10235 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10238 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10239 VT.getSizeInBits() / SclTy.getSizeInBits());
10240 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10243 SDLoc dl = SDLoc(N);
10244 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10245 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10249 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10250 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10251 if (N->getNumOperands() == 2 &&
10252 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10253 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10254 EVT VT = N->getValueType(0);
10255 SDValue N0 = N->getOperand(0);
10256 SDValue N1 = N->getOperand(1);
10257 SmallVector<SDValue, 8> Opnds;
10258 unsigned BuildVecNumElts = N0.getNumOperands();
10260 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10261 Opnds.push_back(N0.getOperand(i));
10262 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10263 Opnds.push_back(N1.getOperand(i));
10265 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10268 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10269 // nodes often generate nop CONCAT_VECTOR nodes.
10270 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10271 // place the incoming vectors at the exact same location.
10272 SDValue SingleSource = SDValue();
10273 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10275 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10276 SDValue Op = N->getOperand(i);
10278 if (Op.getOpcode() == ISD::UNDEF)
10281 // Check if this is the identity extract:
10282 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10285 // Find the single incoming vector for the extract_subvector.
10286 if (SingleSource.getNode()) {
10287 if (Op.getOperand(0) != SingleSource)
10290 SingleSource = Op.getOperand(0);
10292 // Check the source type is the same as the type of the result.
10293 // If not, this concat may extend the vector, so we can not
10294 // optimize it away.
10295 if (SingleSource.getValueType() != N->getValueType(0))
10299 unsigned IdentityIndex = i * PartNumElem;
10300 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10301 // The extract index must be constant.
10305 // Check that we are reading from the identity index.
10306 if (CS->getZExtValue() != IdentityIndex)
10310 if (SingleSource.getNode())
10311 return SingleSource;
10316 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10317 EVT NVT = N->getValueType(0);
10318 SDValue V = N->getOperand(0);
10320 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10322 // (extract_subvec (concat V1, V2, ...), i)
10325 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10327 if (V->getOperand(0).getValueType() != NVT)
10329 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10330 unsigned NumElems = NVT.getVectorNumElements();
10331 assert((Idx % NumElems) == 0 &&
10332 "IDX in concat is not a multiple of the result vector length.");
10333 return V->getOperand(Idx / NumElems);
10337 if (V->getOpcode() == ISD::BITCAST)
10338 V = V.getOperand(0);
10340 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10342 // Handle only simple case where vector being inserted and vector
10343 // being extracted are of same type, and are half size of larger vectors.
10344 EVT BigVT = V->getOperand(0).getValueType();
10345 EVT SmallVT = V->getOperand(1).getValueType();
10346 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10349 // Only handle cases where both indexes are constants with the same type.
10350 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10351 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10353 if (InsIdx && ExtIdx &&
10354 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10355 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10357 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10359 // indices are equal or bit offsets are equal => V1
10360 // otherwise => (extract_subvec V1, ExtIdx)
10361 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10362 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10363 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10364 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10365 DAG.getNode(ISD::BITCAST, dl,
10366 N->getOperand(0).getValueType(),
10367 V->getOperand(0)), N->getOperand(1));
10374 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10375 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10376 EVT VT = N->getValueType(0);
10377 unsigned NumElts = VT.getVectorNumElements();
10379 SDValue N0 = N->getOperand(0);
10380 SDValue N1 = N->getOperand(1);
10381 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10383 SmallVector<SDValue, 4> Ops;
10384 EVT ConcatVT = N0.getOperand(0).getValueType();
10385 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10386 unsigned NumConcats = NumElts / NumElemsPerConcat;
10388 // Look at every vector that's inserted. We're looking for exact
10389 // subvector-sized copies from a concatenated vector
10390 for (unsigned I = 0; I != NumConcats; ++I) {
10391 // Make sure we're dealing with a copy.
10392 unsigned Begin = I * NumElemsPerConcat;
10393 bool AllUndef = true, NoUndef = true;
10394 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10395 if (SVN->getMaskElt(J) >= 0)
10402 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10405 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10406 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10409 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10410 if (FirstElt < N0.getNumOperands())
10411 Ops.push_back(N0.getOperand(FirstElt));
10413 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10415 } else if (AllUndef) {
10416 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10417 } else { // Mixed with general masks and undefs, can't do optimization.
10422 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10425 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10426 EVT VT = N->getValueType(0);
10427 unsigned NumElts = VT.getVectorNumElements();
10429 SDValue N0 = N->getOperand(0);
10430 SDValue N1 = N->getOperand(1);
10432 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10434 // Canonicalize shuffle undef, undef -> undef
10435 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10436 return DAG.getUNDEF(VT);
10438 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10440 // Canonicalize shuffle v, v -> v, undef
10442 SmallVector<int, 8> NewMask;
10443 for (unsigned i = 0; i != NumElts; ++i) {
10444 int Idx = SVN->getMaskElt(i);
10445 if (Idx >= (int)NumElts) Idx -= NumElts;
10446 NewMask.push_back(Idx);
10448 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10452 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10453 if (N0.getOpcode() == ISD::UNDEF) {
10454 SmallVector<int, 8> NewMask;
10455 for (unsigned i = 0; i != NumElts; ++i) {
10456 int Idx = SVN->getMaskElt(i);
10458 if (Idx >= (int)NumElts)
10461 Idx = -1; // remove reference to lhs
10463 NewMask.push_back(Idx);
10465 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10469 // Remove references to rhs if it is undef
10470 if (N1.getOpcode() == ISD::UNDEF) {
10471 bool Changed = false;
10472 SmallVector<int, 8> NewMask;
10473 for (unsigned i = 0; i != NumElts; ++i) {
10474 int Idx = SVN->getMaskElt(i);
10475 if (Idx >= (int)NumElts) {
10479 NewMask.push_back(Idx);
10482 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10485 // If it is a splat, check if the argument vector is another splat or a
10486 // build_vector with all scalar elements the same.
10487 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10488 SDNode *V = N0.getNode();
10490 // If this is a bit convert that changes the element type of the vector but
10491 // not the number of vector elements, look through it. Be careful not to
10492 // look though conversions that change things like v4f32 to v2f64.
10493 if (V->getOpcode() == ISD::BITCAST) {
10494 SDValue ConvInput = V->getOperand(0);
10495 if (ConvInput.getValueType().isVector() &&
10496 ConvInput.getValueType().getVectorNumElements() == NumElts)
10497 V = ConvInput.getNode();
10500 if (V->getOpcode() == ISD::BUILD_VECTOR) {
10501 assert(V->getNumOperands() == NumElts &&
10502 "BUILD_VECTOR has wrong number of operands");
10504 bool AllSame = true;
10505 for (unsigned i = 0; i != NumElts; ++i) {
10506 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10507 Base = V->getOperand(i);
10511 // Splat of <u, u, u, u>, return <u, u, u, u>
10512 if (!Base.getNode())
10514 for (unsigned i = 0; i != NumElts; ++i) {
10515 if (V->getOperand(i) != Base) {
10520 // Splat of <x, x, x, x>, return <x, x, x, x>
10526 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10527 Level < AfterLegalizeVectorOps &&
10528 (N1.getOpcode() == ISD::UNDEF ||
10529 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10530 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10531 SDValue V = partitionShuffleOfConcats(N, DAG);
10537 // If this shuffle node is simply a swizzle of another shuffle node,
10538 // and it reverses the swizzle of the previous shuffle then we can
10539 // optimize shuffle(shuffle(x, undef), undef) -> x.
10540 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10541 N1.getOpcode() == ISD::UNDEF) {
10543 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10545 // Shuffle nodes can only reverse shuffles with a single non-undef value.
10546 if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10549 // The incoming shuffle must be of the same type as the result of the
10550 // current shuffle.
10551 assert(OtherSV->getOperand(0).getValueType() == VT &&
10552 "Shuffle types don't match");
10554 for (unsigned i = 0; i != NumElts; ++i) {
10555 int Idx = SVN->getMaskElt(i);
10556 assert(Idx < (int)NumElts && "Index references undef operand");
10557 // Next, this index comes from the first value, which is the incoming
10558 // shuffle. Adopt the incoming index.
10560 Idx = OtherSV->getMaskElt(Idx);
10562 // The combined shuffle must map each index to itself.
10563 if (Idx >= 0 && (unsigned)Idx != i)
10567 return OtherSV->getOperand(0);
10573 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10574 SDValue N0 = N->getOperand(0);
10575 SDValue N2 = N->getOperand(2);
10577 // If the input vector is a concatenation, and the insert replaces
10578 // one of the halves, we can optimize into a single concat_vectors.
10579 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10580 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10581 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10582 EVT VT = N->getValueType(0);
10584 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10585 // (concat_vectors Z, Y)
10587 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10588 N->getOperand(1), N0.getOperand(1));
10590 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10591 // (concat_vectors X, Z)
10592 if (InsIdx == VT.getVectorNumElements()/2)
10593 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10594 N0.getOperand(0), N->getOperand(1));
10600 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10601 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10602 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10603 /// vector_shuffle V, Zero, <0, 4, 2, 4>
10604 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10605 EVT VT = N->getValueType(0);
10607 SDValue LHS = N->getOperand(0);
10608 SDValue RHS = N->getOperand(1);
10609 if (N->getOpcode() == ISD::AND) {
10610 if (RHS.getOpcode() == ISD::BITCAST)
10611 RHS = RHS.getOperand(0);
10612 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10613 SmallVector<int, 8> Indices;
10614 unsigned NumElts = RHS.getNumOperands();
10615 for (unsigned i = 0; i != NumElts; ++i) {
10616 SDValue Elt = RHS.getOperand(i);
10617 if (!isa<ConstantSDNode>(Elt))
10620 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10621 Indices.push_back(i);
10622 else if (cast<ConstantSDNode>(Elt)->isNullValue())
10623 Indices.push_back(NumElts);
10628 // Let's see if the target supports this vector_shuffle.
10629 EVT RVT = RHS.getValueType();
10630 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10633 // Return the new VECTOR_SHUFFLE node.
10634 EVT EltVT = RVT.getVectorElementType();
10635 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10636 DAG.getConstant(0, EltVT));
10637 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
10638 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10639 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10640 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10647 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10648 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10649 assert(N->getValueType(0).isVector() &&
10650 "SimplifyVBinOp only works on vectors!");
10652 SDValue LHS = N->getOperand(0);
10653 SDValue RHS = N->getOperand(1);
10654 SDValue Shuffle = XformToShuffleWithZero(N);
10655 if (Shuffle.getNode()) return Shuffle;
10657 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10659 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10660 RHS.getOpcode() == ISD::BUILD_VECTOR) {
10661 // Check if both vectors are constants. If not bail out.
10662 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10663 cast<BuildVectorSDNode>(RHS)->isConstant()))
10666 SmallVector<SDValue, 8> Ops;
10667 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10668 SDValue LHSOp = LHS.getOperand(i);
10669 SDValue RHSOp = RHS.getOperand(i);
10671 // Can't fold divide by zero.
10672 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10673 N->getOpcode() == ISD::FDIV) {
10674 if ((RHSOp.getOpcode() == ISD::Constant &&
10675 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10676 (RHSOp.getOpcode() == ISD::ConstantFP &&
10677 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10681 EVT VT = LHSOp.getValueType();
10682 EVT RVT = RHSOp.getValueType();
10684 // Integer BUILD_VECTOR operands may have types larger than the element
10685 // size (e.g., when the element type is not legal). Prior to type
10686 // legalization, the types may not match between the two BUILD_VECTORS.
10687 // Truncate one of the operands to make them match.
10688 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10689 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10691 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10695 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10697 if (FoldOp.getOpcode() != ISD::UNDEF &&
10698 FoldOp.getOpcode() != ISD::Constant &&
10699 FoldOp.getOpcode() != ISD::ConstantFP)
10701 Ops.push_back(FoldOp);
10702 AddToWorkList(FoldOp.getNode());
10705 if (Ops.size() == LHS.getNumOperands())
10706 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
10712 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10713 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10714 assert(N->getValueType(0).isVector() &&
10715 "SimplifyVUnaryOp only works on vectors!");
10717 SDValue N0 = N->getOperand(0);
10719 if (N0.getOpcode() != ISD::BUILD_VECTOR)
10722 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10723 SmallVector<SDValue, 8> Ops;
10724 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10725 SDValue Op = N0.getOperand(i);
10726 if (Op.getOpcode() != ISD::UNDEF &&
10727 Op.getOpcode() != ISD::ConstantFP)
10729 EVT EltVT = Op.getValueType();
10730 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
10731 if (FoldOp.getOpcode() != ISD::UNDEF &&
10732 FoldOp.getOpcode() != ISD::ConstantFP)
10734 Ops.push_back(FoldOp);
10735 AddToWorkList(FoldOp.getNode());
10738 if (Ops.size() != N0.getNumOperands())
10741 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
10744 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10745 SDValue N1, SDValue N2){
10746 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10748 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
10749 cast<CondCodeSDNode>(N0.getOperand(2))->get());
10751 // If we got a simplified select_cc node back from SimplifySelectCC, then
10752 // break it down into a new SETCC node, and a new SELECT node, and then return
10753 // the SELECT node, since we were called with a SELECT node.
10754 if (SCC.getNode()) {
10755 // Check to see if we got a select_cc back (to turn into setcc/select).
10756 // Otherwise, just return whatever node we got back, like fabs.
10757 if (SCC.getOpcode() == ISD::SELECT_CC) {
10758 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
10760 SCC.getOperand(0), SCC.getOperand(1),
10761 SCC.getOperand(4));
10762 AddToWorkList(SETCC.getNode());
10763 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10764 SCC.getOperand(2), SCC.getOperand(3), SETCC);
10772 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10773 /// are the two values being selected between, see if we can simplify the
10774 /// select. Callers of this should assume that TheSelect is deleted if this
10775 /// returns true. As such, they should return the appropriate thing (e.g. the
10776 /// node) back to the top-level of the DAG combiner loop to avoid it being
10778 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
10781 // Cannot simplify select with vector condition
10782 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10784 // If this is a select from two identical things, try to pull the operation
10785 // through the select.
10786 if (LHS.getOpcode() != RHS.getOpcode() ||
10787 !LHS.hasOneUse() || !RHS.hasOneUse())
10790 // If this is a load and the token chain is identical, replace the select
10791 // of two loads with a load through a select of the address to load from.
10792 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10793 // constants have been dropped into the constant pool.
10794 if (LHS.getOpcode() == ISD::LOAD) {
10795 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10796 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
10798 // Token chains must be identical.
10799 if (LHS.getOperand(0) != RHS.getOperand(0) ||
10800 // Do not let this transformation reduce the number of volatile loads.
10801 LLD->isVolatile() || RLD->isVolatile() ||
10802 // If this is an EXTLOAD, the VT's must match.
10803 LLD->getMemoryVT() != RLD->getMemoryVT() ||
10804 // If this is an EXTLOAD, the kind of extension must match.
10805 (LLD->getExtensionType() != RLD->getExtensionType() &&
10806 // The only exception is if one of the extensions is anyext.
10807 LLD->getExtensionType() != ISD::EXTLOAD &&
10808 RLD->getExtensionType() != ISD::EXTLOAD) ||
10809 // FIXME: this discards src value information. This is
10810 // over-conservative. It would be beneficial to be able to remember
10811 // both potential memory locations. Since we are discarding
10812 // src value info, don't do the transformation if the memory
10813 // locations are not in the default address space.
10814 LLD->getPointerInfo().getAddrSpace() != 0 ||
10815 RLD->getPointerInfo().getAddrSpace() != 0 ||
10816 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10817 LLD->getBasePtr().getValueType()))
10820 // Check that the select condition doesn't reach either load. If so,
10821 // folding this will induce a cycle into the DAG. If not, this is safe to
10822 // xform, so create a select of the addresses.
10824 if (TheSelect->getOpcode() == ISD::SELECT) {
10825 SDNode *CondNode = TheSelect->getOperand(0).getNode();
10826 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10827 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10829 // The loads must not depend on one another.
10830 if (LLD->isPredecessorOf(RLD) ||
10831 RLD->isPredecessorOf(LLD))
10833 Addr = DAG.getSelect(SDLoc(TheSelect),
10834 LLD->getBasePtr().getValueType(),
10835 TheSelect->getOperand(0), LLD->getBasePtr(),
10836 RLD->getBasePtr());
10837 } else { // Otherwise SELECT_CC
10838 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10839 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10841 if ((LLD->hasAnyUseOfValue(1) &&
10842 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
10843 (RLD->hasAnyUseOfValue(1) &&
10844 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
10847 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
10848 LLD->getBasePtr().getValueType(),
10849 TheSelect->getOperand(0),
10850 TheSelect->getOperand(1),
10851 LLD->getBasePtr(), RLD->getBasePtr(),
10852 TheSelect->getOperand(4));
10856 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10857 Load = DAG.getLoad(TheSelect->getValueType(0),
10859 // FIXME: Discards pointer and TBAA info.
10860 LLD->getChain(), Addr, MachinePointerInfo(),
10861 LLD->isVolatile(), LLD->isNonTemporal(),
10862 LLD->isInvariant(), LLD->getAlignment());
10864 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10865 RLD->getExtensionType() : LLD->getExtensionType(),
10867 TheSelect->getValueType(0),
10868 // FIXME: Discards pointer and TBAA info.
10869 LLD->getChain(), Addr, MachinePointerInfo(),
10870 LLD->getMemoryVT(), LLD->isVolatile(),
10871 LLD->isNonTemporal(), LLD->getAlignment());
10874 // Users of the select now use the result of the load.
10875 CombineTo(TheSelect, Load);
10877 // Users of the old loads now use the new load's chain. We know the
10878 // old-load value is dead now.
10879 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10880 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10887 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10888 /// where 'cond' is the comparison specified by CC.
10889 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
10890 SDValue N2, SDValue N3,
10891 ISD::CondCode CC, bool NotExtCompare) {
10892 // (x ? y : y) -> y.
10893 if (N2 == N3) return N2;
10895 EVT VT = N2.getValueType();
10896 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10897 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10898 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
10900 // Determine if the condition we're dealing with is constant
10901 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
10902 N0, N1, CC, DL, false);
10903 if (SCC.getNode()) AddToWorkList(SCC.getNode());
10904 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
10906 // fold select_cc true, x, y -> x
10907 if (SCCC && !SCCC->isNullValue())
10909 // fold select_cc false, x, y -> y
10910 if (SCCC && SCCC->isNullValue())
10913 // Check to see if we can simplify the select into an fabs node
10914 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10915 // Allow either -0.0 or 0.0
10916 if (CFP->getValueAPF().isZero()) {
10917 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10918 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10919 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10920 N2 == N3.getOperand(0))
10921 return DAG.getNode(ISD::FABS, DL, VT, N0);
10923 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10924 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10925 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10926 N2.getOperand(0) == N3)
10927 return DAG.getNode(ISD::FABS, DL, VT, N3);
10931 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10932 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10933 // in it. This is a win when the constant is not otherwise available because
10934 // it replaces two constant pool loads with one. We only do this if the FP
10935 // type is known to be legal, because if it isn't, then we are before legalize
10936 // types an we want the other legalization to happen first (e.g. to avoid
10937 // messing with soft float) and if the ConstantFP is not legal, because if
10938 // it is legal, we may not need to store the FP constant in a constant pool.
10939 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10940 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10941 if (TLI.isTypeLegal(N2.getValueType()) &&
10942 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10943 TargetLowering::Legal &&
10944 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
10945 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
10946 // If both constants have multiple uses, then we won't need to do an
10947 // extra load, they are likely around in registers for other users.
10948 (TV->hasOneUse() || FV->hasOneUse())) {
10949 Constant *Elts[] = {
10950 const_cast<ConstantFP*>(FV->getConstantFPValue()),
10951 const_cast<ConstantFP*>(TV->getConstantFPValue())
10953 Type *FPTy = Elts[0]->getType();
10954 const DataLayout &TD = *TLI.getDataLayout();
10956 // Create a ConstantArray of the two constants.
10957 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
10958 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10959 TD.getPrefTypeAlignment(FPTy));
10960 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10962 // Get the offsets to the 0 and 1 element of the array so that we can
10963 // select between them.
10964 SDValue Zero = DAG.getIntPtrConstant(0);
10965 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
10966 SDValue One = DAG.getIntPtrConstant(EltSize);
10968 SDValue Cond = DAG.getSetCC(DL,
10969 getSetCCResultType(N0.getValueType()),
10971 AddToWorkList(Cond.getNode());
10972 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
10974 AddToWorkList(CstOffset.getNode());
10975 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
10977 AddToWorkList(CPIdx.getNode());
10978 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
10979 MachinePointerInfo::getConstantPool(), false,
10980 false, false, Alignment);
10985 // Check to see if we can perform the "gzip trick", transforming
10986 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
10987 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
10988 (N1C->isNullValue() || // (a < 0) ? b : 0
10989 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
10990 EVT XType = N0.getValueType();
10991 EVT AType = N2.getValueType();
10992 if (XType.bitsGE(AType)) {
10993 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
10994 // single-bit constant.
10995 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
10996 unsigned ShCtV = N2C->getAPIntValue().logBase2();
10997 ShCtV = XType.getSizeInBits()-ShCtV-1;
10998 SDValue ShCt = DAG.getConstant(ShCtV,
10999 getShiftAmountTy(N0.getValueType()));
11000 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11002 AddToWorkList(Shift.getNode());
11004 if (XType.bitsGT(AType)) {
11005 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11006 AddToWorkList(Shift.getNode());
11009 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11012 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11014 DAG.getConstant(XType.getSizeInBits()-1,
11015 getShiftAmountTy(N0.getValueType())));
11016 AddToWorkList(Shift.getNode());
11018 if (XType.bitsGT(AType)) {
11019 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11020 AddToWorkList(Shift.getNode());
11023 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11027 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11028 // where y is has a single bit set.
11029 // A plaintext description would be, we can turn the SELECT_CC into an AND
11030 // when the condition can be materialized as an all-ones register. Any
11031 // single bit-test can be materialized as an all-ones register with
11032 // shift-left and shift-right-arith.
11033 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11034 N0->getValueType(0) == VT &&
11035 N1C && N1C->isNullValue() &&
11036 N2C && N2C->isNullValue()) {
11037 SDValue AndLHS = N0->getOperand(0);
11038 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11039 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11040 // Shift the tested bit over the sign bit.
11041 APInt AndMask = ConstAndRHS->getAPIntValue();
11043 DAG.getConstant(AndMask.countLeadingZeros(),
11044 getShiftAmountTy(AndLHS.getValueType()));
11045 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11047 // Now arithmetic right shift it all the way over, so the result is either
11048 // all-ones, or zero.
11050 DAG.getConstant(AndMask.getBitWidth()-1,
11051 getShiftAmountTy(Shl.getValueType()));
11052 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11054 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11058 // fold select C, 16, 0 -> shl C, 4
11059 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11060 TLI.getBooleanContents(N0.getValueType().isVector()) ==
11061 TargetLowering::ZeroOrOneBooleanContent) {
11063 // If the caller doesn't want us to simplify this into a zext of a compare,
11065 if (NotExtCompare && N2C->getAPIntValue() == 1)
11068 // Get a SetCC of the condition
11069 // NOTE: Don't create a SETCC if it's not legal on this target.
11070 if (!LegalOperations ||
11071 TLI.isOperationLegal(ISD::SETCC,
11072 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11074 // cast from setcc result type to select result type
11076 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11078 if (N2.getValueType().bitsLT(SCC.getValueType()))
11079 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11080 N2.getValueType());
11082 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11083 N2.getValueType(), SCC);
11085 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11086 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11087 N2.getValueType(), SCC);
11090 AddToWorkList(SCC.getNode());
11091 AddToWorkList(Temp.getNode());
11093 if (N2C->getAPIntValue() == 1)
11096 // shl setcc result by log2 n2c
11097 return DAG.getNode(
11098 ISD::SHL, DL, N2.getValueType(), Temp,
11099 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11100 getShiftAmountTy(Temp.getValueType())));
11104 // Check to see if this is the equivalent of setcc
11105 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11106 // otherwise, go ahead with the folds.
11107 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11108 EVT XType = N0.getValueType();
11109 if (!LegalOperations ||
11110 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11111 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11112 if (Res.getValueType() != VT)
11113 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11117 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11118 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11119 (!LegalOperations ||
11120 TLI.isOperationLegal(ISD::CTLZ, XType))) {
11121 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11122 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11123 DAG.getConstant(Log2_32(XType.getSizeInBits()),
11124 getShiftAmountTy(Ctlz.getValueType())));
11126 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11127 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11128 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11129 XType, DAG.getConstant(0, XType), N0);
11130 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11131 return DAG.getNode(ISD::SRL, DL, XType,
11132 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11133 DAG.getConstant(XType.getSizeInBits()-1,
11134 getShiftAmountTy(XType)));
11136 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11137 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11138 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11139 DAG.getConstant(XType.getSizeInBits()-1,
11140 getShiftAmountTy(N0.getValueType())));
11141 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11145 // Check to see if this is an integer abs.
11146 // select_cc setg[te] X, 0, X, -X ->
11147 // select_cc setgt X, -1, X, -X ->
11148 // select_cc setl[te] X, 0, -X, X ->
11149 // select_cc setlt X, 1, -X, X ->
11150 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11152 ConstantSDNode *SubC = nullptr;
11153 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11154 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11155 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11156 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11157 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11158 (N1C->isOne() && CC == ISD::SETLT)) &&
11159 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11160 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11162 EVT XType = N0.getValueType();
11163 if (SubC && SubC->isNullValue() && XType.isInteger()) {
11164 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11166 DAG.getConstant(XType.getSizeInBits()-1,
11167 getShiftAmountTy(N0.getValueType())));
11168 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11170 AddToWorkList(Shift.getNode());
11171 AddToWorkList(Add.getNode());
11172 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11179 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11180 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11181 SDValue N1, ISD::CondCode Cond,
11182 SDLoc DL, bool foldBooleans) {
11183 TargetLowering::DAGCombinerInfo
11184 DagCombineInfo(DAG, Level, false, this);
11185 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11188 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11189 /// return a DAG expression to select that will generate the same value by
11190 /// multiplying by a magic number. See:
11191 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11192 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11193 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11197 // Avoid division by zero.
11198 if (!C->getAPIntValue())
11201 std::vector<SDNode*> Built;
11203 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11205 for (SDNode *N : Built)
11210 /// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant,
11211 /// return a DAG expression to select that will generate the same value by
11212 /// multiplying by a magic number. See:
11213 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11214 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11215 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11219 // Avoid division by zero.
11220 if (!C->getAPIntValue())
11223 std::vector<SDNode*> Built;
11225 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11227 for (SDNode *N : Built)
11232 /// FindBaseOffset - Return true if base is a frame index, which is known not
11233 // to alias with anything but itself. Provides base object and offset as
11235 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11236 const GlobalValue *&GV, const void *&CV) {
11237 // Assume it is a primitive operation.
11238 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11240 // If it's an adding a simple constant then integrate the offset.
11241 if (Base.getOpcode() == ISD::ADD) {
11242 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11243 Base = Base.getOperand(0);
11244 Offset += C->getZExtValue();
11248 // Return the underlying GlobalValue, and update the Offset. Return false
11249 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11250 // by multiple nodes with different offsets.
11251 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11252 GV = G->getGlobal();
11253 Offset += G->getOffset();
11257 // Return the underlying Constant value, and update the Offset. Return false
11258 // for ConstantSDNodes since the same constant pool entry may be represented
11259 // by multiple nodes with different offsets.
11260 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11261 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11262 : (const void *)C->getConstVal();
11263 Offset += C->getOffset();
11266 // If it's any of the following then it can't alias with anything but itself.
11267 return isa<FrameIndexSDNode>(Base);
11270 /// isAlias - Return true if there is any possibility that the two addresses
11272 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11273 // If they are the same then they must be aliases.
11274 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11276 // If they are both volatile then they cannot be reordered.
11277 if (Op0->isVolatile() && Op1->isVolatile()) return true;
11279 // Gather base node and offset information.
11280 SDValue Base1, Base2;
11281 int64_t Offset1, Offset2;
11282 const GlobalValue *GV1, *GV2;
11283 const void *CV1, *CV2;
11284 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11285 Base1, Offset1, GV1, CV1);
11286 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11287 Base2, Offset2, GV2, CV2);
11289 // If they have a same base address then check to see if they overlap.
11290 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11291 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11292 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11294 // It is possible for different frame indices to alias each other, mostly
11295 // when tail call optimization reuses return address slots for arguments.
11296 // To catch this case, look up the actual index of frame indices to compute
11297 // the real alias relationship.
11298 if (isFrameIndex1 && isFrameIndex2) {
11299 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11300 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11301 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11302 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11303 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11306 // Otherwise, if we know what the bases are, and they aren't identical, then
11307 // we know they cannot alias.
11308 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11311 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11312 // compared to the size and offset of the access, we may be able to prove they
11313 // do not alias. This check is conservative for now to catch cases created by
11314 // splitting vector types.
11315 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11316 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11317 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11318 Op1->getMemoryVT().getSizeInBits() >> 3) &&
11319 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11320 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11321 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11323 // There is no overlap between these relatively aligned accesses of similar
11324 // size, return no alias.
11325 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11326 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11330 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11331 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11333 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11334 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11338 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11339 // Use alias analysis information.
11340 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11341 Op1->getSrcValueOffset());
11342 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11343 Op0->getSrcValueOffset() - MinOffset;
11344 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11345 Op1->getSrcValueOffset() - MinOffset;
11346 AliasAnalysis::AliasResult AAResult =
11347 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11349 UseTBAA ? Op0->getTBAAInfo() : nullptr),
11350 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11352 UseTBAA ? Op1->getTBAAInfo() : nullptr));
11353 if (AAResult == AliasAnalysis::NoAlias)
11357 // Otherwise we have to assume they alias.
11361 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11362 /// looking for aliasing nodes and adding them to the Aliases vector.
11363 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11364 SmallVectorImpl<SDValue> &Aliases) {
11365 SmallVector<SDValue, 8> Chains; // List of chains to visit.
11366 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
11368 // Get alias information for node.
11369 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11372 Chains.push_back(OriginalChain);
11373 unsigned Depth = 0;
11375 // Look at each chain and determine if it is an alias. If so, add it to the
11376 // aliases list. If not, then continue up the chain looking for the next
11378 while (!Chains.empty()) {
11379 SDValue Chain = Chains.back();
11382 // For TokenFactor nodes, look at each operand and only continue up the
11383 // chain until we find two aliases. If we've seen two aliases, assume we'll
11384 // find more and revert to original chain since the xform is unlikely to be
11387 // FIXME: The depth check could be made to return the last non-aliasing
11388 // chain we found before we hit a tokenfactor rather than the original
11390 if (Depth > 6 || Aliases.size() == 2) {
11392 Aliases.push_back(OriginalChain);
11396 // Don't bother if we've been before.
11397 if (!Visited.insert(Chain.getNode()))
11400 switch (Chain.getOpcode()) {
11401 case ISD::EntryToken:
11402 // Entry token is ideal chain operand, but handled in FindBetterChain.
11407 // Get alias information for Chain.
11408 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11409 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11411 // If chain is alias then stop here.
11412 if (!(IsLoad && IsOpLoad) &&
11413 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11414 Aliases.push_back(Chain);
11416 // Look further up the chain.
11417 Chains.push_back(Chain.getOperand(0));
11423 case ISD::TokenFactor:
11424 // We have to check each of the operands of the token factor for "small"
11425 // token factors, so we queue them up. Adding the operands to the queue
11426 // (stack) in reverse order maintains the original order and increases the
11427 // likelihood that getNode will find a matching token factor (CSE.)
11428 if (Chain.getNumOperands() > 16) {
11429 Aliases.push_back(Chain);
11432 for (unsigned n = Chain.getNumOperands(); n;)
11433 Chains.push_back(Chain.getOperand(--n));
11438 // For all other instructions we will just have to take what we can get.
11439 Aliases.push_back(Chain);
11444 // We need to be careful here to also search for aliases through the
11445 // value operand of a store, etc. Consider the following situation:
11447 // L1 = load Token1, %52
11448 // S1 = store Token1, L1, %51
11449 // L2 = load Token1, %52+8
11450 // S2 = store Token1, L2, %51+8
11451 // Token2 = Token(S1, S2)
11452 // L3 = load Token2, %53
11453 // S3 = store Token2, L3, %52
11454 // L4 = load Token2, %53+8
11455 // S4 = store Token2, L4, %52+8
11456 // If we search for aliases of S3 (which loads address %52), and we look
11457 // only through the chain, then we'll miss the trivial dependence on L1
11458 // (which also loads from %52). We then might change all loads and
11459 // stores to use Token1 as their chain operand, which could result in
11460 // copying %53 into %52 before copying %52 into %51 (which should
11463 // The problem is, however, that searching for such data dependencies
11464 // can become expensive, and the cost is not directly related to the
11465 // chain depth. Instead, we'll rule out such configurations here by
11466 // insisting that we've visited all chain users (except for users
11467 // of the original chain, which is not necessary). When doing this,
11468 // we need to look through nodes we don't care about (otherwise, things
11469 // like register copies will interfere with trivial cases).
11471 SmallVector<const SDNode *, 16> Worklist;
11472 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11473 IE = Visited.end(); I != IE; ++I)
11474 if (*I != OriginalChain.getNode())
11475 Worklist.push_back(*I);
11477 while (!Worklist.empty()) {
11478 const SDNode *M = Worklist.pop_back_val();
11480 // We have already visited M, and want to make sure we've visited any uses
11481 // of M that we care about. For uses that we've not visisted, and don't
11482 // care about, queue them to the worklist.
11484 for (SDNode::use_iterator UI = M->use_begin(),
11485 UIE = M->use_end(); UI != UIE; ++UI)
11486 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11487 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11488 // We've not visited this use, and we care about it (it could have an
11489 // ordering dependency with the original node).
11491 Aliases.push_back(OriginalChain);
11495 // We've not visited this use, but we don't care about it. Mark it as
11496 // visited and enqueue it to the worklist.
11497 Worklist.push_back(*UI);
11502 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11503 /// for a better chain (aliasing node.)
11504 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11505 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
11507 // Accumulate all the aliases to this node.
11508 GatherAllAliases(N, OldChain, Aliases);
11510 // If no operands then chain to entry token.
11511 if (Aliases.size() == 0)
11512 return DAG.getEntryNode();
11514 // If a single operand then chain to it. We don't need to revisit it.
11515 if (Aliases.size() == 1)
11518 // Construct a custom tailored token factor.
11519 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
11522 // SelectionDAG::Combine - This is the entry point for the file.
11524 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11525 CodeGenOpt::Level OptLevel) {
11526 /// run - This is the main entry point to this class.
11528 DAGCombiner(*this, AA, OptLevel).Run(Level);