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 return BV->getConstantSplatValue();
653 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
654 SDValue N0, SDValue N1) {
655 EVT VT = N0.getValueType();
656 if (N0.getOpcode() == Opc) {
657 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
658 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
659 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
660 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
661 if (!OpNode.getNode())
663 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
665 if (N0.hasOneUse()) {
666 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
668 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
669 if (!OpNode.getNode())
671 AddToWorkList(OpNode.getNode());
672 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
677 if (N1.getOpcode() == Opc) {
678 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
679 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
680 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
681 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
682 if (!OpNode.getNode())
684 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
686 if (N1.hasOneUse()) {
687 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
689 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
690 if (!OpNode.getNode())
692 AddToWorkList(OpNode.getNode());
693 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
701 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
703 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
705 DEBUG(dbgs() << "\nReplacing.1 ";
707 dbgs() << "\nWith: ";
708 To[0].getNode()->dump(&DAG);
709 dbgs() << " and " << NumTo-1 << " other values\n";
710 for (unsigned i = 0, e = NumTo; i != e; ++i)
711 assert((!To[i].getNode() ||
712 N->getValueType(i) == To[i].getValueType()) &&
713 "Cannot combine value to value of different type!"));
714 WorkListRemover DeadNodes(*this);
715 DAG.ReplaceAllUsesWith(N, To);
717 // Push the new nodes and any users onto the worklist
718 for (unsigned i = 0, e = NumTo; i != e; ++i) {
719 if (To[i].getNode()) {
720 AddToWorkList(To[i].getNode());
721 AddUsersToWorkList(To[i].getNode());
726 // Finally, if the node is now dead, remove it from the graph. The node
727 // may not be dead if the replacement process recursively simplified to
728 // something else needing this node.
729 if (N->use_empty()) {
730 // Nodes can be reintroduced into the worklist. Make sure we do not
731 // process a node that has been replaced.
732 removeFromWorkList(N);
734 // Finally, since the node is now dead, remove it from the graph.
737 return SDValue(N, 0);
741 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
742 // Replace all uses. If any nodes become isomorphic to other nodes and
743 // are deleted, make sure to remove them from our worklist.
744 WorkListRemover DeadNodes(*this);
745 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
747 // Push the new node and any (possibly new) users onto the worklist.
748 AddToWorkList(TLO.New.getNode());
749 AddUsersToWorkList(TLO.New.getNode());
751 // Finally, if the node is now dead, remove it from the graph. The node
752 // may not be dead if the replacement process recursively simplified to
753 // something else needing this node.
754 if (TLO.Old.getNode()->use_empty()) {
755 removeFromWorkList(TLO.Old.getNode());
757 // If the operands of this node are only used by the node, they will now
758 // be dead. Make sure to visit them first to delete dead nodes early.
759 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
760 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
761 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
763 DAG.DeleteNode(TLO.Old.getNode());
767 /// SimplifyDemandedBits - Check the specified integer node value to see if
768 /// it can be simplified or if things it uses can be simplified by bit
769 /// propagation. If so, return true.
770 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
771 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
772 APInt KnownZero, KnownOne;
773 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
777 AddToWorkList(Op.getNode());
779 // Replace the old value with the new one.
781 DEBUG(dbgs() << "\nReplacing.2 ";
782 TLO.Old.getNode()->dump(&DAG);
783 dbgs() << "\nWith: ";
784 TLO.New.getNode()->dump(&DAG);
787 CommitTargetLoweringOpt(TLO);
791 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
793 EVT VT = Load->getValueType(0);
794 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
796 DEBUG(dbgs() << "\nReplacing.9 ";
798 dbgs() << "\nWith: ";
799 Trunc.getNode()->dump(&DAG);
801 WorkListRemover DeadNodes(*this);
802 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
803 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
804 removeFromWorkList(Load);
805 DAG.DeleteNode(Load);
806 AddToWorkList(Trunc.getNode());
809 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
812 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
813 EVT MemVT = LD->getMemoryVT();
814 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
815 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
817 : LD->getExtensionType();
819 return DAG.getExtLoad(ExtType, dl, PVT,
820 LD->getChain(), LD->getBasePtr(),
821 MemVT, LD->getMemOperand());
824 unsigned Opc = Op.getOpcode();
827 case ISD::AssertSext:
828 return DAG.getNode(ISD::AssertSext, dl, PVT,
829 SExtPromoteOperand(Op.getOperand(0), PVT),
831 case ISD::AssertZext:
832 return DAG.getNode(ISD::AssertZext, dl, PVT,
833 ZExtPromoteOperand(Op.getOperand(0), PVT),
835 case ISD::Constant: {
837 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
838 return DAG.getNode(ExtOpc, dl, PVT, Op);
842 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
844 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
847 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
848 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
850 EVT OldVT = Op.getValueType();
852 bool Replace = false;
853 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
854 if (!NewOp.getNode())
856 AddToWorkList(NewOp.getNode());
859 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
860 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
861 DAG.getValueType(OldVT));
864 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
865 EVT OldVT = Op.getValueType();
867 bool Replace = false;
868 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
869 if (!NewOp.getNode())
871 AddToWorkList(NewOp.getNode());
874 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
875 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
878 /// PromoteIntBinOp - Promote the specified integer binary operation if the
879 /// target indicates it is beneficial. e.g. On x86, it's usually better to
880 /// promote i16 operations to i32 since i16 instructions are longer.
881 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
882 if (!LegalOperations)
885 EVT VT = Op.getValueType();
886 if (VT.isVector() || !VT.isInteger())
889 // If operation type is 'undesirable', e.g. i16 on x86, consider
891 unsigned Opc = Op.getOpcode();
892 if (TLI.isTypeDesirableForOp(Opc, VT))
896 // Consult target whether it is a good idea to promote this operation and
897 // what's the right type to promote it to.
898 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
899 assert(PVT != VT && "Don't know what type to promote to!");
901 bool Replace0 = false;
902 SDValue N0 = Op.getOperand(0);
903 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
907 bool Replace1 = false;
908 SDValue N1 = Op.getOperand(1);
913 NN1 = PromoteOperand(N1, PVT, Replace1);
918 AddToWorkList(NN0.getNode());
920 AddToWorkList(NN1.getNode());
923 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
925 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
927 DEBUG(dbgs() << "\nPromoting ";
928 Op.getNode()->dump(&DAG));
930 return DAG.getNode(ISD::TRUNCATE, dl, VT,
931 DAG.getNode(Opc, dl, PVT, NN0, NN1));
936 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
937 /// target indicates it is beneficial. e.g. On x86, it's usually better to
938 /// promote i16 operations to i32 since i16 instructions are longer.
939 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
940 if (!LegalOperations)
943 EVT VT = Op.getValueType();
944 if (VT.isVector() || !VT.isInteger())
947 // If operation type is 'undesirable', e.g. i16 on x86, consider
949 unsigned Opc = Op.getOpcode();
950 if (TLI.isTypeDesirableForOp(Opc, VT))
954 // Consult target whether it is a good idea to promote this operation and
955 // what's the right type to promote it to.
956 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
957 assert(PVT != VT && "Don't know what type to promote to!");
959 bool Replace = false;
960 SDValue N0 = Op.getOperand(0);
962 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
963 else if (Opc == ISD::SRL)
964 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
966 N0 = PromoteOperand(N0, PVT, Replace);
970 AddToWorkList(N0.getNode());
972 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
974 DEBUG(dbgs() << "\nPromoting ";
975 Op.getNode()->dump(&DAG));
977 return DAG.getNode(ISD::TRUNCATE, dl, VT,
978 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
983 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
984 if (!LegalOperations)
987 EVT VT = Op.getValueType();
988 if (VT.isVector() || !VT.isInteger())
991 // If operation type is 'undesirable', e.g. i16 on x86, consider
993 unsigned Opc = Op.getOpcode();
994 if (TLI.isTypeDesirableForOp(Opc, VT))
998 // Consult target whether it is a good idea to promote this operation and
999 // what's the right type to promote it to.
1000 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1001 assert(PVT != VT && "Don't know what type to promote to!");
1002 // fold (aext (aext x)) -> (aext x)
1003 // fold (aext (zext x)) -> (zext x)
1004 // fold (aext (sext x)) -> (sext x)
1005 DEBUG(dbgs() << "\nPromoting ";
1006 Op.getNode()->dump(&DAG));
1007 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1012 bool DAGCombiner::PromoteLoad(SDValue Op) {
1013 if (!LegalOperations)
1016 EVT VT = Op.getValueType();
1017 if (VT.isVector() || !VT.isInteger())
1020 // If operation type is 'undesirable', e.g. i16 on x86, consider
1022 unsigned Opc = Op.getOpcode();
1023 if (TLI.isTypeDesirableForOp(Opc, VT))
1027 // Consult target whether it is a good idea to promote this operation and
1028 // what's the right type to promote it to.
1029 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1030 assert(PVT != VT && "Don't know what type to promote to!");
1033 SDNode *N = Op.getNode();
1034 LoadSDNode *LD = cast<LoadSDNode>(N);
1035 EVT MemVT = LD->getMemoryVT();
1036 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1037 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1039 : LD->getExtensionType();
1040 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1041 LD->getChain(), LD->getBasePtr(),
1042 MemVT, LD->getMemOperand());
1043 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1045 DEBUG(dbgs() << "\nPromoting ";
1048 Result.getNode()->dump(&DAG);
1050 WorkListRemover DeadNodes(*this);
1051 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1052 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1053 removeFromWorkList(N);
1055 AddToWorkList(Result.getNode());
1062 //===----------------------------------------------------------------------===//
1063 // Main DAG Combiner implementation
1064 //===----------------------------------------------------------------------===//
1066 void DAGCombiner::Run(CombineLevel AtLevel) {
1067 // set the instance variables, so that the various visit routines may use it.
1069 LegalOperations = Level >= AfterLegalizeVectorOps;
1070 LegalTypes = Level >= AfterLegalizeTypes;
1072 // Add all the dag nodes to the worklist.
1073 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1074 E = DAG.allnodes_end(); I != E; ++I)
1077 // Create a dummy node (which is not added to allnodes), that adds a reference
1078 // to the root node, preventing it from being deleted, and tracking any
1079 // changes of the root.
1080 HandleSDNode Dummy(DAG.getRoot());
1082 // The root of the dag may dangle to deleted nodes until the dag combiner is
1083 // done. Set it to null to avoid confusion.
1084 DAG.setRoot(SDValue());
1086 // while the worklist isn't empty, find a node and
1087 // try and combine it.
1088 while (!WorkListContents.empty()) {
1090 // The WorkListOrder holds the SDNodes in order, but it may contain
1092 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1093 // worklist *should* contain, and check the node we want to visit is should
1094 // actually be visited.
1096 N = WorkListOrder.pop_back_val();
1097 } while (!WorkListContents.erase(N));
1099 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1100 // N is deleted from the DAG, since they too may now be dead or may have a
1101 // reduced number of uses, allowing other xforms.
1102 if (N->use_empty() && N != &Dummy) {
1103 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1104 AddToWorkList(N->getOperand(i).getNode());
1110 SDValue RV = combine(N);
1117 // If we get back the same node we passed in, rather than a new node or
1118 // zero, we know that the node must have defined multiple values and
1119 // CombineTo was used. Since CombineTo takes care of the worklist
1120 // mechanics for us, we have no work to do in this case.
1121 if (RV.getNode() == N)
1124 assert(N->getOpcode() != ISD::DELETED_NODE &&
1125 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1126 "Node was deleted but visit returned new node!");
1128 DEBUG(dbgs() << "\nReplacing.3 ";
1130 dbgs() << "\nWith: ";
1131 RV.getNode()->dump(&DAG);
1134 // Transfer debug value.
1135 DAG.TransferDbgValues(SDValue(N, 0), RV);
1136 WorkListRemover DeadNodes(*this);
1137 if (N->getNumValues() == RV.getNode()->getNumValues())
1138 DAG.ReplaceAllUsesWith(N, RV.getNode());
1140 assert(N->getValueType(0) == RV.getValueType() &&
1141 N->getNumValues() == 1 && "Type mismatch");
1143 DAG.ReplaceAllUsesWith(N, &OpV);
1146 // Push the new node and any users onto the worklist
1147 AddToWorkList(RV.getNode());
1148 AddUsersToWorkList(RV.getNode());
1150 // Add any uses of the old node to the worklist in case this node is the
1151 // last one that uses them. They may become dead after this node is
1153 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1154 AddToWorkList(N->getOperand(i).getNode());
1156 // Finally, if the node is now dead, remove it from the graph. The node
1157 // may not be dead if the replacement process recursively simplified to
1158 // something else needing this node.
1159 if (N->use_empty()) {
1160 // Nodes can be reintroduced into the worklist. Make sure we do not
1161 // process a node that has been replaced.
1162 removeFromWorkList(N);
1164 // Finally, since the node is now dead, remove it from the graph.
1169 // If the root changed (e.g. it was a dead load, update the root).
1170 DAG.setRoot(Dummy.getValue());
1171 DAG.RemoveDeadNodes();
1174 SDValue DAGCombiner::visit(SDNode *N) {
1175 switch (N->getOpcode()) {
1177 case ISD::TokenFactor: return visitTokenFactor(N);
1178 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1179 case ISD::ADD: return visitADD(N);
1180 case ISD::SUB: return visitSUB(N);
1181 case ISD::ADDC: return visitADDC(N);
1182 case ISD::SUBC: return visitSUBC(N);
1183 case ISD::ADDE: return visitADDE(N);
1184 case ISD::SUBE: return visitSUBE(N);
1185 case ISD::MUL: return visitMUL(N);
1186 case ISD::SDIV: return visitSDIV(N);
1187 case ISD::UDIV: return visitUDIV(N);
1188 case ISD::SREM: return visitSREM(N);
1189 case ISD::UREM: return visitUREM(N);
1190 case ISD::MULHU: return visitMULHU(N);
1191 case ISD::MULHS: return visitMULHS(N);
1192 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1193 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1194 case ISD::SMULO: return visitSMULO(N);
1195 case ISD::UMULO: return visitUMULO(N);
1196 case ISD::SDIVREM: return visitSDIVREM(N);
1197 case ISD::UDIVREM: return visitUDIVREM(N);
1198 case ISD::AND: return visitAND(N);
1199 case ISD::OR: return visitOR(N);
1200 case ISD::XOR: return visitXOR(N);
1201 case ISD::SHL: return visitSHL(N);
1202 case ISD::SRA: return visitSRA(N);
1203 case ISD::SRL: return visitSRL(N);
1205 case ISD::ROTL: return visitRotate(N);
1206 case ISD::CTLZ: return visitCTLZ(N);
1207 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1208 case ISD::CTTZ: return visitCTTZ(N);
1209 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1210 case ISD::CTPOP: return visitCTPOP(N);
1211 case ISD::SELECT: return visitSELECT(N);
1212 case ISD::VSELECT: return visitVSELECT(N);
1213 case ISD::SELECT_CC: return visitSELECT_CC(N);
1214 case ISD::SETCC: return visitSETCC(N);
1215 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1216 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1217 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1218 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1219 case ISD::TRUNCATE: return visitTRUNCATE(N);
1220 case ISD::BITCAST: return visitBITCAST(N);
1221 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1222 case ISD::FADD: return visitFADD(N);
1223 case ISD::FSUB: return visitFSUB(N);
1224 case ISD::FMUL: return visitFMUL(N);
1225 case ISD::FMA: return visitFMA(N);
1226 case ISD::FDIV: return visitFDIV(N);
1227 case ISD::FREM: return visitFREM(N);
1228 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1229 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1230 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1231 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1232 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1233 case ISD::FP_ROUND: return visitFP_ROUND(N);
1234 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1235 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1236 case ISD::FNEG: return visitFNEG(N);
1237 case ISD::FABS: return visitFABS(N);
1238 case ISD::FFLOOR: return visitFFLOOR(N);
1239 case ISD::FCEIL: return visitFCEIL(N);
1240 case ISD::FTRUNC: return visitFTRUNC(N);
1241 case ISD::BRCOND: return visitBRCOND(N);
1242 case ISD::BR_CC: return visitBR_CC(N);
1243 case ISD::LOAD: return visitLOAD(N);
1244 case ISD::STORE: return visitSTORE(N);
1245 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1246 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1247 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1248 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1249 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1250 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1251 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1256 SDValue DAGCombiner::combine(SDNode *N) {
1257 SDValue RV = visit(N);
1259 // If nothing happened, try a target-specific DAG combine.
1260 if (!RV.getNode()) {
1261 assert(N->getOpcode() != ISD::DELETED_NODE &&
1262 "Node was deleted but visit returned NULL!");
1264 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1265 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1267 // Expose the DAG combiner to the target combiner impls.
1268 TargetLowering::DAGCombinerInfo
1269 DagCombineInfo(DAG, Level, false, this);
1271 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1275 // If nothing happened still, try promoting the operation.
1276 if (!RV.getNode()) {
1277 switch (N->getOpcode()) {
1285 RV = PromoteIntBinOp(SDValue(N, 0));
1290 RV = PromoteIntShiftOp(SDValue(N, 0));
1292 case ISD::SIGN_EXTEND:
1293 case ISD::ZERO_EXTEND:
1294 case ISD::ANY_EXTEND:
1295 RV = PromoteExtend(SDValue(N, 0));
1298 if (PromoteLoad(SDValue(N, 0)))
1304 // If N is a commutative binary node, try commuting it to enable more
1306 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1307 N->getNumValues() == 1) {
1308 SDValue N0 = N->getOperand(0);
1309 SDValue N1 = N->getOperand(1);
1311 // Constant operands are canonicalized to RHS.
1312 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1313 SDValue Ops[] = { N1, N0 };
1314 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1317 return SDValue(CSENode, 0);
1324 /// getInputChainForNode - Given a node, return its input chain if it has one,
1325 /// otherwise return a null sd operand.
1326 static SDValue getInputChainForNode(SDNode *N) {
1327 if (unsigned NumOps = N->getNumOperands()) {
1328 if (N->getOperand(0).getValueType() == MVT::Other)
1329 return N->getOperand(0);
1330 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1331 return N->getOperand(NumOps-1);
1332 for (unsigned i = 1; i < NumOps-1; ++i)
1333 if (N->getOperand(i).getValueType() == MVT::Other)
1334 return N->getOperand(i);
1339 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1340 // If N has two operands, where one has an input chain equal to the other,
1341 // the 'other' chain is redundant.
1342 if (N->getNumOperands() == 2) {
1343 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1344 return N->getOperand(0);
1345 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1346 return N->getOperand(1);
1349 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1350 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1351 SmallPtrSet<SDNode*, 16> SeenOps;
1352 bool Changed = false; // If we should replace this token factor.
1354 // Start out with this token factor.
1357 // Iterate through token factors. The TFs grows when new token factors are
1359 for (unsigned i = 0; i < TFs.size(); ++i) {
1360 SDNode *TF = TFs[i];
1362 // Check each of the operands.
1363 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1364 SDValue Op = TF->getOperand(i);
1366 switch (Op.getOpcode()) {
1367 case ISD::EntryToken:
1368 // Entry tokens don't need to be added to the list. They are
1373 case ISD::TokenFactor:
1374 if (Op.hasOneUse() &&
1375 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1376 // Queue up for processing.
1377 TFs.push_back(Op.getNode());
1378 // Clean up in case the token factor is removed.
1379 AddToWorkList(Op.getNode());
1386 // Only add if it isn't already in the list.
1387 if (SeenOps.insert(Op.getNode()))
1398 // If we've change things around then replace token factor.
1401 // The entry token is the only possible outcome.
1402 Result = DAG.getEntryNode();
1404 // New and improved token factor.
1405 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
1406 MVT::Other, &Ops[0], Ops.size());
1409 // Don't add users to work list.
1410 return CombineTo(N, Result, false);
1416 /// MERGE_VALUES can always be eliminated.
1417 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1418 WorkListRemover DeadNodes(*this);
1419 // Replacing results may cause a different MERGE_VALUES to suddenly
1420 // be CSE'd with N, and carry its uses with it. Iterate until no
1421 // uses remain, to ensure that the node can be safely deleted.
1422 // First add the users of this node to the work list so that they
1423 // can be tried again once they have new operands.
1424 AddUsersToWorkList(N);
1426 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1427 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1428 } while (!N->use_empty());
1429 removeFromWorkList(N);
1431 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1435 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1436 SelectionDAG &DAG) {
1437 EVT VT = N0.getValueType();
1438 SDValue N00 = N0.getOperand(0);
1439 SDValue N01 = N0.getOperand(1);
1440 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1442 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1443 isa<ConstantSDNode>(N00.getOperand(1))) {
1444 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1445 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1446 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1447 N00.getOperand(0), N01),
1448 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1449 N00.getOperand(1), N01));
1450 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1456 SDValue DAGCombiner::visitADD(SDNode *N) {
1457 SDValue N0 = N->getOperand(0);
1458 SDValue N1 = N->getOperand(1);
1459 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1460 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1461 EVT VT = N0.getValueType();
1464 if (VT.isVector()) {
1465 SDValue FoldedVOp = SimplifyVBinOp(N);
1466 if (FoldedVOp.getNode()) return FoldedVOp;
1468 // fold (add x, 0) -> x, vector edition
1469 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1471 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1475 // fold (add x, undef) -> undef
1476 if (N0.getOpcode() == ISD::UNDEF)
1478 if (N1.getOpcode() == ISD::UNDEF)
1480 // fold (add c1, c2) -> c1+c2
1482 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1483 // canonicalize constant to RHS
1485 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1486 // fold (add x, 0) -> x
1487 if (N1C && N1C->isNullValue())
1489 // fold (add Sym, c) -> Sym+c
1490 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1491 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1492 GA->getOpcode() == ISD::GlobalAddress)
1493 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1495 (uint64_t)N1C->getSExtValue());
1496 // fold ((c1-A)+c2) -> (c1+c2)-A
1497 if (N1C && N0.getOpcode() == ISD::SUB)
1498 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1499 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1500 DAG.getConstant(N1C->getAPIntValue()+
1501 N0C->getAPIntValue(), VT),
1504 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1507 // fold ((0-A) + B) -> B-A
1508 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1509 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1510 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1511 // fold (A + (0-B)) -> A-B
1512 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1513 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1514 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1515 // fold (A+(B-A)) -> B
1516 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1517 return N1.getOperand(0);
1518 // fold ((B-A)+A) -> B
1519 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1520 return N0.getOperand(0);
1521 // fold (A+(B-(A+C))) to (B-C)
1522 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1523 N0 == N1.getOperand(1).getOperand(0))
1524 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1525 N1.getOperand(1).getOperand(1));
1526 // fold (A+(B-(C+A))) to (B-C)
1527 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1528 N0 == N1.getOperand(1).getOperand(1))
1529 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1530 N1.getOperand(1).getOperand(0));
1531 // fold (A+((B-A)+or-C)) to (B+or-C)
1532 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1533 N1.getOperand(0).getOpcode() == ISD::SUB &&
1534 N0 == N1.getOperand(0).getOperand(1))
1535 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1536 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1538 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1539 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1540 SDValue N00 = N0.getOperand(0);
1541 SDValue N01 = N0.getOperand(1);
1542 SDValue N10 = N1.getOperand(0);
1543 SDValue N11 = N1.getOperand(1);
1545 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1546 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1547 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1548 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1551 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1552 return SDValue(N, 0);
1554 // fold (a+b) -> (a|b) iff a and b share no bits.
1555 if (VT.isInteger() && !VT.isVector()) {
1556 APInt LHSZero, LHSOne;
1557 APInt RHSZero, RHSOne;
1558 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1560 if (LHSZero.getBoolValue()) {
1561 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1563 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1564 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1565 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1566 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1567 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1572 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1573 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1574 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1575 if (Result.getNode()) return Result;
1577 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1578 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1579 if (Result.getNode()) return Result;
1582 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1583 if (N1.getOpcode() == ISD::SHL &&
1584 N1.getOperand(0).getOpcode() == ISD::SUB)
1585 if (ConstantSDNode *C =
1586 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1587 if (C->getAPIntValue() == 0)
1588 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1589 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1590 N1.getOperand(0).getOperand(1),
1592 if (N0.getOpcode() == ISD::SHL &&
1593 N0.getOperand(0).getOpcode() == ISD::SUB)
1594 if (ConstantSDNode *C =
1595 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1596 if (C->getAPIntValue() == 0)
1597 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1598 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1599 N0.getOperand(0).getOperand(1),
1602 if (N1.getOpcode() == ISD::AND) {
1603 SDValue AndOp0 = N1.getOperand(0);
1604 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1605 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1606 unsigned DestBits = VT.getScalarType().getSizeInBits();
1608 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1609 // and similar xforms where the inner op is either ~0 or 0.
1610 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1612 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1616 // add (sext i1), X -> sub X, (zext i1)
1617 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1618 N0.getOperand(0).getValueType() == MVT::i1 &&
1619 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1621 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1622 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1628 SDValue DAGCombiner::visitADDC(SDNode *N) {
1629 SDValue N0 = N->getOperand(0);
1630 SDValue N1 = N->getOperand(1);
1631 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1632 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1633 EVT VT = N0.getValueType();
1635 // If the flag result is dead, turn this into an ADD.
1636 if (!N->hasAnyUseOfValue(1))
1637 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1638 DAG.getNode(ISD::CARRY_FALSE,
1639 SDLoc(N), MVT::Glue));
1641 // canonicalize constant to RHS.
1643 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1645 // fold (addc x, 0) -> x + no carry out
1646 if (N1C && N1C->isNullValue())
1647 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1648 SDLoc(N), MVT::Glue));
1650 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1651 APInt LHSZero, LHSOne;
1652 APInt RHSZero, RHSOne;
1653 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1655 if (LHSZero.getBoolValue()) {
1656 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1658 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1659 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1660 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1661 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1662 DAG.getNode(ISD::CARRY_FALSE,
1663 SDLoc(N), MVT::Glue));
1669 SDValue DAGCombiner::visitADDE(SDNode *N) {
1670 SDValue N0 = N->getOperand(0);
1671 SDValue N1 = N->getOperand(1);
1672 SDValue CarryIn = N->getOperand(2);
1673 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1674 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1676 // canonicalize constant to RHS
1678 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1681 // fold (adde x, y, false) -> (addc x, y)
1682 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1683 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1688 // Since it may not be valid to emit a fold to zero for vector initializers
1689 // check if we can before folding.
1690 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1692 bool LegalOperations, bool LegalTypes) {
1694 return DAG.getConstant(0, VT);
1695 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1696 return DAG.getConstant(0, VT);
1700 SDValue DAGCombiner::visitSUB(SDNode *N) {
1701 SDValue N0 = N->getOperand(0);
1702 SDValue N1 = N->getOperand(1);
1703 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1704 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1705 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1706 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1707 EVT VT = N0.getValueType();
1710 if (VT.isVector()) {
1711 SDValue FoldedVOp = SimplifyVBinOp(N);
1712 if (FoldedVOp.getNode()) return FoldedVOp;
1714 // fold (sub x, 0) -> x, vector edition
1715 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1719 // fold (sub x, x) -> 0
1720 // FIXME: Refactor this and xor and other similar operations together.
1722 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1723 // fold (sub c1, c2) -> c1-c2
1725 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1726 // fold (sub x, c) -> (add x, -c)
1728 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1729 DAG.getConstant(-N1C->getAPIntValue(), VT));
1730 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1731 if (N0C && N0C->isAllOnesValue())
1732 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1733 // fold A-(A-B) -> B
1734 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1735 return N1.getOperand(1);
1736 // fold (A+B)-A -> B
1737 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1738 return N0.getOperand(1);
1739 // fold (A+B)-B -> A
1740 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1741 return N0.getOperand(0);
1742 // fold C2-(A+C1) -> (C2-C1)-A
1743 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1744 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1746 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1749 // fold ((A+(B+or-C))-B) -> A+or-C
1750 if (N0.getOpcode() == ISD::ADD &&
1751 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1752 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1753 N0.getOperand(1).getOperand(0) == N1)
1754 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1755 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1756 // fold ((A+(C+B))-B) -> A+C
1757 if (N0.getOpcode() == ISD::ADD &&
1758 N0.getOperand(1).getOpcode() == ISD::ADD &&
1759 N0.getOperand(1).getOperand(1) == N1)
1760 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1761 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1762 // fold ((A-(B-C))-C) -> A-B
1763 if (N0.getOpcode() == ISD::SUB &&
1764 N0.getOperand(1).getOpcode() == ISD::SUB &&
1765 N0.getOperand(1).getOperand(1) == N1)
1766 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1767 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1769 // If either operand of a sub is undef, the result is undef
1770 if (N0.getOpcode() == ISD::UNDEF)
1772 if (N1.getOpcode() == ISD::UNDEF)
1775 // If the relocation model supports it, consider symbol offsets.
1776 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1777 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1778 // fold (sub Sym, c) -> Sym-c
1779 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1780 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1782 (uint64_t)N1C->getSExtValue());
1783 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1784 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1785 if (GA->getGlobal() == GB->getGlobal())
1786 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1793 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1794 SDValue N0 = N->getOperand(0);
1795 SDValue N1 = N->getOperand(1);
1796 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1797 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1798 EVT VT = N0.getValueType();
1800 // If the flag result is dead, turn this into an SUB.
1801 if (!N->hasAnyUseOfValue(1))
1802 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1803 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1806 // fold (subc x, x) -> 0 + no borrow
1808 return CombineTo(N, DAG.getConstant(0, VT),
1809 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1812 // fold (subc x, 0) -> x + no borrow
1813 if (N1C && N1C->isNullValue())
1814 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1817 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1818 if (N0C && N0C->isAllOnesValue())
1819 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1820 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1826 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1827 SDValue N0 = N->getOperand(0);
1828 SDValue N1 = N->getOperand(1);
1829 SDValue CarryIn = N->getOperand(2);
1831 // fold (sube x, y, false) -> (subc x, y)
1832 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1833 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1838 SDValue DAGCombiner::visitMUL(SDNode *N) {
1839 SDValue N0 = N->getOperand(0);
1840 SDValue N1 = N->getOperand(1);
1841 EVT VT = N0.getValueType();
1843 // fold (mul x, undef) -> 0
1844 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1845 return DAG.getConstant(0, VT);
1847 bool N0IsConst = false;
1848 bool N1IsConst = false;
1849 APInt ConstValue0, ConstValue1;
1851 if (VT.isVector()) {
1852 SDValue FoldedVOp = SimplifyVBinOp(N);
1853 if (FoldedVOp.getNode()) return FoldedVOp;
1855 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1856 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1858 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1859 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1861 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1862 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1866 // fold (mul c1, c2) -> c1*c2
1867 if (N0IsConst && N1IsConst)
1868 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1870 // canonicalize constant to RHS
1871 if (N0IsConst && !N1IsConst)
1872 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1873 // fold (mul x, 0) -> 0
1874 if (N1IsConst && ConstValue1 == 0)
1876 // We require a splat of the entire scalar bit width for non-contiguous
1879 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1880 // fold (mul x, 1) -> x
1881 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1883 // fold (mul x, -1) -> 0-x
1884 if (N1IsConst && ConstValue1.isAllOnesValue())
1885 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1886 DAG.getConstant(0, VT), N0);
1887 // fold (mul x, (1 << c)) -> x << c
1888 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1889 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1890 DAG.getConstant(ConstValue1.logBase2(),
1891 getShiftAmountTy(N0.getValueType())));
1892 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1893 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1894 unsigned Log2Val = (-ConstValue1).logBase2();
1895 // FIXME: If the input is something that is easily negated (e.g. a
1896 // single-use add), we should put the negate there.
1897 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1898 DAG.getConstant(0, VT),
1899 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1900 DAG.getConstant(Log2Val,
1901 getShiftAmountTy(N0.getValueType()))));
1905 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1906 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1907 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1908 isa<ConstantSDNode>(N0.getOperand(1)))) {
1909 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1910 N1, N0.getOperand(1));
1911 AddToWorkList(C3.getNode());
1912 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1913 N0.getOperand(0), C3);
1916 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1919 SDValue Sh(nullptr,0), Y(nullptr,0);
1920 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1921 if (N0.getOpcode() == ISD::SHL &&
1922 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1923 isa<ConstantSDNode>(N0.getOperand(1))) &&
1924 N0.getNode()->hasOneUse()) {
1926 } else if (N1.getOpcode() == ISD::SHL &&
1927 isa<ConstantSDNode>(N1.getOperand(1)) &&
1928 N1.getNode()->hasOneUse()) {
1933 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1934 Sh.getOperand(0), Y);
1935 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1936 Mul, Sh.getOperand(1));
1940 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1941 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1942 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1943 isa<ConstantSDNode>(N0.getOperand(1))))
1944 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1945 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1946 N0.getOperand(0), N1),
1947 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1948 N0.getOperand(1), N1));
1951 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1958 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1959 SDValue N0 = N->getOperand(0);
1960 SDValue N1 = N->getOperand(1);
1961 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1962 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1963 EVT VT = N->getValueType(0);
1966 if (VT.isVector()) {
1967 SDValue FoldedVOp = SimplifyVBinOp(N);
1968 if (FoldedVOp.getNode()) return FoldedVOp;
1971 // fold (sdiv c1, c2) -> c1/c2
1972 if (N0C && N1C && !N1C->isNullValue())
1973 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1974 // fold (sdiv X, 1) -> X
1975 if (N1C && N1C->getAPIntValue() == 1LL)
1977 // fold (sdiv X, -1) -> 0-X
1978 if (N1C && N1C->isAllOnesValue())
1979 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1980 DAG.getConstant(0, VT), N0);
1981 // If we know the sign bits of both operands are zero, strength reduce to a
1982 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1983 if (!VT.isVector()) {
1984 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1985 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
1988 // fold (sdiv X, pow2) -> simple ops after legalize
1989 if (N1C && !N1C->isNullValue() &&
1990 (N1C->getAPIntValue().isPowerOf2() ||
1991 (-N1C->getAPIntValue()).isPowerOf2())) {
1992 // If dividing by powers of two is cheap, then don't perform the following
1994 if (TLI.isPow2DivCheap())
1997 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
1999 // Splat the sign bit into the register
2000 SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2001 DAG.getConstant(VT.getSizeInBits()-1,
2002 getShiftAmountTy(N0.getValueType())));
2003 AddToWorkList(SGN.getNode());
2005 // Add (N0 < 0) ? abs2 - 1 : 0;
2006 SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2007 DAG.getConstant(VT.getSizeInBits() - lg2,
2008 getShiftAmountTy(SGN.getValueType())));
2009 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2010 AddToWorkList(SRL.getNode());
2011 AddToWorkList(ADD.getNode()); // Divide by pow2
2012 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2013 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2015 // If we're dividing by a positive value, we're done. Otherwise, we must
2016 // negate the result.
2017 if (N1C->getAPIntValue().isNonNegative())
2020 AddToWorkList(SRA.getNode());
2021 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2022 DAG.getConstant(0, VT), SRA);
2025 // if integer divide is expensive and we satisfy the requirements, emit an
2026 // alternate sequence.
2027 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2028 SDValue Op = BuildSDIV(N);
2029 if (Op.getNode()) return Op;
2033 if (N0.getOpcode() == ISD::UNDEF)
2034 return DAG.getConstant(0, VT);
2035 // X / undef -> undef
2036 if (N1.getOpcode() == ISD::UNDEF)
2042 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2043 SDValue N0 = N->getOperand(0);
2044 SDValue N1 = N->getOperand(1);
2045 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
2046 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2047 EVT VT = N->getValueType(0);
2050 if (VT.isVector()) {
2051 SDValue FoldedVOp = SimplifyVBinOp(N);
2052 if (FoldedVOp.getNode()) return FoldedVOp;
2055 // fold (udiv c1, c2) -> c1/c2
2056 if (N0C && N1C && !N1C->isNullValue())
2057 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2058 // fold (udiv x, (1 << c)) -> x >>u c
2059 if (N1C && N1C->getAPIntValue().isPowerOf2())
2060 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2061 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2062 getShiftAmountTy(N0.getValueType())));
2063 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2064 if (N1.getOpcode() == ISD::SHL) {
2065 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2066 if (SHC->getAPIntValue().isPowerOf2()) {
2067 EVT ADDVT = N1.getOperand(1).getValueType();
2068 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2070 DAG.getConstant(SHC->getAPIntValue()
2073 AddToWorkList(Add.getNode());
2074 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2078 // fold (udiv x, c) -> alternate
2079 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2080 SDValue Op = BuildUDIV(N);
2081 if (Op.getNode()) return Op;
2085 if (N0.getOpcode() == ISD::UNDEF)
2086 return DAG.getConstant(0, VT);
2087 // X / undef -> undef
2088 if (N1.getOpcode() == ISD::UNDEF)
2094 SDValue DAGCombiner::visitSREM(SDNode *N) {
2095 SDValue N0 = N->getOperand(0);
2096 SDValue N1 = N->getOperand(1);
2097 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2098 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2099 EVT VT = N->getValueType(0);
2101 // fold (srem c1, c2) -> c1%c2
2102 if (N0C && N1C && !N1C->isNullValue())
2103 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2104 // If we know the sign bits of both operands are zero, strength reduce to a
2105 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2106 if (!VT.isVector()) {
2107 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2108 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2111 // If X/C can be simplified by the division-by-constant logic, lower
2112 // X%C to the equivalent of X-X/C*C.
2113 if (N1C && !N1C->isNullValue()) {
2114 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2115 AddToWorkList(Div.getNode());
2116 SDValue OptimizedDiv = combine(Div.getNode());
2117 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2118 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2120 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2121 AddToWorkList(Mul.getNode());
2127 if (N0.getOpcode() == ISD::UNDEF)
2128 return DAG.getConstant(0, VT);
2129 // X % undef -> undef
2130 if (N1.getOpcode() == ISD::UNDEF)
2136 SDValue DAGCombiner::visitUREM(SDNode *N) {
2137 SDValue N0 = N->getOperand(0);
2138 SDValue N1 = N->getOperand(1);
2139 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2140 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2141 EVT VT = N->getValueType(0);
2143 // fold (urem c1, c2) -> c1%c2
2144 if (N0C && N1C && !N1C->isNullValue())
2145 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2146 // fold (urem x, pow2) -> (and x, pow2-1)
2147 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2148 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2149 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2150 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2151 if (N1.getOpcode() == ISD::SHL) {
2152 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2153 if (SHC->getAPIntValue().isPowerOf2()) {
2155 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2156 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2158 AddToWorkList(Add.getNode());
2159 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2164 // If X/C can be simplified by the division-by-constant logic, lower
2165 // X%C to the equivalent of X-X/C*C.
2166 if (N1C && !N1C->isNullValue()) {
2167 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2168 AddToWorkList(Div.getNode());
2169 SDValue OptimizedDiv = combine(Div.getNode());
2170 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2171 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2173 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2174 AddToWorkList(Mul.getNode());
2180 if (N0.getOpcode() == ISD::UNDEF)
2181 return DAG.getConstant(0, VT);
2182 // X % undef -> undef
2183 if (N1.getOpcode() == ISD::UNDEF)
2189 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2190 SDValue N0 = N->getOperand(0);
2191 SDValue N1 = N->getOperand(1);
2192 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2193 EVT VT = N->getValueType(0);
2196 // fold (mulhs x, 0) -> 0
2197 if (N1C && N1C->isNullValue())
2199 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2200 if (N1C && N1C->getAPIntValue() == 1)
2201 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2202 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2203 getShiftAmountTy(N0.getValueType())));
2204 // fold (mulhs x, undef) -> 0
2205 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2206 return DAG.getConstant(0, VT);
2208 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2210 if (VT.isSimple() && !VT.isVector()) {
2211 MVT Simple = VT.getSimpleVT();
2212 unsigned SimpleSize = Simple.getSizeInBits();
2213 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2214 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2215 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2216 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2217 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2218 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2219 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2220 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2227 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2228 SDValue N0 = N->getOperand(0);
2229 SDValue N1 = N->getOperand(1);
2230 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2231 EVT VT = N->getValueType(0);
2234 // fold (mulhu x, 0) -> 0
2235 if (N1C && N1C->isNullValue())
2237 // fold (mulhu x, 1) -> 0
2238 if (N1C && N1C->getAPIntValue() == 1)
2239 return DAG.getConstant(0, N0.getValueType());
2240 // fold (mulhu x, undef) -> 0
2241 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2242 return DAG.getConstant(0, VT);
2244 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2246 if (VT.isSimple() && !VT.isVector()) {
2247 MVT Simple = VT.getSimpleVT();
2248 unsigned SimpleSize = Simple.getSizeInBits();
2249 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2250 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2251 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2252 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2253 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2254 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2255 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2256 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2263 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2264 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2265 /// that are being performed. Return true if a simplification was made.
2267 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2269 // If the high half is not needed, just compute the low half.
2270 bool HiExists = N->hasAnyUseOfValue(1);
2272 (!LegalOperations ||
2273 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2274 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2275 N->op_begin(), N->getNumOperands());
2276 return CombineTo(N, Res, Res);
2279 // If the low half is not needed, just compute the high half.
2280 bool LoExists = N->hasAnyUseOfValue(0);
2282 (!LegalOperations ||
2283 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2284 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2285 N->op_begin(), N->getNumOperands());
2286 return CombineTo(N, Res, Res);
2289 // If both halves are used, return as it is.
2290 if (LoExists && HiExists)
2293 // If the two computed results can be simplified separately, separate them.
2295 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2296 N->op_begin(), N->getNumOperands());
2297 AddToWorkList(Lo.getNode());
2298 SDValue LoOpt = combine(Lo.getNode());
2299 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2300 (!LegalOperations ||
2301 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2302 return CombineTo(N, LoOpt, LoOpt);
2306 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2307 N->op_begin(), N->getNumOperands());
2308 AddToWorkList(Hi.getNode());
2309 SDValue HiOpt = combine(Hi.getNode());
2310 if (HiOpt.getNode() && HiOpt != Hi &&
2311 (!LegalOperations ||
2312 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2313 return CombineTo(N, HiOpt, HiOpt);
2319 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2320 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2321 if (Res.getNode()) return Res;
2323 EVT VT = N->getValueType(0);
2326 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2328 if (VT.isSimple() && !VT.isVector()) {
2329 MVT Simple = VT.getSimpleVT();
2330 unsigned SimpleSize = Simple.getSizeInBits();
2331 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2332 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2333 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2334 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2335 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2336 // Compute the high part as N1.
2337 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2338 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2339 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2340 // Compute the low part as N0.
2341 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2342 return CombineTo(N, Lo, Hi);
2349 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2350 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2351 if (Res.getNode()) return Res;
2353 EVT VT = N->getValueType(0);
2356 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2358 if (VT.isSimple() && !VT.isVector()) {
2359 MVT Simple = VT.getSimpleVT();
2360 unsigned SimpleSize = Simple.getSizeInBits();
2361 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2362 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2363 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2364 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2365 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2366 // Compute the high part as N1.
2367 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2368 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2369 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2370 // Compute the low part as N0.
2371 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2372 return CombineTo(N, Lo, Hi);
2379 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2380 // (smulo x, 2) -> (saddo x, x)
2381 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2382 if (C2->getAPIntValue() == 2)
2383 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2384 N->getOperand(0), N->getOperand(0));
2389 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2390 // (umulo x, 2) -> (uaddo x, x)
2391 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2392 if (C2->getAPIntValue() == 2)
2393 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2394 N->getOperand(0), N->getOperand(0));
2399 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2400 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2401 if (Res.getNode()) return Res;
2406 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2407 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2408 if (Res.getNode()) return Res;
2413 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2414 /// two operands of the same opcode, try to simplify it.
2415 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2416 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2417 EVT VT = N0.getValueType();
2418 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2420 // Bail early if none of these transforms apply.
2421 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2423 // For each of OP in AND/OR/XOR:
2424 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2425 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2426 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2427 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2429 // do not sink logical op inside of a vector extend, since it may combine
2431 EVT Op0VT = N0.getOperand(0).getValueType();
2432 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2433 N0.getOpcode() == ISD::SIGN_EXTEND ||
2434 // Avoid infinite looping with PromoteIntBinOp.
2435 (N0.getOpcode() == ISD::ANY_EXTEND &&
2436 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2437 (N0.getOpcode() == ISD::TRUNCATE &&
2438 (!TLI.isZExtFree(VT, Op0VT) ||
2439 !TLI.isTruncateFree(Op0VT, VT)) &&
2440 TLI.isTypeLegal(Op0VT))) &&
2442 Op0VT == N1.getOperand(0).getValueType() &&
2443 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2444 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2445 N0.getOperand(0).getValueType(),
2446 N0.getOperand(0), N1.getOperand(0));
2447 AddToWorkList(ORNode.getNode());
2448 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2451 // For each of OP in SHL/SRL/SRA/AND...
2452 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2453 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2454 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2455 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2456 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2457 N0.getOperand(1) == N1.getOperand(1)) {
2458 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2459 N0.getOperand(0).getValueType(),
2460 N0.getOperand(0), N1.getOperand(0));
2461 AddToWorkList(ORNode.getNode());
2462 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2463 ORNode, N0.getOperand(1));
2466 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2467 // Only perform this optimization after type legalization and before
2468 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2469 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2470 // we don't want to undo this promotion.
2471 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2473 if ((N0.getOpcode() == ISD::BITCAST ||
2474 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2475 Level == AfterLegalizeTypes) {
2476 SDValue In0 = N0.getOperand(0);
2477 SDValue In1 = N1.getOperand(0);
2478 EVT In0Ty = In0.getValueType();
2479 EVT In1Ty = In1.getValueType();
2481 // If both incoming values are integers, and the original types are the
2483 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2484 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2485 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2486 AddToWorkList(Op.getNode());
2491 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2492 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2493 // If both shuffles use the same mask, and both shuffle within a single
2494 // vector, then it is worthwhile to move the swizzle after the operation.
2495 // The type-legalizer generates this pattern when loading illegal
2496 // vector types from memory. In many cases this allows additional shuffle
2498 // There are other cases where moving the shuffle after the xor/and/or
2499 // is profitable even if shuffles don't perform a swizzle.
2500 // If both shuffles use the same mask, and both shuffles have the same first
2501 // or second operand, then it might still be profitable to move the shuffle
2502 // after the xor/and/or operation.
2503 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2504 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2505 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2507 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2508 "Inputs to shuffles are not the same type");
2510 // Check that both shuffles use the same mask. The masks are known to be of
2511 // the same length because the result vector type is the same.
2512 // Check also that shuffles have only one use to avoid introducing extra
2514 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2515 SVN0->getMask().equals(SVN1->getMask())) {
2516 SDValue ShOp = N0->getOperand(1);
2518 // Don't try to fold this node if it requires introducing a
2519 // build vector of all zeros that might be illegal at this stage.
2520 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2522 ShOp = DAG.getConstant(0, VT);
2527 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2528 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2529 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2530 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2531 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2532 N0->getOperand(0), N1->getOperand(0));
2533 AddToWorkList(NewNode.getNode());
2534 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2535 &SVN0->getMask()[0]);
2538 // Don't try to fold this node if it requires introducing a
2539 // build vector of all zeros that might be illegal at this stage.
2540 ShOp = N0->getOperand(0);
2541 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2543 ShOp = DAG.getConstant(0, VT);
2548 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2549 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2550 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2551 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2552 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2553 N0->getOperand(1), N1->getOperand(1));
2554 AddToWorkList(NewNode.getNode());
2555 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2556 &SVN0->getMask()[0]);
2564 SDValue DAGCombiner::visitAND(SDNode *N) {
2565 SDValue N0 = N->getOperand(0);
2566 SDValue N1 = N->getOperand(1);
2567 SDValue LL, LR, RL, RR, CC0, CC1;
2568 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2569 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2570 EVT VT = N1.getValueType();
2571 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2574 if (VT.isVector()) {
2575 SDValue FoldedVOp = SimplifyVBinOp(N);
2576 if (FoldedVOp.getNode()) return FoldedVOp;
2578 // fold (and x, 0) -> 0, vector edition
2579 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2581 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2584 // fold (and x, -1) -> x, vector edition
2585 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2587 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2591 // fold (and x, undef) -> 0
2592 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2593 return DAG.getConstant(0, VT);
2594 // fold (and c1, c2) -> c1&c2
2596 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2597 // canonicalize constant to RHS
2599 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2600 // fold (and x, -1) -> x
2601 if (N1C && N1C->isAllOnesValue())
2603 // if (and x, c) is known to be zero, return 0
2604 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2605 APInt::getAllOnesValue(BitWidth)))
2606 return DAG.getConstant(0, VT);
2608 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2611 // fold (and (or x, C), D) -> D if (C & D) == D
2612 if (N1C && N0.getOpcode() == ISD::OR)
2613 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2614 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2616 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2617 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2618 SDValue N0Op0 = N0.getOperand(0);
2619 APInt Mask = ~N1C->getAPIntValue();
2620 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2621 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2622 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2623 N0.getValueType(), N0Op0);
2625 // Replace uses of the AND with uses of the Zero extend node.
2628 // We actually want to replace all uses of the any_extend with the
2629 // zero_extend, to avoid duplicating things. This will later cause this
2630 // AND to be folded.
2631 CombineTo(N0.getNode(), Zext);
2632 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2635 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2636 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2637 // already be zero by virtue of the width of the base type of the load.
2639 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2641 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2642 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2643 N0.getOpcode() == ISD::LOAD) {
2644 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2645 N0 : N0.getOperand(0) );
2647 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2648 // This can be a pure constant or a vector splat, in which case we treat the
2649 // vector as a scalar and use the splat value.
2650 APInt Constant = APInt::getNullValue(1);
2651 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2652 Constant = C->getAPIntValue();
2653 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2654 APInt SplatValue, SplatUndef;
2655 unsigned SplatBitSize;
2657 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2658 SplatBitSize, HasAnyUndefs);
2660 // Undef bits can contribute to a possible optimisation if set, so
2662 SplatValue |= SplatUndef;
2664 // The splat value may be something like "0x00FFFFFF", which means 0 for
2665 // the first vector value and FF for the rest, repeating. We need a mask
2666 // that will apply equally to all members of the vector, so AND all the
2667 // lanes of the constant together.
2668 EVT VT = Vector->getValueType(0);
2669 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2671 // If the splat value has been compressed to a bitlength lower
2672 // than the size of the vector lane, we need to re-expand it to
2674 if (BitWidth > SplatBitSize)
2675 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2676 SplatBitSize < BitWidth;
2677 SplatBitSize = SplatBitSize * 2)
2678 SplatValue |= SplatValue.shl(SplatBitSize);
2680 Constant = APInt::getAllOnesValue(BitWidth);
2681 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2682 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2686 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2687 // actually legal and isn't going to get expanded, else this is a false
2689 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2690 Load->getMemoryVT());
2692 // Resize the constant to the same size as the original memory access before
2693 // extension. If it is still the AllOnesValue then this AND is completely
2696 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2699 switch (Load->getExtensionType()) {
2700 default: B = false; break;
2701 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2703 case ISD::NON_EXTLOAD: B = true; break;
2706 if (B && Constant.isAllOnesValue()) {
2707 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2708 // preserve semantics once we get rid of the AND.
2709 SDValue NewLoad(Load, 0);
2710 if (Load->getExtensionType() == ISD::EXTLOAD) {
2711 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2712 Load->getValueType(0), SDLoc(Load),
2713 Load->getChain(), Load->getBasePtr(),
2714 Load->getOffset(), Load->getMemoryVT(),
2715 Load->getMemOperand());
2716 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2717 if (Load->getNumValues() == 3) {
2718 // PRE/POST_INC loads have 3 values.
2719 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2720 NewLoad.getValue(2) };
2721 CombineTo(Load, To, 3, true);
2723 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2727 // Fold the AND away, taking care not to fold to the old load node if we
2729 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2731 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2734 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2735 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2736 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2737 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2739 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2740 LL.getValueType().isInteger()) {
2741 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2742 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2743 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2744 LR.getValueType(), LL, RL);
2745 AddToWorkList(ORNode.getNode());
2746 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2748 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2749 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2750 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2751 LR.getValueType(), LL, RL);
2752 AddToWorkList(ANDNode.getNode());
2753 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2755 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2756 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2757 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2758 LR.getValueType(), LL, RL);
2759 AddToWorkList(ORNode.getNode());
2760 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2763 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2764 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2765 Op0 == Op1 && LL.getValueType().isInteger() &&
2766 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2767 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2768 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2769 cast<ConstantSDNode>(RR)->isNullValue()))) {
2770 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2771 LL, DAG.getConstant(1, LL.getValueType()));
2772 AddToWorkList(ADDNode.getNode());
2773 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2774 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2776 // canonicalize equivalent to ll == rl
2777 if (LL == RR && LR == RL) {
2778 Op1 = ISD::getSetCCSwappedOperands(Op1);
2781 if (LL == RL && LR == RR) {
2782 bool isInteger = LL.getValueType().isInteger();
2783 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2784 if (Result != ISD::SETCC_INVALID &&
2785 (!LegalOperations ||
2786 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2787 TLI.isOperationLegal(ISD::SETCC,
2788 getSetCCResultType(N0.getSimpleValueType())))))
2789 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2794 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2795 if (N0.getOpcode() == N1.getOpcode()) {
2796 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2797 if (Tmp.getNode()) return Tmp;
2800 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2801 // fold (and (sra)) -> (and (srl)) when possible.
2802 if (!VT.isVector() &&
2803 SimplifyDemandedBits(SDValue(N, 0)))
2804 return SDValue(N, 0);
2806 // fold (zext_inreg (extload x)) -> (zextload x)
2807 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2808 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2809 EVT MemVT = LN0->getMemoryVT();
2810 // If we zero all the possible extended bits, then we can turn this into
2811 // a zextload if we are running before legalize or the operation is legal.
2812 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2813 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2814 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2815 ((!LegalOperations && !LN0->isVolatile()) ||
2816 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2817 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2818 LN0->getChain(), LN0->getBasePtr(),
2819 MemVT, LN0->getMemOperand());
2821 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2822 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2825 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2826 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2828 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2829 EVT MemVT = LN0->getMemoryVT();
2830 // If we zero all the possible extended bits, then we can turn this into
2831 // a zextload if we are running before legalize or the operation is legal.
2832 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2833 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2834 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2835 ((!LegalOperations && !LN0->isVolatile()) ||
2836 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2837 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2838 LN0->getChain(), LN0->getBasePtr(),
2839 MemVT, LN0->getMemOperand());
2841 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2842 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2846 // fold (and (load x), 255) -> (zextload x, i8)
2847 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2848 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2849 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2850 (N0.getOpcode() == ISD::ANY_EXTEND &&
2851 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2852 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2853 LoadSDNode *LN0 = HasAnyExt
2854 ? cast<LoadSDNode>(N0.getOperand(0))
2855 : cast<LoadSDNode>(N0);
2856 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2857 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2858 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2859 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2860 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2861 EVT LoadedVT = LN0->getMemoryVT();
2863 if (ExtVT == LoadedVT &&
2864 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2865 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2868 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2869 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2870 LN0->getMemOperand());
2872 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2873 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2876 // Do not change the width of a volatile load.
2877 // Do not generate loads of non-round integer types since these can
2878 // be expensive (and would be wrong if the type is not byte sized).
2879 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2880 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2881 EVT PtrType = LN0->getOperand(1).getValueType();
2883 unsigned Alignment = LN0->getAlignment();
2884 SDValue NewPtr = LN0->getBasePtr();
2886 // For big endian targets, we need to add an offset to the pointer
2887 // to load the correct bytes. For little endian systems, we merely
2888 // need to read fewer bytes from the same pointer.
2889 if (TLI.isBigEndian()) {
2890 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2891 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2892 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2893 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2894 NewPtr, DAG.getConstant(PtrOff, PtrType));
2895 Alignment = MinAlign(Alignment, PtrOff);
2898 AddToWorkList(NewPtr.getNode());
2900 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2902 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2903 LN0->getChain(), NewPtr,
2904 LN0->getPointerInfo(),
2905 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2906 Alignment, LN0->getTBAAInfo());
2908 CombineTo(LN0, Load, Load.getValue(1));
2909 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2915 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2916 VT.getSizeInBits() <= 64) {
2917 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2918 APInt ADDC = ADDI->getAPIntValue();
2919 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2920 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2921 // immediate for an add, but it is legal if its top c2 bits are set,
2922 // transform the ADD so the immediate doesn't need to be materialized
2924 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2925 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2926 SRLI->getZExtValue());
2927 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2929 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2931 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2932 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2933 CombineTo(N0.getNode(), NewAdd);
2934 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2942 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2943 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2944 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2945 N0.getOperand(1), false);
2946 if (BSwap.getNode())
2953 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2955 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2956 bool DemandHighBits) {
2957 if (!LegalOperations)
2960 EVT VT = N->getValueType(0);
2961 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2963 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2966 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2967 bool LookPassAnd0 = false;
2968 bool LookPassAnd1 = false;
2969 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2971 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2973 if (N0.getOpcode() == ISD::AND) {
2974 if (!N0.getNode()->hasOneUse())
2976 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2977 if (!N01C || N01C->getZExtValue() != 0xFF00)
2979 N0 = N0.getOperand(0);
2980 LookPassAnd0 = true;
2983 if (N1.getOpcode() == ISD::AND) {
2984 if (!N1.getNode()->hasOneUse())
2986 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2987 if (!N11C || N11C->getZExtValue() != 0xFF)
2989 N1 = N1.getOperand(0);
2990 LookPassAnd1 = true;
2993 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2995 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2997 if (!N0.getNode()->hasOneUse() ||
2998 !N1.getNode()->hasOneUse())
3001 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3002 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3005 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3008 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3009 SDValue N00 = N0->getOperand(0);
3010 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3011 if (!N00.getNode()->hasOneUse())
3013 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3014 if (!N001C || N001C->getZExtValue() != 0xFF)
3016 N00 = N00.getOperand(0);
3017 LookPassAnd0 = true;
3020 SDValue N10 = N1->getOperand(0);
3021 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3022 if (!N10.getNode()->hasOneUse())
3024 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3025 if (!N101C || N101C->getZExtValue() != 0xFF00)
3027 N10 = N10.getOperand(0);
3028 LookPassAnd1 = true;
3034 // Make sure everything beyond the low halfword gets set to zero since the SRL
3035 // 16 will clear the top bits.
3036 unsigned OpSizeInBits = VT.getSizeInBits();
3037 if (DemandHighBits && OpSizeInBits > 16) {
3038 // If the left-shift isn't masked out then the only way this is a bswap is
3039 // if all bits beyond the low 8 are 0. In that case the entire pattern
3040 // reduces to a left shift anyway: leave it for other parts of the combiner.
3044 // However, if the right shift isn't masked out then it might be because
3045 // it's not needed. See if we can spot that too.
3046 if (!LookPassAnd1 &&
3047 !DAG.MaskedValueIsZero(
3048 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3052 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3053 if (OpSizeInBits > 16)
3054 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3055 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3059 /// isBSwapHWordElement - Return true if the specified node is an element
3060 /// that makes up a 32-bit packed halfword byteswap. i.e.
3061 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3062 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3063 if (!N.getNode()->hasOneUse())
3066 unsigned Opc = N.getOpcode();
3067 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3070 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3075 switch (N1C->getZExtValue()) {
3078 case 0xFF: Num = 0; break;
3079 case 0xFF00: Num = 1; break;
3080 case 0xFF0000: Num = 2; break;
3081 case 0xFF000000: Num = 3; break;
3084 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3085 SDValue N0 = N.getOperand(0);
3086 if (Opc == ISD::AND) {
3087 if (Num == 0 || Num == 2) {
3089 // (x >> 8) & 0xff0000
3090 if (N0.getOpcode() != ISD::SRL)
3092 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3093 if (!C || C->getZExtValue() != 8)
3096 // (x << 8) & 0xff00
3097 // (x << 8) & 0xff000000
3098 if (N0.getOpcode() != ISD::SHL)
3100 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3101 if (!C || C->getZExtValue() != 8)
3104 } else if (Opc == ISD::SHL) {
3106 // (x & 0xff0000) << 8
3107 if (Num != 0 && Num != 2)
3109 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3110 if (!C || C->getZExtValue() != 8)
3112 } else { // Opc == ISD::SRL
3113 // (x & 0xff00) >> 8
3114 // (x & 0xff000000) >> 8
3115 if (Num != 1 && Num != 3)
3117 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3118 if (!C || C->getZExtValue() != 8)
3125 Parts[Num] = N0.getOperand(0).getNode();
3129 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3130 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3131 /// => (rotl (bswap x), 16)
3132 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3133 if (!LegalOperations)
3136 EVT VT = N->getValueType(0);
3139 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3142 SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3144 // (or (or (and), (and)), (or (and), (and)))
3145 // (or (or (or (and), (and)), (and)), (and))
3146 if (N0.getOpcode() != ISD::OR)
3148 SDValue N00 = N0.getOperand(0);
3149 SDValue N01 = N0.getOperand(1);
3151 if (N1.getOpcode() == ISD::OR &&
3152 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3153 // (or (or (and), (and)), (or (and), (and)))
3154 SDValue N000 = N00.getOperand(0);
3155 if (!isBSwapHWordElement(N000, Parts))
3158 SDValue N001 = N00.getOperand(1);
3159 if (!isBSwapHWordElement(N001, Parts))
3161 SDValue N010 = N01.getOperand(0);
3162 if (!isBSwapHWordElement(N010, Parts))
3164 SDValue N011 = N01.getOperand(1);
3165 if (!isBSwapHWordElement(N011, Parts))
3168 // (or (or (or (and), (and)), (and)), (and))
3169 if (!isBSwapHWordElement(N1, Parts))
3171 if (!isBSwapHWordElement(N01, Parts))
3173 if (N00.getOpcode() != ISD::OR)
3175 SDValue N000 = N00.getOperand(0);
3176 if (!isBSwapHWordElement(N000, Parts))
3178 SDValue N001 = N00.getOperand(1);
3179 if (!isBSwapHWordElement(N001, Parts))
3183 // Make sure the parts are all coming from the same node.
3184 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3187 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3188 SDValue(Parts[0],0));
3190 // Result of the bswap should be rotated by 16. If it's not legal, then
3191 // do (x << 16) | (x >> 16).
3192 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3193 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3194 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3195 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3196 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3197 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3198 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3199 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3202 SDValue DAGCombiner::visitOR(SDNode *N) {
3203 SDValue N0 = N->getOperand(0);
3204 SDValue N1 = N->getOperand(1);
3205 SDValue LL, LR, RL, RR, CC0, CC1;
3206 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3207 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3208 EVT VT = N1.getValueType();
3211 if (VT.isVector()) {
3212 SDValue FoldedVOp = SimplifyVBinOp(N);
3213 if (FoldedVOp.getNode()) return FoldedVOp;
3215 // fold (or x, 0) -> x, vector edition
3216 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3218 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3221 // fold (or x, -1) -> -1, vector edition
3222 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3224 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3227 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3228 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3229 // Do this only if the resulting shuffle is legal.
3230 if (isa<ShuffleVectorSDNode>(N0) &&
3231 isa<ShuffleVectorSDNode>(N1) &&
3232 N0->getOperand(1) == N1->getOperand(1) &&
3233 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3234 bool CanFold = true;
3235 unsigned NumElts = VT.getVectorNumElements();
3236 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3237 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3238 // We construct two shuffle masks:
3239 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3240 // and N1 as the second operand.
3241 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3242 // and N0 as the second operand.
3243 // We do this because OR is commutable and therefore there might be
3244 // two ways to fold this node into a shuffle.
3245 SmallVector<int,4> Mask1;
3246 SmallVector<int,4> Mask2;
3248 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3249 int M0 = SV0->getMaskElt(i);
3250 int M1 = SV1->getMaskElt(i);
3252 // Both shuffle indexes are undef. Propagate Undef.
3253 if (M0 < 0 && M1 < 0) {
3254 Mask1.push_back(M0);
3255 Mask2.push_back(M0);
3259 if (M0 < 0 || M1 < 0 ||
3260 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3261 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3266 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3267 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3271 // Fold this sequence only if the resulting shuffle is 'legal'.
3272 if (TLI.isShuffleMaskLegal(Mask1, VT))
3273 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3274 N1->getOperand(0), &Mask1[0]);
3275 if (TLI.isShuffleMaskLegal(Mask2, VT))
3276 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3277 N0->getOperand(0), &Mask2[0]);
3282 // fold (or x, undef) -> -1
3283 if (!LegalOperations &&
3284 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3285 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3286 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3288 // fold (or c1, c2) -> c1|c2
3290 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3291 // canonicalize constant to RHS
3293 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3294 // fold (or x, 0) -> x
3295 if (N1C && N1C->isNullValue())
3297 // fold (or x, -1) -> -1
3298 if (N1C && N1C->isAllOnesValue())
3300 // fold (or x, c) -> c iff (x & ~c) == 0
3301 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3304 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3305 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3306 if (BSwap.getNode())
3308 BSwap = MatchBSwapHWordLow(N, N0, N1);
3309 if (BSwap.getNode())
3313 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3316 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3317 // iff (c1 & c2) == 0.
3318 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3319 isa<ConstantSDNode>(N0.getOperand(1))) {
3320 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3321 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3322 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3325 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3326 DAG.getNode(ISD::OR, SDLoc(N0), VT,
3327 N0.getOperand(0), N1), COR);
3330 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3331 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3332 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3333 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3335 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3336 LL.getValueType().isInteger()) {
3337 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3338 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3339 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3340 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3341 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3342 LR.getValueType(), LL, RL);
3343 AddToWorkList(ORNode.getNode());
3344 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3346 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3347 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3348 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3349 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3350 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3351 LR.getValueType(), LL, RL);
3352 AddToWorkList(ANDNode.getNode());
3353 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3356 // canonicalize equivalent to ll == rl
3357 if (LL == RR && LR == RL) {
3358 Op1 = ISD::getSetCCSwappedOperands(Op1);
3361 if (LL == RL && LR == RR) {
3362 bool isInteger = LL.getValueType().isInteger();
3363 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3364 if (Result != ISD::SETCC_INVALID &&
3365 (!LegalOperations ||
3366 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3367 TLI.isOperationLegal(ISD::SETCC,
3368 getSetCCResultType(N0.getValueType())))))
3369 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3374 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3375 if (N0.getOpcode() == N1.getOpcode()) {
3376 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3377 if (Tmp.getNode()) return Tmp;
3380 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3381 if (N0.getOpcode() == ISD::AND &&
3382 N1.getOpcode() == ISD::AND &&
3383 N0.getOperand(1).getOpcode() == ISD::Constant &&
3384 N1.getOperand(1).getOpcode() == ISD::Constant &&
3385 // Don't increase # computations.
3386 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3387 // We can only do this xform if we know that bits from X that are set in C2
3388 // but not in C1 are already zero. Likewise for Y.
3389 const APInt &LHSMask =
3390 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3391 const APInt &RHSMask =
3392 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3394 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3395 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3396 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3397 N0.getOperand(0), N1.getOperand(0));
3398 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3399 DAG.getConstant(LHSMask | RHSMask, VT));
3403 // See if this is some rotate idiom.
3404 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3405 return SDValue(Rot, 0);
3407 // Simplify the operands using demanded-bits information.
3408 if (!VT.isVector() &&
3409 SimplifyDemandedBits(SDValue(N, 0)))
3410 return SDValue(N, 0);
3415 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3416 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3417 if (Op.getOpcode() == ISD::AND) {
3418 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3419 Mask = Op.getOperand(1);
3420 Op = Op.getOperand(0);
3426 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3434 // Return true if we can prove that, whenever Neg and Pos are both in the
3435 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3436 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3438 // (or (shift1 X, Neg), (shift2 X, Pos))
3440 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3441 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3442 // to consider shift amounts with defined behavior.
3443 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3444 // If OpSize is a power of 2 then:
3446 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3447 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3449 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3450 // for the stronger condition:
3452 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3454 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3455 // we can just replace Neg with Neg' for the rest of the function.
3457 // In other cases we check for the even stronger condition:
3459 // Neg == OpSize - Pos [B]
3461 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3462 // behavior if Pos == 0 (and consequently Neg == OpSize).
3464 // We could actually use [A] whenever OpSize is a power of 2, but the
3465 // only extra cases that it would match are those uninteresting ones
3466 // where Neg and Pos are never in range at the same time. E.g. for
3467 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3468 // as well as (sub 32, Pos), but:
3470 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3472 // always invokes undefined behavior for 32-bit X.
3474 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3475 unsigned MaskLoBits = 0;
3476 if (Neg.getOpcode() == ISD::AND &&
3477 isPowerOf2_64(OpSize) &&
3478 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3479 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3480 Neg = Neg.getOperand(0);
3481 MaskLoBits = Log2_64(OpSize);
3484 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3485 if (Neg.getOpcode() != ISD::SUB)
3487 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3490 SDValue NegOp1 = Neg.getOperand(1);
3492 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3493 // Pos'. The truncation is redundant for the purpose of the equality.
3495 Pos.getOpcode() == ISD::AND &&
3496 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3497 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3498 Pos = Pos.getOperand(0);
3500 // The condition we need is now:
3502 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3504 // If NegOp1 == Pos then we need:
3506 // OpSize & Mask == NegC & Mask
3508 // (because "x & Mask" is a truncation and distributes through subtraction).
3511 Width = NegC->getAPIntValue();
3512 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3513 // Then the condition we want to prove becomes:
3515 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3517 // which, again because "x & Mask" is a truncation, becomes:
3519 // NegC & Mask == (OpSize - PosC) & Mask
3520 // OpSize & Mask == (NegC + PosC) & Mask
3521 else if (Pos.getOpcode() == ISD::ADD &&
3522 Pos.getOperand(0) == NegOp1 &&
3523 Pos.getOperand(1).getOpcode() == ISD::Constant)
3524 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3525 NegC->getAPIntValue());
3529 // Now we just need to check that OpSize & Mask == Width & Mask.
3531 // Opsize & Mask is 0 since Mask is Opsize - 1.
3532 return Width.getLoBits(MaskLoBits) == 0;
3533 return Width == OpSize;
3536 // A subroutine of MatchRotate used once we have found an OR of two opposite
3537 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3538 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3539 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3540 // Neg with outer conversions stripped away.
3541 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3542 SDValue Neg, SDValue InnerPos,
3543 SDValue InnerNeg, unsigned PosOpcode,
3544 unsigned NegOpcode, SDLoc DL) {
3545 // fold (or (shl x, (*ext y)),
3546 // (srl x, (*ext (sub 32, y)))) ->
3547 // (rotl x, y) or (rotr x, (sub 32, y))
3549 // fold (or (shl x, (*ext (sub 32, y))),
3550 // (srl x, (*ext y))) ->
3551 // (rotr x, y) or (rotl x, (sub 32, y))
3552 EVT VT = Shifted.getValueType();
3553 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3554 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3555 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3556 HasPos ? Pos : Neg).getNode();
3562 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3563 // idioms for rotate, and if the target supports rotation instructions, generate
3565 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3566 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3567 EVT VT = LHS.getValueType();
3568 if (!TLI.isTypeLegal(VT)) return nullptr;
3570 // The target must have at least one rotate flavor.
3571 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3572 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3573 if (!HasROTL && !HasROTR) return nullptr;
3575 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3576 SDValue LHSShift; // The shift.
3577 SDValue LHSMask; // AND value if any.
3578 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3579 return nullptr; // Not part of a rotate.
3581 SDValue RHSShift; // The shift.
3582 SDValue RHSMask; // AND value if any.
3583 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3584 return nullptr; // Not part of a rotate.
3586 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3587 return nullptr; // Not shifting the same value.
3589 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3590 return nullptr; // Shifts must disagree.
3592 // Canonicalize shl to left side in a shl/srl pair.
3593 if (RHSShift.getOpcode() == ISD::SHL) {
3594 std::swap(LHS, RHS);
3595 std::swap(LHSShift, RHSShift);
3596 std::swap(LHSMask , RHSMask );
3599 unsigned OpSizeInBits = VT.getSizeInBits();
3600 SDValue LHSShiftArg = LHSShift.getOperand(0);
3601 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3602 SDValue RHSShiftArg = RHSShift.getOperand(0);
3603 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3605 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3606 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3607 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3608 RHSShiftAmt.getOpcode() == ISD::Constant) {
3609 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3610 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3611 if ((LShVal + RShVal) != OpSizeInBits)
3614 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3615 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3617 // If there is an AND of either shifted operand, apply it to the result.
3618 if (LHSMask.getNode() || RHSMask.getNode()) {
3619 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3621 if (LHSMask.getNode()) {
3622 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3623 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3625 if (RHSMask.getNode()) {
3626 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3627 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3630 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3633 return Rot.getNode();
3636 // If there is a mask here, and we have a variable shift, we can't be sure
3637 // that we're masking out the right stuff.
3638 if (LHSMask.getNode() || RHSMask.getNode())
3641 // If the shift amount is sign/zext/any-extended just peel it off.
3642 SDValue LExtOp0 = LHSShiftAmt;
3643 SDValue RExtOp0 = RHSShiftAmt;
3644 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3645 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3646 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3647 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3648 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3649 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3650 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3651 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3652 LExtOp0 = LHSShiftAmt.getOperand(0);
3653 RExtOp0 = RHSShiftAmt.getOperand(0);
3656 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3657 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3661 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3662 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3669 SDValue DAGCombiner::visitXOR(SDNode *N) {
3670 SDValue N0 = N->getOperand(0);
3671 SDValue N1 = N->getOperand(1);
3672 SDValue LHS, RHS, CC;
3673 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3674 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3675 EVT VT = N0.getValueType();
3678 if (VT.isVector()) {
3679 SDValue FoldedVOp = SimplifyVBinOp(N);
3680 if (FoldedVOp.getNode()) return FoldedVOp;
3682 // fold (xor x, 0) -> x, vector edition
3683 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3685 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3689 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3690 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3691 return DAG.getConstant(0, VT);
3692 // fold (xor x, undef) -> undef
3693 if (N0.getOpcode() == ISD::UNDEF)
3695 if (N1.getOpcode() == ISD::UNDEF)
3697 // fold (xor c1, c2) -> c1^c2
3699 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3700 // canonicalize constant to RHS
3702 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3703 // fold (xor x, 0) -> x
3704 if (N1C && N1C->isNullValue())
3707 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3711 // fold !(x cc y) -> (x !cc y)
3712 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3713 bool isInt = LHS.getValueType().isInteger();
3714 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3717 if (!LegalOperations ||
3718 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3719 switch (N0.getOpcode()) {
3721 llvm_unreachable("Unhandled SetCC Equivalent!");
3723 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3724 case ISD::SELECT_CC:
3725 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3726 N0.getOperand(3), NotCC);
3731 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3732 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3733 N0.getNode()->hasOneUse() &&
3734 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3735 SDValue V = N0.getOperand(0);
3736 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3737 DAG.getConstant(1, V.getValueType()));
3738 AddToWorkList(V.getNode());
3739 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3742 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3743 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3744 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3745 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3746 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3747 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3748 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3749 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3750 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3751 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3754 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3755 if (N1C && N1C->isAllOnesValue() &&
3756 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3757 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3758 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3759 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3760 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3761 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3762 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3763 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3766 // fold (xor (and x, y), y) -> (and (not x), y)
3767 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3768 N0->getOperand(1) == N1) {
3769 SDValue X = N0->getOperand(0);
3770 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3771 AddToWorkList(NotX.getNode());
3772 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3774 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3775 if (N1C && N0.getOpcode() == ISD::XOR) {
3776 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3777 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3779 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3780 DAG.getConstant(N1C->getAPIntValue() ^
3781 N00C->getAPIntValue(), VT));
3783 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3784 DAG.getConstant(N1C->getAPIntValue() ^
3785 N01C->getAPIntValue(), VT));
3787 // fold (xor x, x) -> 0
3789 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3791 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3792 if (N0.getOpcode() == N1.getOpcode()) {
3793 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3794 if (Tmp.getNode()) return Tmp;
3797 // Simplify the expression using non-local knowledge.
3798 if (!VT.isVector() &&
3799 SimplifyDemandedBits(SDValue(N, 0)))
3800 return SDValue(N, 0);
3805 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3806 /// the shift amount is a constant.
3807 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3808 // We can't and shouldn't fold opaque constants.
3809 if (Amt->isOpaque())
3812 SDNode *LHS = N->getOperand(0).getNode();
3813 if (!LHS->hasOneUse()) return SDValue();
3815 // We want to pull some binops through shifts, so that we have (and (shift))
3816 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3817 // thing happens with address calculations, so it's important to canonicalize
3819 bool HighBitSet = false; // Can we transform this if the high bit is set?
3821 switch (LHS->getOpcode()) {
3822 default: return SDValue();
3825 HighBitSet = false; // We can only transform sra if the high bit is clear.
3828 HighBitSet = true; // We can only transform sra if the high bit is set.
3831 if (N->getOpcode() != ISD::SHL)
3832 return SDValue(); // only shl(add) not sr[al](add).
3833 HighBitSet = false; // We can only transform sra if the high bit is clear.
3837 // We require the RHS of the binop to be a constant and not opaque as well.
3838 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3839 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3841 // FIXME: disable this unless the input to the binop is a shift by a constant.
3842 // If it is not a shift, it pessimizes some common cases like:
3844 // void foo(int *X, int i) { X[i & 1235] = 1; }
3845 // int bar(int *X, int i) { return X[i & 255]; }
3846 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3847 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3848 BinOpLHSVal->getOpcode() != ISD::SRA &&
3849 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3850 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3853 EVT VT = N->getValueType(0);
3855 // If this is a signed shift right, and the high bit is modified by the
3856 // logical operation, do not perform the transformation. The highBitSet
3857 // boolean indicates the value of the high bit of the constant which would
3858 // cause it to be modified for this operation.
3859 if (N->getOpcode() == ISD::SRA) {
3860 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3861 if (BinOpRHSSignSet != HighBitSet)
3865 // Fold the constants, shifting the binop RHS by the shift amount.
3866 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3868 LHS->getOperand(1), N->getOperand(1));
3869 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3871 // Create the new shift.
3872 SDValue NewShift = DAG.getNode(N->getOpcode(),
3873 SDLoc(LHS->getOperand(0)),
3874 VT, LHS->getOperand(0), N->getOperand(1));
3876 // Create the new binop.
3877 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3880 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3881 assert(N->getOpcode() == ISD::TRUNCATE);
3882 assert(N->getOperand(0).getOpcode() == ISD::AND);
3884 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3885 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3886 SDValue N01 = N->getOperand(0).getOperand(1);
3888 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3889 EVT TruncVT = N->getValueType(0);
3890 SDValue N00 = N->getOperand(0).getOperand(0);
3891 APInt TruncC = N01C->getAPIntValue();
3892 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3894 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3895 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3896 DAG.getConstant(TruncC, TruncVT));
3903 SDValue DAGCombiner::visitRotate(SDNode *N) {
3904 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3905 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3906 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3907 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3908 if (NewOp1.getNode())
3909 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3910 N->getOperand(0), NewOp1);
3915 SDValue DAGCombiner::visitSHL(SDNode *N) {
3916 SDValue N0 = N->getOperand(0);
3917 SDValue N1 = N->getOperand(1);
3918 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3919 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3920 EVT VT = N0.getValueType();
3921 unsigned OpSizeInBits = VT.getScalarSizeInBits();
3924 if (VT.isVector()) {
3925 SDValue FoldedVOp = SimplifyVBinOp(N);
3926 if (FoldedVOp.getNode()) return FoldedVOp;
3928 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3929 // If setcc produces all-one true value then:
3930 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
3931 if (N1CV && N1CV->isConstant()) {
3932 if (N0.getOpcode() == ISD::AND &&
3933 TLI.getBooleanContents(true) ==
3934 TargetLowering::ZeroOrNegativeOneBooleanContent) {
3935 SDValue N00 = N0->getOperand(0);
3936 SDValue N01 = N0->getOperand(1);
3937 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
3939 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC) {
3940 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3942 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3945 N1C = isConstOrConstSplat(N1);
3950 // fold (shl c1, c2) -> c1<<c2
3952 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3953 // fold (shl 0, x) -> 0
3954 if (N0C && N0C->isNullValue())
3956 // fold (shl x, c >= size(x)) -> undef
3957 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3958 return DAG.getUNDEF(VT);
3959 // fold (shl x, 0) -> x
3960 if (N1C && N1C->isNullValue())
3962 // fold (shl undef, x) -> 0
3963 if (N0.getOpcode() == ISD::UNDEF)
3964 return DAG.getConstant(0, VT);
3965 // if (shl x, c) is known to be zero, return 0
3966 if (DAG.MaskedValueIsZero(SDValue(N, 0),
3967 APInt::getAllOnesValue(OpSizeInBits)))
3968 return DAG.getConstant(0, VT);
3969 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3970 if (N1.getOpcode() == ISD::TRUNCATE &&
3971 N1.getOperand(0).getOpcode() == ISD::AND) {
3972 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
3973 if (NewOp1.getNode())
3974 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
3977 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3978 return SDValue(N, 0);
3980 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3981 if (N1C && N0.getOpcode() == ISD::SHL) {
3982 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
3983 uint64_t c1 = N0C1->getZExtValue();
3984 uint64_t c2 = N1C->getZExtValue();
3985 if (c1 + c2 >= OpSizeInBits)
3986 return DAG.getConstant(0, VT);
3987 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3988 DAG.getConstant(c1 + c2, N1.getValueType()));
3992 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3993 // For this to be valid, the second form must not preserve any of the bits
3994 // that are shifted out by the inner shift in the first form. This means
3995 // the outer shift size must be >= the number of bits added by the ext.
3996 // As a corollary, we don't care what kind of ext it is.
3997 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3998 N0.getOpcode() == ISD::ANY_EXTEND ||
3999 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4000 N0.getOperand(0).getOpcode() == ISD::SHL) {
4001 SDValue N0Op0 = N0.getOperand(0);
4002 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4003 uint64_t c1 = N0Op0C1->getZExtValue();
4004 uint64_t c2 = N1C->getZExtValue();
4005 EVT InnerShiftVT = N0Op0.getValueType();
4006 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4007 if (c2 >= OpSizeInBits - InnerShiftSize) {
4008 if (c1 + c2 >= OpSizeInBits)
4009 return DAG.getConstant(0, VT);
4010 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4011 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4012 N0Op0->getOperand(0)),
4013 DAG.getConstant(c1 + c2, N1.getValueType()));
4018 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4019 // Only fold this if the inner zext has no other uses to avoid increasing
4020 // the total number of instructions.
4021 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4022 N0.getOperand(0).getOpcode() == ISD::SRL) {
4023 SDValue N0Op0 = N0.getOperand(0);
4024 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4025 uint64_t c1 = N0Op0C1->getZExtValue();
4026 if (c1 < VT.getScalarSizeInBits()) {
4027 uint64_t c2 = N1C->getZExtValue();
4029 SDValue NewOp0 = N0.getOperand(0);
4030 EVT CountVT = NewOp0.getOperand(1).getValueType();
4031 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4032 NewOp0, DAG.getConstant(c2, CountVT));
4033 AddToWorkList(NewSHL.getNode());
4034 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4040 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4041 // (and (srl x, (sub c1, c2), MASK)
4042 // Only fold this if the inner shift has no other uses -- if it does, folding
4043 // this will increase the total number of instructions.
4044 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4045 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4046 uint64_t c1 = N0C1->getZExtValue();
4047 if (c1 < OpSizeInBits) {
4048 uint64_t c2 = N1C->getZExtValue();
4049 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4052 Mask = Mask.shl(c2 - c1);
4053 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4054 DAG.getConstant(c2 - c1, N1.getValueType()));
4056 Mask = Mask.lshr(c1 - c2);
4057 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4058 DAG.getConstant(c1 - c2, N1.getValueType()));
4060 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4061 DAG.getConstant(Mask, VT));
4065 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4066 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4067 unsigned BitSize = VT.getScalarSizeInBits();
4068 SDValue HiBitsMask =
4069 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4070 BitSize - N1C->getZExtValue()), VT);
4071 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4076 SDValue NewSHL = visitShiftByConstant(N, N1C);
4077 if (NewSHL.getNode())
4084 SDValue DAGCombiner::visitSRA(SDNode *N) {
4085 SDValue N0 = N->getOperand(0);
4086 SDValue N1 = N->getOperand(1);
4087 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4088 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4089 EVT VT = N0.getValueType();
4090 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4093 if (VT.isVector()) {
4094 SDValue FoldedVOp = SimplifyVBinOp(N);
4095 if (FoldedVOp.getNode()) return FoldedVOp;
4097 N1C = isConstOrConstSplat(N1);
4100 // fold (sra c1, c2) -> (sra c1, c2)
4102 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4103 // fold (sra 0, x) -> 0
4104 if (N0C && N0C->isNullValue())
4106 // fold (sra -1, x) -> -1
4107 if (N0C && N0C->isAllOnesValue())
4109 // fold (sra x, (setge c, size(x))) -> undef
4110 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4111 return DAG.getUNDEF(VT);
4112 // fold (sra x, 0) -> x
4113 if (N1C && N1C->isNullValue())
4115 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4117 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4118 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4119 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4121 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4122 ExtVT, VT.getVectorNumElements());
4123 if ((!LegalOperations ||
4124 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4125 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4126 N0.getOperand(0), DAG.getValueType(ExtVT));
4129 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4130 if (N1C && N0.getOpcode() == ISD::SRA) {
4131 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4132 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4133 if (Sum >= OpSizeInBits)
4134 Sum = OpSizeInBits - 1;
4135 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4136 DAG.getConstant(Sum, N1.getValueType()));
4140 // fold (sra (shl X, m), (sub result_size, n))
4141 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4142 // result_size - n != m.
4143 // If truncate is free for the target sext(shl) is likely to result in better
4145 if (N0.getOpcode() == ISD::SHL && N1C) {
4146 // Get the two constanst of the shifts, CN0 = m, CN = n.
4147 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4149 LLVMContext &Ctx = *DAG.getContext();
4150 // Determine what the truncate's result bitsize and type would be.
4151 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4154 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4156 // Determine the residual right-shift amount.
4157 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4159 // If the shift is not a no-op (in which case this should be just a sign
4160 // extend already), the truncated to type is legal, sign_extend is legal
4161 // on that type, and the truncate to that type is both legal and free,
4162 // perform the transform.
4163 if ((ShiftAmt > 0) &&
4164 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4165 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4166 TLI.isTruncateFree(VT, TruncVT)) {
4168 SDValue Amt = DAG.getConstant(ShiftAmt,
4169 getShiftAmountTy(N0.getOperand(0).getValueType()));
4170 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4171 N0.getOperand(0), Amt);
4172 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4174 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4175 N->getValueType(0), Trunc);
4180 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4181 if (N1.getOpcode() == ISD::TRUNCATE &&
4182 N1.getOperand(0).getOpcode() == ISD::AND) {
4183 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4184 if (NewOp1.getNode())
4185 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4188 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4189 // if c1 is equal to the number of bits the trunc removes
4190 if (N0.getOpcode() == ISD::TRUNCATE &&
4191 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4192 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4193 N0.getOperand(0).hasOneUse() &&
4194 N0.getOperand(0).getOperand(1).hasOneUse() &&
4196 SDValue N0Op0 = N0.getOperand(0);
4197 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4198 unsigned LargeShiftVal = LargeShift->getZExtValue();
4199 EVT LargeVT = N0Op0.getValueType();
4201 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4203 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4204 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4205 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4206 N0Op0.getOperand(0), Amt);
4207 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4212 // Simplify, based on bits shifted out of the LHS.
4213 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4214 return SDValue(N, 0);
4217 // If the sign bit is known to be zero, switch this to a SRL.
4218 if (DAG.SignBitIsZero(N0))
4219 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4222 SDValue NewSRA = visitShiftByConstant(N, N1C);
4223 if (NewSRA.getNode())
4230 SDValue DAGCombiner::visitSRL(SDNode *N) {
4231 SDValue N0 = N->getOperand(0);
4232 SDValue N1 = N->getOperand(1);
4233 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4234 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4235 EVT VT = N0.getValueType();
4236 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4239 if (VT.isVector()) {
4240 SDValue FoldedVOp = SimplifyVBinOp(N);
4241 if (FoldedVOp.getNode()) return FoldedVOp;
4243 N1C = isConstOrConstSplat(N1);
4246 // fold (srl c1, c2) -> c1 >>u c2
4248 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4249 // fold (srl 0, x) -> 0
4250 if (N0C && N0C->isNullValue())
4252 // fold (srl x, c >= size(x)) -> undef
4253 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4254 return DAG.getUNDEF(VT);
4255 // fold (srl x, 0) -> x
4256 if (N1C && N1C->isNullValue())
4258 // if (srl x, c) is known to be zero, return 0
4259 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4260 APInt::getAllOnesValue(OpSizeInBits)))
4261 return DAG.getConstant(0, VT);
4263 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4264 if (N1C && N0.getOpcode() == ISD::SRL) {
4265 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4266 uint64_t c1 = N01C->getZExtValue();
4267 uint64_t c2 = N1C->getZExtValue();
4268 if (c1 + c2 >= OpSizeInBits)
4269 return DAG.getConstant(0, VT);
4270 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4271 DAG.getConstant(c1 + c2, N1.getValueType()));
4275 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4276 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4277 N0.getOperand(0).getOpcode() == ISD::SRL &&
4278 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4280 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4281 uint64_t c2 = N1C->getZExtValue();
4282 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4283 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4284 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4285 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4286 if (c1 + OpSizeInBits == InnerShiftSize) {
4287 if (c1 + c2 >= InnerShiftSize)
4288 return DAG.getConstant(0, VT);
4289 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4290 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4291 N0.getOperand(0)->getOperand(0),
4292 DAG.getConstant(c1 + c2, ShiftCountVT)));
4296 // fold (srl (shl x, c), c) -> (and x, cst2)
4297 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4298 unsigned BitSize = N0.getScalarValueSizeInBits();
4299 if (BitSize <= 64) {
4300 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4301 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4302 DAG.getConstant(~0ULL >> ShAmt, VT));
4306 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4307 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4308 // Shifting in all undef bits?
4309 EVT SmallVT = N0.getOperand(0).getValueType();
4310 unsigned BitSize = SmallVT.getScalarSizeInBits();
4311 if (N1C->getZExtValue() >= BitSize)
4312 return DAG.getUNDEF(VT);
4314 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4315 uint64_t ShiftAmt = N1C->getZExtValue();
4316 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4318 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4319 AddToWorkList(SmallShift.getNode());
4320 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4321 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4322 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4323 DAG.getConstant(Mask, VT));
4327 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4328 // bit, which is unmodified by sra.
4329 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4330 if (N0.getOpcode() == ISD::SRA)
4331 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4334 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4335 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4336 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4337 APInt KnownZero, KnownOne;
4338 DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
4340 // If any of the input bits are KnownOne, then the input couldn't be all
4341 // zeros, thus the result of the srl will always be zero.
4342 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4344 // If all of the bits input the to ctlz node are known to be zero, then
4345 // the result of the ctlz is "32" and the result of the shift is one.
4346 APInt UnknownBits = ~KnownZero;
4347 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4349 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4350 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4351 // Okay, we know that only that the single bit specified by UnknownBits
4352 // could be set on input to the CTLZ node. If this bit is set, the SRL
4353 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4354 // to an SRL/XOR pair, which is likely to simplify more.
4355 unsigned ShAmt = UnknownBits.countTrailingZeros();
4356 SDValue Op = N0.getOperand(0);
4359 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4360 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4361 AddToWorkList(Op.getNode());
4364 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4365 Op, DAG.getConstant(1, VT));
4369 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4370 if (N1.getOpcode() == ISD::TRUNCATE &&
4371 N1.getOperand(0).getOpcode() == ISD::AND) {
4372 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4373 if (NewOp1.getNode())
4374 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4377 // fold operands of srl based on knowledge that the low bits are not
4379 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4380 return SDValue(N, 0);
4383 SDValue NewSRL = visitShiftByConstant(N, N1C);
4384 if (NewSRL.getNode())
4388 // Attempt to convert a srl of a load into a narrower zero-extending load.
4389 SDValue NarrowLoad = ReduceLoadWidth(N);
4390 if (NarrowLoad.getNode())
4393 // Here is a common situation. We want to optimize:
4396 // %b = and i32 %a, 2
4397 // %c = srl i32 %b, 1
4398 // brcond i32 %c ...
4404 // %c = setcc eq %b, 0
4407 // However when after the source operand of SRL is optimized into AND, the SRL
4408 // itself may not be optimized further. Look for it and add the BRCOND into
4410 if (N->hasOneUse()) {
4411 SDNode *Use = *N->use_begin();
4412 if (Use->getOpcode() == ISD::BRCOND)
4414 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4415 // Also look pass the truncate.
4416 Use = *Use->use_begin();
4417 if (Use->getOpcode() == ISD::BRCOND)
4425 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4426 SDValue N0 = N->getOperand(0);
4427 EVT VT = N->getValueType(0);
4429 // fold (ctlz c1) -> c2
4430 if (isa<ConstantSDNode>(N0))
4431 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4435 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4436 SDValue N0 = N->getOperand(0);
4437 EVT VT = N->getValueType(0);
4439 // fold (ctlz_zero_undef c1) -> c2
4440 if (isa<ConstantSDNode>(N0))
4441 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4445 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4446 SDValue N0 = N->getOperand(0);
4447 EVT VT = N->getValueType(0);
4449 // fold (cttz c1) -> c2
4450 if (isa<ConstantSDNode>(N0))
4451 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4455 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4456 SDValue N0 = N->getOperand(0);
4457 EVT VT = N->getValueType(0);
4459 // fold (cttz_zero_undef c1) -> c2
4460 if (isa<ConstantSDNode>(N0))
4461 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4465 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4466 SDValue N0 = N->getOperand(0);
4467 EVT VT = N->getValueType(0);
4469 // fold (ctpop c1) -> c2
4470 if (isa<ConstantSDNode>(N0))
4471 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4475 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4476 SDValue N0 = N->getOperand(0);
4477 SDValue N1 = N->getOperand(1);
4478 SDValue N2 = N->getOperand(2);
4479 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4480 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4481 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4482 EVT VT = N->getValueType(0);
4483 EVT VT0 = N0.getValueType();
4485 // fold (select C, X, X) -> X
4488 // fold (select true, X, Y) -> X
4489 if (N0C && !N0C->isNullValue())
4491 // fold (select false, X, Y) -> Y
4492 if (N0C && N0C->isNullValue())
4494 // fold (select C, 1, X) -> (or C, X)
4495 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4496 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4497 // fold (select C, 0, 1) -> (xor C, 1)
4498 if (VT.isInteger() &&
4501 TLI.getBooleanContents(false) ==
4502 TargetLowering::ZeroOrOneBooleanContent)) &&
4503 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4506 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4507 N0, DAG.getConstant(1, VT0));
4508 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4509 N0, DAG.getConstant(1, VT0));
4510 AddToWorkList(XORNode.getNode());
4512 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4513 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4515 // fold (select C, 0, X) -> (and (not C), X)
4516 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4517 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4518 AddToWorkList(NOTNode.getNode());
4519 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4521 // fold (select C, X, 1) -> (or (not C), X)
4522 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4523 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4524 AddToWorkList(NOTNode.getNode());
4525 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4527 // fold (select C, X, 0) -> (and C, X)
4528 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4529 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4530 // fold (select X, X, Y) -> (or X, Y)
4531 // fold (select X, 1, Y) -> (or X, Y)
4532 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4533 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4534 // fold (select X, Y, X) -> (and X, Y)
4535 // fold (select X, Y, 0) -> (and X, Y)
4536 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4537 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4539 // If we can fold this based on the true/false value, do so.
4540 if (SimplifySelectOps(N, N1, N2))
4541 return SDValue(N, 0); // Don't revisit N.
4543 // fold selects based on a setcc into other things, such as min/max/abs
4544 if (N0.getOpcode() == ISD::SETCC) {
4546 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4547 // having to say they don't support SELECT_CC on every type the DAG knows
4548 // about, since there is no way to mark an opcode illegal at all value types
4549 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4550 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4551 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4552 N0.getOperand(0), N0.getOperand(1),
4553 N1, N2, N0.getOperand(2));
4554 return SimplifySelect(SDLoc(N), N0, N1, N2);
4561 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4564 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4566 // Split the inputs.
4567 SDValue Lo, Hi, LL, LH, RL, RH;
4568 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4569 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4571 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4572 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4574 return std::make_pair(Lo, Hi);
4577 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4578 SDValue N0 = N->getOperand(0);
4579 SDValue N1 = N->getOperand(1);
4580 SDValue N2 = N->getOperand(2);
4583 // Canonicalize integer abs.
4584 // vselect (setg[te] X, 0), X, -X ->
4585 // vselect (setgt X, -1), X, -X ->
4586 // vselect (setl[te] X, 0), -X, X ->
4587 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4588 if (N0.getOpcode() == ISD::SETCC) {
4589 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4590 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4592 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4594 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4595 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4596 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4597 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4598 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4599 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4600 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4603 EVT VT = LHS.getValueType();
4604 SDValue Shift = DAG.getNode(
4605 ISD::SRA, DL, VT, LHS,
4606 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4607 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4608 AddToWorkList(Shift.getNode());
4609 AddToWorkList(Add.getNode());
4610 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4614 // If the VSELECT result requires splitting and the mask is provided by a
4615 // SETCC, then split both nodes and its operands before legalization. This
4616 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4617 // and enables future optimizations (e.g. min/max pattern matching on X86).
4618 if (N0.getOpcode() == ISD::SETCC) {
4619 EVT VT = N->getValueType(0);
4621 // Check if any splitting is required.
4622 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4623 TargetLowering::TypeSplitVector)
4626 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4627 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4628 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4629 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4631 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4632 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4634 // Add the new VSELECT nodes to the work list in case they need to be split
4636 AddToWorkList(Lo.getNode());
4637 AddToWorkList(Hi.getNode());
4639 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4642 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4643 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4645 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4646 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4652 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4653 SDValue N0 = N->getOperand(0);
4654 SDValue N1 = N->getOperand(1);
4655 SDValue N2 = N->getOperand(2);
4656 SDValue N3 = N->getOperand(3);
4657 SDValue N4 = N->getOperand(4);
4658 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4660 // fold select_cc lhs, rhs, x, x, cc -> x
4664 // Determine if the condition we're dealing with is constant
4665 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4666 N0, N1, CC, SDLoc(N), false);
4667 if (SCC.getNode()) {
4668 AddToWorkList(SCC.getNode());
4670 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4671 if (!SCCC->isNullValue())
4672 return N2; // cond always true -> true val
4674 return N3; // cond always false -> false val
4677 // Fold to a simpler select_cc
4678 if (SCC.getOpcode() == ISD::SETCC)
4679 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4680 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4684 // If we can fold this based on the true/false value, do so.
4685 if (SimplifySelectOps(N, N2, N3))
4686 return SDValue(N, 0); // Don't revisit N.
4688 // fold select_cc into other things, such as min/max/abs
4689 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4692 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4693 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4694 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4698 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4699 // dag node into a ConstantSDNode or a build_vector of constants.
4700 // This function is called by the DAGCombiner when visiting sext/zext/aext
4701 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4702 // Vector extends are not folded if operations are legal; this is to
4703 // avoid introducing illegal build_vector dag nodes.
4704 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4705 SelectionDAG &DAG, bool LegalTypes,
4706 bool LegalOperations) {
4707 unsigned Opcode = N->getOpcode();
4708 SDValue N0 = N->getOperand(0);
4709 EVT VT = N->getValueType(0);
4711 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4712 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4714 // fold (sext c1) -> c1
4715 // fold (zext c1) -> c1
4716 // fold (aext c1) -> c1
4717 if (isa<ConstantSDNode>(N0))
4718 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4720 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4721 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4722 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4723 EVT SVT = VT.getScalarType();
4724 if (!(VT.isVector() &&
4725 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4726 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4729 // We can fold this node into a build_vector.
4730 unsigned VTBits = SVT.getSizeInBits();
4731 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4732 unsigned ShAmt = VTBits - EVTBits;
4733 SmallVector<SDValue, 8> Elts;
4734 unsigned NumElts = N0->getNumOperands();
4737 for (unsigned i=0; i != NumElts; ++i) {
4738 SDValue Op = N0->getOperand(i);
4739 if (Op->getOpcode() == ISD::UNDEF) {
4740 Elts.push_back(DAG.getUNDEF(SVT));
4744 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4745 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4746 if (Opcode == ISD::SIGN_EXTEND)
4747 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4750 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4754 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], NumElts).getNode();
4757 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4758 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4759 // transformation. Returns true if extension are possible and the above
4760 // mentioned transformation is profitable.
4761 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4763 SmallVectorImpl<SDNode *> &ExtendNodes,
4764 const TargetLowering &TLI) {
4765 bool HasCopyToRegUses = false;
4766 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4767 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4768 UE = N0.getNode()->use_end();
4773 if (UI.getUse().getResNo() != N0.getResNo())
4775 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4776 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4777 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4778 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4779 // Sign bits will be lost after a zext.
4782 for (unsigned i = 0; i != 2; ++i) {
4783 SDValue UseOp = User->getOperand(i);
4786 if (!isa<ConstantSDNode>(UseOp))
4791 ExtendNodes.push_back(User);
4794 // If truncates aren't free and there are users we can't
4795 // extend, it isn't worthwhile.
4798 // Remember if this value is live-out.
4799 if (User->getOpcode() == ISD::CopyToReg)
4800 HasCopyToRegUses = true;
4803 if (HasCopyToRegUses) {
4804 bool BothLiveOut = false;
4805 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4807 SDUse &Use = UI.getUse();
4808 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4814 // Both unextended and extended values are live out. There had better be
4815 // a good reason for the transformation.
4816 return ExtendNodes.size();
4821 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4822 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4823 ISD::NodeType ExtType) {
4824 // Extend SetCC uses if necessary.
4825 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4826 SDNode *SetCC = SetCCs[i];
4827 SmallVector<SDValue, 4> Ops;
4829 for (unsigned j = 0; j != 2; ++j) {
4830 SDValue SOp = SetCC->getOperand(j);
4832 Ops.push_back(ExtLoad);
4834 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4837 Ops.push_back(SetCC->getOperand(2));
4838 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4839 &Ops[0], Ops.size()));
4843 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4844 SDValue N0 = N->getOperand(0);
4845 EVT VT = N->getValueType(0);
4847 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4849 return SDValue(Res, 0);
4851 // fold (sext (sext x)) -> (sext x)
4852 // fold (sext (aext x)) -> (sext x)
4853 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4854 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4857 if (N0.getOpcode() == ISD::TRUNCATE) {
4858 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4859 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4860 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4861 if (NarrowLoad.getNode()) {
4862 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4863 if (NarrowLoad.getNode() != N0.getNode()) {
4864 CombineTo(N0.getNode(), NarrowLoad);
4865 // CombineTo deleted the truncate, if needed, but not what's under it.
4868 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4871 // See if the value being truncated is already sign extended. If so, just
4872 // eliminate the trunc/sext pair.
4873 SDValue Op = N0.getOperand(0);
4874 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4875 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4876 unsigned DestBits = VT.getScalarType().getSizeInBits();
4877 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4879 if (OpBits == DestBits) {
4880 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4881 // bits, it is already ready.
4882 if (NumSignBits > DestBits-MidBits)
4884 } else if (OpBits < DestBits) {
4885 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4886 // bits, just sext from i32.
4887 if (NumSignBits > OpBits-MidBits)
4888 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4890 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4891 // bits, just truncate to i32.
4892 if (NumSignBits > OpBits-MidBits)
4893 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4896 // fold (sext (truncate x)) -> (sextinreg x).
4897 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4898 N0.getValueType())) {
4899 if (OpBits < DestBits)
4900 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4901 else if (OpBits > DestBits)
4902 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4903 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4904 DAG.getValueType(N0.getValueType()));
4908 // fold (sext (load x)) -> (sext (truncate (sextload x)))
4909 // None of the supported targets knows how to perform load and sign extend
4910 // on vectors in one instruction. We only perform this transformation on
4912 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4913 ISD::isUNINDEXEDLoad(N0.getNode()) &&
4914 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4915 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4916 bool DoXform = true;
4917 SmallVector<SDNode*, 4> SetCCs;
4918 if (!N0.hasOneUse())
4919 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4921 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4922 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4924 LN0->getBasePtr(), N0.getValueType(),
4925 LN0->getMemOperand());
4926 CombineTo(N, ExtLoad);
4927 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4928 N0.getValueType(), ExtLoad);
4929 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4930 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4932 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4936 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4937 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4938 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4939 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4940 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4941 EVT MemVT = LN0->getMemoryVT();
4942 if ((!LegalOperations && !LN0->isVolatile()) ||
4943 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4944 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4946 LN0->getBasePtr(), MemVT,
4947 LN0->getMemOperand());
4948 CombineTo(N, ExtLoad);
4949 CombineTo(N0.getNode(),
4950 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4951 N0.getValueType(), ExtLoad),
4952 ExtLoad.getValue(1));
4953 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4957 // fold (sext (and/or/xor (load x), cst)) ->
4958 // (and/or/xor (sextload x), (sext cst))
4959 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4960 N0.getOpcode() == ISD::XOR) &&
4961 isa<LoadSDNode>(N0.getOperand(0)) &&
4962 N0.getOperand(1).getOpcode() == ISD::Constant &&
4963 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4964 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4965 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4966 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
4967 bool DoXform = true;
4968 SmallVector<SDNode*, 4> SetCCs;
4969 if (!N0.hasOneUse())
4970 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4973 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
4974 LN0->getChain(), LN0->getBasePtr(),
4976 LN0->getMemOperand());
4977 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4978 Mask = Mask.sext(VT.getSizeInBits());
4979 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4980 ExtLoad, DAG.getConstant(Mask, VT));
4981 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4982 SDLoc(N0.getOperand(0)),
4983 N0.getOperand(0).getValueType(), ExtLoad);
4985 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4986 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4988 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4993 if (N0.getOpcode() == ISD::SETCC) {
4994 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
4995 // Only do this before legalize for now.
4996 if (VT.isVector() && !LegalOperations &&
4997 TLI.getBooleanContents(true) ==
4998 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4999 EVT N0VT = N0.getOperand(0).getValueType();
5000 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5001 // of the same size as the compared operands. Only optimize sext(setcc())
5002 // if this is the case.
5003 EVT SVT = getSetCCResultType(N0VT);
5005 // We know that the # elements of the results is the same as the
5006 // # elements of the compare (and the # elements of the compare result
5007 // for that matter). Check to see that they are the same size. If so,
5008 // we know that the element size of the sext'd result matches the
5009 // element size of the compare operands.
5010 if (VT.getSizeInBits() == SVT.getSizeInBits())
5011 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5013 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5015 // If the desired elements are smaller or larger than the source
5016 // elements we can use a matching integer vector type and then
5017 // truncate/sign extend
5018 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5019 if (SVT == MatchingVectorType) {
5020 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5021 N0.getOperand(0), N0.getOperand(1),
5022 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5023 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5027 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5028 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5030 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5032 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5033 NegOne, DAG.getConstant(0, VT),
5034 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5035 if (SCC.getNode()) return SCC;
5037 if (!VT.isVector()) {
5038 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5039 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5041 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5042 SDValue SetCC = DAG.getSetCC(DL,
5044 N0.getOperand(0), N0.getOperand(1), CC);
5045 EVT SelectVT = getSetCCResultType(VT);
5046 return DAG.getSelect(DL, VT,
5047 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5048 NegOne, DAG.getConstant(0, VT));
5054 // fold (sext x) -> (zext x) if the sign bit is known zero.
5055 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5056 DAG.SignBitIsZero(N0))
5057 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5062 // isTruncateOf - If N is a truncate of some other value, return true, record
5063 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5064 // This function computes KnownZero to avoid a duplicated call to
5065 // ComputeMaskedBits in the caller.
5066 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5069 if (N->getOpcode() == ISD::TRUNCATE) {
5070 Op = N->getOperand(0);
5071 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5075 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5076 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5079 SDValue Op0 = N->getOperand(0);
5080 SDValue Op1 = N->getOperand(1);
5081 assert(Op0.getValueType() == Op1.getValueType());
5083 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5084 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5085 if (COp0 && COp0->isNullValue())
5087 else if (COp1 && COp1->isNullValue())
5092 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5094 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5100 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5101 SDValue N0 = N->getOperand(0);
5102 EVT VT = N->getValueType(0);
5104 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5106 return SDValue(Res, 0);
5108 // fold (zext (zext x)) -> (zext x)
5109 // fold (zext (aext x)) -> (zext x)
5110 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5111 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5114 // fold (zext (truncate x)) -> (zext x) or
5115 // (zext (truncate x)) -> (truncate x)
5116 // This is valid when the truncated bits of x are already zero.
5117 // FIXME: We should extend this to work for vectors too.
5120 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5121 APInt TruncatedBits =
5122 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5123 APInt(Op.getValueSizeInBits(), 0) :
5124 APInt::getBitsSet(Op.getValueSizeInBits(),
5125 N0.getValueSizeInBits(),
5126 std::min(Op.getValueSizeInBits(),
5127 VT.getSizeInBits()));
5128 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5129 if (VT.bitsGT(Op.getValueType()))
5130 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5131 if (VT.bitsLT(Op.getValueType()))
5132 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5138 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5139 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5140 if (N0.getOpcode() == ISD::TRUNCATE) {
5141 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5142 if (NarrowLoad.getNode()) {
5143 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5144 if (NarrowLoad.getNode() != N0.getNode()) {
5145 CombineTo(N0.getNode(), NarrowLoad);
5146 // CombineTo deleted the truncate, if needed, but not what's under it.
5149 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5153 // fold (zext (truncate x)) -> (and x, mask)
5154 if (N0.getOpcode() == ISD::TRUNCATE &&
5155 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5157 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5158 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5159 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5160 if (NarrowLoad.getNode()) {
5161 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5162 if (NarrowLoad.getNode() != N0.getNode()) {
5163 CombineTo(N0.getNode(), NarrowLoad);
5164 // CombineTo deleted the truncate, if needed, but not what's under it.
5167 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5170 SDValue Op = N0.getOperand(0);
5171 if (Op.getValueType().bitsLT(VT)) {
5172 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5173 AddToWorkList(Op.getNode());
5174 } else if (Op.getValueType().bitsGT(VT)) {
5175 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5176 AddToWorkList(Op.getNode());
5178 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5179 N0.getValueType().getScalarType());
5182 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5183 // if either of the casts is not free.
5184 if (N0.getOpcode() == ISD::AND &&
5185 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5186 N0.getOperand(1).getOpcode() == ISD::Constant &&
5187 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5188 N0.getValueType()) ||
5189 !TLI.isZExtFree(N0.getValueType(), VT))) {
5190 SDValue X = N0.getOperand(0).getOperand(0);
5191 if (X.getValueType().bitsLT(VT)) {
5192 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5193 } else if (X.getValueType().bitsGT(VT)) {
5194 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5196 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5197 Mask = Mask.zext(VT.getSizeInBits());
5198 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5199 X, DAG.getConstant(Mask, VT));
5202 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5203 // None of the supported targets knows how to perform load and vector_zext
5204 // on vectors in one instruction. We only perform this transformation on
5206 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5207 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5208 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5209 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5210 bool DoXform = true;
5211 SmallVector<SDNode*, 4> SetCCs;
5212 if (!N0.hasOneUse())
5213 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5215 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5216 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5218 LN0->getBasePtr(), N0.getValueType(),
5219 LN0->getMemOperand());
5220 CombineTo(N, ExtLoad);
5221 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5222 N0.getValueType(), ExtLoad);
5223 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5225 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5227 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5231 // fold (zext (and/or/xor (load x), cst)) ->
5232 // (and/or/xor (zextload x), (zext cst))
5233 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5234 N0.getOpcode() == ISD::XOR) &&
5235 isa<LoadSDNode>(N0.getOperand(0)) &&
5236 N0.getOperand(1).getOpcode() == ISD::Constant &&
5237 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5238 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5239 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5240 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5241 bool DoXform = true;
5242 SmallVector<SDNode*, 4> SetCCs;
5243 if (!N0.hasOneUse())
5244 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5247 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5248 LN0->getChain(), LN0->getBasePtr(),
5250 LN0->getMemOperand());
5251 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5252 Mask = Mask.zext(VT.getSizeInBits());
5253 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5254 ExtLoad, DAG.getConstant(Mask, VT));
5255 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5256 SDLoc(N0.getOperand(0)),
5257 N0.getOperand(0).getValueType(), ExtLoad);
5259 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5260 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5262 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5267 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5268 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5269 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5270 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5271 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5272 EVT MemVT = LN0->getMemoryVT();
5273 if ((!LegalOperations && !LN0->isVolatile()) ||
5274 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5275 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5277 LN0->getBasePtr(), MemVT,
5278 LN0->getMemOperand());
5279 CombineTo(N, ExtLoad);
5280 CombineTo(N0.getNode(),
5281 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5283 ExtLoad.getValue(1));
5284 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5288 if (N0.getOpcode() == ISD::SETCC) {
5289 if (!LegalOperations && VT.isVector() &&
5290 N0.getValueType().getVectorElementType() == MVT::i1) {
5291 EVT N0VT = N0.getOperand(0).getValueType();
5292 if (getSetCCResultType(N0VT) == N0.getValueType())
5295 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5296 // Only do this before legalize for now.
5297 EVT EltVT = VT.getVectorElementType();
5298 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5299 DAG.getConstant(1, EltVT));
5300 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5301 // We know that the # elements of the results is the same as the
5302 // # elements of the compare (and the # elements of the compare result
5303 // for that matter). Check to see that they are the same size. If so,
5304 // we know that the element size of the sext'd result matches the
5305 // element size of the compare operands.
5306 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5307 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5309 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5310 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5311 &OneOps[0], OneOps.size()));
5313 // If the desired elements are smaller or larger than the source
5314 // elements we can use a matching integer vector type and then
5315 // truncate/sign extend
5316 EVT MatchingElementType =
5317 EVT::getIntegerVT(*DAG.getContext(),
5318 N0VT.getScalarType().getSizeInBits());
5319 EVT MatchingVectorType =
5320 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5321 N0VT.getVectorNumElements());
5323 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5325 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5326 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5327 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5328 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5329 &OneOps[0], OneOps.size()));
5332 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5334 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5335 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5336 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5337 if (SCC.getNode()) return SCC;
5340 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5341 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5342 isa<ConstantSDNode>(N0.getOperand(1)) &&
5343 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5345 SDValue ShAmt = N0.getOperand(1);
5346 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5347 if (N0.getOpcode() == ISD::SHL) {
5348 SDValue InnerZExt = N0.getOperand(0);
5349 // If the original shl may be shifting out bits, do not perform this
5351 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5352 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5353 if (ShAmtVal > KnownZeroBits)
5359 // Ensure that the shift amount is wide enough for the shifted value.
5360 if (VT.getSizeInBits() >= 256)
5361 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5363 return DAG.getNode(N0.getOpcode(), DL, VT,
5364 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5371 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5372 SDValue N0 = N->getOperand(0);
5373 EVT VT = N->getValueType(0);
5375 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5377 return SDValue(Res, 0);
5379 // fold (aext (aext x)) -> (aext x)
5380 // fold (aext (zext x)) -> (zext x)
5381 // fold (aext (sext x)) -> (sext x)
5382 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5383 N0.getOpcode() == ISD::ZERO_EXTEND ||
5384 N0.getOpcode() == ISD::SIGN_EXTEND)
5385 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5387 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5388 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5389 if (N0.getOpcode() == ISD::TRUNCATE) {
5390 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5391 if (NarrowLoad.getNode()) {
5392 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5393 if (NarrowLoad.getNode() != N0.getNode()) {
5394 CombineTo(N0.getNode(), NarrowLoad);
5395 // CombineTo deleted the truncate, if needed, but not what's under it.
5398 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5402 // fold (aext (truncate x))
5403 if (N0.getOpcode() == ISD::TRUNCATE) {
5404 SDValue TruncOp = N0.getOperand(0);
5405 if (TruncOp.getValueType() == VT)
5406 return TruncOp; // x iff x size == zext size.
5407 if (TruncOp.getValueType().bitsGT(VT))
5408 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5409 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5412 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5413 // if the trunc is not free.
5414 if (N0.getOpcode() == ISD::AND &&
5415 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5416 N0.getOperand(1).getOpcode() == ISD::Constant &&
5417 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5418 N0.getValueType())) {
5419 SDValue X = N0.getOperand(0).getOperand(0);
5420 if (X.getValueType().bitsLT(VT)) {
5421 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5422 } else if (X.getValueType().bitsGT(VT)) {
5423 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5425 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5426 Mask = Mask.zext(VT.getSizeInBits());
5427 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5428 X, DAG.getConstant(Mask, VT));
5431 // fold (aext (load x)) -> (aext (truncate (extload x)))
5432 // None of the supported targets knows how to perform load and any_ext
5433 // on vectors in one instruction. We only perform this transformation on
5435 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5436 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5437 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5438 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5439 bool DoXform = true;
5440 SmallVector<SDNode*, 4> SetCCs;
5441 if (!N0.hasOneUse())
5442 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5444 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5445 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5447 LN0->getBasePtr(), N0.getValueType(),
5448 LN0->getMemOperand());
5449 CombineTo(N, ExtLoad);
5450 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5451 N0.getValueType(), ExtLoad);
5452 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5453 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5455 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5459 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5460 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5461 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5462 if (N0.getOpcode() == ISD::LOAD &&
5463 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5465 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5466 ISD::LoadExtType ExtType = LN0->getExtensionType();
5467 EVT MemVT = LN0->getMemoryVT();
5468 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5469 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5470 VT, LN0->getChain(), LN0->getBasePtr(),
5471 MemVT, LN0->getMemOperand());
5472 CombineTo(N, ExtLoad);
5473 CombineTo(N0.getNode(),
5474 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5475 N0.getValueType(), ExtLoad),
5476 ExtLoad.getValue(1));
5477 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5481 if (N0.getOpcode() == ISD::SETCC) {
5483 // aext(setcc) -> vsetcc
5484 // aext(setcc) -> truncate(vsetcc)
5485 // aext(setcc) -> aext(vsetcc)
5486 // Only do this before legalize for now.
5487 if (VT.isVector() && !LegalOperations) {
5488 EVT N0VT = N0.getOperand(0).getValueType();
5489 // We know that the # elements of the results is the same as the
5490 // # elements of the compare (and the # elements of the compare result
5491 // for that matter). Check to see that they are the same size. If so,
5492 // we know that the element size of the sext'd result matches the
5493 // element size of the compare operands.
5494 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5495 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5497 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5498 // If the desired elements are smaller or larger than the source
5499 // elements we can use a matching integer vector type and then
5500 // truncate/any extend
5502 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5504 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5506 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5507 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5511 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5513 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5514 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5515 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5523 /// GetDemandedBits - See if the specified operand can be simplified with the
5524 /// knowledge that only the bits specified by Mask are used. If so, return the
5525 /// simpler operand, otherwise return a null SDValue.
5526 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5527 switch (V.getOpcode()) {
5529 case ISD::Constant: {
5530 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5531 assert(CV && "Const value should be ConstSDNode.");
5532 const APInt &CVal = CV->getAPIntValue();
5533 APInt NewVal = CVal & Mask;
5535 return DAG.getConstant(NewVal, V.getValueType());
5540 // If the LHS or RHS don't contribute bits to the or, drop them.
5541 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5542 return V.getOperand(1);
5543 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5544 return V.getOperand(0);
5547 // Only look at single-use SRLs.
5548 if (!V.getNode()->hasOneUse())
5550 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5551 // See if we can recursively simplify the LHS.
5552 unsigned Amt = RHSC->getZExtValue();
5554 // Watch out for shift count overflow though.
5555 if (Amt >= Mask.getBitWidth()) break;
5556 APInt NewMask = Mask << Amt;
5557 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5558 if (SimplifyLHS.getNode())
5559 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5560 SimplifyLHS, V.getOperand(1));
5566 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5567 /// bits and then truncated to a narrower type and where N is a multiple
5568 /// of number of bits of the narrower type, transform it to a narrower load
5569 /// from address + N / num of bits of new type. If the result is to be
5570 /// extended, also fold the extension to form a extending load.
5571 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5572 unsigned Opc = N->getOpcode();
5574 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5575 SDValue N0 = N->getOperand(0);
5576 EVT VT = N->getValueType(0);
5579 // This transformation isn't valid for vector loads.
5583 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5585 if (Opc == ISD::SIGN_EXTEND_INREG) {
5586 ExtType = ISD::SEXTLOAD;
5587 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5588 } else if (Opc == ISD::SRL) {
5589 // Another special-case: SRL is basically zero-extending a narrower value.
5590 ExtType = ISD::ZEXTLOAD;
5592 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5593 if (!N01) return SDValue();
5594 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5595 VT.getSizeInBits() - N01->getZExtValue());
5597 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5600 unsigned EVTBits = ExtVT.getSizeInBits();
5602 // Do not generate loads of non-round integer types since these can
5603 // be expensive (and would be wrong if the type is not byte sized).
5604 if (!ExtVT.isRound())
5608 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5609 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5610 ShAmt = N01->getZExtValue();
5611 // Is the shift amount a multiple of size of VT?
5612 if ((ShAmt & (EVTBits-1)) == 0) {
5613 N0 = N0.getOperand(0);
5614 // Is the load width a multiple of size of VT?
5615 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5619 // At this point, we must have a load or else we can't do the transform.
5620 if (!isa<LoadSDNode>(N0)) return SDValue();
5622 // Because a SRL must be assumed to *need* to zero-extend the high bits
5623 // (as opposed to anyext the high bits), we can't combine the zextload
5624 // lowering of SRL and an sextload.
5625 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5628 // If the shift amount is larger than the input type then we're not
5629 // accessing any of the loaded bytes. If the load was a zextload/extload
5630 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5631 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5636 // If the load is shifted left (and the result isn't shifted back right),
5637 // we can fold the truncate through the shift.
5638 unsigned ShLeftAmt = 0;
5639 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5640 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5641 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5642 ShLeftAmt = N01->getZExtValue();
5643 N0 = N0.getOperand(0);
5647 // If we haven't found a load, we can't narrow it. Don't transform one with
5648 // multiple uses, this would require adding a new load.
5649 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5652 // Don't change the width of a volatile load.
5653 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5654 if (LN0->isVolatile())
5657 // Verify that we are actually reducing a load width here.
5658 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5661 // For the transform to be legal, the load must produce only two values
5662 // (the value loaded and the chain). Don't transform a pre-increment
5663 // load, for example, which produces an extra value. Otherwise the
5664 // transformation is not equivalent, and the downstream logic to replace
5665 // uses gets things wrong.
5666 if (LN0->getNumValues() > 2)
5669 // If the load that we're shrinking is an extload and we're not just
5670 // discarding the extension we can't simply shrink the load. Bail.
5671 // TODO: It would be possible to merge the extensions in some cases.
5672 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5673 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5676 EVT PtrType = N0.getOperand(1).getValueType();
5678 if (PtrType == MVT::Untyped || PtrType.isExtended())
5679 // It's not possible to generate a constant of extended or untyped type.
5682 // For big endian targets, we need to adjust the offset to the pointer to
5683 // load the correct bytes.
5684 if (TLI.isBigEndian()) {
5685 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5686 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5687 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5690 uint64_t PtrOff = ShAmt / 8;
5691 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5692 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5693 PtrType, LN0->getBasePtr(),
5694 DAG.getConstant(PtrOff, PtrType));
5695 AddToWorkList(NewPtr.getNode());
5698 if (ExtType == ISD::NON_EXTLOAD)
5699 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5700 LN0->getPointerInfo().getWithOffset(PtrOff),
5701 LN0->isVolatile(), LN0->isNonTemporal(),
5702 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5704 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5705 LN0->getPointerInfo().getWithOffset(PtrOff),
5706 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5707 NewAlign, LN0->getTBAAInfo());
5709 // Replace the old load's chain with the new load's chain.
5710 WorkListRemover DeadNodes(*this);
5711 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5713 // Shift the result left, if we've swallowed a left shift.
5714 SDValue Result = Load;
5715 if (ShLeftAmt != 0) {
5716 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5717 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5719 // If the shift amount is as large as the result size (but, presumably,
5720 // no larger than the source) then the useful bits of the result are
5721 // zero; we can't simply return the shortened shift, because the result
5722 // of that operation is undefined.
5723 if (ShLeftAmt >= VT.getSizeInBits())
5724 Result = DAG.getConstant(0, VT);
5726 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5727 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5730 // Return the new loaded value.
5734 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5735 SDValue N0 = N->getOperand(0);
5736 SDValue N1 = N->getOperand(1);
5737 EVT VT = N->getValueType(0);
5738 EVT EVT = cast<VTSDNode>(N1)->getVT();
5739 unsigned VTBits = VT.getScalarType().getSizeInBits();
5740 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5742 // fold (sext_in_reg c1) -> c1
5743 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5744 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5746 // If the input is already sign extended, just drop the extension.
5747 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5750 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5751 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5752 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5753 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5754 N0.getOperand(0), N1);
5756 // fold (sext_in_reg (sext x)) -> (sext x)
5757 // fold (sext_in_reg (aext x)) -> (sext x)
5758 // if x is small enough.
5759 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5760 SDValue N00 = N0.getOperand(0);
5761 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5762 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5763 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5766 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5767 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5768 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5770 // fold operands of sext_in_reg based on knowledge that the top bits are not
5772 if (SimplifyDemandedBits(SDValue(N, 0)))
5773 return SDValue(N, 0);
5775 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5776 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5777 SDValue NarrowLoad = ReduceLoadWidth(N);
5778 if (NarrowLoad.getNode())
5781 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5782 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5783 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5784 if (N0.getOpcode() == ISD::SRL) {
5785 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5786 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5787 // We can turn this into an SRA iff the input to the SRL is already sign
5789 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5790 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5791 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5792 N0.getOperand(0), N0.getOperand(1));
5796 // fold (sext_inreg (extload x)) -> (sextload x)
5797 if (ISD::isEXTLoad(N0.getNode()) &&
5798 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5799 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5800 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5801 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5802 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5803 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5805 LN0->getBasePtr(), EVT,
5806 LN0->getMemOperand());
5807 CombineTo(N, ExtLoad);
5808 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5809 AddToWorkList(ExtLoad.getNode());
5810 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5812 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5813 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5815 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5816 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5817 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5818 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5819 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5821 LN0->getBasePtr(), EVT,
5822 LN0->getMemOperand());
5823 CombineTo(N, ExtLoad);
5824 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5825 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5828 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5829 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5830 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5831 N0.getOperand(1), false);
5832 if (BSwap.getNode())
5833 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5837 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5838 // into a build_vector.
5839 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5840 SmallVector<SDValue, 8> Elts;
5841 unsigned NumElts = N0->getNumOperands();
5842 unsigned ShAmt = VTBits - EVTBits;
5844 for (unsigned i = 0; i != NumElts; ++i) {
5845 SDValue Op = N0->getOperand(i);
5846 if (Op->getOpcode() == ISD::UNDEF) {
5851 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5852 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5853 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5854 Op.getValueType()));
5857 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Elts[0], NumElts);
5863 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5864 SDValue N0 = N->getOperand(0);
5865 EVT VT = N->getValueType(0);
5866 bool isLE = TLI.isLittleEndian();
5869 if (N0.getValueType() == N->getValueType(0))
5871 // fold (truncate c1) -> c1
5872 if (isa<ConstantSDNode>(N0))
5873 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5874 // fold (truncate (truncate x)) -> (truncate x)
5875 if (N0.getOpcode() == ISD::TRUNCATE)
5876 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5877 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5878 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5879 N0.getOpcode() == ISD::SIGN_EXTEND ||
5880 N0.getOpcode() == ISD::ANY_EXTEND) {
5881 if (N0.getOperand(0).getValueType().bitsLT(VT))
5882 // if the source is smaller than the dest, we still need an extend
5883 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5885 if (N0.getOperand(0).getValueType().bitsGT(VT))
5886 // if the source is larger than the dest, than we just need the truncate
5887 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5888 // if the source and dest are the same type, we can drop both the extend
5889 // and the truncate.
5890 return N0.getOperand(0);
5893 // Fold extract-and-trunc into a narrow extract. For example:
5894 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5895 // i32 y = TRUNCATE(i64 x)
5897 // v16i8 b = BITCAST (v2i64 val)
5898 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5900 // Note: We only run this optimization after type legalization (which often
5901 // creates this pattern) and before operation legalization after which
5902 // we need to be more careful about the vector instructions that we generate.
5903 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5904 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
5906 EVT VecTy = N0.getOperand(0).getValueType();
5907 EVT ExTy = N0.getValueType();
5908 EVT TrTy = N->getValueType(0);
5910 unsigned NumElem = VecTy.getVectorNumElements();
5911 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5913 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5914 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5916 SDValue EltNo = N0->getOperand(1);
5917 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5918 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5919 EVT IndexTy = TLI.getVectorIdxTy();
5920 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5922 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5923 NVT, N0.getOperand(0));
5925 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5927 DAG.getConstant(Index, IndexTy));
5931 // Fold a series of buildvector, bitcast, and truncate if possible.
5933 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5934 // (2xi32 (buildvector x, y)).
5935 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5936 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5937 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5938 N0.getOperand(0).hasOneUse()) {
5940 SDValue BuildVect = N0.getOperand(0);
5941 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5942 EVT TruncVecEltTy = VT.getVectorElementType();
5944 // Check that the element types match.
5945 if (BuildVectEltTy == TruncVecEltTy) {
5946 // Now we only need to compute the offset of the truncated elements.
5947 unsigned BuildVecNumElts = BuildVect.getNumOperands();
5948 unsigned TruncVecNumElts = VT.getVectorNumElements();
5949 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5951 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5952 "Invalid number of elements");
5954 SmallVector<SDValue, 8> Opnds;
5955 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5956 Opnds.push_back(BuildVect.getOperand(i));
5958 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
5963 // See if we can simplify the input to this truncate through knowledge that
5964 // only the low bits are being used.
5965 // For example "trunc (or (shl x, 8), y)" // -> trunc y
5966 // Currently we only perform this optimization on scalars because vectors
5967 // may have different active low bits.
5968 if (!VT.isVector()) {
5970 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5971 VT.getSizeInBits()));
5972 if (Shorter.getNode())
5973 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
5975 // fold (truncate (load x)) -> (smaller load x)
5976 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5977 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5978 SDValue Reduced = ReduceLoadWidth(N);
5979 if (Reduced.getNode())
5981 // Handle the case where the load remains an extending load even
5982 // after truncation.
5983 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
5984 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5985 if (!LN0->isVolatile() &&
5986 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
5987 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
5988 VT, LN0->getChain(), LN0->getBasePtr(),
5990 LN0->getMemOperand());
5991 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
5996 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
5997 // where ... are all 'undef'.
5998 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
5999 SmallVector<EVT, 8> VTs;
6002 unsigned NumDefs = 0;
6004 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6005 SDValue X = N0.getOperand(i);
6006 if (X.getOpcode() != ISD::UNDEF) {
6011 // Stop if more than one members are non-undef.
6014 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6015 VT.getVectorElementType(),
6016 X.getValueType().getVectorNumElements()));
6020 return DAG.getUNDEF(VT);
6023 assert(V.getNode() && "The single defined operand is empty!");
6024 SmallVector<SDValue, 8> Opnds;
6025 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6027 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6030 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6031 AddToWorkList(NV.getNode());
6032 Opnds.push_back(NV);
6034 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
6035 &Opnds[0], Opnds.size());
6039 // Simplify the operands using demanded-bits information.
6040 if (!VT.isVector() &&
6041 SimplifyDemandedBits(SDValue(N, 0)))
6042 return SDValue(N, 0);
6047 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6048 SDValue Elt = N->getOperand(i);
6049 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6050 return Elt.getNode();
6051 return Elt.getOperand(Elt.getResNo()).getNode();
6054 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6055 /// if load locations are consecutive.
6056 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6057 assert(N->getOpcode() == ISD::BUILD_PAIR);
6059 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6060 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6061 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6062 LD1->getAddressSpace() != LD2->getAddressSpace())
6064 EVT LD1VT = LD1->getValueType(0);
6066 if (ISD::isNON_EXTLoad(LD2) &&
6068 // If both are volatile this would reduce the number of volatile loads.
6069 // If one is volatile it might be ok, but play conservative and bail out.
6070 !LD1->isVolatile() &&
6071 !LD2->isVolatile() &&
6072 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6073 unsigned Align = LD1->getAlignment();
6074 unsigned NewAlign = TLI.getDataLayout()->
6075 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6077 if (NewAlign <= Align &&
6078 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6079 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6080 LD1->getBasePtr(), LD1->getPointerInfo(),
6081 false, false, false, Align);
6087 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6088 SDValue N0 = N->getOperand(0);
6089 EVT VT = N->getValueType(0);
6091 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6092 // Only do this before legalize, since afterward the target may be depending
6093 // on the bitconvert.
6094 // First check to see if this is all constant.
6096 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6098 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6100 EVT DestEltVT = N->getValueType(0).getVectorElementType();
6101 assert(!DestEltVT.isVector() &&
6102 "Element type of vector ValueType must not be vector!");
6104 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6107 // If the input is a constant, let getNode fold it.
6108 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6109 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6110 if (Res.getNode() != N) {
6111 if (!LegalOperations ||
6112 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6115 // Folding it resulted in an illegal node, and it's too late to
6116 // do that. Clean up the old node and forego the transformation.
6117 // Ideally this won't happen very often, because instcombine
6118 // and the earlier dagcombine runs (where illegal nodes are
6119 // permitted) should have folded most of them already.
6120 DAG.DeleteNode(Res.getNode());
6124 // (conv (conv x, t1), t2) -> (conv x, t2)
6125 if (N0.getOpcode() == ISD::BITCAST)
6126 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6129 // fold (conv (load x)) -> (load (conv*)x)
6130 // If the resultant load doesn't need a higher alignment than the original!
6131 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6132 // Do not change the width of a volatile load.
6133 !cast<LoadSDNode>(N0)->isVolatile() &&
6134 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6135 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6136 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6137 unsigned Align = TLI.getDataLayout()->
6138 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6139 unsigned OrigAlign = LN0->getAlignment();
6141 if (Align <= OrigAlign) {
6142 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6143 LN0->getBasePtr(), LN0->getPointerInfo(),
6144 LN0->isVolatile(), LN0->isNonTemporal(),
6145 LN0->isInvariant(), OrigAlign,
6146 LN0->getTBAAInfo());
6148 CombineTo(N0.getNode(),
6149 DAG.getNode(ISD::BITCAST, SDLoc(N0),
6150 N0.getValueType(), Load),
6156 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6157 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6158 // This often reduces constant pool loads.
6159 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6160 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6161 N0.getNode()->hasOneUse() && VT.isInteger() &&
6162 !VT.isVector() && !N0.getValueType().isVector()) {
6163 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6165 AddToWorkList(NewConv.getNode());
6167 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6168 if (N0.getOpcode() == ISD::FNEG)
6169 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6170 NewConv, DAG.getConstant(SignBit, VT));
6171 assert(N0.getOpcode() == ISD::FABS);
6172 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6173 NewConv, DAG.getConstant(~SignBit, VT));
6176 // fold (bitconvert (fcopysign cst, x)) ->
6177 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6178 // Note that we don't handle (copysign x, cst) because this can always be
6179 // folded to an fneg or fabs.
6180 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6181 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6182 VT.isInteger() && !VT.isVector()) {
6183 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6184 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6185 if (isTypeLegal(IntXVT)) {
6186 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6187 IntXVT, N0.getOperand(1));
6188 AddToWorkList(X.getNode());
6190 // If X has a different width than the result/lhs, sext it or truncate it.
6191 unsigned VTWidth = VT.getSizeInBits();
6192 if (OrigXWidth < VTWidth) {
6193 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6194 AddToWorkList(X.getNode());
6195 } else if (OrigXWidth > VTWidth) {
6196 // To get the sign bit in the right place, we have to shift it right
6197 // before truncating.
6198 X = DAG.getNode(ISD::SRL, SDLoc(X),
6199 X.getValueType(), X,
6200 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6201 AddToWorkList(X.getNode());
6202 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6203 AddToWorkList(X.getNode());
6206 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6207 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6208 X, DAG.getConstant(SignBit, VT));
6209 AddToWorkList(X.getNode());
6211 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6212 VT, N0.getOperand(0));
6213 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6214 Cst, DAG.getConstant(~SignBit, VT));
6215 AddToWorkList(Cst.getNode());
6217 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6221 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6222 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6223 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6224 if (CombineLD.getNode())
6231 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6232 EVT VT = N->getValueType(0);
6233 return CombineConsecutiveLoads(N, VT);
6236 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6237 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
6238 /// destination element value type.
6239 SDValue DAGCombiner::
6240 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6241 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6243 // If this is already the right type, we're done.
6244 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6246 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6247 unsigned DstBitSize = DstEltVT.getSizeInBits();
6249 // If this is a conversion of N elements of one type to N elements of another
6250 // type, convert each element. This handles FP<->INT cases.
6251 if (SrcBitSize == DstBitSize) {
6252 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6253 BV->getValueType(0).getVectorNumElements());
6255 // Due to the FP element handling below calling this routine recursively,
6256 // we can end up with a scalar-to-vector node here.
6257 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6258 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6259 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6260 DstEltVT, BV->getOperand(0)));
6262 SmallVector<SDValue, 8> Ops;
6263 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6264 SDValue Op = BV->getOperand(i);
6265 // If the vector element type is not legal, the BUILD_VECTOR operands
6266 // are promoted and implicitly truncated. Make that explicit here.
6267 if (Op.getValueType() != SrcEltVT)
6268 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6269 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6271 AddToWorkList(Ops.back().getNode());
6273 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6274 &Ops[0], Ops.size());
6277 // Otherwise, we're growing or shrinking the elements. To avoid having to
6278 // handle annoying details of growing/shrinking FP values, we convert them to
6280 if (SrcEltVT.isFloatingPoint()) {
6281 // Convert the input float vector to a int vector where the elements are the
6283 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6284 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6285 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6289 // Now we know the input is an integer vector. If the output is a FP type,
6290 // convert to integer first, then to FP of the right size.
6291 if (DstEltVT.isFloatingPoint()) {
6292 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6293 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6294 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6296 // Next, convert to FP elements of the same size.
6297 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6300 // Okay, we know the src/dst types are both integers of differing types.
6301 // Handling growing first.
6302 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6303 if (SrcBitSize < DstBitSize) {
6304 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6306 SmallVector<SDValue, 8> Ops;
6307 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6308 i += NumInputsPerOutput) {
6309 bool isLE = TLI.isLittleEndian();
6310 APInt NewBits = APInt(DstBitSize, 0);
6311 bool EltIsUndef = true;
6312 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6313 // Shift the previously computed bits over.
6314 NewBits <<= SrcBitSize;
6315 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6316 if (Op.getOpcode() == ISD::UNDEF) continue;
6319 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6320 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6324 Ops.push_back(DAG.getUNDEF(DstEltVT));
6326 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6329 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6330 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6331 &Ops[0], Ops.size());
6334 // Finally, this must be the case where we are shrinking elements: each input
6335 // turns into multiple outputs.
6336 bool isS2V = ISD::isScalarToVector(BV);
6337 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6338 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6339 NumOutputsPerInput*BV->getNumOperands());
6340 SmallVector<SDValue, 8> Ops;
6342 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6343 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6344 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6345 Ops.push_back(DAG.getUNDEF(DstEltVT));
6349 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6350 getAPIntValue().zextOrTrunc(SrcBitSize);
6352 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6353 APInt ThisVal = OpVal.trunc(DstBitSize);
6354 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6355 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6356 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6357 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6359 OpVal = OpVal.lshr(DstBitSize);
6362 // For big endian targets, swap the order of the pieces of each element.
6363 if (TLI.isBigEndian())
6364 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6367 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6368 &Ops[0], Ops.size());
6371 SDValue DAGCombiner::visitFADD(SDNode *N) {
6372 SDValue N0 = N->getOperand(0);
6373 SDValue N1 = N->getOperand(1);
6374 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6375 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6376 EVT VT = N->getValueType(0);
6379 if (VT.isVector()) {
6380 SDValue FoldedVOp = SimplifyVBinOp(N);
6381 if (FoldedVOp.getNode()) return FoldedVOp;
6384 // fold (fadd c1, c2) -> c1 + c2
6386 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6387 // canonicalize constant to RHS
6388 if (N0CFP && !N1CFP)
6389 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6390 // fold (fadd A, 0) -> A
6391 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6392 N1CFP->getValueAPF().isZero())
6394 // fold (fadd A, (fneg B)) -> (fsub A, B)
6395 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6396 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6397 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6398 GetNegatedExpression(N1, DAG, LegalOperations));
6399 // fold (fadd (fneg A), B) -> (fsub B, A)
6400 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6401 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6402 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6403 GetNegatedExpression(N0, DAG, LegalOperations));
6405 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6406 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6407 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6408 isa<ConstantFPSDNode>(N0.getOperand(1)))
6409 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6410 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6411 N0.getOperand(1), N1));
6413 // No FP constant should be created after legalization as Instruction
6414 // Selection pass has hard time in dealing with FP constant.
6416 // We don't need test this condition for transformation like following, as
6417 // the DAG being transformed implies it is legal to take FP constant as
6420 // (fadd (fmul c, x), x) -> (fmul c+1, x)
6422 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6424 // If allow, fold (fadd (fneg x), x) -> 0.0
6425 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6426 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6427 return DAG.getConstantFP(0.0, VT);
6429 // If allow, fold (fadd x, (fneg x)) -> 0.0
6430 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6431 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6432 return DAG.getConstantFP(0.0, VT);
6434 // In unsafe math mode, we can fold chains of FADD's of the same value
6435 // into multiplications. This transform is not safe in general because
6436 // we are reducing the number of rounding steps.
6437 if (DAG.getTarget().Options.UnsafeFPMath &&
6438 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6440 if (N0.getOpcode() == ISD::FMUL) {
6441 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6442 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6444 // (fadd (fmul c, x), x) -> (fmul x, c+1)
6445 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6446 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6448 DAG.getConstantFP(1.0, VT));
6449 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6453 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6454 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6455 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6457 DAG.getConstantFP(1.0, VT));
6458 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6462 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6463 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6464 N1.getOperand(0) == N1.getOperand(1) &&
6465 N0.getOperand(1) == N1.getOperand(0)) {
6466 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6468 DAG.getConstantFP(2.0, VT));
6469 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6470 N0.getOperand(1), NewCFP);
6473 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6474 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6475 N1.getOperand(0) == N1.getOperand(1) &&
6476 N0.getOperand(0) == N1.getOperand(0)) {
6477 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6479 DAG.getConstantFP(2.0, VT));
6480 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6481 N0.getOperand(0), NewCFP);
6485 if (N1.getOpcode() == ISD::FMUL) {
6486 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6487 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6489 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6490 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6491 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6493 DAG.getConstantFP(1.0, VT));
6494 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6498 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6499 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6500 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6502 DAG.getConstantFP(1.0, VT));
6503 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6508 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6509 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6510 N0.getOperand(0) == N0.getOperand(1) &&
6511 N1.getOperand(1) == N0.getOperand(0)) {
6512 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6514 DAG.getConstantFP(2.0, VT));
6515 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6516 N1.getOperand(1), NewCFP);
6519 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6520 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6521 N0.getOperand(0) == N0.getOperand(1) &&
6522 N1.getOperand(0) == N0.getOperand(0)) {
6523 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6525 DAG.getConstantFP(2.0, VT));
6526 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6527 N1.getOperand(0), NewCFP);
6531 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6532 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6533 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6534 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6535 (N0.getOperand(0) == N1))
6536 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6537 N1, DAG.getConstantFP(3.0, VT));
6540 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6541 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6542 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6543 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6544 N1.getOperand(0) == N0)
6545 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6546 N0, DAG.getConstantFP(3.0, VT));
6549 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6550 if (AllowNewFpConst &&
6551 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6552 N0.getOperand(0) == N0.getOperand(1) &&
6553 N1.getOperand(0) == N1.getOperand(1) &&
6554 N0.getOperand(0) == N1.getOperand(0))
6555 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6557 DAG.getConstantFP(4.0, VT));
6560 // FADD -> FMA combines:
6561 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6562 DAG.getTarget().Options.UnsafeFPMath) &&
6563 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6564 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6566 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6567 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6568 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6569 N0.getOperand(0), N0.getOperand(1), N1);
6571 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6572 // Note: Commutes FADD operands.
6573 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6574 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6575 N1.getOperand(0), N1.getOperand(1), N0);
6581 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6582 SDValue N0 = N->getOperand(0);
6583 SDValue N1 = N->getOperand(1);
6584 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6585 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6586 EVT VT = N->getValueType(0);
6590 if (VT.isVector()) {
6591 SDValue FoldedVOp = SimplifyVBinOp(N);
6592 if (FoldedVOp.getNode()) return FoldedVOp;
6595 // fold (fsub c1, c2) -> c1-c2
6597 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6598 // fold (fsub A, 0) -> A
6599 if (DAG.getTarget().Options.UnsafeFPMath &&
6600 N1CFP && N1CFP->getValueAPF().isZero())
6602 // fold (fsub 0, B) -> -B
6603 if (DAG.getTarget().Options.UnsafeFPMath &&
6604 N0CFP && N0CFP->getValueAPF().isZero()) {
6605 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6606 return GetNegatedExpression(N1, DAG, LegalOperations);
6607 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6608 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6610 // fold (fsub A, (fneg B)) -> (fadd A, B)
6611 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6612 return DAG.getNode(ISD::FADD, dl, VT, N0,
6613 GetNegatedExpression(N1, DAG, LegalOperations));
6615 // If 'unsafe math' is enabled, fold
6616 // (fsub x, x) -> 0.0 &
6617 // (fsub x, (fadd x, y)) -> (fneg y) &
6618 // (fsub x, (fadd y, x)) -> (fneg y)
6619 if (DAG.getTarget().Options.UnsafeFPMath) {
6621 return DAG.getConstantFP(0.0f, VT);
6623 if (N1.getOpcode() == ISD::FADD) {
6624 SDValue N10 = N1->getOperand(0);
6625 SDValue N11 = N1->getOperand(1);
6627 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6628 &DAG.getTarget().Options))
6629 return GetNegatedExpression(N11, DAG, LegalOperations);
6631 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6632 &DAG.getTarget().Options))
6633 return GetNegatedExpression(N10, DAG, LegalOperations);
6637 // FSUB -> FMA combines:
6638 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6639 DAG.getTarget().Options.UnsafeFPMath) &&
6640 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6641 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6643 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6644 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6645 return DAG.getNode(ISD::FMA, dl, VT,
6646 N0.getOperand(0), N0.getOperand(1),
6647 DAG.getNode(ISD::FNEG, dl, VT, N1));
6649 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6650 // Note: Commutes FSUB operands.
6651 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6652 return DAG.getNode(ISD::FMA, dl, VT,
6653 DAG.getNode(ISD::FNEG, dl, VT,
6655 N1.getOperand(1), N0);
6657 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6658 if (N0.getOpcode() == ISD::FNEG &&
6659 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6660 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6661 SDValue N00 = N0.getOperand(0).getOperand(0);
6662 SDValue N01 = N0.getOperand(0).getOperand(1);
6663 return DAG.getNode(ISD::FMA, dl, VT,
6664 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6665 DAG.getNode(ISD::FNEG, dl, VT, N1));
6672 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6673 SDValue N0 = N->getOperand(0);
6674 SDValue N1 = N->getOperand(1);
6675 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6676 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6677 EVT VT = N->getValueType(0);
6678 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6681 if (VT.isVector()) {
6682 SDValue FoldedVOp = SimplifyVBinOp(N);
6683 if (FoldedVOp.getNode()) return FoldedVOp;
6686 // fold (fmul c1, c2) -> c1*c2
6688 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6689 // canonicalize constant to RHS
6690 if (N0CFP && !N1CFP)
6691 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6692 // fold (fmul A, 0) -> 0
6693 if (DAG.getTarget().Options.UnsafeFPMath &&
6694 N1CFP && N1CFP->getValueAPF().isZero())
6696 // fold (fmul A, 0) -> 0, vector edition.
6697 if (DAG.getTarget().Options.UnsafeFPMath &&
6698 ISD::isBuildVectorAllZeros(N1.getNode()))
6700 // fold (fmul A, 1.0) -> A
6701 if (N1CFP && N1CFP->isExactlyValue(1.0))
6703 // fold (fmul X, 2.0) -> (fadd X, X)
6704 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6705 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6706 // fold (fmul X, -1.0) -> (fneg X)
6707 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6708 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6709 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6711 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6712 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6713 &DAG.getTarget().Options)) {
6714 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6715 &DAG.getTarget().Options)) {
6716 // Both can be negated for free, check to see if at least one is cheaper
6718 if (LHSNeg == 2 || RHSNeg == 2)
6719 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6720 GetNegatedExpression(N0, DAG, LegalOperations),
6721 GetNegatedExpression(N1, DAG, LegalOperations));
6725 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6726 if (DAG.getTarget().Options.UnsafeFPMath &&
6727 N1CFP && N0.getOpcode() == ISD::FMUL &&
6728 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6729 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6730 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6731 N0.getOperand(1), N1));
6736 SDValue DAGCombiner::visitFMA(SDNode *N) {
6737 SDValue N0 = N->getOperand(0);
6738 SDValue N1 = N->getOperand(1);
6739 SDValue N2 = N->getOperand(2);
6740 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6741 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6742 EVT VT = N->getValueType(0);
6745 if (DAG.getTarget().Options.UnsafeFPMath) {
6746 if (N0CFP && N0CFP->isZero())
6748 if (N1CFP && N1CFP->isZero())
6751 if (N0CFP && N0CFP->isExactlyValue(1.0))
6752 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6753 if (N1CFP && N1CFP->isExactlyValue(1.0))
6754 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6756 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6757 if (N0CFP && !N1CFP)
6758 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6760 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6761 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6762 N2.getOpcode() == ISD::FMUL &&
6763 N0 == N2.getOperand(0) &&
6764 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6765 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6766 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6770 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6771 if (DAG.getTarget().Options.UnsafeFPMath &&
6772 N0.getOpcode() == ISD::FMUL && N1CFP &&
6773 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6774 return DAG.getNode(ISD::FMA, dl, VT,
6776 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6780 // (fma x, 1, y) -> (fadd x, y)
6781 // (fma x, -1, y) -> (fadd (fneg x), y)
6783 if (N1CFP->isExactlyValue(1.0))
6784 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6786 if (N1CFP->isExactlyValue(-1.0) &&
6787 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6788 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6789 AddToWorkList(RHSNeg.getNode());
6790 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6794 // (fma x, c, x) -> (fmul x, (c+1))
6795 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6796 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6797 DAG.getNode(ISD::FADD, dl, VT,
6798 N1, DAG.getConstantFP(1.0, VT)));
6800 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6801 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6802 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6803 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6804 DAG.getNode(ISD::FADD, dl, VT,
6805 N1, DAG.getConstantFP(-1.0, VT)));
6811 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6812 SDValue N0 = N->getOperand(0);
6813 SDValue N1 = N->getOperand(1);
6814 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6815 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6816 EVT VT = N->getValueType(0);
6817 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6820 if (VT.isVector()) {
6821 SDValue FoldedVOp = SimplifyVBinOp(N);
6822 if (FoldedVOp.getNode()) return FoldedVOp;
6825 // fold (fdiv c1, c2) -> c1/c2
6827 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6829 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6830 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6831 // Compute the reciprocal 1.0 / c2.
6832 APFloat N1APF = N1CFP->getValueAPF();
6833 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6834 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6835 // Only do the transform if the reciprocal is a legal fp immediate that
6836 // isn't too nasty (eg NaN, denormal, ...).
6837 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6838 (!LegalOperations ||
6839 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6840 // backend)... we should handle this gracefully after Legalize.
6841 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6842 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6843 TLI.isFPImmLegal(Recip, VT)))
6844 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6845 DAG.getConstantFP(Recip, VT));
6848 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6849 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6850 &DAG.getTarget().Options)) {
6851 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6852 &DAG.getTarget().Options)) {
6853 // Both can be negated for free, check to see if at least one is cheaper
6855 if (LHSNeg == 2 || RHSNeg == 2)
6856 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6857 GetNegatedExpression(N0, DAG, LegalOperations),
6858 GetNegatedExpression(N1, DAG, LegalOperations));
6865 SDValue DAGCombiner::visitFREM(SDNode *N) {
6866 SDValue N0 = N->getOperand(0);
6867 SDValue N1 = N->getOperand(1);
6868 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6869 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6870 EVT VT = N->getValueType(0);
6872 // fold (frem c1, c2) -> fmod(c1,c2)
6874 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6879 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6880 SDValue N0 = N->getOperand(0);
6881 SDValue N1 = N->getOperand(1);
6882 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6883 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6884 EVT VT = N->getValueType(0);
6886 if (N0CFP && N1CFP) // Constant fold
6887 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6890 const APFloat& V = N1CFP->getValueAPF();
6891 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6892 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6893 if (!V.isNegative()) {
6894 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6895 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6897 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6898 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6899 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6903 // copysign(fabs(x), y) -> copysign(x, y)
6904 // copysign(fneg(x), y) -> copysign(x, y)
6905 // copysign(copysign(x,z), y) -> copysign(x, y)
6906 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6907 N0.getOpcode() == ISD::FCOPYSIGN)
6908 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6909 N0.getOperand(0), N1);
6911 // copysign(x, abs(y)) -> abs(x)
6912 if (N1.getOpcode() == ISD::FABS)
6913 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6915 // copysign(x, copysign(y,z)) -> copysign(x, z)
6916 if (N1.getOpcode() == ISD::FCOPYSIGN)
6917 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6918 N0, N1.getOperand(1));
6920 // copysign(x, fp_extend(y)) -> copysign(x, y)
6921 // copysign(x, fp_round(y)) -> copysign(x, y)
6922 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6923 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6924 N0, N1.getOperand(0));
6929 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6930 SDValue N0 = N->getOperand(0);
6931 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6932 EVT VT = N->getValueType(0);
6933 EVT OpVT = N0.getValueType();
6935 // fold (sint_to_fp c1) -> c1fp
6937 // ...but only if the target supports immediate floating-point values
6938 (!LegalOperations ||
6939 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6940 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6942 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6943 // but UINT_TO_FP is legal on this target, try to convert.
6944 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6945 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6946 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6947 if (DAG.SignBitIsZero(N0))
6948 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6951 // The next optimizations are desirable only if SELECT_CC can be lowered.
6952 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6953 // having to say they don't support SELECT_CC on every type the DAG knows
6954 // about, since there is no way to mark an opcode illegal at all value types
6955 // (See also visitSELECT)
6956 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6957 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6958 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6960 (!LegalOperations ||
6961 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6963 { N0.getOperand(0), N0.getOperand(1),
6964 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6966 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6969 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6970 // (select_cc x, y, 1.0, 0.0,, cc)
6971 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6972 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6973 (!LegalOperations ||
6974 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6976 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6977 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6978 N0.getOperand(0).getOperand(2) };
6979 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6986 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6987 SDValue N0 = N->getOperand(0);
6988 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6989 EVT VT = N->getValueType(0);
6990 EVT OpVT = N0.getValueType();
6992 // fold (uint_to_fp c1) -> c1fp
6994 // ...but only if the target supports immediate floating-point values
6995 (!LegalOperations ||
6996 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6997 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6999 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7000 // but SINT_TO_FP is legal on this target, try to convert.
7001 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7002 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7003 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7004 if (DAG.SignBitIsZero(N0))
7005 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7008 // The next optimizations are desirable only if SELECT_CC can be lowered.
7009 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
7010 // having to say they don't support SELECT_CC on every type the DAG knows
7011 // about, since there is no way to mark an opcode illegal at all value types
7012 // (See also visitSELECT)
7013 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
7014 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7016 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7017 (!LegalOperations ||
7018 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7020 { N0.getOperand(0), N0.getOperand(1),
7021 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7023 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
7030 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7031 SDValue N0 = N->getOperand(0);
7032 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7033 EVT VT = N->getValueType(0);
7035 // fold (fp_to_sint c1fp) -> c1
7037 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7042 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7043 SDValue N0 = N->getOperand(0);
7044 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7045 EVT VT = N->getValueType(0);
7047 // fold (fp_to_uint c1fp) -> c1
7049 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7054 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7055 SDValue N0 = N->getOperand(0);
7056 SDValue N1 = N->getOperand(1);
7057 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7058 EVT VT = N->getValueType(0);
7060 // fold (fp_round c1fp) -> c1fp
7062 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7064 // fold (fp_round (fp_extend x)) -> x
7065 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7066 return N0.getOperand(0);
7068 // fold (fp_round (fp_round x)) -> (fp_round x)
7069 if (N0.getOpcode() == ISD::FP_ROUND) {
7070 // This is a value preserving truncation if both round's are.
7071 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7072 N0.getNode()->getConstantOperandVal(1) == 1;
7073 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7074 DAG.getIntPtrConstant(IsTrunc));
7077 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7078 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7079 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7080 N0.getOperand(0), N1);
7081 AddToWorkList(Tmp.getNode());
7082 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7083 Tmp, N0.getOperand(1));
7089 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7090 SDValue N0 = N->getOperand(0);
7091 EVT VT = N->getValueType(0);
7092 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7093 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7095 // fold (fp_round_inreg c1fp) -> c1fp
7096 if (N0CFP && isTypeLegal(EVT)) {
7097 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7098 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7104 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7105 SDValue N0 = N->getOperand(0);
7106 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7107 EVT VT = N->getValueType(0);
7109 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7110 if (N->hasOneUse() &&
7111 N->use_begin()->getOpcode() == ISD::FP_ROUND)
7114 // fold (fp_extend c1fp) -> c1fp
7116 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7118 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7120 if (N0.getOpcode() == ISD::FP_ROUND
7121 && N0.getNode()->getConstantOperandVal(1) == 1) {
7122 SDValue In = N0.getOperand(0);
7123 if (In.getValueType() == VT) return In;
7124 if (VT.bitsLT(In.getValueType()))
7125 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7126 In, N0.getOperand(1));
7127 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7130 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7131 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7132 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7133 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
7134 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7135 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7137 LN0->getBasePtr(), N0.getValueType(),
7138 LN0->getMemOperand());
7139 CombineTo(N, ExtLoad);
7140 CombineTo(N0.getNode(),
7141 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7142 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7143 ExtLoad.getValue(1));
7144 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7150 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7151 SDValue N0 = N->getOperand(0);
7152 EVT VT = N->getValueType(0);
7154 if (VT.isVector()) {
7155 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7156 if (FoldedVOp.getNode()) return FoldedVOp;
7159 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7160 &DAG.getTarget().Options))
7161 return GetNegatedExpression(N0, DAG, LegalOperations);
7163 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7164 // constant pool values.
7165 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7167 N0.getNode()->hasOneUse() &&
7168 N0.getOperand(0).getValueType().isInteger()) {
7169 SDValue Int = N0.getOperand(0);
7170 EVT IntVT = Int.getValueType();
7171 if (IntVT.isInteger() && !IntVT.isVector()) {
7172 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7173 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7174 AddToWorkList(Int.getNode());
7175 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7180 // (fneg (fmul c, x)) -> (fmul -c, x)
7181 if (N0.getOpcode() == ISD::FMUL) {
7182 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7184 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7186 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7193 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7194 SDValue N0 = N->getOperand(0);
7195 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7196 EVT VT = N->getValueType(0);
7198 // fold (fceil c1) -> fceil(c1)
7200 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7205 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7206 SDValue N0 = N->getOperand(0);
7207 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7208 EVT VT = N->getValueType(0);
7210 // fold (ftrunc c1) -> ftrunc(c1)
7212 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7217 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7218 SDValue N0 = N->getOperand(0);
7219 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7220 EVT VT = N->getValueType(0);
7222 // fold (ffloor c1) -> ffloor(c1)
7224 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7229 SDValue DAGCombiner::visitFABS(SDNode *N) {
7230 SDValue N0 = N->getOperand(0);
7231 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7232 EVT VT = N->getValueType(0);
7234 if (VT.isVector()) {
7235 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7236 if (FoldedVOp.getNode()) return FoldedVOp;
7239 // fold (fabs c1) -> fabs(c1)
7241 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7242 // fold (fabs (fabs x)) -> (fabs x)
7243 if (N0.getOpcode() == ISD::FABS)
7244 return N->getOperand(0);
7245 // fold (fabs (fneg x)) -> (fabs x)
7246 // fold (fabs (fcopysign x, y)) -> (fabs x)
7247 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7248 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7250 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7251 // constant pool values.
7252 if (!TLI.isFAbsFree(VT) &&
7253 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7254 N0.getOperand(0).getValueType().isInteger() &&
7255 !N0.getOperand(0).getValueType().isVector()) {
7256 SDValue Int = N0.getOperand(0);
7257 EVT IntVT = Int.getValueType();
7258 if (IntVT.isInteger() && !IntVT.isVector()) {
7259 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7260 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7261 AddToWorkList(Int.getNode());
7262 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7263 N->getValueType(0), Int);
7270 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7271 SDValue Chain = N->getOperand(0);
7272 SDValue N1 = N->getOperand(1);
7273 SDValue N2 = N->getOperand(2);
7275 // If N is a constant we could fold this into a fallthrough or unconditional
7276 // branch. However that doesn't happen very often in normal code, because
7277 // Instcombine/SimplifyCFG should have handled the available opportunities.
7278 // If we did this folding here, it would be necessary to update the
7279 // MachineBasicBlock CFG, which is awkward.
7281 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7283 if (N1.getOpcode() == ISD::SETCC &&
7284 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7285 N1.getOperand(0).getValueType())) {
7286 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7287 Chain, N1.getOperand(2),
7288 N1.getOperand(0), N1.getOperand(1), N2);
7291 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7292 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7293 (N1.getOperand(0).hasOneUse() &&
7294 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7295 SDNode *Trunc = nullptr;
7296 if (N1.getOpcode() == ISD::TRUNCATE) {
7297 // Look pass the truncate.
7298 Trunc = N1.getNode();
7299 N1 = N1.getOperand(0);
7302 // Match this pattern so that we can generate simpler code:
7305 // %b = and i32 %a, 2
7306 // %c = srl i32 %b, 1
7307 // brcond i32 %c ...
7312 // %b = and i32 %a, 2
7313 // %c = setcc eq %b, 0
7316 // This applies only when the AND constant value has one bit set and the
7317 // SRL constant is equal to the log2 of the AND constant. The back-end is
7318 // smart enough to convert the result into a TEST/JMP sequence.
7319 SDValue Op0 = N1.getOperand(0);
7320 SDValue Op1 = N1.getOperand(1);
7322 if (Op0.getOpcode() == ISD::AND &&
7323 Op1.getOpcode() == ISD::Constant) {
7324 SDValue AndOp1 = Op0.getOperand(1);
7326 if (AndOp1.getOpcode() == ISD::Constant) {
7327 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7329 if (AndConst.isPowerOf2() &&
7330 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7332 DAG.getSetCC(SDLoc(N),
7333 getSetCCResultType(Op0.getValueType()),
7334 Op0, DAG.getConstant(0, Op0.getValueType()),
7337 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7338 MVT::Other, Chain, SetCC, N2);
7339 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7340 // will convert it back to (X & C1) >> C2.
7341 CombineTo(N, NewBRCond, false);
7342 // Truncate is dead.
7344 removeFromWorkList(Trunc);
7345 DAG.DeleteNode(Trunc);
7347 // Replace the uses of SRL with SETCC
7348 WorkListRemover DeadNodes(*this);
7349 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7350 removeFromWorkList(N1.getNode());
7351 DAG.DeleteNode(N1.getNode());
7352 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7358 // Restore N1 if the above transformation doesn't match.
7359 N1 = N->getOperand(1);
7362 // Transform br(xor(x, y)) -> br(x != y)
7363 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7364 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7365 SDNode *TheXor = N1.getNode();
7366 SDValue Op0 = TheXor->getOperand(0);
7367 SDValue Op1 = TheXor->getOperand(1);
7368 if (Op0.getOpcode() == Op1.getOpcode()) {
7369 // Avoid missing important xor optimizations.
7370 SDValue Tmp = visitXOR(TheXor);
7371 if (Tmp.getNode()) {
7372 if (Tmp.getNode() != TheXor) {
7373 DEBUG(dbgs() << "\nReplacing.8 ";
7375 dbgs() << "\nWith: ";
7376 Tmp.getNode()->dump(&DAG);
7378 WorkListRemover DeadNodes(*this);
7379 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7380 removeFromWorkList(TheXor);
7381 DAG.DeleteNode(TheXor);
7382 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7383 MVT::Other, Chain, Tmp, N2);
7386 // visitXOR has changed XOR's operands or replaced the XOR completely,
7388 return SDValue(N, 0);
7392 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7394 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7395 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7396 Op0.getOpcode() == ISD::XOR) {
7397 TheXor = Op0.getNode();
7401 EVT SetCCVT = N1.getValueType();
7403 SetCCVT = getSetCCResultType(SetCCVT);
7404 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7407 Equal ? ISD::SETEQ : ISD::SETNE);
7408 // Replace the uses of XOR with SETCC
7409 WorkListRemover DeadNodes(*this);
7410 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7411 removeFromWorkList(N1.getNode());
7412 DAG.DeleteNode(N1.getNode());
7413 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7414 MVT::Other, Chain, SetCC, N2);
7421 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7423 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7424 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7425 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7427 // If N is a constant we could fold this into a fallthrough or unconditional
7428 // branch. However that doesn't happen very often in normal code, because
7429 // Instcombine/SimplifyCFG should have handled the available opportunities.
7430 // If we did this folding here, it would be necessary to update the
7431 // MachineBasicBlock CFG, which is awkward.
7433 // Use SimplifySetCC to simplify SETCC's.
7434 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7435 CondLHS, CondRHS, CC->get(), SDLoc(N),
7437 if (Simp.getNode()) AddToWorkList(Simp.getNode());
7439 // fold to a simpler setcc
7440 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7441 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7442 N->getOperand(0), Simp.getOperand(2),
7443 Simp.getOperand(0), Simp.getOperand(1),
7449 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7450 /// uses N as its base pointer and that N may be folded in the load / store
7451 /// addressing mode.
7452 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7454 const TargetLowering &TLI) {
7456 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7457 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7459 VT = Use->getValueType(0);
7460 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7461 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7463 VT = ST->getValue().getValueType();
7467 TargetLowering::AddrMode AM;
7468 if (N->getOpcode() == ISD::ADD) {
7469 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7472 AM.BaseOffs = Offset->getSExtValue();
7476 } else if (N->getOpcode() == ISD::SUB) {
7477 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7480 AM.BaseOffs = -Offset->getSExtValue();
7487 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7490 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7491 /// pre-indexed load / store when the base pointer is an add or subtract
7492 /// and it has other uses besides the load / store. After the
7493 /// transformation, the new indexed load / store has effectively folded
7494 /// the add / subtract in and all of its other uses are redirected to the
7495 /// new load / store.
7496 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7497 if (Level < AfterLegalizeDAG)
7503 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7504 if (LD->isIndexed())
7506 VT = LD->getMemoryVT();
7507 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7508 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7510 Ptr = LD->getBasePtr();
7511 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7512 if (ST->isIndexed())
7514 VT = ST->getMemoryVT();
7515 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7516 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7518 Ptr = ST->getBasePtr();
7524 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7525 // out. There is no reason to make this a preinc/predec.
7526 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7527 Ptr.getNode()->hasOneUse())
7530 // Ask the target to do addressing mode selection.
7533 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7534 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7537 // Backends without true r+i pre-indexed forms may need to pass a
7538 // constant base with a variable offset so that constant coercion
7539 // will work with the patterns in canonical form.
7540 bool Swapped = false;
7541 if (isa<ConstantSDNode>(BasePtr)) {
7542 std::swap(BasePtr, Offset);
7546 // Don't create a indexed load / store with zero offset.
7547 if (isa<ConstantSDNode>(Offset) &&
7548 cast<ConstantSDNode>(Offset)->isNullValue())
7551 // Try turning it into a pre-indexed load / store except when:
7552 // 1) The new base ptr is a frame index.
7553 // 2) If N is a store and the new base ptr is either the same as or is a
7554 // predecessor of the value being stored.
7555 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7556 // that would create a cycle.
7557 // 4) All uses are load / store ops that use it as old base ptr.
7559 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7560 // (plus the implicit offset) to a register to preinc anyway.
7561 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7566 SDValue Val = cast<StoreSDNode>(N)->getValue();
7567 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7571 // If the offset is a constant, there may be other adds of constants that
7572 // can be folded with this one. We should do this to avoid having to keep
7573 // a copy of the original base pointer.
7574 SmallVector<SDNode *, 16> OtherUses;
7575 if (isa<ConstantSDNode>(Offset))
7576 for (SDNode *Use : BasePtr.getNode()->uses()) {
7577 if (Use == Ptr.getNode())
7580 if (Use->isPredecessorOf(N))
7583 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7588 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7589 if (Op1.getNode() == BasePtr.getNode())
7590 std::swap(Op0, Op1);
7591 assert(Op0.getNode() == BasePtr.getNode() &&
7592 "Use of ADD/SUB but not an operand");
7594 if (!isa<ConstantSDNode>(Op1)) {
7599 // FIXME: In some cases, we can be smarter about this.
7600 if (Op1.getValueType() != Offset.getValueType()) {
7605 OtherUses.push_back(Use);
7609 std::swap(BasePtr, Offset);
7611 // Now check for #3 and #4.
7612 bool RealUse = false;
7614 // Caches for hasPredecessorHelper
7615 SmallPtrSet<const SDNode *, 32> Visited;
7616 SmallVector<const SDNode *, 16> Worklist;
7618 for (SDNode *Use : Ptr.getNode()->uses()) {
7621 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7624 // If Ptr may be folded in addressing mode of other use, then it's
7625 // not profitable to do this transformation.
7626 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7635 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7636 BasePtr, Offset, AM);
7638 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7639 BasePtr, Offset, AM);
7642 DEBUG(dbgs() << "\nReplacing.4 ";
7644 dbgs() << "\nWith: ";
7645 Result.getNode()->dump(&DAG);
7647 WorkListRemover DeadNodes(*this);
7649 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7650 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7652 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7655 // Finally, since the node is now dead, remove it from the graph.
7659 std::swap(BasePtr, Offset);
7661 // Replace other uses of BasePtr that can be updated to use Ptr
7662 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7663 unsigned OffsetIdx = 1;
7664 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7666 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7667 BasePtr.getNode() && "Expected BasePtr operand");
7669 // We need to replace ptr0 in the following expression:
7670 // x0 * offset0 + y0 * ptr0 = t0
7672 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7674 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7675 // indexed load/store and the expresion that needs to be re-written.
7677 // Therefore, we have:
7678 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7680 ConstantSDNode *CN =
7681 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7683 APInt Offset0 = CN->getAPIntValue();
7684 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7686 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7687 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7688 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7689 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7691 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7693 APInt CNV = Offset0;
7694 if (X0 < 0) CNV = -CNV;
7695 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7696 else CNV = CNV - Offset1;
7698 // We can now generate the new expression.
7699 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7700 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7702 SDValue NewUse = DAG.getNode(Opcode,
7703 SDLoc(OtherUses[i]),
7704 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7705 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7706 removeFromWorkList(OtherUses[i]);
7707 DAG.DeleteNode(OtherUses[i]);
7710 // Replace the uses of Ptr with uses of the updated base value.
7711 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7712 removeFromWorkList(Ptr.getNode());
7713 DAG.DeleteNode(Ptr.getNode());
7718 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7719 /// add / sub of the base pointer node into a post-indexed load / store.
7720 /// The transformation folded the add / subtract into the new indexed
7721 /// load / store effectively and all of its uses are redirected to the
7722 /// new load / store.
7723 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7724 if (Level < AfterLegalizeDAG)
7730 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7731 if (LD->isIndexed())
7733 VT = LD->getMemoryVT();
7734 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7735 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7737 Ptr = LD->getBasePtr();
7738 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7739 if (ST->isIndexed())
7741 VT = ST->getMemoryVT();
7742 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7743 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7745 Ptr = ST->getBasePtr();
7751 if (Ptr.getNode()->hasOneUse())
7754 for (SDNode *Op : Ptr.getNode()->uses()) {
7756 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7761 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7762 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7763 // Don't create a indexed load / store with zero offset.
7764 if (isa<ConstantSDNode>(Offset) &&
7765 cast<ConstantSDNode>(Offset)->isNullValue())
7768 // Try turning it into a post-indexed load / store except when
7769 // 1) All uses are load / store ops that use it as base ptr (and
7770 // it may be folded as addressing mmode).
7771 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7772 // nor a successor of N. Otherwise, if Op is folded that would
7775 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7779 bool TryNext = false;
7780 for (SDNode *Use : BasePtr.getNode()->uses()) {
7781 if (Use == Ptr.getNode())
7784 // If all the uses are load / store addresses, then don't do the
7786 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7787 bool RealUse = false;
7788 for (SDNode *UseUse : Use->uses()) {
7789 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7804 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7805 SDValue Result = isLoad
7806 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7807 BasePtr, Offset, AM)
7808 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7809 BasePtr, Offset, AM);
7812 DEBUG(dbgs() << "\nReplacing.5 ";
7814 dbgs() << "\nWith: ";
7815 Result.getNode()->dump(&DAG);
7817 WorkListRemover DeadNodes(*this);
7819 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7820 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7822 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7825 // Finally, since the node is now dead, remove it from the graph.
7828 // Replace the uses of Use with uses of the updated base value.
7829 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7830 Result.getValue(isLoad ? 1 : 0));
7831 removeFromWorkList(Op);
7841 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7842 LoadSDNode *LD = cast<LoadSDNode>(N);
7843 SDValue Chain = LD->getChain();
7844 SDValue Ptr = LD->getBasePtr();
7846 // If load is not volatile and there are no uses of the loaded value (and
7847 // the updated indexed value in case of indexed loads), change uses of the
7848 // chain value into uses of the chain input (i.e. delete the dead load).
7849 if (!LD->isVolatile()) {
7850 if (N->getValueType(1) == MVT::Other) {
7852 if (!N->hasAnyUseOfValue(0)) {
7853 // It's not safe to use the two value CombineTo variant here. e.g.
7854 // v1, chain2 = load chain1, loc
7855 // v2, chain3 = load chain2, loc
7857 // Now we replace use of chain2 with chain1. This makes the second load
7858 // isomorphic to the one we are deleting, and thus makes this load live.
7859 DEBUG(dbgs() << "\nReplacing.6 ";
7861 dbgs() << "\nWith chain: ";
7862 Chain.getNode()->dump(&DAG);
7864 WorkListRemover DeadNodes(*this);
7865 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7867 if (N->use_empty()) {
7868 removeFromWorkList(N);
7872 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7876 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7877 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7878 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7879 DEBUG(dbgs() << "\nReplacing.7 ";
7881 dbgs() << "\nWith: ";
7882 Undef.getNode()->dump(&DAG);
7883 dbgs() << " and 2 other values\n");
7884 WorkListRemover DeadNodes(*this);
7885 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7886 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7887 DAG.getUNDEF(N->getValueType(1)));
7888 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7889 removeFromWorkList(N);
7891 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7896 // If this load is directly stored, replace the load value with the stored
7898 // TODO: Handle store large -> read small portion.
7899 // TODO: Handle TRUNCSTORE/LOADEXT
7900 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7901 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7902 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7903 if (PrevST->getBasePtr() == Ptr &&
7904 PrevST->getValue().getValueType() == N->getValueType(0))
7905 return CombineTo(N, Chain.getOperand(1), Chain);
7909 // Try to infer better alignment information than the load already has.
7910 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7911 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7912 if (Align > LD->getMemOperand()->getBaseAlignment()) {
7914 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7915 LD->getValueType(0),
7916 Chain, Ptr, LD->getPointerInfo(),
7918 LD->isVolatile(), LD->isNonTemporal(), Align,
7920 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7925 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7926 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7928 if (CombinerAAOnlyFunc.getNumOccurrences() &&
7929 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
7932 if (UseAA && LD->isUnindexed()) {
7933 // Walk up chain skipping non-aliasing memory nodes.
7934 SDValue BetterChain = FindBetterChain(N, Chain);
7936 // If there is a better chain.
7937 if (Chain != BetterChain) {
7940 // Replace the chain to void dependency.
7941 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7942 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7943 BetterChain, Ptr, LD->getMemOperand());
7945 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7946 LD->getValueType(0),
7947 BetterChain, Ptr, LD->getMemoryVT(),
7948 LD->getMemOperand());
7951 // Create token factor to keep old chain connected.
7952 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7953 MVT::Other, Chain, ReplLoad.getValue(1));
7955 // Make sure the new and old chains are cleaned up.
7956 AddToWorkList(Token.getNode());
7958 // Replace uses with load result and token factor. Don't add users
7960 return CombineTo(N, ReplLoad.getValue(0), Token, false);
7964 // Try transforming N to an indexed load.
7965 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7966 return SDValue(N, 0);
7968 // Try to slice up N to more direct loads if the slices are mapped to
7969 // different register banks or pairing can take place.
7971 return SDValue(N, 0);
7977 /// \brief Helper structure used to slice a load in smaller loads.
7978 /// Basically a slice is obtained from the following sequence:
7979 /// Origin = load Ty1, Base
7980 /// Shift = srl Ty1 Origin, CstTy Amount
7981 /// Inst = trunc Shift to Ty2
7983 /// Then, it will be rewriten into:
7984 /// Slice = load SliceTy, Base + SliceOffset
7985 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
7987 /// SliceTy is deduced from the number of bits that are actually used to
7989 struct LoadedSlice {
7990 /// \brief Helper structure used to compute the cost of a slice.
7992 /// Are we optimizing for code size.
7997 unsigned CrossRegisterBanksCopies;
8001 Cost(bool ForCodeSize = false)
8002 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8003 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8005 /// \brief Get the cost of one isolated slice.
8006 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8007 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8008 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8009 EVT TruncType = LS.Inst->getValueType(0);
8010 EVT LoadedType = LS.getLoadedType();
8011 if (TruncType != LoadedType &&
8012 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8016 /// \brief Account for slicing gain in the current cost.
8017 /// Slicing provide a few gains like removing a shift or a
8018 /// truncate. This method allows to grow the cost of the original
8019 /// load with the gain from this slice.
8020 void addSliceGain(const LoadedSlice &LS) {
8021 // Each slice saves a truncate.
8022 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8023 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8024 LS.Inst->getOperand(0).getValueType()))
8026 // If there is a shift amount, this slice gets rid of it.
8029 // If this slice can merge a cross register bank copy, account for it.
8030 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8031 ++CrossRegisterBanksCopies;
8034 Cost &operator+=(const Cost &RHS) {
8036 Truncates += RHS.Truncates;
8037 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8043 bool operator==(const Cost &RHS) const {
8044 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8045 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8046 ZExts == RHS.ZExts && Shift == RHS.Shift;
8049 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8051 bool operator<(const Cost &RHS) const {
8052 // Assume cross register banks copies are as expensive as loads.
8053 // FIXME: Do we want some more target hooks?
8054 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8055 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8056 // Unless we are optimizing for code size, consider the
8057 // expensive operation first.
8058 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8059 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8060 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8061 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8064 bool operator>(const Cost &RHS) const { return RHS < *this; }
8066 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8068 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8070 // The last instruction that represent the slice. This should be a
8071 // truncate instruction.
8073 // The original load instruction.
8075 // The right shift amount in bits from the original load.
8077 // The DAG from which Origin came from.
8078 // This is used to get some contextual information about legal types, etc.
8081 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8082 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8083 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8085 LoadedSlice(const LoadedSlice &LS)
8086 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8088 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8089 /// \return Result is \p BitWidth and has used bits set to 1 and
8090 /// not used bits set to 0.
8091 APInt getUsedBits() const {
8092 // Reproduce the trunc(lshr) sequence:
8093 // - Start from the truncated value.
8094 // - Zero extend to the desired bit width.
8096 assert(Origin && "No original load to compare against.");
8097 unsigned BitWidth = Origin->getValueSizeInBits(0);
8098 assert(Inst && "This slice is not bound to an instruction");
8099 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8100 "Extracted slice is bigger than the whole type!");
8101 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8102 UsedBits.setAllBits();
8103 UsedBits = UsedBits.zext(BitWidth);
8108 /// \brief Get the size of the slice to be loaded in bytes.
8109 unsigned getLoadedSize() const {
8110 unsigned SliceSize = getUsedBits().countPopulation();
8111 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8112 return SliceSize / 8;
8115 /// \brief Get the type that will be loaded for this slice.
8116 /// Note: This may not be the final type for the slice.
8117 EVT getLoadedType() const {
8118 assert(DAG && "Missing context");
8119 LLVMContext &Ctxt = *DAG->getContext();
8120 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8123 /// \brief Get the alignment of the load used for this slice.
8124 unsigned getAlignment() const {
8125 unsigned Alignment = Origin->getAlignment();
8126 unsigned Offset = getOffsetFromBase();
8128 Alignment = MinAlign(Alignment, Alignment + Offset);
8132 /// \brief Check if this slice can be rewritten with legal operations.
8133 bool isLegal() const {
8134 // An invalid slice is not legal.
8135 if (!Origin || !Inst || !DAG)
8138 // Offsets are for indexed load only, we do not handle that.
8139 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8142 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8144 // Check that the type is legal.
8145 EVT SliceType = getLoadedType();
8146 if (!TLI.isTypeLegal(SliceType))
8149 // Check that the load is legal for this type.
8150 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8153 // Check that the offset can be computed.
8154 // 1. Check its type.
8155 EVT PtrType = Origin->getBasePtr().getValueType();
8156 if (PtrType == MVT::Untyped || PtrType.isExtended())
8159 // 2. Check that it fits in the immediate.
8160 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8163 // 3. Check that the computation is legal.
8164 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8167 // Check that the zext is legal if it needs one.
8168 EVT TruncateType = Inst->getValueType(0);
8169 if (TruncateType != SliceType &&
8170 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8176 /// \brief Get the offset in bytes of this slice in the original chunk of
8178 /// \pre DAG != nullptr.
8179 uint64_t getOffsetFromBase() const {
8180 assert(DAG && "Missing context.");
8182 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8183 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8184 uint64_t Offset = Shift / 8;
8185 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8186 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8187 "The size of the original loaded type is not a multiple of a"
8189 // If Offset is bigger than TySizeInBytes, it means we are loading all
8190 // zeros. This should have been optimized before in the process.
8191 assert(TySizeInBytes > Offset &&
8192 "Invalid shift amount for given loaded size");
8194 Offset = TySizeInBytes - Offset - getLoadedSize();
8198 /// \brief Generate the sequence of instructions to load the slice
8199 /// represented by this object and redirect the uses of this slice to
8200 /// this new sequence of instructions.
8201 /// \pre this->Inst && this->Origin are valid Instructions and this
8202 /// object passed the legal check: LoadedSlice::isLegal returned true.
8203 /// \return The last instruction of the sequence used to load the slice.
8204 SDValue loadSlice() const {
8205 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8206 const SDValue &OldBaseAddr = Origin->getBasePtr();
8207 SDValue BaseAddr = OldBaseAddr;
8208 // Get the offset in that chunk of bytes w.r.t. the endianess.
8209 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8210 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8212 // BaseAddr = BaseAddr + Offset.
8213 EVT ArithType = BaseAddr.getValueType();
8214 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8215 DAG->getConstant(Offset, ArithType));
8218 // Create the type of the loaded slice according to its size.
8219 EVT SliceType = getLoadedType();
8221 // Create the load for the slice.
8222 SDValue LastInst = DAG->getLoad(
8223 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8224 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8225 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8226 // If the final type is not the same as the loaded type, this means that
8227 // we have to pad with zero. Create a zero extend for that.
8228 EVT FinalType = Inst->getValueType(0);
8229 if (SliceType != FinalType)
8231 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8235 /// \brief Check if this slice can be merged with an expensive cross register
8236 /// bank copy. E.g.,
8238 /// f = bitcast i32 i to float
8239 bool canMergeExpensiveCrossRegisterBankCopy() const {
8240 if (!Inst || !Inst->hasOneUse())
8242 SDNode *Use = *Inst->use_begin();
8243 if (Use->getOpcode() != ISD::BITCAST)
8245 assert(DAG && "Missing context");
8246 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8247 EVT ResVT = Use->getValueType(0);
8248 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8249 const TargetRegisterClass *ArgRC =
8250 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8251 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8254 // At this point, we know that we perform a cross-register-bank copy.
8255 // Check if it is expensive.
8256 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8257 // Assume bitcasts are cheap, unless both register classes do not
8258 // explicitly share a common sub class.
8259 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8262 // Check if it will be merged with the load.
8263 // 1. Check the alignment constraint.
8264 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8265 ResVT.getTypeForEVT(*DAG->getContext()));
8267 if (RequiredAlignment > getAlignment())
8270 // 2. Check that the load is a legal operation for that type.
8271 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8274 // 3. Check that we do not have a zext in the way.
8275 if (Inst->getValueType(0) != getLoadedType())
8283 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8284 /// \p UsedBits looks like 0..0 1..1 0..0.
8285 static bool areUsedBitsDense(const APInt &UsedBits) {
8286 // If all the bits are one, this is dense!
8287 if (UsedBits.isAllOnesValue())
8290 // Get rid of the unused bits on the right.
8291 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8292 // Get rid of the unused bits on the left.
8293 if (NarrowedUsedBits.countLeadingZeros())
8294 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8295 // Check that the chunk of bits is completely used.
8296 return NarrowedUsedBits.isAllOnesValue();
8299 /// \brief Check whether or not \p First and \p Second are next to each other
8300 /// in memory. This means that there is no hole between the bits loaded
8301 /// by \p First and the bits loaded by \p Second.
8302 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8303 const LoadedSlice &Second) {
8304 assert(First.Origin == Second.Origin && First.Origin &&
8305 "Unable to match different memory origins.");
8306 APInt UsedBits = First.getUsedBits();
8307 assert((UsedBits & Second.getUsedBits()) == 0 &&
8308 "Slices are not supposed to overlap.");
8309 UsedBits |= Second.getUsedBits();
8310 return areUsedBitsDense(UsedBits);
8313 /// \brief Adjust the \p GlobalLSCost according to the target
8314 /// paring capabilities and the layout of the slices.
8315 /// \pre \p GlobalLSCost should account for at least as many loads as
8316 /// there is in the slices in \p LoadedSlices.
8317 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8318 LoadedSlice::Cost &GlobalLSCost) {
8319 unsigned NumberOfSlices = LoadedSlices.size();
8320 // If there is less than 2 elements, no pairing is possible.
8321 if (NumberOfSlices < 2)
8324 // Sort the slices so that elements that are likely to be next to each
8325 // other in memory are next to each other in the list.
8326 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8327 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8328 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8329 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8331 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8332 // First (resp. Second) is the first (resp. Second) potentially candidate
8333 // to be placed in a paired load.
8334 const LoadedSlice *First = nullptr;
8335 const LoadedSlice *Second = nullptr;
8336 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8337 // Set the beginning of the pair.
8340 Second = &LoadedSlices[CurrSlice];
8342 // If First is NULL, it means we start a new pair.
8343 // Get to the next slice.
8347 EVT LoadedType = First->getLoadedType();
8349 // If the types of the slices are different, we cannot pair them.
8350 if (LoadedType != Second->getLoadedType())
8353 // Check if the target supplies paired loads for this type.
8354 unsigned RequiredAlignment = 0;
8355 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8356 // move to the next pair, this type is hopeless.
8360 // Check if we meet the alignment requirement.
8361 if (RequiredAlignment > First->getAlignment())
8364 // Check that both loads are next to each other in memory.
8365 if (!areSlicesNextToEachOther(*First, *Second))
8368 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8369 --GlobalLSCost.Loads;
8370 // Move to the next pair.
8375 /// \brief Check the profitability of all involved LoadedSlice.
8376 /// Currently, it is considered profitable if there is exactly two
8377 /// involved slices (1) which are (2) next to each other in memory, and
8378 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8380 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8381 /// the elements themselves.
8383 /// FIXME: When the cost model will be mature enough, we can relax
8384 /// constraints (1) and (2).
8385 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8386 const APInt &UsedBits, bool ForCodeSize) {
8387 unsigned NumberOfSlices = LoadedSlices.size();
8388 if (StressLoadSlicing)
8389 return NumberOfSlices > 1;
8392 if (NumberOfSlices != 2)
8396 if (!areUsedBitsDense(UsedBits))
8400 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8401 // The original code has one big load.
8403 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8404 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8405 // Accumulate the cost of all the slices.
8406 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8407 GlobalSlicingCost += SliceCost;
8409 // Account as cost in the original configuration the gain obtained
8410 // with the current slices.
8411 OrigCost.addSliceGain(LS);
8414 // If the target supports paired load, adjust the cost accordingly.
8415 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8416 return OrigCost > GlobalSlicingCost;
8419 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8420 /// operations, split it in the various pieces being extracted.
8422 /// This sort of thing is introduced by SROA.
8423 /// This slicing takes care not to insert overlapping loads.
8424 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8425 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8426 if (Level < AfterLegalizeDAG)
8429 LoadSDNode *LD = cast<LoadSDNode>(N);
8430 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8431 !LD->getValueType(0).isInteger())
8434 // Keep track of already used bits to detect overlapping values.
8435 // In that case, we will just abort the transformation.
8436 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8438 SmallVector<LoadedSlice, 4> LoadedSlices;
8440 // Check if this load is used as several smaller chunks of bits.
8441 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8442 // of computation for each trunc.
8443 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8444 UI != UIEnd; ++UI) {
8445 // Skip the uses of the chain.
8446 if (UI.getUse().getResNo() != 0)
8452 // Check if this is a trunc(lshr).
8453 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8454 isa<ConstantSDNode>(User->getOperand(1))) {
8455 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8456 User = *User->use_begin();
8459 // At this point, User is a Truncate, iff we encountered, trunc or
8461 if (User->getOpcode() != ISD::TRUNCATE)
8464 // The width of the type must be a power of 2 and greater than 8-bits.
8465 // Otherwise the load cannot be represented in LLVM IR.
8466 // Moreover, if we shifted with a non-8-bits multiple, the slice
8467 // will be across several bytes. We do not support that.
8468 unsigned Width = User->getValueSizeInBits(0);
8469 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8472 // Build the slice for this chain of computations.
8473 LoadedSlice LS(User, LD, Shift, &DAG);
8474 APInt CurrentUsedBits = LS.getUsedBits();
8476 // Check if this slice overlaps with another.
8477 if ((CurrentUsedBits & UsedBits) != 0)
8479 // Update the bits used globally.
8480 UsedBits |= CurrentUsedBits;
8482 // Check if the new slice would be legal.
8486 // Record the slice.
8487 LoadedSlices.push_back(LS);
8490 // Abort slicing if it does not seem to be profitable.
8491 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8496 // Rewrite each chain to use an independent load.
8497 // By construction, each chain can be represented by a unique load.
8499 // Prepare the argument for the new token factor for all the slices.
8500 SmallVector<SDValue, 8> ArgChains;
8501 for (SmallVectorImpl<LoadedSlice>::const_iterator
8502 LSIt = LoadedSlices.begin(),
8503 LSItEnd = LoadedSlices.end();
8504 LSIt != LSItEnd; ++LSIt) {
8505 SDValue SliceInst = LSIt->loadSlice();
8506 CombineTo(LSIt->Inst, SliceInst, true);
8507 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8508 SliceInst = SliceInst.getOperand(0);
8509 assert(SliceInst->getOpcode() == ISD::LOAD &&
8510 "It takes more than a zext to get to the loaded slice!!");
8511 ArgChains.push_back(SliceInst.getValue(1));
8514 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8515 &ArgChains[0], ArgChains.size());
8516 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8520 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8521 /// load is having specific bytes cleared out. If so, return the byte size
8522 /// being masked out and the shift amount.
8523 static std::pair<unsigned, unsigned>
8524 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8525 std::pair<unsigned, unsigned> Result(0, 0);
8527 // Check for the structure we're looking for.
8528 if (V->getOpcode() != ISD::AND ||
8529 !isa<ConstantSDNode>(V->getOperand(1)) ||
8530 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8533 // Check the chain and pointer.
8534 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8535 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
8537 // The store should be chained directly to the load or be an operand of a
8539 if (LD == Chain.getNode())
8541 else if (Chain->getOpcode() != ISD::TokenFactor)
8542 return Result; // Fail.
8545 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8546 if (Chain->getOperand(i).getNode() == LD) {
8550 if (!isOk) return Result;
8553 // This only handles simple types.
8554 if (V.getValueType() != MVT::i16 &&
8555 V.getValueType() != MVT::i32 &&
8556 V.getValueType() != MVT::i64)
8559 // Check the constant mask. Invert it so that the bits being masked out are
8560 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8561 // follow the sign bit for uniformity.
8562 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8563 unsigned NotMaskLZ = countLeadingZeros(NotMask);
8564 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
8565 unsigned NotMaskTZ = countTrailingZeros(NotMask);
8566 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8567 if (NotMaskLZ == 64) return Result; // All zero mask.
8569 // See if we have a continuous run of bits. If so, we have 0*1+0*
8570 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8573 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8574 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8575 NotMaskLZ -= 64-V.getValueSizeInBits();
8577 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8578 switch (MaskedBytes) {
8582 default: return Result; // All one mask, or 5-byte mask.
8585 // Verify that the first bit starts at a multiple of mask so that the access
8586 // is aligned the same as the access width.
8587 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8589 Result.first = MaskedBytes;
8590 Result.second = NotMaskTZ/8;
8595 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8596 /// provides a value as specified by MaskInfo. If so, replace the specified
8597 /// store with a narrower store of truncated IVal.
8599 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8600 SDValue IVal, StoreSDNode *St,
8602 unsigned NumBytes = MaskInfo.first;
8603 unsigned ByteShift = MaskInfo.second;
8604 SelectionDAG &DAG = DC->getDAG();
8606 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8607 // that uses this. If not, this is not a replacement.
8608 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8609 ByteShift*8, (ByteShift+NumBytes)*8);
8610 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8612 // Check that it is legal on the target to do this. It is legal if the new
8613 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8615 MVT VT = MVT::getIntegerVT(NumBytes*8);
8616 if (!DC->isTypeLegal(VT))
8619 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8620 // shifted by ByteShift and truncated down to NumBytes.
8622 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8623 DAG.getConstant(ByteShift*8,
8624 DC->getShiftAmountTy(IVal.getValueType())));
8626 // Figure out the offset for the store and the alignment of the access.
8628 unsigned NewAlign = St->getAlignment();
8630 if (DAG.getTargetLoweringInfo().isLittleEndian())
8631 StOffset = ByteShift;
8633 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8635 SDValue Ptr = St->getBasePtr();
8637 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8638 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8639 NewAlign = MinAlign(NewAlign, StOffset);
8642 // Truncate down to the new size.
8643 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8646 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8647 St->getPointerInfo().getWithOffset(StOffset),
8648 false, false, NewAlign).getNode();
8652 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8653 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8654 /// of the loaded bits, try narrowing the load and store if it would end up
8655 /// being a win for performance or code size.
8656 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8657 StoreSDNode *ST = cast<StoreSDNode>(N);
8658 if (ST->isVolatile())
8661 SDValue Chain = ST->getChain();
8662 SDValue Value = ST->getValue();
8663 SDValue Ptr = ST->getBasePtr();
8664 EVT VT = Value.getValueType();
8666 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8669 unsigned Opc = Value.getOpcode();
8671 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8672 // is a byte mask indicating a consecutive number of bytes, check to see if
8673 // Y is known to provide just those bytes. If so, we try to replace the
8674 // load + replace + store sequence with a single (narrower) store, which makes
8676 if (Opc == ISD::OR) {
8677 std::pair<unsigned, unsigned> MaskedLoad;
8678 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8679 if (MaskedLoad.first)
8680 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8681 Value.getOperand(1), ST,this))
8682 return SDValue(NewST, 0);
8684 // Or is commutative, so try swapping X and Y.
8685 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8686 if (MaskedLoad.first)
8687 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8688 Value.getOperand(0), ST,this))
8689 return SDValue(NewST, 0);
8692 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8693 Value.getOperand(1).getOpcode() != ISD::Constant)
8696 SDValue N0 = Value.getOperand(0);
8697 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8698 Chain == SDValue(N0.getNode(), 1)) {
8699 LoadSDNode *LD = cast<LoadSDNode>(N0);
8700 if (LD->getBasePtr() != Ptr ||
8701 LD->getPointerInfo().getAddrSpace() !=
8702 ST->getPointerInfo().getAddrSpace())
8705 // Find the type to narrow it the load / op / store to.
8706 SDValue N1 = Value.getOperand(1);
8707 unsigned BitWidth = N1.getValueSizeInBits();
8708 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8709 if (Opc == ISD::AND)
8710 Imm ^= APInt::getAllOnesValue(BitWidth);
8711 if (Imm == 0 || Imm.isAllOnesValue())
8713 unsigned ShAmt = Imm.countTrailingZeros();
8714 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8715 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8716 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8717 while (NewBW < BitWidth &&
8718 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8719 TLI.isNarrowingProfitable(VT, NewVT))) {
8720 NewBW = NextPowerOf2(NewBW);
8721 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8723 if (NewBW >= BitWidth)
8726 // If the lsb changed does not start at the type bitwidth boundary,
8727 // start at the previous one.
8729 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8730 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8731 std::min(BitWidth, ShAmt + NewBW));
8732 if ((Imm & Mask) == Imm) {
8733 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8734 if (Opc == ISD::AND)
8735 NewImm ^= APInt::getAllOnesValue(NewBW);
8736 uint64_t PtrOff = ShAmt / 8;
8737 // For big endian targets, we need to adjust the offset to the pointer to
8738 // load the correct bytes.
8739 if (TLI.isBigEndian())
8740 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8742 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8743 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8744 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8747 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8748 Ptr.getValueType(), Ptr,
8749 DAG.getConstant(PtrOff, Ptr.getValueType()));
8750 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8751 LD->getChain(), NewPtr,
8752 LD->getPointerInfo().getWithOffset(PtrOff),
8753 LD->isVolatile(), LD->isNonTemporal(),
8754 LD->isInvariant(), NewAlign,
8756 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8757 DAG.getConstant(NewImm, NewVT));
8758 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8760 ST->getPointerInfo().getWithOffset(PtrOff),
8761 false, false, NewAlign);
8763 AddToWorkList(NewPtr.getNode());
8764 AddToWorkList(NewLD.getNode());
8765 AddToWorkList(NewVal.getNode());
8766 WorkListRemover DeadNodes(*this);
8767 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8776 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8777 /// if the load value isn't used by any other operations, then consider
8778 /// transforming the pair to integer load / store operations if the target
8779 /// deems the transformation profitable.
8780 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8781 StoreSDNode *ST = cast<StoreSDNode>(N);
8782 SDValue Chain = ST->getChain();
8783 SDValue Value = ST->getValue();
8784 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8785 Value.hasOneUse() &&
8786 Chain == SDValue(Value.getNode(), 1)) {
8787 LoadSDNode *LD = cast<LoadSDNode>(Value);
8788 EVT VT = LD->getMemoryVT();
8789 if (!VT.isFloatingPoint() ||
8790 VT != ST->getMemoryVT() ||
8791 LD->isNonTemporal() ||
8792 ST->isNonTemporal() ||
8793 LD->getPointerInfo().getAddrSpace() != 0 ||
8794 ST->getPointerInfo().getAddrSpace() != 0)
8797 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8798 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8799 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8800 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8801 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8804 unsigned LDAlign = LD->getAlignment();
8805 unsigned STAlign = ST->getAlignment();
8806 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8807 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8808 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8811 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8812 LD->getChain(), LD->getBasePtr(),
8813 LD->getPointerInfo(),
8814 false, false, false, LDAlign);
8816 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8817 NewLD, ST->getBasePtr(),
8818 ST->getPointerInfo(),
8819 false, false, STAlign);
8821 AddToWorkList(NewLD.getNode());
8822 AddToWorkList(NewST.getNode());
8823 WorkListRemover DeadNodes(*this);
8824 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8832 /// Helper struct to parse and store a memory address as base + index + offset.
8833 /// We ignore sign extensions when it is safe to do so.
8834 /// The following two expressions are not equivalent. To differentiate we need
8835 /// to store whether there was a sign extension involved in the index
8837 /// (load (i64 add (i64 copyfromreg %c)
8838 /// (i64 signextend (add (i8 load %index)
8842 /// (load (i64 add (i64 copyfromreg %c)
8843 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8845 struct BaseIndexOffset {
8849 bool IsIndexSignExt;
8851 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8853 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8854 bool IsIndexSignExt) :
8855 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8857 bool equalBaseIndex(const BaseIndexOffset &Other) {
8858 return Other.Base == Base && Other.Index == Index &&
8859 Other.IsIndexSignExt == IsIndexSignExt;
8862 /// Parses tree in Ptr for base, index, offset addresses.
8863 static BaseIndexOffset match(SDValue Ptr) {
8864 bool IsIndexSignExt = false;
8866 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8867 // instruction, then it could be just the BASE or everything else we don't
8868 // know how to handle. Just use Ptr as BASE and give up.
8869 if (Ptr->getOpcode() != ISD::ADD)
8870 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8872 // We know that we have at least an ADD instruction. Try to pattern match
8873 // the simple case of BASE + OFFSET.
8874 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8875 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8876 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8880 // Inside a loop the current BASE pointer is calculated using an ADD and a
8881 // MUL instruction. In this case Ptr is the actual BASE pointer.
8882 // (i64 add (i64 %array_ptr)
8883 // (i64 mul (i64 %induction_var)
8884 // (i64 %element_size)))
8885 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8886 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8888 // Look at Base + Index + Offset cases.
8889 SDValue Base = Ptr->getOperand(0);
8890 SDValue IndexOffset = Ptr->getOperand(1);
8892 // Skip signextends.
8893 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8894 IndexOffset = IndexOffset->getOperand(0);
8895 IsIndexSignExt = true;
8898 // Either the case of Base + Index (no offset) or something else.
8899 if (IndexOffset->getOpcode() != ISD::ADD)
8900 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8902 // Now we have the case of Base + Index + offset.
8903 SDValue Index = IndexOffset->getOperand(0);
8904 SDValue Offset = IndexOffset->getOperand(1);
8906 if (!isa<ConstantSDNode>(Offset))
8907 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8909 // Ignore signextends.
8910 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8911 Index = Index->getOperand(0);
8912 IsIndexSignExt = true;
8913 } else IsIndexSignExt = false;
8915 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8916 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8920 /// Holds a pointer to an LSBaseSDNode as well as information on where it
8921 /// is located in a sequence of memory operations connected by a chain.
8923 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8924 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8925 // Ptr to the mem node.
8926 LSBaseSDNode *MemNode;
8927 // Offset from the base ptr.
8928 int64_t OffsetFromBase;
8929 // What is the sequence number of this mem node.
8930 // Lowest mem operand in the DAG starts at zero.
8931 unsigned SequenceNum;
8934 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8935 EVT MemVT = St->getMemoryVT();
8936 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
8937 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8938 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
8940 // Don't merge vectors into wider inputs.
8941 if (MemVT.isVector() || !MemVT.isSimple())
8944 // Perform an early exit check. Do not bother looking at stored values that
8945 // are not constants or loads.
8946 SDValue StoredVal = St->getValue();
8947 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8948 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8952 // Only look at ends of store sequences.
8953 SDValue Chain = SDValue(St, 1);
8954 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8957 // This holds the base pointer, index, and the offset in bytes from the base
8959 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
8961 // We must have a base and an offset.
8962 if (!BasePtr.Base.getNode())
8965 // Do not handle stores to undef base pointers.
8966 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
8969 // Save the LoadSDNodes that we find in the chain.
8970 // We need to make sure that these nodes do not interfere with
8971 // any of the store nodes.
8972 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8974 // Save the StoreSDNodes that we find in the chain.
8975 SmallVector<MemOpLink, 8> StoreNodes;
8977 // Walk up the chain and look for nodes with offsets from the same
8978 // base pointer. Stop when reaching an instruction with a different kind
8979 // or instruction which has a different base pointer.
8981 StoreSDNode *Index = St;
8983 // If the chain has more than one use, then we can't reorder the mem ops.
8984 if (Index != St && !SDValue(Index, 1)->hasOneUse())
8987 // Find the base pointer and offset for this memory node.
8988 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
8990 // Check that the base pointer is the same as the original one.
8991 if (!Ptr.equalBaseIndex(BasePtr))
8994 // Check that the alignment is the same.
8995 if (Index->getAlignment() != St->getAlignment())
8998 // The memory operands must not be volatile.
8999 if (Index->isVolatile() || Index->isIndexed())
9003 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9004 if (St->isTruncatingStore())
9007 // The stored memory type must be the same.
9008 if (Index->getMemoryVT() != MemVT)
9011 // We do not allow unaligned stores because we want to prevent overriding
9013 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9016 // We found a potential memory operand to merge.
9017 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9019 // Find the next memory operand in the chain. If the next operand in the
9020 // chain is a store then move up and continue the scan with the next
9021 // memory operand. If the next operand is a load save it and use alias
9022 // information to check if it interferes with anything.
9023 SDNode *NextInChain = Index->getChain().getNode();
9025 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9026 // We found a store node. Use it for the next iteration.
9029 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9030 if (Ldn->isVolatile()) {
9035 // Save the load node for later. Continue the scan.
9036 AliasLoadNodes.push_back(Ldn);
9037 NextInChain = Ldn->getChain().getNode();
9046 // Check if there is anything to merge.
9047 if (StoreNodes.size() < 2)
9050 // Sort the memory operands according to their distance from the base pointer.
9051 std::sort(StoreNodes.begin(), StoreNodes.end(),
9052 [](MemOpLink LHS, MemOpLink RHS) {
9053 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9054 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9055 LHS.SequenceNum > RHS.SequenceNum);
9058 // Scan the memory operations on the chain and find the first non-consecutive
9059 // store memory address.
9060 unsigned LastConsecutiveStore = 0;
9061 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9062 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9064 // Check that the addresses are consecutive starting from the second
9065 // element in the list of stores.
9067 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9068 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9073 // Check if this store interferes with any of the loads that we found.
9074 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9075 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9079 // We found a load that alias with this store. Stop the sequence.
9083 // Mark this node as useful.
9084 LastConsecutiveStore = i;
9087 // The node with the lowest store address.
9088 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9090 // Store the constants into memory as one consecutive store.
9092 unsigned LastLegalType = 0;
9093 unsigned LastLegalVectorType = 0;
9094 bool NonZero = false;
9095 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9096 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9097 SDValue StoredVal = St->getValue();
9099 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9100 NonZero |= !C->isNullValue();
9101 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9102 NonZero |= !C->getConstantFPValue()->isNullValue();
9108 // Find a legal type for the constant store.
9109 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9110 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9111 if (TLI.isTypeLegal(StoreTy))
9112 LastLegalType = i+1;
9113 // Or check whether a truncstore is legal.
9114 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9115 TargetLowering::TypePromoteInteger) {
9116 EVT LegalizedStoredValueTy =
9117 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9118 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9119 LastLegalType = i+1;
9122 // Find a legal type for the vector store.
9123 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9124 if (TLI.isTypeLegal(Ty))
9125 LastLegalVectorType = i + 1;
9128 // We only use vectors if the constant is known to be zero and the
9129 // function is not marked with the noimplicitfloat attribute.
9130 if (NonZero || NoVectors)
9131 LastLegalVectorType = 0;
9133 // Check if we found a legal integer type to store.
9134 if (LastLegalType == 0 && LastLegalVectorType == 0)
9137 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9138 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9140 // Make sure we have something to merge.
9144 unsigned EarliestNodeUsed = 0;
9145 for (unsigned i=0; i < NumElem; ++i) {
9146 // Find a chain for the new wide-store operand. Notice that some
9147 // of the store nodes that we found may not be selected for inclusion
9148 // in the wide store. The chain we use needs to be the chain of the
9149 // earliest store node which is *used* and replaced by the wide store.
9150 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9151 EarliestNodeUsed = i;
9154 // The earliest Node in the DAG.
9155 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9156 SDLoc DL(StoreNodes[0].MemNode);
9160 // Find a legal type for the vector store.
9161 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9162 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9163 StoredVal = DAG.getConstant(0, Ty);
9165 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9166 APInt StoreInt(StoreBW, 0);
9168 // Construct a single integer constant which is made of the smaller
9170 bool IsLE = TLI.isLittleEndian();
9171 for (unsigned i = 0; i < NumElem ; ++i) {
9172 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9173 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9174 SDValue Val = St->getValue();
9175 StoreInt<<=ElementSizeBytes*8;
9176 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9177 StoreInt|=C->getAPIntValue().zext(StoreBW);
9178 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9179 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9181 assert(false && "Invalid constant element type");
9185 // Create the new Load and Store operations.
9186 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9187 StoredVal = DAG.getConstant(StoreInt, StoreTy);
9190 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9191 FirstInChain->getBasePtr(),
9192 FirstInChain->getPointerInfo(),
9194 FirstInChain->getAlignment());
9196 // Replace the first store with the new store
9197 CombineTo(EarliestOp, NewStore);
9198 // Erase all other stores.
9199 for (unsigned i = 0; i < NumElem ; ++i) {
9200 if (StoreNodes[i].MemNode == EarliestOp)
9202 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9203 // ReplaceAllUsesWith will replace all uses that existed when it was
9204 // called, but graph optimizations may cause new ones to appear. For
9205 // example, the case in pr14333 looks like
9207 // St's chain -> St -> another store -> X
9209 // And the only difference from St to the other store is the chain.
9210 // When we change it's chain to be St's chain they become identical,
9211 // get CSEed and the net result is that X is now a use of St.
9212 // Since we know that St is redundant, just iterate.
9213 while (!St->use_empty())
9214 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9215 removeFromWorkList(St);
9222 // Below we handle the case of multiple consecutive stores that
9223 // come from multiple consecutive loads. We merge them into a single
9224 // wide load and a single wide store.
9226 // Look for load nodes which are used by the stored values.
9227 SmallVector<MemOpLink, 8> LoadNodes;
9229 // Find acceptable loads. Loads need to have the same chain (token factor),
9230 // must not be zext, volatile, indexed, and they must be consecutive.
9231 BaseIndexOffset LdBasePtr;
9232 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9233 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9234 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9237 // Loads must only have one use.
9238 if (!Ld->hasNUsesOfValue(1, 0))
9241 // Check that the alignment is the same as the stores.
9242 if (Ld->getAlignment() != St->getAlignment())
9245 // The memory operands must not be volatile.
9246 if (Ld->isVolatile() || Ld->isIndexed())
9249 // We do not accept ext loads.
9250 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9253 // The stored memory type must be the same.
9254 if (Ld->getMemoryVT() != MemVT)
9257 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9258 // If this is not the first ptr that we check.
9259 if (LdBasePtr.Base.getNode()) {
9260 // The base ptr must be the same.
9261 if (!LdPtr.equalBaseIndex(LdBasePtr))
9264 // Check that all other base pointers are the same as this one.
9268 // We found a potential memory operand to merge.
9269 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9272 if (LoadNodes.size() < 2)
9275 // Scan the memory operations on the chain and find the first non-consecutive
9276 // load memory address. These variables hold the index in the store node
9278 unsigned LastConsecutiveLoad = 0;
9279 // This variable refers to the size and not index in the array.
9280 unsigned LastLegalVectorType = 0;
9281 unsigned LastLegalIntegerType = 0;
9282 StartAddress = LoadNodes[0].OffsetFromBase;
9283 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9284 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9285 // All loads much share the same chain.
9286 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9289 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9290 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9292 LastConsecutiveLoad = i;
9294 // Find a legal type for the vector store.
9295 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9296 if (TLI.isTypeLegal(StoreTy))
9297 LastLegalVectorType = i + 1;
9299 // Find a legal type for the integer store.
9300 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9301 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9302 if (TLI.isTypeLegal(StoreTy))
9303 LastLegalIntegerType = i + 1;
9304 // Or check whether a truncstore and extload is legal.
9305 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9306 TargetLowering::TypePromoteInteger) {
9307 EVT LegalizedStoredValueTy =
9308 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9309 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9310 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9311 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9312 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9313 LastLegalIntegerType = i+1;
9317 // Only use vector types if the vector type is larger than the integer type.
9318 // If they are the same, use integers.
9319 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9320 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9322 // We add +1 here because the LastXXX variables refer to location while
9323 // the NumElem refers to array/index size.
9324 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9325 NumElem = std::min(LastLegalType, NumElem);
9330 // The earliest Node in the DAG.
9331 unsigned EarliestNodeUsed = 0;
9332 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9333 for (unsigned i=1; i<NumElem; ++i) {
9334 // Find a chain for the new wide-store operand. Notice that some
9335 // of the store nodes that we found may not be selected for inclusion
9336 // in the wide store. The chain we use needs to be the chain of the
9337 // earliest store node which is *used* and replaced by the wide store.
9338 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9339 EarliestNodeUsed = i;
9342 // Find if it is better to use vectors or integers to load and store
9346 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9348 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9349 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9352 SDLoc LoadDL(LoadNodes[0].MemNode);
9353 SDLoc StoreDL(StoreNodes[0].MemNode);
9355 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9356 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9357 FirstLoad->getChain(),
9358 FirstLoad->getBasePtr(),
9359 FirstLoad->getPointerInfo(),
9360 false, false, false,
9361 FirstLoad->getAlignment());
9363 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9364 FirstInChain->getBasePtr(),
9365 FirstInChain->getPointerInfo(), false, false,
9366 FirstInChain->getAlignment());
9368 // Replace one of the loads with the new load.
9369 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9370 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9371 SDValue(NewLoad.getNode(), 1));
9373 // Remove the rest of the load chains.
9374 for (unsigned i = 1; i < NumElem ; ++i) {
9375 // Replace all chain users of the old load nodes with the chain of the new
9377 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9378 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9381 // Replace the first store with the new store.
9382 CombineTo(EarliestOp, NewStore);
9383 // Erase all other stores.
9384 for (unsigned i = 0; i < NumElem ; ++i) {
9385 // Remove all Store nodes.
9386 if (StoreNodes[i].MemNode == EarliestOp)
9388 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9389 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9390 removeFromWorkList(St);
9397 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9398 StoreSDNode *ST = cast<StoreSDNode>(N);
9399 SDValue Chain = ST->getChain();
9400 SDValue Value = ST->getValue();
9401 SDValue Ptr = ST->getBasePtr();
9403 // If this is a store of a bit convert, store the input value if the
9404 // resultant store does not need a higher alignment than the original.
9405 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9406 ST->isUnindexed()) {
9407 unsigned OrigAlign = ST->getAlignment();
9408 EVT SVT = Value.getOperand(0).getValueType();
9409 unsigned Align = TLI.getDataLayout()->
9410 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9411 if (Align <= OrigAlign &&
9412 ((!LegalOperations && !ST->isVolatile()) ||
9413 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9414 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9415 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9416 ST->isNonTemporal(), OrigAlign,
9420 // Turn 'store undef, Ptr' -> nothing.
9421 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9424 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9425 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9426 // NOTE: If the original store is volatile, this transform must not increase
9427 // the number of stores. For example, on x86-32 an f64 can be stored in one
9428 // processor operation but an i64 (which is not legal) requires two. So the
9429 // transform should not be done in this case.
9430 if (Value.getOpcode() != ISD::TargetConstantFP) {
9432 switch (CFP->getSimpleValueType(0).SimpleTy) {
9433 default: llvm_unreachable("Unknown FP type");
9434 case MVT::f16: // We don't do this for these yet.
9440 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9441 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9442 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9443 bitcastToAPInt().getZExtValue(), MVT::i32);
9444 return DAG.getStore(Chain, SDLoc(N), Tmp,
9445 Ptr, ST->getMemOperand());
9449 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9450 !ST->isVolatile()) ||
9451 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9452 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9453 getZExtValue(), MVT::i64);
9454 return DAG.getStore(Chain, SDLoc(N), Tmp,
9455 Ptr, ST->getMemOperand());
9458 if (!ST->isVolatile() &&
9459 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9460 // Many FP stores are not made apparent until after legalize, e.g. for
9461 // argument passing. Since this is so common, custom legalize the
9462 // 64-bit integer store into two 32-bit stores.
9463 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9464 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9465 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9466 if (TLI.isBigEndian()) std::swap(Lo, Hi);
9468 unsigned Alignment = ST->getAlignment();
9469 bool isVolatile = ST->isVolatile();
9470 bool isNonTemporal = ST->isNonTemporal();
9471 const MDNode *TBAAInfo = ST->getTBAAInfo();
9473 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9474 Ptr, ST->getPointerInfo(),
9475 isVolatile, isNonTemporal,
9476 ST->getAlignment(), TBAAInfo);
9477 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9478 DAG.getConstant(4, Ptr.getValueType()));
9479 Alignment = MinAlign(Alignment, 4U);
9480 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9481 Ptr, ST->getPointerInfo().getWithOffset(4),
9482 isVolatile, isNonTemporal,
9483 Alignment, TBAAInfo);
9484 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9493 // Try to infer better alignment information than the store already has.
9494 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9495 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9496 if (Align > ST->getAlignment())
9497 return DAG.getTruncStore(Chain, SDLoc(N), Value,
9498 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9499 ST->isVolatile(), ST->isNonTemporal(), Align,
9504 // Try transforming a pair floating point load / store ops to integer
9505 // load / store ops.
9506 SDValue NewST = TransformFPLoadStorePair(N);
9507 if (NewST.getNode())
9510 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9511 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9513 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9514 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9517 if (UseAA && ST->isUnindexed()) {
9518 // Walk up chain skipping non-aliasing memory nodes.
9519 SDValue BetterChain = FindBetterChain(N, Chain);
9521 // If there is a better chain.
9522 if (Chain != BetterChain) {
9525 // Replace the chain to avoid dependency.
9526 if (ST->isTruncatingStore()) {
9527 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9528 ST->getMemoryVT(), ST->getMemOperand());
9530 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9531 ST->getMemOperand());
9534 // Create token to keep both nodes around.
9535 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9536 MVT::Other, Chain, ReplStore);
9538 // Make sure the new and old chains are cleaned up.
9539 AddToWorkList(Token.getNode());
9541 // Don't add users to work list.
9542 return CombineTo(N, Token, false);
9546 // Try transforming N to an indexed store.
9547 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9548 return SDValue(N, 0);
9550 // FIXME: is there such a thing as a truncating indexed store?
9551 if (ST->isTruncatingStore() && ST->isUnindexed() &&
9552 Value.getValueType().isInteger()) {
9553 // See if we can simplify the input to this truncstore with knowledge that
9554 // only the low bits are being used. For example:
9555 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
9557 GetDemandedBits(Value,
9558 APInt::getLowBitsSet(
9559 Value.getValueType().getScalarType().getSizeInBits(),
9560 ST->getMemoryVT().getScalarType().getSizeInBits()));
9561 AddToWorkList(Value.getNode());
9562 if (Shorter.getNode())
9563 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9564 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9566 // Otherwise, see if we can simplify the operation with
9567 // SimplifyDemandedBits, which only works if the value has a single use.
9568 if (SimplifyDemandedBits(Value,
9569 APInt::getLowBitsSet(
9570 Value.getValueType().getScalarType().getSizeInBits(),
9571 ST->getMemoryVT().getScalarType().getSizeInBits())))
9572 return SDValue(N, 0);
9575 // If this is a load followed by a store to the same location, then the store
9577 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9578 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9579 ST->isUnindexed() && !ST->isVolatile() &&
9580 // There can't be any side effects between the load and store, such as
9582 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9583 // The store is dead, remove it.
9588 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9589 // truncating store. We can do this even if this is already a truncstore.
9590 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9591 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9592 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9593 ST->getMemoryVT())) {
9594 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9595 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9598 // Only perform this optimization before the types are legal, because we
9599 // don't want to perform this optimization on every DAGCombine invocation.
9601 bool EverChanged = false;
9604 // There can be multiple store sequences on the same chain.
9605 // Keep trying to merge store sequences until we are unable to do so
9606 // or until we merge the last store on the chain.
9607 bool Changed = MergeConsecutiveStores(ST);
9608 EverChanged |= Changed;
9609 if (!Changed) break;
9610 } while (ST->getOpcode() != ISD::DELETED_NODE);
9613 return SDValue(N, 0);
9616 return ReduceLoadOpStoreWidth(N);
9619 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9620 SDValue InVec = N->getOperand(0);
9621 SDValue InVal = N->getOperand(1);
9622 SDValue EltNo = N->getOperand(2);
9625 // If the inserted element is an UNDEF, just use the input vector.
9626 if (InVal.getOpcode() == ISD::UNDEF)
9629 EVT VT = InVec.getValueType();
9631 // If we can't generate a legal BUILD_VECTOR, exit
9632 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9635 // Check that we know which element is being inserted
9636 if (!isa<ConstantSDNode>(EltNo))
9638 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9640 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9641 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9643 SmallVector<SDValue, 8> Ops;
9644 // Do not combine these two vectors if the output vector will not replace
9645 // the input vector.
9646 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9647 Ops.append(InVec.getNode()->op_begin(),
9648 InVec.getNode()->op_end());
9649 } else if (InVec.getOpcode() == ISD::UNDEF) {
9650 unsigned NElts = VT.getVectorNumElements();
9651 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9656 // Insert the element
9657 if (Elt < Ops.size()) {
9658 // All the operands of BUILD_VECTOR must have the same type;
9659 // we enforce that here.
9660 EVT OpVT = Ops[0].getValueType();
9661 if (InVal.getValueType() != OpVT)
9662 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9663 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9664 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9668 // Return the new vector
9669 return DAG.getNode(ISD::BUILD_VECTOR, dl,
9670 VT, &Ops[0], Ops.size());
9673 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9674 // (vextract (scalar_to_vector val, 0) -> val
9675 SDValue InVec = N->getOperand(0);
9676 EVT VT = InVec.getValueType();
9677 EVT NVT = N->getValueType(0);
9679 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9680 // Check if the result type doesn't match the inserted element type. A
9681 // SCALAR_TO_VECTOR may truncate the inserted element and the
9682 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9683 SDValue InOp = InVec.getOperand(0);
9684 if (InOp.getValueType() != NVT) {
9685 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9686 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9691 SDValue EltNo = N->getOperand(1);
9692 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9694 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9695 // We only perform this optimization before the op legalization phase because
9696 // we may introduce new vector instructions which are not backed by TD
9697 // patterns. For example on AVX, extracting elements from a wide vector
9698 // without using extract_subvector. However, if we can find an underlying
9699 // scalar value, then we can always use that.
9700 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9702 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9703 int NumElem = VT.getVectorNumElements();
9704 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9705 // Find the new index to extract from.
9706 int OrigElt = SVOp->getMaskElt(Elt);
9708 // Extracting an undef index is undef.
9710 return DAG.getUNDEF(NVT);
9712 // Select the right vector half to extract from.
9714 if (OrigElt < NumElem) {
9715 SVInVec = InVec->getOperand(0);
9717 SVInVec = InVec->getOperand(1);
9721 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9722 SDValue InOp = SVInVec.getOperand(OrigElt);
9723 if (InOp.getValueType() != NVT) {
9724 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9725 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9731 // FIXME: We should handle recursing on other vector shuffles and
9732 // scalar_to_vector here as well.
9734 if (!LegalOperations) {
9735 EVT IndexTy = TLI.getVectorIdxTy();
9736 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9737 SVInVec, DAG.getConstant(OrigElt, IndexTy));
9741 // Perform only after legalization to ensure build_vector / vector_shuffle
9742 // optimizations have already been done.
9743 if (!LegalOperations) return SDValue();
9745 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9746 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9747 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9750 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9751 bool NewLoad = false;
9752 bool BCNumEltsChanged = false;
9753 EVT ExtVT = VT.getVectorElementType();
9756 // If the result of load has to be truncated, then it's not necessarily
9758 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9761 if (InVec.getOpcode() == ISD::BITCAST) {
9762 // Don't duplicate a load with other uses.
9763 if (!InVec.hasOneUse())
9766 EVT BCVT = InVec.getOperand(0).getValueType();
9767 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9769 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9770 BCNumEltsChanged = true;
9771 InVec = InVec.getOperand(0);
9772 ExtVT = BCVT.getVectorElementType();
9776 LoadSDNode *LN0 = nullptr;
9777 const ShuffleVectorSDNode *SVN = nullptr;
9778 if (ISD::isNormalLoad(InVec.getNode())) {
9779 LN0 = cast<LoadSDNode>(InVec);
9780 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9781 InVec.getOperand(0).getValueType() == ExtVT &&
9782 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9783 // Don't duplicate a load with other uses.
9784 if (!InVec.hasOneUse())
9787 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9788 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9789 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9791 // (load $addr+1*size)
9793 // Don't duplicate a load with other uses.
9794 if (!InVec.hasOneUse())
9797 // If the bit convert changed the number of elements, it is unsafe
9798 // to examine the mask.
9799 if (BCNumEltsChanged)
9802 // Select the input vector, guarding against out of range extract vector.
9803 unsigned NumElems = VT.getVectorNumElements();
9804 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9805 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9807 if (InVec.getOpcode() == ISD::BITCAST) {
9808 // Don't duplicate a load with other uses.
9809 if (!InVec.hasOneUse())
9812 InVec = InVec.getOperand(0);
9814 if (ISD::isNormalLoad(InVec.getNode())) {
9815 LN0 = cast<LoadSDNode>(InVec);
9816 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9820 // Make sure we found a non-volatile load and the extractelement is
9822 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9825 // If Idx was -1 above, Elt is going to be -1, so just return undef.
9827 return DAG.getUNDEF(LVT);
9829 unsigned Align = LN0->getAlignment();
9831 // Check the resultant load doesn't need a higher alignment than the
9835 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9837 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9843 SDValue NewPtr = LN0->getBasePtr();
9844 unsigned PtrOff = 0;
9847 PtrOff = LVT.getSizeInBits() * Elt / 8;
9848 EVT PtrType = NewPtr.getValueType();
9849 if (TLI.isBigEndian())
9850 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9851 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9852 DAG.getConstant(PtrOff, PtrType));
9855 // The replacement we need to do here is a little tricky: we need to
9856 // replace an extractelement of a load with a load.
9857 // Use ReplaceAllUsesOfValuesWith to do the replacement.
9858 // Note that this replacement assumes that the extractvalue is the only
9859 // use of the load; that's okay because we don't want to perform this
9860 // transformation in other cases anyway.
9863 if (NVT.bitsGT(LVT)) {
9864 // If the result type of vextract is wider than the load, then issue an
9865 // extending load instead.
9866 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9867 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9868 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9869 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9870 LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9871 Align, LN0->getTBAAInfo());
9872 Chain = Load.getValue(1);
9874 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9875 LN0->getPointerInfo().getWithOffset(PtrOff),
9876 LN0->isVolatile(), LN0->isNonTemporal(),
9877 LN0->isInvariant(), Align, LN0->getTBAAInfo());
9878 Chain = Load.getValue(1);
9879 if (NVT.bitsLT(LVT))
9880 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
9882 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
9884 WorkListRemover DeadNodes(*this);
9885 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
9886 SDValue To[] = { Load, Chain };
9887 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9888 // Since we're explcitly calling ReplaceAllUses, add the new node to the
9889 // worklist explicitly as well.
9890 AddToWorkList(Load.getNode());
9891 AddUsersToWorkList(Load.getNode()); // Add users too
9892 // Make sure to revisit this node to clean it up; it will usually be dead.
9894 return SDValue(N, 0);
9900 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
9901 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9902 // We perform this optimization post type-legalization because
9903 // the type-legalizer often scalarizes integer-promoted vectors.
9904 // Performing this optimization before may create bit-casts which
9905 // will be type-legalized to complex code sequences.
9906 // We perform this optimization only before the operation legalizer because we
9907 // may introduce illegal operations.
9908 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9911 unsigned NumInScalars = N->getNumOperands();
9913 EVT VT = N->getValueType(0);
9915 // Check to see if this is a BUILD_VECTOR of a bunch of values
9916 // which come from any_extend or zero_extend nodes. If so, we can create
9917 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
9918 // optimizations. We do not handle sign-extend because we can't fill the sign
9920 EVT SourceType = MVT::Other;
9921 bool AllAnyExt = true;
9923 for (unsigned i = 0; i != NumInScalars; ++i) {
9924 SDValue In = N->getOperand(i);
9925 // Ignore undef inputs.
9926 if (In.getOpcode() == ISD::UNDEF) continue;
9928 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
9929 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9931 // Abort if the element is not an extension.
9932 if (!ZeroExt && !AnyExt) {
9933 SourceType = MVT::Other;
9937 // The input is a ZeroExt or AnyExt. Check the original type.
9938 EVT InTy = In.getOperand(0).getValueType();
9940 // Check that all of the widened source types are the same.
9941 if (SourceType == MVT::Other)
9944 else if (InTy != SourceType) {
9945 // Multiple income types. Abort.
9946 SourceType = MVT::Other;
9950 // Check if all of the extends are ANY_EXTENDs.
9951 AllAnyExt &= AnyExt;
9954 // In order to have valid types, all of the inputs must be extended from the
9955 // same source type and all of the inputs must be any or zero extend.
9956 // Scalar sizes must be a power of two.
9957 EVT OutScalarTy = VT.getScalarType();
9958 bool ValidTypes = SourceType != MVT::Other &&
9959 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9960 isPowerOf2_32(SourceType.getSizeInBits());
9962 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9963 // turn into a single shuffle instruction.
9967 bool isLE = TLI.isLittleEndian();
9968 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
9969 assert(ElemRatio > 1 && "Invalid element size ratio");
9970 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
9971 DAG.getConstant(0, SourceType);
9973 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
9974 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
9976 // Populate the new build_vector
9977 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9978 SDValue Cast = N->getOperand(i);
9979 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
9980 Cast.getOpcode() == ISD::ZERO_EXTEND ||
9981 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
9983 if (Cast.getOpcode() == ISD::UNDEF)
9984 In = DAG.getUNDEF(SourceType);
9986 In = Cast->getOperand(0);
9987 unsigned Index = isLE ? (i * ElemRatio) :
9988 (i * ElemRatio + (ElemRatio - 1));
9990 assert(Index < Ops.size() && "Invalid index");
9994 // The type of the new BUILD_VECTOR node.
9995 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
9996 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
9997 "Invalid vector size");
9998 // Check if the new vector type is legal.
9999 if (!isTypeLegal(VecVT)) return SDValue();
10001 // Make the new BUILD_VECTOR.
10002 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
10004 // The new BUILD_VECTOR node has the potential to be further optimized.
10005 AddToWorkList(BV.getNode());
10006 // Bitcast to the desired type.
10007 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10010 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10011 EVT VT = N->getValueType(0);
10013 unsigned NumInScalars = N->getNumOperands();
10016 EVT SrcVT = MVT::Other;
10017 unsigned Opcode = ISD::DELETED_NODE;
10018 unsigned NumDefs = 0;
10020 for (unsigned i = 0; i != NumInScalars; ++i) {
10021 SDValue In = N->getOperand(i);
10022 unsigned Opc = In.getOpcode();
10024 if (Opc == ISD::UNDEF)
10027 // If all scalar values are floats and converted from integers.
10028 if (Opcode == ISD::DELETED_NODE &&
10029 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10036 EVT InVT = In.getOperand(0).getValueType();
10038 // If all scalar values are typed differently, bail out. It's chosen to
10039 // simplify BUILD_VECTOR of integer types.
10040 if (SrcVT == MVT::Other)
10047 // If the vector has just one element defined, it's not worth to fold it into
10048 // a vectorized one.
10052 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10053 && "Should only handle conversion from integer to float.");
10054 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10056 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10058 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10061 SmallVector<SDValue, 8> Opnds;
10062 for (unsigned i = 0; i != NumInScalars; ++i) {
10063 SDValue In = N->getOperand(i);
10065 if (In.getOpcode() == ISD::UNDEF)
10066 Opnds.push_back(DAG.getUNDEF(SrcVT));
10068 Opnds.push_back(In.getOperand(0));
10070 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
10071 &Opnds[0], Opnds.size());
10072 AddToWorkList(BV.getNode());
10074 return DAG.getNode(Opcode, dl, VT, BV);
10077 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10078 unsigned NumInScalars = N->getNumOperands();
10080 EVT VT = N->getValueType(0);
10082 // A vector built entirely of undefs is undef.
10083 if (ISD::allOperandsUndef(N))
10084 return DAG.getUNDEF(VT);
10086 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10090 V = reduceBuildVecConvertToConvertBuildVec(N);
10094 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10095 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10096 // at most two distinct vectors, turn this into a shuffle node.
10098 // May only combine to shuffle after legalize if shuffle is legal.
10099 if (LegalOperations &&
10100 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10103 SDValue VecIn1, VecIn2;
10104 for (unsigned i = 0; i != NumInScalars; ++i) {
10105 // Ignore undef inputs.
10106 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10108 // If this input is something other than a EXTRACT_VECTOR_ELT with a
10109 // constant index, bail out.
10110 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10111 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10112 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10116 // We allow up to two distinct input vectors.
10117 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10118 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10121 if (!VecIn1.getNode()) {
10122 VecIn1 = ExtractedFromVec;
10123 } else if (!VecIn2.getNode()) {
10124 VecIn2 = ExtractedFromVec;
10126 // Too many inputs.
10127 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10132 // If everything is good, we can make a shuffle operation.
10133 if (VecIn1.getNode()) {
10134 SmallVector<int, 8> Mask;
10135 for (unsigned i = 0; i != NumInScalars; ++i) {
10136 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10137 Mask.push_back(-1);
10141 // If extracting from the first vector, just use the index directly.
10142 SDValue Extract = N->getOperand(i);
10143 SDValue ExtVal = Extract.getOperand(1);
10144 if (Extract.getOperand(0) == VecIn1) {
10145 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10146 if (ExtIndex > VT.getVectorNumElements())
10149 Mask.push_back(ExtIndex);
10153 // Otherwise, use InIdx + VecSize
10154 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10155 Mask.push_back(Idx+NumInScalars);
10158 // We can't generate a shuffle node with mismatched input and output types.
10159 // Attempt to transform a single input vector to the correct type.
10160 if ((VT != VecIn1.getValueType())) {
10161 // We don't support shuffeling between TWO values of different types.
10162 if (VecIn2.getNode())
10165 // We only support widening of vectors which are half the size of the
10166 // output registers. For example XMM->YMM widening on X86 with AVX.
10167 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10170 // If the input vector type has a different base type to the output
10171 // vector type, bail out.
10172 if (VecIn1.getValueType().getVectorElementType() !=
10173 VT.getVectorElementType())
10176 // Widen the input vector by adding undef values.
10177 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10178 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10181 // If VecIn2 is unused then change it to undef.
10182 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10184 // Check that we were able to transform all incoming values to the same
10186 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10187 VecIn1.getValueType() != VT)
10190 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10191 if (!isTypeLegal(VT))
10194 // Return the new VECTOR_SHUFFLE node.
10198 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10204 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10205 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10206 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10207 // inputs come from at most two distinct vectors, turn this into a shuffle
10210 // If we only have one input vector, we don't need to do any concatenation.
10211 if (N->getNumOperands() == 1)
10212 return N->getOperand(0);
10214 // Check if all of the operands are undefs.
10215 EVT VT = N->getValueType(0);
10216 if (ISD::allOperandsUndef(N))
10217 return DAG.getUNDEF(VT);
10219 // Optimize concat_vectors where one of the vectors is undef.
10220 if (N->getNumOperands() == 2 &&
10221 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10222 SDValue In = N->getOperand(0);
10223 assert(In.getValueType().isVector() && "Must concat vectors");
10225 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10226 if (In->getOpcode() == ISD::BITCAST &&
10227 !In->getOperand(0)->getValueType(0).isVector()) {
10228 SDValue Scalar = In->getOperand(0);
10229 EVT SclTy = Scalar->getValueType(0);
10231 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10234 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10235 VT.getSizeInBits() / SclTy.getSizeInBits());
10236 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10239 SDLoc dl = SDLoc(N);
10240 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10241 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10245 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10246 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10247 if (N->getNumOperands() == 2 &&
10248 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10249 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10250 EVT VT = N->getValueType(0);
10251 SDValue N0 = N->getOperand(0);
10252 SDValue N1 = N->getOperand(1);
10253 SmallVector<SDValue, 8> Opnds;
10254 unsigned BuildVecNumElts = N0.getNumOperands();
10256 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10257 Opnds.push_back(N0.getOperand(i));
10258 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10259 Opnds.push_back(N1.getOperand(i));
10261 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
10265 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10266 // nodes often generate nop CONCAT_VECTOR nodes.
10267 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10268 // place the incoming vectors at the exact same location.
10269 SDValue SingleSource = SDValue();
10270 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10272 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10273 SDValue Op = N->getOperand(i);
10275 if (Op.getOpcode() == ISD::UNDEF)
10278 // Check if this is the identity extract:
10279 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10282 // Find the single incoming vector for the extract_subvector.
10283 if (SingleSource.getNode()) {
10284 if (Op.getOperand(0) != SingleSource)
10287 SingleSource = Op.getOperand(0);
10289 // Check the source type is the same as the type of the result.
10290 // If not, this concat may extend the vector, so we can not
10291 // optimize it away.
10292 if (SingleSource.getValueType() != N->getValueType(0))
10296 unsigned IdentityIndex = i * PartNumElem;
10297 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10298 // The extract index must be constant.
10302 // Check that we are reading from the identity index.
10303 if (CS->getZExtValue() != IdentityIndex)
10307 if (SingleSource.getNode())
10308 return SingleSource;
10313 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10314 EVT NVT = N->getValueType(0);
10315 SDValue V = N->getOperand(0);
10317 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10319 // (extract_subvec (concat V1, V2, ...), i)
10322 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10324 if (V->getOperand(0).getValueType() != NVT)
10326 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10327 unsigned NumElems = NVT.getVectorNumElements();
10328 assert((Idx % NumElems) == 0 &&
10329 "IDX in concat is not a multiple of the result vector length.");
10330 return V->getOperand(Idx / NumElems);
10334 if (V->getOpcode() == ISD::BITCAST)
10335 V = V.getOperand(0);
10337 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10339 // Handle only simple case where vector being inserted and vector
10340 // being extracted are of same type, and are half size of larger vectors.
10341 EVT BigVT = V->getOperand(0).getValueType();
10342 EVT SmallVT = V->getOperand(1).getValueType();
10343 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10346 // Only handle cases where both indexes are constants with the same type.
10347 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10348 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10350 if (InsIdx && ExtIdx &&
10351 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10352 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10354 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10356 // indices are equal or bit offsets are equal => V1
10357 // otherwise => (extract_subvec V1, ExtIdx)
10358 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10359 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10360 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10361 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10362 DAG.getNode(ISD::BITCAST, dl,
10363 N->getOperand(0).getValueType(),
10364 V->getOperand(0)), N->getOperand(1));
10371 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10372 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10373 EVT VT = N->getValueType(0);
10374 unsigned NumElts = VT.getVectorNumElements();
10376 SDValue N0 = N->getOperand(0);
10377 SDValue N1 = N->getOperand(1);
10378 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10380 SmallVector<SDValue, 4> Ops;
10381 EVT ConcatVT = N0.getOperand(0).getValueType();
10382 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10383 unsigned NumConcats = NumElts / NumElemsPerConcat;
10385 // Look at every vector that's inserted. We're looking for exact
10386 // subvector-sized copies from a concatenated vector
10387 for (unsigned I = 0; I != NumConcats; ++I) {
10388 // Make sure we're dealing with a copy.
10389 unsigned Begin = I * NumElemsPerConcat;
10390 bool AllUndef = true, NoUndef = true;
10391 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10392 if (SVN->getMaskElt(J) >= 0)
10399 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10402 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10403 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10406 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10407 if (FirstElt < N0.getNumOperands())
10408 Ops.push_back(N0.getOperand(FirstElt));
10410 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10412 } else if (AllUndef) {
10413 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10414 } else { // Mixed with general masks and undefs, can't do optimization.
10419 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
10423 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10424 EVT VT = N->getValueType(0);
10425 unsigned NumElts = VT.getVectorNumElements();
10427 SDValue N0 = N->getOperand(0);
10428 SDValue N1 = N->getOperand(1);
10430 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10432 // Canonicalize shuffle undef, undef -> undef
10433 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10434 return DAG.getUNDEF(VT);
10436 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10438 // Canonicalize shuffle v, v -> v, undef
10440 SmallVector<int, 8> NewMask;
10441 for (unsigned i = 0; i != NumElts; ++i) {
10442 int Idx = SVN->getMaskElt(i);
10443 if (Idx >= (int)NumElts) Idx -= NumElts;
10444 NewMask.push_back(Idx);
10446 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10450 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10451 if (N0.getOpcode() == ISD::UNDEF) {
10452 SmallVector<int, 8> NewMask;
10453 for (unsigned i = 0; i != NumElts; ++i) {
10454 int Idx = SVN->getMaskElt(i);
10456 if (Idx >= (int)NumElts)
10459 Idx = -1; // remove reference to lhs
10461 NewMask.push_back(Idx);
10463 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10467 // Remove references to rhs if it is undef
10468 if (N1.getOpcode() == ISD::UNDEF) {
10469 bool Changed = false;
10470 SmallVector<int, 8> NewMask;
10471 for (unsigned i = 0; i != NumElts; ++i) {
10472 int Idx = SVN->getMaskElt(i);
10473 if (Idx >= (int)NumElts) {
10477 NewMask.push_back(Idx);
10480 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10483 // If it is a splat, check if the argument vector is another splat or a
10484 // build_vector with all scalar elements the same.
10485 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10486 SDNode *V = N0.getNode();
10488 // If this is a bit convert that changes the element type of the vector but
10489 // not the number of vector elements, look through it. Be careful not to
10490 // look though conversions that change things like v4f32 to v2f64.
10491 if (V->getOpcode() == ISD::BITCAST) {
10492 SDValue ConvInput = V->getOperand(0);
10493 if (ConvInput.getValueType().isVector() &&
10494 ConvInput.getValueType().getVectorNumElements() == NumElts)
10495 V = ConvInput.getNode();
10498 if (V->getOpcode() == ISD::BUILD_VECTOR) {
10499 assert(V->getNumOperands() == NumElts &&
10500 "BUILD_VECTOR has wrong number of operands");
10502 bool AllSame = true;
10503 for (unsigned i = 0; i != NumElts; ++i) {
10504 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10505 Base = V->getOperand(i);
10509 // Splat of <u, u, u, u>, return <u, u, u, u>
10510 if (!Base.getNode())
10512 for (unsigned i = 0; i != NumElts; ++i) {
10513 if (V->getOperand(i) != Base) {
10518 // Splat of <x, x, x, x>, return <x, x, x, x>
10524 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10525 Level < AfterLegalizeVectorOps &&
10526 (N1.getOpcode() == ISD::UNDEF ||
10527 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10528 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10529 SDValue V = partitionShuffleOfConcats(N, DAG);
10535 // If this shuffle node is simply a swizzle of another shuffle node,
10536 // and it reverses the swizzle of the previous shuffle then we can
10537 // optimize shuffle(shuffle(x, undef), undef) -> x.
10538 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10539 N1.getOpcode() == ISD::UNDEF) {
10541 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10543 // Shuffle nodes can only reverse shuffles with a single non-undef value.
10544 if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10547 // The incoming shuffle must be of the same type as the result of the
10548 // current shuffle.
10549 assert(OtherSV->getOperand(0).getValueType() == VT &&
10550 "Shuffle types don't match");
10552 for (unsigned i = 0; i != NumElts; ++i) {
10553 int Idx = SVN->getMaskElt(i);
10554 assert(Idx < (int)NumElts && "Index references undef operand");
10555 // Next, this index comes from the first value, which is the incoming
10556 // shuffle. Adopt the incoming index.
10558 Idx = OtherSV->getMaskElt(Idx);
10560 // The combined shuffle must map each index to itself.
10561 if (Idx >= 0 && (unsigned)Idx != i)
10565 return OtherSV->getOperand(0);
10571 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10572 SDValue N0 = N->getOperand(0);
10573 SDValue N2 = N->getOperand(2);
10575 // If the input vector is a concatenation, and the insert replaces
10576 // one of the halves, we can optimize into a single concat_vectors.
10577 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10578 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10579 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10580 EVT VT = N->getValueType(0);
10582 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10583 // (concat_vectors Z, Y)
10585 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10586 N->getOperand(1), N0.getOperand(1));
10588 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10589 // (concat_vectors X, Z)
10590 if (InsIdx == VT.getVectorNumElements()/2)
10591 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10592 N0.getOperand(0), N->getOperand(1));
10598 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10599 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10600 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10601 /// vector_shuffle V, Zero, <0, 4, 2, 4>
10602 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10603 EVT VT = N->getValueType(0);
10605 SDValue LHS = N->getOperand(0);
10606 SDValue RHS = N->getOperand(1);
10607 if (N->getOpcode() == ISD::AND) {
10608 if (RHS.getOpcode() == ISD::BITCAST)
10609 RHS = RHS.getOperand(0);
10610 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10611 SmallVector<int, 8> Indices;
10612 unsigned NumElts = RHS.getNumOperands();
10613 for (unsigned i = 0; i != NumElts; ++i) {
10614 SDValue Elt = RHS.getOperand(i);
10615 if (!isa<ConstantSDNode>(Elt))
10618 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10619 Indices.push_back(i);
10620 else if (cast<ConstantSDNode>(Elt)->isNullValue())
10621 Indices.push_back(NumElts);
10626 // Let's see if the target supports this vector_shuffle.
10627 EVT RVT = RHS.getValueType();
10628 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10631 // Return the new VECTOR_SHUFFLE node.
10632 EVT EltVT = RVT.getVectorElementType();
10633 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10634 DAG.getConstant(0, EltVT));
10635 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10636 RVT, &ZeroOps[0], ZeroOps.size());
10637 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10638 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10639 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10646 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10647 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10648 assert(N->getValueType(0).isVector() &&
10649 "SimplifyVBinOp only works on vectors!");
10651 SDValue LHS = N->getOperand(0);
10652 SDValue RHS = N->getOperand(1);
10653 SDValue Shuffle = XformToShuffleWithZero(N);
10654 if (Shuffle.getNode()) return Shuffle;
10656 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10658 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10659 RHS.getOpcode() == ISD::BUILD_VECTOR) {
10660 // Check if both vectors are constants. If not bail out.
10661 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10662 cast<BuildVectorSDNode>(RHS)->isConstant()))
10665 SmallVector<SDValue, 8> Ops;
10666 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10667 SDValue LHSOp = LHS.getOperand(i);
10668 SDValue RHSOp = RHS.getOperand(i);
10670 // Can't fold divide by zero.
10671 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10672 N->getOpcode() == ISD::FDIV) {
10673 if ((RHSOp.getOpcode() == ISD::Constant &&
10674 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10675 (RHSOp.getOpcode() == ISD::ConstantFP &&
10676 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10680 EVT VT = LHSOp.getValueType();
10681 EVT RVT = RHSOp.getValueType();
10683 // Integer BUILD_VECTOR operands may have types larger than the element
10684 // size (e.g., when the element type is not legal). Prior to type
10685 // legalization, the types may not match between the two BUILD_VECTORS.
10686 // Truncate one of the operands to make them match.
10687 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10688 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10690 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10694 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10696 if (FoldOp.getOpcode() != ISD::UNDEF &&
10697 FoldOp.getOpcode() != ISD::Constant &&
10698 FoldOp.getOpcode() != ISD::ConstantFP)
10700 Ops.push_back(FoldOp);
10701 AddToWorkList(FoldOp.getNode());
10704 if (Ops.size() == LHS.getNumOperands())
10705 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10706 LHS.getValueType(), &Ops[0], Ops.size());
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),
10742 N0.getValueType(), &Ops[0], Ops.size());
10745 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10746 SDValue N1, SDValue N2){
10747 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10749 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
10750 cast<CondCodeSDNode>(N0.getOperand(2))->get());
10752 // If we got a simplified select_cc node back from SimplifySelectCC, then
10753 // break it down into a new SETCC node, and a new SELECT node, and then return
10754 // the SELECT node, since we were called with a SELECT node.
10755 if (SCC.getNode()) {
10756 // Check to see if we got a select_cc back (to turn into setcc/select).
10757 // Otherwise, just return whatever node we got back, like fabs.
10758 if (SCC.getOpcode() == ISD::SELECT_CC) {
10759 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
10761 SCC.getOperand(0), SCC.getOperand(1),
10762 SCC.getOperand(4));
10763 AddToWorkList(SETCC.getNode());
10764 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10765 SCC.getOperand(2), SCC.getOperand(3), SETCC);
10773 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10774 /// are the two values being selected between, see if we can simplify the
10775 /// select. Callers of this should assume that TheSelect is deleted if this
10776 /// returns true. As such, they should return the appropriate thing (e.g. the
10777 /// node) back to the top-level of the DAG combiner loop to avoid it being
10779 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
10782 // Cannot simplify select with vector condition
10783 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10785 // If this is a select from two identical things, try to pull the operation
10786 // through the select.
10787 if (LHS.getOpcode() != RHS.getOpcode() ||
10788 !LHS.hasOneUse() || !RHS.hasOneUse())
10791 // If this is a load and the token chain is identical, replace the select
10792 // of two loads with a load through a select of the address to load from.
10793 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10794 // constants have been dropped into the constant pool.
10795 if (LHS.getOpcode() == ISD::LOAD) {
10796 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10797 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
10799 // Token chains must be identical.
10800 if (LHS.getOperand(0) != RHS.getOperand(0) ||
10801 // Do not let this transformation reduce the number of volatile loads.
10802 LLD->isVolatile() || RLD->isVolatile() ||
10803 // If this is an EXTLOAD, the VT's must match.
10804 LLD->getMemoryVT() != RLD->getMemoryVT() ||
10805 // If this is an EXTLOAD, the kind of extension must match.
10806 (LLD->getExtensionType() != RLD->getExtensionType() &&
10807 // The only exception is if one of the extensions is anyext.
10808 LLD->getExtensionType() != ISD::EXTLOAD &&
10809 RLD->getExtensionType() != ISD::EXTLOAD) ||
10810 // FIXME: this discards src value information. This is
10811 // over-conservative. It would be beneficial to be able to remember
10812 // both potential memory locations. Since we are discarding
10813 // src value info, don't do the transformation if the memory
10814 // locations are not in the default address space.
10815 LLD->getPointerInfo().getAddrSpace() != 0 ||
10816 RLD->getPointerInfo().getAddrSpace() != 0 ||
10817 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10818 LLD->getBasePtr().getValueType()))
10821 // Check that the select condition doesn't reach either load. If so,
10822 // folding this will induce a cycle into the DAG. If not, this is safe to
10823 // xform, so create a select of the addresses.
10825 if (TheSelect->getOpcode() == ISD::SELECT) {
10826 SDNode *CondNode = TheSelect->getOperand(0).getNode();
10827 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10828 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10830 // The loads must not depend on one another.
10831 if (LLD->isPredecessorOf(RLD) ||
10832 RLD->isPredecessorOf(LLD))
10834 Addr = DAG.getSelect(SDLoc(TheSelect),
10835 LLD->getBasePtr().getValueType(),
10836 TheSelect->getOperand(0), LLD->getBasePtr(),
10837 RLD->getBasePtr());
10838 } else { // Otherwise SELECT_CC
10839 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10840 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10842 if ((LLD->hasAnyUseOfValue(1) &&
10843 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
10844 (RLD->hasAnyUseOfValue(1) &&
10845 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
10848 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
10849 LLD->getBasePtr().getValueType(),
10850 TheSelect->getOperand(0),
10851 TheSelect->getOperand(1),
10852 LLD->getBasePtr(), RLD->getBasePtr(),
10853 TheSelect->getOperand(4));
10857 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10858 Load = DAG.getLoad(TheSelect->getValueType(0),
10860 // FIXME: Discards pointer and TBAA info.
10861 LLD->getChain(), Addr, MachinePointerInfo(),
10862 LLD->isVolatile(), LLD->isNonTemporal(),
10863 LLD->isInvariant(), LLD->getAlignment());
10865 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10866 RLD->getExtensionType() : LLD->getExtensionType(),
10868 TheSelect->getValueType(0),
10869 // FIXME: Discards pointer and TBAA info.
10870 LLD->getChain(), Addr, MachinePointerInfo(),
10871 LLD->getMemoryVT(), LLD->isVolatile(),
10872 LLD->isNonTemporal(), LLD->getAlignment());
10875 // Users of the select now use the result of the load.
10876 CombineTo(TheSelect, Load);
10878 // Users of the old loads now use the new load's chain. We know the
10879 // old-load value is dead now.
10880 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10881 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10888 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10889 /// where 'cond' is the comparison specified by CC.
10890 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
10891 SDValue N2, SDValue N3,
10892 ISD::CondCode CC, bool NotExtCompare) {
10893 // (x ? y : y) -> y.
10894 if (N2 == N3) return N2;
10896 EVT VT = N2.getValueType();
10897 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10898 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10899 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
10901 // Determine if the condition we're dealing with is constant
10902 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
10903 N0, N1, CC, DL, false);
10904 if (SCC.getNode()) AddToWorkList(SCC.getNode());
10905 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
10907 // fold select_cc true, x, y -> x
10908 if (SCCC && !SCCC->isNullValue())
10910 // fold select_cc false, x, y -> y
10911 if (SCCC && SCCC->isNullValue())
10914 // Check to see if we can simplify the select into an fabs node
10915 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10916 // Allow either -0.0 or 0.0
10917 if (CFP->getValueAPF().isZero()) {
10918 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10919 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10920 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10921 N2 == N3.getOperand(0))
10922 return DAG.getNode(ISD::FABS, DL, VT, N0);
10924 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10925 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10926 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10927 N2.getOperand(0) == N3)
10928 return DAG.getNode(ISD::FABS, DL, VT, N3);
10932 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10933 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10934 // in it. This is a win when the constant is not otherwise available because
10935 // it replaces two constant pool loads with one. We only do this if the FP
10936 // type is known to be legal, because if it isn't, then we are before legalize
10937 // types an we want the other legalization to happen first (e.g. to avoid
10938 // messing with soft float) and if the ConstantFP is not legal, because if
10939 // it is legal, we may not need to store the FP constant in a constant pool.
10940 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10941 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10942 if (TLI.isTypeLegal(N2.getValueType()) &&
10943 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10944 TargetLowering::Legal &&
10945 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
10946 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
10947 // If both constants have multiple uses, then we won't need to do an
10948 // extra load, they are likely around in registers for other users.
10949 (TV->hasOneUse() || FV->hasOneUse())) {
10950 Constant *Elts[] = {
10951 const_cast<ConstantFP*>(FV->getConstantFPValue()),
10952 const_cast<ConstantFP*>(TV->getConstantFPValue())
10954 Type *FPTy = Elts[0]->getType();
10955 const DataLayout &TD = *TLI.getDataLayout();
10957 // Create a ConstantArray of the two constants.
10958 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
10959 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10960 TD.getPrefTypeAlignment(FPTy));
10961 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10963 // Get the offsets to the 0 and 1 element of the array so that we can
10964 // select between them.
10965 SDValue Zero = DAG.getIntPtrConstant(0);
10966 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
10967 SDValue One = DAG.getIntPtrConstant(EltSize);
10969 SDValue Cond = DAG.getSetCC(DL,
10970 getSetCCResultType(N0.getValueType()),
10972 AddToWorkList(Cond.getNode());
10973 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
10975 AddToWorkList(CstOffset.getNode());
10976 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
10978 AddToWorkList(CPIdx.getNode());
10979 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
10980 MachinePointerInfo::getConstantPool(), false,
10981 false, false, Alignment);
10986 // Check to see if we can perform the "gzip trick", transforming
10987 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
10988 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
10989 (N1C->isNullValue() || // (a < 0) ? b : 0
10990 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
10991 EVT XType = N0.getValueType();
10992 EVT AType = N2.getValueType();
10993 if (XType.bitsGE(AType)) {
10994 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
10995 // single-bit constant.
10996 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
10997 unsigned ShCtV = N2C->getAPIntValue().logBase2();
10998 ShCtV = XType.getSizeInBits()-ShCtV-1;
10999 SDValue ShCt = DAG.getConstant(ShCtV,
11000 getShiftAmountTy(N0.getValueType()));
11001 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11003 AddToWorkList(Shift.getNode());
11005 if (XType.bitsGT(AType)) {
11006 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11007 AddToWorkList(Shift.getNode());
11010 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11013 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11015 DAG.getConstant(XType.getSizeInBits()-1,
11016 getShiftAmountTy(N0.getValueType())));
11017 AddToWorkList(Shift.getNode());
11019 if (XType.bitsGT(AType)) {
11020 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11021 AddToWorkList(Shift.getNode());
11024 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11028 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11029 // where y is has a single bit set.
11030 // A plaintext description would be, we can turn the SELECT_CC into an AND
11031 // when the condition can be materialized as an all-ones register. Any
11032 // single bit-test can be materialized as an all-ones register with
11033 // shift-left and shift-right-arith.
11034 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11035 N0->getValueType(0) == VT &&
11036 N1C && N1C->isNullValue() &&
11037 N2C && N2C->isNullValue()) {
11038 SDValue AndLHS = N0->getOperand(0);
11039 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11040 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11041 // Shift the tested bit over the sign bit.
11042 APInt AndMask = ConstAndRHS->getAPIntValue();
11044 DAG.getConstant(AndMask.countLeadingZeros(),
11045 getShiftAmountTy(AndLHS.getValueType()));
11046 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11048 // Now arithmetic right shift it all the way over, so the result is either
11049 // all-ones, or zero.
11051 DAG.getConstant(AndMask.getBitWidth()-1,
11052 getShiftAmountTy(Shl.getValueType()));
11053 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11055 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11059 // fold select C, 16, 0 -> shl C, 4
11060 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11061 TLI.getBooleanContents(N0.getValueType().isVector()) ==
11062 TargetLowering::ZeroOrOneBooleanContent) {
11064 // If the caller doesn't want us to simplify this into a zext of a compare,
11066 if (NotExtCompare && N2C->getAPIntValue() == 1)
11069 // Get a SetCC of the condition
11070 // NOTE: Don't create a SETCC if it's not legal on this target.
11071 if (!LegalOperations ||
11072 TLI.isOperationLegal(ISD::SETCC,
11073 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11075 // cast from setcc result type to select result type
11077 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11079 if (N2.getValueType().bitsLT(SCC.getValueType()))
11080 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11081 N2.getValueType());
11083 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11084 N2.getValueType(), SCC);
11086 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11087 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11088 N2.getValueType(), SCC);
11091 AddToWorkList(SCC.getNode());
11092 AddToWorkList(Temp.getNode());
11094 if (N2C->getAPIntValue() == 1)
11097 // shl setcc result by log2 n2c
11098 return DAG.getNode(
11099 ISD::SHL, DL, N2.getValueType(), Temp,
11100 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11101 getShiftAmountTy(Temp.getValueType())));
11105 // Check to see if this is the equivalent of setcc
11106 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11107 // otherwise, go ahead with the folds.
11108 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11109 EVT XType = N0.getValueType();
11110 if (!LegalOperations ||
11111 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11112 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11113 if (Res.getValueType() != VT)
11114 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11118 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11119 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11120 (!LegalOperations ||
11121 TLI.isOperationLegal(ISD::CTLZ, XType))) {
11122 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11123 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11124 DAG.getConstant(Log2_32(XType.getSizeInBits()),
11125 getShiftAmountTy(Ctlz.getValueType())));
11127 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11128 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11129 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11130 XType, DAG.getConstant(0, XType), N0);
11131 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11132 return DAG.getNode(ISD::SRL, DL, XType,
11133 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11134 DAG.getConstant(XType.getSizeInBits()-1,
11135 getShiftAmountTy(XType)));
11137 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11138 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11139 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11140 DAG.getConstant(XType.getSizeInBits()-1,
11141 getShiftAmountTy(N0.getValueType())));
11142 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11146 // Check to see if this is an integer abs.
11147 // select_cc setg[te] X, 0, X, -X ->
11148 // select_cc setgt X, -1, X, -X ->
11149 // select_cc setl[te] X, 0, -X, X ->
11150 // select_cc setlt X, 1, -X, X ->
11151 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11153 ConstantSDNode *SubC = nullptr;
11154 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11155 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11156 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11157 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11158 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11159 (N1C->isOne() && CC == ISD::SETLT)) &&
11160 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11161 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11163 EVT XType = N0.getValueType();
11164 if (SubC && SubC->isNullValue() && XType.isInteger()) {
11165 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11167 DAG.getConstant(XType.getSizeInBits()-1,
11168 getShiftAmountTy(N0.getValueType())));
11169 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11171 AddToWorkList(Shift.getNode());
11172 AddToWorkList(Add.getNode());
11173 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11180 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11181 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11182 SDValue N1, ISD::CondCode Cond,
11183 SDLoc DL, bool foldBooleans) {
11184 TargetLowering::DAGCombinerInfo
11185 DagCombineInfo(DAG, Level, false, this);
11186 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11189 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11190 /// return a DAG expression to select that will generate the same value by
11191 /// multiplying by a magic number. See:
11192 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11193 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11194 std::vector<SDNode*> Built;
11195 SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
11197 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
11199 AddToWorkList(*ii);
11203 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
11204 /// return a DAG expression to select that will generate the same value by
11205 /// multiplying by a magic number. See:
11206 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11207 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11208 std::vector<SDNode*> Built;
11209 SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
11211 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
11213 AddToWorkList(*ii);
11217 /// FindBaseOffset - Return true if base is a frame index, which is known not
11218 // to alias with anything but itself. Provides base object and offset as
11220 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11221 const GlobalValue *&GV, const void *&CV) {
11222 // Assume it is a primitive operation.
11223 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11225 // If it's an adding a simple constant then integrate the offset.
11226 if (Base.getOpcode() == ISD::ADD) {
11227 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11228 Base = Base.getOperand(0);
11229 Offset += C->getZExtValue();
11233 // Return the underlying GlobalValue, and update the Offset. Return false
11234 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11235 // by multiple nodes with different offsets.
11236 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11237 GV = G->getGlobal();
11238 Offset += G->getOffset();
11242 // Return the underlying Constant value, and update the Offset. Return false
11243 // for ConstantSDNodes since the same constant pool entry may be represented
11244 // by multiple nodes with different offsets.
11245 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11246 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11247 : (const void *)C->getConstVal();
11248 Offset += C->getOffset();
11251 // If it's any of the following then it can't alias with anything but itself.
11252 return isa<FrameIndexSDNode>(Base);
11255 /// isAlias - Return true if there is any possibility that the two addresses
11257 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11258 // If they are the same then they must be aliases.
11259 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11261 // If they are both volatile then they cannot be reordered.
11262 if (Op0->isVolatile() && Op1->isVolatile()) return true;
11264 // Gather base node and offset information.
11265 SDValue Base1, Base2;
11266 int64_t Offset1, Offset2;
11267 const GlobalValue *GV1, *GV2;
11268 const void *CV1, *CV2;
11269 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11270 Base1, Offset1, GV1, CV1);
11271 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11272 Base2, Offset2, GV2, CV2);
11274 // If they have a same base address then check to see if they overlap.
11275 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11276 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11277 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11279 // It is possible for different frame indices to alias each other, mostly
11280 // when tail call optimization reuses return address slots for arguments.
11281 // To catch this case, look up the actual index of frame indices to compute
11282 // the real alias relationship.
11283 if (isFrameIndex1 && isFrameIndex2) {
11284 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11285 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11286 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11287 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11288 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11291 // Otherwise, if we know what the bases are, and they aren't identical, then
11292 // we know they cannot alias.
11293 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11296 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11297 // compared to the size and offset of the access, we may be able to prove they
11298 // do not alias. This check is conservative for now to catch cases created by
11299 // splitting vector types.
11300 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11301 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11302 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11303 Op1->getMemoryVT().getSizeInBits() >> 3) &&
11304 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11305 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11306 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11308 // There is no overlap between these relatively aligned accesses of similar
11309 // size, return no alias.
11310 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11311 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11315 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11316 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11318 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11319 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11323 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11324 // Use alias analysis information.
11325 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11326 Op1->getSrcValueOffset());
11327 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11328 Op0->getSrcValueOffset() - MinOffset;
11329 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11330 Op1->getSrcValueOffset() - MinOffset;
11331 AliasAnalysis::AliasResult AAResult =
11332 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11334 UseTBAA ? Op0->getTBAAInfo() : nullptr),
11335 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11337 UseTBAA ? Op1->getTBAAInfo() : nullptr));
11338 if (AAResult == AliasAnalysis::NoAlias)
11342 // Otherwise we have to assume they alias.
11346 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11347 /// looking for aliasing nodes and adding them to the Aliases vector.
11348 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11349 SmallVectorImpl<SDValue> &Aliases) {
11350 SmallVector<SDValue, 8> Chains; // List of chains to visit.
11351 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
11353 // Get alias information for node.
11354 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11357 Chains.push_back(OriginalChain);
11358 unsigned Depth = 0;
11360 // Look at each chain and determine if it is an alias. If so, add it to the
11361 // aliases list. If not, then continue up the chain looking for the next
11363 while (!Chains.empty()) {
11364 SDValue Chain = Chains.back();
11367 // For TokenFactor nodes, look at each operand and only continue up the
11368 // chain until we find two aliases. If we've seen two aliases, assume we'll
11369 // find more and revert to original chain since the xform is unlikely to be
11372 // FIXME: The depth check could be made to return the last non-aliasing
11373 // chain we found before we hit a tokenfactor rather than the original
11375 if (Depth > 6 || Aliases.size() == 2) {
11377 Aliases.push_back(OriginalChain);
11381 // Don't bother if we've been before.
11382 if (!Visited.insert(Chain.getNode()))
11385 switch (Chain.getOpcode()) {
11386 case ISD::EntryToken:
11387 // Entry token is ideal chain operand, but handled in FindBetterChain.
11392 // Get alias information for Chain.
11393 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11394 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11396 // If chain is alias then stop here.
11397 if (!(IsLoad && IsOpLoad) &&
11398 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11399 Aliases.push_back(Chain);
11401 // Look further up the chain.
11402 Chains.push_back(Chain.getOperand(0));
11408 case ISD::TokenFactor:
11409 // We have to check each of the operands of the token factor for "small"
11410 // token factors, so we queue them up. Adding the operands to the queue
11411 // (stack) in reverse order maintains the original order and increases the
11412 // likelihood that getNode will find a matching token factor (CSE.)
11413 if (Chain.getNumOperands() > 16) {
11414 Aliases.push_back(Chain);
11417 for (unsigned n = Chain.getNumOperands(); n;)
11418 Chains.push_back(Chain.getOperand(--n));
11423 // For all other instructions we will just have to take what we can get.
11424 Aliases.push_back(Chain);
11429 // We need to be careful here to also search for aliases through the
11430 // value operand of a store, etc. Consider the following situation:
11432 // L1 = load Token1, %52
11433 // S1 = store Token1, L1, %51
11434 // L2 = load Token1, %52+8
11435 // S2 = store Token1, L2, %51+8
11436 // Token2 = Token(S1, S2)
11437 // L3 = load Token2, %53
11438 // S3 = store Token2, L3, %52
11439 // L4 = load Token2, %53+8
11440 // S4 = store Token2, L4, %52+8
11441 // If we search for aliases of S3 (which loads address %52), and we look
11442 // only through the chain, then we'll miss the trivial dependence on L1
11443 // (which also loads from %52). We then might change all loads and
11444 // stores to use Token1 as their chain operand, which could result in
11445 // copying %53 into %52 before copying %52 into %51 (which should
11448 // The problem is, however, that searching for such data dependencies
11449 // can become expensive, and the cost is not directly related to the
11450 // chain depth. Instead, we'll rule out such configurations here by
11451 // insisting that we've visited all chain users (except for users
11452 // of the original chain, which is not necessary). When doing this,
11453 // we need to look through nodes we don't care about (otherwise, things
11454 // like register copies will interfere with trivial cases).
11456 SmallVector<const SDNode *, 16> Worklist;
11457 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11458 IE = Visited.end(); I != IE; ++I)
11459 if (*I != OriginalChain.getNode())
11460 Worklist.push_back(*I);
11462 while (!Worklist.empty()) {
11463 const SDNode *M = Worklist.pop_back_val();
11465 // We have already visited M, and want to make sure we've visited any uses
11466 // of M that we care about. For uses that we've not visisted, and don't
11467 // care about, queue them to the worklist.
11469 for (SDNode::use_iterator UI = M->use_begin(),
11470 UIE = M->use_end(); UI != UIE; ++UI)
11471 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11472 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11473 // We've not visited this use, and we care about it (it could have an
11474 // ordering dependency with the original node).
11476 Aliases.push_back(OriginalChain);
11480 // We've not visited this use, but we don't care about it. Mark it as
11481 // visited and enqueue it to the worklist.
11482 Worklist.push_back(*UI);
11487 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11488 /// for a better chain (aliasing node.)
11489 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11490 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
11492 // Accumulate all the aliases to this node.
11493 GatherAllAliases(N, OldChain, Aliases);
11495 // If no operands then chain to entry token.
11496 if (Aliases.size() == 0)
11497 return DAG.getEntryNode();
11499 // If a single operand then chain to it. We don't need to revisit it.
11500 if (Aliases.size() == 1)
11503 // Construct a custom tailored token factor.
11504 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
11505 &Aliases[0], Aliases.size());
11508 // SelectionDAG::Combine - This is the entry point for the file.
11510 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11511 CodeGenOpt::Level OptLevel) {
11512 /// run - This is the main entry point to this class.
11514 DAGCombiner(*this, AA, OptLevel).Run(Level);