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 BitVector UndefElements;
649 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
651 // BuildVectors can truncate their operands. Ignore that case here.
652 // FIXME: We blindly ignore splats which include undef which is overly
654 if (CN && UndefElements.none() &&
655 CN->getValueType(0) == N.getValueType().getScalarType())
662 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
663 SDValue N0, SDValue N1) {
664 EVT VT = N0.getValueType();
665 if (N0.getOpcode() == Opc) {
666 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
667 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
668 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
669 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
670 if (!OpNode.getNode())
672 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
674 if (N0.hasOneUse()) {
675 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
677 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
678 if (!OpNode.getNode())
680 AddToWorkList(OpNode.getNode());
681 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
686 if (N1.getOpcode() == Opc) {
687 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
688 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
689 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
690 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
691 if (!OpNode.getNode())
693 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
695 if (N1.hasOneUse()) {
696 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
698 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
699 if (!OpNode.getNode())
701 AddToWorkList(OpNode.getNode());
702 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
710 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
712 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
714 DEBUG(dbgs() << "\nReplacing.1 ";
716 dbgs() << "\nWith: ";
717 To[0].getNode()->dump(&DAG);
718 dbgs() << " and " << NumTo-1 << " other values\n";
719 for (unsigned i = 0, e = NumTo; i != e; ++i)
720 assert((!To[i].getNode() ||
721 N->getValueType(i) == To[i].getValueType()) &&
722 "Cannot combine value to value of different type!"));
723 WorkListRemover DeadNodes(*this);
724 DAG.ReplaceAllUsesWith(N, To);
726 // Push the new nodes and any users onto the worklist
727 for (unsigned i = 0, e = NumTo; i != e; ++i) {
728 if (To[i].getNode()) {
729 AddToWorkList(To[i].getNode());
730 AddUsersToWorkList(To[i].getNode());
735 // Finally, if the node is now dead, remove it from the graph. The node
736 // may not be dead if the replacement process recursively simplified to
737 // something else needing this node.
738 if (N->use_empty()) {
739 // Nodes can be reintroduced into the worklist. Make sure we do not
740 // process a node that has been replaced.
741 removeFromWorkList(N);
743 // Finally, since the node is now dead, remove it from the graph.
746 return SDValue(N, 0);
750 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
751 // Replace all uses. If any nodes become isomorphic to other nodes and
752 // are deleted, make sure to remove them from our worklist.
753 WorkListRemover DeadNodes(*this);
754 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
756 // Push the new node and any (possibly new) users onto the worklist.
757 AddToWorkList(TLO.New.getNode());
758 AddUsersToWorkList(TLO.New.getNode());
760 // Finally, if the node is now dead, remove it from the graph. The node
761 // may not be dead if the replacement process recursively simplified to
762 // something else needing this node.
763 if (TLO.Old.getNode()->use_empty()) {
764 removeFromWorkList(TLO.Old.getNode());
766 // If the operands of this node are only used by the node, they will now
767 // be dead. Make sure to visit them first to delete dead nodes early.
768 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
769 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
770 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
772 DAG.DeleteNode(TLO.Old.getNode());
776 /// SimplifyDemandedBits - Check the specified integer node value to see if
777 /// it can be simplified or if things it uses can be simplified by bit
778 /// propagation. If so, return true.
779 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
780 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
781 APInt KnownZero, KnownOne;
782 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
786 AddToWorkList(Op.getNode());
788 // Replace the old value with the new one.
790 DEBUG(dbgs() << "\nReplacing.2 ";
791 TLO.Old.getNode()->dump(&DAG);
792 dbgs() << "\nWith: ";
793 TLO.New.getNode()->dump(&DAG);
796 CommitTargetLoweringOpt(TLO);
800 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
802 EVT VT = Load->getValueType(0);
803 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
805 DEBUG(dbgs() << "\nReplacing.9 ";
807 dbgs() << "\nWith: ";
808 Trunc.getNode()->dump(&DAG);
810 WorkListRemover DeadNodes(*this);
811 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
812 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
813 removeFromWorkList(Load);
814 DAG.DeleteNode(Load);
815 AddToWorkList(Trunc.getNode());
818 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
821 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
822 EVT MemVT = LD->getMemoryVT();
823 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
824 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
826 : LD->getExtensionType();
828 return DAG.getExtLoad(ExtType, dl, PVT,
829 LD->getChain(), LD->getBasePtr(),
830 MemVT, LD->getMemOperand());
833 unsigned Opc = Op.getOpcode();
836 case ISD::AssertSext:
837 return DAG.getNode(ISD::AssertSext, dl, PVT,
838 SExtPromoteOperand(Op.getOperand(0), PVT),
840 case ISD::AssertZext:
841 return DAG.getNode(ISD::AssertZext, dl, PVT,
842 ZExtPromoteOperand(Op.getOperand(0), PVT),
844 case ISD::Constant: {
846 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
847 return DAG.getNode(ExtOpc, dl, PVT, Op);
851 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
853 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
856 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
857 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
859 EVT OldVT = Op.getValueType();
861 bool Replace = false;
862 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
863 if (!NewOp.getNode())
865 AddToWorkList(NewOp.getNode());
868 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
869 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
870 DAG.getValueType(OldVT));
873 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
874 EVT OldVT = Op.getValueType();
876 bool Replace = false;
877 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
878 if (!NewOp.getNode())
880 AddToWorkList(NewOp.getNode());
883 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
884 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
887 /// PromoteIntBinOp - Promote the specified integer binary operation if the
888 /// target indicates it is beneficial. e.g. On x86, it's usually better to
889 /// promote i16 operations to i32 since i16 instructions are longer.
890 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
891 if (!LegalOperations)
894 EVT VT = Op.getValueType();
895 if (VT.isVector() || !VT.isInteger())
898 // If operation type is 'undesirable', e.g. i16 on x86, consider
900 unsigned Opc = Op.getOpcode();
901 if (TLI.isTypeDesirableForOp(Opc, VT))
905 // Consult target whether it is a good idea to promote this operation and
906 // what's the right type to promote it to.
907 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
908 assert(PVT != VT && "Don't know what type to promote to!");
910 bool Replace0 = false;
911 SDValue N0 = Op.getOperand(0);
912 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
916 bool Replace1 = false;
917 SDValue N1 = Op.getOperand(1);
922 NN1 = PromoteOperand(N1, PVT, Replace1);
927 AddToWorkList(NN0.getNode());
929 AddToWorkList(NN1.getNode());
932 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
934 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
936 DEBUG(dbgs() << "\nPromoting ";
937 Op.getNode()->dump(&DAG));
939 return DAG.getNode(ISD::TRUNCATE, dl, VT,
940 DAG.getNode(Opc, dl, PVT, NN0, NN1));
945 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
946 /// target indicates it is beneficial. e.g. On x86, it's usually better to
947 /// promote i16 operations to i32 since i16 instructions are longer.
948 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
949 if (!LegalOperations)
952 EVT VT = Op.getValueType();
953 if (VT.isVector() || !VT.isInteger())
956 // If operation type is 'undesirable', e.g. i16 on x86, consider
958 unsigned Opc = Op.getOpcode();
959 if (TLI.isTypeDesirableForOp(Opc, VT))
963 // Consult target whether it is a good idea to promote this operation and
964 // what's the right type to promote it to.
965 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
966 assert(PVT != VT && "Don't know what type to promote to!");
968 bool Replace = false;
969 SDValue N0 = Op.getOperand(0);
971 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
972 else if (Opc == ISD::SRL)
973 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
975 N0 = PromoteOperand(N0, PVT, Replace);
979 AddToWorkList(N0.getNode());
981 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
983 DEBUG(dbgs() << "\nPromoting ";
984 Op.getNode()->dump(&DAG));
986 return DAG.getNode(ISD::TRUNCATE, dl, VT,
987 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
992 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
993 if (!LegalOperations)
996 EVT VT = Op.getValueType();
997 if (VT.isVector() || !VT.isInteger())
1000 // If operation type is 'undesirable', e.g. i16 on x86, consider
1002 unsigned Opc = Op.getOpcode();
1003 if (TLI.isTypeDesirableForOp(Opc, VT))
1007 // Consult target whether it is a good idea to promote this operation and
1008 // what's the right type to promote it to.
1009 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1010 assert(PVT != VT && "Don't know what type to promote to!");
1011 // fold (aext (aext x)) -> (aext x)
1012 // fold (aext (zext x)) -> (zext x)
1013 // fold (aext (sext x)) -> (sext x)
1014 DEBUG(dbgs() << "\nPromoting ";
1015 Op.getNode()->dump(&DAG));
1016 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1021 bool DAGCombiner::PromoteLoad(SDValue Op) {
1022 if (!LegalOperations)
1025 EVT VT = Op.getValueType();
1026 if (VT.isVector() || !VT.isInteger())
1029 // If operation type is 'undesirable', e.g. i16 on x86, consider
1031 unsigned Opc = Op.getOpcode();
1032 if (TLI.isTypeDesirableForOp(Opc, VT))
1036 // Consult target whether it is a good idea to promote this operation and
1037 // what's the right type to promote it to.
1038 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1039 assert(PVT != VT && "Don't know what type to promote to!");
1042 SDNode *N = Op.getNode();
1043 LoadSDNode *LD = cast<LoadSDNode>(N);
1044 EVT MemVT = LD->getMemoryVT();
1045 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1046 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1048 : LD->getExtensionType();
1049 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1050 LD->getChain(), LD->getBasePtr(),
1051 MemVT, LD->getMemOperand());
1052 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1054 DEBUG(dbgs() << "\nPromoting ";
1057 Result.getNode()->dump(&DAG);
1059 WorkListRemover DeadNodes(*this);
1060 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1061 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1062 removeFromWorkList(N);
1064 AddToWorkList(Result.getNode());
1071 //===----------------------------------------------------------------------===//
1072 // Main DAG Combiner implementation
1073 //===----------------------------------------------------------------------===//
1075 void DAGCombiner::Run(CombineLevel AtLevel) {
1076 // set the instance variables, so that the various visit routines may use it.
1078 LegalOperations = Level >= AfterLegalizeVectorOps;
1079 LegalTypes = Level >= AfterLegalizeTypes;
1081 // Add all the dag nodes to the worklist.
1082 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1083 E = DAG.allnodes_end(); I != E; ++I)
1086 // Create a dummy node (which is not added to allnodes), that adds a reference
1087 // to the root node, preventing it from being deleted, and tracking any
1088 // changes of the root.
1089 HandleSDNode Dummy(DAG.getRoot());
1091 // The root of the dag may dangle to deleted nodes until the dag combiner is
1092 // done. Set it to null to avoid confusion.
1093 DAG.setRoot(SDValue());
1095 // while the worklist isn't empty, find a node and
1096 // try and combine it.
1097 while (!WorkListContents.empty()) {
1099 // The WorkListOrder holds the SDNodes in order, but it may contain
1101 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1102 // worklist *should* contain, and check the node we want to visit is should
1103 // actually be visited.
1105 N = WorkListOrder.pop_back_val();
1106 } while (!WorkListContents.erase(N));
1108 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1109 // N is deleted from the DAG, since they too may now be dead or may have a
1110 // reduced number of uses, allowing other xforms.
1111 if (N->use_empty() && N != &Dummy) {
1112 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1113 AddToWorkList(N->getOperand(i).getNode());
1119 SDValue RV = combine(N);
1126 // If we get back the same node we passed in, rather than a new node or
1127 // zero, we know that the node must have defined multiple values and
1128 // CombineTo was used. Since CombineTo takes care of the worklist
1129 // mechanics for us, we have no work to do in this case.
1130 if (RV.getNode() == N)
1133 assert(N->getOpcode() != ISD::DELETED_NODE &&
1134 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1135 "Node was deleted but visit returned new node!");
1137 DEBUG(dbgs() << "\nReplacing.3 ";
1139 dbgs() << "\nWith: ";
1140 RV.getNode()->dump(&DAG);
1143 // Transfer debug value.
1144 DAG.TransferDbgValues(SDValue(N, 0), RV);
1145 WorkListRemover DeadNodes(*this);
1146 if (N->getNumValues() == RV.getNode()->getNumValues())
1147 DAG.ReplaceAllUsesWith(N, RV.getNode());
1149 assert(N->getValueType(0) == RV.getValueType() &&
1150 N->getNumValues() == 1 && "Type mismatch");
1152 DAG.ReplaceAllUsesWith(N, &OpV);
1155 // Push the new node and any users onto the worklist
1156 AddToWorkList(RV.getNode());
1157 AddUsersToWorkList(RV.getNode());
1159 // Add any uses of the old node to the worklist in case this node is the
1160 // last one that uses them. They may become dead after this node is
1162 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1163 AddToWorkList(N->getOperand(i).getNode());
1165 // Finally, if the node is now dead, remove it from the graph. The node
1166 // may not be dead if the replacement process recursively simplified to
1167 // something else needing this node.
1168 if (N->use_empty()) {
1169 // Nodes can be reintroduced into the worklist. Make sure we do not
1170 // process a node that has been replaced.
1171 removeFromWorkList(N);
1173 // Finally, since the node is now dead, remove it from the graph.
1178 // If the root changed (e.g. it was a dead load, update the root).
1179 DAG.setRoot(Dummy.getValue());
1180 DAG.RemoveDeadNodes();
1183 SDValue DAGCombiner::visit(SDNode *N) {
1184 switch (N->getOpcode()) {
1186 case ISD::TokenFactor: return visitTokenFactor(N);
1187 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1188 case ISD::ADD: return visitADD(N);
1189 case ISD::SUB: return visitSUB(N);
1190 case ISD::ADDC: return visitADDC(N);
1191 case ISD::SUBC: return visitSUBC(N);
1192 case ISD::ADDE: return visitADDE(N);
1193 case ISD::SUBE: return visitSUBE(N);
1194 case ISD::MUL: return visitMUL(N);
1195 case ISD::SDIV: return visitSDIV(N);
1196 case ISD::UDIV: return visitUDIV(N);
1197 case ISD::SREM: return visitSREM(N);
1198 case ISD::UREM: return visitUREM(N);
1199 case ISD::MULHU: return visitMULHU(N);
1200 case ISD::MULHS: return visitMULHS(N);
1201 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1202 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1203 case ISD::SMULO: return visitSMULO(N);
1204 case ISD::UMULO: return visitUMULO(N);
1205 case ISD::SDIVREM: return visitSDIVREM(N);
1206 case ISD::UDIVREM: return visitUDIVREM(N);
1207 case ISD::AND: return visitAND(N);
1208 case ISD::OR: return visitOR(N);
1209 case ISD::XOR: return visitXOR(N);
1210 case ISD::SHL: return visitSHL(N);
1211 case ISD::SRA: return visitSRA(N);
1212 case ISD::SRL: return visitSRL(N);
1214 case ISD::ROTL: return visitRotate(N);
1215 case ISD::CTLZ: return visitCTLZ(N);
1216 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1217 case ISD::CTTZ: return visitCTTZ(N);
1218 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1219 case ISD::CTPOP: return visitCTPOP(N);
1220 case ISD::SELECT: return visitSELECT(N);
1221 case ISD::VSELECT: return visitVSELECT(N);
1222 case ISD::SELECT_CC: return visitSELECT_CC(N);
1223 case ISD::SETCC: return visitSETCC(N);
1224 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1225 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1226 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1227 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1228 case ISD::TRUNCATE: return visitTRUNCATE(N);
1229 case ISD::BITCAST: return visitBITCAST(N);
1230 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1231 case ISD::FADD: return visitFADD(N);
1232 case ISD::FSUB: return visitFSUB(N);
1233 case ISD::FMUL: return visitFMUL(N);
1234 case ISD::FMA: return visitFMA(N);
1235 case ISD::FDIV: return visitFDIV(N);
1236 case ISD::FREM: return visitFREM(N);
1237 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1238 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1239 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1240 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1241 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1242 case ISD::FP_ROUND: return visitFP_ROUND(N);
1243 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1244 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1245 case ISD::FNEG: return visitFNEG(N);
1246 case ISD::FABS: return visitFABS(N);
1247 case ISD::FFLOOR: return visitFFLOOR(N);
1248 case ISD::FCEIL: return visitFCEIL(N);
1249 case ISD::FTRUNC: return visitFTRUNC(N);
1250 case ISD::BRCOND: return visitBRCOND(N);
1251 case ISD::BR_CC: return visitBR_CC(N);
1252 case ISD::LOAD: return visitLOAD(N);
1253 case ISD::STORE: return visitSTORE(N);
1254 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1255 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1256 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1257 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1258 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1259 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1260 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1265 SDValue DAGCombiner::combine(SDNode *N) {
1266 SDValue RV = visit(N);
1268 // If nothing happened, try a target-specific DAG combine.
1269 if (!RV.getNode()) {
1270 assert(N->getOpcode() != ISD::DELETED_NODE &&
1271 "Node was deleted but visit returned NULL!");
1273 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1274 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1276 // Expose the DAG combiner to the target combiner impls.
1277 TargetLowering::DAGCombinerInfo
1278 DagCombineInfo(DAG, Level, false, this);
1280 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1284 // If nothing happened still, try promoting the operation.
1285 if (!RV.getNode()) {
1286 switch (N->getOpcode()) {
1294 RV = PromoteIntBinOp(SDValue(N, 0));
1299 RV = PromoteIntShiftOp(SDValue(N, 0));
1301 case ISD::SIGN_EXTEND:
1302 case ISD::ZERO_EXTEND:
1303 case ISD::ANY_EXTEND:
1304 RV = PromoteExtend(SDValue(N, 0));
1307 if (PromoteLoad(SDValue(N, 0)))
1313 // If N is a commutative binary node, try commuting it to enable more
1315 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1316 N->getNumValues() == 1) {
1317 SDValue N0 = N->getOperand(0);
1318 SDValue N1 = N->getOperand(1);
1320 // Constant operands are canonicalized to RHS.
1321 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1322 SDValue Ops[] = {N1, N0};
1324 if (const BinaryWithFlagsSDNode *BinNode =
1325 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1326 CSENode = DAG.getNodeIfExists(
1327 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1328 BinNode->hasNoSignedWrap(), BinNode->isExact());
1330 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1333 return SDValue(CSENode, 0);
1340 /// getInputChainForNode - Given a node, return its input chain if it has one,
1341 /// otherwise return a null sd operand.
1342 static SDValue getInputChainForNode(SDNode *N) {
1343 if (unsigned NumOps = N->getNumOperands()) {
1344 if (N->getOperand(0).getValueType() == MVT::Other)
1345 return N->getOperand(0);
1346 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1347 return N->getOperand(NumOps-1);
1348 for (unsigned i = 1; i < NumOps-1; ++i)
1349 if (N->getOperand(i).getValueType() == MVT::Other)
1350 return N->getOperand(i);
1355 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1356 // If N has two operands, where one has an input chain equal to the other,
1357 // the 'other' chain is redundant.
1358 if (N->getNumOperands() == 2) {
1359 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1360 return N->getOperand(0);
1361 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1362 return N->getOperand(1);
1365 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1366 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1367 SmallPtrSet<SDNode*, 16> SeenOps;
1368 bool Changed = false; // If we should replace this token factor.
1370 // Start out with this token factor.
1373 // Iterate through token factors. The TFs grows when new token factors are
1375 for (unsigned i = 0; i < TFs.size(); ++i) {
1376 SDNode *TF = TFs[i];
1378 // Check each of the operands.
1379 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1380 SDValue Op = TF->getOperand(i);
1382 switch (Op.getOpcode()) {
1383 case ISD::EntryToken:
1384 // Entry tokens don't need to be added to the list. They are
1389 case ISD::TokenFactor:
1390 if (Op.hasOneUse() &&
1391 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1392 // Queue up for processing.
1393 TFs.push_back(Op.getNode());
1394 // Clean up in case the token factor is removed.
1395 AddToWorkList(Op.getNode());
1402 // Only add if it isn't already in the list.
1403 if (SeenOps.insert(Op.getNode()))
1414 // If we've change things around then replace token factor.
1417 // The entry token is the only possible outcome.
1418 Result = DAG.getEntryNode();
1420 // New and improved token factor.
1421 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1424 // Don't add users to work list.
1425 return CombineTo(N, Result, false);
1431 /// MERGE_VALUES can always be eliminated.
1432 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1433 WorkListRemover DeadNodes(*this);
1434 // Replacing results may cause a different MERGE_VALUES to suddenly
1435 // be CSE'd with N, and carry its uses with it. Iterate until no
1436 // uses remain, to ensure that the node can be safely deleted.
1437 // First add the users of this node to the work list so that they
1438 // can be tried again once they have new operands.
1439 AddUsersToWorkList(N);
1441 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1442 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1443 } while (!N->use_empty());
1444 removeFromWorkList(N);
1446 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1450 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1451 SelectionDAG &DAG) {
1452 EVT VT = N0.getValueType();
1453 SDValue N00 = N0.getOperand(0);
1454 SDValue N01 = N0.getOperand(1);
1455 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1457 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1458 isa<ConstantSDNode>(N00.getOperand(1))) {
1459 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1460 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1461 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1462 N00.getOperand(0), N01),
1463 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1464 N00.getOperand(1), N01));
1465 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1471 SDValue DAGCombiner::visitADD(SDNode *N) {
1472 SDValue N0 = N->getOperand(0);
1473 SDValue N1 = N->getOperand(1);
1474 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1475 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1476 EVT VT = N0.getValueType();
1479 if (VT.isVector()) {
1480 SDValue FoldedVOp = SimplifyVBinOp(N);
1481 if (FoldedVOp.getNode()) return FoldedVOp;
1483 // fold (add x, 0) -> x, vector edition
1484 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1486 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1490 // fold (add x, undef) -> undef
1491 if (N0.getOpcode() == ISD::UNDEF)
1493 if (N1.getOpcode() == ISD::UNDEF)
1495 // fold (add c1, c2) -> c1+c2
1497 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1498 // canonicalize constant to RHS
1500 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1501 // fold (add x, 0) -> x
1502 if (N1C && N1C->isNullValue())
1504 // fold (add Sym, c) -> Sym+c
1505 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1506 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1507 GA->getOpcode() == ISD::GlobalAddress)
1508 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1510 (uint64_t)N1C->getSExtValue());
1511 // fold ((c1-A)+c2) -> (c1+c2)-A
1512 if (N1C && N0.getOpcode() == ISD::SUB)
1513 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1514 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1515 DAG.getConstant(N1C->getAPIntValue()+
1516 N0C->getAPIntValue(), VT),
1519 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1522 // fold ((0-A) + B) -> B-A
1523 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1524 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1525 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1526 // fold (A + (0-B)) -> A-B
1527 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1528 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1529 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1530 // fold (A+(B-A)) -> B
1531 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1532 return N1.getOperand(0);
1533 // fold ((B-A)+A) -> B
1534 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1535 return N0.getOperand(0);
1536 // fold (A+(B-(A+C))) to (B-C)
1537 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1538 N0 == N1.getOperand(1).getOperand(0))
1539 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1540 N1.getOperand(1).getOperand(1));
1541 // fold (A+(B-(C+A))) to (B-C)
1542 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1543 N0 == N1.getOperand(1).getOperand(1))
1544 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1545 N1.getOperand(1).getOperand(0));
1546 // fold (A+((B-A)+or-C)) to (B+or-C)
1547 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1548 N1.getOperand(0).getOpcode() == ISD::SUB &&
1549 N0 == N1.getOperand(0).getOperand(1))
1550 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1551 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1553 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1554 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1555 SDValue N00 = N0.getOperand(0);
1556 SDValue N01 = N0.getOperand(1);
1557 SDValue N10 = N1.getOperand(0);
1558 SDValue N11 = N1.getOperand(1);
1560 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1561 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1562 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1563 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1566 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1567 return SDValue(N, 0);
1569 // fold (a+b) -> (a|b) iff a and b share no bits.
1570 if (VT.isInteger() && !VT.isVector()) {
1571 APInt LHSZero, LHSOne;
1572 APInt RHSZero, RHSOne;
1573 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1575 if (LHSZero.getBoolValue()) {
1576 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1578 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1579 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1580 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1581 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1582 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1587 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1588 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1589 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1590 if (Result.getNode()) return Result;
1592 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1593 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1594 if (Result.getNode()) return Result;
1597 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1598 if (N1.getOpcode() == ISD::SHL &&
1599 N1.getOperand(0).getOpcode() == ISD::SUB)
1600 if (ConstantSDNode *C =
1601 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1602 if (C->getAPIntValue() == 0)
1603 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1604 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1605 N1.getOperand(0).getOperand(1),
1607 if (N0.getOpcode() == ISD::SHL &&
1608 N0.getOperand(0).getOpcode() == ISD::SUB)
1609 if (ConstantSDNode *C =
1610 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1611 if (C->getAPIntValue() == 0)
1612 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1613 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1614 N0.getOperand(0).getOperand(1),
1617 if (N1.getOpcode() == ISD::AND) {
1618 SDValue AndOp0 = N1.getOperand(0);
1619 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1620 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1621 unsigned DestBits = VT.getScalarType().getSizeInBits();
1623 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1624 // and similar xforms where the inner op is either ~0 or 0.
1625 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1627 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1631 // add (sext i1), X -> sub X, (zext i1)
1632 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1633 N0.getOperand(0).getValueType() == MVT::i1 &&
1634 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1636 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1637 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1643 SDValue DAGCombiner::visitADDC(SDNode *N) {
1644 SDValue N0 = N->getOperand(0);
1645 SDValue N1 = N->getOperand(1);
1646 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1647 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1648 EVT VT = N0.getValueType();
1650 // If the flag result is dead, turn this into an ADD.
1651 if (!N->hasAnyUseOfValue(1))
1652 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1653 DAG.getNode(ISD::CARRY_FALSE,
1654 SDLoc(N), MVT::Glue));
1656 // canonicalize constant to RHS.
1658 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1660 // fold (addc x, 0) -> x + no carry out
1661 if (N1C && N1C->isNullValue())
1662 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1663 SDLoc(N), MVT::Glue));
1665 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1666 APInt LHSZero, LHSOne;
1667 APInt RHSZero, RHSOne;
1668 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1670 if (LHSZero.getBoolValue()) {
1671 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1673 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1674 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1675 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1676 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1677 DAG.getNode(ISD::CARRY_FALSE,
1678 SDLoc(N), MVT::Glue));
1684 SDValue DAGCombiner::visitADDE(SDNode *N) {
1685 SDValue N0 = N->getOperand(0);
1686 SDValue N1 = N->getOperand(1);
1687 SDValue CarryIn = N->getOperand(2);
1688 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1689 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1691 // canonicalize constant to RHS
1693 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1696 // fold (adde x, y, false) -> (addc x, y)
1697 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1698 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1703 // Since it may not be valid to emit a fold to zero for vector initializers
1704 // check if we can before folding.
1705 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1707 bool LegalOperations, bool LegalTypes) {
1709 return DAG.getConstant(0, VT);
1710 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1711 return DAG.getConstant(0, VT);
1715 SDValue DAGCombiner::visitSUB(SDNode *N) {
1716 SDValue N0 = N->getOperand(0);
1717 SDValue N1 = N->getOperand(1);
1718 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1719 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1720 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1721 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1722 EVT VT = N0.getValueType();
1725 if (VT.isVector()) {
1726 SDValue FoldedVOp = SimplifyVBinOp(N);
1727 if (FoldedVOp.getNode()) return FoldedVOp;
1729 // fold (sub x, 0) -> x, vector edition
1730 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1734 // fold (sub x, x) -> 0
1735 // FIXME: Refactor this and xor and other similar operations together.
1737 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1738 // fold (sub c1, c2) -> c1-c2
1740 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1741 // fold (sub x, c) -> (add x, -c)
1743 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1744 DAG.getConstant(-N1C->getAPIntValue(), VT));
1745 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1746 if (N0C && N0C->isAllOnesValue())
1747 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1748 // fold A-(A-B) -> B
1749 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1750 return N1.getOperand(1);
1751 // fold (A+B)-A -> B
1752 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1753 return N0.getOperand(1);
1754 // fold (A+B)-B -> A
1755 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1756 return N0.getOperand(0);
1757 // fold C2-(A+C1) -> (C2-C1)-A
1758 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1759 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1761 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1764 // fold ((A+(B+or-C))-B) -> A+or-C
1765 if (N0.getOpcode() == ISD::ADD &&
1766 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1767 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1768 N0.getOperand(1).getOperand(0) == N1)
1769 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1770 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1771 // fold ((A+(C+B))-B) -> A+C
1772 if (N0.getOpcode() == ISD::ADD &&
1773 N0.getOperand(1).getOpcode() == ISD::ADD &&
1774 N0.getOperand(1).getOperand(1) == N1)
1775 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1776 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1777 // fold ((A-(B-C))-C) -> A-B
1778 if (N0.getOpcode() == ISD::SUB &&
1779 N0.getOperand(1).getOpcode() == ISD::SUB &&
1780 N0.getOperand(1).getOperand(1) == N1)
1781 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1782 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1784 // If either operand of a sub is undef, the result is undef
1785 if (N0.getOpcode() == ISD::UNDEF)
1787 if (N1.getOpcode() == ISD::UNDEF)
1790 // If the relocation model supports it, consider symbol offsets.
1791 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1792 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1793 // fold (sub Sym, c) -> Sym-c
1794 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1795 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1797 (uint64_t)N1C->getSExtValue());
1798 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1799 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1800 if (GA->getGlobal() == GB->getGlobal())
1801 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1808 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1809 SDValue N0 = N->getOperand(0);
1810 SDValue N1 = N->getOperand(1);
1811 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1812 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1813 EVT VT = N0.getValueType();
1815 // If the flag result is dead, turn this into an SUB.
1816 if (!N->hasAnyUseOfValue(1))
1817 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1818 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1821 // fold (subc x, x) -> 0 + no borrow
1823 return CombineTo(N, DAG.getConstant(0, VT),
1824 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1827 // fold (subc x, 0) -> x + no borrow
1828 if (N1C && N1C->isNullValue())
1829 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1832 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1833 if (N0C && N0C->isAllOnesValue())
1834 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1835 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1841 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1842 SDValue N0 = N->getOperand(0);
1843 SDValue N1 = N->getOperand(1);
1844 SDValue CarryIn = N->getOperand(2);
1846 // fold (sube x, y, false) -> (subc x, y)
1847 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1848 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1853 SDValue DAGCombiner::visitMUL(SDNode *N) {
1854 SDValue N0 = N->getOperand(0);
1855 SDValue N1 = N->getOperand(1);
1856 EVT VT = N0.getValueType();
1858 // fold (mul x, undef) -> 0
1859 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1860 return DAG.getConstant(0, VT);
1862 bool N0IsConst = false;
1863 bool N1IsConst = false;
1864 APInt ConstValue0, ConstValue1;
1866 if (VT.isVector()) {
1867 SDValue FoldedVOp = SimplifyVBinOp(N);
1868 if (FoldedVOp.getNode()) return FoldedVOp;
1870 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1871 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1873 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1874 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1876 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1877 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1881 // fold (mul c1, c2) -> c1*c2
1882 if (N0IsConst && N1IsConst)
1883 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1885 // canonicalize constant to RHS
1886 if (N0IsConst && !N1IsConst)
1887 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1888 // fold (mul x, 0) -> 0
1889 if (N1IsConst && ConstValue1 == 0)
1891 // We require a splat of the entire scalar bit width for non-contiguous
1894 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1895 // fold (mul x, 1) -> x
1896 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1898 // fold (mul x, -1) -> 0-x
1899 if (N1IsConst && ConstValue1.isAllOnesValue())
1900 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1901 DAG.getConstant(0, VT), N0);
1902 // fold (mul x, (1 << c)) -> x << c
1903 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1904 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1905 DAG.getConstant(ConstValue1.logBase2(),
1906 getShiftAmountTy(N0.getValueType())));
1907 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1908 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1909 unsigned Log2Val = (-ConstValue1).logBase2();
1910 // FIXME: If the input is something that is easily negated (e.g. a
1911 // single-use add), we should put the negate there.
1912 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1913 DAG.getConstant(0, VT),
1914 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1915 DAG.getConstant(Log2Val,
1916 getShiftAmountTy(N0.getValueType()))));
1920 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1921 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1922 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1923 isa<ConstantSDNode>(N0.getOperand(1)))) {
1924 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1925 N1, N0.getOperand(1));
1926 AddToWorkList(C3.getNode());
1927 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1928 N0.getOperand(0), C3);
1931 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1934 SDValue Sh(nullptr,0), Y(nullptr,0);
1935 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1936 if (N0.getOpcode() == ISD::SHL &&
1937 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1938 isa<ConstantSDNode>(N0.getOperand(1))) &&
1939 N0.getNode()->hasOneUse()) {
1941 } else if (N1.getOpcode() == ISD::SHL &&
1942 isa<ConstantSDNode>(N1.getOperand(1)) &&
1943 N1.getNode()->hasOneUse()) {
1948 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1949 Sh.getOperand(0), Y);
1950 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1951 Mul, Sh.getOperand(1));
1955 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1956 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1957 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1958 isa<ConstantSDNode>(N0.getOperand(1))))
1959 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1960 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1961 N0.getOperand(0), N1),
1962 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1963 N0.getOperand(1), N1));
1966 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1973 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1974 SDValue N0 = N->getOperand(0);
1975 SDValue N1 = N->getOperand(1);
1976 ConstantSDNode *N0C = isConstOrConstSplat(N0);
1977 ConstantSDNode *N1C = isConstOrConstSplat(N1);
1978 EVT VT = N->getValueType(0);
1981 if (VT.isVector()) {
1982 SDValue FoldedVOp = SimplifyVBinOp(N);
1983 if (FoldedVOp.getNode()) return FoldedVOp;
1986 // fold (sdiv c1, c2) -> c1/c2
1987 if (N0C && N1C && !N1C->isNullValue())
1988 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1989 // fold (sdiv X, 1) -> X
1990 if (N1C && N1C->getAPIntValue() == 1LL)
1992 // fold (sdiv X, -1) -> 0-X
1993 if (N1C && N1C->isAllOnesValue())
1994 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1995 DAG.getConstant(0, VT), N0);
1996 // If we know the sign bits of both operands are zero, strength reduce to a
1997 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1998 if (!VT.isVector()) {
1999 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2000 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2004 // fold (sdiv X, pow2) -> simple ops after legalize
2005 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2006 (-N1C->getAPIntValue()).isPowerOf2())) {
2007 // If dividing by powers of two is cheap, then don't perform the following
2009 if (TLI.isPow2DivCheap())
2012 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2014 // Splat the sign bit into the register
2016 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2017 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2018 getShiftAmountTy(N0.getValueType())));
2019 AddToWorkList(SGN.getNode());
2021 // Add (N0 < 0) ? abs2 - 1 : 0;
2023 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2024 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2025 getShiftAmountTy(SGN.getValueType())));
2026 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2027 AddToWorkList(SRL.getNode());
2028 AddToWorkList(ADD.getNode()); // Divide by pow2
2029 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2030 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2032 // If we're dividing by a positive value, we're done. Otherwise, we must
2033 // negate the result.
2034 if (N1C->getAPIntValue().isNonNegative())
2037 AddToWorkList(SRA.getNode());
2038 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2041 // if integer divide is expensive and we satisfy the requirements, emit an
2042 // alternate sequence.
2043 if (N1C && !TLI.isIntDivCheap()) {
2044 SDValue Op = BuildSDIV(N);
2045 if (Op.getNode()) return Op;
2049 if (N0.getOpcode() == ISD::UNDEF)
2050 return DAG.getConstant(0, VT);
2051 // X / undef -> undef
2052 if (N1.getOpcode() == ISD::UNDEF)
2058 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2059 SDValue N0 = N->getOperand(0);
2060 SDValue N1 = N->getOperand(1);
2061 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2062 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2063 EVT VT = N->getValueType(0);
2066 if (VT.isVector()) {
2067 SDValue FoldedVOp = SimplifyVBinOp(N);
2068 if (FoldedVOp.getNode()) return FoldedVOp;
2071 // fold (udiv c1, c2) -> c1/c2
2072 if (N0C && N1C && !N1C->isNullValue())
2073 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2074 // fold (udiv x, (1 << c)) -> x >>u c
2075 if (N1C && N1C->getAPIntValue().isPowerOf2())
2076 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2077 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2078 getShiftAmountTy(N0.getValueType())));
2079 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2080 if (N1.getOpcode() == ISD::SHL) {
2081 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2082 if (SHC->getAPIntValue().isPowerOf2()) {
2083 EVT ADDVT = N1.getOperand(1).getValueType();
2084 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2086 DAG.getConstant(SHC->getAPIntValue()
2089 AddToWorkList(Add.getNode());
2090 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2094 // fold (udiv x, c) -> alternate
2095 if (N1C && !TLI.isIntDivCheap()) {
2096 SDValue Op = BuildUDIV(N);
2097 if (Op.getNode()) return Op;
2101 if (N0.getOpcode() == ISD::UNDEF)
2102 return DAG.getConstant(0, VT);
2103 // X / undef -> undef
2104 if (N1.getOpcode() == ISD::UNDEF)
2110 SDValue DAGCombiner::visitSREM(SDNode *N) {
2111 SDValue N0 = N->getOperand(0);
2112 SDValue N1 = N->getOperand(1);
2113 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2114 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2115 EVT VT = N->getValueType(0);
2117 // fold (srem c1, c2) -> c1%c2
2118 if (N0C && N1C && !N1C->isNullValue())
2119 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2120 // If we know the sign bits of both operands are zero, strength reduce to a
2121 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2122 if (!VT.isVector()) {
2123 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2124 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2127 // If X/C can be simplified by the division-by-constant logic, lower
2128 // X%C to the equivalent of X-X/C*C.
2129 if (N1C && !N1C->isNullValue()) {
2130 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2131 AddToWorkList(Div.getNode());
2132 SDValue OptimizedDiv = combine(Div.getNode());
2133 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2134 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2136 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2137 AddToWorkList(Mul.getNode());
2143 if (N0.getOpcode() == ISD::UNDEF)
2144 return DAG.getConstant(0, VT);
2145 // X % undef -> undef
2146 if (N1.getOpcode() == ISD::UNDEF)
2152 SDValue DAGCombiner::visitUREM(SDNode *N) {
2153 SDValue N0 = N->getOperand(0);
2154 SDValue N1 = N->getOperand(1);
2155 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2156 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2157 EVT VT = N->getValueType(0);
2159 // fold (urem c1, c2) -> c1%c2
2160 if (N0C && N1C && !N1C->isNullValue())
2161 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2162 // fold (urem x, pow2) -> (and x, pow2-1)
2163 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2164 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2165 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2166 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2167 if (N1.getOpcode() == ISD::SHL) {
2168 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2169 if (SHC->getAPIntValue().isPowerOf2()) {
2171 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2172 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2174 AddToWorkList(Add.getNode());
2175 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2180 // If X/C can be simplified by the division-by-constant logic, lower
2181 // X%C to the equivalent of X-X/C*C.
2182 if (N1C && !N1C->isNullValue()) {
2183 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2184 AddToWorkList(Div.getNode());
2185 SDValue OptimizedDiv = combine(Div.getNode());
2186 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2187 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2189 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2190 AddToWorkList(Mul.getNode());
2196 if (N0.getOpcode() == ISD::UNDEF)
2197 return DAG.getConstant(0, VT);
2198 // X % undef -> undef
2199 if (N1.getOpcode() == ISD::UNDEF)
2205 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2206 SDValue N0 = N->getOperand(0);
2207 SDValue N1 = N->getOperand(1);
2208 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2209 EVT VT = N->getValueType(0);
2212 // fold (mulhs x, 0) -> 0
2213 if (N1C && N1C->isNullValue())
2215 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2216 if (N1C && N1C->getAPIntValue() == 1)
2217 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2218 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2219 getShiftAmountTy(N0.getValueType())));
2220 // fold (mulhs x, undef) -> 0
2221 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2222 return DAG.getConstant(0, VT);
2224 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2226 if (VT.isSimple() && !VT.isVector()) {
2227 MVT Simple = VT.getSimpleVT();
2228 unsigned SimpleSize = Simple.getSizeInBits();
2229 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2230 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2231 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2232 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2233 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2234 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2235 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2236 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2243 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2244 SDValue N0 = N->getOperand(0);
2245 SDValue N1 = N->getOperand(1);
2246 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2247 EVT VT = N->getValueType(0);
2250 // fold (mulhu x, 0) -> 0
2251 if (N1C && N1C->isNullValue())
2253 // fold (mulhu x, 1) -> 0
2254 if (N1C && N1C->getAPIntValue() == 1)
2255 return DAG.getConstant(0, N0.getValueType());
2256 // fold (mulhu x, undef) -> 0
2257 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2258 return DAG.getConstant(0, VT);
2260 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2262 if (VT.isSimple() && !VT.isVector()) {
2263 MVT Simple = VT.getSimpleVT();
2264 unsigned SimpleSize = Simple.getSizeInBits();
2265 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2266 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2267 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2268 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2269 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2270 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2271 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2272 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2279 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2280 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2281 /// that are being performed. Return true if a simplification was made.
2283 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2285 // If the high half is not needed, just compute the low half.
2286 bool HiExists = N->hasAnyUseOfValue(1);
2288 (!LegalOperations ||
2289 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2290 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2291 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2292 return CombineTo(N, Res, Res);
2295 // If the low half is not needed, just compute the high half.
2296 bool LoExists = N->hasAnyUseOfValue(0);
2298 (!LegalOperations ||
2299 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2300 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2301 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2302 return CombineTo(N, Res, Res);
2305 // If both halves are used, return as it is.
2306 if (LoExists && HiExists)
2309 // If the two computed results can be simplified separately, separate them.
2311 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2312 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2313 AddToWorkList(Lo.getNode());
2314 SDValue LoOpt = combine(Lo.getNode());
2315 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2316 (!LegalOperations ||
2317 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2318 return CombineTo(N, LoOpt, LoOpt);
2322 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2323 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2324 AddToWorkList(Hi.getNode());
2325 SDValue HiOpt = combine(Hi.getNode());
2326 if (HiOpt.getNode() && HiOpt != Hi &&
2327 (!LegalOperations ||
2328 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2329 return CombineTo(N, HiOpt, HiOpt);
2335 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2336 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2337 if (Res.getNode()) return Res;
2339 EVT VT = N->getValueType(0);
2342 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2344 if (VT.isSimple() && !VT.isVector()) {
2345 MVT Simple = VT.getSimpleVT();
2346 unsigned SimpleSize = Simple.getSizeInBits();
2347 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2348 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2349 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2350 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2351 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2352 // Compute the high part as N1.
2353 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2354 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2355 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2356 // Compute the low part as N0.
2357 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2358 return CombineTo(N, Lo, Hi);
2365 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2366 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2367 if (Res.getNode()) return Res;
2369 EVT VT = N->getValueType(0);
2372 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2374 if (VT.isSimple() && !VT.isVector()) {
2375 MVT Simple = VT.getSimpleVT();
2376 unsigned SimpleSize = Simple.getSizeInBits();
2377 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2378 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2379 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2380 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2381 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2382 // Compute the high part as N1.
2383 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2384 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2385 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2386 // Compute the low part as N0.
2387 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2388 return CombineTo(N, Lo, Hi);
2395 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2396 // (smulo x, 2) -> (saddo x, x)
2397 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2398 if (C2->getAPIntValue() == 2)
2399 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2400 N->getOperand(0), N->getOperand(0));
2405 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2406 // (umulo x, 2) -> (uaddo x, x)
2407 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2408 if (C2->getAPIntValue() == 2)
2409 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2410 N->getOperand(0), N->getOperand(0));
2415 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2416 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2417 if (Res.getNode()) return Res;
2422 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2423 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2424 if (Res.getNode()) return Res;
2429 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2430 /// two operands of the same opcode, try to simplify it.
2431 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2432 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2433 EVT VT = N0.getValueType();
2434 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2436 // Bail early if none of these transforms apply.
2437 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2439 // For each of OP in AND/OR/XOR:
2440 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2441 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2442 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2443 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2445 // do not sink logical op inside of a vector extend, since it may combine
2447 EVT Op0VT = N0.getOperand(0).getValueType();
2448 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2449 N0.getOpcode() == ISD::SIGN_EXTEND ||
2450 // Avoid infinite looping with PromoteIntBinOp.
2451 (N0.getOpcode() == ISD::ANY_EXTEND &&
2452 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2453 (N0.getOpcode() == ISD::TRUNCATE &&
2454 (!TLI.isZExtFree(VT, Op0VT) ||
2455 !TLI.isTruncateFree(Op0VT, VT)) &&
2456 TLI.isTypeLegal(Op0VT))) &&
2458 Op0VT == N1.getOperand(0).getValueType() &&
2459 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2460 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2461 N0.getOperand(0).getValueType(),
2462 N0.getOperand(0), N1.getOperand(0));
2463 AddToWorkList(ORNode.getNode());
2464 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2467 // For each of OP in SHL/SRL/SRA/AND...
2468 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2469 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2470 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2471 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2472 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2473 N0.getOperand(1) == N1.getOperand(1)) {
2474 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2475 N0.getOperand(0).getValueType(),
2476 N0.getOperand(0), N1.getOperand(0));
2477 AddToWorkList(ORNode.getNode());
2478 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2479 ORNode, N0.getOperand(1));
2482 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2483 // Only perform this optimization after type legalization and before
2484 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2485 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2486 // we don't want to undo this promotion.
2487 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2489 if ((N0.getOpcode() == ISD::BITCAST ||
2490 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2491 Level == AfterLegalizeTypes) {
2492 SDValue In0 = N0.getOperand(0);
2493 SDValue In1 = N1.getOperand(0);
2494 EVT In0Ty = In0.getValueType();
2495 EVT In1Ty = In1.getValueType();
2497 // If both incoming values are integers, and the original types are the
2499 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2500 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2501 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2502 AddToWorkList(Op.getNode());
2507 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2508 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2509 // If both shuffles use the same mask, and both shuffle within a single
2510 // vector, then it is worthwhile to move the swizzle after the operation.
2511 // The type-legalizer generates this pattern when loading illegal
2512 // vector types from memory. In many cases this allows additional shuffle
2514 // There are other cases where moving the shuffle after the xor/and/or
2515 // is profitable even if shuffles don't perform a swizzle.
2516 // If both shuffles use the same mask, and both shuffles have the same first
2517 // or second operand, then it might still be profitable to move the shuffle
2518 // after the xor/and/or operation.
2519 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2520 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2521 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2523 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2524 "Inputs to shuffles are not the same type");
2526 // Check that both shuffles use the same mask. The masks are known to be of
2527 // the same length because the result vector type is the same.
2528 // Check also that shuffles have only one use to avoid introducing extra
2530 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2531 SVN0->getMask().equals(SVN1->getMask())) {
2532 SDValue ShOp = N0->getOperand(1);
2534 // Don't try to fold this node if it requires introducing a
2535 // build vector of all zeros that might be illegal at this stage.
2536 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2538 ShOp = DAG.getConstant(0, VT);
2543 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2544 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2545 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2546 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2547 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2548 N0->getOperand(0), N1->getOperand(0));
2549 AddToWorkList(NewNode.getNode());
2550 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2551 &SVN0->getMask()[0]);
2554 // Don't try to fold this node if it requires introducing a
2555 // build vector of all zeros that might be illegal at this stage.
2556 ShOp = N0->getOperand(0);
2557 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2559 ShOp = DAG.getConstant(0, VT);
2564 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2565 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2566 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2567 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2568 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2569 N0->getOperand(1), N1->getOperand(1));
2570 AddToWorkList(NewNode.getNode());
2571 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2572 &SVN0->getMask()[0]);
2580 SDValue DAGCombiner::visitAND(SDNode *N) {
2581 SDValue N0 = N->getOperand(0);
2582 SDValue N1 = N->getOperand(1);
2583 SDValue LL, LR, RL, RR, CC0, CC1;
2584 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2585 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2586 EVT VT = N1.getValueType();
2587 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2590 if (VT.isVector()) {
2591 SDValue FoldedVOp = SimplifyVBinOp(N);
2592 if (FoldedVOp.getNode()) return FoldedVOp;
2594 // fold (and x, 0) -> 0, vector edition
2595 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2597 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2600 // fold (and x, -1) -> x, vector edition
2601 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2603 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2607 // fold (and x, undef) -> 0
2608 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2609 return DAG.getConstant(0, VT);
2610 // fold (and c1, c2) -> c1&c2
2612 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2613 // canonicalize constant to RHS
2615 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2616 // fold (and x, -1) -> x
2617 if (N1C && N1C->isAllOnesValue())
2619 // if (and x, c) is known to be zero, return 0
2620 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2621 APInt::getAllOnesValue(BitWidth)))
2622 return DAG.getConstant(0, VT);
2624 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2627 // fold (and (or x, C), D) -> D if (C & D) == D
2628 if (N1C && N0.getOpcode() == ISD::OR)
2629 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2630 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2632 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2633 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2634 SDValue N0Op0 = N0.getOperand(0);
2635 APInt Mask = ~N1C->getAPIntValue();
2636 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2637 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2638 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2639 N0.getValueType(), N0Op0);
2641 // Replace uses of the AND with uses of the Zero extend node.
2644 // We actually want to replace all uses of the any_extend with the
2645 // zero_extend, to avoid duplicating things. This will later cause this
2646 // AND to be folded.
2647 CombineTo(N0.getNode(), Zext);
2648 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2651 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2652 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2653 // already be zero by virtue of the width of the base type of the load.
2655 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2657 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2658 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2659 N0.getOpcode() == ISD::LOAD) {
2660 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2661 N0 : N0.getOperand(0) );
2663 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2664 // This can be a pure constant or a vector splat, in which case we treat the
2665 // vector as a scalar and use the splat value.
2666 APInt Constant = APInt::getNullValue(1);
2667 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2668 Constant = C->getAPIntValue();
2669 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2670 APInt SplatValue, SplatUndef;
2671 unsigned SplatBitSize;
2673 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2674 SplatBitSize, HasAnyUndefs);
2676 // Undef bits can contribute to a possible optimisation if set, so
2678 SplatValue |= SplatUndef;
2680 // The splat value may be something like "0x00FFFFFF", which means 0 for
2681 // the first vector value and FF for the rest, repeating. We need a mask
2682 // that will apply equally to all members of the vector, so AND all the
2683 // lanes of the constant together.
2684 EVT VT = Vector->getValueType(0);
2685 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2687 // If the splat value has been compressed to a bitlength lower
2688 // than the size of the vector lane, we need to re-expand it to
2690 if (BitWidth > SplatBitSize)
2691 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2692 SplatBitSize < BitWidth;
2693 SplatBitSize = SplatBitSize * 2)
2694 SplatValue |= SplatValue.shl(SplatBitSize);
2696 Constant = APInt::getAllOnesValue(BitWidth);
2697 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2698 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2702 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2703 // actually legal and isn't going to get expanded, else this is a false
2705 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2706 Load->getMemoryVT());
2708 // Resize the constant to the same size as the original memory access before
2709 // extension. If it is still the AllOnesValue then this AND is completely
2712 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2715 switch (Load->getExtensionType()) {
2716 default: B = false; break;
2717 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2719 case ISD::NON_EXTLOAD: B = true; break;
2722 if (B && Constant.isAllOnesValue()) {
2723 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2724 // preserve semantics once we get rid of the AND.
2725 SDValue NewLoad(Load, 0);
2726 if (Load->getExtensionType() == ISD::EXTLOAD) {
2727 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2728 Load->getValueType(0), SDLoc(Load),
2729 Load->getChain(), Load->getBasePtr(),
2730 Load->getOffset(), Load->getMemoryVT(),
2731 Load->getMemOperand());
2732 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2733 if (Load->getNumValues() == 3) {
2734 // PRE/POST_INC loads have 3 values.
2735 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2736 NewLoad.getValue(2) };
2737 CombineTo(Load, To, 3, true);
2739 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2743 // Fold the AND away, taking care not to fold to the old load node if we
2745 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2747 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2750 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2751 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2752 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2753 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2755 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2756 LL.getValueType().isInteger()) {
2757 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2758 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2759 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2760 LR.getValueType(), LL, RL);
2761 AddToWorkList(ORNode.getNode());
2762 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2764 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2765 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2766 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2767 LR.getValueType(), LL, RL);
2768 AddToWorkList(ANDNode.getNode());
2769 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2771 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2772 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2773 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2774 LR.getValueType(), LL, RL);
2775 AddToWorkList(ORNode.getNode());
2776 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2779 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2780 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2781 Op0 == Op1 && LL.getValueType().isInteger() &&
2782 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2783 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2784 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2785 cast<ConstantSDNode>(RR)->isNullValue()))) {
2786 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2787 LL, DAG.getConstant(1, LL.getValueType()));
2788 AddToWorkList(ADDNode.getNode());
2789 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2790 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2792 // canonicalize equivalent to ll == rl
2793 if (LL == RR && LR == RL) {
2794 Op1 = ISD::getSetCCSwappedOperands(Op1);
2797 if (LL == RL && LR == RR) {
2798 bool isInteger = LL.getValueType().isInteger();
2799 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2800 if (Result != ISD::SETCC_INVALID &&
2801 (!LegalOperations ||
2802 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2803 TLI.isOperationLegal(ISD::SETCC,
2804 getSetCCResultType(N0.getSimpleValueType())))))
2805 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2810 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2811 if (N0.getOpcode() == N1.getOpcode()) {
2812 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2813 if (Tmp.getNode()) return Tmp;
2816 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2817 // fold (and (sra)) -> (and (srl)) when possible.
2818 if (!VT.isVector() &&
2819 SimplifyDemandedBits(SDValue(N, 0)))
2820 return SDValue(N, 0);
2822 // fold (zext_inreg (extload x)) -> (zextload x)
2823 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2824 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2825 EVT MemVT = LN0->getMemoryVT();
2826 // If we zero all the possible extended bits, then we can turn this into
2827 // a zextload if we are running before legalize or the operation is legal.
2828 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2829 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2830 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2831 ((!LegalOperations && !LN0->isVolatile()) ||
2832 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2833 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2834 LN0->getChain(), LN0->getBasePtr(),
2835 MemVT, LN0->getMemOperand());
2837 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2838 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2841 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2842 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2844 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2845 EVT MemVT = LN0->getMemoryVT();
2846 // If we zero all the possible extended bits, then we can turn this into
2847 // a zextload if we are running before legalize or the operation is legal.
2848 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2849 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2850 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2851 ((!LegalOperations && !LN0->isVolatile()) ||
2852 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2853 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2854 LN0->getChain(), LN0->getBasePtr(),
2855 MemVT, LN0->getMemOperand());
2857 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2858 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2862 // fold (and (load x), 255) -> (zextload x, i8)
2863 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2864 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2865 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2866 (N0.getOpcode() == ISD::ANY_EXTEND &&
2867 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2868 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2869 LoadSDNode *LN0 = HasAnyExt
2870 ? cast<LoadSDNode>(N0.getOperand(0))
2871 : cast<LoadSDNode>(N0);
2872 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2873 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2874 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2875 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2876 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2877 EVT LoadedVT = LN0->getMemoryVT();
2879 if (ExtVT == LoadedVT &&
2880 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2881 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2884 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2885 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2886 LN0->getMemOperand());
2888 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2889 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2892 // Do not change the width of a volatile load.
2893 // Do not generate loads of non-round integer types since these can
2894 // be expensive (and would be wrong if the type is not byte sized).
2895 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2896 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2897 EVT PtrType = LN0->getOperand(1).getValueType();
2899 unsigned Alignment = LN0->getAlignment();
2900 SDValue NewPtr = LN0->getBasePtr();
2902 // For big endian targets, we need to add an offset to the pointer
2903 // to load the correct bytes. For little endian systems, we merely
2904 // need to read fewer bytes from the same pointer.
2905 if (TLI.isBigEndian()) {
2906 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2907 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2908 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2909 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2910 NewPtr, DAG.getConstant(PtrOff, PtrType));
2911 Alignment = MinAlign(Alignment, PtrOff);
2914 AddToWorkList(NewPtr.getNode());
2916 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2918 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2919 LN0->getChain(), NewPtr,
2920 LN0->getPointerInfo(),
2921 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2922 Alignment, LN0->getTBAAInfo());
2924 CombineTo(LN0, Load, Load.getValue(1));
2925 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2931 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2932 VT.getSizeInBits() <= 64) {
2933 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2934 APInt ADDC = ADDI->getAPIntValue();
2935 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2936 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2937 // immediate for an add, but it is legal if its top c2 bits are set,
2938 // transform the ADD so the immediate doesn't need to be materialized
2940 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2941 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2942 SRLI->getZExtValue());
2943 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2945 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2947 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2948 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2949 CombineTo(N0.getNode(), NewAdd);
2950 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2958 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2959 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2960 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2961 N0.getOperand(1), false);
2962 if (BSwap.getNode())
2969 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2971 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2972 bool DemandHighBits) {
2973 if (!LegalOperations)
2976 EVT VT = N->getValueType(0);
2977 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2979 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2982 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2983 bool LookPassAnd0 = false;
2984 bool LookPassAnd1 = false;
2985 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2987 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2989 if (N0.getOpcode() == ISD::AND) {
2990 if (!N0.getNode()->hasOneUse())
2992 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2993 if (!N01C || N01C->getZExtValue() != 0xFF00)
2995 N0 = N0.getOperand(0);
2996 LookPassAnd0 = true;
2999 if (N1.getOpcode() == ISD::AND) {
3000 if (!N1.getNode()->hasOneUse())
3002 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3003 if (!N11C || N11C->getZExtValue() != 0xFF)
3005 N1 = N1.getOperand(0);
3006 LookPassAnd1 = true;
3009 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3011 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3013 if (!N0.getNode()->hasOneUse() ||
3014 !N1.getNode()->hasOneUse())
3017 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3018 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3021 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3024 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3025 SDValue N00 = N0->getOperand(0);
3026 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3027 if (!N00.getNode()->hasOneUse())
3029 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3030 if (!N001C || N001C->getZExtValue() != 0xFF)
3032 N00 = N00.getOperand(0);
3033 LookPassAnd0 = true;
3036 SDValue N10 = N1->getOperand(0);
3037 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3038 if (!N10.getNode()->hasOneUse())
3040 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3041 if (!N101C || N101C->getZExtValue() != 0xFF00)
3043 N10 = N10.getOperand(0);
3044 LookPassAnd1 = true;
3050 // Make sure everything beyond the low halfword gets set to zero since the SRL
3051 // 16 will clear the top bits.
3052 unsigned OpSizeInBits = VT.getSizeInBits();
3053 if (DemandHighBits && OpSizeInBits > 16) {
3054 // If the left-shift isn't masked out then the only way this is a bswap is
3055 // if all bits beyond the low 8 are 0. In that case the entire pattern
3056 // reduces to a left shift anyway: leave it for other parts of the combiner.
3060 // However, if the right shift isn't masked out then it might be because
3061 // it's not needed. See if we can spot that too.
3062 if (!LookPassAnd1 &&
3063 !DAG.MaskedValueIsZero(
3064 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3068 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3069 if (OpSizeInBits > 16)
3070 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3071 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3075 /// isBSwapHWordElement - Return true if the specified node is an element
3076 /// that makes up a 32-bit packed halfword byteswap. i.e.
3077 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3078 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3079 if (!N.getNode()->hasOneUse())
3082 unsigned Opc = N.getOpcode();
3083 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3086 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3091 switch (N1C->getZExtValue()) {
3094 case 0xFF: Num = 0; break;
3095 case 0xFF00: Num = 1; break;
3096 case 0xFF0000: Num = 2; break;
3097 case 0xFF000000: Num = 3; break;
3100 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3101 SDValue N0 = N.getOperand(0);
3102 if (Opc == ISD::AND) {
3103 if (Num == 0 || Num == 2) {
3105 // (x >> 8) & 0xff0000
3106 if (N0.getOpcode() != ISD::SRL)
3108 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3109 if (!C || C->getZExtValue() != 8)
3112 // (x << 8) & 0xff00
3113 // (x << 8) & 0xff000000
3114 if (N0.getOpcode() != ISD::SHL)
3116 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3117 if (!C || C->getZExtValue() != 8)
3120 } else if (Opc == ISD::SHL) {
3122 // (x & 0xff0000) << 8
3123 if (Num != 0 && Num != 2)
3125 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3126 if (!C || C->getZExtValue() != 8)
3128 } else { // Opc == ISD::SRL
3129 // (x & 0xff00) >> 8
3130 // (x & 0xff000000) >> 8
3131 if (Num != 1 && Num != 3)
3133 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3134 if (!C || C->getZExtValue() != 8)
3141 Parts[Num] = N0.getOperand(0).getNode();
3145 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3146 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3147 /// => (rotl (bswap x), 16)
3148 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3149 if (!LegalOperations)
3152 EVT VT = N->getValueType(0);
3155 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3158 SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3160 // (or (or (and), (and)), (or (and), (and)))
3161 // (or (or (or (and), (and)), (and)), (and))
3162 if (N0.getOpcode() != ISD::OR)
3164 SDValue N00 = N0.getOperand(0);
3165 SDValue N01 = N0.getOperand(1);
3167 if (N1.getOpcode() == ISD::OR &&
3168 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3169 // (or (or (and), (and)), (or (and), (and)))
3170 SDValue N000 = N00.getOperand(0);
3171 if (!isBSwapHWordElement(N000, Parts))
3174 SDValue N001 = N00.getOperand(1);
3175 if (!isBSwapHWordElement(N001, Parts))
3177 SDValue N010 = N01.getOperand(0);
3178 if (!isBSwapHWordElement(N010, Parts))
3180 SDValue N011 = N01.getOperand(1);
3181 if (!isBSwapHWordElement(N011, Parts))
3184 // (or (or (or (and), (and)), (and)), (and))
3185 if (!isBSwapHWordElement(N1, Parts))
3187 if (!isBSwapHWordElement(N01, Parts))
3189 if (N00.getOpcode() != ISD::OR)
3191 SDValue N000 = N00.getOperand(0);
3192 if (!isBSwapHWordElement(N000, Parts))
3194 SDValue N001 = N00.getOperand(1);
3195 if (!isBSwapHWordElement(N001, Parts))
3199 // Make sure the parts are all coming from the same node.
3200 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3203 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3204 SDValue(Parts[0],0));
3206 // Result of the bswap should be rotated by 16. If it's not legal, then
3207 // do (x << 16) | (x >> 16).
3208 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3209 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3210 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3211 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3212 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3213 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3214 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3215 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3218 SDValue DAGCombiner::visitOR(SDNode *N) {
3219 SDValue N0 = N->getOperand(0);
3220 SDValue N1 = N->getOperand(1);
3221 SDValue LL, LR, RL, RR, CC0, CC1;
3222 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3223 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3224 EVT VT = N1.getValueType();
3227 if (VT.isVector()) {
3228 SDValue FoldedVOp = SimplifyVBinOp(N);
3229 if (FoldedVOp.getNode()) return FoldedVOp;
3231 // fold (or x, 0) -> x, vector edition
3232 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3234 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3237 // fold (or x, -1) -> -1, vector edition
3238 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3240 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3243 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3244 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3245 // Do this only if the resulting shuffle is legal.
3246 if (isa<ShuffleVectorSDNode>(N0) &&
3247 isa<ShuffleVectorSDNode>(N1) &&
3248 // Avoid folding a node with illegal type.
3249 TLI.isTypeLegal(VT) &&
3250 N0->getOperand(1) == N1->getOperand(1) &&
3251 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3252 bool CanFold = true;
3253 unsigned NumElts = VT.getVectorNumElements();
3254 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3255 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3256 // We construct two shuffle masks:
3257 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3258 // and N1 as the second operand.
3259 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3260 // and N0 as the second operand.
3261 // We do this because OR is commutable and therefore there might be
3262 // two ways to fold this node into a shuffle.
3263 SmallVector<int,4> Mask1;
3264 SmallVector<int,4> Mask2;
3266 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3267 int M0 = SV0->getMaskElt(i);
3268 int M1 = SV1->getMaskElt(i);
3270 // Both shuffle indexes are undef. Propagate Undef.
3271 if (M0 < 0 && M1 < 0) {
3272 Mask1.push_back(M0);
3273 Mask2.push_back(M0);
3277 if (M0 < 0 || M1 < 0 ||
3278 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3279 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3284 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3285 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3289 // Fold this sequence only if the resulting shuffle is 'legal'.
3290 if (TLI.isShuffleMaskLegal(Mask1, VT))
3291 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3292 N1->getOperand(0), &Mask1[0]);
3293 if (TLI.isShuffleMaskLegal(Mask2, VT))
3294 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3295 N0->getOperand(0), &Mask2[0]);
3300 // fold (or x, undef) -> -1
3301 if (!LegalOperations &&
3302 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3303 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3304 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3306 // fold (or c1, c2) -> c1|c2
3308 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3309 // canonicalize constant to RHS
3311 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3312 // fold (or x, 0) -> x
3313 if (N1C && N1C->isNullValue())
3315 // fold (or x, -1) -> -1
3316 if (N1C && N1C->isAllOnesValue())
3318 // fold (or x, c) -> c iff (x & ~c) == 0
3319 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3322 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3323 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3324 if (BSwap.getNode())
3326 BSwap = MatchBSwapHWordLow(N, N0, N1);
3327 if (BSwap.getNode())
3331 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3334 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3335 // iff (c1 & c2) == 0.
3336 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3337 isa<ConstantSDNode>(N0.getOperand(1))) {
3338 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3339 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3340 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3343 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3344 DAG.getNode(ISD::OR, SDLoc(N0), VT,
3345 N0.getOperand(0), N1), COR);
3348 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3349 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3350 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3351 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3353 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3354 LL.getValueType().isInteger()) {
3355 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3356 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3357 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3358 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3359 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3360 LR.getValueType(), LL, RL);
3361 AddToWorkList(ORNode.getNode());
3362 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3364 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3365 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3366 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3367 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3368 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3369 LR.getValueType(), LL, RL);
3370 AddToWorkList(ANDNode.getNode());
3371 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3374 // canonicalize equivalent to ll == rl
3375 if (LL == RR && LR == RL) {
3376 Op1 = ISD::getSetCCSwappedOperands(Op1);
3379 if (LL == RL && LR == RR) {
3380 bool isInteger = LL.getValueType().isInteger();
3381 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3382 if (Result != ISD::SETCC_INVALID &&
3383 (!LegalOperations ||
3384 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3385 TLI.isOperationLegal(ISD::SETCC,
3386 getSetCCResultType(N0.getValueType())))))
3387 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3392 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3393 if (N0.getOpcode() == N1.getOpcode()) {
3394 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3395 if (Tmp.getNode()) return Tmp;
3398 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3399 if (N0.getOpcode() == ISD::AND &&
3400 N1.getOpcode() == ISD::AND &&
3401 N0.getOperand(1).getOpcode() == ISD::Constant &&
3402 N1.getOperand(1).getOpcode() == ISD::Constant &&
3403 // Don't increase # computations.
3404 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3405 // We can only do this xform if we know that bits from X that are set in C2
3406 // but not in C1 are already zero. Likewise for Y.
3407 const APInt &LHSMask =
3408 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3409 const APInt &RHSMask =
3410 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3412 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3413 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3414 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3415 N0.getOperand(0), N1.getOperand(0));
3416 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3417 DAG.getConstant(LHSMask | RHSMask, VT));
3421 // See if this is some rotate idiom.
3422 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3423 return SDValue(Rot, 0);
3425 // Simplify the operands using demanded-bits information.
3426 if (!VT.isVector() &&
3427 SimplifyDemandedBits(SDValue(N, 0)))
3428 return SDValue(N, 0);
3433 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3434 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3435 if (Op.getOpcode() == ISD::AND) {
3436 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3437 Mask = Op.getOperand(1);
3438 Op = Op.getOperand(0);
3444 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3452 // Return true if we can prove that, whenever Neg and Pos are both in the
3453 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3454 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3456 // (or (shift1 X, Neg), (shift2 X, Pos))
3458 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3459 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3460 // to consider shift amounts with defined behavior.
3461 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3462 // If OpSize is a power of 2 then:
3464 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3465 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3467 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3468 // for the stronger condition:
3470 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3472 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3473 // we can just replace Neg with Neg' for the rest of the function.
3475 // In other cases we check for the even stronger condition:
3477 // Neg == OpSize - Pos [B]
3479 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3480 // behavior if Pos == 0 (and consequently Neg == OpSize).
3482 // We could actually use [A] whenever OpSize is a power of 2, but the
3483 // only extra cases that it would match are those uninteresting ones
3484 // where Neg and Pos are never in range at the same time. E.g. for
3485 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3486 // as well as (sub 32, Pos), but:
3488 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3490 // always invokes undefined behavior for 32-bit X.
3492 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3493 unsigned MaskLoBits = 0;
3494 if (Neg.getOpcode() == ISD::AND &&
3495 isPowerOf2_64(OpSize) &&
3496 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3497 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3498 Neg = Neg.getOperand(0);
3499 MaskLoBits = Log2_64(OpSize);
3502 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3503 if (Neg.getOpcode() != ISD::SUB)
3505 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3508 SDValue NegOp1 = Neg.getOperand(1);
3510 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3511 // Pos'. The truncation is redundant for the purpose of the equality.
3513 Pos.getOpcode() == ISD::AND &&
3514 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3515 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3516 Pos = Pos.getOperand(0);
3518 // The condition we need is now:
3520 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3522 // If NegOp1 == Pos then we need:
3524 // OpSize & Mask == NegC & Mask
3526 // (because "x & Mask" is a truncation and distributes through subtraction).
3529 Width = NegC->getAPIntValue();
3530 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3531 // Then the condition we want to prove becomes:
3533 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3535 // which, again because "x & Mask" is a truncation, becomes:
3537 // NegC & Mask == (OpSize - PosC) & Mask
3538 // OpSize & Mask == (NegC + PosC) & Mask
3539 else if (Pos.getOpcode() == ISD::ADD &&
3540 Pos.getOperand(0) == NegOp1 &&
3541 Pos.getOperand(1).getOpcode() == ISD::Constant)
3542 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3543 NegC->getAPIntValue());
3547 // Now we just need to check that OpSize & Mask == Width & Mask.
3549 // Opsize & Mask is 0 since Mask is Opsize - 1.
3550 return Width.getLoBits(MaskLoBits) == 0;
3551 return Width == OpSize;
3554 // A subroutine of MatchRotate used once we have found an OR of two opposite
3555 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3556 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3557 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3558 // Neg with outer conversions stripped away.
3559 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3560 SDValue Neg, SDValue InnerPos,
3561 SDValue InnerNeg, unsigned PosOpcode,
3562 unsigned NegOpcode, SDLoc DL) {
3563 // fold (or (shl x, (*ext y)),
3564 // (srl x, (*ext (sub 32, y)))) ->
3565 // (rotl x, y) or (rotr x, (sub 32, y))
3567 // fold (or (shl x, (*ext (sub 32, y))),
3568 // (srl x, (*ext y))) ->
3569 // (rotr x, y) or (rotl x, (sub 32, y))
3570 EVT VT = Shifted.getValueType();
3571 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3572 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3573 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3574 HasPos ? Pos : Neg).getNode();
3580 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3581 // idioms for rotate, and if the target supports rotation instructions, generate
3583 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3584 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3585 EVT VT = LHS.getValueType();
3586 if (!TLI.isTypeLegal(VT)) return nullptr;
3588 // The target must have at least one rotate flavor.
3589 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3590 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3591 if (!HasROTL && !HasROTR) return nullptr;
3593 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3594 SDValue LHSShift; // The shift.
3595 SDValue LHSMask; // AND value if any.
3596 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3597 return nullptr; // Not part of a rotate.
3599 SDValue RHSShift; // The shift.
3600 SDValue RHSMask; // AND value if any.
3601 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3602 return nullptr; // Not part of a rotate.
3604 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3605 return nullptr; // Not shifting the same value.
3607 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3608 return nullptr; // Shifts must disagree.
3610 // Canonicalize shl to left side in a shl/srl pair.
3611 if (RHSShift.getOpcode() == ISD::SHL) {
3612 std::swap(LHS, RHS);
3613 std::swap(LHSShift, RHSShift);
3614 std::swap(LHSMask , RHSMask );
3617 unsigned OpSizeInBits = VT.getSizeInBits();
3618 SDValue LHSShiftArg = LHSShift.getOperand(0);
3619 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3620 SDValue RHSShiftArg = RHSShift.getOperand(0);
3621 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3623 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3624 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3625 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3626 RHSShiftAmt.getOpcode() == ISD::Constant) {
3627 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3628 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3629 if ((LShVal + RShVal) != OpSizeInBits)
3632 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3633 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3635 // If there is an AND of either shifted operand, apply it to the result.
3636 if (LHSMask.getNode() || RHSMask.getNode()) {
3637 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3639 if (LHSMask.getNode()) {
3640 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3641 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3643 if (RHSMask.getNode()) {
3644 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3645 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3648 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3651 return Rot.getNode();
3654 // If there is a mask here, and we have a variable shift, we can't be sure
3655 // that we're masking out the right stuff.
3656 if (LHSMask.getNode() || RHSMask.getNode())
3659 // If the shift amount is sign/zext/any-extended just peel it off.
3660 SDValue LExtOp0 = LHSShiftAmt;
3661 SDValue RExtOp0 = RHSShiftAmt;
3662 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3663 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3664 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3665 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3666 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3667 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3668 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3669 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3670 LExtOp0 = LHSShiftAmt.getOperand(0);
3671 RExtOp0 = RHSShiftAmt.getOperand(0);
3674 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3675 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3679 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3680 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3687 SDValue DAGCombiner::visitXOR(SDNode *N) {
3688 SDValue N0 = N->getOperand(0);
3689 SDValue N1 = N->getOperand(1);
3690 SDValue LHS, RHS, CC;
3691 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3692 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3693 EVT VT = N0.getValueType();
3696 if (VT.isVector()) {
3697 SDValue FoldedVOp = SimplifyVBinOp(N);
3698 if (FoldedVOp.getNode()) return FoldedVOp;
3700 // fold (xor x, 0) -> x, vector edition
3701 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3703 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3707 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3708 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3709 return DAG.getConstant(0, VT);
3710 // fold (xor x, undef) -> undef
3711 if (N0.getOpcode() == ISD::UNDEF)
3713 if (N1.getOpcode() == ISD::UNDEF)
3715 // fold (xor c1, c2) -> c1^c2
3717 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3718 // canonicalize constant to RHS
3720 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3721 // fold (xor x, 0) -> x
3722 if (N1C && N1C->isNullValue())
3725 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3729 // fold !(x cc y) -> (x !cc y)
3730 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3731 bool isInt = LHS.getValueType().isInteger();
3732 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3735 if (!LegalOperations ||
3736 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3737 switch (N0.getOpcode()) {
3739 llvm_unreachable("Unhandled SetCC Equivalent!");
3741 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3742 case ISD::SELECT_CC:
3743 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3744 N0.getOperand(3), NotCC);
3749 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3750 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3751 N0.getNode()->hasOneUse() &&
3752 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3753 SDValue V = N0.getOperand(0);
3754 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3755 DAG.getConstant(1, V.getValueType()));
3756 AddToWorkList(V.getNode());
3757 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3760 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3761 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3762 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3763 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3764 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3765 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3766 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3767 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3768 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3769 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3772 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3773 if (N1C && N1C->isAllOnesValue() &&
3774 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3775 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3776 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3777 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3778 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3779 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3780 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3781 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3784 // fold (xor (and x, y), y) -> (and (not x), y)
3785 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3786 N0->getOperand(1) == N1) {
3787 SDValue X = N0->getOperand(0);
3788 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3789 AddToWorkList(NotX.getNode());
3790 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3792 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3793 if (N1C && N0.getOpcode() == ISD::XOR) {
3794 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3795 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3797 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3798 DAG.getConstant(N1C->getAPIntValue() ^
3799 N00C->getAPIntValue(), VT));
3801 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3802 DAG.getConstant(N1C->getAPIntValue() ^
3803 N01C->getAPIntValue(), VT));
3805 // fold (xor x, x) -> 0
3807 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3809 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3810 if (N0.getOpcode() == N1.getOpcode()) {
3811 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3812 if (Tmp.getNode()) return Tmp;
3815 // Simplify the expression using non-local knowledge.
3816 if (!VT.isVector() &&
3817 SimplifyDemandedBits(SDValue(N, 0)))
3818 return SDValue(N, 0);
3823 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3824 /// the shift amount is a constant.
3825 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3826 // We can't and shouldn't fold opaque constants.
3827 if (Amt->isOpaque())
3830 SDNode *LHS = N->getOperand(0).getNode();
3831 if (!LHS->hasOneUse()) return SDValue();
3833 // We want to pull some binops through shifts, so that we have (and (shift))
3834 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3835 // thing happens with address calculations, so it's important to canonicalize
3837 bool HighBitSet = false; // Can we transform this if the high bit is set?
3839 switch (LHS->getOpcode()) {
3840 default: return SDValue();
3843 HighBitSet = false; // We can only transform sra if the high bit is clear.
3846 HighBitSet = true; // We can only transform sra if the high bit is set.
3849 if (N->getOpcode() != ISD::SHL)
3850 return SDValue(); // only shl(add) not sr[al](add).
3851 HighBitSet = false; // We can only transform sra if the high bit is clear.
3855 // We require the RHS of the binop to be a constant and not opaque as well.
3856 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3857 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3859 // FIXME: disable this unless the input to the binop is a shift by a constant.
3860 // If it is not a shift, it pessimizes some common cases like:
3862 // void foo(int *X, int i) { X[i & 1235] = 1; }
3863 // int bar(int *X, int i) { return X[i & 255]; }
3864 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3865 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3866 BinOpLHSVal->getOpcode() != ISD::SRA &&
3867 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3868 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3871 EVT VT = N->getValueType(0);
3873 // If this is a signed shift right, and the high bit is modified by the
3874 // logical operation, do not perform the transformation. The highBitSet
3875 // boolean indicates the value of the high bit of the constant which would
3876 // cause it to be modified for this operation.
3877 if (N->getOpcode() == ISD::SRA) {
3878 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3879 if (BinOpRHSSignSet != HighBitSet)
3883 if (!TLI.isDesirableToCommuteWithShift(LHS))
3886 // Fold the constants, shifting the binop RHS by the shift amount.
3887 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3889 LHS->getOperand(1), N->getOperand(1));
3890 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3892 // Create the new shift.
3893 SDValue NewShift = DAG.getNode(N->getOpcode(),
3894 SDLoc(LHS->getOperand(0)),
3895 VT, LHS->getOperand(0), N->getOperand(1));
3897 // Create the new binop.
3898 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3901 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3902 assert(N->getOpcode() == ISD::TRUNCATE);
3903 assert(N->getOperand(0).getOpcode() == ISD::AND);
3905 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3906 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3907 SDValue N01 = N->getOperand(0).getOperand(1);
3909 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3910 EVT TruncVT = N->getValueType(0);
3911 SDValue N00 = N->getOperand(0).getOperand(0);
3912 APInt TruncC = N01C->getAPIntValue();
3913 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3915 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3916 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3917 DAG.getConstant(TruncC, TruncVT));
3924 SDValue DAGCombiner::visitRotate(SDNode *N) {
3925 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3926 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3927 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3928 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3929 if (NewOp1.getNode())
3930 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3931 N->getOperand(0), NewOp1);
3936 SDValue DAGCombiner::visitSHL(SDNode *N) {
3937 SDValue N0 = N->getOperand(0);
3938 SDValue N1 = N->getOperand(1);
3939 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3940 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3941 EVT VT = N0.getValueType();
3942 unsigned OpSizeInBits = VT.getScalarSizeInBits();
3945 if (VT.isVector()) {
3946 SDValue FoldedVOp = SimplifyVBinOp(N);
3947 if (FoldedVOp.getNode()) return FoldedVOp;
3949 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3950 // If setcc produces all-one true value then:
3951 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
3952 if (N1CV && N1CV->isConstant()) {
3953 if (N0.getOpcode() == ISD::AND) {
3954 SDValue N00 = N0->getOperand(0);
3955 SDValue N01 = N0->getOperand(1);
3956 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
3958 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
3959 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
3960 TargetLowering::ZeroOrNegativeOneBooleanContent) {
3961 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3963 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3966 N1C = isConstOrConstSplat(N1);
3971 // fold (shl c1, c2) -> c1<<c2
3973 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3974 // fold (shl 0, x) -> 0
3975 if (N0C && N0C->isNullValue())
3977 // fold (shl x, c >= size(x)) -> undef
3978 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3979 return DAG.getUNDEF(VT);
3980 // fold (shl x, 0) -> x
3981 if (N1C && N1C->isNullValue())
3983 // fold (shl undef, x) -> 0
3984 if (N0.getOpcode() == ISD::UNDEF)
3985 return DAG.getConstant(0, VT);
3986 // if (shl x, c) is known to be zero, return 0
3987 if (DAG.MaskedValueIsZero(SDValue(N, 0),
3988 APInt::getAllOnesValue(OpSizeInBits)))
3989 return DAG.getConstant(0, VT);
3990 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3991 if (N1.getOpcode() == ISD::TRUNCATE &&
3992 N1.getOperand(0).getOpcode() == ISD::AND) {
3993 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
3994 if (NewOp1.getNode())
3995 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
3998 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3999 return SDValue(N, 0);
4001 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4002 if (N1C && N0.getOpcode() == ISD::SHL) {
4003 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4004 uint64_t c1 = N0C1->getZExtValue();
4005 uint64_t c2 = N1C->getZExtValue();
4006 if (c1 + c2 >= OpSizeInBits)
4007 return DAG.getConstant(0, VT);
4008 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4009 DAG.getConstant(c1 + c2, N1.getValueType()));
4013 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4014 // For this to be valid, the second form must not preserve any of the bits
4015 // that are shifted out by the inner shift in the first form. This means
4016 // the outer shift size must be >= the number of bits added by the ext.
4017 // As a corollary, we don't care what kind of ext it is.
4018 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4019 N0.getOpcode() == ISD::ANY_EXTEND ||
4020 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4021 N0.getOperand(0).getOpcode() == ISD::SHL) {
4022 SDValue N0Op0 = N0.getOperand(0);
4023 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4024 uint64_t c1 = N0Op0C1->getZExtValue();
4025 uint64_t c2 = N1C->getZExtValue();
4026 EVT InnerShiftVT = N0Op0.getValueType();
4027 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4028 if (c2 >= OpSizeInBits - InnerShiftSize) {
4029 if (c1 + c2 >= OpSizeInBits)
4030 return DAG.getConstant(0, VT);
4031 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4032 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4033 N0Op0->getOperand(0)),
4034 DAG.getConstant(c1 + c2, N1.getValueType()));
4039 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4040 // Only fold this if the inner zext has no other uses to avoid increasing
4041 // the total number of instructions.
4042 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4043 N0.getOperand(0).getOpcode() == ISD::SRL) {
4044 SDValue N0Op0 = N0.getOperand(0);
4045 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4046 uint64_t c1 = N0Op0C1->getZExtValue();
4047 if (c1 < VT.getScalarSizeInBits()) {
4048 uint64_t c2 = N1C->getZExtValue();
4050 SDValue NewOp0 = N0.getOperand(0);
4051 EVT CountVT = NewOp0.getOperand(1).getValueType();
4052 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4053 NewOp0, DAG.getConstant(c2, CountVT));
4054 AddToWorkList(NewSHL.getNode());
4055 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4061 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4062 // (and (srl x, (sub c1, c2), MASK)
4063 // Only fold this if the inner shift has no other uses -- if it does, folding
4064 // this will increase the total number of instructions.
4065 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4066 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4067 uint64_t c1 = N0C1->getZExtValue();
4068 if (c1 < OpSizeInBits) {
4069 uint64_t c2 = N1C->getZExtValue();
4070 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4073 Mask = Mask.shl(c2 - c1);
4074 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4075 DAG.getConstant(c2 - c1, N1.getValueType()));
4077 Mask = Mask.lshr(c1 - c2);
4078 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4079 DAG.getConstant(c1 - c2, N1.getValueType()));
4081 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4082 DAG.getConstant(Mask, VT));
4086 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4087 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4088 unsigned BitSize = VT.getScalarSizeInBits();
4089 SDValue HiBitsMask =
4090 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4091 BitSize - N1C->getZExtValue()), VT);
4092 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4097 SDValue NewSHL = visitShiftByConstant(N, N1C);
4098 if (NewSHL.getNode())
4105 SDValue DAGCombiner::visitSRA(SDNode *N) {
4106 SDValue N0 = N->getOperand(0);
4107 SDValue N1 = N->getOperand(1);
4108 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4109 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4110 EVT VT = N0.getValueType();
4111 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4114 if (VT.isVector()) {
4115 SDValue FoldedVOp = SimplifyVBinOp(N);
4116 if (FoldedVOp.getNode()) return FoldedVOp;
4118 N1C = isConstOrConstSplat(N1);
4121 // fold (sra c1, c2) -> (sra c1, c2)
4123 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4124 // fold (sra 0, x) -> 0
4125 if (N0C && N0C->isNullValue())
4127 // fold (sra -1, x) -> -1
4128 if (N0C && N0C->isAllOnesValue())
4130 // fold (sra x, (setge c, size(x))) -> undef
4131 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4132 return DAG.getUNDEF(VT);
4133 // fold (sra x, 0) -> x
4134 if (N1C && N1C->isNullValue())
4136 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4138 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4139 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4140 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4142 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4143 ExtVT, VT.getVectorNumElements());
4144 if ((!LegalOperations ||
4145 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4146 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4147 N0.getOperand(0), DAG.getValueType(ExtVT));
4150 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4151 if (N1C && N0.getOpcode() == ISD::SRA) {
4152 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4153 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4154 if (Sum >= OpSizeInBits)
4155 Sum = OpSizeInBits - 1;
4156 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4157 DAG.getConstant(Sum, N1.getValueType()));
4161 // fold (sra (shl X, m), (sub result_size, n))
4162 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4163 // result_size - n != m.
4164 // If truncate is free for the target sext(shl) is likely to result in better
4166 if (N0.getOpcode() == ISD::SHL && N1C) {
4167 // Get the two constanst of the shifts, CN0 = m, CN = n.
4168 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4170 LLVMContext &Ctx = *DAG.getContext();
4171 // Determine what the truncate's result bitsize and type would be.
4172 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4175 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4177 // Determine the residual right-shift amount.
4178 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4180 // If the shift is not a no-op (in which case this should be just a sign
4181 // extend already), the truncated to type is legal, sign_extend is legal
4182 // on that type, and the truncate to that type is both legal and free,
4183 // perform the transform.
4184 if ((ShiftAmt > 0) &&
4185 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4186 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4187 TLI.isTruncateFree(VT, TruncVT)) {
4189 SDValue Amt = DAG.getConstant(ShiftAmt,
4190 getShiftAmountTy(N0.getOperand(0).getValueType()));
4191 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4192 N0.getOperand(0), Amt);
4193 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4195 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4196 N->getValueType(0), Trunc);
4201 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4202 if (N1.getOpcode() == ISD::TRUNCATE &&
4203 N1.getOperand(0).getOpcode() == ISD::AND) {
4204 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4205 if (NewOp1.getNode())
4206 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4209 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4210 // if c1 is equal to the number of bits the trunc removes
4211 if (N0.getOpcode() == ISD::TRUNCATE &&
4212 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4213 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4214 N0.getOperand(0).hasOneUse() &&
4215 N0.getOperand(0).getOperand(1).hasOneUse() &&
4217 SDValue N0Op0 = N0.getOperand(0);
4218 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4219 unsigned LargeShiftVal = LargeShift->getZExtValue();
4220 EVT LargeVT = N0Op0.getValueType();
4222 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4224 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4225 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4226 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4227 N0Op0.getOperand(0), Amt);
4228 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4233 // Simplify, based on bits shifted out of the LHS.
4234 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4235 return SDValue(N, 0);
4238 // If the sign bit is known to be zero, switch this to a SRL.
4239 if (DAG.SignBitIsZero(N0))
4240 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4243 SDValue NewSRA = visitShiftByConstant(N, N1C);
4244 if (NewSRA.getNode())
4251 SDValue DAGCombiner::visitSRL(SDNode *N) {
4252 SDValue N0 = N->getOperand(0);
4253 SDValue N1 = N->getOperand(1);
4254 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4255 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4256 EVT VT = N0.getValueType();
4257 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4260 if (VT.isVector()) {
4261 SDValue FoldedVOp = SimplifyVBinOp(N);
4262 if (FoldedVOp.getNode()) return FoldedVOp;
4264 N1C = isConstOrConstSplat(N1);
4267 // fold (srl c1, c2) -> c1 >>u c2
4269 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4270 // fold (srl 0, x) -> 0
4271 if (N0C && N0C->isNullValue())
4273 // fold (srl x, c >= size(x)) -> undef
4274 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4275 return DAG.getUNDEF(VT);
4276 // fold (srl x, 0) -> x
4277 if (N1C && N1C->isNullValue())
4279 // if (srl x, c) is known to be zero, return 0
4280 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4281 APInt::getAllOnesValue(OpSizeInBits)))
4282 return DAG.getConstant(0, VT);
4284 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4285 if (N1C && N0.getOpcode() == ISD::SRL) {
4286 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4287 uint64_t c1 = N01C->getZExtValue();
4288 uint64_t c2 = N1C->getZExtValue();
4289 if (c1 + c2 >= OpSizeInBits)
4290 return DAG.getConstant(0, VT);
4291 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4292 DAG.getConstant(c1 + c2, N1.getValueType()));
4296 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4297 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4298 N0.getOperand(0).getOpcode() == ISD::SRL &&
4299 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4301 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4302 uint64_t c2 = N1C->getZExtValue();
4303 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4304 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4305 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4306 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4307 if (c1 + OpSizeInBits == InnerShiftSize) {
4308 if (c1 + c2 >= InnerShiftSize)
4309 return DAG.getConstant(0, VT);
4310 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4311 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4312 N0.getOperand(0)->getOperand(0),
4313 DAG.getConstant(c1 + c2, ShiftCountVT)));
4317 // fold (srl (shl x, c), c) -> (and x, cst2)
4318 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4319 unsigned BitSize = N0.getScalarValueSizeInBits();
4320 if (BitSize <= 64) {
4321 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4322 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4323 DAG.getConstant(~0ULL >> ShAmt, VT));
4327 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4328 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4329 // Shifting in all undef bits?
4330 EVT SmallVT = N0.getOperand(0).getValueType();
4331 unsigned BitSize = SmallVT.getScalarSizeInBits();
4332 if (N1C->getZExtValue() >= BitSize)
4333 return DAG.getUNDEF(VT);
4335 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4336 uint64_t ShiftAmt = N1C->getZExtValue();
4337 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4339 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4340 AddToWorkList(SmallShift.getNode());
4341 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4342 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4343 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4344 DAG.getConstant(Mask, VT));
4348 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4349 // bit, which is unmodified by sra.
4350 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4351 if (N0.getOpcode() == ISD::SRA)
4352 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4355 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4356 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4357 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4358 APInt KnownZero, KnownOne;
4359 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4361 // If any of the input bits are KnownOne, then the input couldn't be all
4362 // zeros, thus the result of the srl will always be zero.
4363 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4365 // If all of the bits input the to ctlz node are known to be zero, then
4366 // the result of the ctlz is "32" and the result of the shift is one.
4367 APInt UnknownBits = ~KnownZero;
4368 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4370 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4371 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4372 // Okay, we know that only that the single bit specified by UnknownBits
4373 // could be set on input to the CTLZ node. If this bit is set, the SRL
4374 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4375 // to an SRL/XOR pair, which is likely to simplify more.
4376 unsigned ShAmt = UnknownBits.countTrailingZeros();
4377 SDValue Op = N0.getOperand(0);
4380 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4381 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4382 AddToWorkList(Op.getNode());
4385 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4386 Op, DAG.getConstant(1, VT));
4390 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4391 if (N1.getOpcode() == ISD::TRUNCATE &&
4392 N1.getOperand(0).getOpcode() == ISD::AND) {
4393 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4394 if (NewOp1.getNode())
4395 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4398 // fold operands of srl based on knowledge that the low bits are not
4400 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4401 return SDValue(N, 0);
4404 SDValue NewSRL = visitShiftByConstant(N, N1C);
4405 if (NewSRL.getNode())
4409 // Attempt to convert a srl of a load into a narrower zero-extending load.
4410 SDValue NarrowLoad = ReduceLoadWidth(N);
4411 if (NarrowLoad.getNode())
4414 // Here is a common situation. We want to optimize:
4417 // %b = and i32 %a, 2
4418 // %c = srl i32 %b, 1
4419 // brcond i32 %c ...
4425 // %c = setcc eq %b, 0
4428 // However when after the source operand of SRL is optimized into AND, the SRL
4429 // itself may not be optimized further. Look for it and add the BRCOND into
4431 if (N->hasOneUse()) {
4432 SDNode *Use = *N->use_begin();
4433 if (Use->getOpcode() == ISD::BRCOND)
4435 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4436 // Also look pass the truncate.
4437 Use = *Use->use_begin();
4438 if (Use->getOpcode() == ISD::BRCOND)
4446 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4447 SDValue N0 = N->getOperand(0);
4448 EVT VT = N->getValueType(0);
4450 // fold (ctlz c1) -> c2
4451 if (isa<ConstantSDNode>(N0))
4452 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4456 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4457 SDValue N0 = N->getOperand(0);
4458 EVT VT = N->getValueType(0);
4460 // fold (ctlz_zero_undef c1) -> c2
4461 if (isa<ConstantSDNode>(N0))
4462 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4466 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4467 SDValue N0 = N->getOperand(0);
4468 EVT VT = N->getValueType(0);
4470 // fold (cttz c1) -> c2
4471 if (isa<ConstantSDNode>(N0))
4472 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4476 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4477 SDValue N0 = N->getOperand(0);
4478 EVT VT = N->getValueType(0);
4480 // fold (cttz_zero_undef c1) -> c2
4481 if (isa<ConstantSDNode>(N0))
4482 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4486 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4487 SDValue N0 = N->getOperand(0);
4488 EVT VT = N->getValueType(0);
4490 // fold (ctpop c1) -> c2
4491 if (isa<ConstantSDNode>(N0))
4492 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4496 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4497 SDValue N0 = N->getOperand(0);
4498 SDValue N1 = N->getOperand(1);
4499 SDValue N2 = N->getOperand(2);
4500 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4501 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4502 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4503 EVT VT = N->getValueType(0);
4504 EVT VT0 = N0.getValueType();
4506 // fold (select C, X, X) -> X
4509 // fold (select true, X, Y) -> X
4510 if (N0C && !N0C->isNullValue())
4512 // fold (select false, X, Y) -> Y
4513 if (N0C && N0C->isNullValue())
4515 // fold (select C, 1, X) -> (or C, X)
4516 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4517 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4518 // fold (select C, 0, 1) -> (xor C, 1)
4519 // We can't do this reliably if integer based booleans have different contents
4520 // to floating point based booleans. This is because we can't tell whether we
4521 // have an integer-based boolean or a floating-point-based boolean unless we
4522 // can find the SETCC that produced it and inspect its operands. This is
4523 // fairly easy if C is the SETCC node, but it can potentially be
4524 // undiscoverable (or not reasonably discoverable). For example, it could be
4525 // in another basic block or it could require searching a complicated
4527 if (VT.isInteger() &&
4528 (VT0 == MVT::i1 || (VT0.isInteger() &&
4529 TLI.getBooleanContents(false, false) ==
4530 TLI.getBooleanContents(false, true) &&
4531 TLI.getBooleanContents(false, false) ==
4532 TargetLowering::ZeroOrOneBooleanContent)) &&
4533 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4536 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4537 N0, DAG.getConstant(1, VT0));
4538 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4539 N0, DAG.getConstant(1, VT0));
4540 AddToWorkList(XORNode.getNode());
4542 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4543 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4545 // fold (select C, 0, X) -> (and (not C), X)
4546 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4547 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4548 AddToWorkList(NOTNode.getNode());
4549 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4551 // fold (select C, X, 1) -> (or (not C), X)
4552 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4553 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4554 AddToWorkList(NOTNode.getNode());
4555 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4557 // fold (select C, X, 0) -> (and C, X)
4558 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4559 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4560 // fold (select X, X, Y) -> (or X, Y)
4561 // fold (select X, 1, Y) -> (or X, Y)
4562 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4563 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4564 // fold (select X, Y, X) -> (and X, Y)
4565 // fold (select X, Y, 0) -> (and X, Y)
4566 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4567 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4569 // If we can fold this based on the true/false value, do so.
4570 if (SimplifySelectOps(N, N1, N2))
4571 return SDValue(N, 0); // Don't revisit N.
4573 // fold selects based on a setcc into other things, such as min/max/abs
4574 if (N0.getOpcode() == ISD::SETCC) {
4575 if ((!LegalOperations &&
4576 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4577 TLI.isOperationLegal(ISD::SELECT_CC, VT))
4578 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4579 N0.getOperand(0), N0.getOperand(1),
4580 N1, N2, N0.getOperand(2));
4581 return SimplifySelect(SDLoc(N), N0, N1, N2);
4588 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4591 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4593 // Split the inputs.
4594 SDValue Lo, Hi, LL, LH, RL, RH;
4595 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4596 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4598 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4599 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4601 return std::make_pair(Lo, Hi);
4604 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4605 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4606 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4608 SDValue Cond = N->getOperand(0);
4609 SDValue LHS = N->getOperand(1);
4610 SDValue RHS = N->getOperand(2);
4611 MVT VT = N->getSimpleValueType(0);
4612 int NumElems = VT.getVectorNumElements();
4613 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4614 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4615 Cond.getOpcode() == ISD::BUILD_VECTOR);
4617 // We're sure we have an even number of elements due to the
4618 // concat_vectors we have as arguments to vselect.
4619 // Skip BV elements until we find one that's not an UNDEF
4620 // After we find an UNDEF element, keep looping until we get to half the
4621 // length of the BV and see if all the non-undef nodes are the same.
4622 ConstantSDNode *BottomHalf = nullptr;
4623 for (int i = 0; i < NumElems / 2; ++i) {
4624 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4627 if (BottomHalf == nullptr)
4628 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4629 else if (Cond->getOperand(i).getNode() != BottomHalf)
4633 // Do the same for the second half of the BuildVector
4634 ConstantSDNode *TopHalf = nullptr;
4635 for (int i = NumElems / 2; i < NumElems; ++i) {
4636 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4639 if (TopHalf == nullptr)
4640 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4641 else if (Cond->getOperand(i).getNode() != TopHalf)
4645 assert(TopHalf && BottomHalf &&
4646 "One half of the selector was all UNDEFs and the other was all the "
4647 "same value. This should have been addressed before this function.");
4649 ISD::CONCAT_VECTORS, dl, VT,
4650 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4651 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4654 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4655 SDValue N0 = N->getOperand(0);
4656 SDValue N1 = N->getOperand(1);
4657 SDValue N2 = N->getOperand(2);
4660 // Canonicalize integer abs.
4661 // vselect (setg[te] X, 0), X, -X ->
4662 // vselect (setgt X, -1), X, -X ->
4663 // vselect (setl[te] X, 0), -X, X ->
4664 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4665 if (N0.getOpcode() == ISD::SETCC) {
4666 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4667 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4669 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4671 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4672 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4673 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4674 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4675 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4676 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4677 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4680 EVT VT = LHS.getValueType();
4681 SDValue Shift = DAG.getNode(
4682 ISD::SRA, DL, VT, LHS,
4683 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4684 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4685 AddToWorkList(Shift.getNode());
4686 AddToWorkList(Add.getNode());
4687 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4691 // If the VSELECT result requires splitting and the mask is provided by a
4692 // SETCC, then split both nodes and its operands before legalization. This
4693 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4694 // and enables future optimizations (e.g. min/max pattern matching on X86).
4695 if (N0.getOpcode() == ISD::SETCC) {
4696 EVT VT = N->getValueType(0);
4698 // Check if any splitting is required.
4699 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4700 TargetLowering::TypeSplitVector)
4703 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4704 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4705 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4706 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4708 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4709 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4711 // Add the new VSELECT nodes to the work list in case they need to be split
4713 AddToWorkList(Lo.getNode());
4714 AddToWorkList(Hi.getNode());
4716 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4719 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4720 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4722 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4723 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4726 // The ConvertSelectToConcatVector function is assuming both the above
4727 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4729 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4730 N2.getOpcode() == ISD::CONCAT_VECTORS &&
4731 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4732 SDValue CV = ConvertSelectToConcatVector(N, DAG);
4740 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4741 SDValue N0 = N->getOperand(0);
4742 SDValue N1 = N->getOperand(1);
4743 SDValue N2 = N->getOperand(2);
4744 SDValue N3 = N->getOperand(3);
4745 SDValue N4 = N->getOperand(4);
4746 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4748 // fold select_cc lhs, rhs, x, x, cc -> x
4752 // Determine if the condition we're dealing with is constant
4753 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4754 N0, N1, CC, SDLoc(N), false);
4755 if (SCC.getNode()) {
4756 AddToWorkList(SCC.getNode());
4758 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4759 if (!SCCC->isNullValue())
4760 return N2; // cond always true -> true val
4762 return N3; // cond always false -> false val
4765 // Fold to a simpler select_cc
4766 if (SCC.getOpcode() == ISD::SETCC)
4767 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4768 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4772 // If we can fold this based on the true/false value, do so.
4773 if (SimplifySelectOps(N, N2, N3))
4774 return SDValue(N, 0); // Don't revisit N.
4776 // fold select_cc into other things, such as min/max/abs
4777 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4780 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4781 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4782 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4786 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4787 // dag node into a ConstantSDNode or a build_vector of constants.
4788 // This function is called by the DAGCombiner when visiting sext/zext/aext
4789 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4790 // Vector extends are not folded if operations are legal; this is to
4791 // avoid introducing illegal build_vector dag nodes.
4792 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4793 SelectionDAG &DAG, bool LegalTypes,
4794 bool LegalOperations) {
4795 unsigned Opcode = N->getOpcode();
4796 SDValue N0 = N->getOperand(0);
4797 EVT VT = N->getValueType(0);
4799 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4800 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4802 // fold (sext c1) -> c1
4803 // fold (zext c1) -> c1
4804 // fold (aext c1) -> c1
4805 if (isa<ConstantSDNode>(N0))
4806 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4808 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4809 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4810 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4811 EVT SVT = VT.getScalarType();
4812 if (!(VT.isVector() &&
4813 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4814 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4817 // We can fold this node into a build_vector.
4818 unsigned VTBits = SVT.getSizeInBits();
4819 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4820 unsigned ShAmt = VTBits - EVTBits;
4821 SmallVector<SDValue, 8> Elts;
4822 unsigned NumElts = N0->getNumOperands();
4825 for (unsigned i=0; i != NumElts; ++i) {
4826 SDValue Op = N0->getOperand(i);
4827 if (Op->getOpcode() == ISD::UNDEF) {
4828 Elts.push_back(DAG.getUNDEF(SVT));
4832 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4833 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4834 if (Opcode == ISD::SIGN_EXTEND)
4835 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4838 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4842 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4845 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4846 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4847 // transformation. Returns true if extension are possible and the above
4848 // mentioned transformation is profitable.
4849 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4851 SmallVectorImpl<SDNode *> &ExtendNodes,
4852 const TargetLowering &TLI) {
4853 bool HasCopyToRegUses = false;
4854 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4855 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4856 UE = N0.getNode()->use_end();
4861 if (UI.getUse().getResNo() != N0.getResNo())
4863 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4864 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4865 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4866 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4867 // Sign bits will be lost after a zext.
4870 for (unsigned i = 0; i != 2; ++i) {
4871 SDValue UseOp = User->getOperand(i);
4874 if (!isa<ConstantSDNode>(UseOp))
4879 ExtendNodes.push_back(User);
4882 // If truncates aren't free and there are users we can't
4883 // extend, it isn't worthwhile.
4886 // Remember if this value is live-out.
4887 if (User->getOpcode() == ISD::CopyToReg)
4888 HasCopyToRegUses = true;
4891 if (HasCopyToRegUses) {
4892 bool BothLiveOut = false;
4893 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4895 SDUse &Use = UI.getUse();
4896 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4902 // Both unextended and extended values are live out. There had better be
4903 // a good reason for the transformation.
4904 return ExtendNodes.size();
4909 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4910 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4911 ISD::NodeType ExtType) {
4912 // Extend SetCC uses if necessary.
4913 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4914 SDNode *SetCC = SetCCs[i];
4915 SmallVector<SDValue, 4> Ops;
4917 for (unsigned j = 0; j != 2; ++j) {
4918 SDValue SOp = SetCC->getOperand(j);
4920 Ops.push_back(ExtLoad);
4922 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4925 Ops.push_back(SetCC->getOperand(2));
4926 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
4930 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4931 SDValue N0 = N->getOperand(0);
4932 EVT VT = N->getValueType(0);
4934 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4936 return SDValue(Res, 0);
4938 // fold (sext (sext x)) -> (sext x)
4939 // fold (sext (aext x)) -> (sext x)
4940 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4941 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4944 if (N0.getOpcode() == ISD::TRUNCATE) {
4945 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4946 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4947 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4948 if (NarrowLoad.getNode()) {
4949 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4950 if (NarrowLoad.getNode() != N0.getNode()) {
4951 CombineTo(N0.getNode(), NarrowLoad);
4952 // CombineTo deleted the truncate, if needed, but not what's under it.
4955 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4958 // See if the value being truncated is already sign extended. If so, just
4959 // eliminate the trunc/sext pair.
4960 SDValue Op = N0.getOperand(0);
4961 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4962 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4963 unsigned DestBits = VT.getScalarType().getSizeInBits();
4964 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4966 if (OpBits == DestBits) {
4967 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4968 // bits, it is already ready.
4969 if (NumSignBits > DestBits-MidBits)
4971 } else if (OpBits < DestBits) {
4972 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4973 // bits, just sext from i32.
4974 if (NumSignBits > OpBits-MidBits)
4975 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4977 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4978 // bits, just truncate to i32.
4979 if (NumSignBits > OpBits-MidBits)
4980 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4983 // fold (sext (truncate x)) -> (sextinreg x).
4984 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4985 N0.getValueType())) {
4986 if (OpBits < DestBits)
4987 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4988 else if (OpBits > DestBits)
4989 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4990 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4991 DAG.getValueType(N0.getValueType()));
4995 // fold (sext (load x)) -> (sext (truncate (sextload x)))
4996 // None of the supported targets knows how to perform load and sign extend
4997 // on vectors in one instruction. We only perform this transformation on
4999 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5000 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5001 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5002 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5003 bool DoXform = true;
5004 SmallVector<SDNode*, 4> SetCCs;
5005 if (!N0.hasOneUse())
5006 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5008 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5009 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5011 LN0->getBasePtr(), N0.getValueType(),
5012 LN0->getMemOperand());
5013 CombineTo(N, ExtLoad);
5014 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5015 N0.getValueType(), ExtLoad);
5016 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5017 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5019 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5023 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5024 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5025 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5026 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5027 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5028 EVT MemVT = LN0->getMemoryVT();
5029 if ((!LegalOperations && !LN0->isVolatile()) ||
5030 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5031 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5033 LN0->getBasePtr(), MemVT,
5034 LN0->getMemOperand());
5035 CombineTo(N, ExtLoad);
5036 CombineTo(N0.getNode(),
5037 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5038 N0.getValueType(), ExtLoad),
5039 ExtLoad.getValue(1));
5040 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5044 // fold (sext (and/or/xor (load x), cst)) ->
5045 // (and/or/xor (sextload x), (sext cst))
5046 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5047 N0.getOpcode() == ISD::XOR) &&
5048 isa<LoadSDNode>(N0.getOperand(0)) &&
5049 N0.getOperand(1).getOpcode() == ISD::Constant &&
5050 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5051 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5052 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5053 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5054 bool DoXform = true;
5055 SmallVector<SDNode*, 4> SetCCs;
5056 if (!N0.hasOneUse())
5057 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5060 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5061 LN0->getChain(), LN0->getBasePtr(),
5063 LN0->getMemOperand());
5064 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5065 Mask = Mask.sext(VT.getSizeInBits());
5066 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5067 ExtLoad, DAG.getConstant(Mask, VT));
5068 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5069 SDLoc(N0.getOperand(0)),
5070 N0.getOperand(0).getValueType(), ExtLoad);
5072 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5073 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5075 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5080 if (N0.getOpcode() == ISD::SETCC) {
5081 EVT N0VT = N0.getOperand(0).getValueType();
5082 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5083 // Only do this before legalize for now.
5084 if (VT.isVector() && !LegalOperations &&
5085 TLI.getBooleanContents(N0VT) ==
5086 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5087 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5088 // of the same size as the compared operands. Only optimize sext(setcc())
5089 // if this is the case.
5090 EVT SVT = getSetCCResultType(N0VT);
5092 // We know that the # elements of the results is the same as the
5093 // # elements of the compare (and the # elements of the compare result
5094 // for that matter). Check to see that they are the same size. If so,
5095 // we know that the element size of the sext'd result matches the
5096 // element size of the compare operands.
5097 if (VT.getSizeInBits() == SVT.getSizeInBits())
5098 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5100 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5102 // If the desired elements are smaller or larger than the source
5103 // elements we can use a matching integer vector type and then
5104 // truncate/sign extend
5105 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5106 if (SVT == MatchingVectorType) {
5107 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5108 N0.getOperand(0), N0.getOperand(1),
5109 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5110 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5114 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5115 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5117 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5119 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5120 NegOne, DAG.getConstant(0, VT),
5121 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5122 if (SCC.getNode()) return SCC;
5124 if (!VT.isVector()) {
5125 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5126 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5128 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5129 SDValue SetCC = DAG.getSetCC(DL,
5131 N0.getOperand(0), N0.getOperand(1), CC);
5132 EVT SelectVT = getSetCCResultType(VT);
5133 return DAG.getSelect(DL, VT,
5134 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5135 NegOne, DAG.getConstant(0, VT));
5141 // fold (sext x) -> (zext x) if the sign bit is known zero.
5142 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5143 DAG.SignBitIsZero(N0))
5144 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5149 // isTruncateOf - If N is a truncate of some other value, return true, record
5150 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5151 // This function computes KnownZero to avoid a duplicated call to
5152 // computeKnownBits in the caller.
5153 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5156 if (N->getOpcode() == ISD::TRUNCATE) {
5157 Op = N->getOperand(0);
5158 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5162 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5163 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5166 SDValue Op0 = N->getOperand(0);
5167 SDValue Op1 = N->getOperand(1);
5168 assert(Op0.getValueType() == Op1.getValueType());
5170 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5171 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5172 if (COp0 && COp0->isNullValue())
5174 else if (COp1 && COp1->isNullValue())
5179 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5181 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5187 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5188 SDValue N0 = N->getOperand(0);
5189 EVT VT = N->getValueType(0);
5191 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5193 return SDValue(Res, 0);
5195 // fold (zext (zext x)) -> (zext x)
5196 // fold (zext (aext x)) -> (zext x)
5197 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5198 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5201 // fold (zext (truncate x)) -> (zext x) or
5202 // (zext (truncate x)) -> (truncate x)
5203 // This is valid when the truncated bits of x are already zero.
5204 // FIXME: We should extend this to work for vectors too.
5207 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5208 APInt TruncatedBits =
5209 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5210 APInt(Op.getValueSizeInBits(), 0) :
5211 APInt::getBitsSet(Op.getValueSizeInBits(),
5212 N0.getValueSizeInBits(),
5213 std::min(Op.getValueSizeInBits(),
5214 VT.getSizeInBits()));
5215 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5216 if (VT.bitsGT(Op.getValueType()))
5217 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5218 if (VT.bitsLT(Op.getValueType()))
5219 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5225 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5226 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5227 if (N0.getOpcode() == ISD::TRUNCATE) {
5228 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5229 if (NarrowLoad.getNode()) {
5230 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5231 if (NarrowLoad.getNode() != N0.getNode()) {
5232 CombineTo(N0.getNode(), NarrowLoad);
5233 // CombineTo deleted the truncate, if needed, but not what's under it.
5236 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5240 // fold (zext (truncate x)) -> (and x, mask)
5241 if (N0.getOpcode() == ISD::TRUNCATE &&
5242 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5244 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5245 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5246 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5247 if (NarrowLoad.getNode()) {
5248 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5249 if (NarrowLoad.getNode() != N0.getNode()) {
5250 CombineTo(N0.getNode(), NarrowLoad);
5251 // CombineTo deleted the truncate, if needed, but not what's under it.
5254 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5257 SDValue Op = N0.getOperand(0);
5258 if (Op.getValueType().bitsLT(VT)) {
5259 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5260 AddToWorkList(Op.getNode());
5261 } else if (Op.getValueType().bitsGT(VT)) {
5262 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5263 AddToWorkList(Op.getNode());
5265 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5266 N0.getValueType().getScalarType());
5269 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5270 // if either of the casts is not free.
5271 if (N0.getOpcode() == ISD::AND &&
5272 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5273 N0.getOperand(1).getOpcode() == ISD::Constant &&
5274 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5275 N0.getValueType()) ||
5276 !TLI.isZExtFree(N0.getValueType(), VT))) {
5277 SDValue X = N0.getOperand(0).getOperand(0);
5278 if (X.getValueType().bitsLT(VT)) {
5279 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5280 } else if (X.getValueType().bitsGT(VT)) {
5281 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5283 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5284 Mask = Mask.zext(VT.getSizeInBits());
5285 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5286 X, DAG.getConstant(Mask, VT));
5289 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5290 // None of the supported targets knows how to perform load and vector_zext
5291 // on vectors in one instruction. We only perform this transformation on
5293 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5294 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5295 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5296 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5297 bool DoXform = true;
5298 SmallVector<SDNode*, 4> SetCCs;
5299 if (!N0.hasOneUse())
5300 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5302 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5303 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5305 LN0->getBasePtr(), N0.getValueType(),
5306 LN0->getMemOperand());
5307 CombineTo(N, ExtLoad);
5308 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5309 N0.getValueType(), ExtLoad);
5310 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5312 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5314 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5318 // fold (zext (and/or/xor (load x), cst)) ->
5319 // (and/or/xor (zextload x), (zext cst))
5320 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5321 N0.getOpcode() == ISD::XOR) &&
5322 isa<LoadSDNode>(N0.getOperand(0)) &&
5323 N0.getOperand(1).getOpcode() == ISD::Constant &&
5324 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5325 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5326 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5327 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5328 bool DoXform = true;
5329 SmallVector<SDNode*, 4> SetCCs;
5330 if (!N0.hasOneUse())
5331 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5334 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5335 LN0->getChain(), LN0->getBasePtr(),
5337 LN0->getMemOperand());
5338 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5339 Mask = Mask.zext(VT.getSizeInBits());
5340 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5341 ExtLoad, DAG.getConstant(Mask, VT));
5342 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5343 SDLoc(N0.getOperand(0)),
5344 N0.getOperand(0).getValueType(), ExtLoad);
5346 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5347 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5349 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5354 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5355 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5356 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5357 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5358 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5359 EVT MemVT = LN0->getMemoryVT();
5360 if ((!LegalOperations && !LN0->isVolatile()) ||
5361 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5362 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5364 LN0->getBasePtr(), MemVT,
5365 LN0->getMemOperand());
5366 CombineTo(N, ExtLoad);
5367 CombineTo(N0.getNode(),
5368 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5370 ExtLoad.getValue(1));
5371 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5375 if (N0.getOpcode() == ISD::SETCC) {
5376 if (!LegalOperations && VT.isVector() &&
5377 N0.getValueType().getVectorElementType() == MVT::i1) {
5378 EVT N0VT = N0.getOperand(0).getValueType();
5379 if (getSetCCResultType(N0VT) == N0.getValueType())
5382 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5383 // Only do this before legalize for now.
5384 EVT EltVT = VT.getVectorElementType();
5385 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5386 DAG.getConstant(1, EltVT));
5387 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5388 // We know that the # elements of the results is the same as the
5389 // # elements of the compare (and the # elements of the compare result
5390 // for that matter). Check to see that they are the same size. If so,
5391 // we know that the element size of the sext'd result matches the
5392 // element size of the compare operands.
5393 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5394 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5396 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5397 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5400 // If the desired elements are smaller or larger than the source
5401 // elements we can use a matching integer vector type and then
5402 // truncate/sign extend
5403 EVT MatchingElementType =
5404 EVT::getIntegerVT(*DAG.getContext(),
5405 N0VT.getScalarType().getSizeInBits());
5406 EVT MatchingVectorType =
5407 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5408 N0VT.getVectorNumElements());
5410 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5412 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5413 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5414 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5415 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5418 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5420 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5421 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5422 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5423 if (SCC.getNode()) return SCC;
5426 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5427 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5428 isa<ConstantSDNode>(N0.getOperand(1)) &&
5429 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5431 SDValue ShAmt = N0.getOperand(1);
5432 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5433 if (N0.getOpcode() == ISD::SHL) {
5434 SDValue InnerZExt = N0.getOperand(0);
5435 // If the original shl may be shifting out bits, do not perform this
5437 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5438 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5439 if (ShAmtVal > KnownZeroBits)
5445 // Ensure that the shift amount is wide enough for the shifted value.
5446 if (VT.getSizeInBits() >= 256)
5447 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5449 return DAG.getNode(N0.getOpcode(), DL, VT,
5450 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5457 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5458 SDValue N0 = N->getOperand(0);
5459 EVT VT = N->getValueType(0);
5461 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5463 return SDValue(Res, 0);
5465 // fold (aext (aext x)) -> (aext x)
5466 // fold (aext (zext x)) -> (zext x)
5467 // fold (aext (sext x)) -> (sext x)
5468 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5469 N0.getOpcode() == ISD::ZERO_EXTEND ||
5470 N0.getOpcode() == ISD::SIGN_EXTEND)
5471 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5473 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5474 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5475 if (N0.getOpcode() == ISD::TRUNCATE) {
5476 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5477 if (NarrowLoad.getNode()) {
5478 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5479 if (NarrowLoad.getNode() != N0.getNode()) {
5480 CombineTo(N0.getNode(), NarrowLoad);
5481 // CombineTo deleted the truncate, if needed, but not what's under it.
5484 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5488 // fold (aext (truncate x))
5489 if (N0.getOpcode() == ISD::TRUNCATE) {
5490 SDValue TruncOp = N0.getOperand(0);
5491 if (TruncOp.getValueType() == VT)
5492 return TruncOp; // x iff x size == zext size.
5493 if (TruncOp.getValueType().bitsGT(VT))
5494 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5495 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5498 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5499 // if the trunc is not free.
5500 if (N0.getOpcode() == ISD::AND &&
5501 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5502 N0.getOperand(1).getOpcode() == ISD::Constant &&
5503 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5504 N0.getValueType())) {
5505 SDValue X = N0.getOperand(0).getOperand(0);
5506 if (X.getValueType().bitsLT(VT)) {
5507 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5508 } else if (X.getValueType().bitsGT(VT)) {
5509 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5511 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5512 Mask = Mask.zext(VT.getSizeInBits());
5513 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5514 X, DAG.getConstant(Mask, VT));
5517 // fold (aext (load x)) -> (aext (truncate (extload x)))
5518 // None of the supported targets knows how to perform load and any_ext
5519 // on vectors in one instruction. We only perform this transformation on
5521 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5522 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5523 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
5524 bool DoXform = true;
5525 SmallVector<SDNode*, 4> SetCCs;
5526 if (!N0.hasOneUse())
5527 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5529 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5530 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5532 LN0->getBasePtr(), N0.getValueType(),
5533 LN0->getMemOperand());
5534 CombineTo(N, ExtLoad);
5535 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5536 N0.getValueType(), ExtLoad);
5537 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5538 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5540 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5544 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5545 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5546 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5547 if (N0.getOpcode() == ISD::LOAD &&
5548 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5550 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5551 ISD::LoadExtType ExtType = LN0->getExtensionType();
5552 EVT MemVT = LN0->getMemoryVT();
5553 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5554 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5555 VT, LN0->getChain(), LN0->getBasePtr(),
5556 MemVT, LN0->getMemOperand());
5557 CombineTo(N, ExtLoad);
5558 CombineTo(N0.getNode(),
5559 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5560 N0.getValueType(), ExtLoad),
5561 ExtLoad.getValue(1));
5562 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5566 if (N0.getOpcode() == ISD::SETCC) {
5568 // aext(setcc) -> vsetcc
5569 // aext(setcc) -> truncate(vsetcc)
5570 // aext(setcc) -> aext(vsetcc)
5571 // Only do this before legalize for now.
5572 if (VT.isVector() && !LegalOperations) {
5573 EVT N0VT = N0.getOperand(0).getValueType();
5574 // We know that the # elements of the results is the same as the
5575 // # elements of the compare (and the # elements of the compare result
5576 // for that matter). Check to see that they are the same size. If so,
5577 // we know that the element size of the sext'd result matches the
5578 // element size of the compare operands.
5579 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5580 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5582 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5583 // If the desired elements are smaller or larger than the source
5584 // elements we can use a matching integer vector type and then
5585 // truncate/any extend
5587 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5589 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5591 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5592 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5596 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5598 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5599 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5600 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5608 /// GetDemandedBits - See if the specified operand can be simplified with the
5609 /// knowledge that only the bits specified by Mask are used. If so, return the
5610 /// simpler operand, otherwise return a null SDValue.
5611 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5612 switch (V.getOpcode()) {
5614 case ISD::Constant: {
5615 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5616 assert(CV && "Const value should be ConstSDNode.");
5617 const APInt &CVal = CV->getAPIntValue();
5618 APInt NewVal = CVal & Mask;
5620 return DAG.getConstant(NewVal, V.getValueType());
5625 // If the LHS or RHS don't contribute bits to the or, drop them.
5626 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5627 return V.getOperand(1);
5628 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5629 return V.getOperand(0);
5632 // Only look at single-use SRLs.
5633 if (!V.getNode()->hasOneUse())
5635 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5636 // See if we can recursively simplify the LHS.
5637 unsigned Amt = RHSC->getZExtValue();
5639 // Watch out for shift count overflow though.
5640 if (Amt >= Mask.getBitWidth()) break;
5641 APInt NewMask = Mask << Amt;
5642 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5643 if (SimplifyLHS.getNode())
5644 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5645 SimplifyLHS, V.getOperand(1));
5651 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5652 /// bits and then truncated to a narrower type and where N is a multiple
5653 /// of number of bits of the narrower type, transform it to a narrower load
5654 /// from address + N / num of bits of new type. If the result is to be
5655 /// extended, also fold the extension to form a extending load.
5656 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5657 unsigned Opc = N->getOpcode();
5659 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5660 SDValue N0 = N->getOperand(0);
5661 EVT VT = N->getValueType(0);
5664 // This transformation isn't valid for vector loads.
5668 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5670 if (Opc == ISD::SIGN_EXTEND_INREG) {
5671 ExtType = ISD::SEXTLOAD;
5672 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5673 } else if (Opc == ISD::SRL) {
5674 // Another special-case: SRL is basically zero-extending a narrower value.
5675 ExtType = ISD::ZEXTLOAD;
5677 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5678 if (!N01) return SDValue();
5679 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5680 VT.getSizeInBits() - N01->getZExtValue());
5682 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5685 unsigned EVTBits = ExtVT.getSizeInBits();
5687 // Do not generate loads of non-round integer types since these can
5688 // be expensive (and would be wrong if the type is not byte sized).
5689 if (!ExtVT.isRound())
5693 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5694 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5695 ShAmt = N01->getZExtValue();
5696 // Is the shift amount a multiple of size of VT?
5697 if ((ShAmt & (EVTBits-1)) == 0) {
5698 N0 = N0.getOperand(0);
5699 // Is the load width a multiple of size of VT?
5700 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5704 // At this point, we must have a load or else we can't do the transform.
5705 if (!isa<LoadSDNode>(N0)) return SDValue();
5707 // Because a SRL must be assumed to *need* to zero-extend the high bits
5708 // (as opposed to anyext the high bits), we can't combine the zextload
5709 // lowering of SRL and an sextload.
5710 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5713 // If the shift amount is larger than the input type then we're not
5714 // accessing any of the loaded bytes. If the load was a zextload/extload
5715 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5716 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5721 // If the load is shifted left (and the result isn't shifted back right),
5722 // we can fold the truncate through the shift.
5723 unsigned ShLeftAmt = 0;
5724 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5725 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5726 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5727 ShLeftAmt = N01->getZExtValue();
5728 N0 = N0.getOperand(0);
5732 // If we haven't found a load, we can't narrow it. Don't transform one with
5733 // multiple uses, this would require adding a new load.
5734 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5737 // Don't change the width of a volatile load.
5738 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5739 if (LN0->isVolatile())
5742 // Verify that we are actually reducing a load width here.
5743 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5746 // For the transform to be legal, the load must produce only two values
5747 // (the value loaded and the chain). Don't transform a pre-increment
5748 // load, for example, which produces an extra value. Otherwise the
5749 // transformation is not equivalent, and the downstream logic to replace
5750 // uses gets things wrong.
5751 if (LN0->getNumValues() > 2)
5754 // If the load that we're shrinking is an extload and we're not just
5755 // discarding the extension we can't simply shrink the load. Bail.
5756 // TODO: It would be possible to merge the extensions in some cases.
5757 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5758 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5761 EVT PtrType = N0.getOperand(1).getValueType();
5763 if (PtrType == MVT::Untyped || PtrType.isExtended())
5764 // It's not possible to generate a constant of extended or untyped type.
5767 // For big endian targets, we need to adjust the offset to the pointer to
5768 // load the correct bytes.
5769 if (TLI.isBigEndian()) {
5770 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5771 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5772 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5775 uint64_t PtrOff = ShAmt / 8;
5776 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5777 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5778 PtrType, LN0->getBasePtr(),
5779 DAG.getConstant(PtrOff, PtrType));
5780 AddToWorkList(NewPtr.getNode());
5783 if (ExtType == ISD::NON_EXTLOAD)
5784 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5785 LN0->getPointerInfo().getWithOffset(PtrOff),
5786 LN0->isVolatile(), LN0->isNonTemporal(),
5787 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5789 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5790 LN0->getPointerInfo().getWithOffset(PtrOff),
5791 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5792 NewAlign, LN0->getTBAAInfo());
5794 // Replace the old load's chain with the new load's chain.
5795 WorkListRemover DeadNodes(*this);
5796 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5798 // Shift the result left, if we've swallowed a left shift.
5799 SDValue Result = Load;
5800 if (ShLeftAmt != 0) {
5801 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5802 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5804 // If the shift amount is as large as the result size (but, presumably,
5805 // no larger than the source) then the useful bits of the result are
5806 // zero; we can't simply return the shortened shift, because the result
5807 // of that operation is undefined.
5808 if (ShLeftAmt >= VT.getSizeInBits())
5809 Result = DAG.getConstant(0, VT);
5811 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5812 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5815 // Return the new loaded value.
5819 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5820 SDValue N0 = N->getOperand(0);
5821 SDValue N1 = N->getOperand(1);
5822 EVT VT = N->getValueType(0);
5823 EVT EVT = cast<VTSDNode>(N1)->getVT();
5824 unsigned VTBits = VT.getScalarType().getSizeInBits();
5825 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5827 // fold (sext_in_reg c1) -> c1
5828 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5829 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5831 // If the input is already sign extended, just drop the extension.
5832 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5835 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5836 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5837 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5838 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5839 N0.getOperand(0), N1);
5841 // fold (sext_in_reg (sext x)) -> (sext x)
5842 // fold (sext_in_reg (aext x)) -> (sext x)
5843 // if x is small enough.
5844 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5845 SDValue N00 = N0.getOperand(0);
5846 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5847 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5848 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5851 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5852 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5853 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5855 // fold operands of sext_in_reg based on knowledge that the top bits are not
5857 if (SimplifyDemandedBits(SDValue(N, 0)))
5858 return SDValue(N, 0);
5860 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5861 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5862 SDValue NarrowLoad = ReduceLoadWidth(N);
5863 if (NarrowLoad.getNode())
5866 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5867 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5868 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5869 if (N0.getOpcode() == ISD::SRL) {
5870 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5871 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5872 // We can turn this into an SRA iff the input to the SRL is already sign
5874 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5875 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5876 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5877 N0.getOperand(0), N0.getOperand(1));
5881 // fold (sext_inreg (extload x)) -> (sextload x)
5882 if (ISD::isEXTLoad(N0.getNode()) &&
5883 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5884 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5885 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5886 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5887 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5888 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5890 LN0->getBasePtr(), EVT,
5891 LN0->getMemOperand());
5892 CombineTo(N, ExtLoad);
5893 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5894 AddToWorkList(ExtLoad.getNode());
5895 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5897 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5898 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5900 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5901 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5902 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5903 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5904 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5906 LN0->getBasePtr(), EVT,
5907 LN0->getMemOperand());
5908 CombineTo(N, ExtLoad);
5909 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5910 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5913 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5914 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5915 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5916 N0.getOperand(1), false);
5917 if (BSwap.getNode())
5918 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5922 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5923 // into a build_vector.
5924 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5925 SmallVector<SDValue, 8> Elts;
5926 unsigned NumElts = N0->getNumOperands();
5927 unsigned ShAmt = VTBits - EVTBits;
5929 for (unsigned i = 0; i != NumElts; ++i) {
5930 SDValue Op = N0->getOperand(i);
5931 if (Op->getOpcode() == ISD::UNDEF) {
5936 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5937 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5938 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5939 Op.getValueType()));
5942 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
5948 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5949 SDValue N0 = N->getOperand(0);
5950 EVT VT = N->getValueType(0);
5951 bool isLE = TLI.isLittleEndian();
5954 if (N0.getValueType() == N->getValueType(0))
5956 // fold (truncate c1) -> c1
5957 if (isa<ConstantSDNode>(N0))
5958 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5959 // fold (truncate (truncate x)) -> (truncate x)
5960 if (N0.getOpcode() == ISD::TRUNCATE)
5961 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5962 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5963 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5964 N0.getOpcode() == ISD::SIGN_EXTEND ||
5965 N0.getOpcode() == ISD::ANY_EXTEND) {
5966 if (N0.getOperand(0).getValueType().bitsLT(VT))
5967 // if the source is smaller than the dest, we still need an extend
5968 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5970 if (N0.getOperand(0).getValueType().bitsGT(VT))
5971 // if the source is larger than the dest, than we just need the truncate
5972 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5973 // if the source and dest are the same type, we can drop both the extend
5974 // and the truncate.
5975 return N0.getOperand(0);
5978 // Fold extract-and-trunc into a narrow extract. For example:
5979 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5980 // i32 y = TRUNCATE(i64 x)
5982 // v16i8 b = BITCAST (v2i64 val)
5983 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5985 // Note: We only run this optimization after type legalization (which often
5986 // creates this pattern) and before operation legalization after which
5987 // we need to be more careful about the vector instructions that we generate.
5988 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5989 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
5991 EVT VecTy = N0.getOperand(0).getValueType();
5992 EVT ExTy = N0.getValueType();
5993 EVT TrTy = N->getValueType(0);
5995 unsigned NumElem = VecTy.getVectorNumElements();
5996 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5998 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5999 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6001 SDValue EltNo = N0->getOperand(1);
6002 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6003 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6004 EVT IndexTy = TLI.getVectorIdxTy();
6005 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6007 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6008 NVT, N0.getOperand(0));
6010 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6012 DAG.getConstant(Index, IndexTy));
6016 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6017 if (N0.getOpcode() == ISD::SELECT) {
6018 EVT SrcVT = N0.getValueType();
6019 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6020 TLI.isTruncateFree(SrcVT, VT)) {
6022 SDValue Cond = N0.getOperand(0);
6023 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6024 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6025 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6029 // Fold a series of buildvector, bitcast, and truncate if possible.
6031 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6032 // (2xi32 (buildvector x, y)).
6033 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6034 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6035 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6036 N0.getOperand(0).hasOneUse()) {
6038 SDValue BuildVect = N0.getOperand(0);
6039 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6040 EVT TruncVecEltTy = VT.getVectorElementType();
6042 // Check that the element types match.
6043 if (BuildVectEltTy == TruncVecEltTy) {
6044 // Now we only need to compute the offset of the truncated elements.
6045 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6046 unsigned TruncVecNumElts = VT.getVectorNumElements();
6047 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6049 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6050 "Invalid number of elements");
6052 SmallVector<SDValue, 8> Opnds;
6053 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6054 Opnds.push_back(BuildVect.getOperand(i));
6056 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6060 // See if we can simplify the input to this truncate through knowledge that
6061 // only the low bits are being used.
6062 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6063 // Currently we only perform this optimization on scalars because vectors
6064 // may have different active low bits.
6065 if (!VT.isVector()) {
6067 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6068 VT.getSizeInBits()));
6069 if (Shorter.getNode())
6070 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6072 // fold (truncate (load x)) -> (smaller load x)
6073 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6074 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6075 SDValue Reduced = ReduceLoadWidth(N);
6076 if (Reduced.getNode())
6078 // Handle the case where the load remains an extending load even
6079 // after truncation.
6080 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6081 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6082 if (!LN0->isVolatile() &&
6083 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6084 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6085 VT, LN0->getChain(), LN0->getBasePtr(),
6087 LN0->getMemOperand());
6088 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6093 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6094 // where ... are all 'undef'.
6095 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6096 SmallVector<EVT, 8> VTs;
6099 unsigned NumDefs = 0;
6101 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6102 SDValue X = N0.getOperand(i);
6103 if (X.getOpcode() != ISD::UNDEF) {
6108 // Stop if more than one members are non-undef.
6111 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6112 VT.getVectorElementType(),
6113 X.getValueType().getVectorNumElements()));
6117 return DAG.getUNDEF(VT);
6120 assert(V.getNode() && "The single defined operand is empty!");
6121 SmallVector<SDValue, 8> Opnds;
6122 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6124 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6127 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6128 AddToWorkList(NV.getNode());
6129 Opnds.push_back(NV);
6131 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6135 // Simplify the operands using demanded-bits information.
6136 if (!VT.isVector() &&
6137 SimplifyDemandedBits(SDValue(N, 0)))
6138 return SDValue(N, 0);
6143 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6144 SDValue Elt = N->getOperand(i);
6145 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6146 return Elt.getNode();
6147 return Elt.getOperand(Elt.getResNo()).getNode();
6150 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6151 /// if load locations are consecutive.
6152 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6153 assert(N->getOpcode() == ISD::BUILD_PAIR);
6155 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6156 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6157 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6158 LD1->getAddressSpace() != LD2->getAddressSpace())
6160 EVT LD1VT = LD1->getValueType(0);
6162 if (ISD::isNON_EXTLoad(LD2) &&
6164 // If both are volatile this would reduce the number of volatile loads.
6165 // If one is volatile it might be ok, but play conservative and bail out.
6166 !LD1->isVolatile() &&
6167 !LD2->isVolatile() &&
6168 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6169 unsigned Align = LD1->getAlignment();
6170 unsigned NewAlign = TLI.getDataLayout()->
6171 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6173 if (NewAlign <= Align &&
6174 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6175 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6176 LD1->getBasePtr(), LD1->getPointerInfo(),
6177 false, false, false, Align);
6183 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6184 SDValue N0 = N->getOperand(0);
6185 EVT VT = N->getValueType(0);
6187 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6188 // Only do this before legalize, since afterward the target may be depending
6189 // on the bitconvert.
6190 // First check to see if this is all constant.
6192 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6194 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6196 EVT DestEltVT = N->getValueType(0).getVectorElementType();
6197 assert(!DestEltVT.isVector() &&
6198 "Element type of vector ValueType must not be vector!");
6200 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6203 // If the input is a constant, let getNode fold it.
6204 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6205 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6206 if (Res.getNode() != N) {
6207 if (!LegalOperations ||
6208 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6211 // Folding it resulted in an illegal node, and it's too late to
6212 // do that. Clean up the old node and forego the transformation.
6213 // Ideally this won't happen very often, because instcombine
6214 // and the earlier dagcombine runs (where illegal nodes are
6215 // permitted) should have folded most of them already.
6216 DAG.DeleteNode(Res.getNode());
6220 // (conv (conv x, t1), t2) -> (conv x, t2)
6221 if (N0.getOpcode() == ISD::BITCAST)
6222 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6225 // fold (conv (load x)) -> (load (conv*)x)
6226 // If the resultant load doesn't need a higher alignment than the original!
6227 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6228 // Do not change the width of a volatile load.
6229 !cast<LoadSDNode>(N0)->isVolatile() &&
6230 // Do not remove the cast if the types differ in endian layout.
6231 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6232 TLI.hasBigEndianPartOrdering(VT) &&
6233 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6234 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6235 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6236 unsigned Align = TLI.getDataLayout()->
6237 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6238 unsigned OrigAlign = LN0->getAlignment();
6240 if (Align <= OrigAlign) {
6241 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6242 LN0->getBasePtr(), LN0->getPointerInfo(),
6243 LN0->isVolatile(), LN0->isNonTemporal(),
6244 LN0->isInvariant(), OrigAlign,
6245 LN0->getTBAAInfo());
6247 CombineTo(N0.getNode(),
6248 DAG.getNode(ISD::BITCAST, SDLoc(N0),
6249 N0.getValueType(), Load),
6255 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6256 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6257 // This often reduces constant pool loads.
6258 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6259 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6260 N0.getNode()->hasOneUse() && VT.isInteger() &&
6261 !VT.isVector() && !N0.getValueType().isVector()) {
6262 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6264 AddToWorkList(NewConv.getNode());
6266 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6267 if (N0.getOpcode() == ISD::FNEG)
6268 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6269 NewConv, DAG.getConstant(SignBit, VT));
6270 assert(N0.getOpcode() == ISD::FABS);
6271 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6272 NewConv, DAG.getConstant(~SignBit, VT));
6275 // fold (bitconvert (fcopysign cst, x)) ->
6276 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6277 // Note that we don't handle (copysign x, cst) because this can always be
6278 // folded to an fneg or fabs.
6279 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6280 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6281 VT.isInteger() && !VT.isVector()) {
6282 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6283 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6284 if (isTypeLegal(IntXVT)) {
6285 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6286 IntXVT, N0.getOperand(1));
6287 AddToWorkList(X.getNode());
6289 // If X has a different width than the result/lhs, sext it or truncate it.
6290 unsigned VTWidth = VT.getSizeInBits();
6291 if (OrigXWidth < VTWidth) {
6292 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6293 AddToWorkList(X.getNode());
6294 } else if (OrigXWidth > VTWidth) {
6295 // To get the sign bit in the right place, we have to shift it right
6296 // before truncating.
6297 X = DAG.getNode(ISD::SRL, SDLoc(X),
6298 X.getValueType(), X,
6299 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6300 AddToWorkList(X.getNode());
6301 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6302 AddToWorkList(X.getNode());
6305 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6306 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6307 X, DAG.getConstant(SignBit, VT));
6308 AddToWorkList(X.getNode());
6310 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6311 VT, N0.getOperand(0));
6312 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6313 Cst, DAG.getConstant(~SignBit, VT));
6314 AddToWorkList(Cst.getNode());
6316 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6320 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6321 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6322 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6323 if (CombineLD.getNode())
6330 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6331 EVT VT = N->getValueType(0);
6332 return CombineConsecutiveLoads(N, VT);
6335 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6336 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
6337 /// destination element value type.
6338 SDValue DAGCombiner::
6339 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6340 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6342 // If this is already the right type, we're done.
6343 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6345 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6346 unsigned DstBitSize = DstEltVT.getSizeInBits();
6348 // If this is a conversion of N elements of one type to N elements of another
6349 // type, convert each element. This handles FP<->INT cases.
6350 if (SrcBitSize == DstBitSize) {
6351 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6352 BV->getValueType(0).getVectorNumElements());
6354 // Due to the FP element handling below calling this routine recursively,
6355 // we can end up with a scalar-to-vector node here.
6356 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6357 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6358 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6359 DstEltVT, BV->getOperand(0)));
6361 SmallVector<SDValue, 8> Ops;
6362 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6363 SDValue Op = BV->getOperand(i);
6364 // If the vector element type is not legal, the BUILD_VECTOR operands
6365 // are promoted and implicitly truncated. Make that explicit here.
6366 if (Op.getValueType() != SrcEltVT)
6367 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6368 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6370 AddToWorkList(Ops.back().getNode());
6372 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6375 // Otherwise, we're growing or shrinking the elements. To avoid having to
6376 // handle annoying details of growing/shrinking FP values, we convert them to
6378 if (SrcEltVT.isFloatingPoint()) {
6379 // Convert the input float vector to a int vector where the elements are the
6381 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6382 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6383 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6387 // Now we know the input is an integer vector. If the output is a FP type,
6388 // convert to integer first, then to FP of the right size.
6389 if (DstEltVT.isFloatingPoint()) {
6390 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6391 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6392 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6394 // Next, convert to FP elements of the same size.
6395 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6398 // Okay, we know the src/dst types are both integers of differing types.
6399 // Handling growing first.
6400 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6401 if (SrcBitSize < DstBitSize) {
6402 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6404 SmallVector<SDValue, 8> Ops;
6405 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6406 i += NumInputsPerOutput) {
6407 bool isLE = TLI.isLittleEndian();
6408 APInt NewBits = APInt(DstBitSize, 0);
6409 bool EltIsUndef = true;
6410 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6411 // Shift the previously computed bits over.
6412 NewBits <<= SrcBitSize;
6413 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6414 if (Op.getOpcode() == ISD::UNDEF) continue;
6417 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6418 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6422 Ops.push_back(DAG.getUNDEF(DstEltVT));
6424 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6427 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6428 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6431 // Finally, this must be the case where we are shrinking elements: each input
6432 // turns into multiple outputs.
6433 bool isS2V = ISD::isScalarToVector(BV);
6434 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6435 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6436 NumOutputsPerInput*BV->getNumOperands());
6437 SmallVector<SDValue, 8> Ops;
6439 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6440 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6441 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6442 Ops.push_back(DAG.getUNDEF(DstEltVT));
6446 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6447 getAPIntValue().zextOrTrunc(SrcBitSize);
6449 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6450 APInt ThisVal = OpVal.trunc(DstBitSize);
6451 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6452 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6453 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6454 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6456 OpVal = OpVal.lshr(DstBitSize);
6459 // For big endian targets, swap the order of the pieces of each element.
6460 if (TLI.isBigEndian())
6461 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6464 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6467 SDValue DAGCombiner::visitFADD(SDNode *N) {
6468 SDValue N0 = N->getOperand(0);
6469 SDValue N1 = N->getOperand(1);
6470 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6471 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6472 EVT VT = N->getValueType(0);
6475 if (VT.isVector()) {
6476 SDValue FoldedVOp = SimplifyVBinOp(N);
6477 if (FoldedVOp.getNode()) return FoldedVOp;
6480 // fold (fadd c1, c2) -> c1 + c2
6482 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6483 // canonicalize constant to RHS
6484 if (N0CFP && !N1CFP)
6485 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6486 // fold (fadd A, 0) -> A
6487 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6488 N1CFP->getValueAPF().isZero())
6490 // fold (fadd A, (fneg B)) -> (fsub A, B)
6491 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6492 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6493 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6494 GetNegatedExpression(N1, DAG, LegalOperations));
6495 // fold (fadd (fneg A), B) -> (fsub B, A)
6496 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6497 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6498 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6499 GetNegatedExpression(N0, DAG, LegalOperations));
6501 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6502 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6503 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6504 isa<ConstantFPSDNode>(N0.getOperand(1)))
6505 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6506 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6507 N0.getOperand(1), N1));
6509 // No FP constant should be created after legalization as Instruction
6510 // Selection pass has hard time in dealing with FP constant.
6512 // We don't need test this condition for transformation like following, as
6513 // the DAG being transformed implies it is legal to take FP constant as
6516 // (fadd (fmul c, x), x) -> (fmul c+1, x)
6518 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6520 // If allow, fold (fadd (fneg x), x) -> 0.0
6521 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6522 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6523 return DAG.getConstantFP(0.0, VT);
6525 // If allow, fold (fadd x, (fneg x)) -> 0.0
6526 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6527 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6528 return DAG.getConstantFP(0.0, VT);
6530 // In unsafe math mode, we can fold chains of FADD's of the same value
6531 // into multiplications. This transform is not safe in general because
6532 // we are reducing the number of rounding steps.
6533 if (DAG.getTarget().Options.UnsafeFPMath &&
6534 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6536 if (N0.getOpcode() == ISD::FMUL) {
6537 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6538 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6540 // (fadd (fmul c, x), x) -> (fmul x, c+1)
6541 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6542 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6544 DAG.getConstantFP(1.0, VT));
6545 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6549 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6550 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6551 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6553 DAG.getConstantFP(1.0, VT));
6554 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6558 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6559 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6560 N1.getOperand(0) == N1.getOperand(1) &&
6561 N0.getOperand(1) == N1.getOperand(0)) {
6562 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6564 DAG.getConstantFP(2.0, VT));
6565 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6566 N0.getOperand(1), NewCFP);
6569 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6570 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6571 N1.getOperand(0) == N1.getOperand(1) &&
6572 N0.getOperand(0) == N1.getOperand(0)) {
6573 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6575 DAG.getConstantFP(2.0, VT));
6576 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6577 N0.getOperand(0), NewCFP);
6581 if (N1.getOpcode() == ISD::FMUL) {
6582 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6583 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6585 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6586 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6587 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6589 DAG.getConstantFP(1.0, VT));
6590 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6594 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6595 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6596 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6598 DAG.getConstantFP(1.0, VT));
6599 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6604 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6605 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6606 N0.getOperand(0) == N0.getOperand(1) &&
6607 N1.getOperand(1) == N0.getOperand(0)) {
6608 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6610 DAG.getConstantFP(2.0, VT));
6611 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6612 N1.getOperand(1), NewCFP);
6615 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6616 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6617 N0.getOperand(0) == N0.getOperand(1) &&
6618 N1.getOperand(0) == N0.getOperand(0)) {
6619 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6621 DAG.getConstantFP(2.0, VT));
6622 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6623 N1.getOperand(0), NewCFP);
6627 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6628 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6629 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6630 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6631 (N0.getOperand(0) == N1))
6632 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6633 N1, DAG.getConstantFP(3.0, VT));
6636 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6637 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6638 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6639 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6640 N1.getOperand(0) == N0)
6641 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6642 N0, DAG.getConstantFP(3.0, VT));
6645 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6646 if (AllowNewFpConst &&
6647 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6648 N0.getOperand(0) == N0.getOperand(1) &&
6649 N1.getOperand(0) == N1.getOperand(1) &&
6650 N0.getOperand(0) == N1.getOperand(0))
6651 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6653 DAG.getConstantFP(4.0, VT));
6656 // FADD -> FMA combines:
6657 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6658 DAG.getTarget().Options.UnsafeFPMath) &&
6659 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6660 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6662 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6663 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6664 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6665 N0.getOperand(0), N0.getOperand(1), N1);
6667 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6668 // Note: Commutes FADD operands.
6669 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6670 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6671 N1.getOperand(0), N1.getOperand(1), N0);
6677 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6678 SDValue N0 = N->getOperand(0);
6679 SDValue N1 = N->getOperand(1);
6680 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6681 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6682 EVT VT = N->getValueType(0);
6686 if (VT.isVector()) {
6687 SDValue FoldedVOp = SimplifyVBinOp(N);
6688 if (FoldedVOp.getNode()) return FoldedVOp;
6691 // fold (fsub c1, c2) -> c1-c2
6693 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6694 // fold (fsub A, 0) -> A
6695 if (DAG.getTarget().Options.UnsafeFPMath &&
6696 N1CFP && N1CFP->getValueAPF().isZero())
6698 // fold (fsub 0, B) -> -B
6699 if (DAG.getTarget().Options.UnsafeFPMath &&
6700 N0CFP && N0CFP->getValueAPF().isZero()) {
6701 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6702 return GetNegatedExpression(N1, DAG, LegalOperations);
6703 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6704 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6706 // fold (fsub A, (fneg B)) -> (fadd A, B)
6707 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6708 return DAG.getNode(ISD::FADD, dl, VT, N0,
6709 GetNegatedExpression(N1, DAG, LegalOperations));
6711 // If 'unsafe math' is enabled, fold
6712 // (fsub x, x) -> 0.0 &
6713 // (fsub x, (fadd x, y)) -> (fneg y) &
6714 // (fsub x, (fadd y, x)) -> (fneg y)
6715 if (DAG.getTarget().Options.UnsafeFPMath) {
6717 return DAG.getConstantFP(0.0f, VT);
6719 if (N1.getOpcode() == ISD::FADD) {
6720 SDValue N10 = N1->getOperand(0);
6721 SDValue N11 = N1->getOperand(1);
6723 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6724 &DAG.getTarget().Options))
6725 return GetNegatedExpression(N11, DAG, LegalOperations);
6727 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6728 &DAG.getTarget().Options))
6729 return GetNegatedExpression(N10, DAG, LegalOperations);
6733 // FSUB -> FMA combines:
6734 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6735 DAG.getTarget().Options.UnsafeFPMath) &&
6736 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6737 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6739 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6740 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6741 return DAG.getNode(ISD::FMA, dl, VT,
6742 N0.getOperand(0), N0.getOperand(1),
6743 DAG.getNode(ISD::FNEG, dl, VT, N1));
6745 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6746 // Note: Commutes FSUB operands.
6747 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6748 return DAG.getNode(ISD::FMA, dl, VT,
6749 DAG.getNode(ISD::FNEG, dl, VT,
6751 N1.getOperand(1), N0);
6753 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6754 if (N0.getOpcode() == ISD::FNEG &&
6755 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6756 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6757 SDValue N00 = N0.getOperand(0).getOperand(0);
6758 SDValue N01 = N0.getOperand(0).getOperand(1);
6759 return DAG.getNode(ISD::FMA, dl, VT,
6760 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6761 DAG.getNode(ISD::FNEG, dl, VT, N1));
6768 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6769 SDValue N0 = N->getOperand(0);
6770 SDValue N1 = N->getOperand(1);
6771 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6772 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6773 EVT VT = N->getValueType(0);
6774 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6777 if (VT.isVector()) {
6778 SDValue FoldedVOp = SimplifyVBinOp(N);
6779 if (FoldedVOp.getNode()) return FoldedVOp;
6782 // fold (fmul c1, c2) -> c1*c2
6784 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6785 // canonicalize constant to RHS
6786 if (N0CFP && !N1CFP)
6787 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6788 // fold (fmul A, 0) -> 0
6789 if (DAG.getTarget().Options.UnsafeFPMath &&
6790 N1CFP && N1CFP->getValueAPF().isZero())
6792 // fold (fmul A, 0) -> 0, vector edition.
6793 if (DAG.getTarget().Options.UnsafeFPMath &&
6794 ISD::isBuildVectorAllZeros(N1.getNode()))
6796 // fold (fmul A, 1.0) -> A
6797 if (N1CFP && N1CFP->isExactlyValue(1.0))
6799 // fold (fmul X, 2.0) -> (fadd X, X)
6800 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6801 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6802 // fold (fmul X, -1.0) -> (fneg X)
6803 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6804 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6805 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6807 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6808 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6809 &DAG.getTarget().Options)) {
6810 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6811 &DAG.getTarget().Options)) {
6812 // Both can be negated for free, check to see if at least one is cheaper
6814 if (LHSNeg == 2 || RHSNeg == 2)
6815 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6816 GetNegatedExpression(N0, DAG, LegalOperations),
6817 GetNegatedExpression(N1, DAG, LegalOperations));
6821 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6822 if (DAG.getTarget().Options.UnsafeFPMath &&
6823 N1CFP && N0.getOpcode() == ISD::FMUL &&
6824 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6825 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6826 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6827 N0.getOperand(1), N1));
6832 SDValue DAGCombiner::visitFMA(SDNode *N) {
6833 SDValue N0 = N->getOperand(0);
6834 SDValue N1 = N->getOperand(1);
6835 SDValue N2 = N->getOperand(2);
6836 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6837 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6838 EVT VT = N->getValueType(0);
6841 if (DAG.getTarget().Options.UnsafeFPMath) {
6842 if (N0CFP && N0CFP->isZero())
6844 if (N1CFP && N1CFP->isZero())
6847 if (N0CFP && N0CFP->isExactlyValue(1.0))
6848 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6849 if (N1CFP && N1CFP->isExactlyValue(1.0))
6850 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6852 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6853 if (N0CFP && !N1CFP)
6854 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6856 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6857 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6858 N2.getOpcode() == ISD::FMUL &&
6859 N0 == N2.getOperand(0) &&
6860 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6861 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6862 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6866 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6867 if (DAG.getTarget().Options.UnsafeFPMath &&
6868 N0.getOpcode() == ISD::FMUL && N1CFP &&
6869 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6870 return DAG.getNode(ISD::FMA, dl, VT,
6872 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6876 // (fma x, 1, y) -> (fadd x, y)
6877 // (fma x, -1, y) -> (fadd (fneg x), y)
6879 if (N1CFP->isExactlyValue(1.0))
6880 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6882 if (N1CFP->isExactlyValue(-1.0) &&
6883 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6884 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6885 AddToWorkList(RHSNeg.getNode());
6886 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6890 // (fma x, c, x) -> (fmul x, (c+1))
6891 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6892 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6893 DAG.getNode(ISD::FADD, dl, VT,
6894 N1, DAG.getConstantFP(1.0, VT)));
6896 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6897 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6898 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6899 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6900 DAG.getNode(ISD::FADD, dl, VT,
6901 N1, DAG.getConstantFP(-1.0, VT)));
6907 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6908 SDValue N0 = N->getOperand(0);
6909 SDValue N1 = N->getOperand(1);
6910 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6911 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6912 EVT VT = N->getValueType(0);
6913 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6916 if (VT.isVector()) {
6917 SDValue FoldedVOp = SimplifyVBinOp(N);
6918 if (FoldedVOp.getNode()) return FoldedVOp;
6921 // fold (fdiv c1, c2) -> c1/c2
6923 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6925 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6926 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6927 // Compute the reciprocal 1.0 / c2.
6928 APFloat N1APF = N1CFP->getValueAPF();
6929 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6930 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6931 // Only do the transform if the reciprocal is a legal fp immediate that
6932 // isn't too nasty (eg NaN, denormal, ...).
6933 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6934 (!LegalOperations ||
6935 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6936 // backend)... we should handle this gracefully after Legalize.
6937 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6938 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6939 TLI.isFPImmLegal(Recip, VT)))
6940 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6941 DAG.getConstantFP(Recip, VT));
6944 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6945 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6946 &DAG.getTarget().Options)) {
6947 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6948 &DAG.getTarget().Options)) {
6949 // Both can be negated for free, check to see if at least one is cheaper
6951 if (LHSNeg == 2 || RHSNeg == 2)
6952 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6953 GetNegatedExpression(N0, DAG, LegalOperations),
6954 GetNegatedExpression(N1, DAG, LegalOperations));
6961 SDValue DAGCombiner::visitFREM(SDNode *N) {
6962 SDValue N0 = N->getOperand(0);
6963 SDValue N1 = N->getOperand(1);
6964 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6965 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6966 EVT VT = N->getValueType(0);
6968 // fold (frem c1, c2) -> fmod(c1,c2)
6970 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6975 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6976 SDValue N0 = N->getOperand(0);
6977 SDValue N1 = N->getOperand(1);
6978 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6979 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6980 EVT VT = N->getValueType(0);
6982 if (N0CFP && N1CFP) // Constant fold
6983 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6986 const APFloat& V = N1CFP->getValueAPF();
6987 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6988 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6989 if (!V.isNegative()) {
6990 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6991 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6993 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6994 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6995 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6999 // copysign(fabs(x), y) -> copysign(x, y)
7000 // copysign(fneg(x), y) -> copysign(x, y)
7001 // copysign(copysign(x,z), y) -> copysign(x, y)
7002 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7003 N0.getOpcode() == ISD::FCOPYSIGN)
7004 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7005 N0.getOperand(0), N1);
7007 // copysign(x, abs(y)) -> abs(x)
7008 if (N1.getOpcode() == ISD::FABS)
7009 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7011 // copysign(x, copysign(y,z)) -> copysign(x, z)
7012 if (N1.getOpcode() == ISD::FCOPYSIGN)
7013 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7014 N0, N1.getOperand(1));
7016 // copysign(x, fp_extend(y)) -> copysign(x, y)
7017 // copysign(x, fp_round(y)) -> copysign(x, y)
7018 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7019 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7020 N0, N1.getOperand(0));
7025 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7026 SDValue N0 = N->getOperand(0);
7027 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7028 EVT VT = N->getValueType(0);
7029 EVT OpVT = N0.getValueType();
7031 // fold (sint_to_fp c1) -> c1fp
7033 // ...but only if the target supports immediate floating-point values
7034 (!LegalOperations ||
7035 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7036 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7038 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7039 // but UINT_TO_FP is legal on this target, try to convert.
7040 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7041 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7042 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7043 if (DAG.SignBitIsZero(N0))
7044 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7047 // The next optimizations are desirable only if SELECT_CC can be lowered.
7048 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7049 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7050 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7052 (!LegalOperations ||
7053 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7055 { N0.getOperand(0), N0.getOperand(1),
7056 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7058 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7061 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7062 // (select_cc x, y, 1.0, 0.0,, cc)
7063 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7064 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7065 (!LegalOperations ||
7066 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7068 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7069 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7070 N0.getOperand(0).getOperand(2) };
7071 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7078 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7079 SDValue N0 = N->getOperand(0);
7080 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7081 EVT VT = N->getValueType(0);
7082 EVT OpVT = N0.getValueType();
7084 // fold (uint_to_fp c1) -> c1fp
7086 // ...but only if the target supports immediate floating-point values
7087 (!LegalOperations ||
7088 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7089 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7091 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7092 // but SINT_TO_FP is legal on this target, try to convert.
7093 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7094 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7095 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7096 if (DAG.SignBitIsZero(N0))
7097 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7100 // The next optimizations are desirable only if SELECT_CC can be lowered.
7101 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7102 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7104 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7105 (!LegalOperations ||
7106 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7108 { N0.getOperand(0), N0.getOperand(1),
7109 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7111 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7118 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7119 SDValue N0 = N->getOperand(0);
7120 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7121 EVT VT = N->getValueType(0);
7123 // fold (fp_to_sint c1fp) -> c1
7125 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7130 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7131 SDValue N0 = N->getOperand(0);
7132 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7133 EVT VT = N->getValueType(0);
7135 // fold (fp_to_uint c1fp) -> c1
7137 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7142 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7143 SDValue N0 = N->getOperand(0);
7144 SDValue N1 = N->getOperand(1);
7145 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7146 EVT VT = N->getValueType(0);
7148 // fold (fp_round c1fp) -> c1fp
7150 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7152 // fold (fp_round (fp_extend x)) -> x
7153 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7154 return N0.getOperand(0);
7156 // fold (fp_round (fp_round x)) -> (fp_round x)
7157 if (N0.getOpcode() == ISD::FP_ROUND) {
7158 // This is a value preserving truncation if both round's are.
7159 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7160 N0.getNode()->getConstantOperandVal(1) == 1;
7161 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7162 DAG.getIntPtrConstant(IsTrunc));
7165 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7166 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7167 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7168 N0.getOperand(0), N1);
7169 AddToWorkList(Tmp.getNode());
7170 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7171 Tmp, N0.getOperand(1));
7177 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7178 SDValue N0 = N->getOperand(0);
7179 EVT VT = N->getValueType(0);
7180 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7181 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7183 // fold (fp_round_inreg c1fp) -> c1fp
7184 if (N0CFP && isTypeLegal(EVT)) {
7185 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7186 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7192 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7193 SDValue N0 = N->getOperand(0);
7194 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7195 EVT VT = N->getValueType(0);
7197 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7198 if (N->hasOneUse() &&
7199 N->use_begin()->getOpcode() == ISD::FP_ROUND)
7202 // fold (fp_extend c1fp) -> c1fp
7204 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7206 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7208 if (N0.getOpcode() == ISD::FP_ROUND
7209 && N0.getNode()->getConstantOperandVal(1) == 1) {
7210 SDValue In = N0.getOperand(0);
7211 if (In.getValueType() == VT) return In;
7212 if (VT.bitsLT(In.getValueType()))
7213 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7214 In, N0.getOperand(1));
7215 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7218 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7219 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7220 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
7221 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7222 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7224 LN0->getBasePtr(), N0.getValueType(),
7225 LN0->getMemOperand());
7226 CombineTo(N, ExtLoad);
7227 CombineTo(N0.getNode(),
7228 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7229 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7230 ExtLoad.getValue(1));
7231 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7237 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7238 SDValue N0 = N->getOperand(0);
7239 EVT VT = N->getValueType(0);
7241 if (VT.isVector()) {
7242 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7243 if (FoldedVOp.getNode()) return FoldedVOp;
7246 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7247 &DAG.getTarget().Options))
7248 return GetNegatedExpression(N0, DAG, LegalOperations);
7250 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7251 // constant pool values.
7252 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7254 N0.getNode()->hasOneUse() &&
7255 N0.getOperand(0).getValueType().isInteger()) {
7256 SDValue Int = N0.getOperand(0);
7257 EVT IntVT = Int.getValueType();
7258 if (IntVT.isInteger() && !IntVT.isVector()) {
7259 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7260 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7261 AddToWorkList(Int.getNode());
7262 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7267 // (fneg (fmul c, x)) -> (fmul -c, x)
7268 if (N0.getOpcode() == ISD::FMUL) {
7269 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7271 APFloat CVal = CFP1->getValueAPF();
7273 if (Level >= AfterLegalizeDAG &&
7274 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7275 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7277 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7278 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7285 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7286 SDValue N0 = N->getOperand(0);
7287 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7288 EVT VT = N->getValueType(0);
7290 // fold (fceil c1) -> fceil(c1)
7292 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7297 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7298 SDValue N0 = N->getOperand(0);
7299 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7300 EVT VT = N->getValueType(0);
7302 // fold (ftrunc c1) -> ftrunc(c1)
7304 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7309 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7310 SDValue N0 = N->getOperand(0);
7311 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7312 EVT VT = N->getValueType(0);
7314 // fold (ffloor c1) -> ffloor(c1)
7316 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7321 SDValue DAGCombiner::visitFABS(SDNode *N) {
7322 SDValue N0 = N->getOperand(0);
7323 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7324 EVT VT = N->getValueType(0);
7326 if (VT.isVector()) {
7327 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7328 if (FoldedVOp.getNode()) return FoldedVOp;
7331 // fold (fabs c1) -> fabs(c1)
7333 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7334 // fold (fabs (fabs x)) -> (fabs x)
7335 if (N0.getOpcode() == ISD::FABS)
7336 return N->getOperand(0);
7337 // fold (fabs (fneg x)) -> (fabs x)
7338 // fold (fabs (fcopysign x, y)) -> (fabs x)
7339 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7340 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7342 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7343 // constant pool values.
7344 if (!TLI.isFAbsFree(VT) &&
7345 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7346 N0.getOperand(0).getValueType().isInteger() &&
7347 !N0.getOperand(0).getValueType().isVector()) {
7348 SDValue Int = N0.getOperand(0);
7349 EVT IntVT = Int.getValueType();
7350 if (IntVT.isInteger() && !IntVT.isVector()) {
7351 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7352 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7353 AddToWorkList(Int.getNode());
7354 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7355 N->getValueType(0), Int);
7362 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7363 SDValue Chain = N->getOperand(0);
7364 SDValue N1 = N->getOperand(1);
7365 SDValue N2 = N->getOperand(2);
7367 // If N is a constant we could fold this into a fallthrough or unconditional
7368 // branch. However that doesn't happen very often in normal code, because
7369 // Instcombine/SimplifyCFG should have handled the available opportunities.
7370 // If we did this folding here, it would be necessary to update the
7371 // MachineBasicBlock CFG, which is awkward.
7373 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7375 if (N1.getOpcode() == ISD::SETCC &&
7376 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7377 N1.getOperand(0).getValueType())) {
7378 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7379 Chain, N1.getOperand(2),
7380 N1.getOperand(0), N1.getOperand(1), N2);
7383 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7384 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7385 (N1.getOperand(0).hasOneUse() &&
7386 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7387 SDNode *Trunc = nullptr;
7388 if (N1.getOpcode() == ISD::TRUNCATE) {
7389 // Look pass the truncate.
7390 Trunc = N1.getNode();
7391 N1 = N1.getOperand(0);
7394 // Match this pattern so that we can generate simpler code:
7397 // %b = and i32 %a, 2
7398 // %c = srl i32 %b, 1
7399 // brcond i32 %c ...
7404 // %b = and i32 %a, 2
7405 // %c = setcc eq %b, 0
7408 // This applies only when the AND constant value has one bit set and the
7409 // SRL constant is equal to the log2 of the AND constant. The back-end is
7410 // smart enough to convert the result into a TEST/JMP sequence.
7411 SDValue Op0 = N1.getOperand(0);
7412 SDValue Op1 = N1.getOperand(1);
7414 if (Op0.getOpcode() == ISD::AND &&
7415 Op1.getOpcode() == ISD::Constant) {
7416 SDValue AndOp1 = Op0.getOperand(1);
7418 if (AndOp1.getOpcode() == ISD::Constant) {
7419 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7421 if (AndConst.isPowerOf2() &&
7422 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7424 DAG.getSetCC(SDLoc(N),
7425 getSetCCResultType(Op0.getValueType()),
7426 Op0, DAG.getConstant(0, Op0.getValueType()),
7429 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7430 MVT::Other, Chain, SetCC, N2);
7431 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7432 // will convert it back to (X & C1) >> C2.
7433 CombineTo(N, NewBRCond, false);
7434 // Truncate is dead.
7436 removeFromWorkList(Trunc);
7437 DAG.DeleteNode(Trunc);
7439 // Replace the uses of SRL with SETCC
7440 WorkListRemover DeadNodes(*this);
7441 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7442 removeFromWorkList(N1.getNode());
7443 DAG.DeleteNode(N1.getNode());
7444 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7450 // Restore N1 if the above transformation doesn't match.
7451 N1 = N->getOperand(1);
7454 // Transform br(xor(x, y)) -> br(x != y)
7455 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7456 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7457 SDNode *TheXor = N1.getNode();
7458 SDValue Op0 = TheXor->getOperand(0);
7459 SDValue Op1 = TheXor->getOperand(1);
7460 if (Op0.getOpcode() == Op1.getOpcode()) {
7461 // Avoid missing important xor optimizations.
7462 SDValue Tmp = visitXOR(TheXor);
7463 if (Tmp.getNode()) {
7464 if (Tmp.getNode() != TheXor) {
7465 DEBUG(dbgs() << "\nReplacing.8 ";
7467 dbgs() << "\nWith: ";
7468 Tmp.getNode()->dump(&DAG);
7470 WorkListRemover DeadNodes(*this);
7471 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7472 removeFromWorkList(TheXor);
7473 DAG.DeleteNode(TheXor);
7474 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7475 MVT::Other, Chain, Tmp, N2);
7478 // visitXOR has changed XOR's operands or replaced the XOR completely,
7480 return SDValue(N, 0);
7484 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7486 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7487 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7488 Op0.getOpcode() == ISD::XOR) {
7489 TheXor = Op0.getNode();
7493 EVT SetCCVT = N1.getValueType();
7495 SetCCVT = getSetCCResultType(SetCCVT);
7496 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7499 Equal ? ISD::SETEQ : ISD::SETNE);
7500 // Replace the uses of XOR with SETCC
7501 WorkListRemover DeadNodes(*this);
7502 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7503 removeFromWorkList(N1.getNode());
7504 DAG.DeleteNode(N1.getNode());
7505 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7506 MVT::Other, Chain, SetCC, N2);
7513 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7515 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7516 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7517 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7519 // If N is a constant we could fold this into a fallthrough or unconditional
7520 // branch. However that doesn't happen very often in normal code, because
7521 // Instcombine/SimplifyCFG should have handled the available opportunities.
7522 // If we did this folding here, it would be necessary to update the
7523 // MachineBasicBlock CFG, which is awkward.
7525 // Use SimplifySetCC to simplify SETCC's.
7526 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7527 CondLHS, CondRHS, CC->get(), SDLoc(N),
7529 if (Simp.getNode()) AddToWorkList(Simp.getNode());
7531 // fold to a simpler setcc
7532 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7533 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7534 N->getOperand(0), Simp.getOperand(2),
7535 Simp.getOperand(0), Simp.getOperand(1),
7541 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7542 /// uses N as its base pointer and that N may be folded in the load / store
7543 /// addressing mode.
7544 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7546 const TargetLowering &TLI) {
7548 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7549 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7551 VT = Use->getValueType(0);
7552 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7553 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7555 VT = ST->getValue().getValueType();
7559 TargetLowering::AddrMode AM;
7560 if (N->getOpcode() == ISD::ADD) {
7561 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7564 AM.BaseOffs = Offset->getSExtValue();
7568 } else if (N->getOpcode() == ISD::SUB) {
7569 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7572 AM.BaseOffs = -Offset->getSExtValue();
7579 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7582 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7583 /// pre-indexed load / store when the base pointer is an add or subtract
7584 /// and it has other uses besides the load / store. After the
7585 /// transformation, the new indexed load / store has effectively folded
7586 /// the add / subtract in and all of its other uses are redirected to the
7587 /// new load / store.
7588 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7589 if (Level < AfterLegalizeDAG)
7595 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7596 if (LD->isIndexed())
7598 VT = LD->getMemoryVT();
7599 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7600 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7602 Ptr = LD->getBasePtr();
7603 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7604 if (ST->isIndexed())
7606 VT = ST->getMemoryVT();
7607 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7608 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7610 Ptr = ST->getBasePtr();
7616 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7617 // out. There is no reason to make this a preinc/predec.
7618 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7619 Ptr.getNode()->hasOneUse())
7622 // Ask the target to do addressing mode selection.
7625 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7626 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7629 // Backends without true r+i pre-indexed forms may need to pass a
7630 // constant base with a variable offset so that constant coercion
7631 // will work with the patterns in canonical form.
7632 bool Swapped = false;
7633 if (isa<ConstantSDNode>(BasePtr)) {
7634 std::swap(BasePtr, Offset);
7638 // Don't create a indexed load / store with zero offset.
7639 if (isa<ConstantSDNode>(Offset) &&
7640 cast<ConstantSDNode>(Offset)->isNullValue())
7643 // Try turning it into a pre-indexed load / store except when:
7644 // 1) The new base ptr is a frame index.
7645 // 2) If N is a store and the new base ptr is either the same as or is a
7646 // predecessor of the value being stored.
7647 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7648 // that would create a cycle.
7649 // 4) All uses are load / store ops that use it as old base ptr.
7651 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7652 // (plus the implicit offset) to a register to preinc anyway.
7653 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7658 SDValue Val = cast<StoreSDNode>(N)->getValue();
7659 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7663 // If the offset is a constant, there may be other adds of constants that
7664 // can be folded with this one. We should do this to avoid having to keep
7665 // a copy of the original base pointer.
7666 SmallVector<SDNode *, 16> OtherUses;
7667 if (isa<ConstantSDNode>(Offset))
7668 for (SDNode *Use : BasePtr.getNode()->uses()) {
7669 if (Use == Ptr.getNode())
7672 if (Use->isPredecessorOf(N))
7675 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7680 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7681 if (Op1.getNode() == BasePtr.getNode())
7682 std::swap(Op0, Op1);
7683 assert(Op0.getNode() == BasePtr.getNode() &&
7684 "Use of ADD/SUB but not an operand");
7686 if (!isa<ConstantSDNode>(Op1)) {
7691 // FIXME: In some cases, we can be smarter about this.
7692 if (Op1.getValueType() != Offset.getValueType()) {
7697 OtherUses.push_back(Use);
7701 std::swap(BasePtr, Offset);
7703 // Now check for #3 and #4.
7704 bool RealUse = false;
7706 // Caches for hasPredecessorHelper
7707 SmallPtrSet<const SDNode *, 32> Visited;
7708 SmallVector<const SDNode *, 16> Worklist;
7710 for (SDNode *Use : Ptr.getNode()->uses()) {
7713 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7716 // If Ptr may be folded in addressing mode of other use, then it's
7717 // not profitable to do this transformation.
7718 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7727 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7728 BasePtr, Offset, AM);
7730 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7731 BasePtr, Offset, AM);
7734 DEBUG(dbgs() << "\nReplacing.4 ";
7736 dbgs() << "\nWith: ";
7737 Result.getNode()->dump(&DAG);
7739 WorkListRemover DeadNodes(*this);
7741 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7742 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7744 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7747 // Finally, since the node is now dead, remove it from the graph.
7751 std::swap(BasePtr, Offset);
7753 // Replace other uses of BasePtr that can be updated to use Ptr
7754 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7755 unsigned OffsetIdx = 1;
7756 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7758 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7759 BasePtr.getNode() && "Expected BasePtr operand");
7761 // We need to replace ptr0 in the following expression:
7762 // x0 * offset0 + y0 * ptr0 = t0
7764 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7766 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7767 // indexed load/store and the expresion that needs to be re-written.
7769 // Therefore, we have:
7770 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7772 ConstantSDNode *CN =
7773 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7775 APInt Offset0 = CN->getAPIntValue();
7776 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7778 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7779 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7780 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7781 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7783 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7785 APInt CNV = Offset0;
7786 if (X0 < 0) CNV = -CNV;
7787 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7788 else CNV = CNV - Offset1;
7790 // We can now generate the new expression.
7791 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7792 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7794 SDValue NewUse = DAG.getNode(Opcode,
7795 SDLoc(OtherUses[i]),
7796 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7797 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7798 removeFromWorkList(OtherUses[i]);
7799 DAG.DeleteNode(OtherUses[i]);
7802 // Replace the uses of Ptr with uses of the updated base value.
7803 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7804 removeFromWorkList(Ptr.getNode());
7805 DAG.DeleteNode(Ptr.getNode());
7810 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7811 /// add / sub of the base pointer node into a post-indexed load / store.
7812 /// The transformation folded the add / subtract into the new indexed
7813 /// load / store effectively and all of its uses are redirected to the
7814 /// new load / store.
7815 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7816 if (Level < AfterLegalizeDAG)
7822 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7823 if (LD->isIndexed())
7825 VT = LD->getMemoryVT();
7826 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7827 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7829 Ptr = LD->getBasePtr();
7830 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7831 if (ST->isIndexed())
7833 VT = ST->getMemoryVT();
7834 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7835 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7837 Ptr = ST->getBasePtr();
7843 if (Ptr.getNode()->hasOneUse())
7846 for (SDNode *Op : Ptr.getNode()->uses()) {
7848 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7853 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7854 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7855 // Don't create a indexed load / store with zero offset.
7856 if (isa<ConstantSDNode>(Offset) &&
7857 cast<ConstantSDNode>(Offset)->isNullValue())
7860 // Try turning it into a post-indexed load / store except when
7861 // 1) All uses are load / store ops that use it as base ptr (and
7862 // it may be folded as addressing mmode).
7863 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7864 // nor a successor of N. Otherwise, if Op is folded that would
7867 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7871 bool TryNext = false;
7872 for (SDNode *Use : BasePtr.getNode()->uses()) {
7873 if (Use == Ptr.getNode())
7876 // If all the uses are load / store addresses, then don't do the
7878 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7879 bool RealUse = false;
7880 for (SDNode *UseUse : Use->uses()) {
7881 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7896 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7897 SDValue Result = isLoad
7898 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7899 BasePtr, Offset, AM)
7900 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7901 BasePtr, Offset, AM);
7904 DEBUG(dbgs() << "\nReplacing.5 ";
7906 dbgs() << "\nWith: ";
7907 Result.getNode()->dump(&DAG);
7909 WorkListRemover DeadNodes(*this);
7911 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7912 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7914 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7917 // Finally, since the node is now dead, remove it from the graph.
7920 // Replace the uses of Use with uses of the updated base value.
7921 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7922 Result.getValue(isLoad ? 1 : 0));
7923 removeFromWorkList(Op);
7933 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7934 LoadSDNode *LD = cast<LoadSDNode>(N);
7935 SDValue Chain = LD->getChain();
7936 SDValue Ptr = LD->getBasePtr();
7938 // If load is not volatile and there are no uses of the loaded value (and
7939 // the updated indexed value in case of indexed loads), change uses of the
7940 // chain value into uses of the chain input (i.e. delete the dead load).
7941 if (!LD->isVolatile()) {
7942 if (N->getValueType(1) == MVT::Other) {
7944 if (!N->hasAnyUseOfValue(0)) {
7945 // It's not safe to use the two value CombineTo variant here. e.g.
7946 // v1, chain2 = load chain1, loc
7947 // v2, chain3 = load chain2, loc
7949 // Now we replace use of chain2 with chain1. This makes the second load
7950 // isomorphic to the one we are deleting, and thus makes this load live.
7951 DEBUG(dbgs() << "\nReplacing.6 ";
7953 dbgs() << "\nWith chain: ";
7954 Chain.getNode()->dump(&DAG);
7956 WorkListRemover DeadNodes(*this);
7957 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7959 if (N->use_empty()) {
7960 removeFromWorkList(N);
7964 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7968 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7969 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7970 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7971 DEBUG(dbgs() << "\nReplacing.7 ";
7973 dbgs() << "\nWith: ";
7974 Undef.getNode()->dump(&DAG);
7975 dbgs() << " and 2 other values\n");
7976 WorkListRemover DeadNodes(*this);
7977 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7978 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7979 DAG.getUNDEF(N->getValueType(1)));
7980 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7981 removeFromWorkList(N);
7983 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7988 // If this load is directly stored, replace the load value with the stored
7990 // TODO: Handle store large -> read small portion.
7991 // TODO: Handle TRUNCSTORE/LOADEXT
7992 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7993 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7994 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7995 if (PrevST->getBasePtr() == Ptr &&
7996 PrevST->getValue().getValueType() == N->getValueType(0))
7997 return CombineTo(N, Chain.getOperand(1), Chain);
8001 // Try to infer better alignment information than the load already has.
8002 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8003 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8004 if (Align > LD->getMemOperand()->getBaseAlignment()) {
8006 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8007 LD->getValueType(0),
8008 Chain, Ptr, LD->getPointerInfo(),
8010 LD->isVolatile(), LD->isNonTemporal(), Align,
8012 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8017 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8018 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
8020 if (CombinerAAOnlyFunc.getNumOccurrences() &&
8021 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8024 if (UseAA && LD->isUnindexed()) {
8025 // Walk up chain skipping non-aliasing memory nodes.
8026 SDValue BetterChain = FindBetterChain(N, Chain);
8028 // If there is a better chain.
8029 if (Chain != BetterChain) {
8032 // Replace the chain to void dependency.
8033 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8034 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8035 BetterChain, Ptr, LD->getMemOperand());
8037 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8038 LD->getValueType(0),
8039 BetterChain, Ptr, LD->getMemoryVT(),
8040 LD->getMemOperand());
8043 // Create token factor to keep old chain connected.
8044 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8045 MVT::Other, Chain, ReplLoad.getValue(1));
8047 // Make sure the new and old chains are cleaned up.
8048 AddToWorkList(Token.getNode());
8050 // Replace uses with load result and token factor. Don't add users
8052 return CombineTo(N, ReplLoad.getValue(0), Token, false);
8056 // Try transforming N to an indexed load.
8057 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8058 return SDValue(N, 0);
8060 // Try to slice up N to more direct loads if the slices are mapped to
8061 // different register banks or pairing can take place.
8063 return SDValue(N, 0);
8069 /// \brief Helper structure used to slice a load in smaller loads.
8070 /// Basically a slice is obtained from the following sequence:
8071 /// Origin = load Ty1, Base
8072 /// Shift = srl Ty1 Origin, CstTy Amount
8073 /// Inst = trunc Shift to Ty2
8075 /// Then, it will be rewriten into:
8076 /// Slice = load SliceTy, Base + SliceOffset
8077 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8079 /// SliceTy is deduced from the number of bits that are actually used to
8081 struct LoadedSlice {
8082 /// \brief Helper structure used to compute the cost of a slice.
8084 /// Are we optimizing for code size.
8089 unsigned CrossRegisterBanksCopies;
8093 Cost(bool ForCodeSize = false)
8094 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8095 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8097 /// \brief Get the cost of one isolated slice.
8098 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8099 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8100 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8101 EVT TruncType = LS.Inst->getValueType(0);
8102 EVT LoadedType = LS.getLoadedType();
8103 if (TruncType != LoadedType &&
8104 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8108 /// \brief Account for slicing gain in the current cost.
8109 /// Slicing provide a few gains like removing a shift or a
8110 /// truncate. This method allows to grow the cost of the original
8111 /// load with the gain from this slice.
8112 void addSliceGain(const LoadedSlice &LS) {
8113 // Each slice saves a truncate.
8114 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8115 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8116 LS.Inst->getOperand(0).getValueType()))
8118 // If there is a shift amount, this slice gets rid of it.
8121 // If this slice can merge a cross register bank copy, account for it.
8122 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8123 ++CrossRegisterBanksCopies;
8126 Cost &operator+=(const Cost &RHS) {
8128 Truncates += RHS.Truncates;
8129 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8135 bool operator==(const Cost &RHS) const {
8136 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8137 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8138 ZExts == RHS.ZExts && Shift == RHS.Shift;
8141 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8143 bool operator<(const Cost &RHS) const {
8144 // Assume cross register banks copies are as expensive as loads.
8145 // FIXME: Do we want some more target hooks?
8146 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8147 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8148 // Unless we are optimizing for code size, consider the
8149 // expensive operation first.
8150 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8151 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8152 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8153 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8156 bool operator>(const Cost &RHS) const { return RHS < *this; }
8158 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8160 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8162 // The last instruction that represent the slice. This should be a
8163 // truncate instruction.
8165 // The original load instruction.
8167 // The right shift amount in bits from the original load.
8169 // The DAG from which Origin came from.
8170 // This is used to get some contextual information about legal types, etc.
8173 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8174 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8175 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8177 LoadedSlice(const LoadedSlice &LS)
8178 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8180 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8181 /// \return Result is \p BitWidth and has used bits set to 1 and
8182 /// not used bits set to 0.
8183 APInt getUsedBits() const {
8184 // Reproduce the trunc(lshr) sequence:
8185 // - Start from the truncated value.
8186 // - Zero extend to the desired bit width.
8188 assert(Origin && "No original load to compare against.");
8189 unsigned BitWidth = Origin->getValueSizeInBits(0);
8190 assert(Inst && "This slice is not bound to an instruction");
8191 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8192 "Extracted slice is bigger than the whole type!");
8193 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8194 UsedBits.setAllBits();
8195 UsedBits = UsedBits.zext(BitWidth);
8200 /// \brief Get the size of the slice to be loaded in bytes.
8201 unsigned getLoadedSize() const {
8202 unsigned SliceSize = getUsedBits().countPopulation();
8203 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8204 return SliceSize / 8;
8207 /// \brief Get the type that will be loaded for this slice.
8208 /// Note: This may not be the final type for the slice.
8209 EVT getLoadedType() const {
8210 assert(DAG && "Missing context");
8211 LLVMContext &Ctxt = *DAG->getContext();
8212 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8215 /// \brief Get the alignment of the load used for this slice.
8216 unsigned getAlignment() const {
8217 unsigned Alignment = Origin->getAlignment();
8218 unsigned Offset = getOffsetFromBase();
8220 Alignment = MinAlign(Alignment, Alignment + Offset);
8224 /// \brief Check if this slice can be rewritten with legal operations.
8225 bool isLegal() const {
8226 // An invalid slice is not legal.
8227 if (!Origin || !Inst || !DAG)
8230 // Offsets are for indexed load only, we do not handle that.
8231 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8234 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8236 // Check that the type is legal.
8237 EVT SliceType = getLoadedType();
8238 if (!TLI.isTypeLegal(SliceType))
8241 // Check that the load is legal for this type.
8242 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8245 // Check that the offset can be computed.
8246 // 1. Check its type.
8247 EVT PtrType = Origin->getBasePtr().getValueType();
8248 if (PtrType == MVT::Untyped || PtrType.isExtended())
8251 // 2. Check that it fits in the immediate.
8252 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8255 // 3. Check that the computation is legal.
8256 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8259 // Check that the zext is legal if it needs one.
8260 EVT TruncateType = Inst->getValueType(0);
8261 if (TruncateType != SliceType &&
8262 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8268 /// \brief Get the offset in bytes of this slice in the original chunk of
8270 /// \pre DAG != nullptr.
8271 uint64_t getOffsetFromBase() const {
8272 assert(DAG && "Missing context.");
8274 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8275 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8276 uint64_t Offset = Shift / 8;
8277 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8278 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8279 "The size of the original loaded type is not a multiple of a"
8281 // If Offset is bigger than TySizeInBytes, it means we are loading all
8282 // zeros. This should have been optimized before in the process.
8283 assert(TySizeInBytes > Offset &&
8284 "Invalid shift amount for given loaded size");
8286 Offset = TySizeInBytes - Offset - getLoadedSize();
8290 /// \brief Generate the sequence of instructions to load the slice
8291 /// represented by this object and redirect the uses of this slice to
8292 /// this new sequence of instructions.
8293 /// \pre this->Inst && this->Origin are valid Instructions and this
8294 /// object passed the legal check: LoadedSlice::isLegal returned true.
8295 /// \return The last instruction of the sequence used to load the slice.
8296 SDValue loadSlice() const {
8297 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8298 const SDValue &OldBaseAddr = Origin->getBasePtr();
8299 SDValue BaseAddr = OldBaseAddr;
8300 // Get the offset in that chunk of bytes w.r.t. the endianess.
8301 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8302 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8304 // BaseAddr = BaseAddr + Offset.
8305 EVT ArithType = BaseAddr.getValueType();
8306 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8307 DAG->getConstant(Offset, ArithType));
8310 // Create the type of the loaded slice according to its size.
8311 EVT SliceType = getLoadedType();
8313 // Create the load for the slice.
8314 SDValue LastInst = DAG->getLoad(
8315 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8316 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8317 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8318 // If the final type is not the same as the loaded type, this means that
8319 // we have to pad with zero. Create a zero extend for that.
8320 EVT FinalType = Inst->getValueType(0);
8321 if (SliceType != FinalType)
8323 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8327 /// \brief Check if this slice can be merged with an expensive cross register
8328 /// bank copy. E.g.,
8330 /// f = bitcast i32 i to float
8331 bool canMergeExpensiveCrossRegisterBankCopy() const {
8332 if (!Inst || !Inst->hasOneUse())
8334 SDNode *Use = *Inst->use_begin();
8335 if (Use->getOpcode() != ISD::BITCAST)
8337 assert(DAG && "Missing context");
8338 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8339 EVT ResVT = Use->getValueType(0);
8340 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8341 const TargetRegisterClass *ArgRC =
8342 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8343 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8346 // At this point, we know that we perform a cross-register-bank copy.
8347 // Check if it is expensive.
8348 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8349 // Assume bitcasts are cheap, unless both register classes do not
8350 // explicitly share a common sub class.
8351 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8354 // Check if it will be merged with the load.
8355 // 1. Check the alignment constraint.
8356 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8357 ResVT.getTypeForEVT(*DAG->getContext()));
8359 if (RequiredAlignment > getAlignment())
8362 // 2. Check that the load is a legal operation for that type.
8363 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8366 // 3. Check that we do not have a zext in the way.
8367 if (Inst->getValueType(0) != getLoadedType())
8375 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8376 /// \p UsedBits looks like 0..0 1..1 0..0.
8377 static bool areUsedBitsDense(const APInt &UsedBits) {
8378 // If all the bits are one, this is dense!
8379 if (UsedBits.isAllOnesValue())
8382 // Get rid of the unused bits on the right.
8383 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8384 // Get rid of the unused bits on the left.
8385 if (NarrowedUsedBits.countLeadingZeros())
8386 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8387 // Check that the chunk of bits is completely used.
8388 return NarrowedUsedBits.isAllOnesValue();
8391 /// \brief Check whether or not \p First and \p Second are next to each other
8392 /// in memory. This means that there is no hole between the bits loaded
8393 /// by \p First and the bits loaded by \p Second.
8394 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8395 const LoadedSlice &Second) {
8396 assert(First.Origin == Second.Origin && First.Origin &&
8397 "Unable to match different memory origins.");
8398 APInt UsedBits = First.getUsedBits();
8399 assert((UsedBits & Second.getUsedBits()) == 0 &&
8400 "Slices are not supposed to overlap.");
8401 UsedBits |= Second.getUsedBits();
8402 return areUsedBitsDense(UsedBits);
8405 /// \brief Adjust the \p GlobalLSCost according to the target
8406 /// paring capabilities and the layout of the slices.
8407 /// \pre \p GlobalLSCost should account for at least as many loads as
8408 /// there is in the slices in \p LoadedSlices.
8409 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8410 LoadedSlice::Cost &GlobalLSCost) {
8411 unsigned NumberOfSlices = LoadedSlices.size();
8412 // If there is less than 2 elements, no pairing is possible.
8413 if (NumberOfSlices < 2)
8416 // Sort the slices so that elements that are likely to be next to each
8417 // other in memory are next to each other in the list.
8418 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8419 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8420 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8421 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8423 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8424 // First (resp. Second) is the first (resp. Second) potentially candidate
8425 // to be placed in a paired load.
8426 const LoadedSlice *First = nullptr;
8427 const LoadedSlice *Second = nullptr;
8428 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8429 // Set the beginning of the pair.
8432 Second = &LoadedSlices[CurrSlice];
8434 // If First is NULL, it means we start a new pair.
8435 // Get to the next slice.
8439 EVT LoadedType = First->getLoadedType();
8441 // If the types of the slices are different, we cannot pair them.
8442 if (LoadedType != Second->getLoadedType())
8445 // Check if the target supplies paired loads for this type.
8446 unsigned RequiredAlignment = 0;
8447 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8448 // move to the next pair, this type is hopeless.
8452 // Check if we meet the alignment requirement.
8453 if (RequiredAlignment > First->getAlignment())
8456 // Check that both loads are next to each other in memory.
8457 if (!areSlicesNextToEachOther(*First, *Second))
8460 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8461 --GlobalLSCost.Loads;
8462 // Move to the next pair.
8467 /// \brief Check the profitability of all involved LoadedSlice.
8468 /// Currently, it is considered profitable if there is exactly two
8469 /// involved slices (1) which are (2) next to each other in memory, and
8470 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8472 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8473 /// the elements themselves.
8475 /// FIXME: When the cost model will be mature enough, we can relax
8476 /// constraints (1) and (2).
8477 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8478 const APInt &UsedBits, bool ForCodeSize) {
8479 unsigned NumberOfSlices = LoadedSlices.size();
8480 if (StressLoadSlicing)
8481 return NumberOfSlices > 1;
8484 if (NumberOfSlices != 2)
8488 if (!areUsedBitsDense(UsedBits))
8492 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8493 // The original code has one big load.
8495 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8496 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8497 // Accumulate the cost of all the slices.
8498 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8499 GlobalSlicingCost += SliceCost;
8501 // Account as cost in the original configuration the gain obtained
8502 // with the current slices.
8503 OrigCost.addSliceGain(LS);
8506 // If the target supports paired load, adjust the cost accordingly.
8507 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8508 return OrigCost > GlobalSlicingCost;
8511 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8512 /// operations, split it in the various pieces being extracted.
8514 /// This sort of thing is introduced by SROA.
8515 /// This slicing takes care not to insert overlapping loads.
8516 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8517 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8518 if (Level < AfterLegalizeDAG)
8521 LoadSDNode *LD = cast<LoadSDNode>(N);
8522 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8523 !LD->getValueType(0).isInteger())
8526 // Keep track of already used bits to detect overlapping values.
8527 // In that case, we will just abort the transformation.
8528 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8530 SmallVector<LoadedSlice, 4> LoadedSlices;
8532 // Check if this load is used as several smaller chunks of bits.
8533 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8534 // of computation for each trunc.
8535 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8536 UI != UIEnd; ++UI) {
8537 // Skip the uses of the chain.
8538 if (UI.getUse().getResNo() != 0)
8544 // Check if this is a trunc(lshr).
8545 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8546 isa<ConstantSDNode>(User->getOperand(1))) {
8547 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8548 User = *User->use_begin();
8551 // At this point, User is a Truncate, iff we encountered, trunc or
8553 if (User->getOpcode() != ISD::TRUNCATE)
8556 // The width of the type must be a power of 2 and greater than 8-bits.
8557 // Otherwise the load cannot be represented in LLVM IR.
8558 // Moreover, if we shifted with a non-8-bits multiple, the slice
8559 // will be across several bytes. We do not support that.
8560 unsigned Width = User->getValueSizeInBits(0);
8561 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8564 // Build the slice for this chain of computations.
8565 LoadedSlice LS(User, LD, Shift, &DAG);
8566 APInt CurrentUsedBits = LS.getUsedBits();
8568 // Check if this slice overlaps with another.
8569 if ((CurrentUsedBits & UsedBits) != 0)
8571 // Update the bits used globally.
8572 UsedBits |= CurrentUsedBits;
8574 // Check if the new slice would be legal.
8578 // Record the slice.
8579 LoadedSlices.push_back(LS);
8582 // Abort slicing if it does not seem to be profitable.
8583 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8588 // Rewrite each chain to use an independent load.
8589 // By construction, each chain can be represented by a unique load.
8591 // Prepare the argument for the new token factor for all the slices.
8592 SmallVector<SDValue, 8> ArgChains;
8593 for (SmallVectorImpl<LoadedSlice>::const_iterator
8594 LSIt = LoadedSlices.begin(),
8595 LSItEnd = LoadedSlices.end();
8596 LSIt != LSItEnd; ++LSIt) {
8597 SDValue SliceInst = LSIt->loadSlice();
8598 CombineTo(LSIt->Inst, SliceInst, true);
8599 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8600 SliceInst = SliceInst.getOperand(0);
8601 assert(SliceInst->getOpcode() == ISD::LOAD &&
8602 "It takes more than a zext to get to the loaded slice!!");
8603 ArgChains.push_back(SliceInst.getValue(1));
8606 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8608 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8612 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8613 /// load is having specific bytes cleared out. If so, return the byte size
8614 /// being masked out and the shift amount.
8615 static std::pair<unsigned, unsigned>
8616 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8617 std::pair<unsigned, unsigned> Result(0, 0);
8619 // Check for the structure we're looking for.
8620 if (V->getOpcode() != ISD::AND ||
8621 !isa<ConstantSDNode>(V->getOperand(1)) ||
8622 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8625 // Check the chain and pointer.
8626 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8627 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
8629 // The store should be chained directly to the load or be an operand of a
8631 if (LD == Chain.getNode())
8633 else if (Chain->getOpcode() != ISD::TokenFactor)
8634 return Result; // Fail.
8637 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8638 if (Chain->getOperand(i).getNode() == LD) {
8642 if (!isOk) return Result;
8645 // This only handles simple types.
8646 if (V.getValueType() != MVT::i16 &&
8647 V.getValueType() != MVT::i32 &&
8648 V.getValueType() != MVT::i64)
8651 // Check the constant mask. Invert it so that the bits being masked out are
8652 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8653 // follow the sign bit for uniformity.
8654 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8655 unsigned NotMaskLZ = countLeadingZeros(NotMask);
8656 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
8657 unsigned NotMaskTZ = countTrailingZeros(NotMask);
8658 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8659 if (NotMaskLZ == 64) return Result; // All zero mask.
8661 // See if we have a continuous run of bits. If so, we have 0*1+0*
8662 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8665 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8666 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8667 NotMaskLZ -= 64-V.getValueSizeInBits();
8669 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8670 switch (MaskedBytes) {
8674 default: return Result; // All one mask, or 5-byte mask.
8677 // Verify that the first bit starts at a multiple of mask so that the access
8678 // is aligned the same as the access width.
8679 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8681 Result.first = MaskedBytes;
8682 Result.second = NotMaskTZ/8;
8687 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8688 /// provides a value as specified by MaskInfo. If so, replace the specified
8689 /// store with a narrower store of truncated IVal.
8691 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8692 SDValue IVal, StoreSDNode *St,
8694 unsigned NumBytes = MaskInfo.first;
8695 unsigned ByteShift = MaskInfo.second;
8696 SelectionDAG &DAG = DC->getDAG();
8698 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8699 // that uses this. If not, this is not a replacement.
8700 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8701 ByteShift*8, (ByteShift+NumBytes)*8);
8702 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8704 // Check that it is legal on the target to do this. It is legal if the new
8705 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8707 MVT VT = MVT::getIntegerVT(NumBytes*8);
8708 if (!DC->isTypeLegal(VT))
8711 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8712 // shifted by ByteShift and truncated down to NumBytes.
8714 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8715 DAG.getConstant(ByteShift*8,
8716 DC->getShiftAmountTy(IVal.getValueType())));
8718 // Figure out the offset for the store and the alignment of the access.
8720 unsigned NewAlign = St->getAlignment();
8722 if (DAG.getTargetLoweringInfo().isLittleEndian())
8723 StOffset = ByteShift;
8725 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8727 SDValue Ptr = St->getBasePtr();
8729 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8730 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8731 NewAlign = MinAlign(NewAlign, StOffset);
8734 // Truncate down to the new size.
8735 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8738 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8739 St->getPointerInfo().getWithOffset(StOffset),
8740 false, false, NewAlign).getNode();
8744 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8745 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8746 /// of the loaded bits, try narrowing the load and store if it would end up
8747 /// being a win for performance or code size.
8748 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8749 StoreSDNode *ST = cast<StoreSDNode>(N);
8750 if (ST->isVolatile())
8753 SDValue Chain = ST->getChain();
8754 SDValue Value = ST->getValue();
8755 SDValue Ptr = ST->getBasePtr();
8756 EVT VT = Value.getValueType();
8758 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8761 unsigned Opc = Value.getOpcode();
8763 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8764 // is a byte mask indicating a consecutive number of bytes, check to see if
8765 // Y is known to provide just those bytes. If so, we try to replace the
8766 // load + replace + store sequence with a single (narrower) store, which makes
8768 if (Opc == ISD::OR) {
8769 std::pair<unsigned, unsigned> MaskedLoad;
8770 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8771 if (MaskedLoad.first)
8772 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8773 Value.getOperand(1), ST,this))
8774 return SDValue(NewST, 0);
8776 // Or is commutative, so try swapping X and Y.
8777 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8778 if (MaskedLoad.first)
8779 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8780 Value.getOperand(0), ST,this))
8781 return SDValue(NewST, 0);
8784 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8785 Value.getOperand(1).getOpcode() != ISD::Constant)
8788 SDValue N0 = Value.getOperand(0);
8789 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8790 Chain == SDValue(N0.getNode(), 1)) {
8791 LoadSDNode *LD = cast<LoadSDNode>(N0);
8792 if (LD->getBasePtr() != Ptr ||
8793 LD->getPointerInfo().getAddrSpace() !=
8794 ST->getPointerInfo().getAddrSpace())
8797 // Find the type to narrow it the load / op / store to.
8798 SDValue N1 = Value.getOperand(1);
8799 unsigned BitWidth = N1.getValueSizeInBits();
8800 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8801 if (Opc == ISD::AND)
8802 Imm ^= APInt::getAllOnesValue(BitWidth);
8803 if (Imm == 0 || Imm.isAllOnesValue())
8805 unsigned ShAmt = Imm.countTrailingZeros();
8806 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8807 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8808 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8809 while (NewBW < BitWidth &&
8810 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8811 TLI.isNarrowingProfitable(VT, NewVT))) {
8812 NewBW = NextPowerOf2(NewBW);
8813 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8815 if (NewBW >= BitWidth)
8818 // If the lsb changed does not start at the type bitwidth boundary,
8819 // start at the previous one.
8821 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8822 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8823 std::min(BitWidth, ShAmt + NewBW));
8824 if ((Imm & Mask) == Imm) {
8825 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8826 if (Opc == ISD::AND)
8827 NewImm ^= APInt::getAllOnesValue(NewBW);
8828 uint64_t PtrOff = ShAmt / 8;
8829 // For big endian targets, we need to adjust the offset to the pointer to
8830 // load the correct bytes.
8831 if (TLI.isBigEndian())
8832 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8834 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8835 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8836 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8839 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8840 Ptr.getValueType(), Ptr,
8841 DAG.getConstant(PtrOff, Ptr.getValueType()));
8842 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8843 LD->getChain(), NewPtr,
8844 LD->getPointerInfo().getWithOffset(PtrOff),
8845 LD->isVolatile(), LD->isNonTemporal(),
8846 LD->isInvariant(), NewAlign,
8848 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8849 DAG.getConstant(NewImm, NewVT));
8850 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8852 ST->getPointerInfo().getWithOffset(PtrOff),
8853 false, false, NewAlign);
8855 AddToWorkList(NewPtr.getNode());
8856 AddToWorkList(NewLD.getNode());
8857 AddToWorkList(NewVal.getNode());
8858 WorkListRemover DeadNodes(*this);
8859 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8868 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8869 /// if the load value isn't used by any other operations, then consider
8870 /// transforming the pair to integer load / store operations if the target
8871 /// deems the transformation profitable.
8872 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8873 StoreSDNode *ST = cast<StoreSDNode>(N);
8874 SDValue Chain = ST->getChain();
8875 SDValue Value = ST->getValue();
8876 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8877 Value.hasOneUse() &&
8878 Chain == SDValue(Value.getNode(), 1)) {
8879 LoadSDNode *LD = cast<LoadSDNode>(Value);
8880 EVT VT = LD->getMemoryVT();
8881 if (!VT.isFloatingPoint() ||
8882 VT != ST->getMemoryVT() ||
8883 LD->isNonTemporal() ||
8884 ST->isNonTemporal() ||
8885 LD->getPointerInfo().getAddrSpace() != 0 ||
8886 ST->getPointerInfo().getAddrSpace() != 0)
8889 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8890 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8891 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8892 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8893 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8896 unsigned LDAlign = LD->getAlignment();
8897 unsigned STAlign = ST->getAlignment();
8898 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8899 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8900 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8903 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8904 LD->getChain(), LD->getBasePtr(),
8905 LD->getPointerInfo(),
8906 false, false, false, LDAlign);
8908 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8909 NewLD, ST->getBasePtr(),
8910 ST->getPointerInfo(),
8911 false, false, STAlign);
8913 AddToWorkList(NewLD.getNode());
8914 AddToWorkList(NewST.getNode());
8915 WorkListRemover DeadNodes(*this);
8916 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8924 /// Helper struct to parse and store a memory address as base + index + offset.
8925 /// We ignore sign extensions when it is safe to do so.
8926 /// The following two expressions are not equivalent. To differentiate we need
8927 /// to store whether there was a sign extension involved in the index
8929 /// (load (i64 add (i64 copyfromreg %c)
8930 /// (i64 signextend (add (i8 load %index)
8934 /// (load (i64 add (i64 copyfromreg %c)
8935 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8937 struct BaseIndexOffset {
8941 bool IsIndexSignExt;
8943 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8945 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8946 bool IsIndexSignExt) :
8947 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8949 bool equalBaseIndex(const BaseIndexOffset &Other) {
8950 return Other.Base == Base && Other.Index == Index &&
8951 Other.IsIndexSignExt == IsIndexSignExt;
8954 /// Parses tree in Ptr for base, index, offset addresses.
8955 static BaseIndexOffset match(SDValue Ptr) {
8956 bool IsIndexSignExt = false;
8958 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8959 // instruction, then it could be just the BASE or everything else we don't
8960 // know how to handle. Just use Ptr as BASE and give up.
8961 if (Ptr->getOpcode() != ISD::ADD)
8962 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8964 // We know that we have at least an ADD instruction. Try to pattern match
8965 // the simple case of BASE + OFFSET.
8966 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8967 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8968 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8972 // Inside a loop the current BASE pointer is calculated using an ADD and a
8973 // MUL instruction. In this case Ptr is the actual BASE pointer.
8974 // (i64 add (i64 %array_ptr)
8975 // (i64 mul (i64 %induction_var)
8976 // (i64 %element_size)))
8977 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8978 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8980 // Look at Base + Index + Offset cases.
8981 SDValue Base = Ptr->getOperand(0);
8982 SDValue IndexOffset = Ptr->getOperand(1);
8984 // Skip signextends.
8985 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8986 IndexOffset = IndexOffset->getOperand(0);
8987 IsIndexSignExt = true;
8990 // Either the case of Base + Index (no offset) or something else.
8991 if (IndexOffset->getOpcode() != ISD::ADD)
8992 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8994 // Now we have the case of Base + Index + offset.
8995 SDValue Index = IndexOffset->getOperand(0);
8996 SDValue Offset = IndexOffset->getOperand(1);
8998 if (!isa<ConstantSDNode>(Offset))
8999 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9001 // Ignore signextends.
9002 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9003 Index = Index->getOperand(0);
9004 IsIndexSignExt = true;
9005 } else IsIndexSignExt = false;
9007 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9008 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9012 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9013 /// is located in a sequence of memory operations connected by a chain.
9015 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9016 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9017 // Ptr to the mem node.
9018 LSBaseSDNode *MemNode;
9019 // Offset from the base ptr.
9020 int64_t OffsetFromBase;
9021 // What is the sequence number of this mem node.
9022 // Lowest mem operand in the DAG starts at zero.
9023 unsigned SequenceNum;
9026 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9027 EVT MemVT = St->getMemoryVT();
9028 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9029 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9030 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9032 // Don't merge vectors into wider inputs.
9033 if (MemVT.isVector() || !MemVT.isSimple())
9036 // Perform an early exit check. Do not bother looking at stored values that
9037 // are not constants or loads.
9038 SDValue StoredVal = St->getValue();
9039 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9040 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9044 // Only look at ends of store sequences.
9045 SDValue Chain = SDValue(St, 1);
9046 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9049 // This holds the base pointer, index, and the offset in bytes from the base
9051 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9053 // We must have a base and an offset.
9054 if (!BasePtr.Base.getNode())
9057 // Do not handle stores to undef base pointers.
9058 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9061 // Save the LoadSDNodes that we find in the chain.
9062 // We need to make sure that these nodes do not interfere with
9063 // any of the store nodes.
9064 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9066 // Save the StoreSDNodes that we find in the chain.
9067 SmallVector<MemOpLink, 8> StoreNodes;
9069 // Walk up the chain and look for nodes with offsets from the same
9070 // base pointer. Stop when reaching an instruction with a different kind
9071 // or instruction which has a different base pointer.
9073 StoreSDNode *Index = St;
9075 // If the chain has more than one use, then we can't reorder the mem ops.
9076 if (Index != St && !SDValue(Index, 1)->hasOneUse())
9079 // Find the base pointer and offset for this memory node.
9080 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9082 // Check that the base pointer is the same as the original one.
9083 if (!Ptr.equalBaseIndex(BasePtr))
9086 // Check that the alignment is the same.
9087 if (Index->getAlignment() != St->getAlignment())
9090 // The memory operands must not be volatile.
9091 if (Index->isVolatile() || Index->isIndexed())
9095 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9096 if (St->isTruncatingStore())
9099 // The stored memory type must be the same.
9100 if (Index->getMemoryVT() != MemVT)
9103 // We do not allow unaligned stores because we want to prevent overriding
9105 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9108 // We found a potential memory operand to merge.
9109 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9111 // Find the next memory operand in the chain. If the next operand in the
9112 // chain is a store then move up and continue the scan with the next
9113 // memory operand. If the next operand is a load save it and use alias
9114 // information to check if it interferes with anything.
9115 SDNode *NextInChain = Index->getChain().getNode();
9117 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9118 // We found a store node. Use it for the next iteration.
9121 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9122 if (Ldn->isVolatile()) {
9127 // Save the load node for later. Continue the scan.
9128 AliasLoadNodes.push_back(Ldn);
9129 NextInChain = Ldn->getChain().getNode();
9138 // Check if there is anything to merge.
9139 if (StoreNodes.size() < 2)
9142 // Sort the memory operands according to their distance from the base pointer.
9143 std::sort(StoreNodes.begin(), StoreNodes.end(),
9144 [](MemOpLink LHS, MemOpLink RHS) {
9145 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9146 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9147 LHS.SequenceNum > RHS.SequenceNum);
9150 // Scan the memory operations on the chain and find the first non-consecutive
9151 // store memory address.
9152 unsigned LastConsecutiveStore = 0;
9153 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9154 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9156 // Check that the addresses are consecutive starting from the second
9157 // element in the list of stores.
9159 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9160 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9165 // Check if this store interferes with any of the loads that we found.
9166 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9167 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9171 // We found a load that alias with this store. Stop the sequence.
9175 // Mark this node as useful.
9176 LastConsecutiveStore = i;
9179 // The node with the lowest store address.
9180 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9182 // Store the constants into memory as one consecutive store.
9184 unsigned LastLegalType = 0;
9185 unsigned LastLegalVectorType = 0;
9186 bool NonZero = false;
9187 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9188 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9189 SDValue StoredVal = St->getValue();
9191 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9192 NonZero |= !C->isNullValue();
9193 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9194 NonZero |= !C->getConstantFPValue()->isNullValue();
9200 // Find a legal type for the constant store.
9201 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9202 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9203 if (TLI.isTypeLegal(StoreTy))
9204 LastLegalType = i+1;
9205 // Or check whether a truncstore is legal.
9206 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9207 TargetLowering::TypePromoteInteger) {
9208 EVT LegalizedStoredValueTy =
9209 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9210 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9211 LastLegalType = i+1;
9214 // Find a legal type for the vector store.
9215 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9216 if (TLI.isTypeLegal(Ty))
9217 LastLegalVectorType = i + 1;
9220 // We only use vectors if the constant is known to be zero and the
9221 // function is not marked with the noimplicitfloat attribute.
9222 if (NonZero || NoVectors)
9223 LastLegalVectorType = 0;
9225 // Check if we found a legal integer type to store.
9226 if (LastLegalType == 0 && LastLegalVectorType == 0)
9229 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9230 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9232 // Make sure we have something to merge.
9236 unsigned EarliestNodeUsed = 0;
9237 for (unsigned i=0; i < NumElem; ++i) {
9238 // Find a chain for the new wide-store operand. Notice that some
9239 // of the store nodes that we found may not be selected for inclusion
9240 // in the wide store. The chain we use needs to be the chain of the
9241 // earliest store node which is *used* and replaced by the wide store.
9242 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9243 EarliestNodeUsed = i;
9246 // The earliest Node in the DAG.
9247 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9248 SDLoc DL(StoreNodes[0].MemNode);
9252 // Find a legal type for the vector store.
9253 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9254 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9255 StoredVal = DAG.getConstant(0, Ty);
9257 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9258 APInt StoreInt(StoreBW, 0);
9260 // Construct a single integer constant which is made of the smaller
9262 bool IsLE = TLI.isLittleEndian();
9263 for (unsigned i = 0; i < NumElem ; ++i) {
9264 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9265 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9266 SDValue Val = St->getValue();
9267 StoreInt<<=ElementSizeBytes*8;
9268 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9269 StoreInt|=C->getAPIntValue().zext(StoreBW);
9270 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9271 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9273 assert(false && "Invalid constant element type");
9277 // Create the new Load and Store operations.
9278 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9279 StoredVal = DAG.getConstant(StoreInt, StoreTy);
9282 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9283 FirstInChain->getBasePtr(),
9284 FirstInChain->getPointerInfo(),
9286 FirstInChain->getAlignment());
9288 // Replace the first store with the new store
9289 CombineTo(EarliestOp, NewStore);
9290 // Erase all other stores.
9291 for (unsigned i = 0; i < NumElem ; ++i) {
9292 if (StoreNodes[i].MemNode == EarliestOp)
9294 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9295 // ReplaceAllUsesWith will replace all uses that existed when it was
9296 // called, but graph optimizations may cause new ones to appear. For
9297 // example, the case in pr14333 looks like
9299 // St's chain -> St -> another store -> X
9301 // And the only difference from St to the other store is the chain.
9302 // When we change it's chain to be St's chain they become identical,
9303 // get CSEed and the net result is that X is now a use of St.
9304 // Since we know that St is redundant, just iterate.
9305 while (!St->use_empty())
9306 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9307 removeFromWorkList(St);
9314 // Below we handle the case of multiple consecutive stores that
9315 // come from multiple consecutive loads. We merge them into a single
9316 // wide load and a single wide store.
9318 // Look for load nodes which are used by the stored values.
9319 SmallVector<MemOpLink, 8> LoadNodes;
9321 // Find acceptable loads. Loads need to have the same chain (token factor),
9322 // must not be zext, volatile, indexed, and they must be consecutive.
9323 BaseIndexOffset LdBasePtr;
9324 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9325 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9326 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9329 // Loads must only have one use.
9330 if (!Ld->hasNUsesOfValue(1, 0))
9333 // Check that the alignment is the same as the stores.
9334 if (Ld->getAlignment() != St->getAlignment())
9337 // The memory operands must not be volatile.
9338 if (Ld->isVolatile() || Ld->isIndexed())
9341 // We do not accept ext loads.
9342 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9345 // The stored memory type must be the same.
9346 if (Ld->getMemoryVT() != MemVT)
9349 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9350 // If this is not the first ptr that we check.
9351 if (LdBasePtr.Base.getNode()) {
9352 // The base ptr must be the same.
9353 if (!LdPtr.equalBaseIndex(LdBasePtr))
9356 // Check that all other base pointers are the same as this one.
9360 // We found a potential memory operand to merge.
9361 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9364 if (LoadNodes.size() < 2)
9367 // Scan the memory operations on the chain and find the first non-consecutive
9368 // load memory address. These variables hold the index in the store node
9370 unsigned LastConsecutiveLoad = 0;
9371 // This variable refers to the size and not index in the array.
9372 unsigned LastLegalVectorType = 0;
9373 unsigned LastLegalIntegerType = 0;
9374 StartAddress = LoadNodes[0].OffsetFromBase;
9375 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9376 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9377 // All loads much share the same chain.
9378 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9381 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9382 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9384 LastConsecutiveLoad = i;
9386 // Find a legal type for the vector store.
9387 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9388 if (TLI.isTypeLegal(StoreTy))
9389 LastLegalVectorType = i + 1;
9391 // Find a legal type for the integer store.
9392 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9393 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9394 if (TLI.isTypeLegal(StoreTy))
9395 LastLegalIntegerType = i + 1;
9396 // Or check whether a truncstore and extload is legal.
9397 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9398 TargetLowering::TypePromoteInteger) {
9399 EVT LegalizedStoredValueTy =
9400 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9401 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9402 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9403 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9404 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9405 LastLegalIntegerType = i+1;
9409 // Only use vector types if the vector type is larger than the integer type.
9410 // If they are the same, use integers.
9411 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9412 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9414 // We add +1 here because the LastXXX variables refer to location while
9415 // the NumElem refers to array/index size.
9416 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9417 NumElem = std::min(LastLegalType, NumElem);
9422 // The earliest Node in the DAG.
9423 unsigned EarliestNodeUsed = 0;
9424 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9425 for (unsigned i=1; i<NumElem; ++i) {
9426 // Find a chain for the new wide-store operand. Notice that some
9427 // of the store nodes that we found may not be selected for inclusion
9428 // in the wide store. The chain we use needs to be the chain of the
9429 // earliest store node which is *used* and replaced by the wide store.
9430 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9431 EarliestNodeUsed = i;
9434 // Find if it is better to use vectors or integers to load and store
9438 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9440 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9441 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9444 SDLoc LoadDL(LoadNodes[0].MemNode);
9445 SDLoc StoreDL(StoreNodes[0].MemNode);
9447 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9448 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9449 FirstLoad->getChain(),
9450 FirstLoad->getBasePtr(),
9451 FirstLoad->getPointerInfo(),
9452 false, false, false,
9453 FirstLoad->getAlignment());
9455 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9456 FirstInChain->getBasePtr(),
9457 FirstInChain->getPointerInfo(), false, false,
9458 FirstInChain->getAlignment());
9460 // Replace one of the loads with the new load.
9461 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9462 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9463 SDValue(NewLoad.getNode(), 1));
9465 // Remove the rest of the load chains.
9466 for (unsigned i = 1; i < NumElem ; ++i) {
9467 // Replace all chain users of the old load nodes with the chain of the new
9469 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9470 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9473 // Replace the first store with the new store.
9474 CombineTo(EarliestOp, NewStore);
9475 // Erase all other stores.
9476 for (unsigned i = 0; i < NumElem ; ++i) {
9477 // Remove all Store nodes.
9478 if (StoreNodes[i].MemNode == EarliestOp)
9480 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9481 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9482 removeFromWorkList(St);
9489 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9490 StoreSDNode *ST = cast<StoreSDNode>(N);
9491 SDValue Chain = ST->getChain();
9492 SDValue Value = ST->getValue();
9493 SDValue Ptr = ST->getBasePtr();
9495 // If this is a store of a bit convert, store the input value if the
9496 // resultant store does not need a higher alignment than the original.
9497 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9498 ST->isUnindexed()) {
9499 unsigned OrigAlign = ST->getAlignment();
9500 EVT SVT = Value.getOperand(0).getValueType();
9501 unsigned Align = TLI.getDataLayout()->
9502 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9503 if (Align <= OrigAlign &&
9504 ((!LegalOperations && !ST->isVolatile()) ||
9505 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9506 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9507 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9508 ST->isNonTemporal(), OrigAlign,
9512 // Turn 'store undef, Ptr' -> nothing.
9513 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9516 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9517 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9518 // NOTE: If the original store is volatile, this transform must not increase
9519 // the number of stores. For example, on x86-32 an f64 can be stored in one
9520 // processor operation but an i64 (which is not legal) requires two. So the
9521 // transform should not be done in this case.
9522 if (Value.getOpcode() != ISD::TargetConstantFP) {
9524 switch (CFP->getSimpleValueType(0).SimpleTy) {
9525 default: llvm_unreachable("Unknown FP type");
9526 case MVT::f16: // We don't do this for these yet.
9532 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9533 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9534 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9535 bitcastToAPInt().getZExtValue(), MVT::i32);
9536 return DAG.getStore(Chain, SDLoc(N), Tmp,
9537 Ptr, ST->getMemOperand());
9541 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9542 !ST->isVolatile()) ||
9543 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9544 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9545 getZExtValue(), MVT::i64);
9546 return DAG.getStore(Chain, SDLoc(N), Tmp,
9547 Ptr, ST->getMemOperand());
9550 if (!ST->isVolatile() &&
9551 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9552 // Many FP stores are not made apparent until after legalize, e.g. for
9553 // argument passing. Since this is so common, custom legalize the
9554 // 64-bit integer store into two 32-bit stores.
9555 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9556 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9557 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9558 if (TLI.isBigEndian()) std::swap(Lo, Hi);
9560 unsigned Alignment = ST->getAlignment();
9561 bool isVolatile = ST->isVolatile();
9562 bool isNonTemporal = ST->isNonTemporal();
9563 const MDNode *TBAAInfo = ST->getTBAAInfo();
9565 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9566 Ptr, ST->getPointerInfo(),
9567 isVolatile, isNonTemporal,
9568 ST->getAlignment(), TBAAInfo);
9569 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9570 DAG.getConstant(4, Ptr.getValueType()));
9571 Alignment = MinAlign(Alignment, 4U);
9572 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9573 Ptr, ST->getPointerInfo().getWithOffset(4),
9574 isVolatile, isNonTemporal,
9575 Alignment, TBAAInfo);
9576 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9585 // Try to infer better alignment information than the store already has.
9586 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9587 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9588 if (Align > ST->getAlignment())
9589 return DAG.getTruncStore(Chain, SDLoc(N), Value,
9590 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9591 ST->isVolatile(), ST->isNonTemporal(), Align,
9596 // Try transforming a pair floating point load / store ops to integer
9597 // load / store ops.
9598 SDValue NewST = TransformFPLoadStorePair(N);
9599 if (NewST.getNode())
9602 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9603 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9605 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9606 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9609 if (UseAA && ST->isUnindexed()) {
9610 // Walk up chain skipping non-aliasing memory nodes.
9611 SDValue BetterChain = FindBetterChain(N, Chain);
9613 // If there is a better chain.
9614 if (Chain != BetterChain) {
9617 // Replace the chain to avoid dependency.
9618 if (ST->isTruncatingStore()) {
9619 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9620 ST->getMemoryVT(), ST->getMemOperand());
9622 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9623 ST->getMemOperand());
9626 // Create token to keep both nodes around.
9627 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9628 MVT::Other, Chain, ReplStore);
9630 // Make sure the new and old chains are cleaned up.
9631 AddToWorkList(Token.getNode());
9633 // Don't add users to work list.
9634 return CombineTo(N, Token, false);
9638 // Try transforming N to an indexed store.
9639 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9640 return SDValue(N, 0);
9642 // FIXME: is there such a thing as a truncating indexed store?
9643 if (ST->isTruncatingStore() && ST->isUnindexed() &&
9644 Value.getValueType().isInteger()) {
9645 // See if we can simplify the input to this truncstore with knowledge that
9646 // only the low bits are being used. For example:
9647 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
9649 GetDemandedBits(Value,
9650 APInt::getLowBitsSet(
9651 Value.getValueType().getScalarType().getSizeInBits(),
9652 ST->getMemoryVT().getScalarType().getSizeInBits()));
9653 AddToWorkList(Value.getNode());
9654 if (Shorter.getNode())
9655 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9656 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9658 // Otherwise, see if we can simplify the operation with
9659 // SimplifyDemandedBits, which only works if the value has a single use.
9660 if (SimplifyDemandedBits(Value,
9661 APInt::getLowBitsSet(
9662 Value.getValueType().getScalarType().getSizeInBits(),
9663 ST->getMemoryVT().getScalarType().getSizeInBits())))
9664 return SDValue(N, 0);
9667 // If this is a load followed by a store to the same location, then the store
9669 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9670 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9671 ST->isUnindexed() && !ST->isVolatile() &&
9672 // There can't be any side effects between the load and store, such as
9674 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9675 // The store is dead, remove it.
9680 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9681 // truncating store. We can do this even if this is already a truncstore.
9682 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9683 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9684 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9685 ST->getMemoryVT())) {
9686 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9687 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9690 // Only perform this optimization before the types are legal, because we
9691 // don't want to perform this optimization on every DAGCombine invocation.
9693 bool EverChanged = false;
9696 // There can be multiple store sequences on the same chain.
9697 // Keep trying to merge store sequences until we are unable to do so
9698 // or until we merge the last store on the chain.
9699 bool Changed = MergeConsecutiveStores(ST);
9700 EverChanged |= Changed;
9701 if (!Changed) break;
9702 } while (ST->getOpcode() != ISD::DELETED_NODE);
9705 return SDValue(N, 0);
9708 return ReduceLoadOpStoreWidth(N);
9711 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9712 SDValue InVec = N->getOperand(0);
9713 SDValue InVal = N->getOperand(1);
9714 SDValue EltNo = N->getOperand(2);
9717 // If the inserted element is an UNDEF, just use the input vector.
9718 if (InVal.getOpcode() == ISD::UNDEF)
9721 EVT VT = InVec.getValueType();
9723 // If we can't generate a legal BUILD_VECTOR, exit
9724 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9727 // Check that we know which element is being inserted
9728 if (!isa<ConstantSDNode>(EltNo))
9730 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9732 // Canonicalize insert_vector_elt dag nodes.
9734 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9735 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9737 // Do this only if the child insert_vector node has one use; also
9738 // do this only if indices are both constants and Idx1 < Idx0.
9739 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9740 && isa<ConstantSDNode>(InVec.getOperand(2))) {
9742 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9743 if (Elt < OtherElt) {
9745 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9746 InVec.getOperand(0), InVal, EltNo);
9747 AddToWorkList(NewOp.getNode());
9748 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9749 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9753 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9754 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9756 SmallVector<SDValue, 8> Ops;
9757 // Do not combine these two vectors if the output vector will not replace
9758 // the input vector.
9759 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9760 Ops.append(InVec.getNode()->op_begin(),
9761 InVec.getNode()->op_end());
9762 } else if (InVec.getOpcode() == ISD::UNDEF) {
9763 unsigned NElts = VT.getVectorNumElements();
9764 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9769 // Insert the element
9770 if (Elt < Ops.size()) {
9771 // All the operands of BUILD_VECTOR must have the same type;
9772 // we enforce that here.
9773 EVT OpVT = Ops[0].getValueType();
9774 if (InVal.getValueType() != OpVT)
9775 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9776 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9777 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9781 // Return the new vector
9782 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
9785 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9786 // (vextract (scalar_to_vector val, 0) -> val
9787 SDValue InVec = N->getOperand(0);
9788 EVT VT = InVec.getValueType();
9789 EVT NVT = N->getValueType(0);
9791 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9792 // Check if the result type doesn't match the inserted element type. A
9793 // SCALAR_TO_VECTOR may truncate the inserted element and the
9794 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9795 SDValue InOp = InVec.getOperand(0);
9796 if (InOp.getValueType() != NVT) {
9797 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9798 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9803 SDValue EltNo = N->getOperand(1);
9804 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9806 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9807 // We only perform this optimization before the op legalization phase because
9808 // we may introduce new vector instructions which are not backed by TD
9809 // patterns. For example on AVX, extracting elements from a wide vector
9810 // without using extract_subvector. However, if we can find an underlying
9811 // scalar value, then we can always use that.
9812 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9814 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9815 int NumElem = VT.getVectorNumElements();
9816 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9817 // Find the new index to extract from.
9818 int OrigElt = SVOp->getMaskElt(Elt);
9820 // Extracting an undef index is undef.
9822 return DAG.getUNDEF(NVT);
9824 // Select the right vector half to extract from.
9826 if (OrigElt < NumElem) {
9827 SVInVec = InVec->getOperand(0);
9829 SVInVec = InVec->getOperand(1);
9833 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9834 SDValue InOp = SVInVec.getOperand(OrigElt);
9835 if (InOp.getValueType() != NVT) {
9836 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9837 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9843 // FIXME: We should handle recursing on other vector shuffles and
9844 // scalar_to_vector here as well.
9846 if (!LegalOperations) {
9847 EVT IndexTy = TLI.getVectorIdxTy();
9848 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9849 SVInVec, DAG.getConstant(OrigElt, IndexTy));
9853 // Perform only after legalization to ensure build_vector / vector_shuffle
9854 // optimizations have already been done.
9855 if (!LegalOperations) return SDValue();
9857 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9858 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9859 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9862 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9863 bool NewLoad = false;
9864 bool BCNumEltsChanged = false;
9865 EVT ExtVT = VT.getVectorElementType();
9868 // If the result of load has to be truncated, then it's not necessarily
9870 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9873 if (InVec.getOpcode() == ISD::BITCAST) {
9874 // Don't duplicate a load with other uses.
9875 if (!InVec.hasOneUse())
9878 EVT BCVT = InVec.getOperand(0).getValueType();
9879 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9881 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9882 BCNumEltsChanged = true;
9883 InVec = InVec.getOperand(0);
9884 ExtVT = BCVT.getVectorElementType();
9888 LoadSDNode *LN0 = nullptr;
9889 const ShuffleVectorSDNode *SVN = nullptr;
9890 if (ISD::isNormalLoad(InVec.getNode())) {
9891 LN0 = cast<LoadSDNode>(InVec);
9892 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9893 InVec.getOperand(0).getValueType() == ExtVT &&
9894 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9895 // Don't duplicate a load with other uses.
9896 if (!InVec.hasOneUse())
9899 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9900 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9901 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9903 // (load $addr+1*size)
9905 // Don't duplicate a load with other uses.
9906 if (!InVec.hasOneUse())
9909 // If the bit convert changed the number of elements, it is unsafe
9910 // to examine the mask.
9911 if (BCNumEltsChanged)
9914 // Select the input vector, guarding against out of range extract vector.
9915 unsigned NumElems = VT.getVectorNumElements();
9916 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9917 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9919 if (InVec.getOpcode() == ISD::BITCAST) {
9920 // Don't duplicate a load with other uses.
9921 if (!InVec.hasOneUse())
9924 InVec = InVec.getOperand(0);
9926 if (ISD::isNormalLoad(InVec.getNode())) {
9927 LN0 = cast<LoadSDNode>(InVec);
9928 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9932 // Make sure we found a non-volatile load and the extractelement is
9934 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9937 // If Idx was -1 above, Elt is going to be -1, so just return undef.
9939 return DAG.getUNDEF(LVT);
9941 unsigned Align = LN0->getAlignment();
9943 // Check the resultant load doesn't need a higher alignment than the
9947 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9949 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9955 SDValue NewPtr = LN0->getBasePtr();
9956 unsigned PtrOff = 0;
9959 PtrOff = LVT.getSizeInBits() * Elt / 8;
9960 EVT PtrType = NewPtr.getValueType();
9961 if (TLI.isBigEndian())
9962 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9963 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9964 DAG.getConstant(PtrOff, PtrType));
9967 // The replacement we need to do here is a little tricky: we need to
9968 // replace an extractelement of a load with a load.
9969 // Use ReplaceAllUsesOfValuesWith to do the replacement.
9970 // Note that this replacement assumes that the extractvalue is the only
9971 // use of the load; that's okay because we don't want to perform this
9972 // transformation in other cases anyway.
9975 if (NVT.bitsGT(LVT)) {
9976 // If the result type of vextract is wider than the load, then issue an
9977 // extending load instead.
9978 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9979 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9980 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9981 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9982 LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9983 Align, LN0->getTBAAInfo());
9984 Chain = Load.getValue(1);
9986 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9987 LN0->getPointerInfo().getWithOffset(PtrOff),
9988 LN0->isVolatile(), LN0->isNonTemporal(),
9989 LN0->isInvariant(), Align, LN0->getTBAAInfo());
9990 Chain = Load.getValue(1);
9991 if (NVT.bitsLT(LVT))
9992 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
9994 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
9996 WorkListRemover DeadNodes(*this);
9997 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
9998 SDValue To[] = { Load, Chain };
9999 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10000 // Since we're explcitly calling ReplaceAllUses, add the new node to the
10001 // worklist explicitly as well.
10002 AddToWorkList(Load.getNode());
10003 AddUsersToWorkList(Load.getNode()); // Add users too
10004 // Make sure to revisit this node to clean it up; it will usually be dead.
10006 return SDValue(N, 0);
10012 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10013 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10014 // We perform this optimization post type-legalization because
10015 // the type-legalizer often scalarizes integer-promoted vectors.
10016 // Performing this optimization before may create bit-casts which
10017 // will be type-legalized to complex code sequences.
10018 // We perform this optimization only before the operation legalizer because we
10019 // may introduce illegal operations.
10020 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10023 unsigned NumInScalars = N->getNumOperands();
10025 EVT VT = N->getValueType(0);
10027 // Check to see if this is a BUILD_VECTOR of a bunch of values
10028 // which come from any_extend or zero_extend nodes. If so, we can create
10029 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10030 // optimizations. We do not handle sign-extend because we can't fill the sign
10032 EVT SourceType = MVT::Other;
10033 bool AllAnyExt = true;
10035 for (unsigned i = 0; i != NumInScalars; ++i) {
10036 SDValue In = N->getOperand(i);
10037 // Ignore undef inputs.
10038 if (In.getOpcode() == ISD::UNDEF) continue;
10040 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
10041 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10043 // Abort if the element is not an extension.
10044 if (!ZeroExt && !AnyExt) {
10045 SourceType = MVT::Other;
10049 // The input is a ZeroExt or AnyExt. Check the original type.
10050 EVT InTy = In.getOperand(0).getValueType();
10052 // Check that all of the widened source types are the same.
10053 if (SourceType == MVT::Other)
10056 else if (InTy != SourceType) {
10057 // Multiple income types. Abort.
10058 SourceType = MVT::Other;
10062 // Check if all of the extends are ANY_EXTENDs.
10063 AllAnyExt &= AnyExt;
10066 // In order to have valid types, all of the inputs must be extended from the
10067 // same source type and all of the inputs must be any or zero extend.
10068 // Scalar sizes must be a power of two.
10069 EVT OutScalarTy = VT.getScalarType();
10070 bool ValidTypes = SourceType != MVT::Other &&
10071 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10072 isPowerOf2_32(SourceType.getSizeInBits());
10074 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10075 // turn into a single shuffle instruction.
10079 bool isLE = TLI.isLittleEndian();
10080 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10081 assert(ElemRatio > 1 && "Invalid element size ratio");
10082 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10083 DAG.getConstant(0, SourceType);
10085 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10086 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10088 // Populate the new build_vector
10089 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10090 SDValue Cast = N->getOperand(i);
10091 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10092 Cast.getOpcode() == ISD::ZERO_EXTEND ||
10093 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10095 if (Cast.getOpcode() == ISD::UNDEF)
10096 In = DAG.getUNDEF(SourceType);
10098 In = Cast->getOperand(0);
10099 unsigned Index = isLE ? (i * ElemRatio) :
10100 (i * ElemRatio + (ElemRatio - 1));
10102 assert(Index < Ops.size() && "Invalid index");
10106 // The type of the new BUILD_VECTOR node.
10107 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10108 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10109 "Invalid vector size");
10110 // Check if the new vector type is legal.
10111 if (!isTypeLegal(VecVT)) return SDValue();
10113 // Make the new BUILD_VECTOR.
10114 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10116 // The new BUILD_VECTOR node has the potential to be further optimized.
10117 AddToWorkList(BV.getNode());
10118 // Bitcast to the desired type.
10119 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10122 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10123 EVT VT = N->getValueType(0);
10125 unsigned NumInScalars = N->getNumOperands();
10128 EVT SrcVT = MVT::Other;
10129 unsigned Opcode = ISD::DELETED_NODE;
10130 unsigned NumDefs = 0;
10132 for (unsigned i = 0; i != NumInScalars; ++i) {
10133 SDValue In = N->getOperand(i);
10134 unsigned Opc = In.getOpcode();
10136 if (Opc == ISD::UNDEF)
10139 // If all scalar values are floats and converted from integers.
10140 if (Opcode == ISD::DELETED_NODE &&
10141 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10148 EVT InVT = In.getOperand(0).getValueType();
10150 // If all scalar values are typed differently, bail out. It's chosen to
10151 // simplify BUILD_VECTOR of integer types.
10152 if (SrcVT == MVT::Other)
10159 // If the vector has just one element defined, it's not worth to fold it into
10160 // a vectorized one.
10164 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10165 && "Should only handle conversion from integer to float.");
10166 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10168 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10170 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10173 SmallVector<SDValue, 8> Opnds;
10174 for (unsigned i = 0; i != NumInScalars; ++i) {
10175 SDValue In = N->getOperand(i);
10177 if (In.getOpcode() == ISD::UNDEF)
10178 Opnds.push_back(DAG.getUNDEF(SrcVT));
10180 Opnds.push_back(In.getOperand(0));
10182 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10183 AddToWorkList(BV.getNode());
10185 return DAG.getNode(Opcode, dl, VT, BV);
10188 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10189 unsigned NumInScalars = N->getNumOperands();
10191 EVT VT = N->getValueType(0);
10193 // A vector built entirely of undefs is undef.
10194 if (ISD::allOperandsUndef(N))
10195 return DAG.getUNDEF(VT);
10197 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10201 V = reduceBuildVecConvertToConvertBuildVec(N);
10205 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10206 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10207 // at most two distinct vectors, turn this into a shuffle node.
10209 // May only combine to shuffle after legalize if shuffle is legal.
10210 if (LegalOperations &&
10211 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10214 SDValue VecIn1, VecIn2;
10215 for (unsigned i = 0; i != NumInScalars; ++i) {
10216 // Ignore undef inputs.
10217 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10219 // If this input is something other than a EXTRACT_VECTOR_ELT with a
10220 // constant index, bail out.
10221 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10222 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10223 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10227 // We allow up to two distinct input vectors.
10228 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10229 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10232 if (!VecIn1.getNode()) {
10233 VecIn1 = ExtractedFromVec;
10234 } else if (!VecIn2.getNode()) {
10235 VecIn2 = ExtractedFromVec;
10237 // Too many inputs.
10238 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10243 // If everything is good, we can make a shuffle operation.
10244 if (VecIn1.getNode()) {
10245 SmallVector<int, 8> Mask;
10246 for (unsigned i = 0; i != NumInScalars; ++i) {
10247 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10248 Mask.push_back(-1);
10252 // If extracting from the first vector, just use the index directly.
10253 SDValue Extract = N->getOperand(i);
10254 SDValue ExtVal = Extract.getOperand(1);
10255 if (Extract.getOperand(0) == VecIn1) {
10256 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10257 if (ExtIndex > VT.getVectorNumElements())
10260 Mask.push_back(ExtIndex);
10264 // Otherwise, use InIdx + VecSize
10265 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10266 Mask.push_back(Idx+NumInScalars);
10269 // We can't generate a shuffle node with mismatched input and output types.
10270 // Attempt to transform a single input vector to the correct type.
10271 if ((VT != VecIn1.getValueType())) {
10272 // We don't support shuffeling between TWO values of different types.
10273 if (VecIn2.getNode())
10276 // We only support widening of vectors which are half the size of the
10277 // output registers. For example XMM->YMM widening on X86 with AVX.
10278 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10281 // If the input vector type has a different base type to the output
10282 // vector type, bail out.
10283 if (VecIn1.getValueType().getVectorElementType() !=
10284 VT.getVectorElementType())
10287 // Widen the input vector by adding undef values.
10288 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10289 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10292 // If VecIn2 is unused then change it to undef.
10293 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10295 // Check that we were able to transform all incoming values to the same
10297 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10298 VecIn1.getValueType() != VT)
10301 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10302 if (!isTypeLegal(VT))
10305 // Return the new VECTOR_SHUFFLE node.
10309 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10315 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10316 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10317 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10318 // inputs come from at most two distinct vectors, turn this into a shuffle
10321 // If we only have one input vector, we don't need to do any concatenation.
10322 if (N->getNumOperands() == 1)
10323 return N->getOperand(0);
10325 // Check if all of the operands are undefs.
10326 EVT VT = N->getValueType(0);
10327 if (ISD::allOperandsUndef(N))
10328 return DAG.getUNDEF(VT);
10330 // Optimize concat_vectors where one of the vectors is undef.
10331 if (N->getNumOperands() == 2 &&
10332 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10333 SDValue In = N->getOperand(0);
10334 assert(In.getValueType().isVector() && "Must concat vectors");
10336 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10337 if (In->getOpcode() == ISD::BITCAST &&
10338 !In->getOperand(0)->getValueType(0).isVector()) {
10339 SDValue Scalar = In->getOperand(0);
10340 EVT SclTy = Scalar->getValueType(0);
10342 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10345 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10346 VT.getSizeInBits() / SclTy.getSizeInBits());
10347 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10350 SDLoc dl = SDLoc(N);
10351 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10352 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10356 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10357 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10358 if (N->getNumOperands() == 2 &&
10359 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10360 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10361 EVT VT = N->getValueType(0);
10362 SDValue N0 = N->getOperand(0);
10363 SDValue N1 = N->getOperand(1);
10364 SmallVector<SDValue, 8> Opnds;
10365 unsigned BuildVecNumElts = N0.getNumOperands();
10367 EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10368 EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10369 if (SclTy0.isFloatingPoint()) {
10370 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10371 Opnds.push_back(N0.getOperand(i));
10372 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10373 Opnds.push_back(N1.getOperand(i));
10375 // If BUILD_VECTOR are from built from integer, they may have different
10376 // operand types. Get the smaller type and truncate all operands to it.
10377 EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10378 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10379 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10380 N0.getOperand(i)));
10381 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10382 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10383 N1.getOperand(i)));
10386 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10389 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10390 // nodes often generate nop CONCAT_VECTOR nodes.
10391 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10392 // place the incoming vectors at the exact same location.
10393 SDValue SingleSource = SDValue();
10394 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10396 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10397 SDValue Op = N->getOperand(i);
10399 if (Op.getOpcode() == ISD::UNDEF)
10402 // Check if this is the identity extract:
10403 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10406 // Find the single incoming vector for the extract_subvector.
10407 if (SingleSource.getNode()) {
10408 if (Op.getOperand(0) != SingleSource)
10411 SingleSource = Op.getOperand(0);
10413 // Check the source type is the same as the type of the result.
10414 // If not, this concat may extend the vector, so we can not
10415 // optimize it away.
10416 if (SingleSource.getValueType() != N->getValueType(0))
10420 unsigned IdentityIndex = i * PartNumElem;
10421 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10422 // The extract index must be constant.
10426 // Check that we are reading from the identity index.
10427 if (CS->getZExtValue() != IdentityIndex)
10431 if (SingleSource.getNode())
10432 return SingleSource;
10437 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10438 EVT NVT = N->getValueType(0);
10439 SDValue V = N->getOperand(0);
10441 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10443 // (extract_subvec (concat V1, V2, ...), i)
10446 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10448 if (V->getOperand(0).getValueType() != NVT)
10450 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10451 unsigned NumElems = NVT.getVectorNumElements();
10452 assert((Idx % NumElems) == 0 &&
10453 "IDX in concat is not a multiple of the result vector length.");
10454 return V->getOperand(Idx / NumElems);
10458 if (V->getOpcode() == ISD::BITCAST)
10459 V = V.getOperand(0);
10461 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10463 // Handle only simple case where vector being inserted and vector
10464 // being extracted are of same type, and are half size of larger vectors.
10465 EVT BigVT = V->getOperand(0).getValueType();
10466 EVT SmallVT = V->getOperand(1).getValueType();
10467 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10470 // Only handle cases where both indexes are constants with the same type.
10471 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10472 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10474 if (InsIdx && ExtIdx &&
10475 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10476 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10478 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10480 // indices are equal or bit offsets are equal => V1
10481 // otherwise => (extract_subvec V1, ExtIdx)
10482 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10483 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10484 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10485 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10486 DAG.getNode(ISD::BITCAST, dl,
10487 N->getOperand(0).getValueType(),
10488 V->getOperand(0)), N->getOperand(1));
10495 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10496 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10497 EVT VT = N->getValueType(0);
10498 unsigned NumElts = VT.getVectorNumElements();
10500 SDValue N0 = N->getOperand(0);
10501 SDValue N1 = N->getOperand(1);
10502 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10504 SmallVector<SDValue, 4> Ops;
10505 EVT ConcatVT = N0.getOperand(0).getValueType();
10506 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10507 unsigned NumConcats = NumElts / NumElemsPerConcat;
10509 // Look at every vector that's inserted. We're looking for exact
10510 // subvector-sized copies from a concatenated vector
10511 for (unsigned I = 0; I != NumConcats; ++I) {
10512 // Make sure we're dealing with a copy.
10513 unsigned Begin = I * NumElemsPerConcat;
10514 bool AllUndef = true, NoUndef = true;
10515 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10516 if (SVN->getMaskElt(J) >= 0)
10523 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10526 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10527 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10530 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10531 if (FirstElt < N0.getNumOperands())
10532 Ops.push_back(N0.getOperand(FirstElt));
10534 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10536 } else if (AllUndef) {
10537 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10538 } else { // Mixed with general masks and undefs, can't do optimization.
10543 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10546 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10547 EVT VT = N->getValueType(0);
10548 unsigned NumElts = VT.getVectorNumElements();
10550 SDValue N0 = N->getOperand(0);
10551 SDValue N1 = N->getOperand(1);
10553 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10555 // Canonicalize shuffle undef, undef -> undef
10556 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10557 return DAG.getUNDEF(VT);
10559 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10561 // Canonicalize shuffle v, v -> v, undef
10563 SmallVector<int, 8> NewMask;
10564 for (unsigned i = 0; i != NumElts; ++i) {
10565 int Idx = SVN->getMaskElt(i);
10566 if (Idx >= (int)NumElts) Idx -= NumElts;
10567 NewMask.push_back(Idx);
10569 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10573 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10574 if (N0.getOpcode() == ISD::UNDEF) {
10575 SmallVector<int, 8> NewMask;
10576 for (unsigned i = 0; i != NumElts; ++i) {
10577 int Idx = SVN->getMaskElt(i);
10579 if (Idx >= (int)NumElts)
10582 Idx = -1; // remove reference to lhs
10584 NewMask.push_back(Idx);
10586 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10590 // Remove references to rhs if it is undef
10591 if (N1.getOpcode() == ISD::UNDEF) {
10592 bool Changed = false;
10593 SmallVector<int, 8> NewMask;
10594 for (unsigned i = 0; i != NumElts; ++i) {
10595 int Idx = SVN->getMaskElt(i);
10596 if (Idx >= (int)NumElts) {
10600 NewMask.push_back(Idx);
10603 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10606 // If it is a splat, check if the argument vector is another splat or a
10607 // build_vector with all scalar elements the same.
10608 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10609 SDNode *V = N0.getNode();
10611 // If this is a bit convert that changes the element type of the vector but
10612 // not the number of vector elements, look through it. Be careful not to
10613 // look though conversions that change things like v4f32 to v2f64.
10614 if (V->getOpcode() == ISD::BITCAST) {
10615 SDValue ConvInput = V->getOperand(0);
10616 if (ConvInput.getValueType().isVector() &&
10617 ConvInput.getValueType().getVectorNumElements() == NumElts)
10618 V = ConvInput.getNode();
10621 if (V->getOpcode() == ISD::BUILD_VECTOR) {
10622 assert(V->getNumOperands() == NumElts &&
10623 "BUILD_VECTOR has wrong number of operands");
10625 bool AllSame = true;
10626 for (unsigned i = 0; i != NumElts; ++i) {
10627 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10628 Base = V->getOperand(i);
10632 // Splat of <u, u, u, u>, return <u, u, u, u>
10633 if (!Base.getNode())
10635 for (unsigned i = 0; i != NumElts; ++i) {
10636 if (V->getOperand(i) != Base) {
10641 // Splat of <x, x, x, x>, return <x, x, x, x>
10647 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10648 Level < AfterLegalizeVectorOps &&
10649 (N1.getOpcode() == ISD::UNDEF ||
10650 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10651 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10652 SDValue V = partitionShuffleOfConcats(N, DAG);
10658 // If this shuffle node is simply a swizzle of another shuffle node,
10659 // then try to simplify it.
10660 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10661 N1.getOpcode() == ISD::UNDEF) {
10663 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10665 // The incoming shuffle must be of the same type as the result of the
10666 // current shuffle.
10667 assert(OtherSV->getOperand(0).getValueType() == VT &&
10668 "Shuffle types don't match");
10670 SmallVector<int, 4> Mask;
10671 // Compute the combined shuffle mask.
10672 for (unsigned i = 0; i != NumElts; ++i) {
10673 int Idx = SVN->getMaskElt(i);
10674 assert(Idx < (int)NumElts && "Index references undef operand");
10675 // Next, this index comes from the first value, which is the incoming
10676 // shuffle. Adopt the incoming index.
10678 Idx = OtherSV->getMaskElt(Idx);
10679 Mask.push_back(Idx);
10682 bool CommuteOperands = false;
10683 if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
10684 // To be valid, the combine shuffle mask should only reference elements
10685 // from one of the two vectors in input to the inner shufflevector.
10686 bool IsValidMask = true;
10687 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10688 // See if the combined mask only reference undefs or elements coming
10689 // from the first shufflevector operand.
10690 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
10692 if (!IsValidMask) {
10693 IsValidMask = true;
10694 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10695 // Check that all the elements come from the second shuffle operand.
10696 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
10697 CommuteOperands = IsValidMask;
10700 // Early exit if the combined shuffle mask is not valid.
10705 // See if this pair of shuffles can be safely folded according to either
10706 // of the following rules:
10707 // shuffle(shuffle(x, y), undef) -> x
10708 // shuffle(shuffle(x, undef), undef) -> x
10709 // shuffle(shuffle(x, y), undef) -> y
10710 bool IsIdentityMask = true;
10711 unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
10712 for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
10717 // The combined shuffle must map each index to itself.
10718 IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
10721 if (IsIdentityMask) {
10722 if (CommuteOperands)
10723 // optimize shuffle(shuffle(x, y), undef) -> y.
10724 return OtherSV->getOperand(1);
10726 // optimize shuffle(shuffle(x, undef), undef) -> x
10727 // optimize shuffle(shuffle(x, y), undef) -> x
10728 return OtherSV->getOperand(0);
10731 // It may still be beneficial to combine the two shuffles if the
10732 // resulting shuffle is legal.
10733 if (TLI.isTypeLegal(VT) && TLI.isShuffleMaskLegal(Mask, VT)) {
10734 if (!CommuteOperands)
10735 // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
10736 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
10737 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
10740 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(undef, y, M3)
10741 return DAG.getVectorShuffle(VT, SDLoc(N), N1, N0->getOperand(1),
10746 // Canonicalize shuffles according to rules:
10747 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
10748 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
10749 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
10750 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
10751 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10752 TLI.isTypeLegal(VT)) {
10753 // The incoming shuffle must be of the same type as the result of the
10754 // current shuffle.
10755 assert(N1->getOperand(0).getValueType() == VT &&
10756 "Shuffle types don't match");
10758 SDValue SV0 = N1->getOperand(0);
10759 SDValue SV1 = N1->getOperand(1);
10760 bool HasSameOp0 = N0 == SV0;
10761 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10762 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
10763 // Commute the operands of this shuffle so that next rule
10765 return DAG.getCommutedVectorShuffle(*SVN);
10768 // Try to fold according to rules:
10769 // shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
10770 // shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
10771 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10772 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10773 // Don't try to fold shuffles with illegal type.
10774 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10775 N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
10776 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10778 // The incoming shuffle must be of the same type as the result of the
10779 // current shuffle.
10780 assert(OtherSV->getOperand(0).getValueType() == VT &&
10781 "Shuffle types don't match");
10783 SDValue SV0 = OtherSV->getOperand(0);
10784 SDValue SV1 = OtherSV->getOperand(1);
10785 bool HasSameOp0 = N1 == SV0;
10786 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10787 if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
10791 SmallVector<int, 4> Mask;
10792 // Compute the combined shuffle mask for a shuffle with SV0 as the first
10793 // operand, and SV1 as the second operand.
10794 for (unsigned i = 0; i != NumElts; ++i) {
10795 int Idx = SVN->getMaskElt(i);
10797 // Propagate Undef.
10798 Mask.push_back(Idx);
10802 if (Idx < (int)NumElts) {
10803 Idx = OtherSV->getMaskElt(Idx);
10804 if (IsSV1Undef && Idx >= (int) NumElts)
10805 Idx = -1; // Propagate Undef.
10807 Idx = HasSameOp0 ? Idx - NumElts : Idx;
10809 Mask.push_back(Idx);
10812 // Avoid introducing shuffles with illegal mask.
10813 if (TLI.isShuffleMaskLegal(Mask, VT)) {
10815 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10816 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10817 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
10818 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
10825 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10826 SDValue N0 = N->getOperand(0);
10827 SDValue N2 = N->getOperand(2);
10829 // If the input vector is a concatenation, and the insert replaces
10830 // one of the halves, we can optimize into a single concat_vectors.
10831 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10832 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10833 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10834 EVT VT = N->getValueType(0);
10836 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10837 // (concat_vectors Z, Y)
10839 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10840 N->getOperand(1), N0.getOperand(1));
10842 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10843 // (concat_vectors X, Z)
10844 if (InsIdx == VT.getVectorNumElements()/2)
10845 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10846 N0.getOperand(0), N->getOperand(1));
10852 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10853 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10854 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10855 /// vector_shuffle V, Zero, <0, 4, 2, 4>
10856 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10857 EVT VT = N->getValueType(0);
10859 SDValue LHS = N->getOperand(0);
10860 SDValue RHS = N->getOperand(1);
10861 if (N->getOpcode() == ISD::AND) {
10862 if (RHS.getOpcode() == ISD::BITCAST)
10863 RHS = RHS.getOperand(0);
10864 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10865 SmallVector<int, 8> Indices;
10866 unsigned NumElts = RHS.getNumOperands();
10867 for (unsigned i = 0; i != NumElts; ++i) {
10868 SDValue Elt = RHS.getOperand(i);
10869 if (!isa<ConstantSDNode>(Elt))
10872 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10873 Indices.push_back(i);
10874 else if (cast<ConstantSDNode>(Elt)->isNullValue())
10875 Indices.push_back(NumElts);
10880 // Let's see if the target supports this vector_shuffle.
10881 EVT RVT = RHS.getValueType();
10882 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10885 // Return the new VECTOR_SHUFFLE node.
10886 EVT EltVT = RVT.getVectorElementType();
10887 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10888 DAG.getConstant(0, EltVT));
10889 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
10890 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10891 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10892 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10899 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10900 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10901 assert(N->getValueType(0).isVector() &&
10902 "SimplifyVBinOp only works on vectors!");
10904 SDValue LHS = N->getOperand(0);
10905 SDValue RHS = N->getOperand(1);
10906 SDValue Shuffle = XformToShuffleWithZero(N);
10907 if (Shuffle.getNode()) return Shuffle;
10909 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10911 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10912 RHS.getOpcode() == ISD::BUILD_VECTOR) {
10913 // Check if both vectors are constants. If not bail out.
10914 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10915 cast<BuildVectorSDNode>(RHS)->isConstant()))
10918 SmallVector<SDValue, 8> Ops;
10919 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10920 SDValue LHSOp = LHS.getOperand(i);
10921 SDValue RHSOp = RHS.getOperand(i);
10923 // Can't fold divide by zero.
10924 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10925 N->getOpcode() == ISD::FDIV) {
10926 if ((RHSOp.getOpcode() == ISD::Constant &&
10927 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10928 (RHSOp.getOpcode() == ISD::ConstantFP &&
10929 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10933 EVT VT = LHSOp.getValueType();
10934 EVT RVT = RHSOp.getValueType();
10936 // Integer BUILD_VECTOR operands may have types larger than the element
10937 // size (e.g., when the element type is not legal). Prior to type
10938 // legalization, the types may not match between the two BUILD_VECTORS.
10939 // Truncate one of the operands to make them match.
10940 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10941 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10943 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10947 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10949 if (FoldOp.getOpcode() != ISD::UNDEF &&
10950 FoldOp.getOpcode() != ISD::Constant &&
10951 FoldOp.getOpcode() != ISD::ConstantFP)
10953 Ops.push_back(FoldOp);
10954 AddToWorkList(FoldOp.getNode());
10957 if (Ops.size() == LHS.getNumOperands())
10958 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
10961 // Type legalization might introduce new shuffles in the DAG.
10962 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
10963 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
10964 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
10965 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
10966 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
10967 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
10968 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
10969 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
10971 if (SVN0->getMask().equals(SVN1->getMask())) {
10972 EVT VT = N->getValueType(0);
10973 SDValue UndefVector = LHS.getOperand(1);
10974 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
10975 LHS.getOperand(0), RHS.getOperand(0));
10976 AddUsersToWorkList(N);
10977 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
10978 &SVN0->getMask()[0]);
10985 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10986 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10987 assert(N->getValueType(0).isVector() &&
10988 "SimplifyVUnaryOp only works on vectors!");
10990 SDValue N0 = N->getOperand(0);
10992 if (N0.getOpcode() != ISD::BUILD_VECTOR)
10995 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10996 SmallVector<SDValue, 8> Ops;
10997 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10998 SDValue Op = N0.getOperand(i);
10999 if (Op.getOpcode() != ISD::UNDEF &&
11000 Op.getOpcode() != ISD::ConstantFP)
11002 EVT EltVT = Op.getValueType();
11003 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11004 if (FoldOp.getOpcode() != ISD::UNDEF &&
11005 FoldOp.getOpcode() != ISD::ConstantFP)
11007 Ops.push_back(FoldOp);
11008 AddToWorkList(FoldOp.getNode());
11011 if (Ops.size() != N0.getNumOperands())
11014 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11017 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11018 SDValue N1, SDValue N2){
11019 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11021 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11022 cast<CondCodeSDNode>(N0.getOperand(2))->get());
11024 // If we got a simplified select_cc node back from SimplifySelectCC, then
11025 // break it down into a new SETCC node, and a new SELECT node, and then return
11026 // the SELECT node, since we were called with a SELECT node.
11027 if (SCC.getNode()) {
11028 // Check to see if we got a select_cc back (to turn into setcc/select).
11029 // Otherwise, just return whatever node we got back, like fabs.
11030 if (SCC.getOpcode() == ISD::SELECT_CC) {
11031 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11033 SCC.getOperand(0), SCC.getOperand(1),
11034 SCC.getOperand(4));
11035 AddToWorkList(SETCC.getNode());
11036 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
11037 SCC.getOperand(2), SCC.getOperand(3), SETCC);
11045 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
11046 /// are the two values being selected between, see if we can simplify the
11047 /// select. Callers of this should assume that TheSelect is deleted if this
11048 /// returns true. As such, they should return the appropriate thing (e.g. the
11049 /// node) back to the top-level of the DAG combiner loop to avoid it being
11051 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11054 // Cannot simplify select with vector condition
11055 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11057 // If this is a select from two identical things, try to pull the operation
11058 // through the select.
11059 if (LHS.getOpcode() != RHS.getOpcode() ||
11060 !LHS.hasOneUse() || !RHS.hasOneUse())
11063 // If this is a load and the token chain is identical, replace the select
11064 // of two loads with a load through a select of the address to load from.
11065 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11066 // constants have been dropped into the constant pool.
11067 if (LHS.getOpcode() == ISD::LOAD) {
11068 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11069 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11071 // Token chains must be identical.
11072 if (LHS.getOperand(0) != RHS.getOperand(0) ||
11073 // Do not let this transformation reduce the number of volatile loads.
11074 LLD->isVolatile() || RLD->isVolatile() ||
11075 // If this is an EXTLOAD, the VT's must match.
11076 LLD->getMemoryVT() != RLD->getMemoryVT() ||
11077 // If this is an EXTLOAD, the kind of extension must match.
11078 (LLD->getExtensionType() != RLD->getExtensionType() &&
11079 // The only exception is if one of the extensions is anyext.
11080 LLD->getExtensionType() != ISD::EXTLOAD &&
11081 RLD->getExtensionType() != ISD::EXTLOAD) ||
11082 // FIXME: this discards src value information. This is
11083 // over-conservative. It would be beneficial to be able to remember
11084 // both potential memory locations. Since we are discarding
11085 // src value info, don't do the transformation if the memory
11086 // locations are not in the default address space.
11087 LLD->getPointerInfo().getAddrSpace() != 0 ||
11088 RLD->getPointerInfo().getAddrSpace() != 0 ||
11089 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11090 LLD->getBasePtr().getValueType()))
11093 // Check that the select condition doesn't reach either load. If so,
11094 // folding this will induce a cycle into the DAG. If not, this is safe to
11095 // xform, so create a select of the addresses.
11097 if (TheSelect->getOpcode() == ISD::SELECT) {
11098 SDNode *CondNode = TheSelect->getOperand(0).getNode();
11099 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11100 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11102 // The loads must not depend on one another.
11103 if (LLD->isPredecessorOf(RLD) ||
11104 RLD->isPredecessorOf(LLD))
11106 Addr = DAG.getSelect(SDLoc(TheSelect),
11107 LLD->getBasePtr().getValueType(),
11108 TheSelect->getOperand(0), LLD->getBasePtr(),
11109 RLD->getBasePtr());
11110 } else { // Otherwise SELECT_CC
11111 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11112 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11114 if ((LLD->hasAnyUseOfValue(1) &&
11115 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11116 (RLD->hasAnyUseOfValue(1) &&
11117 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11120 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11121 LLD->getBasePtr().getValueType(),
11122 TheSelect->getOperand(0),
11123 TheSelect->getOperand(1),
11124 LLD->getBasePtr(), RLD->getBasePtr(),
11125 TheSelect->getOperand(4));
11129 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11130 Load = DAG.getLoad(TheSelect->getValueType(0),
11132 // FIXME: Discards pointer and TBAA info.
11133 LLD->getChain(), Addr, MachinePointerInfo(),
11134 LLD->isVolatile(), LLD->isNonTemporal(),
11135 LLD->isInvariant(), LLD->getAlignment());
11137 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11138 RLD->getExtensionType() : LLD->getExtensionType(),
11140 TheSelect->getValueType(0),
11141 // FIXME: Discards pointer and TBAA info.
11142 LLD->getChain(), Addr, MachinePointerInfo(),
11143 LLD->getMemoryVT(), LLD->isVolatile(),
11144 LLD->isNonTemporal(), LLD->getAlignment());
11147 // Users of the select now use the result of the load.
11148 CombineTo(TheSelect, Load);
11150 // Users of the old loads now use the new load's chain. We know the
11151 // old-load value is dead now.
11152 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11153 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11160 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
11161 /// where 'cond' is the comparison specified by CC.
11162 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11163 SDValue N2, SDValue N3,
11164 ISD::CondCode CC, bool NotExtCompare) {
11165 // (x ? y : y) -> y.
11166 if (N2 == N3) return N2;
11168 EVT VT = N2.getValueType();
11169 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11170 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11171 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11173 // Determine if the condition we're dealing with is constant
11174 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11175 N0, N1, CC, DL, false);
11176 if (SCC.getNode()) AddToWorkList(SCC.getNode());
11177 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11179 // fold select_cc true, x, y -> x
11180 if (SCCC && !SCCC->isNullValue())
11182 // fold select_cc false, x, y -> y
11183 if (SCCC && SCCC->isNullValue())
11186 // Check to see if we can simplify the select into an fabs node
11187 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11188 // Allow either -0.0 or 0.0
11189 if (CFP->getValueAPF().isZero()) {
11190 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11191 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11192 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11193 N2 == N3.getOperand(0))
11194 return DAG.getNode(ISD::FABS, DL, VT, N0);
11196 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11197 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11198 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11199 N2.getOperand(0) == N3)
11200 return DAG.getNode(ISD::FABS, DL, VT, N3);
11204 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11205 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11206 // in it. This is a win when the constant is not otherwise available because
11207 // it replaces two constant pool loads with one. We only do this if the FP
11208 // type is known to be legal, because if it isn't, then we are before legalize
11209 // types an we want the other legalization to happen first (e.g. to avoid
11210 // messing with soft float) and if the ConstantFP is not legal, because if
11211 // it is legal, we may not need to store the FP constant in a constant pool.
11212 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11213 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11214 if (TLI.isTypeLegal(N2.getValueType()) &&
11215 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11216 TargetLowering::Legal &&
11217 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11218 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11219 // If both constants have multiple uses, then we won't need to do an
11220 // extra load, they are likely around in registers for other users.
11221 (TV->hasOneUse() || FV->hasOneUse())) {
11222 Constant *Elts[] = {
11223 const_cast<ConstantFP*>(FV->getConstantFPValue()),
11224 const_cast<ConstantFP*>(TV->getConstantFPValue())
11226 Type *FPTy = Elts[0]->getType();
11227 const DataLayout &TD = *TLI.getDataLayout();
11229 // Create a ConstantArray of the two constants.
11230 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11231 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11232 TD.getPrefTypeAlignment(FPTy));
11233 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11235 // Get the offsets to the 0 and 1 element of the array so that we can
11236 // select between them.
11237 SDValue Zero = DAG.getIntPtrConstant(0);
11238 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11239 SDValue One = DAG.getIntPtrConstant(EltSize);
11241 SDValue Cond = DAG.getSetCC(DL,
11242 getSetCCResultType(N0.getValueType()),
11244 AddToWorkList(Cond.getNode());
11245 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11247 AddToWorkList(CstOffset.getNode());
11248 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11250 AddToWorkList(CPIdx.getNode());
11251 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11252 MachinePointerInfo::getConstantPool(), false,
11253 false, false, Alignment);
11258 // Check to see if we can perform the "gzip trick", transforming
11259 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11260 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11261 (N1C->isNullValue() || // (a < 0) ? b : 0
11262 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
11263 EVT XType = N0.getValueType();
11264 EVT AType = N2.getValueType();
11265 if (XType.bitsGE(AType)) {
11266 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11267 // single-bit constant.
11268 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11269 unsigned ShCtV = N2C->getAPIntValue().logBase2();
11270 ShCtV = XType.getSizeInBits()-ShCtV-1;
11271 SDValue ShCt = DAG.getConstant(ShCtV,
11272 getShiftAmountTy(N0.getValueType()));
11273 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11275 AddToWorkList(Shift.getNode());
11277 if (XType.bitsGT(AType)) {
11278 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11279 AddToWorkList(Shift.getNode());
11282 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11285 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11287 DAG.getConstant(XType.getSizeInBits()-1,
11288 getShiftAmountTy(N0.getValueType())));
11289 AddToWorkList(Shift.getNode());
11291 if (XType.bitsGT(AType)) {
11292 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11293 AddToWorkList(Shift.getNode());
11296 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11300 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11301 // where y is has a single bit set.
11302 // A plaintext description would be, we can turn the SELECT_CC into an AND
11303 // when the condition can be materialized as an all-ones register. Any
11304 // single bit-test can be materialized as an all-ones register with
11305 // shift-left and shift-right-arith.
11306 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11307 N0->getValueType(0) == VT &&
11308 N1C && N1C->isNullValue() &&
11309 N2C && N2C->isNullValue()) {
11310 SDValue AndLHS = N0->getOperand(0);
11311 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11312 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11313 // Shift the tested bit over the sign bit.
11314 APInt AndMask = ConstAndRHS->getAPIntValue();
11316 DAG.getConstant(AndMask.countLeadingZeros(),
11317 getShiftAmountTy(AndLHS.getValueType()));
11318 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11320 // Now arithmetic right shift it all the way over, so the result is either
11321 // all-ones, or zero.
11323 DAG.getConstant(AndMask.getBitWidth()-1,
11324 getShiftAmountTy(Shl.getValueType()));
11325 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11327 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11331 // fold select C, 16, 0 -> shl C, 4
11332 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11333 TLI.getBooleanContents(N0.getValueType()) ==
11334 TargetLowering::ZeroOrOneBooleanContent) {
11336 // If the caller doesn't want us to simplify this into a zext of a compare,
11338 if (NotExtCompare && N2C->getAPIntValue() == 1)
11341 // Get a SetCC of the condition
11342 // NOTE: Don't create a SETCC if it's not legal on this target.
11343 if (!LegalOperations ||
11344 TLI.isOperationLegal(ISD::SETCC,
11345 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11347 // cast from setcc result type to select result type
11349 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11351 if (N2.getValueType().bitsLT(SCC.getValueType()))
11352 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11353 N2.getValueType());
11355 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11356 N2.getValueType(), SCC);
11358 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11359 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11360 N2.getValueType(), SCC);
11363 AddToWorkList(SCC.getNode());
11364 AddToWorkList(Temp.getNode());
11366 if (N2C->getAPIntValue() == 1)
11369 // shl setcc result by log2 n2c
11370 return DAG.getNode(
11371 ISD::SHL, DL, N2.getValueType(), Temp,
11372 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11373 getShiftAmountTy(Temp.getValueType())));
11377 // Check to see if this is the equivalent of setcc
11378 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11379 // otherwise, go ahead with the folds.
11380 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11381 EVT XType = N0.getValueType();
11382 if (!LegalOperations ||
11383 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11384 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11385 if (Res.getValueType() != VT)
11386 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11390 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11391 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11392 (!LegalOperations ||
11393 TLI.isOperationLegal(ISD::CTLZ, XType))) {
11394 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11395 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11396 DAG.getConstant(Log2_32(XType.getSizeInBits()),
11397 getShiftAmountTy(Ctlz.getValueType())));
11399 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11400 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11401 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11402 XType, DAG.getConstant(0, XType), N0);
11403 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11404 return DAG.getNode(ISD::SRL, DL, XType,
11405 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11406 DAG.getConstant(XType.getSizeInBits()-1,
11407 getShiftAmountTy(XType)));
11409 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11410 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11411 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11412 DAG.getConstant(XType.getSizeInBits()-1,
11413 getShiftAmountTy(N0.getValueType())));
11414 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11418 // Check to see if this is an integer abs.
11419 // select_cc setg[te] X, 0, X, -X ->
11420 // select_cc setgt X, -1, X, -X ->
11421 // select_cc setl[te] X, 0, -X, X ->
11422 // select_cc setlt X, 1, -X, X ->
11423 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11425 ConstantSDNode *SubC = nullptr;
11426 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11427 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11428 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11429 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11430 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11431 (N1C->isOne() && CC == ISD::SETLT)) &&
11432 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11433 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11435 EVT XType = N0.getValueType();
11436 if (SubC && SubC->isNullValue() && XType.isInteger()) {
11437 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11439 DAG.getConstant(XType.getSizeInBits()-1,
11440 getShiftAmountTy(N0.getValueType())));
11441 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11443 AddToWorkList(Shift.getNode());
11444 AddToWorkList(Add.getNode());
11445 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11452 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11453 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11454 SDValue N1, ISD::CondCode Cond,
11455 SDLoc DL, bool foldBooleans) {
11456 TargetLowering::DAGCombinerInfo
11457 DagCombineInfo(DAG, Level, false, this);
11458 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11461 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11462 /// return a DAG expression to select that will generate the same value by
11463 /// multiplying by a magic number. See:
11464 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11465 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11466 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11470 // Avoid division by zero.
11471 if (!C->getAPIntValue())
11474 std::vector<SDNode*> Built;
11476 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11478 for (SDNode *N : Built)
11483 /// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant,
11484 /// return a DAG expression to select that will generate the same value by
11485 /// multiplying by a magic number. See:
11486 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11487 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11488 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11492 // Avoid division by zero.
11493 if (!C->getAPIntValue())
11496 std::vector<SDNode*> Built;
11498 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11500 for (SDNode *N : Built)
11505 /// FindBaseOffset - Return true if base is a frame index, which is known not
11506 // to alias with anything but itself. Provides base object and offset as
11508 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11509 const GlobalValue *&GV, const void *&CV) {
11510 // Assume it is a primitive operation.
11511 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11513 // If it's an adding a simple constant then integrate the offset.
11514 if (Base.getOpcode() == ISD::ADD) {
11515 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11516 Base = Base.getOperand(0);
11517 Offset += C->getZExtValue();
11521 // Return the underlying GlobalValue, and update the Offset. Return false
11522 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11523 // by multiple nodes with different offsets.
11524 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11525 GV = G->getGlobal();
11526 Offset += G->getOffset();
11530 // Return the underlying Constant value, and update the Offset. Return false
11531 // for ConstantSDNodes since the same constant pool entry may be represented
11532 // by multiple nodes with different offsets.
11533 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11534 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11535 : (const void *)C->getConstVal();
11536 Offset += C->getOffset();
11539 // If it's any of the following then it can't alias with anything but itself.
11540 return isa<FrameIndexSDNode>(Base);
11543 /// isAlias - Return true if there is any possibility that the two addresses
11545 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11546 // If they are the same then they must be aliases.
11547 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11549 // If they are both volatile then they cannot be reordered.
11550 if (Op0->isVolatile() && Op1->isVolatile()) return true;
11552 // Gather base node and offset information.
11553 SDValue Base1, Base2;
11554 int64_t Offset1, Offset2;
11555 const GlobalValue *GV1, *GV2;
11556 const void *CV1, *CV2;
11557 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11558 Base1, Offset1, GV1, CV1);
11559 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11560 Base2, Offset2, GV2, CV2);
11562 // If they have a same base address then check to see if they overlap.
11563 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11564 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11565 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11567 // It is possible for different frame indices to alias each other, mostly
11568 // when tail call optimization reuses return address slots for arguments.
11569 // To catch this case, look up the actual index of frame indices to compute
11570 // the real alias relationship.
11571 if (isFrameIndex1 && isFrameIndex2) {
11572 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11573 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11574 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11575 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11576 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11579 // Otherwise, if we know what the bases are, and they aren't identical, then
11580 // we know they cannot alias.
11581 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11584 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11585 // compared to the size and offset of the access, we may be able to prove they
11586 // do not alias. This check is conservative for now to catch cases created by
11587 // splitting vector types.
11588 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11589 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11590 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11591 Op1->getMemoryVT().getSizeInBits() >> 3) &&
11592 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11593 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11594 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11596 // There is no overlap between these relatively aligned accesses of similar
11597 // size, return no alias.
11598 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11599 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11603 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11604 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11606 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11607 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11611 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11612 // Use alias analysis information.
11613 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11614 Op1->getSrcValueOffset());
11615 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11616 Op0->getSrcValueOffset() - MinOffset;
11617 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11618 Op1->getSrcValueOffset() - MinOffset;
11619 AliasAnalysis::AliasResult AAResult =
11620 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11622 UseTBAA ? Op0->getTBAAInfo() : nullptr),
11623 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11625 UseTBAA ? Op1->getTBAAInfo() : nullptr));
11626 if (AAResult == AliasAnalysis::NoAlias)
11630 // Otherwise we have to assume they alias.
11634 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11635 /// looking for aliasing nodes and adding them to the Aliases vector.
11636 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11637 SmallVectorImpl<SDValue> &Aliases) {
11638 SmallVector<SDValue, 8> Chains; // List of chains to visit.
11639 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
11641 // Get alias information for node.
11642 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11645 Chains.push_back(OriginalChain);
11646 unsigned Depth = 0;
11648 // Look at each chain and determine if it is an alias. If so, add it to the
11649 // aliases list. If not, then continue up the chain looking for the next
11651 while (!Chains.empty()) {
11652 SDValue Chain = Chains.back();
11655 // For TokenFactor nodes, look at each operand and only continue up the
11656 // chain until we find two aliases. If we've seen two aliases, assume we'll
11657 // find more and revert to original chain since the xform is unlikely to be
11660 // FIXME: The depth check could be made to return the last non-aliasing
11661 // chain we found before we hit a tokenfactor rather than the original
11663 if (Depth > 6 || Aliases.size() == 2) {
11665 Aliases.push_back(OriginalChain);
11669 // Don't bother if we've been before.
11670 if (!Visited.insert(Chain.getNode()))
11673 switch (Chain.getOpcode()) {
11674 case ISD::EntryToken:
11675 // Entry token is ideal chain operand, but handled in FindBetterChain.
11680 // Get alias information for Chain.
11681 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11682 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11684 // If chain is alias then stop here.
11685 if (!(IsLoad && IsOpLoad) &&
11686 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11687 Aliases.push_back(Chain);
11689 // Look further up the chain.
11690 Chains.push_back(Chain.getOperand(0));
11696 case ISD::TokenFactor:
11697 // We have to check each of the operands of the token factor for "small"
11698 // token factors, so we queue them up. Adding the operands to the queue
11699 // (stack) in reverse order maintains the original order and increases the
11700 // likelihood that getNode will find a matching token factor (CSE.)
11701 if (Chain.getNumOperands() > 16) {
11702 Aliases.push_back(Chain);
11705 for (unsigned n = Chain.getNumOperands(); n;)
11706 Chains.push_back(Chain.getOperand(--n));
11711 // For all other instructions we will just have to take what we can get.
11712 Aliases.push_back(Chain);
11717 // We need to be careful here to also search for aliases through the
11718 // value operand of a store, etc. Consider the following situation:
11720 // L1 = load Token1, %52
11721 // S1 = store Token1, L1, %51
11722 // L2 = load Token1, %52+8
11723 // S2 = store Token1, L2, %51+8
11724 // Token2 = Token(S1, S2)
11725 // L3 = load Token2, %53
11726 // S3 = store Token2, L3, %52
11727 // L4 = load Token2, %53+8
11728 // S4 = store Token2, L4, %52+8
11729 // If we search for aliases of S3 (which loads address %52), and we look
11730 // only through the chain, then we'll miss the trivial dependence on L1
11731 // (which also loads from %52). We then might change all loads and
11732 // stores to use Token1 as their chain operand, which could result in
11733 // copying %53 into %52 before copying %52 into %51 (which should
11736 // The problem is, however, that searching for such data dependencies
11737 // can become expensive, and the cost is not directly related to the
11738 // chain depth. Instead, we'll rule out such configurations here by
11739 // insisting that we've visited all chain users (except for users
11740 // of the original chain, which is not necessary). When doing this,
11741 // we need to look through nodes we don't care about (otherwise, things
11742 // like register copies will interfere with trivial cases).
11744 SmallVector<const SDNode *, 16> Worklist;
11745 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11746 IE = Visited.end(); I != IE; ++I)
11747 if (*I != OriginalChain.getNode())
11748 Worklist.push_back(*I);
11750 while (!Worklist.empty()) {
11751 const SDNode *M = Worklist.pop_back_val();
11753 // We have already visited M, and want to make sure we've visited any uses
11754 // of M that we care about. For uses that we've not visisted, and don't
11755 // care about, queue them to the worklist.
11757 for (SDNode::use_iterator UI = M->use_begin(),
11758 UIE = M->use_end(); UI != UIE; ++UI)
11759 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11760 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11761 // We've not visited this use, and we care about it (it could have an
11762 // ordering dependency with the original node).
11764 Aliases.push_back(OriginalChain);
11768 // We've not visited this use, but we don't care about it. Mark it as
11769 // visited and enqueue it to the worklist.
11770 Worklist.push_back(*UI);
11775 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11776 /// for a better chain (aliasing node.)
11777 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11778 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
11780 // Accumulate all the aliases to this node.
11781 GatherAllAliases(N, OldChain, Aliases);
11783 // If no operands then chain to entry token.
11784 if (Aliases.size() == 0)
11785 return DAG.getEntryNode();
11787 // If a single operand then chain to it. We don't need to revisit it.
11788 if (Aliases.size() == 1)
11791 // Construct a custom tailored token factor.
11792 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
11795 // SelectionDAG::Combine - This is the entry point for the file.
11797 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11798 CodeGenOpt::Level OptLevel) {
11799 /// run - This is the main entry point to this class.
11801 DAGCombiner(*this, AA, OptLevel).Run(Level);