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(),
1989 const APInt *Divisor = nullptr;
1991 Divisor = &N1C->getAPIntValue();
1992 } else if (N1.getValueType().isVector() &&
1993 N1->getOpcode() == ISD::BUILD_VECTOR) {
1994 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N->getOperand(1));
1995 if (ConstantSDNode *C = BV->getConstantSplatValue())
1996 Divisor = &C->getAPIntValue();
1999 // fold (sdiv X, pow2) -> simple ops after legalize
2000 if (Divisor && !!*Divisor &&
2001 (Divisor->isPowerOf2() || (-*Divisor).isPowerOf2())) {
2002 // If dividing by powers of two is cheap, then don't perform the following
2004 if (TLI.isPow2DivCheap())
2007 unsigned lg2 = Divisor->countTrailingZeros();
2009 // Splat the sign bit into the register
2011 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2012 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2013 getShiftAmountTy(N0.getValueType())));
2014 AddToWorkList(SGN.getNode());
2016 // Add (N0 < 0) ? abs2 - 1 : 0;
2018 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2019 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2020 getShiftAmountTy(SGN.getValueType())));
2021 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2022 AddToWorkList(SRL.getNode());
2023 AddToWorkList(ADD.getNode()); // Divide by pow2
2024 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2025 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2027 // If we're dividing by a positive value, we're done. Otherwise, we must
2028 // negate the result.
2029 if (Divisor->isNonNegative())
2032 AddToWorkList(SRA.getNode());
2033 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2036 // if integer divide is expensive and we satisfy the requirements, emit an
2037 // alternate sequence.
2038 if ((N1C || N1->getOpcode() == ISD::BUILD_VECTOR) && !TLI.isIntDivCheap()) {
2039 SDValue Op = BuildSDIV(N);
2040 if (Op.getNode()) return Op;
2044 if (N0.getOpcode() == ISD::UNDEF)
2045 return DAG.getConstant(0, VT);
2046 // X / undef -> undef
2047 if (N1.getOpcode() == ISD::UNDEF)
2053 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2054 SDValue N0 = N->getOperand(0);
2055 SDValue N1 = N->getOperand(1);
2056 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
2057 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2058 EVT VT = N->getValueType(0);
2061 if (VT.isVector()) {
2062 SDValue FoldedVOp = SimplifyVBinOp(N);
2063 if (FoldedVOp.getNode()) return FoldedVOp;
2066 // fold (udiv c1, c2) -> c1/c2
2067 if (N0C && N1C && !N1C->isNullValue())
2068 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2069 // fold (udiv x, (1 << c)) -> x >>u c
2070 if (N1C && N1C->getAPIntValue().isPowerOf2())
2071 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2072 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2073 getShiftAmountTy(N0.getValueType())));
2074 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2075 if (N1.getOpcode() == ISD::SHL) {
2076 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2077 if (SHC->getAPIntValue().isPowerOf2()) {
2078 EVT ADDVT = N1.getOperand(1).getValueType();
2079 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2081 DAG.getConstant(SHC->getAPIntValue()
2084 AddToWorkList(Add.getNode());
2085 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2089 // fold (udiv x, c) -> alternate
2090 if ((N1C || N1->getOpcode() == ISD::BUILD_VECTOR) && !TLI.isIntDivCheap()) {
2091 SDValue Op = BuildUDIV(N);
2092 if (Op.getNode()) return Op;
2096 if (N0.getOpcode() == ISD::UNDEF)
2097 return DAG.getConstant(0, VT);
2098 // X / undef -> undef
2099 if (N1.getOpcode() == ISD::UNDEF)
2105 SDValue DAGCombiner::visitSREM(SDNode *N) {
2106 SDValue N0 = N->getOperand(0);
2107 SDValue N1 = N->getOperand(1);
2108 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2109 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2110 EVT VT = N->getValueType(0);
2112 // fold (srem c1, c2) -> c1%c2
2113 if (N0C && N1C && !N1C->isNullValue())
2114 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2115 // If we know the sign bits of both operands are zero, strength reduce to a
2116 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2117 if (!VT.isVector()) {
2118 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2119 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2122 // If X/C can be simplified by the division-by-constant logic, lower
2123 // X%C to the equivalent of X-X/C*C.
2124 if (N1C && !N1C->isNullValue()) {
2125 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2126 AddToWorkList(Div.getNode());
2127 SDValue OptimizedDiv = combine(Div.getNode());
2128 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2129 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2131 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2132 AddToWorkList(Mul.getNode());
2138 if (N0.getOpcode() == ISD::UNDEF)
2139 return DAG.getConstant(0, VT);
2140 // X % undef -> undef
2141 if (N1.getOpcode() == ISD::UNDEF)
2147 SDValue DAGCombiner::visitUREM(SDNode *N) {
2148 SDValue N0 = N->getOperand(0);
2149 SDValue N1 = N->getOperand(1);
2150 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2151 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2152 EVT VT = N->getValueType(0);
2154 // fold (urem c1, c2) -> c1%c2
2155 if (N0C && N1C && !N1C->isNullValue())
2156 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2157 // fold (urem x, pow2) -> (and x, pow2-1)
2158 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2159 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2160 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2161 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2162 if (N1.getOpcode() == ISD::SHL) {
2163 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2164 if (SHC->getAPIntValue().isPowerOf2()) {
2166 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2167 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2169 AddToWorkList(Add.getNode());
2170 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2175 // If X/C can be simplified by the division-by-constant logic, lower
2176 // X%C to the equivalent of X-X/C*C.
2177 if (N1C && !N1C->isNullValue()) {
2178 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2179 AddToWorkList(Div.getNode());
2180 SDValue OptimizedDiv = combine(Div.getNode());
2181 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2182 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2184 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2185 AddToWorkList(Mul.getNode());
2191 if (N0.getOpcode() == ISD::UNDEF)
2192 return DAG.getConstant(0, VT);
2193 // X % undef -> undef
2194 if (N1.getOpcode() == ISD::UNDEF)
2200 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2201 SDValue N0 = N->getOperand(0);
2202 SDValue N1 = N->getOperand(1);
2203 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2204 EVT VT = N->getValueType(0);
2207 // fold (mulhs x, 0) -> 0
2208 if (N1C && N1C->isNullValue())
2210 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2211 if (N1C && N1C->getAPIntValue() == 1)
2212 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2213 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2214 getShiftAmountTy(N0.getValueType())));
2215 // fold (mulhs x, undef) -> 0
2216 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2217 return DAG.getConstant(0, VT);
2219 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2221 if (VT.isSimple() && !VT.isVector()) {
2222 MVT Simple = VT.getSimpleVT();
2223 unsigned SimpleSize = Simple.getSizeInBits();
2224 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2225 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2226 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2227 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2228 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2229 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2230 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2231 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2238 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2239 SDValue N0 = N->getOperand(0);
2240 SDValue N1 = N->getOperand(1);
2241 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2242 EVT VT = N->getValueType(0);
2245 // fold (mulhu x, 0) -> 0
2246 if (N1C && N1C->isNullValue())
2248 // fold (mulhu x, 1) -> 0
2249 if (N1C && N1C->getAPIntValue() == 1)
2250 return DAG.getConstant(0, N0.getValueType());
2251 // fold (mulhu x, undef) -> 0
2252 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2253 return DAG.getConstant(0, VT);
2255 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2257 if (VT.isSimple() && !VT.isVector()) {
2258 MVT Simple = VT.getSimpleVT();
2259 unsigned SimpleSize = Simple.getSizeInBits();
2260 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2261 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2262 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2263 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2264 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2265 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2266 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2267 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2274 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2275 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2276 /// that are being performed. Return true if a simplification was made.
2278 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2280 // If the high half is not needed, just compute the low half.
2281 bool HiExists = N->hasAnyUseOfValue(1);
2283 (!LegalOperations ||
2284 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2285 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2286 N->op_begin(), N->getNumOperands());
2287 return CombineTo(N, Res, Res);
2290 // If the low half is not needed, just compute the high half.
2291 bool LoExists = N->hasAnyUseOfValue(0);
2293 (!LegalOperations ||
2294 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2295 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2296 N->op_begin(), N->getNumOperands());
2297 return CombineTo(N, Res, Res);
2300 // If both halves are used, return as it is.
2301 if (LoExists && HiExists)
2304 // If the two computed results can be simplified separately, separate them.
2306 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2307 N->op_begin(), N->getNumOperands());
2308 AddToWorkList(Lo.getNode());
2309 SDValue LoOpt = combine(Lo.getNode());
2310 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2311 (!LegalOperations ||
2312 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2313 return CombineTo(N, LoOpt, LoOpt);
2317 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2318 N->op_begin(), N->getNumOperands());
2319 AddToWorkList(Hi.getNode());
2320 SDValue HiOpt = combine(Hi.getNode());
2321 if (HiOpt.getNode() && HiOpt != Hi &&
2322 (!LegalOperations ||
2323 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2324 return CombineTo(N, HiOpt, HiOpt);
2330 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2331 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2332 if (Res.getNode()) return Res;
2334 EVT VT = N->getValueType(0);
2337 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2339 if (VT.isSimple() && !VT.isVector()) {
2340 MVT Simple = VT.getSimpleVT();
2341 unsigned SimpleSize = Simple.getSizeInBits();
2342 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2343 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2344 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2345 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2346 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2347 // Compute the high part as N1.
2348 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2349 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2350 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2351 // Compute the low part as N0.
2352 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2353 return CombineTo(N, Lo, Hi);
2360 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2361 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2362 if (Res.getNode()) return Res;
2364 EVT VT = N->getValueType(0);
2367 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2369 if (VT.isSimple() && !VT.isVector()) {
2370 MVT Simple = VT.getSimpleVT();
2371 unsigned SimpleSize = Simple.getSizeInBits();
2372 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2373 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2374 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2375 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2376 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2377 // Compute the high part as N1.
2378 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2379 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2380 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2381 // Compute the low part as N0.
2382 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2383 return CombineTo(N, Lo, Hi);
2390 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2391 // (smulo x, 2) -> (saddo x, x)
2392 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2393 if (C2->getAPIntValue() == 2)
2394 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2395 N->getOperand(0), N->getOperand(0));
2400 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2401 // (umulo x, 2) -> (uaddo x, x)
2402 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2403 if (C2->getAPIntValue() == 2)
2404 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2405 N->getOperand(0), N->getOperand(0));
2410 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2411 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2412 if (Res.getNode()) return Res;
2417 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2418 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2419 if (Res.getNode()) return Res;
2424 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2425 /// two operands of the same opcode, try to simplify it.
2426 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2427 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2428 EVT VT = N0.getValueType();
2429 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2431 // Bail early if none of these transforms apply.
2432 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2434 // For each of OP in AND/OR/XOR:
2435 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2436 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2437 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2438 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2440 // do not sink logical op inside of a vector extend, since it may combine
2442 EVT Op0VT = N0.getOperand(0).getValueType();
2443 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2444 N0.getOpcode() == ISD::SIGN_EXTEND ||
2445 // Avoid infinite looping with PromoteIntBinOp.
2446 (N0.getOpcode() == ISD::ANY_EXTEND &&
2447 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2448 (N0.getOpcode() == ISD::TRUNCATE &&
2449 (!TLI.isZExtFree(VT, Op0VT) ||
2450 !TLI.isTruncateFree(Op0VT, VT)) &&
2451 TLI.isTypeLegal(Op0VT))) &&
2453 Op0VT == N1.getOperand(0).getValueType() &&
2454 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2455 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2456 N0.getOperand(0).getValueType(),
2457 N0.getOperand(0), N1.getOperand(0));
2458 AddToWorkList(ORNode.getNode());
2459 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2462 // For each of OP in SHL/SRL/SRA/AND...
2463 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2464 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2465 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2466 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2467 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2468 N0.getOperand(1) == N1.getOperand(1)) {
2469 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2470 N0.getOperand(0).getValueType(),
2471 N0.getOperand(0), N1.getOperand(0));
2472 AddToWorkList(ORNode.getNode());
2473 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2474 ORNode, N0.getOperand(1));
2477 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2478 // Only perform this optimization after type legalization and before
2479 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2480 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2481 // we don't want to undo this promotion.
2482 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2484 if ((N0.getOpcode() == ISD::BITCAST ||
2485 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2486 Level == AfterLegalizeTypes) {
2487 SDValue In0 = N0.getOperand(0);
2488 SDValue In1 = N1.getOperand(0);
2489 EVT In0Ty = In0.getValueType();
2490 EVT In1Ty = In1.getValueType();
2492 // If both incoming values are integers, and the original types are the
2494 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2495 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2496 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2497 AddToWorkList(Op.getNode());
2502 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2503 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2504 // If both shuffles use the same mask, and both shuffle within a single
2505 // vector, then it is worthwhile to move the swizzle after the operation.
2506 // The type-legalizer generates this pattern when loading illegal
2507 // vector types from memory. In many cases this allows additional shuffle
2509 // There are other cases where moving the shuffle after the xor/and/or
2510 // is profitable even if shuffles don't perform a swizzle.
2511 // If both shuffles use the same mask, and both shuffles have the same first
2512 // or second operand, then it might still be profitable to move the shuffle
2513 // after the xor/and/or operation.
2514 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2515 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2516 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2518 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2519 "Inputs to shuffles are not the same type");
2521 // Check that both shuffles use the same mask. The masks are known to be of
2522 // the same length because the result vector type is the same.
2523 // Check also that shuffles have only one use to avoid introducing extra
2525 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2526 SVN0->getMask().equals(SVN1->getMask())) {
2527 SDValue ShOp = N0->getOperand(1);
2529 // Don't try to fold this node if it requires introducing a
2530 // build vector of all zeros that might be illegal at this stage.
2531 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2533 ShOp = DAG.getConstant(0, VT);
2538 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2539 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2540 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2541 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2542 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2543 N0->getOperand(0), N1->getOperand(0));
2544 AddToWorkList(NewNode.getNode());
2545 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2546 &SVN0->getMask()[0]);
2549 // Don't try to fold this node if it requires introducing a
2550 // build vector of all zeros that might be illegal at this stage.
2551 ShOp = N0->getOperand(0);
2552 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2554 ShOp = DAG.getConstant(0, VT);
2559 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2560 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2561 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2562 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2563 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2564 N0->getOperand(1), N1->getOperand(1));
2565 AddToWorkList(NewNode.getNode());
2566 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2567 &SVN0->getMask()[0]);
2575 SDValue DAGCombiner::visitAND(SDNode *N) {
2576 SDValue N0 = N->getOperand(0);
2577 SDValue N1 = N->getOperand(1);
2578 SDValue LL, LR, RL, RR, CC0, CC1;
2579 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2580 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2581 EVT VT = N1.getValueType();
2582 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2585 if (VT.isVector()) {
2586 SDValue FoldedVOp = SimplifyVBinOp(N);
2587 if (FoldedVOp.getNode()) return FoldedVOp;
2589 // fold (and x, 0) -> 0, vector edition
2590 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2592 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2595 // fold (and x, -1) -> x, vector edition
2596 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2598 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2602 // fold (and x, undef) -> 0
2603 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2604 return DAG.getConstant(0, VT);
2605 // fold (and c1, c2) -> c1&c2
2607 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2608 // canonicalize constant to RHS
2610 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2611 // fold (and x, -1) -> x
2612 if (N1C && N1C->isAllOnesValue())
2614 // if (and x, c) is known to be zero, return 0
2615 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2616 APInt::getAllOnesValue(BitWidth)))
2617 return DAG.getConstant(0, VT);
2619 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2622 // fold (and (or x, C), D) -> D if (C & D) == D
2623 if (N1C && N0.getOpcode() == ISD::OR)
2624 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2625 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2627 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2628 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2629 SDValue N0Op0 = N0.getOperand(0);
2630 APInt Mask = ~N1C->getAPIntValue();
2631 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2632 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2633 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2634 N0.getValueType(), N0Op0);
2636 // Replace uses of the AND with uses of the Zero extend node.
2639 // We actually want to replace all uses of the any_extend with the
2640 // zero_extend, to avoid duplicating things. This will later cause this
2641 // AND to be folded.
2642 CombineTo(N0.getNode(), Zext);
2643 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2646 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2647 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2648 // already be zero by virtue of the width of the base type of the load.
2650 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2652 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2653 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2654 N0.getOpcode() == ISD::LOAD) {
2655 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2656 N0 : N0.getOperand(0) );
2658 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2659 // This can be a pure constant or a vector splat, in which case we treat the
2660 // vector as a scalar and use the splat value.
2661 APInt Constant = APInt::getNullValue(1);
2662 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2663 Constant = C->getAPIntValue();
2664 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2665 APInt SplatValue, SplatUndef;
2666 unsigned SplatBitSize;
2668 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2669 SplatBitSize, HasAnyUndefs);
2671 // Undef bits can contribute to a possible optimisation if set, so
2673 SplatValue |= SplatUndef;
2675 // The splat value may be something like "0x00FFFFFF", which means 0 for
2676 // the first vector value and FF for the rest, repeating. We need a mask
2677 // that will apply equally to all members of the vector, so AND all the
2678 // lanes of the constant together.
2679 EVT VT = Vector->getValueType(0);
2680 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2682 // If the splat value has been compressed to a bitlength lower
2683 // than the size of the vector lane, we need to re-expand it to
2685 if (BitWidth > SplatBitSize)
2686 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2687 SplatBitSize < BitWidth;
2688 SplatBitSize = SplatBitSize * 2)
2689 SplatValue |= SplatValue.shl(SplatBitSize);
2691 Constant = APInt::getAllOnesValue(BitWidth);
2692 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2693 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2697 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2698 // actually legal and isn't going to get expanded, else this is a false
2700 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2701 Load->getMemoryVT());
2703 // Resize the constant to the same size as the original memory access before
2704 // extension. If it is still the AllOnesValue then this AND is completely
2707 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2710 switch (Load->getExtensionType()) {
2711 default: B = false; break;
2712 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2714 case ISD::NON_EXTLOAD: B = true; break;
2717 if (B && Constant.isAllOnesValue()) {
2718 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2719 // preserve semantics once we get rid of the AND.
2720 SDValue NewLoad(Load, 0);
2721 if (Load->getExtensionType() == ISD::EXTLOAD) {
2722 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2723 Load->getValueType(0), SDLoc(Load),
2724 Load->getChain(), Load->getBasePtr(),
2725 Load->getOffset(), Load->getMemoryVT(),
2726 Load->getMemOperand());
2727 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2728 if (Load->getNumValues() == 3) {
2729 // PRE/POST_INC loads have 3 values.
2730 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2731 NewLoad.getValue(2) };
2732 CombineTo(Load, To, 3, true);
2734 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2738 // Fold the AND away, taking care not to fold to the old load node if we
2740 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2742 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2745 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2746 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2747 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2748 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2750 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2751 LL.getValueType().isInteger()) {
2752 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2753 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2754 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2755 LR.getValueType(), LL, RL);
2756 AddToWorkList(ORNode.getNode());
2757 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2759 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2760 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2761 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2762 LR.getValueType(), LL, RL);
2763 AddToWorkList(ANDNode.getNode());
2764 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2766 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2767 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2768 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2769 LR.getValueType(), LL, RL);
2770 AddToWorkList(ORNode.getNode());
2771 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2774 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2775 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2776 Op0 == Op1 && LL.getValueType().isInteger() &&
2777 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2778 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2779 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2780 cast<ConstantSDNode>(RR)->isNullValue()))) {
2781 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2782 LL, DAG.getConstant(1, LL.getValueType()));
2783 AddToWorkList(ADDNode.getNode());
2784 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2785 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2787 // canonicalize equivalent to ll == rl
2788 if (LL == RR && LR == RL) {
2789 Op1 = ISD::getSetCCSwappedOperands(Op1);
2792 if (LL == RL && LR == RR) {
2793 bool isInteger = LL.getValueType().isInteger();
2794 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2795 if (Result != ISD::SETCC_INVALID &&
2796 (!LegalOperations ||
2797 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2798 TLI.isOperationLegal(ISD::SETCC,
2799 getSetCCResultType(N0.getSimpleValueType())))))
2800 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2805 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2806 if (N0.getOpcode() == N1.getOpcode()) {
2807 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2808 if (Tmp.getNode()) return Tmp;
2811 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2812 // fold (and (sra)) -> (and (srl)) when possible.
2813 if (!VT.isVector() &&
2814 SimplifyDemandedBits(SDValue(N, 0)))
2815 return SDValue(N, 0);
2817 // fold (zext_inreg (extload x)) -> (zextload x)
2818 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2819 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2820 EVT MemVT = LN0->getMemoryVT();
2821 // If we zero all the possible extended bits, then we can turn this into
2822 // a zextload if we are running before legalize or the operation is legal.
2823 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2824 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2825 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2826 ((!LegalOperations && !LN0->isVolatile()) ||
2827 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2828 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2829 LN0->getChain(), LN0->getBasePtr(),
2830 MemVT, LN0->getMemOperand());
2832 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2833 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2836 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2837 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2839 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2840 EVT MemVT = LN0->getMemoryVT();
2841 // If we zero all the possible extended bits, then we can turn this into
2842 // a zextload if we are running before legalize or the operation is legal.
2843 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2844 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2845 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2846 ((!LegalOperations && !LN0->isVolatile()) ||
2847 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2848 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2849 LN0->getChain(), LN0->getBasePtr(),
2850 MemVT, LN0->getMemOperand());
2852 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2853 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2857 // fold (and (load x), 255) -> (zextload x, i8)
2858 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2859 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2860 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2861 (N0.getOpcode() == ISD::ANY_EXTEND &&
2862 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2863 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2864 LoadSDNode *LN0 = HasAnyExt
2865 ? cast<LoadSDNode>(N0.getOperand(0))
2866 : cast<LoadSDNode>(N0);
2867 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2868 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2869 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2870 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2871 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2872 EVT LoadedVT = LN0->getMemoryVT();
2874 if (ExtVT == LoadedVT &&
2875 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2876 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2879 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2880 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2881 LN0->getMemOperand());
2883 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2884 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2887 // Do not change the width of a volatile load.
2888 // Do not generate loads of non-round integer types since these can
2889 // be expensive (and would be wrong if the type is not byte sized).
2890 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2891 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2892 EVT PtrType = LN0->getOperand(1).getValueType();
2894 unsigned Alignment = LN0->getAlignment();
2895 SDValue NewPtr = LN0->getBasePtr();
2897 // For big endian targets, we need to add an offset to the pointer
2898 // to load the correct bytes. For little endian systems, we merely
2899 // need to read fewer bytes from the same pointer.
2900 if (TLI.isBigEndian()) {
2901 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2902 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2903 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2904 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2905 NewPtr, DAG.getConstant(PtrOff, PtrType));
2906 Alignment = MinAlign(Alignment, PtrOff);
2909 AddToWorkList(NewPtr.getNode());
2911 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2913 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2914 LN0->getChain(), NewPtr,
2915 LN0->getPointerInfo(),
2916 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2917 Alignment, LN0->getTBAAInfo());
2919 CombineTo(LN0, Load, Load.getValue(1));
2920 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2926 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2927 VT.getSizeInBits() <= 64) {
2928 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2929 APInt ADDC = ADDI->getAPIntValue();
2930 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2931 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2932 // immediate for an add, but it is legal if its top c2 bits are set,
2933 // transform the ADD so the immediate doesn't need to be materialized
2935 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2936 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2937 SRLI->getZExtValue());
2938 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2940 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2942 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2943 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2944 CombineTo(N0.getNode(), NewAdd);
2945 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2953 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2954 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2955 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2956 N0.getOperand(1), false);
2957 if (BSwap.getNode())
2964 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2966 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2967 bool DemandHighBits) {
2968 if (!LegalOperations)
2971 EVT VT = N->getValueType(0);
2972 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2974 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2977 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2978 bool LookPassAnd0 = false;
2979 bool LookPassAnd1 = false;
2980 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2982 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2984 if (N0.getOpcode() == ISD::AND) {
2985 if (!N0.getNode()->hasOneUse())
2987 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2988 if (!N01C || N01C->getZExtValue() != 0xFF00)
2990 N0 = N0.getOperand(0);
2991 LookPassAnd0 = true;
2994 if (N1.getOpcode() == ISD::AND) {
2995 if (!N1.getNode()->hasOneUse())
2997 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2998 if (!N11C || N11C->getZExtValue() != 0xFF)
3000 N1 = N1.getOperand(0);
3001 LookPassAnd1 = true;
3004 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3006 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3008 if (!N0.getNode()->hasOneUse() ||
3009 !N1.getNode()->hasOneUse())
3012 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3013 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3016 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3019 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3020 SDValue N00 = N0->getOperand(0);
3021 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3022 if (!N00.getNode()->hasOneUse())
3024 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3025 if (!N001C || N001C->getZExtValue() != 0xFF)
3027 N00 = N00.getOperand(0);
3028 LookPassAnd0 = true;
3031 SDValue N10 = N1->getOperand(0);
3032 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3033 if (!N10.getNode()->hasOneUse())
3035 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3036 if (!N101C || N101C->getZExtValue() != 0xFF00)
3038 N10 = N10.getOperand(0);
3039 LookPassAnd1 = true;
3045 // Make sure everything beyond the low halfword gets set to zero since the SRL
3046 // 16 will clear the top bits.
3047 unsigned OpSizeInBits = VT.getSizeInBits();
3048 if (DemandHighBits && OpSizeInBits > 16) {
3049 // If the left-shift isn't masked out then the only way this is a bswap is
3050 // if all bits beyond the low 8 are 0. In that case the entire pattern
3051 // reduces to a left shift anyway: leave it for other parts of the combiner.
3055 // However, if the right shift isn't masked out then it might be because
3056 // it's not needed. See if we can spot that too.
3057 if (!LookPassAnd1 &&
3058 !DAG.MaskedValueIsZero(
3059 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3063 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3064 if (OpSizeInBits > 16)
3065 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3066 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3070 /// isBSwapHWordElement - Return true if the specified node is an element
3071 /// that makes up a 32-bit packed halfword byteswap. i.e.
3072 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3073 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3074 if (!N.getNode()->hasOneUse())
3077 unsigned Opc = N.getOpcode();
3078 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3081 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3086 switch (N1C->getZExtValue()) {
3089 case 0xFF: Num = 0; break;
3090 case 0xFF00: Num = 1; break;
3091 case 0xFF0000: Num = 2; break;
3092 case 0xFF000000: Num = 3; break;
3095 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3096 SDValue N0 = N.getOperand(0);
3097 if (Opc == ISD::AND) {
3098 if (Num == 0 || Num == 2) {
3100 // (x >> 8) & 0xff0000
3101 if (N0.getOpcode() != ISD::SRL)
3103 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3104 if (!C || C->getZExtValue() != 8)
3107 // (x << 8) & 0xff00
3108 // (x << 8) & 0xff000000
3109 if (N0.getOpcode() != ISD::SHL)
3111 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3112 if (!C || C->getZExtValue() != 8)
3115 } else if (Opc == ISD::SHL) {
3117 // (x & 0xff0000) << 8
3118 if (Num != 0 && Num != 2)
3120 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3121 if (!C || C->getZExtValue() != 8)
3123 } else { // Opc == ISD::SRL
3124 // (x & 0xff00) >> 8
3125 // (x & 0xff000000) >> 8
3126 if (Num != 1 && Num != 3)
3128 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3129 if (!C || C->getZExtValue() != 8)
3136 Parts[Num] = N0.getOperand(0).getNode();
3140 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3141 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3142 /// => (rotl (bswap x), 16)
3143 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3144 if (!LegalOperations)
3147 EVT VT = N->getValueType(0);
3150 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3153 SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3155 // (or (or (and), (and)), (or (and), (and)))
3156 // (or (or (or (and), (and)), (and)), (and))
3157 if (N0.getOpcode() != ISD::OR)
3159 SDValue N00 = N0.getOperand(0);
3160 SDValue N01 = N0.getOperand(1);
3162 if (N1.getOpcode() == ISD::OR &&
3163 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3164 // (or (or (and), (and)), (or (and), (and)))
3165 SDValue N000 = N00.getOperand(0);
3166 if (!isBSwapHWordElement(N000, Parts))
3169 SDValue N001 = N00.getOperand(1);
3170 if (!isBSwapHWordElement(N001, Parts))
3172 SDValue N010 = N01.getOperand(0);
3173 if (!isBSwapHWordElement(N010, Parts))
3175 SDValue N011 = N01.getOperand(1);
3176 if (!isBSwapHWordElement(N011, Parts))
3179 // (or (or (or (and), (and)), (and)), (and))
3180 if (!isBSwapHWordElement(N1, Parts))
3182 if (!isBSwapHWordElement(N01, Parts))
3184 if (N00.getOpcode() != ISD::OR)
3186 SDValue N000 = N00.getOperand(0);
3187 if (!isBSwapHWordElement(N000, Parts))
3189 SDValue N001 = N00.getOperand(1);
3190 if (!isBSwapHWordElement(N001, Parts))
3194 // Make sure the parts are all coming from the same node.
3195 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3198 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3199 SDValue(Parts[0],0));
3201 // Result of the bswap should be rotated by 16. If it's not legal, then
3202 // do (x << 16) | (x >> 16).
3203 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3204 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3205 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3206 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3207 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3208 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3209 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3210 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3213 SDValue DAGCombiner::visitOR(SDNode *N) {
3214 SDValue N0 = N->getOperand(0);
3215 SDValue N1 = N->getOperand(1);
3216 SDValue LL, LR, RL, RR, CC0, CC1;
3217 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3218 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3219 EVT VT = N1.getValueType();
3222 if (VT.isVector()) {
3223 SDValue FoldedVOp = SimplifyVBinOp(N);
3224 if (FoldedVOp.getNode()) return FoldedVOp;
3226 // fold (or x, 0) -> x, vector edition
3227 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3229 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3232 // fold (or x, -1) -> -1, vector edition
3233 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3235 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3238 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3239 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3240 // Do this only if the resulting shuffle is legal.
3241 if (isa<ShuffleVectorSDNode>(N0) &&
3242 isa<ShuffleVectorSDNode>(N1) &&
3243 N0->getOperand(1) == N1->getOperand(1) &&
3244 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3245 bool CanFold = true;
3246 unsigned NumElts = VT.getVectorNumElements();
3247 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3248 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3249 // We construct two shuffle masks:
3250 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3251 // and N1 as the second operand.
3252 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3253 // and N0 as the second operand.
3254 // We do this because OR is commutable and therefore there might be
3255 // two ways to fold this node into a shuffle.
3256 SmallVector<int,4> Mask1;
3257 SmallVector<int,4> Mask2;
3259 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3260 int M0 = SV0->getMaskElt(i);
3261 int M1 = SV1->getMaskElt(i);
3263 // Both shuffle indexes are undef. Propagate Undef.
3264 if (M0 < 0 && M1 < 0) {
3265 Mask1.push_back(M0);
3266 Mask2.push_back(M0);
3270 if (M0 < 0 || M1 < 0 ||
3271 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3272 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3277 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3278 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3282 // Fold this sequence only if the resulting shuffle is 'legal'.
3283 if (TLI.isShuffleMaskLegal(Mask1, VT))
3284 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3285 N1->getOperand(0), &Mask1[0]);
3286 if (TLI.isShuffleMaskLegal(Mask2, VT))
3287 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3288 N0->getOperand(0), &Mask2[0]);
3293 // fold (or x, undef) -> -1
3294 if (!LegalOperations &&
3295 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3296 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3297 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3299 // fold (or c1, c2) -> c1|c2
3301 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3302 // canonicalize constant to RHS
3304 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3305 // fold (or x, 0) -> x
3306 if (N1C && N1C->isNullValue())
3308 // fold (or x, -1) -> -1
3309 if (N1C && N1C->isAllOnesValue())
3311 // fold (or x, c) -> c iff (x & ~c) == 0
3312 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3315 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3316 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3317 if (BSwap.getNode())
3319 BSwap = MatchBSwapHWordLow(N, N0, N1);
3320 if (BSwap.getNode())
3324 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3327 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3328 // iff (c1 & c2) == 0.
3329 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3330 isa<ConstantSDNode>(N0.getOperand(1))) {
3331 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3332 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3333 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3336 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3337 DAG.getNode(ISD::OR, SDLoc(N0), VT,
3338 N0.getOperand(0), N1), COR);
3341 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3342 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3343 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3344 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3346 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3347 LL.getValueType().isInteger()) {
3348 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3349 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3350 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3351 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3352 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3353 LR.getValueType(), LL, RL);
3354 AddToWorkList(ORNode.getNode());
3355 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3357 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3358 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3359 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3360 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3361 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3362 LR.getValueType(), LL, RL);
3363 AddToWorkList(ANDNode.getNode());
3364 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3367 // canonicalize equivalent to ll == rl
3368 if (LL == RR && LR == RL) {
3369 Op1 = ISD::getSetCCSwappedOperands(Op1);
3372 if (LL == RL && LR == RR) {
3373 bool isInteger = LL.getValueType().isInteger();
3374 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3375 if (Result != ISD::SETCC_INVALID &&
3376 (!LegalOperations ||
3377 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3378 TLI.isOperationLegal(ISD::SETCC,
3379 getSetCCResultType(N0.getValueType())))))
3380 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3385 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3386 if (N0.getOpcode() == N1.getOpcode()) {
3387 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3388 if (Tmp.getNode()) return Tmp;
3391 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3392 if (N0.getOpcode() == ISD::AND &&
3393 N1.getOpcode() == ISD::AND &&
3394 N0.getOperand(1).getOpcode() == ISD::Constant &&
3395 N1.getOperand(1).getOpcode() == ISD::Constant &&
3396 // Don't increase # computations.
3397 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3398 // We can only do this xform if we know that bits from X that are set in C2
3399 // but not in C1 are already zero. Likewise for Y.
3400 const APInt &LHSMask =
3401 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3402 const APInt &RHSMask =
3403 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3405 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3406 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3407 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3408 N0.getOperand(0), N1.getOperand(0));
3409 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3410 DAG.getConstant(LHSMask | RHSMask, VT));
3414 // See if this is some rotate idiom.
3415 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3416 return SDValue(Rot, 0);
3418 // Simplify the operands using demanded-bits information.
3419 if (!VT.isVector() &&
3420 SimplifyDemandedBits(SDValue(N, 0)))
3421 return SDValue(N, 0);
3426 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3427 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3428 if (Op.getOpcode() == ISD::AND) {
3429 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3430 Mask = Op.getOperand(1);
3431 Op = Op.getOperand(0);
3437 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3445 // Return true if we can prove that, whenever Neg and Pos are both in the
3446 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3447 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3449 // (or (shift1 X, Neg), (shift2 X, Pos))
3451 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3452 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3453 // to consider shift amounts with defined behavior.
3454 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3455 // If OpSize is a power of 2 then:
3457 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3458 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3460 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3461 // for the stronger condition:
3463 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3465 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3466 // we can just replace Neg with Neg' for the rest of the function.
3468 // In other cases we check for the even stronger condition:
3470 // Neg == OpSize - Pos [B]
3472 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3473 // behavior if Pos == 0 (and consequently Neg == OpSize).
3475 // We could actually use [A] whenever OpSize is a power of 2, but the
3476 // only extra cases that it would match are those uninteresting ones
3477 // where Neg and Pos are never in range at the same time. E.g. for
3478 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3479 // as well as (sub 32, Pos), but:
3481 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3483 // always invokes undefined behavior for 32-bit X.
3485 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3486 unsigned MaskLoBits = 0;
3487 if (Neg.getOpcode() == ISD::AND &&
3488 isPowerOf2_64(OpSize) &&
3489 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3490 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3491 Neg = Neg.getOperand(0);
3492 MaskLoBits = Log2_64(OpSize);
3495 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3496 if (Neg.getOpcode() != ISD::SUB)
3498 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3501 SDValue NegOp1 = Neg.getOperand(1);
3503 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3504 // Pos'. The truncation is redundant for the purpose of the equality.
3506 Pos.getOpcode() == ISD::AND &&
3507 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3508 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3509 Pos = Pos.getOperand(0);
3511 // The condition we need is now:
3513 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3515 // If NegOp1 == Pos then we need:
3517 // OpSize & Mask == NegC & Mask
3519 // (because "x & Mask" is a truncation and distributes through subtraction).
3522 Width = NegC->getAPIntValue();
3523 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3524 // Then the condition we want to prove becomes:
3526 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3528 // which, again because "x & Mask" is a truncation, becomes:
3530 // NegC & Mask == (OpSize - PosC) & Mask
3531 // OpSize & Mask == (NegC + PosC) & Mask
3532 else if (Pos.getOpcode() == ISD::ADD &&
3533 Pos.getOperand(0) == NegOp1 &&
3534 Pos.getOperand(1).getOpcode() == ISD::Constant)
3535 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3536 NegC->getAPIntValue());
3540 // Now we just need to check that OpSize & Mask == Width & Mask.
3542 // Opsize & Mask is 0 since Mask is Opsize - 1.
3543 return Width.getLoBits(MaskLoBits) == 0;
3544 return Width == OpSize;
3547 // A subroutine of MatchRotate used once we have found an OR of two opposite
3548 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3549 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3550 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3551 // Neg with outer conversions stripped away.
3552 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3553 SDValue Neg, SDValue InnerPos,
3554 SDValue InnerNeg, unsigned PosOpcode,
3555 unsigned NegOpcode, SDLoc DL) {
3556 // fold (or (shl x, (*ext y)),
3557 // (srl x, (*ext (sub 32, y)))) ->
3558 // (rotl x, y) or (rotr x, (sub 32, y))
3560 // fold (or (shl x, (*ext (sub 32, y))),
3561 // (srl x, (*ext y))) ->
3562 // (rotr x, y) or (rotl x, (sub 32, y))
3563 EVT VT = Shifted.getValueType();
3564 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3565 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3566 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3567 HasPos ? Pos : Neg).getNode();
3573 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3574 // idioms for rotate, and if the target supports rotation instructions, generate
3576 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3577 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3578 EVT VT = LHS.getValueType();
3579 if (!TLI.isTypeLegal(VT)) return nullptr;
3581 // The target must have at least one rotate flavor.
3582 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3583 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3584 if (!HasROTL && !HasROTR) return nullptr;
3586 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3587 SDValue LHSShift; // The shift.
3588 SDValue LHSMask; // AND value if any.
3589 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3590 return nullptr; // Not part of a rotate.
3592 SDValue RHSShift; // The shift.
3593 SDValue RHSMask; // AND value if any.
3594 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3595 return nullptr; // Not part of a rotate.
3597 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3598 return nullptr; // Not shifting the same value.
3600 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3601 return nullptr; // Shifts must disagree.
3603 // Canonicalize shl to left side in a shl/srl pair.
3604 if (RHSShift.getOpcode() == ISD::SHL) {
3605 std::swap(LHS, RHS);
3606 std::swap(LHSShift, RHSShift);
3607 std::swap(LHSMask , RHSMask );
3610 unsigned OpSizeInBits = VT.getSizeInBits();
3611 SDValue LHSShiftArg = LHSShift.getOperand(0);
3612 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3613 SDValue RHSShiftArg = RHSShift.getOperand(0);
3614 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3616 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3617 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3618 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3619 RHSShiftAmt.getOpcode() == ISD::Constant) {
3620 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3621 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3622 if ((LShVal + RShVal) != OpSizeInBits)
3625 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3626 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3628 // If there is an AND of either shifted operand, apply it to the result.
3629 if (LHSMask.getNode() || RHSMask.getNode()) {
3630 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3632 if (LHSMask.getNode()) {
3633 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3634 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3636 if (RHSMask.getNode()) {
3637 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3638 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3641 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3644 return Rot.getNode();
3647 // If there is a mask here, and we have a variable shift, we can't be sure
3648 // that we're masking out the right stuff.
3649 if (LHSMask.getNode() || RHSMask.getNode())
3652 // If the shift amount is sign/zext/any-extended just peel it off.
3653 SDValue LExtOp0 = LHSShiftAmt;
3654 SDValue RExtOp0 = RHSShiftAmt;
3655 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3656 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3657 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3658 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3659 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3660 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3661 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3662 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3663 LExtOp0 = LHSShiftAmt.getOperand(0);
3664 RExtOp0 = RHSShiftAmt.getOperand(0);
3667 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3668 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3672 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3673 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3680 SDValue DAGCombiner::visitXOR(SDNode *N) {
3681 SDValue N0 = N->getOperand(0);
3682 SDValue N1 = N->getOperand(1);
3683 SDValue LHS, RHS, CC;
3684 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3685 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3686 EVT VT = N0.getValueType();
3689 if (VT.isVector()) {
3690 SDValue FoldedVOp = SimplifyVBinOp(N);
3691 if (FoldedVOp.getNode()) return FoldedVOp;
3693 // fold (xor x, 0) -> x, vector edition
3694 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3696 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3700 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3701 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3702 return DAG.getConstant(0, VT);
3703 // fold (xor x, undef) -> undef
3704 if (N0.getOpcode() == ISD::UNDEF)
3706 if (N1.getOpcode() == ISD::UNDEF)
3708 // fold (xor c1, c2) -> c1^c2
3710 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3711 // canonicalize constant to RHS
3713 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3714 // fold (xor x, 0) -> x
3715 if (N1C && N1C->isNullValue())
3718 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3722 // fold !(x cc y) -> (x !cc y)
3723 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3724 bool isInt = LHS.getValueType().isInteger();
3725 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3728 if (!LegalOperations ||
3729 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3730 switch (N0.getOpcode()) {
3732 llvm_unreachable("Unhandled SetCC Equivalent!");
3734 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3735 case ISD::SELECT_CC:
3736 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3737 N0.getOperand(3), NotCC);
3742 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3743 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3744 N0.getNode()->hasOneUse() &&
3745 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3746 SDValue V = N0.getOperand(0);
3747 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3748 DAG.getConstant(1, V.getValueType()));
3749 AddToWorkList(V.getNode());
3750 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3753 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3754 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3755 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3756 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3757 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3758 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3759 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3760 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3761 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3762 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3765 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3766 if (N1C && N1C->isAllOnesValue() &&
3767 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3768 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3769 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3770 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3771 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3772 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3773 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3774 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3777 // fold (xor (and x, y), y) -> (and (not x), y)
3778 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3779 N0->getOperand(1) == N1) {
3780 SDValue X = N0->getOperand(0);
3781 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3782 AddToWorkList(NotX.getNode());
3783 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3785 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3786 if (N1C && N0.getOpcode() == ISD::XOR) {
3787 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3788 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3790 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3791 DAG.getConstant(N1C->getAPIntValue() ^
3792 N00C->getAPIntValue(), VT));
3794 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3795 DAG.getConstant(N1C->getAPIntValue() ^
3796 N01C->getAPIntValue(), VT));
3798 // fold (xor x, x) -> 0
3800 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3802 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3803 if (N0.getOpcode() == N1.getOpcode()) {
3804 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3805 if (Tmp.getNode()) return Tmp;
3808 // Simplify the expression using non-local knowledge.
3809 if (!VT.isVector() &&
3810 SimplifyDemandedBits(SDValue(N, 0)))
3811 return SDValue(N, 0);
3816 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3817 /// the shift amount is a constant.
3818 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3819 // We can't and shouldn't fold opaque constants.
3820 if (Amt->isOpaque())
3823 SDNode *LHS = N->getOperand(0).getNode();
3824 if (!LHS->hasOneUse()) return SDValue();
3826 // We want to pull some binops through shifts, so that we have (and (shift))
3827 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3828 // thing happens with address calculations, so it's important to canonicalize
3830 bool HighBitSet = false; // Can we transform this if the high bit is set?
3832 switch (LHS->getOpcode()) {
3833 default: return SDValue();
3836 HighBitSet = false; // We can only transform sra if the high bit is clear.
3839 HighBitSet = true; // We can only transform sra if the high bit is set.
3842 if (N->getOpcode() != ISD::SHL)
3843 return SDValue(); // only shl(add) not sr[al](add).
3844 HighBitSet = false; // We can only transform sra if the high bit is clear.
3848 // We require the RHS of the binop to be a constant and not opaque as well.
3849 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3850 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3852 // FIXME: disable this unless the input to the binop is a shift by a constant.
3853 // If it is not a shift, it pessimizes some common cases like:
3855 // void foo(int *X, int i) { X[i & 1235] = 1; }
3856 // int bar(int *X, int i) { return X[i & 255]; }
3857 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3858 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3859 BinOpLHSVal->getOpcode() != ISD::SRA &&
3860 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3861 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3864 EVT VT = N->getValueType(0);
3866 // If this is a signed shift right, and the high bit is modified by the
3867 // logical operation, do not perform the transformation. The highBitSet
3868 // boolean indicates the value of the high bit of the constant which would
3869 // cause it to be modified for this operation.
3870 if (N->getOpcode() == ISD::SRA) {
3871 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3872 if (BinOpRHSSignSet != HighBitSet)
3876 // Fold the constants, shifting the binop RHS by the shift amount.
3877 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3879 LHS->getOperand(1), N->getOperand(1));
3880 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3882 // Create the new shift.
3883 SDValue NewShift = DAG.getNode(N->getOpcode(),
3884 SDLoc(LHS->getOperand(0)),
3885 VT, LHS->getOperand(0), N->getOperand(1));
3887 // Create the new binop.
3888 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3891 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3892 assert(N->getOpcode() == ISD::TRUNCATE);
3893 assert(N->getOperand(0).getOpcode() == ISD::AND);
3895 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3896 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3897 SDValue N01 = N->getOperand(0).getOperand(1);
3899 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3900 EVT TruncVT = N->getValueType(0);
3901 SDValue N00 = N->getOperand(0).getOperand(0);
3902 APInt TruncC = N01C->getAPIntValue();
3903 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3905 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3906 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3907 DAG.getConstant(TruncC, TruncVT));
3914 SDValue DAGCombiner::visitRotate(SDNode *N) {
3915 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3916 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3917 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3918 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3919 if (NewOp1.getNode())
3920 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3921 N->getOperand(0), NewOp1);
3926 SDValue DAGCombiner::visitSHL(SDNode *N) {
3927 SDValue N0 = N->getOperand(0);
3928 SDValue N1 = N->getOperand(1);
3929 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3930 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3931 EVT VT = N0.getValueType();
3932 unsigned OpSizeInBits = VT.getScalarSizeInBits();
3935 if (VT.isVector()) {
3936 SDValue FoldedVOp = SimplifyVBinOp(N);
3937 if (FoldedVOp.getNode()) return FoldedVOp;
3939 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3940 // If setcc produces all-one true value then:
3941 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
3942 if (N1CV && N1CV->isConstant()) {
3943 if (N0.getOpcode() == ISD::AND &&
3944 TLI.getBooleanContents(true) ==
3945 TargetLowering::ZeroOrNegativeOneBooleanContent) {
3946 SDValue N00 = N0->getOperand(0);
3947 SDValue N01 = N0->getOperand(1);
3948 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
3950 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC) {
3951 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3953 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3956 N1C = isConstOrConstSplat(N1);
3961 // fold (shl c1, c2) -> c1<<c2
3963 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3964 // fold (shl 0, x) -> 0
3965 if (N0C && N0C->isNullValue())
3967 // fold (shl x, c >= size(x)) -> undef
3968 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3969 return DAG.getUNDEF(VT);
3970 // fold (shl x, 0) -> x
3971 if (N1C && N1C->isNullValue())
3973 // fold (shl undef, x) -> 0
3974 if (N0.getOpcode() == ISD::UNDEF)
3975 return DAG.getConstant(0, VT);
3976 // if (shl x, c) is known to be zero, return 0
3977 if (DAG.MaskedValueIsZero(SDValue(N, 0),
3978 APInt::getAllOnesValue(OpSizeInBits)))
3979 return DAG.getConstant(0, VT);
3980 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3981 if (N1.getOpcode() == ISD::TRUNCATE &&
3982 N1.getOperand(0).getOpcode() == ISD::AND) {
3983 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
3984 if (NewOp1.getNode())
3985 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
3988 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3989 return SDValue(N, 0);
3991 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3992 if (N1C && N0.getOpcode() == ISD::SHL) {
3993 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
3994 uint64_t c1 = N0C1->getZExtValue();
3995 uint64_t c2 = N1C->getZExtValue();
3996 if (c1 + c2 >= OpSizeInBits)
3997 return DAG.getConstant(0, VT);
3998 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3999 DAG.getConstant(c1 + c2, N1.getValueType()));
4003 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4004 // For this to be valid, the second form must not preserve any of the bits
4005 // that are shifted out by the inner shift in the first form. This means
4006 // the outer shift size must be >= the number of bits added by the ext.
4007 // As a corollary, we don't care what kind of ext it is.
4008 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4009 N0.getOpcode() == ISD::ANY_EXTEND ||
4010 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4011 N0.getOperand(0).getOpcode() == ISD::SHL) {
4012 SDValue N0Op0 = N0.getOperand(0);
4013 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4014 uint64_t c1 = N0Op0C1->getZExtValue();
4015 uint64_t c2 = N1C->getZExtValue();
4016 EVT InnerShiftVT = N0Op0.getValueType();
4017 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4018 if (c2 >= OpSizeInBits - InnerShiftSize) {
4019 if (c1 + c2 >= OpSizeInBits)
4020 return DAG.getConstant(0, VT);
4021 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4022 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4023 N0Op0->getOperand(0)),
4024 DAG.getConstant(c1 + c2, N1.getValueType()));
4029 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4030 // Only fold this if the inner zext has no other uses to avoid increasing
4031 // the total number of instructions.
4032 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4033 N0.getOperand(0).getOpcode() == ISD::SRL) {
4034 SDValue N0Op0 = N0.getOperand(0);
4035 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4036 uint64_t c1 = N0Op0C1->getZExtValue();
4037 if (c1 < VT.getScalarSizeInBits()) {
4038 uint64_t c2 = N1C->getZExtValue();
4040 SDValue NewOp0 = N0.getOperand(0);
4041 EVT CountVT = NewOp0.getOperand(1).getValueType();
4042 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4043 NewOp0, DAG.getConstant(c2, CountVT));
4044 AddToWorkList(NewSHL.getNode());
4045 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4051 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4052 // (and (srl x, (sub c1, c2), MASK)
4053 // Only fold this if the inner shift has no other uses -- if it does, folding
4054 // this will increase the total number of instructions.
4055 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4056 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4057 uint64_t c1 = N0C1->getZExtValue();
4058 if (c1 < OpSizeInBits) {
4059 uint64_t c2 = N1C->getZExtValue();
4060 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4063 Mask = Mask.shl(c2 - c1);
4064 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4065 DAG.getConstant(c2 - c1, N1.getValueType()));
4067 Mask = Mask.lshr(c1 - c2);
4068 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4069 DAG.getConstant(c1 - c2, N1.getValueType()));
4071 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4072 DAG.getConstant(Mask, VT));
4076 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4077 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4078 unsigned BitSize = VT.getScalarSizeInBits();
4079 SDValue HiBitsMask =
4080 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4081 BitSize - N1C->getZExtValue()), VT);
4082 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4087 SDValue NewSHL = visitShiftByConstant(N, N1C);
4088 if (NewSHL.getNode())
4095 SDValue DAGCombiner::visitSRA(SDNode *N) {
4096 SDValue N0 = N->getOperand(0);
4097 SDValue N1 = N->getOperand(1);
4098 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4099 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4100 EVT VT = N0.getValueType();
4101 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4104 if (VT.isVector()) {
4105 SDValue FoldedVOp = SimplifyVBinOp(N);
4106 if (FoldedVOp.getNode()) return FoldedVOp;
4108 N1C = isConstOrConstSplat(N1);
4111 // fold (sra c1, c2) -> (sra c1, c2)
4113 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4114 // fold (sra 0, x) -> 0
4115 if (N0C && N0C->isNullValue())
4117 // fold (sra -1, x) -> -1
4118 if (N0C && N0C->isAllOnesValue())
4120 // fold (sra x, (setge c, size(x))) -> undef
4121 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4122 return DAG.getUNDEF(VT);
4123 // fold (sra x, 0) -> x
4124 if (N1C && N1C->isNullValue())
4126 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4128 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4129 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4130 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4132 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4133 ExtVT, VT.getVectorNumElements());
4134 if ((!LegalOperations ||
4135 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4136 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4137 N0.getOperand(0), DAG.getValueType(ExtVT));
4140 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4141 if (N1C && N0.getOpcode() == ISD::SRA) {
4142 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4143 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4144 if (Sum >= OpSizeInBits)
4145 Sum = OpSizeInBits - 1;
4146 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4147 DAG.getConstant(Sum, N1.getValueType()));
4151 // fold (sra (shl X, m), (sub result_size, n))
4152 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4153 // result_size - n != m.
4154 // If truncate is free for the target sext(shl) is likely to result in better
4156 if (N0.getOpcode() == ISD::SHL && N1C) {
4157 // Get the two constanst of the shifts, CN0 = m, CN = n.
4158 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4160 LLVMContext &Ctx = *DAG.getContext();
4161 // Determine what the truncate's result bitsize and type would be.
4162 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4165 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4167 // Determine the residual right-shift amount.
4168 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4170 // If the shift is not a no-op (in which case this should be just a sign
4171 // extend already), the truncated to type is legal, sign_extend is legal
4172 // on that type, and the truncate to that type is both legal and free,
4173 // perform the transform.
4174 if ((ShiftAmt > 0) &&
4175 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4176 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4177 TLI.isTruncateFree(VT, TruncVT)) {
4179 SDValue Amt = DAG.getConstant(ShiftAmt,
4180 getShiftAmountTy(N0.getOperand(0).getValueType()));
4181 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4182 N0.getOperand(0), Amt);
4183 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4185 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4186 N->getValueType(0), Trunc);
4191 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4192 if (N1.getOpcode() == ISD::TRUNCATE &&
4193 N1.getOperand(0).getOpcode() == ISD::AND) {
4194 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4195 if (NewOp1.getNode())
4196 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4199 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4200 // if c1 is equal to the number of bits the trunc removes
4201 if (N0.getOpcode() == ISD::TRUNCATE &&
4202 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4203 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4204 N0.getOperand(0).hasOneUse() &&
4205 N0.getOperand(0).getOperand(1).hasOneUse() &&
4207 SDValue N0Op0 = N0.getOperand(0);
4208 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4209 unsigned LargeShiftVal = LargeShift->getZExtValue();
4210 EVT LargeVT = N0Op0.getValueType();
4212 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4214 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4215 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4216 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4217 N0Op0.getOperand(0), Amt);
4218 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4223 // Simplify, based on bits shifted out of the LHS.
4224 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4225 return SDValue(N, 0);
4228 // If the sign bit is known to be zero, switch this to a SRL.
4229 if (DAG.SignBitIsZero(N0))
4230 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4233 SDValue NewSRA = visitShiftByConstant(N, N1C);
4234 if (NewSRA.getNode())
4241 SDValue DAGCombiner::visitSRL(SDNode *N) {
4242 SDValue N0 = N->getOperand(0);
4243 SDValue N1 = N->getOperand(1);
4244 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4245 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4246 EVT VT = N0.getValueType();
4247 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4250 if (VT.isVector()) {
4251 SDValue FoldedVOp = SimplifyVBinOp(N);
4252 if (FoldedVOp.getNode()) return FoldedVOp;
4254 N1C = isConstOrConstSplat(N1);
4257 // fold (srl c1, c2) -> c1 >>u c2
4259 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4260 // fold (srl 0, x) -> 0
4261 if (N0C && N0C->isNullValue())
4263 // fold (srl x, c >= size(x)) -> undef
4264 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4265 return DAG.getUNDEF(VT);
4266 // fold (srl x, 0) -> x
4267 if (N1C && N1C->isNullValue())
4269 // if (srl x, c) is known to be zero, return 0
4270 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4271 APInt::getAllOnesValue(OpSizeInBits)))
4272 return DAG.getConstant(0, VT);
4274 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4275 if (N1C && N0.getOpcode() == ISD::SRL) {
4276 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4277 uint64_t c1 = N01C->getZExtValue();
4278 uint64_t c2 = N1C->getZExtValue();
4279 if (c1 + c2 >= OpSizeInBits)
4280 return DAG.getConstant(0, VT);
4281 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4282 DAG.getConstant(c1 + c2, N1.getValueType()));
4286 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4287 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4288 N0.getOperand(0).getOpcode() == ISD::SRL &&
4289 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4291 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4292 uint64_t c2 = N1C->getZExtValue();
4293 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4294 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4295 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4296 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4297 if (c1 + OpSizeInBits == InnerShiftSize) {
4298 if (c1 + c2 >= InnerShiftSize)
4299 return DAG.getConstant(0, VT);
4300 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4301 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4302 N0.getOperand(0)->getOperand(0),
4303 DAG.getConstant(c1 + c2, ShiftCountVT)));
4307 // fold (srl (shl x, c), c) -> (and x, cst2)
4308 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4309 unsigned BitSize = N0.getScalarValueSizeInBits();
4310 if (BitSize <= 64) {
4311 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4312 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4313 DAG.getConstant(~0ULL >> ShAmt, VT));
4317 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4318 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4319 // Shifting in all undef bits?
4320 EVT SmallVT = N0.getOperand(0).getValueType();
4321 unsigned BitSize = SmallVT.getScalarSizeInBits();
4322 if (N1C->getZExtValue() >= BitSize)
4323 return DAG.getUNDEF(VT);
4325 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4326 uint64_t ShiftAmt = N1C->getZExtValue();
4327 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4329 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4330 AddToWorkList(SmallShift.getNode());
4331 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4332 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4333 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4334 DAG.getConstant(Mask, VT));
4338 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4339 // bit, which is unmodified by sra.
4340 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4341 if (N0.getOpcode() == ISD::SRA)
4342 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4345 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4346 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4347 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4348 APInt KnownZero, KnownOne;
4349 DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
4351 // If any of the input bits are KnownOne, then the input couldn't be all
4352 // zeros, thus the result of the srl will always be zero.
4353 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4355 // If all of the bits input the to ctlz node are known to be zero, then
4356 // the result of the ctlz is "32" and the result of the shift is one.
4357 APInt UnknownBits = ~KnownZero;
4358 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4360 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4361 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4362 // Okay, we know that only that the single bit specified by UnknownBits
4363 // could be set on input to the CTLZ node. If this bit is set, the SRL
4364 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4365 // to an SRL/XOR pair, which is likely to simplify more.
4366 unsigned ShAmt = UnknownBits.countTrailingZeros();
4367 SDValue Op = N0.getOperand(0);
4370 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4371 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4372 AddToWorkList(Op.getNode());
4375 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4376 Op, DAG.getConstant(1, VT));
4380 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4381 if (N1.getOpcode() == ISD::TRUNCATE &&
4382 N1.getOperand(0).getOpcode() == ISD::AND) {
4383 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4384 if (NewOp1.getNode())
4385 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4388 // fold operands of srl based on knowledge that the low bits are not
4390 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4391 return SDValue(N, 0);
4394 SDValue NewSRL = visitShiftByConstant(N, N1C);
4395 if (NewSRL.getNode())
4399 // Attempt to convert a srl of a load into a narrower zero-extending load.
4400 SDValue NarrowLoad = ReduceLoadWidth(N);
4401 if (NarrowLoad.getNode())
4404 // Here is a common situation. We want to optimize:
4407 // %b = and i32 %a, 2
4408 // %c = srl i32 %b, 1
4409 // brcond i32 %c ...
4415 // %c = setcc eq %b, 0
4418 // However when after the source operand of SRL is optimized into AND, the SRL
4419 // itself may not be optimized further. Look for it and add the BRCOND into
4421 if (N->hasOneUse()) {
4422 SDNode *Use = *N->use_begin();
4423 if (Use->getOpcode() == ISD::BRCOND)
4425 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4426 // Also look pass the truncate.
4427 Use = *Use->use_begin();
4428 if (Use->getOpcode() == ISD::BRCOND)
4436 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4437 SDValue N0 = N->getOperand(0);
4438 EVT VT = N->getValueType(0);
4440 // fold (ctlz c1) -> c2
4441 if (isa<ConstantSDNode>(N0))
4442 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4446 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4447 SDValue N0 = N->getOperand(0);
4448 EVT VT = N->getValueType(0);
4450 // fold (ctlz_zero_undef c1) -> c2
4451 if (isa<ConstantSDNode>(N0))
4452 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4456 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4457 SDValue N0 = N->getOperand(0);
4458 EVT VT = N->getValueType(0);
4460 // fold (cttz c1) -> c2
4461 if (isa<ConstantSDNode>(N0))
4462 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4466 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4467 SDValue N0 = N->getOperand(0);
4468 EVT VT = N->getValueType(0);
4470 // fold (cttz_zero_undef c1) -> c2
4471 if (isa<ConstantSDNode>(N0))
4472 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4476 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4477 SDValue N0 = N->getOperand(0);
4478 EVT VT = N->getValueType(0);
4480 // fold (ctpop c1) -> c2
4481 if (isa<ConstantSDNode>(N0))
4482 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4486 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4487 SDValue N0 = N->getOperand(0);
4488 SDValue N1 = N->getOperand(1);
4489 SDValue N2 = N->getOperand(2);
4490 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4491 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4492 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4493 EVT VT = N->getValueType(0);
4494 EVT VT0 = N0.getValueType();
4496 // fold (select C, X, X) -> X
4499 // fold (select true, X, Y) -> X
4500 if (N0C && !N0C->isNullValue())
4502 // fold (select false, X, Y) -> Y
4503 if (N0C && N0C->isNullValue())
4505 // fold (select C, 1, X) -> (or C, X)
4506 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4507 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4508 // fold (select C, 0, 1) -> (xor C, 1)
4509 if (VT.isInteger() &&
4512 TLI.getBooleanContents(false) ==
4513 TargetLowering::ZeroOrOneBooleanContent)) &&
4514 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4517 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4518 N0, DAG.getConstant(1, VT0));
4519 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4520 N0, DAG.getConstant(1, VT0));
4521 AddToWorkList(XORNode.getNode());
4523 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4524 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4526 // fold (select C, 0, X) -> (and (not C), X)
4527 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4528 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4529 AddToWorkList(NOTNode.getNode());
4530 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4532 // fold (select C, X, 1) -> (or (not C), X)
4533 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4534 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4535 AddToWorkList(NOTNode.getNode());
4536 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4538 // fold (select C, X, 0) -> (and C, X)
4539 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4540 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4541 // fold (select X, X, Y) -> (or X, Y)
4542 // fold (select X, 1, Y) -> (or X, Y)
4543 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4544 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4545 // fold (select X, Y, X) -> (and X, Y)
4546 // fold (select X, Y, 0) -> (and X, Y)
4547 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4548 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4550 // If we can fold this based on the true/false value, do so.
4551 if (SimplifySelectOps(N, N1, N2))
4552 return SDValue(N, 0); // Don't revisit N.
4554 // fold selects based on a setcc into other things, such as min/max/abs
4555 if (N0.getOpcode() == ISD::SETCC) {
4557 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4558 // having to say they don't support SELECT_CC on every type the DAG knows
4559 // about, since there is no way to mark an opcode illegal at all value types
4560 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4561 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4562 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4563 N0.getOperand(0), N0.getOperand(1),
4564 N1, N2, N0.getOperand(2));
4565 return SimplifySelect(SDLoc(N), N0, N1, N2);
4572 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4575 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4577 // Split the inputs.
4578 SDValue Lo, Hi, LL, LH, RL, RH;
4579 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4580 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4582 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4583 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4585 return std::make_pair(Lo, Hi);
4588 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4589 SDValue N0 = N->getOperand(0);
4590 SDValue N1 = N->getOperand(1);
4591 SDValue N2 = N->getOperand(2);
4594 // Canonicalize integer abs.
4595 // vselect (setg[te] X, 0), X, -X ->
4596 // vselect (setgt X, -1), X, -X ->
4597 // vselect (setl[te] X, 0), -X, X ->
4598 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4599 if (N0.getOpcode() == ISD::SETCC) {
4600 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4601 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4603 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4605 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4606 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4607 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4608 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4609 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4610 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4611 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4614 EVT VT = LHS.getValueType();
4615 SDValue Shift = DAG.getNode(
4616 ISD::SRA, DL, VT, LHS,
4617 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4618 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4619 AddToWorkList(Shift.getNode());
4620 AddToWorkList(Add.getNode());
4621 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4625 // If the VSELECT result requires splitting and the mask is provided by a
4626 // SETCC, then split both nodes and its operands before legalization. This
4627 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4628 // and enables future optimizations (e.g. min/max pattern matching on X86).
4629 if (N0.getOpcode() == ISD::SETCC) {
4630 EVT VT = N->getValueType(0);
4632 // Check if any splitting is required.
4633 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4634 TargetLowering::TypeSplitVector)
4637 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4638 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4639 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4640 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4642 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4643 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4645 // Add the new VSELECT nodes to the work list in case they need to be split
4647 AddToWorkList(Lo.getNode());
4648 AddToWorkList(Hi.getNode());
4650 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4653 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4654 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4656 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4657 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4663 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4664 SDValue N0 = N->getOperand(0);
4665 SDValue N1 = N->getOperand(1);
4666 SDValue N2 = N->getOperand(2);
4667 SDValue N3 = N->getOperand(3);
4668 SDValue N4 = N->getOperand(4);
4669 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4671 // fold select_cc lhs, rhs, x, x, cc -> x
4675 // Determine if the condition we're dealing with is constant
4676 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4677 N0, N1, CC, SDLoc(N), false);
4678 if (SCC.getNode()) {
4679 AddToWorkList(SCC.getNode());
4681 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4682 if (!SCCC->isNullValue())
4683 return N2; // cond always true -> true val
4685 return N3; // cond always false -> false val
4688 // Fold to a simpler select_cc
4689 if (SCC.getOpcode() == ISD::SETCC)
4690 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4691 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4695 // If we can fold this based on the true/false value, do so.
4696 if (SimplifySelectOps(N, N2, N3))
4697 return SDValue(N, 0); // Don't revisit N.
4699 // fold select_cc into other things, such as min/max/abs
4700 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4703 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4704 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4705 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4709 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4710 // dag node into a ConstantSDNode or a build_vector of constants.
4711 // This function is called by the DAGCombiner when visiting sext/zext/aext
4712 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4713 // Vector extends are not folded if operations are legal; this is to
4714 // avoid introducing illegal build_vector dag nodes.
4715 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4716 SelectionDAG &DAG, bool LegalTypes,
4717 bool LegalOperations) {
4718 unsigned Opcode = N->getOpcode();
4719 SDValue N0 = N->getOperand(0);
4720 EVT VT = N->getValueType(0);
4722 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4723 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4725 // fold (sext c1) -> c1
4726 // fold (zext c1) -> c1
4727 // fold (aext c1) -> c1
4728 if (isa<ConstantSDNode>(N0))
4729 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4731 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4732 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4733 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4734 EVT SVT = VT.getScalarType();
4735 if (!(VT.isVector() &&
4736 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4737 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4740 // We can fold this node into a build_vector.
4741 unsigned VTBits = SVT.getSizeInBits();
4742 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4743 unsigned ShAmt = VTBits - EVTBits;
4744 SmallVector<SDValue, 8> Elts;
4745 unsigned NumElts = N0->getNumOperands();
4748 for (unsigned i=0; i != NumElts; ++i) {
4749 SDValue Op = N0->getOperand(i);
4750 if (Op->getOpcode() == ISD::UNDEF) {
4751 Elts.push_back(DAG.getUNDEF(SVT));
4755 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4756 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4757 if (Opcode == ISD::SIGN_EXTEND)
4758 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4761 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4765 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], NumElts).getNode();
4768 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4769 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4770 // transformation. Returns true if extension are possible and the above
4771 // mentioned transformation is profitable.
4772 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4774 SmallVectorImpl<SDNode *> &ExtendNodes,
4775 const TargetLowering &TLI) {
4776 bool HasCopyToRegUses = false;
4777 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4778 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4779 UE = N0.getNode()->use_end();
4784 if (UI.getUse().getResNo() != N0.getResNo())
4786 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4787 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4788 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4789 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4790 // Sign bits will be lost after a zext.
4793 for (unsigned i = 0; i != 2; ++i) {
4794 SDValue UseOp = User->getOperand(i);
4797 if (!isa<ConstantSDNode>(UseOp))
4802 ExtendNodes.push_back(User);
4805 // If truncates aren't free and there are users we can't
4806 // extend, it isn't worthwhile.
4809 // Remember if this value is live-out.
4810 if (User->getOpcode() == ISD::CopyToReg)
4811 HasCopyToRegUses = true;
4814 if (HasCopyToRegUses) {
4815 bool BothLiveOut = false;
4816 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4818 SDUse &Use = UI.getUse();
4819 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4825 // Both unextended and extended values are live out. There had better be
4826 // a good reason for the transformation.
4827 return ExtendNodes.size();
4832 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4833 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4834 ISD::NodeType ExtType) {
4835 // Extend SetCC uses if necessary.
4836 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4837 SDNode *SetCC = SetCCs[i];
4838 SmallVector<SDValue, 4> Ops;
4840 for (unsigned j = 0; j != 2; ++j) {
4841 SDValue SOp = SetCC->getOperand(j);
4843 Ops.push_back(ExtLoad);
4845 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4848 Ops.push_back(SetCC->getOperand(2));
4849 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4850 &Ops[0], Ops.size()));
4854 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4855 SDValue N0 = N->getOperand(0);
4856 EVT VT = N->getValueType(0);
4858 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4860 return SDValue(Res, 0);
4862 // fold (sext (sext x)) -> (sext x)
4863 // fold (sext (aext x)) -> (sext x)
4864 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4865 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4868 if (N0.getOpcode() == ISD::TRUNCATE) {
4869 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4870 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4871 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4872 if (NarrowLoad.getNode()) {
4873 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4874 if (NarrowLoad.getNode() != N0.getNode()) {
4875 CombineTo(N0.getNode(), NarrowLoad);
4876 // CombineTo deleted the truncate, if needed, but not what's under it.
4879 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4882 // See if the value being truncated is already sign extended. If so, just
4883 // eliminate the trunc/sext pair.
4884 SDValue Op = N0.getOperand(0);
4885 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4886 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4887 unsigned DestBits = VT.getScalarType().getSizeInBits();
4888 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4890 if (OpBits == DestBits) {
4891 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4892 // bits, it is already ready.
4893 if (NumSignBits > DestBits-MidBits)
4895 } else if (OpBits < DestBits) {
4896 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4897 // bits, just sext from i32.
4898 if (NumSignBits > OpBits-MidBits)
4899 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4901 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4902 // bits, just truncate to i32.
4903 if (NumSignBits > OpBits-MidBits)
4904 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4907 // fold (sext (truncate x)) -> (sextinreg x).
4908 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4909 N0.getValueType())) {
4910 if (OpBits < DestBits)
4911 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4912 else if (OpBits > DestBits)
4913 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4914 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4915 DAG.getValueType(N0.getValueType()));
4919 // fold (sext (load x)) -> (sext (truncate (sextload x)))
4920 // None of the supported targets knows how to perform load and sign extend
4921 // on vectors in one instruction. We only perform this transformation on
4923 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4924 ISD::isUNINDEXEDLoad(N0.getNode()) &&
4925 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4926 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4927 bool DoXform = true;
4928 SmallVector<SDNode*, 4> SetCCs;
4929 if (!N0.hasOneUse())
4930 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4932 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4933 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4935 LN0->getBasePtr(), N0.getValueType(),
4936 LN0->getMemOperand());
4937 CombineTo(N, ExtLoad);
4938 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4939 N0.getValueType(), ExtLoad);
4940 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4941 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4943 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4947 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4948 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4949 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4950 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4951 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4952 EVT MemVT = LN0->getMemoryVT();
4953 if ((!LegalOperations && !LN0->isVolatile()) ||
4954 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4955 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4957 LN0->getBasePtr(), MemVT,
4958 LN0->getMemOperand());
4959 CombineTo(N, ExtLoad);
4960 CombineTo(N0.getNode(),
4961 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4962 N0.getValueType(), ExtLoad),
4963 ExtLoad.getValue(1));
4964 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4968 // fold (sext (and/or/xor (load x), cst)) ->
4969 // (and/or/xor (sextload x), (sext cst))
4970 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4971 N0.getOpcode() == ISD::XOR) &&
4972 isa<LoadSDNode>(N0.getOperand(0)) &&
4973 N0.getOperand(1).getOpcode() == ISD::Constant &&
4974 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4975 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4976 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4977 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
4978 bool DoXform = true;
4979 SmallVector<SDNode*, 4> SetCCs;
4980 if (!N0.hasOneUse())
4981 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4984 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
4985 LN0->getChain(), LN0->getBasePtr(),
4987 LN0->getMemOperand());
4988 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4989 Mask = Mask.sext(VT.getSizeInBits());
4990 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4991 ExtLoad, DAG.getConstant(Mask, VT));
4992 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4993 SDLoc(N0.getOperand(0)),
4994 N0.getOperand(0).getValueType(), ExtLoad);
4996 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4997 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4999 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5004 if (N0.getOpcode() == ISD::SETCC) {
5005 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5006 // Only do this before legalize for now.
5007 if (VT.isVector() && !LegalOperations &&
5008 TLI.getBooleanContents(true) ==
5009 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5010 EVT N0VT = N0.getOperand(0).getValueType();
5011 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5012 // of the same size as the compared operands. Only optimize sext(setcc())
5013 // if this is the case.
5014 EVT SVT = getSetCCResultType(N0VT);
5016 // We know that the # elements of the results is the same as the
5017 // # elements of the compare (and the # elements of the compare result
5018 // for that matter). Check to see that they are the same size. If so,
5019 // we know that the element size of the sext'd result matches the
5020 // element size of the compare operands.
5021 if (VT.getSizeInBits() == SVT.getSizeInBits())
5022 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5024 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5026 // If the desired elements are smaller or larger than the source
5027 // elements we can use a matching integer vector type and then
5028 // truncate/sign extend
5029 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5030 if (SVT == MatchingVectorType) {
5031 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5032 N0.getOperand(0), N0.getOperand(1),
5033 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5034 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5038 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5039 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5041 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5043 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5044 NegOne, DAG.getConstant(0, VT),
5045 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5046 if (SCC.getNode()) return SCC;
5048 if (!VT.isVector()) {
5049 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5050 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5052 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5053 SDValue SetCC = DAG.getSetCC(DL,
5055 N0.getOperand(0), N0.getOperand(1), CC);
5056 EVT SelectVT = getSetCCResultType(VT);
5057 return DAG.getSelect(DL, VT,
5058 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5059 NegOne, DAG.getConstant(0, VT));
5065 // fold (sext x) -> (zext x) if the sign bit is known zero.
5066 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5067 DAG.SignBitIsZero(N0))
5068 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5073 // isTruncateOf - If N is a truncate of some other value, return true, record
5074 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5075 // This function computes KnownZero to avoid a duplicated call to
5076 // ComputeMaskedBits in the caller.
5077 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5080 if (N->getOpcode() == ISD::TRUNCATE) {
5081 Op = N->getOperand(0);
5082 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5086 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5087 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5090 SDValue Op0 = N->getOperand(0);
5091 SDValue Op1 = N->getOperand(1);
5092 assert(Op0.getValueType() == Op1.getValueType());
5094 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5095 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5096 if (COp0 && COp0->isNullValue())
5098 else if (COp1 && COp1->isNullValue())
5103 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5105 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5111 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5112 SDValue N0 = N->getOperand(0);
5113 EVT VT = N->getValueType(0);
5115 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5117 return SDValue(Res, 0);
5119 // fold (zext (zext x)) -> (zext x)
5120 // fold (zext (aext x)) -> (zext x)
5121 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5122 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5125 // fold (zext (truncate x)) -> (zext x) or
5126 // (zext (truncate x)) -> (truncate x)
5127 // This is valid when the truncated bits of x are already zero.
5128 // FIXME: We should extend this to work for vectors too.
5131 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5132 APInt TruncatedBits =
5133 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5134 APInt(Op.getValueSizeInBits(), 0) :
5135 APInt::getBitsSet(Op.getValueSizeInBits(),
5136 N0.getValueSizeInBits(),
5137 std::min(Op.getValueSizeInBits(),
5138 VT.getSizeInBits()));
5139 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5140 if (VT.bitsGT(Op.getValueType()))
5141 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5142 if (VT.bitsLT(Op.getValueType()))
5143 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5149 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5150 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5151 if (N0.getOpcode() == ISD::TRUNCATE) {
5152 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5153 if (NarrowLoad.getNode()) {
5154 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5155 if (NarrowLoad.getNode() != N0.getNode()) {
5156 CombineTo(N0.getNode(), NarrowLoad);
5157 // CombineTo deleted the truncate, if needed, but not what's under it.
5160 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5164 // fold (zext (truncate x)) -> (and x, mask)
5165 if (N0.getOpcode() == ISD::TRUNCATE &&
5166 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5168 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5169 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5170 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5171 if (NarrowLoad.getNode()) {
5172 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5173 if (NarrowLoad.getNode() != N0.getNode()) {
5174 CombineTo(N0.getNode(), NarrowLoad);
5175 // CombineTo deleted the truncate, if needed, but not what's under it.
5178 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5181 SDValue Op = N0.getOperand(0);
5182 if (Op.getValueType().bitsLT(VT)) {
5183 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5184 AddToWorkList(Op.getNode());
5185 } else if (Op.getValueType().bitsGT(VT)) {
5186 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5187 AddToWorkList(Op.getNode());
5189 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5190 N0.getValueType().getScalarType());
5193 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5194 // if either of the casts is not free.
5195 if (N0.getOpcode() == ISD::AND &&
5196 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5197 N0.getOperand(1).getOpcode() == ISD::Constant &&
5198 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5199 N0.getValueType()) ||
5200 !TLI.isZExtFree(N0.getValueType(), VT))) {
5201 SDValue X = N0.getOperand(0).getOperand(0);
5202 if (X.getValueType().bitsLT(VT)) {
5203 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5204 } else if (X.getValueType().bitsGT(VT)) {
5205 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5207 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5208 Mask = Mask.zext(VT.getSizeInBits());
5209 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5210 X, DAG.getConstant(Mask, VT));
5213 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5214 // None of the supported targets knows how to perform load and vector_zext
5215 // on vectors in one instruction. We only perform this transformation on
5217 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5218 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5219 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5220 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5221 bool DoXform = true;
5222 SmallVector<SDNode*, 4> SetCCs;
5223 if (!N0.hasOneUse())
5224 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5226 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5227 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5229 LN0->getBasePtr(), N0.getValueType(),
5230 LN0->getMemOperand());
5231 CombineTo(N, ExtLoad);
5232 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5233 N0.getValueType(), ExtLoad);
5234 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5236 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5238 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5242 // fold (zext (and/or/xor (load x), cst)) ->
5243 // (and/or/xor (zextload x), (zext cst))
5244 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5245 N0.getOpcode() == ISD::XOR) &&
5246 isa<LoadSDNode>(N0.getOperand(0)) &&
5247 N0.getOperand(1).getOpcode() == ISD::Constant &&
5248 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5249 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5250 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5251 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5252 bool DoXform = true;
5253 SmallVector<SDNode*, 4> SetCCs;
5254 if (!N0.hasOneUse())
5255 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5258 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5259 LN0->getChain(), LN0->getBasePtr(),
5261 LN0->getMemOperand());
5262 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5263 Mask = Mask.zext(VT.getSizeInBits());
5264 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5265 ExtLoad, DAG.getConstant(Mask, VT));
5266 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5267 SDLoc(N0.getOperand(0)),
5268 N0.getOperand(0).getValueType(), ExtLoad);
5270 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5271 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5273 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5278 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5279 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5280 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5281 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5282 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5283 EVT MemVT = LN0->getMemoryVT();
5284 if ((!LegalOperations && !LN0->isVolatile()) ||
5285 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5286 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5288 LN0->getBasePtr(), MemVT,
5289 LN0->getMemOperand());
5290 CombineTo(N, ExtLoad);
5291 CombineTo(N0.getNode(),
5292 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5294 ExtLoad.getValue(1));
5295 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5299 if (N0.getOpcode() == ISD::SETCC) {
5300 if (!LegalOperations && VT.isVector() &&
5301 N0.getValueType().getVectorElementType() == MVT::i1) {
5302 EVT N0VT = N0.getOperand(0).getValueType();
5303 if (getSetCCResultType(N0VT) == N0.getValueType())
5306 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5307 // Only do this before legalize for now.
5308 EVT EltVT = VT.getVectorElementType();
5309 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5310 DAG.getConstant(1, EltVT));
5311 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5312 // We know that the # elements of the results is the same as the
5313 // # elements of the compare (and the # elements of the compare result
5314 // for that matter). Check to see that they are the same size. If so,
5315 // we know that the element size of the sext'd result matches the
5316 // element size of the compare operands.
5317 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5318 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5320 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5321 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5322 &OneOps[0], OneOps.size()));
5324 // If the desired elements are smaller or larger than the source
5325 // elements we can use a matching integer vector type and then
5326 // truncate/sign extend
5327 EVT MatchingElementType =
5328 EVT::getIntegerVT(*DAG.getContext(),
5329 N0VT.getScalarType().getSizeInBits());
5330 EVT MatchingVectorType =
5331 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5332 N0VT.getVectorNumElements());
5334 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5336 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5337 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5338 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5339 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5340 &OneOps[0], OneOps.size()));
5343 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5345 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5346 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5347 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5348 if (SCC.getNode()) return SCC;
5351 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5352 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5353 isa<ConstantSDNode>(N0.getOperand(1)) &&
5354 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5356 SDValue ShAmt = N0.getOperand(1);
5357 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5358 if (N0.getOpcode() == ISD::SHL) {
5359 SDValue InnerZExt = N0.getOperand(0);
5360 // If the original shl may be shifting out bits, do not perform this
5362 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5363 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5364 if (ShAmtVal > KnownZeroBits)
5370 // Ensure that the shift amount is wide enough for the shifted value.
5371 if (VT.getSizeInBits() >= 256)
5372 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5374 return DAG.getNode(N0.getOpcode(), DL, VT,
5375 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5382 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5383 SDValue N0 = N->getOperand(0);
5384 EVT VT = N->getValueType(0);
5386 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5388 return SDValue(Res, 0);
5390 // fold (aext (aext x)) -> (aext x)
5391 // fold (aext (zext x)) -> (zext x)
5392 // fold (aext (sext x)) -> (sext x)
5393 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5394 N0.getOpcode() == ISD::ZERO_EXTEND ||
5395 N0.getOpcode() == ISD::SIGN_EXTEND)
5396 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5398 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5399 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5400 if (N0.getOpcode() == ISD::TRUNCATE) {
5401 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5402 if (NarrowLoad.getNode()) {
5403 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5404 if (NarrowLoad.getNode() != N0.getNode()) {
5405 CombineTo(N0.getNode(), NarrowLoad);
5406 // CombineTo deleted the truncate, if needed, but not what's under it.
5409 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5413 // fold (aext (truncate x))
5414 if (N0.getOpcode() == ISD::TRUNCATE) {
5415 SDValue TruncOp = N0.getOperand(0);
5416 if (TruncOp.getValueType() == VT)
5417 return TruncOp; // x iff x size == zext size.
5418 if (TruncOp.getValueType().bitsGT(VT))
5419 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5420 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5423 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5424 // if the trunc is not free.
5425 if (N0.getOpcode() == ISD::AND &&
5426 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5427 N0.getOperand(1).getOpcode() == ISD::Constant &&
5428 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5429 N0.getValueType())) {
5430 SDValue X = N0.getOperand(0).getOperand(0);
5431 if (X.getValueType().bitsLT(VT)) {
5432 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5433 } else if (X.getValueType().bitsGT(VT)) {
5434 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5436 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5437 Mask = Mask.zext(VT.getSizeInBits());
5438 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5439 X, DAG.getConstant(Mask, VT));
5442 // fold (aext (load x)) -> (aext (truncate (extload x)))
5443 // None of the supported targets knows how to perform load and any_ext
5444 // on vectors in one instruction. We only perform this transformation on
5446 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5447 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5448 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5449 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5450 bool DoXform = true;
5451 SmallVector<SDNode*, 4> SetCCs;
5452 if (!N0.hasOneUse())
5453 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5455 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5456 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5458 LN0->getBasePtr(), N0.getValueType(),
5459 LN0->getMemOperand());
5460 CombineTo(N, ExtLoad);
5461 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5462 N0.getValueType(), ExtLoad);
5463 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5464 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5466 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5470 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5471 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5472 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5473 if (N0.getOpcode() == ISD::LOAD &&
5474 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5476 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5477 ISD::LoadExtType ExtType = LN0->getExtensionType();
5478 EVT MemVT = LN0->getMemoryVT();
5479 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5480 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5481 VT, LN0->getChain(), LN0->getBasePtr(),
5482 MemVT, LN0->getMemOperand());
5483 CombineTo(N, ExtLoad);
5484 CombineTo(N0.getNode(),
5485 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5486 N0.getValueType(), ExtLoad),
5487 ExtLoad.getValue(1));
5488 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5492 if (N0.getOpcode() == ISD::SETCC) {
5494 // aext(setcc) -> vsetcc
5495 // aext(setcc) -> truncate(vsetcc)
5496 // aext(setcc) -> aext(vsetcc)
5497 // Only do this before legalize for now.
5498 if (VT.isVector() && !LegalOperations) {
5499 EVT N0VT = N0.getOperand(0).getValueType();
5500 // We know that the # elements of the results is the same as the
5501 // # elements of the compare (and the # elements of the compare result
5502 // for that matter). Check to see that they are the same size. If so,
5503 // we know that the element size of the sext'd result matches the
5504 // element size of the compare operands.
5505 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5506 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5508 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5509 // If the desired elements are smaller or larger than the source
5510 // elements we can use a matching integer vector type and then
5511 // truncate/any extend
5513 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5515 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5517 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5518 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5522 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5524 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5525 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5526 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5534 /// GetDemandedBits - See if the specified operand can be simplified with the
5535 /// knowledge that only the bits specified by Mask are used. If so, return the
5536 /// simpler operand, otherwise return a null SDValue.
5537 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5538 switch (V.getOpcode()) {
5540 case ISD::Constant: {
5541 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5542 assert(CV && "Const value should be ConstSDNode.");
5543 const APInt &CVal = CV->getAPIntValue();
5544 APInt NewVal = CVal & Mask;
5546 return DAG.getConstant(NewVal, V.getValueType());
5551 // If the LHS or RHS don't contribute bits to the or, drop them.
5552 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5553 return V.getOperand(1);
5554 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5555 return V.getOperand(0);
5558 // Only look at single-use SRLs.
5559 if (!V.getNode()->hasOneUse())
5561 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5562 // See if we can recursively simplify the LHS.
5563 unsigned Amt = RHSC->getZExtValue();
5565 // Watch out for shift count overflow though.
5566 if (Amt >= Mask.getBitWidth()) break;
5567 APInt NewMask = Mask << Amt;
5568 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5569 if (SimplifyLHS.getNode())
5570 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5571 SimplifyLHS, V.getOperand(1));
5577 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5578 /// bits and then truncated to a narrower type and where N is a multiple
5579 /// of number of bits of the narrower type, transform it to a narrower load
5580 /// from address + N / num of bits of new type. If the result is to be
5581 /// extended, also fold the extension to form a extending load.
5582 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5583 unsigned Opc = N->getOpcode();
5585 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5586 SDValue N0 = N->getOperand(0);
5587 EVT VT = N->getValueType(0);
5590 // This transformation isn't valid for vector loads.
5594 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5596 if (Opc == ISD::SIGN_EXTEND_INREG) {
5597 ExtType = ISD::SEXTLOAD;
5598 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5599 } else if (Opc == ISD::SRL) {
5600 // Another special-case: SRL is basically zero-extending a narrower value.
5601 ExtType = ISD::ZEXTLOAD;
5603 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5604 if (!N01) return SDValue();
5605 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5606 VT.getSizeInBits() - N01->getZExtValue());
5608 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5611 unsigned EVTBits = ExtVT.getSizeInBits();
5613 // Do not generate loads of non-round integer types since these can
5614 // be expensive (and would be wrong if the type is not byte sized).
5615 if (!ExtVT.isRound())
5619 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5620 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5621 ShAmt = N01->getZExtValue();
5622 // Is the shift amount a multiple of size of VT?
5623 if ((ShAmt & (EVTBits-1)) == 0) {
5624 N0 = N0.getOperand(0);
5625 // Is the load width a multiple of size of VT?
5626 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5630 // At this point, we must have a load or else we can't do the transform.
5631 if (!isa<LoadSDNode>(N0)) return SDValue();
5633 // Because a SRL must be assumed to *need* to zero-extend the high bits
5634 // (as opposed to anyext the high bits), we can't combine the zextload
5635 // lowering of SRL and an sextload.
5636 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5639 // If the shift amount is larger than the input type then we're not
5640 // accessing any of the loaded bytes. If the load was a zextload/extload
5641 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5642 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5647 // If the load is shifted left (and the result isn't shifted back right),
5648 // we can fold the truncate through the shift.
5649 unsigned ShLeftAmt = 0;
5650 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5651 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5652 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5653 ShLeftAmt = N01->getZExtValue();
5654 N0 = N0.getOperand(0);
5658 // If we haven't found a load, we can't narrow it. Don't transform one with
5659 // multiple uses, this would require adding a new load.
5660 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5663 // Don't change the width of a volatile load.
5664 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5665 if (LN0->isVolatile())
5668 // Verify that we are actually reducing a load width here.
5669 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5672 // For the transform to be legal, the load must produce only two values
5673 // (the value loaded and the chain). Don't transform a pre-increment
5674 // load, for example, which produces an extra value. Otherwise the
5675 // transformation is not equivalent, and the downstream logic to replace
5676 // uses gets things wrong.
5677 if (LN0->getNumValues() > 2)
5680 // If the load that we're shrinking is an extload and we're not just
5681 // discarding the extension we can't simply shrink the load. Bail.
5682 // TODO: It would be possible to merge the extensions in some cases.
5683 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5684 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5687 EVT PtrType = N0.getOperand(1).getValueType();
5689 if (PtrType == MVT::Untyped || PtrType.isExtended())
5690 // It's not possible to generate a constant of extended or untyped type.
5693 // For big endian targets, we need to adjust the offset to the pointer to
5694 // load the correct bytes.
5695 if (TLI.isBigEndian()) {
5696 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5697 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5698 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5701 uint64_t PtrOff = ShAmt / 8;
5702 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5703 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5704 PtrType, LN0->getBasePtr(),
5705 DAG.getConstant(PtrOff, PtrType));
5706 AddToWorkList(NewPtr.getNode());
5709 if (ExtType == ISD::NON_EXTLOAD)
5710 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5711 LN0->getPointerInfo().getWithOffset(PtrOff),
5712 LN0->isVolatile(), LN0->isNonTemporal(),
5713 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5715 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5716 LN0->getPointerInfo().getWithOffset(PtrOff),
5717 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5718 NewAlign, LN0->getTBAAInfo());
5720 // Replace the old load's chain with the new load's chain.
5721 WorkListRemover DeadNodes(*this);
5722 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5724 // Shift the result left, if we've swallowed a left shift.
5725 SDValue Result = Load;
5726 if (ShLeftAmt != 0) {
5727 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5728 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5730 // If the shift amount is as large as the result size (but, presumably,
5731 // no larger than the source) then the useful bits of the result are
5732 // zero; we can't simply return the shortened shift, because the result
5733 // of that operation is undefined.
5734 if (ShLeftAmt >= VT.getSizeInBits())
5735 Result = DAG.getConstant(0, VT);
5737 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5738 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5741 // Return the new loaded value.
5745 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5746 SDValue N0 = N->getOperand(0);
5747 SDValue N1 = N->getOperand(1);
5748 EVT VT = N->getValueType(0);
5749 EVT EVT = cast<VTSDNode>(N1)->getVT();
5750 unsigned VTBits = VT.getScalarType().getSizeInBits();
5751 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5753 // fold (sext_in_reg c1) -> c1
5754 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5755 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5757 // If the input is already sign extended, just drop the extension.
5758 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5761 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5762 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5763 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5764 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5765 N0.getOperand(0), N1);
5767 // fold (sext_in_reg (sext x)) -> (sext x)
5768 // fold (sext_in_reg (aext x)) -> (sext x)
5769 // if x is small enough.
5770 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5771 SDValue N00 = N0.getOperand(0);
5772 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5773 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5774 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5777 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5778 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5779 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5781 // fold operands of sext_in_reg based on knowledge that the top bits are not
5783 if (SimplifyDemandedBits(SDValue(N, 0)))
5784 return SDValue(N, 0);
5786 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5787 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5788 SDValue NarrowLoad = ReduceLoadWidth(N);
5789 if (NarrowLoad.getNode())
5792 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5793 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5794 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5795 if (N0.getOpcode() == ISD::SRL) {
5796 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5797 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5798 // We can turn this into an SRA iff the input to the SRL is already sign
5800 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5801 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5802 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5803 N0.getOperand(0), N0.getOperand(1));
5807 // fold (sext_inreg (extload x)) -> (sextload x)
5808 if (ISD::isEXTLoad(N0.getNode()) &&
5809 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5810 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5811 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5812 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5813 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5814 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5816 LN0->getBasePtr(), EVT,
5817 LN0->getMemOperand());
5818 CombineTo(N, ExtLoad);
5819 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5820 AddToWorkList(ExtLoad.getNode());
5821 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5823 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5824 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5826 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5827 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5828 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5829 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5830 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5832 LN0->getBasePtr(), EVT,
5833 LN0->getMemOperand());
5834 CombineTo(N, ExtLoad);
5835 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5836 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5839 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5840 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5841 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5842 N0.getOperand(1), false);
5843 if (BSwap.getNode())
5844 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5848 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5849 // into a build_vector.
5850 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5851 SmallVector<SDValue, 8> Elts;
5852 unsigned NumElts = N0->getNumOperands();
5853 unsigned ShAmt = VTBits - EVTBits;
5855 for (unsigned i = 0; i != NumElts; ++i) {
5856 SDValue Op = N0->getOperand(i);
5857 if (Op->getOpcode() == ISD::UNDEF) {
5862 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5863 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5864 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5865 Op.getValueType()));
5868 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Elts[0], NumElts);
5874 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5875 SDValue N0 = N->getOperand(0);
5876 EVT VT = N->getValueType(0);
5877 bool isLE = TLI.isLittleEndian();
5880 if (N0.getValueType() == N->getValueType(0))
5882 // fold (truncate c1) -> c1
5883 if (isa<ConstantSDNode>(N0))
5884 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5885 // fold (truncate (truncate x)) -> (truncate x)
5886 if (N0.getOpcode() == ISD::TRUNCATE)
5887 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5888 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5889 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5890 N0.getOpcode() == ISD::SIGN_EXTEND ||
5891 N0.getOpcode() == ISD::ANY_EXTEND) {
5892 if (N0.getOperand(0).getValueType().bitsLT(VT))
5893 // if the source is smaller than the dest, we still need an extend
5894 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5896 if (N0.getOperand(0).getValueType().bitsGT(VT))
5897 // if the source is larger than the dest, than we just need the truncate
5898 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5899 // if the source and dest are the same type, we can drop both the extend
5900 // and the truncate.
5901 return N0.getOperand(0);
5904 // Fold extract-and-trunc into a narrow extract. For example:
5905 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5906 // i32 y = TRUNCATE(i64 x)
5908 // v16i8 b = BITCAST (v2i64 val)
5909 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5911 // Note: We only run this optimization after type legalization (which often
5912 // creates this pattern) and before operation legalization after which
5913 // we need to be more careful about the vector instructions that we generate.
5914 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5915 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
5917 EVT VecTy = N0.getOperand(0).getValueType();
5918 EVT ExTy = N0.getValueType();
5919 EVT TrTy = N->getValueType(0);
5921 unsigned NumElem = VecTy.getVectorNumElements();
5922 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5924 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5925 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5927 SDValue EltNo = N0->getOperand(1);
5928 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5929 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5930 EVT IndexTy = TLI.getVectorIdxTy();
5931 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5933 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5934 NVT, N0.getOperand(0));
5936 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5938 DAG.getConstant(Index, IndexTy));
5942 // Fold a series of buildvector, bitcast, and truncate if possible.
5944 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5945 // (2xi32 (buildvector x, y)).
5946 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5947 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5948 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5949 N0.getOperand(0).hasOneUse()) {
5951 SDValue BuildVect = N0.getOperand(0);
5952 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5953 EVT TruncVecEltTy = VT.getVectorElementType();
5955 // Check that the element types match.
5956 if (BuildVectEltTy == TruncVecEltTy) {
5957 // Now we only need to compute the offset of the truncated elements.
5958 unsigned BuildVecNumElts = BuildVect.getNumOperands();
5959 unsigned TruncVecNumElts = VT.getVectorNumElements();
5960 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5962 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5963 "Invalid number of elements");
5965 SmallVector<SDValue, 8> Opnds;
5966 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5967 Opnds.push_back(BuildVect.getOperand(i));
5969 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
5974 // See if we can simplify the input to this truncate through knowledge that
5975 // only the low bits are being used.
5976 // For example "trunc (or (shl x, 8), y)" // -> trunc y
5977 // Currently we only perform this optimization on scalars because vectors
5978 // may have different active low bits.
5979 if (!VT.isVector()) {
5981 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5982 VT.getSizeInBits()));
5983 if (Shorter.getNode())
5984 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
5986 // fold (truncate (load x)) -> (smaller load x)
5987 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5988 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5989 SDValue Reduced = ReduceLoadWidth(N);
5990 if (Reduced.getNode())
5992 // Handle the case where the load remains an extending load even
5993 // after truncation.
5994 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
5995 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5996 if (!LN0->isVolatile() &&
5997 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
5998 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
5999 VT, LN0->getChain(), LN0->getBasePtr(),
6001 LN0->getMemOperand());
6002 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6007 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6008 // where ... are all 'undef'.
6009 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6010 SmallVector<EVT, 8> VTs;
6013 unsigned NumDefs = 0;
6015 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6016 SDValue X = N0.getOperand(i);
6017 if (X.getOpcode() != ISD::UNDEF) {
6022 // Stop if more than one members are non-undef.
6025 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6026 VT.getVectorElementType(),
6027 X.getValueType().getVectorNumElements()));
6031 return DAG.getUNDEF(VT);
6034 assert(V.getNode() && "The single defined operand is empty!");
6035 SmallVector<SDValue, 8> Opnds;
6036 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6038 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6041 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6042 AddToWorkList(NV.getNode());
6043 Opnds.push_back(NV);
6045 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
6046 &Opnds[0], Opnds.size());
6050 // Simplify the operands using demanded-bits information.
6051 if (!VT.isVector() &&
6052 SimplifyDemandedBits(SDValue(N, 0)))
6053 return SDValue(N, 0);
6058 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6059 SDValue Elt = N->getOperand(i);
6060 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6061 return Elt.getNode();
6062 return Elt.getOperand(Elt.getResNo()).getNode();
6065 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6066 /// if load locations are consecutive.
6067 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6068 assert(N->getOpcode() == ISD::BUILD_PAIR);
6070 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6071 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6072 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6073 LD1->getAddressSpace() != LD2->getAddressSpace())
6075 EVT LD1VT = LD1->getValueType(0);
6077 if (ISD::isNON_EXTLoad(LD2) &&
6079 // If both are volatile this would reduce the number of volatile loads.
6080 // If one is volatile it might be ok, but play conservative and bail out.
6081 !LD1->isVolatile() &&
6082 !LD2->isVolatile() &&
6083 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6084 unsigned Align = LD1->getAlignment();
6085 unsigned NewAlign = TLI.getDataLayout()->
6086 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6088 if (NewAlign <= Align &&
6089 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6090 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6091 LD1->getBasePtr(), LD1->getPointerInfo(),
6092 false, false, false, Align);
6098 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6099 SDValue N0 = N->getOperand(0);
6100 EVT VT = N->getValueType(0);
6102 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6103 // Only do this before legalize, since afterward the target may be depending
6104 // on the bitconvert.
6105 // First check to see if this is all constant.
6107 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6109 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6111 EVT DestEltVT = N->getValueType(0).getVectorElementType();
6112 assert(!DestEltVT.isVector() &&
6113 "Element type of vector ValueType must not be vector!");
6115 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6118 // If the input is a constant, let getNode fold it.
6119 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6120 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6121 if (Res.getNode() != N) {
6122 if (!LegalOperations ||
6123 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6126 // Folding it resulted in an illegal node, and it's too late to
6127 // do that. Clean up the old node and forego the transformation.
6128 // Ideally this won't happen very often, because instcombine
6129 // and the earlier dagcombine runs (where illegal nodes are
6130 // permitted) should have folded most of them already.
6131 DAG.DeleteNode(Res.getNode());
6135 // (conv (conv x, t1), t2) -> (conv x, t2)
6136 if (N0.getOpcode() == ISD::BITCAST)
6137 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6140 // fold (conv (load x)) -> (load (conv*)x)
6141 // If the resultant load doesn't need a higher alignment than the original!
6142 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6143 // Do not change the width of a volatile load.
6144 !cast<LoadSDNode>(N0)->isVolatile() &&
6145 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6146 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6147 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6148 unsigned Align = TLI.getDataLayout()->
6149 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6150 unsigned OrigAlign = LN0->getAlignment();
6152 if (Align <= OrigAlign) {
6153 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6154 LN0->getBasePtr(), LN0->getPointerInfo(),
6155 LN0->isVolatile(), LN0->isNonTemporal(),
6156 LN0->isInvariant(), OrigAlign,
6157 LN0->getTBAAInfo());
6159 CombineTo(N0.getNode(),
6160 DAG.getNode(ISD::BITCAST, SDLoc(N0),
6161 N0.getValueType(), Load),
6167 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6168 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6169 // This often reduces constant pool loads.
6170 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6171 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6172 N0.getNode()->hasOneUse() && VT.isInteger() &&
6173 !VT.isVector() && !N0.getValueType().isVector()) {
6174 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6176 AddToWorkList(NewConv.getNode());
6178 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6179 if (N0.getOpcode() == ISD::FNEG)
6180 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6181 NewConv, DAG.getConstant(SignBit, VT));
6182 assert(N0.getOpcode() == ISD::FABS);
6183 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6184 NewConv, DAG.getConstant(~SignBit, VT));
6187 // fold (bitconvert (fcopysign cst, x)) ->
6188 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6189 // Note that we don't handle (copysign x, cst) because this can always be
6190 // folded to an fneg or fabs.
6191 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6192 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6193 VT.isInteger() && !VT.isVector()) {
6194 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6195 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6196 if (isTypeLegal(IntXVT)) {
6197 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6198 IntXVT, N0.getOperand(1));
6199 AddToWorkList(X.getNode());
6201 // If X has a different width than the result/lhs, sext it or truncate it.
6202 unsigned VTWidth = VT.getSizeInBits();
6203 if (OrigXWidth < VTWidth) {
6204 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6205 AddToWorkList(X.getNode());
6206 } else if (OrigXWidth > VTWidth) {
6207 // To get the sign bit in the right place, we have to shift it right
6208 // before truncating.
6209 X = DAG.getNode(ISD::SRL, SDLoc(X),
6210 X.getValueType(), X,
6211 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6212 AddToWorkList(X.getNode());
6213 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6214 AddToWorkList(X.getNode());
6217 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6218 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6219 X, DAG.getConstant(SignBit, VT));
6220 AddToWorkList(X.getNode());
6222 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6223 VT, N0.getOperand(0));
6224 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6225 Cst, DAG.getConstant(~SignBit, VT));
6226 AddToWorkList(Cst.getNode());
6228 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6232 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6233 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6234 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6235 if (CombineLD.getNode())
6242 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6243 EVT VT = N->getValueType(0);
6244 return CombineConsecutiveLoads(N, VT);
6247 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6248 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
6249 /// destination element value type.
6250 SDValue DAGCombiner::
6251 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6252 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6254 // If this is already the right type, we're done.
6255 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6257 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6258 unsigned DstBitSize = DstEltVT.getSizeInBits();
6260 // If this is a conversion of N elements of one type to N elements of another
6261 // type, convert each element. This handles FP<->INT cases.
6262 if (SrcBitSize == DstBitSize) {
6263 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6264 BV->getValueType(0).getVectorNumElements());
6266 // Due to the FP element handling below calling this routine recursively,
6267 // we can end up with a scalar-to-vector node here.
6268 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6269 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6270 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6271 DstEltVT, BV->getOperand(0)));
6273 SmallVector<SDValue, 8> Ops;
6274 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6275 SDValue Op = BV->getOperand(i);
6276 // If the vector element type is not legal, the BUILD_VECTOR operands
6277 // are promoted and implicitly truncated. Make that explicit here.
6278 if (Op.getValueType() != SrcEltVT)
6279 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6280 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6282 AddToWorkList(Ops.back().getNode());
6284 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6285 &Ops[0], Ops.size());
6288 // Otherwise, we're growing or shrinking the elements. To avoid having to
6289 // handle annoying details of growing/shrinking FP values, we convert them to
6291 if (SrcEltVT.isFloatingPoint()) {
6292 // Convert the input float vector to a int vector where the elements are the
6294 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6295 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6296 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6300 // Now we know the input is an integer vector. If the output is a FP type,
6301 // convert to integer first, then to FP of the right size.
6302 if (DstEltVT.isFloatingPoint()) {
6303 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6304 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6305 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6307 // Next, convert to FP elements of the same size.
6308 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6311 // Okay, we know the src/dst types are both integers of differing types.
6312 // Handling growing first.
6313 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6314 if (SrcBitSize < DstBitSize) {
6315 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6317 SmallVector<SDValue, 8> Ops;
6318 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6319 i += NumInputsPerOutput) {
6320 bool isLE = TLI.isLittleEndian();
6321 APInt NewBits = APInt(DstBitSize, 0);
6322 bool EltIsUndef = true;
6323 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6324 // Shift the previously computed bits over.
6325 NewBits <<= SrcBitSize;
6326 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6327 if (Op.getOpcode() == ISD::UNDEF) continue;
6330 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6331 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6335 Ops.push_back(DAG.getUNDEF(DstEltVT));
6337 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6340 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6341 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6342 &Ops[0], Ops.size());
6345 // Finally, this must be the case where we are shrinking elements: each input
6346 // turns into multiple outputs.
6347 bool isS2V = ISD::isScalarToVector(BV);
6348 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6349 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6350 NumOutputsPerInput*BV->getNumOperands());
6351 SmallVector<SDValue, 8> Ops;
6353 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6354 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6355 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6356 Ops.push_back(DAG.getUNDEF(DstEltVT));
6360 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6361 getAPIntValue().zextOrTrunc(SrcBitSize);
6363 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6364 APInt ThisVal = OpVal.trunc(DstBitSize);
6365 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6366 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6367 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6368 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6370 OpVal = OpVal.lshr(DstBitSize);
6373 // For big endian targets, swap the order of the pieces of each element.
6374 if (TLI.isBigEndian())
6375 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6378 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6379 &Ops[0], Ops.size());
6382 SDValue DAGCombiner::visitFADD(SDNode *N) {
6383 SDValue N0 = N->getOperand(0);
6384 SDValue N1 = N->getOperand(1);
6385 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6386 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6387 EVT VT = N->getValueType(0);
6390 if (VT.isVector()) {
6391 SDValue FoldedVOp = SimplifyVBinOp(N);
6392 if (FoldedVOp.getNode()) return FoldedVOp;
6395 // fold (fadd c1, c2) -> c1 + c2
6397 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6398 // canonicalize constant to RHS
6399 if (N0CFP && !N1CFP)
6400 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6401 // fold (fadd A, 0) -> A
6402 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6403 N1CFP->getValueAPF().isZero())
6405 // fold (fadd A, (fneg B)) -> (fsub A, B)
6406 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6407 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6408 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6409 GetNegatedExpression(N1, DAG, LegalOperations));
6410 // fold (fadd (fneg A), B) -> (fsub B, A)
6411 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6412 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6413 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6414 GetNegatedExpression(N0, DAG, LegalOperations));
6416 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6417 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6418 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6419 isa<ConstantFPSDNode>(N0.getOperand(1)))
6420 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6421 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6422 N0.getOperand(1), N1));
6424 // No FP constant should be created after legalization as Instruction
6425 // Selection pass has hard time in dealing with FP constant.
6427 // We don't need test this condition for transformation like following, as
6428 // the DAG being transformed implies it is legal to take FP constant as
6431 // (fadd (fmul c, x), x) -> (fmul c+1, x)
6433 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6435 // If allow, fold (fadd (fneg x), x) -> 0.0
6436 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6437 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6438 return DAG.getConstantFP(0.0, VT);
6440 // If allow, fold (fadd x, (fneg x)) -> 0.0
6441 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6442 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6443 return DAG.getConstantFP(0.0, VT);
6445 // In unsafe math mode, we can fold chains of FADD's of the same value
6446 // into multiplications. This transform is not safe in general because
6447 // we are reducing the number of rounding steps.
6448 if (DAG.getTarget().Options.UnsafeFPMath &&
6449 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6451 if (N0.getOpcode() == ISD::FMUL) {
6452 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6453 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6455 // (fadd (fmul c, x), x) -> (fmul x, c+1)
6456 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6457 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6459 DAG.getConstantFP(1.0, VT));
6460 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6464 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6465 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6466 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6468 DAG.getConstantFP(1.0, VT));
6469 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6473 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6474 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6475 N1.getOperand(0) == N1.getOperand(1) &&
6476 N0.getOperand(1) == 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(1), NewCFP);
6484 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6485 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6486 N1.getOperand(0) == N1.getOperand(1) &&
6487 N0.getOperand(0) == N1.getOperand(0)) {
6488 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6490 DAG.getConstantFP(2.0, VT));
6491 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6492 N0.getOperand(0), NewCFP);
6496 if (N1.getOpcode() == ISD::FMUL) {
6497 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6498 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6500 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6501 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6502 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6504 DAG.getConstantFP(1.0, VT));
6505 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6509 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6510 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6511 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6513 DAG.getConstantFP(1.0, VT));
6514 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6519 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6520 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6521 N0.getOperand(0) == N0.getOperand(1) &&
6522 N1.getOperand(1) == 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(1), NewCFP);
6530 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6531 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6532 N0.getOperand(0) == N0.getOperand(1) &&
6533 N1.getOperand(0) == N0.getOperand(0)) {
6534 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6536 DAG.getConstantFP(2.0, VT));
6537 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6538 N1.getOperand(0), NewCFP);
6542 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6543 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6544 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6545 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6546 (N0.getOperand(0) == N1))
6547 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6548 N1, DAG.getConstantFP(3.0, VT));
6551 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6552 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6553 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6554 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6555 N1.getOperand(0) == N0)
6556 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6557 N0, DAG.getConstantFP(3.0, VT));
6560 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6561 if (AllowNewFpConst &&
6562 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6563 N0.getOperand(0) == N0.getOperand(1) &&
6564 N1.getOperand(0) == N1.getOperand(1) &&
6565 N0.getOperand(0) == N1.getOperand(0))
6566 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6568 DAG.getConstantFP(4.0, VT));
6571 // FADD -> FMA combines:
6572 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6573 DAG.getTarget().Options.UnsafeFPMath) &&
6574 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6575 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6577 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6578 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6579 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6580 N0.getOperand(0), N0.getOperand(1), N1);
6582 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6583 // Note: Commutes FADD operands.
6584 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6585 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6586 N1.getOperand(0), N1.getOperand(1), N0);
6592 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6593 SDValue N0 = N->getOperand(0);
6594 SDValue N1 = N->getOperand(1);
6595 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6596 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6597 EVT VT = N->getValueType(0);
6601 if (VT.isVector()) {
6602 SDValue FoldedVOp = SimplifyVBinOp(N);
6603 if (FoldedVOp.getNode()) return FoldedVOp;
6606 // fold (fsub c1, c2) -> c1-c2
6608 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6609 // fold (fsub A, 0) -> A
6610 if (DAG.getTarget().Options.UnsafeFPMath &&
6611 N1CFP && N1CFP->getValueAPF().isZero())
6613 // fold (fsub 0, B) -> -B
6614 if (DAG.getTarget().Options.UnsafeFPMath &&
6615 N0CFP && N0CFP->getValueAPF().isZero()) {
6616 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6617 return GetNegatedExpression(N1, DAG, LegalOperations);
6618 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6619 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6621 // fold (fsub A, (fneg B)) -> (fadd A, B)
6622 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6623 return DAG.getNode(ISD::FADD, dl, VT, N0,
6624 GetNegatedExpression(N1, DAG, LegalOperations));
6626 // If 'unsafe math' is enabled, fold
6627 // (fsub x, x) -> 0.0 &
6628 // (fsub x, (fadd x, y)) -> (fneg y) &
6629 // (fsub x, (fadd y, x)) -> (fneg y)
6630 if (DAG.getTarget().Options.UnsafeFPMath) {
6632 return DAG.getConstantFP(0.0f, VT);
6634 if (N1.getOpcode() == ISD::FADD) {
6635 SDValue N10 = N1->getOperand(0);
6636 SDValue N11 = N1->getOperand(1);
6638 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6639 &DAG.getTarget().Options))
6640 return GetNegatedExpression(N11, DAG, LegalOperations);
6642 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6643 &DAG.getTarget().Options))
6644 return GetNegatedExpression(N10, DAG, LegalOperations);
6648 // FSUB -> FMA combines:
6649 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6650 DAG.getTarget().Options.UnsafeFPMath) &&
6651 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6652 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6654 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6655 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6656 return DAG.getNode(ISD::FMA, dl, VT,
6657 N0.getOperand(0), N0.getOperand(1),
6658 DAG.getNode(ISD::FNEG, dl, VT, N1));
6660 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6661 // Note: Commutes FSUB operands.
6662 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6663 return DAG.getNode(ISD::FMA, dl, VT,
6664 DAG.getNode(ISD::FNEG, dl, VT,
6666 N1.getOperand(1), N0);
6668 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6669 if (N0.getOpcode() == ISD::FNEG &&
6670 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6671 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6672 SDValue N00 = N0.getOperand(0).getOperand(0);
6673 SDValue N01 = N0.getOperand(0).getOperand(1);
6674 return DAG.getNode(ISD::FMA, dl, VT,
6675 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6676 DAG.getNode(ISD::FNEG, dl, VT, N1));
6683 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6684 SDValue N0 = N->getOperand(0);
6685 SDValue N1 = N->getOperand(1);
6686 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6687 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6688 EVT VT = N->getValueType(0);
6689 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6692 if (VT.isVector()) {
6693 SDValue FoldedVOp = SimplifyVBinOp(N);
6694 if (FoldedVOp.getNode()) return FoldedVOp;
6697 // fold (fmul c1, c2) -> c1*c2
6699 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6700 // canonicalize constant to RHS
6701 if (N0CFP && !N1CFP)
6702 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6703 // fold (fmul A, 0) -> 0
6704 if (DAG.getTarget().Options.UnsafeFPMath &&
6705 N1CFP && N1CFP->getValueAPF().isZero())
6707 // fold (fmul A, 0) -> 0, vector edition.
6708 if (DAG.getTarget().Options.UnsafeFPMath &&
6709 ISD::isBuildVectorAllZeros(N1.getNode()))
6711 // fold (fmul A, 1.0) -> A
6712 if (N1CFP && N1CFP->isExactlyValue(1.0))
6714 // fold (fmul X, 2.0) -> (fadd X, X)
6715 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6716 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6717 // fold (fmul X, -1.0) -> (fneg X)
6718 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6719 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6720 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6722 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6723 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6724 &DAG.getTarget().Options)) {
6725 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6726 &DAG.getTarget().Options)) {
6727 // Both can be negated for free, check to see if at least one is cheaper
6729 if (LHSNeg == 2 || RHSNeg == 2)
6730 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6731 GetNegatedExpression(N0, DAG, LegalOperations),
6732 GetNegatedExpression(N1, DAG, LegalOperations));
6736 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6737 if (DAG.getTarget().Options.UnsafeFPMath &&
6738 N1CFP && N0.getOpcode() == ISD::FMUL &&
6739 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6740 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6741 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6742 N0.getOperand(1), N1));
6747 SDValue DAGCombiner::visitFMA(SDNode *N) {
6748 SDValue N0 = N->getOperand(0);
6749 SDValue N1 = N->getOperand(1);
6750 SDValue N2 = N->getOperand(2);
6751 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6752 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6753 EVT VT = N->getValueType(0);
6756 if (DAG.getTarget().Options.UnsafeFPMath) {
6757 if (N0CFP && N0CFP->isZero())
6759 if (N1CFP && N1CFP->isZero())
6762 if (N0CFP && N0CFP->isExactlyValue(1.0))
6763 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6764 if (N1CFP && N1CFP->isExactlyValue(1.0))
6765 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6767 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6768 if (N0CFP && !N1CFP)
6769 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6771 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6772 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6773 N2.getOpcode() == ISD::FMUL &&
6774 N0 == N2.getOperand(0) &&
6775 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6776 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6777 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6781 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6782 if (DAG.getTarget().Options.UnsafeFPMath &&
6783 N0.getOpcode() == ISD::FMUL && N1CFP &&
6784 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6785 return DAG.getNode(ISD::FMA, dl, VT,
6787 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6791 // (fma x, 1, y) -> (fadd x, y)
6792 // (fma x, -1, y) -> (fadd (fneg x), y)
6794 if (N1CFP->isExactlyValue(1.0))
6795 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6797 if (N1CFP->isExactlyValue(-1.0) &&
6798 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6799 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6800 AddToWorkList(RHSNeg.getNode());
6801 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6805 // (fma x, c, x) -> (fmul x, (c+1))
6806 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6807 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6808 DAG.getNode(ISD::FADD, dl, VT,
6809 N1, DAG.getConstantFP(1.0, VT)));
6811 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6812 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6813 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6814 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6815 DAG.getNode(ISD::FADD, dl, VT,
6816 N1, DAG.getConstantFP(-1.0, VT)));
6822 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6823 SDValue N0 = N->getOperand(0);
6824 SDValue N1 = N->getOperand(1);
6825 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6826 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6827 EVT VT = N->getValueType(0);
6828 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6831 if (VT.isVector()) {
6832 SDValue FoldedVOp = SimplifyVBinOp(N);
6833 if (FoldedVOp.getNode()) return FoldedVOp;
6836 // fold (fdiv c1, c2) -> c1/c2
6838 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6840 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6841 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6842 // Compute the reciprocal 1.0 / c2.
6843 APFloat N1APF = N1CFP->getValueAPF();
6844 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6845 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6846 // Only do the transform if the reciprocal is a legal fp immediate that
6847 // isn't too nasty (eg NaN, denormal, ...).
6848 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6849 (!LegalOperations ||
6850 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6851 // backend)... we should handle this gracefully after Legalize.
6852 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6853 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6854 TLI.isFPImmLegal(Recip, VT)))
6855 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6856 DAG.getConstantFP(Recip, VT));
6859 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6860 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6861 &DAG.getTarget().Options)) {
6862 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6863 &DAG.getTarget().Options)) {
6864 // Both can be negated for free, check to see if at least one is cheaper
6866 if (LHSNeg == 2 || RHSNeg == 2)
6867 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6868 GetNegatedExpression(N0, DAG, LegalOperations),
6869 GetNegatedExpression(N1, DAG, LegalOperations));
6876 SDValue DAGCombiner::visitFREM(SDNode *N) {
6877 SDValue N0 = N->getOperand(0);
6878 SDValue N1 = N->getOperand(1);
6879 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6880 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6881 EVT VT = N->getValueType(0);
6883 // fold (frem c1, c2) -> fmod(c1,c2)
6885 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6890 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6891 SDValue N0 = N->getOperand(0);
6892 SDValue N1 = N->getOperand(1);
6893 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6894 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6895 EVT VT = N->getValueType(0);
6897 if (N0CFP && N1CFP) // Constant fold
6898 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6901 const APFloat& V = N1CFP->getValueAPF();
6902 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6903 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6904 if (!V.isNegative()) {
6905 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6906 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6908 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6909 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6910 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6914 // copysign(fabs(x), y) -> copysign(x, y)
6915 // copysign(fneg(x), y) -> copysign(x, y)
6916 // copysign(copysign(x,z), y) -> copysign(x, y)
6917 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6918 N0.getOpcode() == ISD::FCOPYSIGN)
6919 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6920 N0.getOperand(0), N1);
6922 // copysign(x, abs(y)) -> abs(x)
6923 if (N1.getOpcode() == ISD::FABS)
6924 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6926 // copysign(x, copysign(y,z)) -> copysign(x, z)
6927 if (N1.getOpcode() == ISD::FCOPYSIGN)
6928 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6929 N0, N1.getOperand(1));
6931 // copysign(x, fp_extend(y)) -> copysign(x, y)
6932 // copysign(x, fp_round(y)) -> copysign(x, y)
6933 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6934 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6935 N0, N1.getOperand(0));
6940 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6941 SDValue N0 = N->getOperand(0);
6942 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6943 EVT VT = N->getValueType(0);
6944 EVT OpVT = N0.getValueType();
6946 // fold (sint_to_fp c1) -> c1fp
6948 // ...but only if the target supports immediate floating-point values
6949 (!LegalOperations ||
6950 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6951 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6953 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6954 // but UINT_TO_FP is legal on this target, try to convert.
6955 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6956 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6957 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6958 if (DAG.SignBitIsZero(N0))
6959 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6962 // The next optimizations are desirable only if SELECT_CC can be lowered.
6963 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6964 // having to say they don't support SELECT_CC on every type the DAG knows
6965 // about, since there is no way to mark an opcode illegal at all value types
6966 // (See also visitSELECT)
6967 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6968 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6969 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6971 (!LegalOperations ||
6972 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6974 { N0.getOperand(0), N0.getOperand(1),
6975 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6977 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6980 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6981 // (select_cc x, y, 1.0, 0.0,, cc)
6982 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6983 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6984 (!LegalOperations ||
6985 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6987 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6988 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6989 N0.getOperand(0).getOperand(2) };
6990 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6997 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6998 SDValue N0 = N->getOperand(0);
6999 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7000 EVT VT = N->getValueType(0);
7001 EVT OpVT = N0.getValueType();
7003 // fold (uint_to_fp c1) -> c1fp
7005 // ...but only if the target supports immediate floating-point values
7006 (!LegalOperations ||
7007 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7008 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7010 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7011 // but SINT_TO_FP is legal on this target, try to convert.
7012 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7013 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7014 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7015 if (DAG.SignBitIsZero(N0))
7016 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7019 // The next optimizations are desirable only if SELECT_CC can be lowered.
7020 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
7021 // having to say they don't support SELECT_CC on every type the DAG knows
7022 // about, since there is no way to mark an opcode illegal at all value types
7023 // (See also visitSELECT)
7024 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
7025 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7027 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7028 (!LegalOperations ||
7029 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7031 { N0.getOperand(0), N0.getOperand(1),
7032 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7034 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
7041 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7042 SDValue N0 = N->getOperand(0);
7043 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7044 EVT VT = N->getValueType(0);
7046 // fold (fp_to_sint c1fp) -> c1
7048 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7053 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7054 SDValue N0 = N->getOperand(0);
7055 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7056 EVT VT = N->getValueType(0);
7058 // fold (fp_to_uint c1fp) -> c1
7060 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7065 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7066 SDValue N0 = N->getOperand(0);
7067 SDValue N1 = N->getOperand(1);
7068 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7069 EVT VT = N->getValueType(0);
7071 // fold (fp_round c1fp) -> c1fp
7073 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7075 // fold (fp_round (fp_extend x)) -> x
7076 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7077 return N0.getOperand(0);
7079 // fold (fp_round (fp_round x)) -> (fp_round x)
7080 if (N0.getOpcode() == ISD::FP_ROUND) {
7081 // This is a value preserving truncation if both round's are.
7082 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7083 N0.getNode()->getConstantOperandVal(1) == 1;
7084 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7085 DAG.getIntPtrConstant(IsTrunc));
7088 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7089 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7090 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7091 N0.getOperand(0), N1);
7092 AddToWorkList(Tmp.getNode());
7093 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7094 Tmp, N0.getOperand(1));
7100 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7101 SDValue N0 = N->getOperand(0);
7102 EVT VT = N->getValueType(0);
7103 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7104 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7106 // fold (fp_round_inreg c1fp) -> c1fp
7107 if (N0CFP && isTypeLegal(EVT)) {
7108 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7109 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7115 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7116 SDValue N0 = N->getOperand(0);
7117 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7118 EVT VT = N->getValueType(0);
7120 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7121 if (N->hasOneUse() &&
7122 N->use_begin()->getOpcode() == ISD::FP_ROUND)
7125 // fold (fp_extend c1fp) -> c1fp
7127 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7129 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7131 if (N0.getOpcode() == ISD::FP_ROUND
7132 && N0.getNode()->getConstantOperandVal(1) == 1) {
7133 SDValue In = N0.getOperand(0);
7134 if (In.getValueType() == VT) return In;
7135 if (VT.bitsLT(In.getValueType()))
7136 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7137 In, N0.getOperand(1));
7138 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7141 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7142 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7143 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7144 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
7145 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7146 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7148 LN0->getBasePtr(), N0.getValueType(),
7149 LN0->getMemOperand());
7150 CombineTo(N, ExtLoad);
7151 CombineTo(N0.getNode(),
7152 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7153 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7154 ExtLoad.getValue(1));
7155 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7161 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7162 SDValue N0 = N->getOperand(0);
7163 EVT VT = N->getValueType(0);
7165 if (VT.isVector()) {
7166 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7167 if (FoldedVOp.getNode()) return FoldedVOp;
7170 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7171 &DAG.getTarget().Options))
7172 return GetNegatedExpression(N0, DAG, LegalOperations);
7174 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7175 // constant pool values.
7176 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7178 N0.getNode()->hasOneUse() &&
7179 N0.getOperand(0).getValueType().isInteger()) {
7180 SDValue Int = N0.getOperand(0);
7181 EVT IntVT = Int.getValueType();
7182 if (IntVT.isInteger() && !IntVT.isVector()) {
7183 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7184 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7185 AddToWorkList(Int.getNode());
7186 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7191 // (fneg (fmul c, x)) -> (fmul -c, x)
7192 if (N0.getOpcode() == ISD::FMUL) {
7193 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7195 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7197 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7204 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7205 SDValue N0 = N->getOperand(0);
7206 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7207 EVT VT = N->getValueType(0);
7209 // fold (fceil c1) -> fceil(c1)
7211 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7216 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7217 SDValue N0 = N->getOperand(0);
7218 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7219 EVT VT = N->getValueType(0);
7221 // fold (ftrunc c1) -> ftrunc(c1)
7223 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7228 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7229 SDValue N0 = N->getOperand(0);
7230 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7231 EVT VT = N->getValueType(0);
7233 // fold (ffloor c1) -> ffloor(c1)
7235 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7240 SDValue DAGCombiner::visitFABS(SDNode *N) {
7241 SDValue N0 = N->getOperand(0);
7242 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7243 EVT VT = N->getValueType(0);
7245 if (VT.isVector()) {
7246 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7247 if (FoldedVOp.getNode()) return FoldedVOp;
7250 // fold (fabs c1) -> fabs(c1)
7252 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7253 // fold (fabs (fabs x)) -> (fabs x)
7254 if (N0.getOpcode() == ISD::FABS)
7255 return N->getOperand(0);
7256 // fold (fabs (fneg x)) -> (fabs x)
7257 // fold (fabs (fcopysign x, y)) -> (fabs x)
7258 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7259 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7261 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7262 // constant pool values.
7263 if (!TLI.isFAbsFree(VT) &&
7264 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7265 N0.getOperand(0).getValueType().isInteger() &&
7266 !N0.getOperand(0).getValueType().isVector()) {
7267 SDValue Int = N0.getOperand(0);
7268 EVT IntVT = Int.getValueType();
7269 if (IntVT.isInteger() && !IntVT.isVector()) {
7270 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7271 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7272 AddToWorkList(Int.getNode());
7273 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7274 N->getValueType(0), Int);
7281 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7282 SDValue Chain = N->getOperand(0);
7283 SDValue N1 = N->getOperand(1);
7284 SDValue N2 = N->getOperand(2);
7286 // If N is a constant we could fold this into a fallthrough or unconditional
7287 // branch. However that doesn't happen very often in normal code, because
7288 // Instcombine/SimplifyCFG should have handled the available opportunities.
7289 // If we did this folding here, it would be necessary to update the
7290 // MachineBasicBlock CFG, which is awkward.
7292 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7294 if (N1.getOpcode() == ISD::SETCC &&
7295 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7296 N1.getOperand(0).getValueType())) {
7297 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7298 Chain, N1.getOperand(2),
7299 N1.getOperand(0), N1.getOperand(1), N2);
7302 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7303 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7304 (N1.getOperand(0).hasOneUse() &&
7305 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7306 SDNode *Trunc = nullptr;
7307 if (N1.getOpcode() == ISD::TRUNCATE) {
7308 // Look pass the truncate.
7309 Trunc = N1.getNode();
7310 N1 = N1.getOperand(0);
7313 // Match this pattern so that we can generate simpler code:
7316 // %b = and i32 %a, 2
7317 // %c = srl i32 %b, 1
7318 // brcond i32 %c ...
7323 // %b = and i32 %a, 2
7324 // %c = setcc eq %b, 0
7327 // This applies only when the AND constant value has one bit set and the
7328 // SRL constant is equal to the log2 of the AND constant. The back-end is
7329 // smart enough to convert the result into a TEST/JMP sequence.
7330 SDValue Op0 = N1.getOperand(0);
7331 SDValue Op1 = N1.getOperand(1);
7333 if (Op0.getOpcode() == ISD::AND &&
7334 Op1.getOpcode() == ISD::Constant) {
7335 SDValue AndOp1 = Op0.getOperand(1);
7337 if (AndOp1.getOpcode() == ISD::Constant) {
7338 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7340 if (AndConst.isPowerOf2() &&
7341 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7343 DAG.getSetCC(SDLoc(N),
7344 getSetCCResultType(Op0.getValueType()),
7345 Op0, DAG.getConstant(0, Op0.getValueType()),
7348 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7349 MVT::Other, Chain, SetCC, N2);
7350 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7351 // will convert it back to (X & C1) >> C2.
7352 CombineTo(N, NewBRCond, false);
7353 // Truncate is dead.
7355 removeFromWorkList(Trunc);
7356 DAG.DeleteNode(Trunc);
7358 // Replace the uses of SRL with SETCC
7359 WorkListRemover DeadNodes(*this);
7360 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7361 removeFromWorkList(N1.getNode());
7362 DAG.DeleteNode(N1.getNode());
7363 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7369 // Restore N1 if the above transformation doesn't match.
7370 N1 = N->getOperand(1);
7373 // Transform br(xor(x, y)) -> br(x != y)
7374 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7375 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7376 SDNode *TheXor = N1.getNode();
7377 SDValue Op0 = TheXor->getOperand(0);
7378 SDValue Op1 = TheXor->getOperand(1);
7379 if (Op0.getOpcode() == Op1.getOpcode()) {
7380 // Avoid missing important xor optimizations.
7381 SDValue Tmp = visitXOR(TheXor);
7382 if (Tmp.getNode()) {
7383 if (Tmp.getNode() != TheXor) {
7384 DEBUG(dbgs() << "\nReplacing.8 ";
7386 dbgs() << "\nWith: ";
7387 Tmp.getNode()->dump(&DAG);
7389 WorkListRemover DeadNodes(*this);
7390 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7391 removeFromWorkList(TheXor);
7392 DAG.DeleteNode(TheXor);
7393 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7394 MVT::Other, Chain, Tmp, N2);
7397 // visitXOR has changed XOR's operands or replaced the XOR completely,
7399 return SDValue(N, 0);
7403 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7405 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7406 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7407 Op0.getOpcode() == ISD::XOR) {
7408 TheXor = Op0.getNode();
7412 EVT SetCCVT = N1.getValueType();
7414 SetCCVT = getSetCCResultType(SetCCVT);
7415 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7418 Equal ? ISD::SETEQ : ISD::SETNE);
7419 // Replace the uses of XOR with SETCC
7420 WorkListRemover DeadNodes(*this);
7421 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7422 removeFromWorkList(N1.getNode());
7423 DAG.DeleteNode(N1.getNode());
7424 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7425 MVT::Other, Chain, SetCC, N2);
7432 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7434 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7435 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7436 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7438 // If N is a constant we could fold this into a fallthrough or unconditional
7439 // branch. However that doesn't happen very often in normal code, because
7440 // Instcombine/SimplifyCFG should have handled the available opportunities.
7441 // If we did this folding here, it would be necessary to update the
7442 // MachineBasicBlock CFG, which is awkward.
7444 // Use SimplifySetCC to simplify SETCC's.
7445 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7446 CondLHS, CondRHS, CC->get(), SDLoc(N),
7448 if (Simp.getNode()) AddToWorkList(Simp.getNode());
7450 // fold to a simpler setcc
7451 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7452 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7453 N->getOperand(0), Simp.getOperand(2),
7454 Simp.getOperand(0), Simp.getOperand(1),
7460 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7461 /// uses N as its base pointer and that N may be folded in the load / store
7462 /// addressing mode.
7463 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7465 const TargetLowering &TLI) {
7467 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7468 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7470 VT = Use->getValueType(0);
7471 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7472 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7474 VT = ST->getValue().getValueType();
7478 TargetLowering::AddrMode AM;
7479 if (N->getOpcode() == ISD::ADD) {
7480 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7483 AM.BaseOffs = Offset->getSExtValue();
7487 } else if (N->getOpcode() == ISD::SUB) {
7488 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7491 AM.BaseOffs = -Offset->getSExtValue();
7498 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7501 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7502 /// pre-indexed load / store when the base pointer is an add or subtract
7503 /// and it has other uses besides the load / store. After the
7504 /// transformation, the new indexed load / store has effectively folded
7505 /// the add / subtract in and all of its other uses are redirected to the
7506 /// new load / store.
7507 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7508 if (Level < AfterLegalizeDAG)
7514 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7515 if (LD->isIndexed())
7517 VT = LD->getMemoryVT();
7518 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7519 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7521 Ptr = LD->getBasePtr();
7522 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7523 if (ST->isIndexed())
7525 VT = ST->getMemoryVT();
7526 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7527 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7529 Ptr = ST->getBasePtr();
7535 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7536 // out. There is no reason to make this a preinc/predec.
7537 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7538 Ptr.getNode()->hasOneUse())
7541 // Ask the target to do addressing mode selection.
7544 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7545 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7548 // Backends without true r+i pre-indexed forms may need to pass a
7549 // constant base with a variable offset so that constant coercion
7550 // will work with the patterns in canonical form.
7551 bool Swapped = false;
7552 if (isa<ConstantSDNode>(BasePtr)) {
7553 std::swap(BasePtr, Offset);
7557 // Don't create a indexed load / store with zero offset.
7558 if (isa<ConstantSDNode>(Offset) &&
7559 cast<ConstantSDNode>(Offset)->isNullValue())
7562 // Try turning it into a pre-indexed load / store except when:
7563 // 1) The new base ptr is a frame index.
7564 // 2) If N is a store and the new base ptr is either the same as or is a
7565 // predecessor of the value being stored.
7566 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7567 // that would create a cycle.
7568 // 4) All uses are load / store ops that use it as old base ptr.
7570 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7571 // (plus the implicit offset) to a register to preinc anyway.
7572 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7577 SDValue Val = cast<StoreSDNode>(N)->getValue();
7578 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7582 // If the offset is a constant, there may be other adds of constants that
7583 // can be folded with this one. We should do this to avoid having to keep
7584 // a copy of the original base pointer.
7585 SmallVector<SDNode *, 16> OtherUses;
7586 if (isa<ConstantSDNode>(Offset))
7587 for (SDNode *Use : BasePtr.getNode()->uses()) {
7588 if (Use == Ptr.getNode())
7591 if (Use->isPredecessorOf(N))
7594 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7599 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7600 if (Op1.getNode() == BasePtr.getNode())
7601 std::swap(Op0, Op1);
7602 assert(Op0.getNode() == BasePtr.getNode() &&
7603 "Use of ADD/SUB but not an operand");
7605 if (!isa<ConstantSDNode>(Op1)) {
7610 // FIXME: In some cases, we can be smarter about this.
7611 if (Op1.getValueType() != Offset.getValueType()) {
7616 OtherUses.push_back(Use);
7620 std::swap(BasePtr, Offset);
7622 // Now check for #3 and #4.
7623 bool RealUse = false;
7625 // Caches for hasPredecessorHelper
7626 SmallPtrSet<const SDNode *, 32> Visited;
7627 SmallVector<const SDNode *, 16> Worklist;
7629 for (SDNode *Use : Ptr.getNode()->uses()) {
7632 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7635 // If Ptr may be folded in addressing mode of other use, then it's
7636 // not profitable to do this transformation.
7637 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7646 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7647 BasePtr, Offset, AM);
7649 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7650 BasePtr, Offset, AM);
7653 DEBUG(dbgs() << "\nReplacing.4 ";
7655 dbgs() << "\nWith: ";
7656 Result.getNode()->dump(&DAG);
7658 WorkListRemover DeadNodes(*this);
7660 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7661 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7663 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7666 // Finally, since the node is now dead, remove it from the graph.
7670 std::swap(BasePtr, Offset);
7672 // Replace other uses of BasePtr that can be updated to use Ptr
7673 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7674 unsigned OffsetIdx = 1;
7675 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7677 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7678 BasePtr.getNode() && "Expected BasePtr operand");
7680 // We need to replace ptr0 in the following expression:
7681 // x0 * offset0 + y0 * ptr0 = t0
7683 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7685 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7686 // indexed load/store and the expresion that needs to be re-written.
7688 // Therefore, we have:
7689 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7691 ConstantSDNode *CN =
7692 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7694 APInt Offset0 = CN->getAPIntValue();
7695 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7697 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7698 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7699 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7700 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7702 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7704 APInt CNV = Offset0;
7705 if (X0 < 0) CNV = -CNV;
7706 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7707 else CNV = CNV - Offset1;
7709 // We can now generate the new expression.
7710 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7711 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7713 SDValue NewUse = DAG.getNode(Opcode,
7714 SDLoc(OtherUses[i]),
7715 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7716 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7717 removeFromWorkList(OtherUses[i]);
7718 DAG.DeleteNode(OtherUses[i]);
7721 // Replace the uses of Ptr with uses of the updated base value.
7722 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7723 removeFromWorkList(Ptr.getNode());
7724 DAG.DeleteNode(Ptr.getNode());
7729 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7730 /// add / sub of the base pointer node into a post-indexed load / store.
7731 /// The transformation folded the add / subtract into the new indexed
7732 /// load / store effectively and all of its uses are redirected to the
7733 /// new load / store.
7734 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7735 if (Level < AfterLegalizeDAG)
7741 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7742 if (LD->isIndexed())
7744 VT = LD->getMemoryVT();
7745 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7746 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7748 Ptr = LD->getBasePtr();
7749 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7750 if (ST->isIndexed())
7752 VT = ST->getMemoryVT();
7753 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7754 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7756 Ptr = ST->getBasePtr();
7762 if (Ptr.getNode()->hasOneUse())
7765 for (SDNode *Op : Ptr.getNode()->uses()) {
7767 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7772 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7773 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7774 // Don't create a indexed load / store with zero offset.
7775 if (isa<ConstantSDNode>(Offset) &&
7776 cast<ConstantSDNode>(Offset)->isNullValue())
7779 // Try turning it into a post-indexed load / store except when
7780 // 1) All uses are load / store ops that use it as base ptr (and
7781 // it may be folded as addressing mmode).
7782 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7783 // nor a successor of N. Otherwise, if Op is folded that would
7786 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7790 bool TryNext = false;
7791 for (SDNode *Use : BasePtr.getNode()->uses()) {
7792 if (Use == Ptr.getNode())
7795 // If all the uses are load / store addresses, then don't do the
7797 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7798 bool RealUse = false;
7799 for (SDNode *UseUse : Use->uses()) {
7800 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7815 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7816 SDValue Result = isLoad
7817 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7818 BasePtr, Offset, AM)
7819 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7820 BasePtr, Offset, AM);
7823 DEBUG(dbgs() << "\nReplacing.5 ";
7825 dbgs() << "\nWith: ";
7826 Result.getNode()->dump(&DAG);
7828 WorkListRemover DeadNodes(*this);
7830 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7831 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7833 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7836 // Finally, since the node is now dead, remove it from the graph.
7839 // Replace the uses of Use with uses of the updated base value.
7840 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7841 Result.getValue(isLoad ? 1 : 0));
7842 removeFromWorkList(Op);
7852 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7853 LoadSDNode *LD = cast<LoadSDNode>(N);
7854 SDValue Chain = LD->getChain();
7855 SDValue Ptr = LD->getBasePtr();
7857 // If load is not volatile and there are no uses of the loaded value (and
7858 // the updated indexed value in case of indexed loads), change uses of the
7859 // chain value into uses of the chain input (i.e. delete the dead load).
7860 if (!LD->isVolatile()) {
7861 if (N->getValueType(1) == MVT::Other) {
7863 if (!N->hasAnyUseOfValue(0)) {
7864 // It's not safe to use the two value CombineTo variant here. e.g.
7865 // v1, chain2 = load chain1, loc
7866 // v2, chain3 = load chain2, loc
7868 // Now we replace use of chain2 with chain1. This makes the second load
7869 // isomorphic to the one we are deleting, and thus makes this load live.
7870 DEBUG(dbgs() << "\nReplacing.6 ";
7872 dbgs() << "\nWith chain: ";
7873 Chain.getNode()->dump(&DAG);
7875 WorkListRemover DeadNodes(*this);
7876 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7878 if (N->use_empty()) {
7879 removeFromWorkList(N);
7883 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7887 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7888 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7889 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7890 DEBUG(dbgs() << "\nReplacing.7 ";
7892 dbgs() << "\nWith: ";
7893 Undef.getNode()->dump(&DAG);
7894 dbgs() << " and 2 other values\n");
7895 WorkListRemover DeadNodes(*this);
7896 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7897 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7898 DAG.getUNDEF(N->getValueType(1)));
7899 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7900 removeFromWorkList(N);
7902 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7907 // If this load is directly stored, replace the load value with the stored
7909 // TODO: Handle store large -> read small portion.
7910 // TODO: Handle TRUNCSTORE/LOADEXT
7911 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7912 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7913 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7914 if (PrevST->getBasePtr() == Ptr &&
7915 PrevST->getValue().getValueType() == N->getValueType(0))
7916 return CombineTo(N, Chain.getOperand(1), Chain);
7920 // Try to infer better alignment information than the load already has.
7921 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7922 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7923 if (Align > LD->getMemOperand()->getBaseAlignment()) {
7925 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7926 LD->getValueType(0),
7927 Chain, Ptr, LD->getPointerInfo(),
7929 LD->isVolatile(), LD->isNonTemporal(), Align,
7931 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7936 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7937 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7939 if (CombinerAAOnlyFunc.getNumOccurrences() &&
7940 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
7943 if (UseAA && LD->isUnindexed()) {
7944 // Walk up chain skipping non-aliasing memory nodes.
7945 SDValue BetterChain = FindBetterChain(N, Chain);
7947 // If there is a better chain.
7948 if (Chain != BetterChain) {
7951 // Replace the chain to void dependency.
7952 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7953 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7954 BetterChain, Ptr, LD->getMemOperand());
7956 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7957 LD->getValueType(0),
7958 BetterChain, Ptr, LD->getMemoryVT(),
7959 LD->getMemOperand());
7962 // Create token factor to keep old chain connected.
7963 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7964 MVT::Other, Chain, ReplLoad.getValue(1));
7966 // Make sure the new and old chains are cleaned up.
7967 AddToWorkList(Token.getNode());
7969 // Replace uses with load result and token factor. Don't add users
7971 return CombineTo(N, ReplLoad.getValue(0), Token, false);
7975 // Try transforming N to an indexed load.
7976 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7977 return SDValue(N, 0);
7979 // Try to slice up N to more direct loads if the slices are mapped to
7980 // different register banks or pairing can take place.
7982 return SDValue(N, 0);
7988 /// \brief Helper structure used to slice a load in smaller loads.
7989 /// Basically a slice is obtained from the following sequence:
7990 /// Origin = load Ty1, Base
7991 /// Shift = srl Ty1 Origin, CstTy Amount
7992 /// Inst = trunc Shift to Ty2
7994 /// Then, it will be rewriten into:
7995 /// Slice = load SliceTy, Base + SliceOffset
7996 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
7998 /// SliceTy is deduced from the number of bits that are actually used to
8000 struct LoadedSlice {
8001 /// \brief Helper structure used to compute the cost of a slice.
8003 /// Are we optimizing for code size.
8008 unsigned CrossRegisterBanksCopies;
8012 Cost(bool ForCodeSize = false)
8013 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8014 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8016 /// \brief Get the cost of one isolated slice.
8017 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8018 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8019 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8020 EVT TruncType = LS.Inst->getValueType(0);
8021 EVT LoadedType = LS.getLoadedType();
8022 if (TruncType != LoadedType &&
8023 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8027 /// \brief Account for slicing gain in the current cost.
8028 /// Slicing provide a few gains like removing a shift or a
8029 /// truncate. This method allows to grow the cost of the original
8030 /// load with the gain from this slice.
8031 void addSliceGain(const LoadedSlice &LS) {
8032 // Each slice saves a truncate.
8033 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8034 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8035 LS.Inst->getOperand(0).getValueType()))
8037 // If there is a shift amount, this slice gets rid of it.
8040 // If this slice can merge a cross register bank copy, account for it.
8041 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8042 ++CrossRegisterBanksCopies;
8045 Cost &operator+=(const Cost &RHS) {
8047 Truncates += RHS.Truncates;
8048 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8054 bool operator==(const Cost &RHS) const {
8055 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8056 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8057 ZExts == RHS.ZExts && Shift == RHS.Shift;
8060 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8062 bool operator<(const Cost &RHS) const {
8063 // Assume cross register banks copies are as expensive as loads.
8064 // FIXME: Do we want some more target hooks?
8065 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8066 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8067 // Unless we are optimizing for code size, consider the
8068 // expensive operation first.
8069 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8070 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8071 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8072 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8075 bool operator>(const Cost &RHS) const { return RHS < *this; }
8077 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8079 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8081 // The last instruction that represent the slice. This should be a
8082 // truncate instruction.
8084 // The original load instruction.
8086 // The right shift amount in bits from the original load.
8088 // The DAG from which Origin came from.
8089 // This is used to get some contextual information about legal types, etc.
8092 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8093 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8094 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8096 LoadedSlice(const LoadedSlice &LS)
8097 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8099 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8100 /// \return Result is \p BitWidth and has used bits set to 1 and
8101 /// not used bits set to 0.
8102 APInt getUsedBits() const {
8103 // Reproduce the trunc(lshr) sequence:
8104 // - Start from the truncated value.
8105 // - Zero extend to the desired bit width.
8107 assert(Origin && "No original load to compare against.");
8108 unsigned BitWidth = Origin->getValueSizeInBits(0);
8109 assert(Inst && "This slice is not bound to an instruction");
8110 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8111 "Extracted slice is bigger than the whole type!");
8112 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8113 UsedBits.setAllBits();
8114 UsedBits = UsedBits.zext(BitWidth);
8119 /// \brief Get the size of the slice to be loaded in bytes.
8120 unsigned getLoadedSize() const {
8121 unsigned SliceSize = getUsedBits().countPopulation();
8122 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8123 return SliceSize / 8;
8126 /// \brief Get the type that will be loaded for this slice.
8127 /// Note: This may not be the final type for the slice.
8128 EVT getLoadedType() const {
8129 assert(DAG && "Missing context");
8130 LLVMContext &Ctxt = *DAG->getContext();
8131 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8134 /// \brief Get the alignment of the load used for this slice.
8135 unsigned getAlignment() const {
8136 unsigned Alignment = Origin->getAlignment();
8137 unsigned Offset = getOffsetFromBase();
8139 Alignment = MinAlign(Alignment, Alignment + Offset);
8143 /// \brief Check if this slice can be rewritten with legal operations.
8144 bool isLegal() const {
8145 // An invalid slice is not legal.
8146 if (!Origin || !Inst || !DAG)
8149 // Offsets are for indexed load only, we do not handle that.
8150 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8153 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8155 // Check that the type is legal.
8156 EVT SliceType = getLoadedType();
8157 if (!TLI.isTypeLegal(SliceType))
8160 // Check that the load is legal for this type.
8161 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8164 // Check that the offset can be computed.
8165 // 1. Check its type.
8166 EVT PtrType = Origin->getBasePtr().getValueType();
8167 if (PtrType == MVT::Untyped || PtrType.isExtended())
8170 // 2. Check that it fits in the immediate.
8171 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8174 // 3. Check that the computation is legal.
8175 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8178 // Check that the zext is legal if it needs one.
8179 EVT TruncateType = Inst->getValueType(0);
8180 if (TruncateType != SliceType &&
8181 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8187 /// \brief Get the offset in bytes of this slice in the original chunk of
8189 /// \pre DAG != nullptr.
8190 uint64_t getOffsetFromBase() const {
8191 assert(DAG && "Missing context.");
8193 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8194 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8195 uint64_t Offset = Shift / 8;
8196 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8197 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8198 "The size of the original loaded type is not a multiple of a"
8200 // If Offset is bigger than TySizeInBytes, it means we are loading all
8201 // zeros. This should have been optimized before in the process.
8202 assert(TySizeInBytes > Offset &&
8203 "Invalid shift amount for given loaded size");
8205 Offset = TySizeInBytes - Offset - getLoadedSize();
8209 /// \brief Generate the sequence of instructions to load the slice
8210 /// represented by this object and redirect the uses of this slice to
8211 /// this new sequence of instructions.
8212 /// \pre this->Inst && this->Origin are valid Instructions and this
8213 /// object passed the legal check: LoadedSlice::isLegal returned true.
8214 /// \return The last instruction of the sequence used to load the slice.
8215 SDValue loadSlice() const {
8216 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8217 const SDValue &OldBaseAddr = Origin->getBasePtr();
8218 SDValue BaseAddr = OldBaseAddr;
8219 // Get the offset in that chunk of bytes w.r.t. the endianess.
8220 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8221 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8223 // BaseAddr = BaseAddr + Offset.
8224 EVT ArithType = BaseAddr.getValueType();
8225 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8226 DAG->getConstant(Offset, ArithType));
8229 // Create the type of the loaded slice according to its size.
8230 EVT SliceType = getLoadedType();
8232 // Create the load for the slice.
8233 SDValue LastInst = DAG->getLoad(
8234 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8235 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8236 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8237 // If the final type is not the same as the loaded type, this means that
8238 // we have to pad with zero. Create a zero extend for that.
8239 EVT FinalType = Inst->getValueType(0);
8240 if (SliceType != FinalType)
8242 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8246 /// \brief Check if this slice can be merged with an expensive cross register
8247 /// bank copy. E.g.,
8249 /// f = bitcast i32 i to float
8250 bool canMergeExpensiveCrossRegisterBankCopy() const {
8251 if (!Inst || !Inst->hasOneUse())
8253 SDNode *Use = *Inst->use_begin();
8254 if (Use->getOpcode() != ISD::BITCAST)
8256 assert(DAG && "Missing context");
8257 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8258 EVT ResVT = Use->getValueType(0);
8259 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8260 const TargetRegisterClass *ArgRC =
8261 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8262 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8265 // At this point, we know that we perform a cross-register-bank copy.
8266 // Check if it is expensive.
8267 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8268 // Assume bitcasts are cheap, unless both register classes do not
8269 // explicitly share a common sub class.
8270 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8273 // Check if it will be merged with the load.
8274 // 1. Check the alignment constraint.
8275 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8276 ResVT.getTypeForEVT(*DAG->getContext()));
8278 if (RequiredAlignment > getAlignment())
8281 // 2. Check that the load is a legal operation for that type.
8282 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8285 // 3. Check that we do not have a zext in the way.
8286 if (Inst->getValueType(0) != getLoadedType())
8294 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8295 /// \p UsedBits looks like 0..0 1..1 0..0.
8296 static bool areUsedBitsDense(const APInt &UsedBits) {
8297 // If all the bits are one, this is dense!
8298 if (UsedBits.isAllOnesValue())
8301 // Get rid of the unused bits on the right.
8302 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8303 // Get rid of the unused bits on the left.
8304 if (NarrowedUsedBits.countLeadingZeros())
8305 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8306 // Check that the chunk of bits is completely used.
8307 return NarrowedUsedBits.isAllOnesValue();
8310 /// \brief Check whether or not \p First and \p Second are next to each other
8311 /// in memory. This means that there is no hole between the bits loaded
8312 /// by \p First and the bits loaded by \p Second.
8313 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8314 const LoadedSlice &Second) {
8315 assert(First.Origin == Second.Origin && First.Origin &&
8316 "Unable to match different memory origins.");
8317 APInt UsedBits = First.getUsedBits();
8318 assert((UsedBits & Second.getUsedBits()) == 0 &&
8319 "Slices are not supposed to overlap.");
8320 UsedBits |= Second.getUsedBits();
8321 return areUsedBitsDense(UsedBits);
8324 /// \brief Adjust the \p GlobalLSCost according to the target
8325 /// paring capabilities and the layout of the slices.
8326 /// \pre \p GlobalLSCost should account for at least as many loads as
8327 /// there is in the slices in \p LoadedSlices.
8328 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8329 LoadedSlice::Cost &GlobalLSCost) {
8330 unsigned NumberOfSlices = LoadedSlices.size();
8331 // If there is less than 2 elements, no pairing is possible.
8332 if (NumberOfSlices < 2)
8335 // Sort the slices so that elements that are likely to be next to each
8336 // other in memory are next to each other in the list.
8337 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8338 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8339 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8340 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8342 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8343 // First (resp. Second) is the first (resp. Second) potentially candidate
8344 // to be placed in a paired load.
8345 const LoadedSlice *First = nullptr;
8346 const LoadedSlice *Second = nullptr;
8347 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8348 // Set the beginning of the pair.
8351 Second = &LoadedSlices[CurrSlice];
8353 // If First is NULL, it means we start a new pair.
8354 // Get to the next slice.
8358 EVT LoadedType = First->getLoadedType();
8360 // If the types of the slices are different, we cannot pair them.
8361 if (LoadedType != Second->getLoadedType())
8364 // Check if the target supplies paired loads for this type.
8365 unsigned RequiredAlignment = 0;
8366 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8367 // move to the next pair, this type is hopeless.
8371 // Check if we meet the alignment requirement.
8372 if (RequiredAlignment > First->getAlignment())
8375 // Check that both loads are next to each other in memory.
8376 if (!areSlicesNextToEachOther(*First, *Second))
8379 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8380 --GlobalLSCost.Loads;
8381 // Move to the next pair.
8386 /// \brief Check the profitability of all involved LoadedSlice.
8387 /// Currently, it is considered profitable if there is exactly two
8388 /// involved slices (1) which are (2) next to each other in memory, and
8389 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8391 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8392 /// the elements themselves.
8394 /// FIXME: When the cost model will be mature enough, we can relax
8395 /// constraints (1) and (2).
8396 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8397 const APInt &UsedBits, bool ForCodeSize) {
8398 unsigned NumberOfSlices = LoadedSlices.size();
8399 if (StressLoadSlicing)
8400 return NumberOfSlices > 1;
8403 if (NumberOfSlices != 2)
8407 if (!areUsedBitsDense(UsedBits))
8411 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8412 // The original code has one big load.
8414 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8415 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8416 // Accumulate the cost of all the slices.
8417 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8418 GlobalSlicingCost += SliceCost;
8420 // Account as cost in the original configuration the gain obtained
8421 // with the current slices.
8422 OrigCost.addSliceGain(LS);
8425 // If the target supports paired load, adjust the cost accordingly.
8426 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8427 return OrigCost > GlobalSlicingCost;
8430 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8431 /// operations, split it in the various pieces being extracted.
8433 /// This sort of thing is introduced by SROA.
8434 /// This slicing takes care not to insert overlapping loads.
8435 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8436 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8437 if (Level < AfterLegalizeDAG)
8440 LoadSDNode *LD = cast<LoadSDNode>(N);
8441 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8442 !LD->getValueType(0).isInteger())
8445 // Keep track of already used bits to detect overlapping values.
8446 // In that case, we will just abort the transformation.
8447 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8449 SmallVector<LoadedSlice, 4> LoadedSlices;
8451 // Check if this load is used as several smaller chunks of bits.
8452 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8453 // of computation for each trunc.
8454 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8455 UI != UIEnd; ++UI) {
8456 // Skip the uses of the chain.
8457 if (UI.getUse().getResNo() != 0)
8463 // Check if this is a trunc(lshr).
8464 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8465 isa<ConstantSDNode>(User->getOperand(1))) {
8466 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8467 User = *User->use_begin();
8470 // At this point, User is a Truncate, iff we encountered, trunc or
8472 if (User->getOpcode() != ISD::TRUNCATE)
8475 // The width of the type must be a power of 2 and greater than 8-bits.
8476 // Otherwise the load cannot be represented in LLVM IR.
8477 // Moreover, if we shifted with a non-8-bits multiple, the slice
8478 // will be across several bytes. We do not support that.
8479 unsigned Width = User->getValueSizeInBits(0);
8480 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8483 // Build the slice for this chain of computations.
8484 LoadedSlice LS(User, LD, Shift, &DAG);
8485 APInt CurrentUsedBits = LS.getUsedBits();
8487 // Check if this slice overlaps with another.
8488 if ((CurrentUsedBits & UsedBits) != 0)
8490 // Update the bits used globally.
8491 UsedBits |= CurrentUsedBits;
8493 // Check if the new slice would be legal.
8497 // Record the slice.
8498 LoadedSlices.push_back(LS);
8501 // Abort slicing if it does not seem to be profitable.
8502 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8507 // Rewrite each chain to use an independent load.
8508 // By construction, each chain can be represented by a unique load.
8510 // Prepare the argument for the new token factor for all the slices.
8511 SmallVector<SDValue, 8> ArgChains;
8512 for (SmallVectorImpl<LoadedSlice>::const_iterator
8513 LSIt = LoadedSlices.begin(),
8514 LSItEnd = LoadedSlices.end();
8515 LSIt != LSItEnd; ++LSIt) {
8516 SDValue SliceInst = LSIt->loadSlice();
8517 CombineTo(LSIt->Inst, SliceInst, true);
8518 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8519 SliceInst = SliceInst.getOperand(0);
8520 assert(SliceInst->getOpcode() == ISD::LOAD &&
8521 "It takes more than a zext to get to the loaded slice!!");
8522 ArgChains.push_back(SliceInst.getValue(1));
8525 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8526 &ArgChains[0], ArgChains.size());
8527 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8531 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8532 /// load is having specific bytes cleared out. If so, return the byte size
8533 /// being masked out and the shift amount.
8534 static std::pair<unsigned, unsigned>
8535 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8536 std::pair<unsigned, unsigned> Result(0, 0);
8538 // Check for the structure we're looking for.
8539 if (V->getOpcode() != ISD::AND ||
8540 !isa<ConstantSDNode>(V->getOperand(1)) ||
8541 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8544 // Check the chain and pointer.
8545 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8546 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
8548 // The store should be chained directly to the load or be an operand of a
8550 if (LD == Chain.getNode())
8552 else if (Chain->getOpcode() != ISD::TokenFactor)
8553 return Result; // Fail.
8556 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8557 if (Chain->getOperand(i).getNode() == LD) {
8561 if (!isOk) return Result;
8564 // This only handles simple types.
8565 if (V.getValueType() != MVT::i16 &&
8566 V.getValueType() != MVT::i32 &&
8567 V.getValueType() != MVT::i64)
8570 // Check the constant mask. Invert it so that the bits being masked out are
8571 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8572 // follow the sign bit for uniformity.
8573 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8574 unsigned NotMaskLZ = countLeadingZeros(NotMask);
8575 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
8576 unsigned NotMaskTZ = countTrailingZeros(NotMask);
8577 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8578 if (NotMaskLZ == 64) return Result; // All zero mask.
8580 // See if we have a continuous run of bits. If so, we have 0*1+0*
8581 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8584 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8585 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8586 NotMaskLZ -= 64-V.getValueSizeInBits();
8588 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8589 switch (MaskedBytes) {
8593 default: return Result; // All one mask, or 5-byte mask.
8596 // Verify that the first bit starts at a multiple of mask so that the access
8597 // is aligned the same as the access width.
8598 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8600 Result.first = MaskedBytes;
8601 Result.second = NotMaskTZ/8;
8606 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8607 /// provides a value as specified by MaskInfo. If so, replace the specified
8608 /// store with a narrower store of truncated IVal.
8610 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8611 SDValue IVal, StoreSDNode *St,
8613 unsigned NumBytes = MaskInfo.first;
8614 unsigned ByteShift = MaskInfo.second;
8615 SelectionDAG &DAG = DC->getDAG();
8617 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8618 // that uses this. If not, this is not a replacement.
8619 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8620 ByteShift*8, (ByteShift+NumBytes)*8);
8621 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8623 // Check that it is legal on the target to do this. It is legal if the new
8624 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8626 MVT VT = MVT::getIntegerVT(NumBytes*8);
8627 if (!DC->isTypeLegal(VT))
8630 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8631 // shifted by ByteShift and truncated down to NumBytes.
8633 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8634 DAG.getConstant(ByteShift*8,
8635 DC->getShiftAmountTy(IVal.getValueType())));
8637 // Figure out the offset for the store and the alignment of the access.
8639 unsigned NewAlign = St->getAlignment();
8641 if (DAG.getTargetLoweringInfo().isLittleEndian())
8642 StOffset = ByteShift;
8644 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8646 SDValue Ptr = St->getBasePtr();
8648 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8649 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8650 NewAlign = MinAlign(NewAlign, StOffset);
8653 // Truncate down to the new size.
8654 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8657 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8658 St->getPointerInfo().getWithOffset(StOffset),
8659 false, false, NewAlign).getNode();
8663 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8664 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8665 /// of the loaded bits, try narrowing the load and store if it would end up
8666 /// being a win for performance or code size.
8667 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8668 StoreSDNode *ST = cast<StoreSDNode>(N);
8669 if (ST->isVolatile())
8672 SDValue Chain = ST->getChain();
8673 SDValue Value = ST->getValue();
8674 SDValue Ptr = ST->getBasePtr();
8675 EVT VT = Value.getValueType();
8677 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8680 unsigned Opc = Value.getOpcode();
8682 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8683 // is a byte mask indicating a consecutive number of bytes, check to see if
8684 // Y is known to provide just those bytes. If so, we try to replace the
8685 // load + replace + store sequence with a single (narrower) store, which makes
8687 if (Opc == ISD::OR) {
8688 std::pair<unsigned, unsigned> MaskedLoad;
8689 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8690 if (MaskedLoad.first)
8691 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8692 Value.getOperand(1), ST,this))
8693 return SDValue(NewST, 0);
8695 // Or is commutative, so try swapping X and Y.
8696 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8697 if (MaskedLoad.first)
8698 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8699 Value.getOperand(0), ST,this))
8700 return SDValue(NewST, 0);
8703 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8704 Value.getOperand(1).getOpcode() != ISD::Constant)
8707 SDValue N0 = Value.getOperand(0);
8708 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8709 Chain == SDValue(N0.getNode(), 1)) {
8710 LoadSDNode *LD = cast<LoadSDNode>(N0);
8711 if (LD->getBasePtr() != Ptr ||
8712 LD->getPointerInfo().getAddrSpace() !=
8713 ST->getPointerInfo().getAddrSpace())
8716 // Find the type to narrow it the load / op / store to.
8717 SDValue N1 = Value.getOperand(1);
8718 unsigned BitWidth = N1.getValueSizeInBits();
8719 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8720 if (Opc == ISD::AND)
8721 Imm ^= APInt::getAllOnesValue(BitWidth);
8722 if (Imm == 0 || Imm.isAllOnesValue())
8724 unsigned ShAmt = Imm.countTrailingZeros();
8725 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8726 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8727 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8728 while (NewBW < BitWidth &&
8729 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8730 TLI.isNarrowingProfitable(VT, NewVT))) {
8731 NewBW = NextPowerOf2(NewBW);
8732 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8734 if (NewBW >= BitWidth)
8737 // If the lsb changed does not start at the type bitwidth boundary,
8738 // start at the previous one.
8740 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8741 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8742 std::min(BitWidth, ShAmt + NewBW));
8743 if ((Imm & Mask) == Imm) {
8744 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8745 if (Opc == ISD::AND)
8746 NewImm ^= APInt::getAllOnesValue(NewBW);
8747 uint64_t PtrOff = ShAmt / 8;
8748 // For big endian targets, we need to adjust the offset to the pointer to
8749 // load the correct bytes.
8750 if (TLI.isBigEndian())
8751 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8753 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8754 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8755 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8758 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8759 Ptr.getValueType(), Ptr,
8760 DAG.getConstant(PtrOff, Ptr.getValueType()));
8761 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8762 LD->getChain(), NewPtr,
8763 LD->getPointerInfo().getWithOffset(PtrOff),
8764 LD->isVolatile(), LD->isNonTemporal(),
8765 LD->isInvariant(), NewAlign,
8767 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8768 DAG.getConstant(NewImm, NewVT));
8769 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8771 ST->getPointerInfo().getWithOffset(PtrOff),
8772 false, false, NewAlign);
8774 AddToWorkList(NewPtr.getNode());
8775 AddToWorkList(NewLD.getNode());
8776 AddToWorkList(NewVal.getNode());
8777 WorkListRemover DeadNodes(*this);
8778 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8787 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8788 /// if the load value isn't used by any other operations, then consider
8789 /// transforming the pair to integer load / store operations if the target
8790 /// deems the transformation profitable.
8791 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8792 StoreSDNode *ST = cast<StoreSDNode>(N);
8793 SDValue Chain = ST->getChain();
8794 SDValue Value = ST->getValue();
8795 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8796 Value.hasOneUse() &&
8797 Chain == SDValue(Value.getNode(), 1)) {
8798 LoadSDNode *LD = cast<LoadSDNode>(Value);
8799 EVT VT = LD->getMemoryVT();
8800 if (!VT.isFloatingPoint() ||
8801 VT != ST->getMemoryVT() ||
8802 LD->isNonTemporal() ||
8803 ST->isNonTemporal() ||
8804 LD->getPointerInfo().getAddrSpace() != 0 ||
8805 ST->getPointerInfo().getAddrSpace() != 0)
8808 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8809 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8810 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8811 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8812 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8815 unsigned LDAlign = LD->getAlignment();
8816 unsigned STAlign = ST->getAlignment();
8817 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8818 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8819 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8822 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8823 LD->getChain(), LD->getBasePtr(),
8824 LD->getPointerInfo(),
8825 false, false, false, LDAlign);
8827 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8828 NewLD, ST->getBasePtr(),
8829 ST->getPointerInfo(),
8830 false, false, STAlign);
8832 AddToWorkList(NewLD.getNode());
8833 AddToWorkList(NewST.getNode());
8834 WorkListRemover DeadNodes(*this);
8835 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8843 /// Helper struct to parse and store a memory address as base + index + offset.
8844 /// We ignore sign extensions when it is safe to do so.
8845 /// The following two expressions are not equivalent. To differentiate we need
8846 /// to store whether there was a sign extension involved in the index
8848 /// (load (i64 add (i64 copyfromreg %c)
8849 /// (i64 signextend (add (i8 load %index)
8853 /// (load (i64 add (i64 copyfromreg %c)
8854 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8856 struct BaseIndexOffset {
8860 bool IsIndexSignExt;
8862 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8864 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8865 bool IsIndexSignExt) :
8866 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8868 bool equalBaseIndex(const BaseIndexOffset &Other) {
8869 return Other.Base == Base && Other.Index == Index &&
8870 Other.IsIndexSignExt == IsIndexSignExt;
8873 /// Parses tree in Ptr for base, index, offset addresses.
8874 static BaseIndexOffset match(SDValue Ptr) {
8875 bool IsIndexSignExt = false;
8877 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8878 // instruction, then it could be just the BASE or everything else we don't
8879 // know how to handle. Just use Ptr as BASE and give up.
8880 if (Ptr->getOpcode() != ISD::ADD)
8881 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8883 // We know that we have at least an ADD instruction. Try to pattern match
8884 // the simple case of BASE + OFFSET.
8885 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8886 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8887 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8891 // Inside a loop the current BASE pointer is calculated using an ADD and a
8892 // MUL instruction. In this case Ptr is the actual BASE pointer.
8893 // (i64 add (i64 %array_ptr)
8894 // (i64 mul (i64 %induction_var)
8895 // (i64 %element_size)))
8896 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8897 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8899 // Look at Base + Index + Offset cases.
8900 SDValue Base = Ptr->getOperand(0);
8901 SDValue IndexOffset = Ptr->getOperand(1);
8903 // Skip signextends.
8904 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8905 IndexOffset = IndexOffset->getOperand(0);
8906 IsIndexSignExt = true;
8909 // Either the case of Base + Index (no offset) or something else.
8910 if (IndexOffset->getOpcode() != ISD::ADD)
8911 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8913 // Now we have the case of Base + Index + offset.
8914 SDValue Index = IndexOffset->getOperand(0);
8915 SDValue Offset = IndexOffset->getOperand(1);
8917 if (!isa<ConstantSDNode>(Offset))
8918 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8920 // Ignore signextends.
8921 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8922 Index = Index->getOperand(0);
8923 IsIndexSignExt = true;
8924 } else IsIndexSignExt = false;
8926 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8927 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8931 /// Holds a pointer to an LSBaseSDNode as well as information on where it
8932 /// is located in a sequence of memory operations connected by a chain.
8934 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8935 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8936 // Ptr to the mem node.
8937 LSBaseSDNode *MemNode;
8938 // Offset from the base ptr.
8939 int64_t OffsetFromBase;
8940 // What is the sequence number of this mem node.
8941 // Lowest mem operand in the DAG starts at zero.
8942 unsigned SequenceNum;
8945 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8946 EVT MemVT = St->getMemoryVT();
8947 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
8948 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8949 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
8951 // Don't merge vectors into wider inputs.
8952 if (MemVT.isVector() || !MemVT.isSimple())
8955 // Perform an early exit check. Do not bother looking at stored values that
8956 // are not constants or loads.
8957 SDValue StoredVal = St->getValue();
8958 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8959 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8963 // Only look at ends of store sequences.
8964 SDValue Chain = SDValue(St, 1);
8965 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8968 // This holds the base pointer, index, and the offset in bytes from the base
8970 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
8972 // We must have a base and an offset.
8973 if (!BasePtr.Base.getNode())
8976 // Do not handle stores to undef base pointers.
8977 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
8980 // Save the LoadSDNodes that we find in the chain.
8981 // We need to make sure that these nodes do not interfere with
8982 // any of the store nodes.
8983 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8985 // Save the StoreSDNodes that we find in the chain.
8986 SmallVector<MemOpLink, 8> StoreNodes;
8988 // Walk up the chain and look for nodes with offsets from the same
8989 // base pointer. Stop when reaching an instruction with a different kind
8990 // or instruction which has a different base pointer.
8992 StoreSDNode *Index = St;
8994 // If the chain has more than one use, then we can't reorder the mem ops.
8995 if (Index != St && !SDValue(Index, 1)->hasOneUse())
8998 // Find the base pointer and offset for this memory node.
8999 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9001 // Check that the base pointer is the same as the original one.
9002 if (!Ptr.equalBaseIndex(BasePtr))
9005 // Check that the alignment is the same.
9006 if (Index->getAlignment() != St->getAlignment())
9009 // The memory operands must not be volatile.
9010 if (Index->isVolatile() || Index->isIndexed())
9014 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9015 if (St->isTruncatingStore())
9018 // The stored memory type must be the same.
9019 if (Index->getMemoryVT() != MemVT)
9022 // We do not allow unaligned stores because we want to prevent overriding
9024 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9027 // We found a potential memory operand to merge.
9028 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9030 // Find the next memory operand in the chain. If the next operand in the
9031 // chain is a store then move up and continue the scan with the next
9032 // memory operand. If the next operand is a load save it and use alias
9033 // information to check if it interferes with anything.
9034 SDNode *NextInChain = Index->getChain().getNode();
9036 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9037 // We found a store node. Use it for the next iteration.
9040 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9041 if (Ldn->isVolatile()) {
9046 // Save the load node for later. Continue the scan.
9047 AliasLoadNodes.push_back(Ldn);
9048 NextInChain = Ldn->getChain().getNode();
9057 // Check if there is anything to merge.
9058 if (StoreNodes.size() < 2)
9061 // Sort the memory operands according to their distance from the base pointer.
9062 std::sort(StoreNodes.begin(), StoreNodes.end(),
9063 [](MemOpLink LHS, MemOpLink RHS) {
9064 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9065 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9066 LHS.SequenceNum > RHS.SequenceNum);
9069 // Scan the memory operations on the chain and find the first non-consecutive
9070 // store memory address.
9071 unsigned LastConsecutiveStore = 0;
9072 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9073 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9075 // Check that the addresses are consecutive starting from the second
9076 // element in the list of stores.
9078 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9079 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9084 // Check if this store interferes with any of the loads that we found.
9085 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9086 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9090 // We found a load that alias with this store. Stop the sequence.
9094 // Mark this node as useful.
9095 LastConsecutiveStore = i;
9098 // The node with the lowest store address.
9099 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9101 // Store the constants into memory as one consecutive store.
9103 unsigned LastLegalType = 0;
9104 unsigned LastLegalVectorType = 0;
9105 bool NonZero = false;
9106 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9107 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9108 SDValue StoredVal = St->getValue();
9110 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9111 NonZero |= !C->isNullValue();
9112 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9113 NonZero |= !C->getConstantFPValue()->isNullValue();
9119 // Find a legal type for the constant store.
9120 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9121 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9122 if (TLI.isTypeLegal(StoreTy))
9123 LastLegalType = i+1;
9124 // Or check whether a truncstore is legal.
9125 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9126 TargetLowering::TypePromoteInteger) {
9127 EVT LegalizedStoredValueTy =
9128 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9129 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9130 LastLegalType = i+1;
9133 // Find a legal type for the vector store.
9134 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9135 if (TLI.isTypeLegal(Ty))
9136 LastLegalVectorType = i + 1;
9139 // We only use vectors if the constant is known to be zero and the
9140 // function is not marked with the noimplicitfloat attribute.
9141 if (NonZero || NoVectors)
9142 LastLegalVectorType = 0;
9144 // Check if we found a legal integer type to store.
9145 if (LastLegalType == 0 && LastLegalVectorType == 0)
9148 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9149 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9151 // Make sure we have something to merge.
9155 unsigned EarliestNodeUsed = 0;
9156 for (unsigned i=0; i < NumElem; ++i) {
9157 // Find a chain for the new wide-store operand. Notice that some
9158 // of the store nodes that we found may not be selected for inclusion
9159 // in the wide store. The chain we use needs to be the chain of the
9160 // earliest store node which is *used* and replaced by the wide store.
9161 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9162 EarliestNodeUsed = i;
9165 // The earliest Node in the DAG.
9166 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9167 SDLoc DL(StoreNodes[0].MemNode);
9171 // Find a legal type for the vector store.
9172 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9173 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9174 StoredVal = DAG.getConstant(0, Ty);
9176 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9177 APInt StoreInt(StoreBW, 0);
9179 // Construct a single integer constant which is made of the smaller
9181 bool IsLE = TLI.isLittleEndian();
9182 for (unsigned i = 0; i < NumElem ; ++i) {
9183 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9184 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9185 SDValue Val = St->getValue();
9186 StoreInt<<=ElementSizeBytes*8;
9187 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9188 StoreInt|=C->getAPIntValue().zext(StoreBW);
9189 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9190 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9192 assert(false && "Invalid constant element type");
9196 // Create the new Load and Store operations.
9197 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9198 StoredVal = DAG.getConstant(StoreInt, StoreTy);
9201 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9202 FirstInChain->getBasePtr(),
9203 FirstInChain->getPointerInfo(),
9205 FirstInChain->getAlignment());
9207 // Replace the first store with the new store
9208 CombineTo(EarliestOp, NewStore);
9209 // Erase all other stores.
9210 for (unsigned i = 0; i < NumElem ; ++i) {
9211 if (StoreNodes[i].MemNode == EarliestOp)
9213 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9214 // ReplaceAllUsesWith will replace all uses that existed when it was
9215 // called, but graph optimizations may cause new ones to appear. For
9216 // example, the case in pr14333 looks like
9218 // St's chain -> St -> another store -> X
9220 // And the only difference from St to the other store is the chain.
9221 // When we change it's chain to be St's chain they become identical,
9222 // get CSEed and the net result is that X is now a use of St.
9223 // Since we know that St is redundant, just iterate.
9224 while (!St->use_empty())
9225 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9226 removeFromWorkList(St);
9233 // Below we handle the case of multiple consecutive stores that
9234 // come from multiple consecutive loads. We merge them into a single
9235 // wide load and a single wide store.
9237 // Look for load nodes which are used by the stored values.
9238 SmallVector<MemOpLink, 8> LoadNodes;
9240 // Find acceptable loads. Loads need to have the same chain (token factor),
9241 // must not be zext, volatile, indexed, and they must be consecutive.
9242 BaseIndexOffset LdBasePtr;
9243 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9244 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9245 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9248 // Loads must only have one use.
9249 if (!Ld->hasNUsesOfValue(1, 0))
9252 // Check that the alignment is the same as the stores.
9253 if (Ld->getAlignment() != St->getAlignment())
9256 // The memory operands must not be volatile.
9257 if (Ld->isVolatile() || Ld->isIndexed())
9260 // We do not accept ext loads.
9261 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9264 // The stored memory type must be the same.
9265 if (Ld->getMemoryVT() != MemVT)
9268 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9269 // If this is not the first ptr that we check.
9270 if (LdBasePtr.Base.getNode()) {
9271 // The base ptr must be the same.
9272 if (!LdPtr.equalBaseIndex(LdBasePtr))
9275 // Check that all other base pointers are the same as this one.
9279 // We found a potential memory operand to merge.
9280 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9283 if (LoadNodes.size() < 2)
9286 // Scan the memory operations on the chain and find the first non-consecutive
9287 // load memory address. These variables hold the index in the store node
9289 unsigned LastConsecutiveLoad = 0;
9290 // This variable refers to the size and not index in the array.
9291 unsigned LastLegalVectorType = 0;
9292 unsigned LastLegalIntegerType = 0;
9293 StartAddress = LoadNodes[0].OffsetFromBase;
9294 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9295 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9296 // All loads much share the same chain.
9297 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9300 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9301 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9303 LastConsecutiveLoad = i;
9305 // Find a legal type for the vector store.
9306 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9307 if (TLI.isTypeLegal(StoreTy))
9308 LastLegalVectorType = i + 1;
9310 // Find a legal type for the integer store.
9311 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9312 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9313 if (TLI.isTypeLegal(StoreTy))
9314 LastLegalIntegerType = i + 1;
9315 // Or check whether a truncstore and extload is legal.
9316 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9317 TargetLowering::TypePromoteInteger) {
9318 EVT LegalizedStoredValueTy =
9319 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9320 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9321 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9322 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9323 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9324 LastLegalIntegerType = i+1;
9328 // Only use vector types if the vector type is larger than the integer type.
9329 // If they are the same, use integers.
9330 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9331 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9333 // We add +1 here because the LastXXX variables refer to location while
9334 // the NumElem refers to array/index size.
9335 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9336 NumElem = std::min(LastLegalType, NumElem);
9341 // The earliest Node in the DAG.
9342 unsigned EarliestNodeUsed = 0;
9343 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9344 for (unsigned i=1; i<NumElem; ++i) {
9345 // Find a chain for the new wide-store operand. Notice that some
9346 // of the store nodes that we found may not be selected for inclusion
9347 // in the wide store. The chain we use needs to be the chain of the
9348 // earliest store node which is *used* and replaced by the wide store.
9349 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9350 EarliestNodeUsed = i;
9353 // Find if it is better to use vectors or integers to load and store
9357 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9359 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9360 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9363 SDLoc LoadDL(LoadNodes[0].MemNode);
9364 SDLoc StoreDL(StoreNodes[0].MemNode);
9366 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9367 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9368 FirstLoad->getChain(),
9369 FirstLoad->getBasePtr(),
9370 FirstLoad->getPointerInfo(),
9371 false, false, false,
9372 FirstLoad->getAlignment());
9374 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9375 FirstInChain->getBasePtr(),
9376 FirstInChain->getPointerInfo(), false, false,
9377 FirstInChain->getAlignment());
9379 // Replace one of the loads with the new load.
9380 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9381 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9382 SDValue(NewLoad.getNode(), 1));
9384 // Remove the rest of the load chains.
9385 for (unsigned i = 1; i < NumElem ; ++i) {
9386 // Replace all chain users of the old load nodes with the chain of the new
9388 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9389 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9392 // Replace the first store with the new store.
9393 CombineTo(EarliestOp, NewStore);
9394 // Erase all other stores.
9395 for (unsigned i = 0; i < NumElem ; ++i) {
9396 // Remove all Store nodes.
9397 if (StoreNodes[i].MemNode == EarliestOp)
9399 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9400 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9401 removeFromWorkList(St);
9408 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9409 StoreSDNode *ST = cast<StoreSDNode>(N);
9410 SDValue Chain = ST->getChain();
9411 SDValue Value = ST->getValue();
9412 SDValue Ptr = ST->getBasePtr();
9414 // If this is a store of a bit convert, store the input value if the
9415 // resultant store does not need a higher alignment than the original.
9416 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9417 ST->isUnindexed()) {
9418 unsigned OrigAlign = ST->getAlignment();
9419 EVT SVT = Value.getOperand(0).getValueType();
9420 unsigned Align = TLI.getDataLayout()->
9421 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9422 if (Align <= OrigAlign &&
9423 ((!LegalOperations && !ST->isVolatile()) ||
9424 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9425 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9426 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9427 ST->isNonTemporal(), OrigAlign,
9431 // Turn 'store undef, Ptr' -> nothing.
9432 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9435 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9436 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9437 // NOTE: If the original store is volatile, this transform must not increase
9438 // the number of stores. For example, on x86-32 an f64 can be stored in one
9439 // processor operation but an i64 (which is not legal) requires two. So the
9440 // transform should not be done in this case.
9441 if (Value.getOpcode() != ISD::TargetConstantFP) {
9443 switch (CFP->getSimpleValueType(0).SimpleTy) {
9444 default: llvm_unreachable("Unknown FP type");
9445 case MVT::f16: // We don't do this for these yet.
9451 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9452 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9453 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9454 bitcastToAPInt().getZExtValue(), MVT::i32);
9455 return DAG.getStore(Chain, SDLoc(N), Tmp,
9456 Ptr, ST->getMemOperand());
9460 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9461 !ST->isVolatile()) ||
9462 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9463 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9464 getZExtValue(), MVT::i64);
9465 return DAG.getStore(Chain, SDLoc(N), Tmp,
9466 Ptr, ST->getMemOperand());
9469 if (!ST->isVolatile() &&
9470 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9471 // Many FP stores are not made apparent until after legalize, e.g. for
9472 // argument passing. Since this is so common, custom legalize the
9473 // 64-bit integer store into two 32-bit stores.
9474 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9475 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9476 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9477 if (TLI.isBigEndian()) std::swap(Lo, Hi);
9479 unsigned Alignment = ST->getAlignment();
9480 bool isVolatile = ST->isVolatile();
9481 bool isNonTemporal = ST->isNonTemporal();
9482 const MDNode *TBAAInfo = ST->getTBAAInfo();
9484 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9485 Ptr, ST->getPointerInfo(),
9486 isVolatile, isNonTemporal,
9487 ST->getAlignment(), TBAAInfo);
9488 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9489 DAG.getConstant(4, Ptr.getValueType()));
9490 Alignment = MinAlign(Alignment, 4U);
9491 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9492 Ptr, ST->getPointerInfo().getWithOffset(4),
9493 isVolatile, isNonTemporal,
9494 Alignment, TBAAInfo);
9495 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9504 // Try to infer better alignment information than the store already has.
9505 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9506 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9507 if (Align > ST->getAlignment())
9508 return DAG.getTruncStore(Chain, SDLoc(N), Value,
9509 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9510 ST->isVolatile(), ST->isNonTemporal(), Align,
9515 // Try transforming a pair floating point load / store ops to integer
9516 // load / store ops.
9517 SDValue NewST = TransformFPLoadStorePair(N);
9518 if (NewST.getNode())
9521 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9522 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9524 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9525 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9528 if (UseAA && ST->isUnindexed()) {
9529 // Walk up chain skipping non-aliasing memory nodes.
9530 SDValue BetterChain = FindBetterChain(N, Chain);
9532 // If there is a better chain.
9533 if (Chain != BetterChain) {
9536 // Replace the chain to avoid dependency.
9537 if (ST->isTruncatingStore()) {
9538 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9539 ST->getMemoryVT(), ST->getMemOperand());
9541 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9542 ST->getMemOperand());
9545 // Create token to keep both nodes around.
9546 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9547 MVT::Other, Chain, ReplStore);
9549 // Make sure the new and old chains are cleaned up.
9550 AddToWorkList(Token.getNode());
9552 // Don't add users to work list.
9553 return CombineTo(N, Token, false);
9557 // Try transforming N to an indexed store.
9558 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9559 return SDValue(N, 0);
9561 // FIXME: is there such a thing as a truncating indexed store?
9562 if (ST->isTruncatingStore() && ST->isUnindexed() &&
9563 Value.getValueType().isInteger()) {
9564 // See if we can simplify the input to this truncstore with knowledge that
9565 // only the low bits are being used. For example:
9566 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
9568 GetDemandedBits(Value,
9569 APInt::getLowBitsSet(
9570 Value.getValueType().getScalarType().getSizeInBits(),
9571 ST->getMemoryVT().getScalarType().getSizeInBits()));
9572 AddToWorkList(Value.getNode());
9573 if (Shorter.getNode())
9574 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9575 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9577 // Otherwise, see if we can simplify the operation with
9578 // SimplifyDemandedBits, which only works if the value has a single use.
9579 if (SimplifyDemandedBits(Value,
9580 APInt::getLowBitsSet(
9581 Value.getValueType().getScalarType().getSizeInBits(),
9582 ST->getMemoryVT().getScalarType().getSizeInBits())))
9583 return SDValue(N, 0);
9586 // If this is a load followed by a store to the same location, then the store
9588 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9589 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9590 ST->isUnindexed() && !ST->isVolatile() &&
9591 // There can't be any side effects between the load and store, such as
9593 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9594 // The store is dead, remove it.
9599 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9600 // truncating store. We can do this even if this is already a truncstore.
9601 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9602 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9603 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9604 ST->getMemoryVT())) {
9605 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9606 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9609 // Only perform this optimization before the types are legal, because we
9610 // don't want to perform this optimization on every DAGCombine invocation.
9612 bool EverChanged = false;
9615 // There can be multiple store sequences on the same chain.
9616 // Keep trying to merge store sequences until we are unable to do so
9617 // or until we merge the last store on the chain.
9618 bool Changed = MergeConsecutiveStores(ST);
9619 EverChanged |= Changed;
9620 if (!Changed) break;
9621 } while (ST->getOpcode() != ISD::DELETED_NODE);
9624 return SDValue(N, 0);
9627 return ReduceLoadOpStoreWidth(N);
9630 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9631 SDValue InVec = N->getOperand(0);
9632 SDValue InVal = N->getOperand(1);
9633 SDValue EltNo = N->getOperand(2);
9636 // If the inserted element is an UNDEF, just use the input vector.
9637 if (InVal.getOpcode() == ISD::UNDEF)
9640 EVT VT = InVec.getValueType();
9642 // If we can't generate a legal BUILD_VECTOR, exit
9643 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9646 // Check that we know which element is being inserted
9647 if (!isa<ConstantSDNode>(EltNo))
9649 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9651 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9652 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9654 SmallVector<SDValue, 8> Ops;
9655 // Do not combine these two vectors if the output vector will not replace
9656 // the input vector.
9657 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9658 Ops.append(InVec.getNode()->op_begin(),
9659 InVec.getNode()->op_end());
9660 } else if (InVec.getOpcode() == ISD::UNDEF) {
9661 unsigned NElts = VT.getVectorNumElements();
9662 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9667 // Insert the element
9668 if (Elt < Ops.size()) {
9669 // All the operands of BUILD_VECTOR must have the same type;
9670 // we enforce that here.
9671 EVT OpVT = Ops[0].getValueType();
9672 if (InVal.getValueType() != OpVT)
9673 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9674 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9675 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9679 // Return the new vector
9680 return DAG.getNode(ISD::BUILD_VECTOR, dl,
9681 VT, &Ops[0], Ops.size());
9684 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9685 // (vextract (scalar_to_vector val, 0) -> val
9686 SDValue InVec = N->getOperand(0);
9687 EVT VT = InVec.getValueType();
9688 EVT NVT = N->getValueType(0);
9690 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9691 // Check if the result type doesn't match the inserted element type. A
9692 // SCALAR_TO_VECTOR may truncate the inserted element and the
9693 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9694 SDValue InOp = InVec.getOperand(0);
9695 if (InOp.getValueType() != NVT) {
9696 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9697 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9702 SDValue EltNo = N->getOperand(1);
9703 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9705 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9706 // We only perform this optimization before the op legalization phase because
9707 // we may introduce new vector instructions which are not backed by TD
9708 // patterns. For example on AVX, extracting elements from a wide vector
9709 // without using extract_subvector. However, if we can find an underlying
9710 // scalar value, then we can always use that.
9711 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9713 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9714 int NumElem = VT.getVectorNumElements();
9715 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9716 // Find the new index to extract from.
9717 int OrigElt = SVOp->getMaskElt(Elt);
9719 // Extracting an undef index is undef.
9721 return DAG.getUNDEF(NVT);
9723 // Select the right vector half to extract from.
9725 if (OrigElt < NumElem) {
9726 SVInVec = InVec->getOperand(0);
9728 SVInVec = InVec->getOperand(1);
9732 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9733 SDValue InOp = SVInVec.getOperand(OrigElt);
9734 if (InOp.getValueType() != NVT) {
9735 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9736 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9742 // FIXME: We should handle recursing on other vector shuffles and
9743 // scalar_to_vector here as well.
9745 if (!LegalOperations) {
9746 EVT IndexTy = TLI.getVectorIdxTy();
9747 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9748 SVInVec, DAG.getConstant(OrigElt, IndexTy));
9752 // Perform only after legalization to ensure build_vector / vector_shuffle
9753 // optimizations have already been done.
9754 if (!LegalOperations) return SDValue();
9756 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9757 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9758 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9761 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9762 bool NewLoad = false;
9763 bool BCNumEltsChanged = false;
9764 EVT ExtVT = VT.getVectorElementType();
9767 // If the result of load has to be truncated, then it's not necessarily
9769 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9772 if (InVec.getOpcode() == ISD::BITCAST) {
9773 // Don't duplicate a load with other uses.
9774 if (!InVec.hasOneUse())
9777 EVT BCVT = InVec.getOperand(0).getValueType();
9778 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9780 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9781 BCNumEltsChanged = true;
9782 InVec = InVec.getOperand(0);
9783 ExtVT = BCVT.getVectorElementType();
9787 LoadSDNode *LN0 = nullptr;
9788 const ShuffleVectorSDNode *SVN = nullptr;
9789 if (ISD::isNormalLoad(InVec.getNode())) {
9790 LN0 = cast<LoadSDNode>(InVec);
9791 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9792 InVec.getOperand(0).getValueType() == ExtVT &&
9793 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9794 // Don't duplicate a load with other uses.
9795 if (!InVec.hasOneUse())
9798 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9799 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9800 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9802 // (load $addr+1*size)
9804 // Don't duplicate a load with other uses.
9805 if (!InVec.hasOneUse())
9808 // If the bit convert changed the number of elements, it is unsafe
9809 // to examine the mask.
9810 if (BCNumEltsChanged)
9813 // Select the input vector, guarding against out of range extract vector.
9814 unsigned NumElems = VT.getVectorNumElements();
9815 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9816 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9818 if (InVec.getOpcode() == ISD::BITCAST) {
9819 // Don't duplicate a load with other uses.
9820 if (!InVec.hasOneUse())
9823 InVec = InVec.getOperand(0);
9825 if (ISD::isNormalLoad(InVec.getNode())) {
9826 LN0 = cast<LoadSDNode>(InVec);
9827 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9831 // Make sure we found a non-volatile load and the extractelement is
9833 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9836 // If Idx was -1 above, Elt is going to be -1, so just return undef.
9838 return DAG.getUNDEF(LVT);
9840 unsigned Align = LN0->getAlignment();
9842 // Check the resultant load doesn't need a higher alignment than the
9846 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9848 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9854 SDValue NewPtr = LN0->getBasePtr();
9855 unsigned PtrOff = 0;
9858 PtrOff = LVT.getSizeInBits() * Elt / 8;
9859 EVT PtrType = NewPtr.getValueType();
9860 if (TLI.isBigEndian())
9861 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9862 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9863 DAG.getConstant(PtrOff, PtrType));
9866 // The replacement we need to do here is a little tricky: we need to
9867 // replace an extractelement of a load with a load.
9868 // Use ReplaceAllUsesOfValuesWith to do the replacement.
9869 // Note that this replacement assumes that the extractvalue is the only
9870 // use of the load; that's okay because we don't want to perform this
9871 // transformation in other cases anyway.
9874 if (NVT.bitsGT(LVT)) {
9875 // If the result type of vextract is wider than the load, then issue an
9876 // extending load instead.
9877 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9878 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9879 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9880 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9881 LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9882 Align, LN0->getTBAAInfo());
9883 Chain = Load.getValue(1);
9885 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9886 LN0->getPointerInfo().getWithOffset(PtrOff),
9887 LN0->isVolatile(), LN0->isNonTemporal(),
9888 LN0->isInvariant(), Align, LN0->getTBAAInfo());
9889 Chain = Load.getValue(1);
9890 if (NVT.bitsLT(LVT))
9891 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
9893 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
9895 WorkListRemover DeadNodes(*this);
9896 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
9897 SDValue To[] = { Load, Chain };
9898 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9899 // Since we're explcitly calling ReplaceAllUses, add the new node to the
9900 // worklist explicitly as well.
9901 AddToWorkList(Load.getNode());
9902 AddUsersToWorkList(Load.getNode()); // Add users too
9903 // Make sure to revisit this node to clean it up; it will usually be dead.
9905 return SDValue(N, 0);
9911 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
9912 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9913 // We perform this optimization post type-legalization because
9914 // the type-legalizer often scalarizes integer-promoted vectors.
9915 // Performing this optimization before may create bit-casts which
9916 // will be type-legalized to complex code sequences.
9917 // We perform this optimization only before the operation legalizer because we
9918 // may introduce illegal operations.
9919 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9922 unsigned NumInScalars = N->getNumOperands();
9924 EVT VT = N->getValueType(0);
9926 // Check to see if this is a BUILD_VECTOR of a bunch of values
9927 // which come from any_extend or zero_extend nodes. If so, we can create
9928 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
9929 // optimizations. We do not handle sign-extend because we can't fill the sign
9931 EVT SourceType = MVT::Other;
9932 bool AllAnyExt = true;
9934 for (unsigned i = 0; i != NumInScalars; ++i) {
9935 SDValue In = N->getOperand(i);
9936 // Ignore undef inputs.
9937 if (In.getOpcode() == ISD::UNDEF) continue;
9939 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
9940 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9942 // Abort if the element is not an extension.
9943 if (!ZeroExt && !AnyExt) {
9944 SourceType = MVT::Other;
9948 // The input is a ZeroExt or AnyExt. Check the original type.
9949 EVT InTy = In.getOperand(0).getValueType();
9951 // Check that all of the widened source types are the same.
9952 if (SourceType == MVT::Other)
9955 else if (InTy != SourceType) {
9956 // Multiple income types. Abort.
9957 SourceType = MVT::Other;
9961 // Check if all of the extends are ANY_EXTENDs.
9962 AllAnyExt &= AnyExt;
9965 // In order to have valid types, all of the inputs must be extended from the
9966 // same source type and all of the inputs must be any or zero extend.
9967 // Scalar sizes must be a power of two.
9968 EVT OutScalarTy = VT.getScalarType();
9969 bool ValidTypes = SourceType != MVT::Other &&
9970 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9971 isPowerOf2_32(SourceType.getSizeInBits());
9973 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9974 // turn into a single shuffle instruction.
9978 bool isLE = TLI.isLittleEndian();
9979 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
9980 assert(ElemRatio > 1 && "Invalid element size ratio");
9981 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
9982 DAG.getConstant(0, SourceType);
9984 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
9985 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
9987 // Populate the new build_vector
9988 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9989 SDValue Cast = N->getOperand(i);
9990 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
9991 Cast.getOpcode() == ISD::ZERO_EXTEND ||
9992 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
9994 if (Cast.getOpcode() == ISD::UNDEF)
9995 In = DAG.getUNDEF(SourceType);
9997 In = Cast->getOperand(0);
9998 unsigned Index = isLE ? (i * ElemRatio) :
9999 (i * ElemRatio + (ElemRatio - 1));
10001 assert(Index < Ops.size() && "Invalid index");
10005 // The type of the new BUILD_VECTOR node.
10006 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10007 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10008 "Invalid vector size");
10009 // Check if the new vector type is legal.
10010 if (!isTypeLegal(VecVT)) return SDValue();
10012 // Make the new BUILD_VECTOR.
10013 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
10015 // The new BUILD_VECTOR node has the potential to be further optimized.
10016 AddToWorkList(BV.getNode());
10017 // Bitcast to the desired type.
10018 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10021 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10022 EVT VT = N->getValueType(0);
10024 unsigned NumInScalars = N->getNumOperands();
10027 EVT SrcVT = MVT::Other;
10028 unsigned Opcode = ISD::DELETED_NODE;
10029 unsigned NumDefs = 0;
10031 for (unsigned i = 0; i != NumInScalars; ++i) {
10032 SDValue In = N->getOperand(i);
10033 unsigned Opc = In.getOpcode();
10035 if (Opc == ISD::UNDEF)
10038 // If all scalar values are floats and converted from integers.
10039 if (Opcode == ISD::DELETED_NODE &&
10040 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10047 EVT InVT = In.getOperand(0).getValueType();
10049 // If all scalar values are typed differently, bail out. It's chosen to
10050 // simplify BUILD_VECTOR of integer types.
10051 if (SrcVT == MVT::Other)
10058 // If the vector has just one element defined, it's not worth to fold it into
10059 // a vectorized one.
10063 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10064 && "Should only handle conversion from integer to float.");
10065 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10067 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10069 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10072 SmallVector<SDValue, 8> Opnds;
10073 for (unsigned i = 0; i != NumInScalars; ++i) {
10074 SDValue In = N->getOperand(i);
10076 if (In.getOpcode() == ISD::UNDEF)
10077 Opnds.push_back(DAG.getUNDEF(SrcVT));
10079 Opnds.push_back(In.getOperand(0));
10081 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
10082 &Opnds[0], Opnds.size());
10083 AddToWorkList(BV.getNode());
10085 return DAG.getNode(Opcode, dl, VT, BV);
10088 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10089 unsigned NumInScalars = N->getNumOperands();
10091 EVT VT = N->getValueType(0);
10093 // A vector built entirely of undefs is undef.
10094 if (ISD::allOperandsUndef(N))
10095 return DAG.getUNDEF(VT);
10097 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10101 V = reduceBuildVecConvertToConvertBuildVec(N);
10105 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10106 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10107 // at most two distinct vectors, turn this into a shuffle node.
10109 // May only combine to shuffle after legalize if shuffle is legal.
10110 if (LegalOperations &&
10111 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10114 SDValue VecIn1, VecIn2;
10115 for (unsigned i = 0; i != NumInScalars; ++i) {
10116 // Ignore undef inputs.
10117 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10119 // If this input is something other than a EXTRACT_VECTOR_ELT with a
10120 // constant index, bail out.
10121 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10122 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10123 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10127 // We allow up to two distinct input vectors.
10128 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10129 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10132 if (!VecIn1.getNode()) {
10133 VecIn1 = ExtractedFromVec;
10134 } else if (!VecIn2.getNode()) {
10135 VecIn2 = ExtractedFromVec;
10137 // Too many inputs.
10138 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10143 // If everything is good, we can make a shuffle operation.
10144 if (VecIn1.getNode()) {
10145 SmallVector<int, 8> Mask;
10146 for (unsigned i = 0; i != NumInScalars; ++i) {
10147 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10148 Mask.push_back(-1);
10152 // If extracting from the first vector, just use the index directly.
10153 SDValue Extract = N->getOperand(i);
10154 SDValue ExtVal = Extract.getOperand(1);
10155 if (Extract.getOperand(0) == VecIn1) {
10156 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10157 if (ExtIndex > VT.getVectorNumElements())
10160 Mask.push_back(ExtIndex);
10164 // Otherwise, use InIdx + VecSize
10165 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10166 Mask.push_back(Idx+NumInScalars);
10169 // We can't generate a shuffle node with mismatched input and output types.
10170 // Attempt to transform a single input vector to the correct type.
10171 if ((VT != VecIn1.getValueType())) {
10172 // We don't support shuffeling between TWO values of different types.
10173 if (VecIn2.getNode())
10176 // We only support widening of vectors which are half the size of the
10177 // output registers. For example XMM->YMM widening on X86 with AVX.
10178 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10181 // If the input vector type has a different base type to the output
10182 // vector type, bail out.
10183 if (VecIn1.getValueType().getVectorElementType() !=
10184 VT.getVectorElementType())
10187 // Widen the input vector by adding undef values.
10188 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10189 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10192 // If VecIn2 is unused then change it to undef.
10193 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10195 // Check that we were able to transform all incoming values to the same
10197 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10198 VecIn1.getValueType() != VT)
10201 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10202 if (!isTypeLegal(VT))
10205 // Return the new VECTOR_SHUFFLE node.
10209 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10215 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10216 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10217 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10218 // inputs come from at most two distinct vectors, turn this into a shuffle
10221 // If we only have one input vector, we don't need to do any concatenation.
10222 if (N->getNumOperands() == 1)
10223 return N->getOperand(0);
10225 // Check if all of the operands are undefs.
10226 EVT VT = N->getValueType(0);
10227 if (ISD::allOperandsUndef(N))
10228 return DAG.getUNDEF(VT);
10230 // Optimize concat_vectors where one of the vectors is undef.
10231 if (N->getNumOperands() == 2 &&
10232 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10233 SDValue In = N->getOperand(0);
10234 assert(In.getValueType().isVector() && "Must concat vectors");
10236 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10237 if (In->getOpcode() == ISD::BITCAST &&
10238 !In->getOperand(0)->getValueType(0).isVector()) {
10239 SDValue Scalar = In->getOperand(0);
10240 EVT SclTy = Scalar->getValueType(0);
10242 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10245 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10246 VT.getSizeInBits() / SclTy.getSizeInBits());
10247 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10250 SDLoc dl = SDLoc(N);
10251 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10252 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10256 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10257 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10258 if (N->getNumOperands() == 2 &&
10259 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10260 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10261 EVT VT = N->getValueType(0);
10262 SDValue N0 = N->getOperand(0);
10263 SDValue N1 = N->getOperand(1);
10264 SmallVector<SDValue, 8> Opnds;
10265 unsigned BuildVecNumElts = N0.getNumOperands();
10267 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10268 Opnds.push_back(N0.getOperand(i));
10269 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10270 Opnds.push_back(N1.getOperand(i));
10272 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
10276 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10277 // nodes often generate nop CONCAT_VECTOR nodes.
10278 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10279 // place the incoming vectors at the exact same location.
10280 SDValue SingleSource = SDValue();
10281 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10283 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10284 SDValue Op = N->getOperand(i);
10286 if (Op.getOpcode() == ISD::UNDEF)
10289 // Check if this is the identity extract:
10290 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10293 // Find the single incoming vector for the extract_subvector.
10294 if (SingleSource.getNode()) {
10295 if (Op.getOperand(0) != SingleSource)
10298 SingleSource = Op.getOperand(0);
10300 // Check the source type is the same as the type of the result.
10301 // If not, this concat may extend the vector, so we can not
10302 // optimize it away.
10303 if (SingleSource.getValueType() != N->getValueType(0))
10307 unsigned IdentityIndex = i * PartNumElem;
10308 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10309 // The extract index must be constant.
10313 // Check that we are reading from the identity index.
10314 if (CS->getZExtValue() != IdentityIndex)
10318 if (SingleSource.getNode())
10319 return SingleSource;
10324 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10325 EVT NVT = N->getValueType(0);
10326 SDValue V = N->getOperand(0);
10328 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10330 // (extract_subvec (concat V1, V2, ...), i)
10333 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10335 if (V->getOperand(0).getValueType() != NVT)
10337 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10338 unsigned NumElems = NVT.getVectorNumElements();
10339 assert((Idx % NumElems) == 0 &&
10340 "IDX in concat is not a multiple of the result vector length.");
10341 return V->getOperand(Idx / NumElems);
10345 if (V->getOpcode() == ISD::BITCAST)
10346 V = V.getOperand(0);
10348 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10350 // Handle only simple case where vector being inserted and vector
10351 // being extracted are of same type, and are half size of larger vectors.
10352 EVT BigVT = V->getOperand(0).getValueType();
10353 EVT SmallVT = V->getOperand(1).getValueType();
10354 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10357 // Only handle cases where both indexes are constants with the same type.
10358 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10359 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10361 if (InsIdx && ExtIdx &&
10362 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10363 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10365 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10367 // indices are equal or bit offsets are equal => V1
10368 // otherwise => (extract_subvec V1, ExtIdx)
10369 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10370 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10371 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10372 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10373 DAG.getNode(ISD::BITCAST, dl,
10374 N->getOperand(0).getValueType(),
10375 V->getOperand(0)), N->getOperand(1));
10382 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10383 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10384 EVT VT = N->getValueType(0);
10385 unsigned NumElts = VT.getVectorNumElements();
10387 SDValue N0 = N->getOperand(0);
10388 SDValue N1 = N->getOperand(1);
10389 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10391 SmallVector<SDValue, 4> Ops;
10392 EVT ConcatVT = N0.getOperand(0).getValueType();
10393 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10394 unsigned NumConcats = NumElts / NumElemsPerConcat;
10396 // Look at every vector that's inserted. We're looking for exact
10397 // subvector-sized copies from a concatenated vector
10398 for (unsigned I = 0; I != NumConcats; ++I) {
10399 // Make sure we're dealing with a copy.
10400 unsigned Begin = I * NumElemsPerConcat;
10401 bool AllUndef = true, NoUndef = true;
10402 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10403 if (SVN->getMaskElt(J) >= 0)
10410 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10413 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10414 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10417 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10418 if (FirstElt < N0.getNumOperands())
10419 Ops.push_back(N0.getOperand(FirstElt));
10421 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10423 } else if (AllUndef) {
10424 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10425 } else { // Mixed with general masks and undefs, can't do optimization.
10430 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
10434 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10435 EVT VT = N->getValueType(0);
10436 unsigned NumElts = VT.getVectorNumElements();
10438 SDValue N0 = N->getOperand(0);
10439 SDValue N1 = N->getOperand(1);
10441 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10443 // Canonicalize shuffle undef, undef -> undef
10444 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10445 return DAG.getUNDEF(VT);
10447 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10449 // Canonicalize shuffle v, v -> v, undef
10451 SmallVector<int, 8> NewMask;
10452 for (unsigned i = 0; i != NumElts; ++i) {
10453 int Idx = SVN->getMaskElt(i);
10454 if (Idx >= (int)NumElts) Idx -= NumElts;
10455 NewMask.push_back(Idx);
10457 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10461 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10462 if (N0.getOpcode() == ISD::UNDEF) {
10463 SmallVector<int, 8> NewMask;
10464 for (unsigned i = 0; i != NumElts; ++i) {
10465 int Idx = SVN->getMaskElt(i);
10467 if (Idx >= (int)NumElts)
10470 Idx = -1; // remove reference to lhs
10472 NewMask.push_back(Idx);
10474 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10478 // Remove references to rhs if it is undef
10479 if (N1.getOpcode() == ISD::UNDEF) {
10480 bool Changed = false;
10481 SmallVector<int, 8> NewMask;
10482 for (unsigned i = 0; i != NumElts; ++i) {
10483 int Idx = SVN->getMaskElt(i);
10484 if (Idx >= (int)NumElts) {
10488 NewMask.push_back(Idx);
10491 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10494 // If it is a splat, check if the argument vector is another splat or a
10495 // build_vector with all scalar elements the same.
10496 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10497 SDNode *V = N0.getNode();
10499 // If this is a bit convert that changes the element type of the vector but
10500 // not the number of vector elements, look through it. Be careful not to
10501 // look though conversions that change things like v4f32 to v2f64.
10502 if (V->getOpcode() == ISD::BITCAST) {
10503 SDValue ConvInput = V->getOperand(0);
10504 if (ConvInput.getValueType().isVector() &&
10505 ConvInput.getValueType().getVectorNumElements() == NumElts)
10506 V = ConvInput.getNode();
10509 if (V->getOpcode() == ISD::BUILD_VECTOR) {
10510 assert(V->getNumOperands() == NumElts &&
10511 "BUILD_VECTOR has wrong number of operands");
10513 bool AllSame = true;
10514 for (unsigned i = 0; i != NumElts; ++i) {
10515 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10516 Base = V->getOperand(i);
10520 // Splat of <u, u, u, u>, return <u, u, u, u>
10521 if (!Base.getNode())
10523 for (unsigned i = 0; i != NumElts; ++i) {
10524 if (V->getOperand(i) != Base) {
10529 // Splat of <x, x, x, x>, return <x, x, x, x>
10535 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10536 Level < AfterLegalizeVectorOps &&
10537 (N1.getOpcode() == ISD::UNDEF ||
10538 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10539 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10540 SDValue V = partitionShuffleOfConcats(N, DAG);
10546 // If this shuffle node is simply a swizzle of another shuffle node,
10547 // and it reverses the swizzle of the previous shuffle then we can
10548 // optimize shuffle(shuffle(x, undef), undef) -> x.
10549 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10550 N1.getOpcode() == ISD::UNDEF) {
10552 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10554 // Shuffle nodes can only reverse shuffles with a single non-undef value.
10555 if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10558 // The incoming shuffle must be of the same type as the result of the
10559 // current shuffle.
10560 assert(OtherSV->getOperand(0).getValueType() == VT &&
10561 "Shuffle types don't match");
10563 for (unsigned i = 0; i != NumElts; ++i) {
10564 int Idx = SVN->getMaskElt(i);
10565 assert(Idx < (int)NumElts && "Index references undef operand");
10566 // Next, this index comes from the first value, which is the incoming
10567 // shuffle. Adopt the incoming index.
10569 Idx = OtherSV->getMaskElt(Idx);
10571 // The combined shuffle must map each index to itself.
10572 if (Idx >= 0 && (unsigned)Idx != i)
10576 return OtherSV->getOperand(0);
10582 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10583 SDValue N0 = N->getOperand(0);
10584 SDValue N2 = N->getOperand(2);
10586 // If the input vector is a concatenation, and the insert replaces
10587 // one of the halves, we can optimize into a single concat_vectors.
10588 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10589 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10590 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10591 EVT VT = N->getValueType(0);
10593 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10594 // (concat_vectors Z, Y)
10596 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10597 N->getOperand(1), N0.getOperand(1));
10599 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10600 // (concat_vectors X, Z)
10601 if (InsIdx == VT.getVectorNumElements()/2)
10602 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10603 N0.getOperand(0), N->getOperand(1));
10609 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10610 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10611 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10612 /// vector_shuffle V, Zero, <0, 4, 2, 4>
10613 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10614 EVT VT = N->getValueType(0);
10616 SDValue LHS = N->getOperand(0);
10617 SDValue RHS = N->getOperand(1);
10618 if (N->getOpcode() == ISD::AND) {
10619 if (RHS.getOpcode() == ISD::BITCAST)
10620 RHS = RHS.getOperand(0);
10621 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10622 SmallVector<int, 8> Indices;
10623 unsigned NumElts = RHS.getNumOperands();
10624 for (unsigned i = 0; i != NumElts; ++i) {
10625 SDValue Elt = RHS.getOperand(i);
10626 if (!isa<ConstantSDNode>(Elt))
10629 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10630 Indices.push_back(i);
10631 else if (cast<ConstantSDNode>(Elt)->isNullValue())
10632 Indices.push_back(NumElts);
10637 // Let's see if the target supports this vector_shuffle.
10638 EVT RVT = RHS.getValueType();
10639 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10642 // Return the new VECTOR_SHUFFLE node.
10643 EVT EltVT = RVT.getVectorElementType();
10644 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10645 DAG.getConstant(0, EltVT));
10646 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10647 RVT, &ZeroOps[0], ZeroOps.size());
10648 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10649 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10650 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10657 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10658 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10659 assert(N->getValueType(0).isVector() &&
10660 "SimplifyVBinOp only works on vectors!");
10662 SDValue LHS = N->getOperand(0);
10663 SDValue RHS = N->getOperand(1);
10664 SDValue Shuffle = XformToShuffleWithZero(N);
10665 if (Shuffle.getNode()) return Shuffle;
10667 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10669 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10670 RHS.getOpcode() == ISD::BUILD_VECTOR) {
10671 // Check if both vectors are constants. If not bail out.
10672 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10673 cast<BuildVectorSDNode>(RHS)->isConstant()))
10676 SmallVector<SDValue, 8> Ops;
10677 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10678 SDValue LHSOp = LHS.getOperand(i);
10679 SDValue RHSOp = RHS.getOperand(i);
10681 // Can't fold divide by zero.
10682 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10683 N->getOpcode() == ISD::FDIV) {
10684 if ((RHSOp.getOpcode() == ISD::Constant &&
10685 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10686 (RHSOp.getOpcode() == ISD::ConstantFP &&
10687 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10691 EVT VT = LHSOp.getValueType();
10692 EVT RVT = RHSOp.getValueType();
10694 // Integer BUILD_VECTOR operands may have types larger than the element
10695 // size (e.g., when the element type is not legal). Prior to type
10696 // legalization, the types may not match between the two BUILD_VECTORS.
10697 // Truncate one of the operands to make them match.
10698 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10699 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10701 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10705 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10707 if (FoldOp.getOpcode() != ISD::UNDEF &&
10708 FoldOp.getOpcode() != ISD::Constant &&
10709 FoldOp.getOpcode() != ISD::ConstantFP)
10711 Ops.push_back(FoldOp);
10712 AddToWorkList(FoldOp.getNode());
10715 if (Ops.size() == LHS.getNumOperands())
10716 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10717 LHS.getValueType(), &Ops[0], Ops.size());
10723 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10724 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10725 assert(N->getValueType(0).isVector() &&
10726 "SimplifyVUnaryOp only works on vectors!");
10728 SDValue N0 = N->getOperand(0);
10730 if (N0.getOpcode() != ISD::BUILD_VECTOR)
10733 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10734 SmallVector<SDValue, 8> Ops;
10735 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10736 SDValue Op = N0.getOperand(i);
10737 if (Op.getOpcode() != ISD::UNDEF &&
10738 Op.getOpcode() != ISD::ConstantFP)
10740 EVT EltVT = Op.getValueType();
10741 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
10742 if (FoldOp.getOpcode() != ISD::UNDEF &&
10743 FoldOp.getOpcode() != ISD::ConstantFP)
10745 Ops.push_back(FoldOp);
10746 AddToWorkList(FoldOp.getNode());
10749 if (Ops.size() != N0.getNumOperands())
10752 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10753 N0.getValueType(), &Ops[0], Ops.size());
10756 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10757 SDValue N1, SDValue N2){
10758 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10760 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
10761 cast<CondCodeSDNode>(N0.getOperand(2))->get());
10763 // If we got a simplified select_cc node back from SimplifySelectCC, then
10764 // break it down into a new SETCC node, and a new SELECT node, and then return
10765 // the SELECT node, since we were called with a SELECT node.
10766 if (SCC.getNode()) {
10767 // Check to see if we got a select_cc back (to turn into setcc/select).
10768 // Otherwise, just return whatever node we got back, like fabs.
10769 if (SCC.getOpcode() == ISD::SELECT_CC) {
10770 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
10772 SCC.getOperand(0), SCC.getOperand(1),
10773 SCC.getOperand(4));
10774 AddToWorkList(SETCC.getNode());
10775 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10776 SCC.getOperand(2), SCC.getOperand(3), SETCC);
10784 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10785 /// are the two values being selected between, see if we can simplify the
10786 /// select. Callers of this should assume that TheSelect is deleted if this
10787 /// returns true. As such, they should return the appropriate thing (e.g. the
10788 /// node) back to the top-level of the DAG combiner loop to avoid it being
10790 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
10793 // Cannot simplify select with vector condition
10794 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10796 // If this is a select from two identical things, try to pull the operation
10797 // through the select.
10798 if (LHS.getOpcode() != RHS.getOpcode() ||
10799 !LHS.hasOneUse() || !RHS.hasOneUse())
10802 // If this is a load and the token chain is identical, replace the select
10803 // of two loads with a load through a select of the address to load from.
10804 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10805 // constants have been dropped into the constant pool.
10806 if (LHS.getOpcode() == ISD::LOAD) {
10807 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10808 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
10810 // Token chains must be identical.
10811 if (LHS.getOperand(0) != RHS.getOperand(0) ||
10812 // Do not let this transformation reduce the number of volatile loads.
10813 LLD->isVolatile() || RLD->isVolatile() ||
10814 // If this is an EXTLOAD, the VT's must match.
10815 LLD->getMemoryVT() != RLD->getMemoryVT() ||
10816 // If this is an EXTLOAD, the kind of extension must match.
10817 (LLD->getExtensionType() != RLD->getExtensionType() &&
10818 // The only exception is if one of the extensions is anyext.
10819 LLD->getExtensionType() != ISD::EXTLOAD &&
10820 RLD->getExtensionType() != ISD::EXTLOAD) ||
10821 // FIXME: this discards src value information. This is
10822 // over-conservative. It would be beneficial to be able to remember
10823 // both potential memory locations. Since we are discarding
10824 // src value info, don't do the transformation if the memory
10825 // locations are not in the default address space.
10826 LLD->getPointerInfo().getAddrSpace() != 0 ||
10827 RLD->getPointerInfo().getAddrSpace() != 0 ||
10828 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10829 LLD->getBasePtr().getValueType()))
10832 // Check that the select condition doesn't reach either load. If so,
10833 // folding this will induce a cycle into the DAG. If not, this is safe to
10834 // xform, so create a select of the addresses.
10836 if (TheSelect->getOpcode() == ISD::SELECT) {
10837 SDNode *CondNode = TheSelect->getOperand(0).getNode();
10838 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10839 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10841 // The loads must not depend on one another.
10842 if (LLD->isPredecessorOf(RLD) ||
10843 RLD->isPredecessorOf(LLD))
10845 Addr = DAG.getSelect(SDLoc(TheSelect),
10846 LLD->getBasePtr().getValueType(),
10847 TheSelect->getOperand(0), LLD->getBasePtr(),
10848 RLD->getBasePtr());
10849 } else { // Otherwise SELECT_CC
10850 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10851 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10853 if ((LLD->hasAnyUseOfValue(1) &&
10854 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
10855 (RLD->hasAnyUseOfValue(1) &&
10856 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
10859 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
10860 LLD->getBasePtr().getValueType(),
10861 TheSelect->getOperand(0),
10862 TheSelect->getOperand(1),
10863 LLD->getBasePtr(), RLD->getBasePtr(),
10864 TheSelect->getOperand(4));
10868 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10869 Load = DAG.getLoad(TheSelect->getValueType(0),
10871 // FIXME: Discards pointer and TBAA info.
10872 LLD->getChain(), Addr, MachinePointerInfo(),
10873 LLD->isVolatile(), LLD->isNonTemporal(),
10874 LLD->isInvariant(), LLD->getAlignment());
10876 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10877 RLD->getExtensionType() : LLD->getExtensionType(),
10879 TheSelect->getValueType(0),
10880 // FIXME: Discards pointer and TBAA info.
10881 LLD->getChain(), Addr, MachinePointerInfo(),
10882 LLD->getMemoryVT(), LLD->isVolatile(),
10883 LLD->isNonTemporal(), LLD->getAlignment());
10886 // Users of the select now use the result of the load.
10887 CombineTo(TheSelect, Load);
10889 // Users of the old loads now use the new load's chain. We know the
10890 // old-load value is dead now.
10891 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10892 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10899 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10900 /// where 'cond' is the comparison specified by CC.
10901 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
10902 SDValue N2, SDValue N3,
10903 ISD::CondCode CC, bool NotExtCompare) {
10904 // (x ? y : y) -> y.
10905 if (N2 == N3) return N2;
10907 EVT VT = N2.getValueType();
10908 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10909 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10910 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
10912 // Determine if the condition we're dealing with is constant
10913 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
10914 N0, N1, CC, DL, false);
10915 if (SCC.getNode()) AddToWorkList(SCC.getNode());
10916 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
10918 // fold select_cc true, x, y -> x
10919 if (SCCC && !SCCC->isNullValue())
10921 // fold select_cc false, x, y -> y
10922 if (SCCC && SCCC->isNullValue())
10925 // Check to see if we can simplify the select into an fabs node
10926 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10927 // Allow either -0.0 or 0.0
10928 if (CFP->getValueAPF().isZero()) {
10929 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10930 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10931 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10932 N2 == N3.getOperand(0))
10933 return DAG.getNode(ISD::FABS, DL, VT, N0);
10935 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10936 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10937 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10938 N2.getOperand(0) == N3)
10939 return DAG.getNode(ISD::FABS, DL, VT, N3);
10943 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10944 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10945 // in it. This is a win when the constant is not otherwise available because
10946 // it replaces two constant pool loads with one. We only do this if the FP
10947 // type is known to be legal, because if it isn't, then we are before legalize
10948 // types an we want the other legalization to happen first (e.g. to avoid
10949 // messing with soft float) and if the ConstantFP is not legal, because if
10950 // it is legal, we may not need to store the FP constant in a constant pool.
10951 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10952 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10953 if (TLI.isTypeLegal(N2.getValueType()) &&
10954 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10955 TargetLowering::Legal &&
10956 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
10957 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
10958 // If both constants have multiple uses, then we won't need to do an
10959 // extra load, they are likely around in registers for other users.
10960 (TV->hasOneUse() || FV->hasOneUse())) {
10961 Constant *Elts[] = {
10962 const_cast<ConstantFP*>(FV->getConstantFPValue()),
10963 const_cast<ConstantFP*>(TV->getConstantFPValue())
10965 Type *FPTy = Elts[0]->getType();
10966 const DataLayout &TD = *TLI.getDataLayout();
10968 // Create a ConstantArray of the two constants.
10969 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
10970 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10971 TD.getPrefTypeAlignment(FPTy));
10972 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10974 // Get the offsets to the 0 and 1 element of the array so that we can
10975 // select between them.
10976 SDValue Zero = DAG.getIntPtrConstant(0);
10977 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
10978 SDValue One = DAG.getIntPtrConstant(EltSize);
10980 SDValue Cond = DAG.getSetCC(DL,
10981 getSetCCResultType(N0.getValueType()),
10983 AddToWorkList(Cond.getNode());
10984 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
10986 AddToWorkList(CstOffset.getNode());
10987 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
10989 AddToWorkList(CPIdx.getNode());
10990 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
10991 MachinePointerInfo::getConstantPool(), false,
10992 false, false, Alignment);
10997 // Check to see if we can perform the "gzip trick", transforming
10998 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
10999 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11000 (N1C->isNullValue() || // (a < 0) ? b : 0
11001 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
11002 EVT XType = N0.getValueType();
11003 EVT AType = N2.getValueType();
11004 if (XType.bitsGE(AType)) {
11005 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11006 // single-bit constant.
11007 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11008 unsigned ShCtV = N2C->getAPIntValue().logBase2();
11009 ShCtV = XType.getSizeInBits()-ShCtV-1;
11010 SDValue ShCt = DAG.getConstant(ShCtV,
11011 getShiftAmountTy(N0.getValueType()));
11012 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11014 AddToWorkList(Shift.getNode());
11016 if (XType.bitsGT(AType)) {
11017 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11018 AddToWorkList(Shift.getNode());
11021 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11024 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11026 DAG.getConstant(XType.getSizeInBits()-1,
11027 getShiftAmountTy(N0.getValueType())));
11028 AddToWorkList(Shift.getNode());
11030 if (XType.bitsGT(AType)) {
11031 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11032 AddToWorkList(Shift.getNode());
11035 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11039 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11040 // where y is has a single bit set.
11041 // A plaintext description would be, we can turn the SELECT_CC into an AND
11042 // when the condition can be materialized as an all-ones register. Any
11043 // single bit-test can be materialized as an all-ones register with
11044 // shift-left and shift-right-arith.
11045 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11046 N0->getValueType(0) == VT &&
11047 N1C && N1C->isNullValue() &&
11048 N2C && N2C->isNullValue()) {
11049 SDValue AndLHS = N0->getOperand(0);
11050 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11051 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11052 // Shift the tested bit over the sign bit.
11053 APInt AndMask = ConstAndRHS->getAPIntValue();
11055 DAG.getConstant(AndMask.countLeadingZeros(),
11056 getShiftAmountTy(AndLHS.getValueType()));
11057 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11059 // Now arithmetic right shift it all the way over, so the result is either
11060 // all-ones, or zero.
11062 DAG.getConstant(AndMask.getBitWidth()-1,
11063 getShiftAmountTy(Shl.getValueType()));
11064 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11066 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11070 // fold select C, 16, 0 -> shl C, 4
11071 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11072 TLI.getBooleanContents(N0.getValueType().isVector()) ==
11073 TargetLowering::ZeroOrOneBooleanContent) {
11075 // If the caller doesn't want us to simplify this into a zext of a compare,
11077 if (NotExtCompare && N2C->getAPIntValue() == 1)
11080 // Get a SetCC of the condition
11081 // NOTE: Don't create a SETCC if it's not legal on this target.
11082 if (!LegalOperations ||
11083 TLI.isOperationLegal(ISD::SETCC,
11084 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11086 // cast from setcc result type to select result type
11088 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11090 if (N2.getValueType().bitsLT(SCC.getValueType()))
11091 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11092 N2.getValueType());
11094 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11095 N2.getValueType(), SCC);
11097 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11098 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11099 N2.getValueType(), SCC);
11102 AddToWorkList(SCC.getNode());
11103 AddToWorkList(Temp.getNode());
11105 if (N2C->getAPIntValue() == 1)
11108 // shl setcc result by log2 n2c
11109 return DAG.getNode(
11110 ISD::SHL, DL, N2.getValueType(), Temp,
11111 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11112 getShiftAmountTy(Temp.getValueType())));
11116 // Check to see if this is the equivalent of setcc
11117 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11118 // otherwise, go ahead with the folds.
11119 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11120 EVT XType = N0.getValueType();
11121 if (!LegalOperations ||
11122 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11123 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11124 if (Res.getValueType() != VT)
11125 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11129 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11130 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11131 (!LegalOperations ||
11132 TLI.isOperationLegal(ISD::CTLZ, XType))) {
11133 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11134 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11135 DAG.getConstant(Log2_32(XType.getSizeInBits()),
11136 getShiftAmountTy(Ctlz.getValueType())));
11138 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11139 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11140 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11141 XType, DAG.getConstant(0, XType), N0);
11142 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11143 return DAG.getNode(ISD::SRL, DL, XType,
11144 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11145 DAG.getConstant(XType.getSizeInBits()-1,
11146 getShiftAmountTy(XType)));
11148 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11149 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11150 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11151 DAG.getConstant(XType.getSizeInBits()-1,
11152 getShiftAmountTy(N0.getValueType())));
11153 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11157 // Check to see if this is an integer abs.
11158 // select_cc setg[te] X, 0, X, -X ->
11159 // select_cc setgt X, -1, X, -X ->
11160 // select_cc setl[te] X, 0, -X, X ->
11161 // select_cc setlt X, 1, -X, X ->
11162 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11164 ConstantSDNode *SubC = nullptr;
11165 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11166 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11167 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11168 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11169 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11170 (N1C->isOne() && CC == ISD::SETLT)) &&
11171 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11172 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11174 EVT XType = N0.getValueType();
11175 if (SubC && SubC->isNullValue() && XType.isInteger()) {
11176 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11178 DAG.getConstant(XType.getSizeInBits()-1,
11179 getShiftAmountTy(N0.getValueType())));
11180 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11182 AddToWorkList(Shift.getNode());
11183 AddToWorkList(Add.getNode());
11184 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11191 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11192 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11193 SDValue N1, ISD::CondCode Cond,
11194 SDLoc DL, bool foldBooleans) {
11195 TargetLowering::DAGCombinerInfo
11196 DagCombineInfo(DAG, Level, false, this);
11197 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11200 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11201 /// return a DAG expression to select that will generate the same value by
11202 /// multiplying by a magic number. See:
11203 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11204 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11205 const APInt *Divisor;
11206 if (N->getValueType(0).isVector()) {
11207 // Handle splat vectors.
11208 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N->getOperand(1));
11209 if (ConstantSDNode *C = BV->getConstantSplatValue())
11210 Divisor = &C->getAPIntValue();
11214 Divisor = &cast<ConstantSDNode>(N->getOperand(1))->getAPIntValue();
11217 // Avoid division by zero.
11221 std::vector<SDNode*> Built;
11222 SDValue S = TLI.BuildSDIV(N, *Divisor, DAG, LegalOperations, &Built);
11224 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
11226 AddToWorkList(*ii);
11230 /// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant,
11231 /// return a DAG expression to select that will generate the same value by
11232 /// multiplying by a magic number. See:
11233 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11234 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11235 const APInt *Divisor;
11236 if (N->getValueType(0).isVector()) {
11237 // Handle splat vectors.
11238 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N->getOperand(1));
11239 if (ConstantSDNode *C = BV->getConstantSplatValue())
11240 Divisor = &C->getAPIntValue();
11244 Divisor = &cast<ConstantSDNode>(N->getOperand(1))->getAPIntValue();
11247 // Avoid division by zero.
11251 std::vector<SDNode*> Built;
11252 SDValue S = TLI.BuildUDIV(N, *Divisor, DAG, LegalOperations, &Built);
11254 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
11256 AddToWorkList(*ii);
11260 /// FindBaseOffset - Return true if base is a frame index, which is known not
11261 // to alias with anything but itself. Provides base object and offset as
11263 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11264 const GlobalValue *&GV, const void *&CV) {
11265 // Assume it is a primitive operation.
11266 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11268 // If it's an adding a simple constant then integrate the offset.
11269 if (Base.getOpcode() == ISD::ADD) {
11270 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11271 Base = Base.getOperand(0);
11272 Offset += C->getZExtValue();
11276 // Return the underlying GlobalValue, and update the Offset. Return false
11277 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11278 // by multiple nodes with different offsets.
11279 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11280 GV = G->getGlobal();
11281 Offset += G->getOffset();
11285 // Return the underlying Constant value, and update the Offset. Return false
11286 // for ConstantSDNodes since the same constant pool entry may be represented
11287 // by multiple nodes with different offsets.
11288 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11289 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11290 : (const void *)C->getConstVal();
11291 Offset += C->getOffset();
11294 // If it's any of the following then it can't alias with anything but itself.
11295 return isa<FrameIndexSDNode>(Base);
11298 /// isAlias - Return true if there is any possibility that the two addresses
11300 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11301 // If they are the same then they must be aliases.
11302 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11304 // If they are both volatile then they cannot be reordered.
11305 if (Op0->isVolatile() && Op1->isVolatile()) return true;
11307 // Gather base node and offset information.
11308 SDValue Base1, Base2;
11309 int64_t Offset1, Offset2;
11310 const GlobalValue *GV1, *GV2;
11311 const void *CV1, *CV2;
11312 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11313 Base1, Offset1, GV1, CV1);
11314 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11315 Base2, Offset2, GV2, CV2);
11317 // If they have a same base address then check to see if they overlap.
11318 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11319 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11320 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11322 // It is possible for different frame indices to alias each other, mostly
11323 // when tail call optimization reuses return address slots for arguments.
11324 // To catch this case, look up the actual index of frame indices to compute
11325 // the real alias relationship.
11326 if (isFrameIndex1 && isFrameIndex2) {
11327 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11328 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11329 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11330 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11331 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11334 // Otherwise, if we know what the bases are, and they aren't identical, then
11335 // we know they cannot alias.
11336 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11339 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11340 // compared to the size and offset of the access, we may be able to prove they
11341 // do not alias. This check is conservative for now to catch cases created by
11342 // splitting vector types.
11343 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11344 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11345 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11346 Op1->getMemoryVT().getSizeInBits() >> 3) &&
11347 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11348 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11349 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11351 // There is no overlap between these relatively aligned accesses of similar
11352 // size, return no alias.
11353 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11354 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11358 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11359 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11361 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11362 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11366 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11367 // Use alias analysis information.
11368 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11369 Op1->getSrcValueOffset());
11370 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11371 Op0->getSrcValueOffset() - MinOffset;
11372 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11373 Op1->getSrcValueOffset() - MinOffset;
11374 AliasAnalysis::AliasResult AAResult =
11375 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11377 UseTBAA ? Op0->getTBAAInfo() : nullptr),
11378 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11380 UseTBAA ? Op1->getTBAAInfo() : nullptr));
11381 if (AAResult == AliasAnalysis::NoAlias)
11385 // Otherwise we have to assume they alias.
11389 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11390 /// looking for aliasing nodes and adding them to the Aliases vector.
11391 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11392 SmallVectorImpl<SDValue> &Aliases) {
11393 SmallVector<SDValue, 8> Chains; // List of chains to visit.
11394 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
11396 // Get alias information for node.
11397 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11400 Chains.push_back(OriginalChain);
11401 unsigned Depth = 0;
11403 // Look at each chain and determine if it is an alias. If so, add it to the
11404 // aliases list. If not, then continue up the chain looking for the next
11406 while (!Chains.empty()) {
11407 SDValue Chain = Chains.back();
11410 // For TokenFactor nodes, look at each operand and only continue up the
11411 // chain until we find two aliases. If we've seen two aliases, assume we'll
11412 // find more and revert to original chain since the xform is unlikely to be
11415 // FIXME: The depth check could be made to return the last non-aliasing
11416 // chain we found before we hit a tokenfactor rather than the original
11418 if (Depth > 6 || Aliases.size() == 2) {
11420 Aliases.push_back(OriginalChain);
11424 // Don't bother if we've been before.
11425 if (!Visited.insert(Chain.getNode()))
11428 switch (Chain.getOpcode()) {
11429 case ISD::EntryToken:
11430 // Entry token is ideal chain operand, but handled in FindBetterChain.
11435 // Get alias information for Chain.
11436 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11437 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11439 // If chain is alias then stop here.
11440 if (!(IsLoad && IsOpLoad) &&
11441 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11442 Aliases.push_back(Chain);
11444 // Look further up the chain.
11445 Chains.push_back(Chain.getOperand(0));
11451 case ISD::TokenFactor:
11452 // We have to check each of the operands of the token factor for "small"
11453 // token factors, so we queue them up. Adding the operands to the queue
11454 // (stack) in reverse order maintains the original order and increases the
11455 // likelihood that getNode will find a matching token factor (CSE.)
11456 if (Chain.getNumOperands() > 16) {
11457 Aliases.push_back(Chain);
11460 for (unsigned n = Chain.getNumOperands(); n;)
11461 Chains.push_back(Chain.getOperand(--n));
11466 // For all other instructions we will just have to take what we can get.
11467 Aliases.push_back(Chain);
11472 // We need to be careful here to also search for aliases through the
11473 // value operand of a store, etc. Consider the following situation:
11475 // L1 = load Token1, %52
11476 // S1 = store Token1, L1, %51
11477 // L2 = load Token1, %52+8
11478 // S2 = store Token1, L2, %51+8
11479 // Token2 = Token(S1, S2)
11480 // L3 = load Token2, %53
11481 // S3 = store Token2, L3, %52
11482 // L4 = load Token2, %53+8
11483 // S4 = store Token2, L4, %52+8
11484 // If we search for aliases of S3 (which loads address %52), and we look
11485 // only through the chain, then we'll miss the trivial dependence on L1
11486 // (which also loads from %52). We then might change all loads and
11487 // stores to use Token1 as their chain operand, which could result in
11488 // copying %53 into %52 before copying %52 into %51 (which should
11491 // The problem is, however, that searching for such data dependencies
11492 // can become expensive, and the cost is not directly related to the
11493 // chain depth. Instead, we'll rule out such configurations here by
11494 // insisting that we've visited all chain users (except for users
11495 // of the original chain, which is not necessary). When doing this,
11496 // we need to look through nodes we don't care about (otherwise, things
11497 // like register copies will interfere with trivial cases).
11499 SmallVector<const SDNode *, 16> Worklist;
11500 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11501 IE = Visited.end(); I != IE; ++I)
11502 if (*I != OriginalChain.getNode())
11503 Worklist.push_back(*I);
11505 while (!Worklist.empty()) {
11506 const SDNode *M = Worklist.pop_back_val();
11508 // We have already visited M, and want to make sure we've visited any uses
11509 // of M that we care about. For uses that we've not visisted, and don't
11510 // care about, queue them to the worklist.
11512 for (SDNode::use_iterator UI = M->use_begin(),
11513 UIE = M->use_end(); UI != UIE; ++UI)
11514 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11515 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11516 // We've not visited this use, and we care about it (it could have an
11517 // ordering dependency with the original node).
11519 Aliases.push_back(OriginalChain);
11523 // We've not visited this use, but we don't care about it. Mark it as
11524 // visited and enqueue it to the worklist.
11525 Worklist.push_back(*UI);
11530 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11531 /// for a better chain (aliasing node.)
11532 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11533 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
11535 // Accumulate all the aliases to this node.
11536 GatherAllAliases(N, OldChain, Aliases);
11538 // If no operands then chain to entry token.
11539 if (Aliases.size() == 0)
11540 return DAG.getEntryNode();
11542 // If a single operand then chain to it. We don't need to revisit it.
11543 if (Aliases.size() == 1)
11546 // Construct a custom tailored token factor.
11547 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
11548 &Aliases[0], Aliases.size());
11551 // SelectionDAG::Combine - This is the entry point for the file.
11553 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11554 CodeGenOpt::Level OptLevel) {
11555 /// run - This is the main entry point to this class.
11557 DAGCombiner(*this, AA, OptLevel).Run(Level);