1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run
11 // both before and after the DAG is legalized.
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
17 //===----------------------------------------------------------------------===//
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetLowering.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Target/TargetOptions.h"
37 #include "llvm/Target/TargetRegisterInfo.h"
38 #include "llvm/Target/TargetSubtargetInfo.h"
42 #define DEBUG_TYPE "dagcombine"
44 STATISTIC(NodesCombined , "Number of dag nodes combined");
45 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
46 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
47 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
48 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
49 STATISTIC(SlicedLoads, "Number of load sliced");
53 CombinerAA("combiner-alias-analysis", cl::Hidden,
54 cl::desc("Enable DAG combiner alias-analysis heuristics"));
57 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
58 cl::desc("Enable DAG combiner's use of IR alias analysis"));
61 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
62 cl::desc("Enable DAG combiner's use of TBAA"));
65 static cl::opt<std::string>
66 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
67 cl::desc("Only use DAG-combiner alias analysis in this"
71 /// Hidden option to stress test load slicing, i.e., when this option
72 /// is enabled, load slicing bypasses most of its profitability guards.
74 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
75 cl::desc("Bypass the profitability model of load "
79 //------------------------------ DAGCombiner ---------------------------------//
83 const TargetLowering &TLI;
85 CodeGenOpt::Level OptLevel;
90 // Worklist of all of the nodes that need to be simplified.
92 // This has the semantics that when adding to the worklist,
93 // the item added must be next to be processed. It should
94 // also only appear once. The naive approach to this takes
97 // To reduce the insert/remove time to logarithmic, we use
98 // a set and a vector to maintain our worklist.
100 // The set contains the items on the worklist, but does not
101 // maintain the order they should be visited.
103 // The vector maintains the order nodes should be visited, but may
104 // contain duplicate or removed nodes. When choosing a node to
105 // visit, we pop off the order stack until we find an item that is
106 // also in the contents set. All operations are O(log N).
107 SmallPtrSet<SDNode*, 64> WorkListContents;
108 SmallVector<SDNode*, 64> WorkListOrder;
110 // AA - Used for DAG load/store alias analysis.
113 /// AddUsersToWorkList - When an instruction is simplified, add all users of
114 /// the instruction to the work lists because they might get more simplified
117 void AddUsersToWorkList(SDNode *N) {
118 for (SDNode *Node : N->uses())
122 /// visit - call the node-specific routine that knows how to fold each
123 /// particular type of node.
124 SDValue visit(SDNode *N);
127 /// AddToWorkList - Add to the work list making sure its instance is at the
128 /// back (next to be processed.)
129 void AddToWorkList(SDNode *N) {
130 WorkListContents.insert(N);
131 WorkListOrder.push_back(N);
134 /// removeFromWorkList - remove all instances of N from the worklist.
136 void removeFromWorkList(SDNode *N) {
137 WorkListContents.erase(N);
140 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
143 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
144 return CombineTo(N, &Res, 1, AddTo);
147 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
149 SDValue To[] = { Res0, Res1 };
150 return CombineTo(N, To, 2, AddTo);
153 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
157 /// SimplifyDemandedBits - Check the specified integer node value to see if
158 /// it can be simplified or if things it uses can be simplified by bit
159 /// propagation. If so, return true.
160 bool SimplifyDemandedBits(SDValue Op) {
161 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
162 APInt Demanded = APInt::getAllOnesValue(BitWidth);
163 return SimplifyDemandedBits(Op, Demanded);
166 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
168 bool CombineToPreIndexedLoadStore(SDNode *N);
169 bool CombineToPostIndexedLoadStore(SDNode *N);
170 bool SliceUpLoad(SDNode *N);
172 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
173 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
174 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
175 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
176 SDValue PromoteIntBinOp(SDValue Op);
177 SDValue PromoteIntShiftOp(SDValue Op);
178 SDValue PromoteExtend(SDValue Op);
179 bool PromoteLoad(SDValue Op);
181 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
182 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
183 ISD::NodeType ExtType);
185 /// combine - call the node-specific routine that knows how to fold each
186 /// particular type of node. If that doesn't do anything, try the
187 /// target-specific DAG combines.
188 SDValue combine(SDNode *N);
190 // Visitation implementation - Implement dag node combining for different
191 // node types. The semantics are as follows:
193 // SDValue.getNode() == 0 - No change was made
194 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
195 // otherwise - N should be replaced by the returned Operand.
197 SDValue visitTokenFactor(SDNode *N);
198 SDValue visitMERGE_VALUES(SDNode *N);
199 SDValue visitADD(SDNode *N);
200 SDValue visitSUB(SDNode *N);
201 SDValue visitADDC(SDNode *N);
202 SDValue visitSUBC(SDNode *N);
203 SDValue visitADDE(SDNode *N);
204 SDValue visitSUBE(SDNode *N);
205 SDValue visitMUL(SDNode *N);
206 SDValue visitSDIV(SDNode *N);
207 SDValue visitUDIV(SDNode *N);
208 SDValue visitSREM(SDNode *N);
209 SDValue visitUREM(SDNode *N);
210 SDValue visitMULHU(SDNode *N);
211 SDValue visitMULHS(SDNode *N);
212 SDValue visitSMUL_LOHI(SDNode *N);
213 SDValue visitUMUL_LOHI(SDNode *N);
214 SDValue visitSMULO(SDNode *N);
215 SDValue visitUMULO(SDNode *N);
216 SDValue visitSDIVREM(SDNode *N);
217 SDValue visitUDIVREM(SDNode *N);
218 SDValue visitAND(SDNode *N);
219 SDValue visitOR(SDNode *N);
220 SDValue visitXOR(SDNode *N);
221 SDValue SimplifyVBinOp(SDNode *N);
222 SDValue SimplifyVUnaryOp(SDNode *N);
223 SDValue visitSHL(SDNode *N);
224 SDValue visitSRA(SDNode *N);
225 SDValue visitSRL(SDNode *N);
226 SDValue visitRotate(SDNode *N);
227 SDValue visitCTLZ(SDNode *N);
228 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
229 SDValue visitCTTZ(SDNode *N);
230 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
231 SDValue visitCTPOP(SDNode *N);
232 SDValue visitSELECT(SDNode *N);
233 SDValue visitVSELECT(SDNode *N);
234 SDValue visitSELECT_CC(SDNode *N);
235 SDValue visitSETCC(SDNode *N);
236 SDValue visitSIGN_EXTEND(SDNode *N);
237 SDValue visitZERO_EXTEND(SDNode *N);
238 SDValue visitANY_EXTEND(SDNode *N);
239 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
240 SDValue visitTRUNCATE(SDNode *N);
241 SDValue visitBITCAST(SDNode *N);
242 SDValue visitBUILD_PAIR(SDNode *N);
243 SDValue visitFADD(SDNode *N);
244 SDValue visitFSUB(SDNode *N);
245 SDValue visitFMUL(SDNode *N);
246 SDValue visitFMA(SDNode *N);
247 SDValue visitFDIV(SDNode *N);
248 SDValue visitFREM(SDNode *N);
249 SDValue visitFCOPYSIGN(SDNode *N);
250 SDValue visitSINT_TO_FP(SDNode *N);
251 SDValue visitUINT_TO_FP(SDNode *N);
252 SDValue visitFP_TO_SINT(SDNode *N);
253 SDValue visitFP_TO_UINT(SDNode *N);
254 SDValue visitFP_ROUND(SDNode *N);
255 SDValue visitFP_ROUND_INREG(SDNode *N);
256 SDValue visitFP_EXTEND(SDNode *N);
257 SDValue visitFNEG(SDNode *N);
258 SDValue visitFABS(SDNode *N);
259 SDValue visitFCEIL(SDNode *N);
260 SDValue visitFTRUNC(SDNode *N);
261 SDValue visitFFLOOR(SDNode *N);
262 SDValue visitBRCOND(SDNode *N);
263 SDValue visitBR_CC(SDNode *N);
264 SDValue visitLOAD(SDNode *N);
265 SDValue visitSTORE(SDNode *N);
266 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
267 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
268 SDValue visitBUILD_VECTOR(SDNode *N);
269 SDValue visitCONCAT_VECTORS(SDNode *N);
270 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
271 SDValue visitVECTOR_SHUFFLE(SDNode *N);
272 SDValue visitINSERT_SUBVECTOR(SDNode *N);
274 SDValue XformToShuffleWithZero(SDNode *N);
275 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
277 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
279 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
280 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
281 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
282 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
283 SDValue N3, ISD::CondCode CC,
284 bool NotExtCompare = false);
285 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
286 SDLoc DL, bool foldBooleans = true);
288 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
290 bool isOneUseSetCC(SDValue N) const;
292 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
294 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
295 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
296 SDValue BuildSDIV(SDNode *N);
297 SDValue BuildUDIV(SDNode *N);
298 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
299 bool DemandHighBits = true);
300 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
301 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
302 SDValue InnerPos, SDValue InnerNeg,
303 unsigned PosOpcode, unsigned NegOpcode,
305 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
306 SDValue ReduceLoadWidth(SDNode *N);
307 SDValue ReduceLoadOpStoreWidth(SDNode *N);
308 SDValue TransformFPLoadStorePair(SDNode *N);
309 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
310 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
312 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
314 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
315 /// looking for aliasing nodes and adding them to the Aliases vector.
316 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
317 SmallVectorImpl<SDValue> &Aliases);
319 /// isAlias - Return true if there is any possibility that the two addresses
321 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
323 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
324 /// looking for a better chain (aliasing node.)
325 SDValue FindBetterChain(SDNode *N, SDValue Chain);
327 /// Merge consecutive store operations into a wide store.
328 /// This optimization uses wide integers or vectors when possible.
329 /// \return True if some memory operations were changed.
330 bool MergeConsecutiveStores(StoreSDNode *N);
332 /// \brief Try to transform a truncation where C is a constant:
333 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
335 /// \p N needs to be a truncation and its first operand an AND. Other
336 /// requirements are checked by the function (e.g. that trunc is
337 /// single-use) and if missed an empty SDValue is returned.
338 SDValue distributeTruncateThroughAnd(SDNode *N);
341 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
342 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
343 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
344 AttributeSet FnAttrs =
345 DAG.getMachineFunction().getFunction()->getAttributes();
347 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
348 Attribute::OptimizeForSize) ||
349 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
352 /// Run - runs the dag combiner on all nodes in the work list
353 void Run(CombineLevel AtLevel);
355 SelectionDAG &getDAG() const { return DAG; }
357 /// getShiftAmountTy - Returns a type large enough to hold any valid
358 /// shift amount - before type legalization these can be huge.
359 EVT getShiftAmountTy(EVT LHSTy) {
360 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
361 if (LHSTy.isVector())
363 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
364 : TLI.getPointerTy();
367 /// isTypeLegal - This method returns true if we are running before type
368 /// legalization or if the specified VT is legal.
369 bool isTypeLegal(const EVT &VT) {
370 if (!LegalTypes) return true;
371 return TLI.isTypeLegal(VT);
374 /// getSetCCResultType - Convenience wrapper around
375 /// TargetLowering::getSetCCResultType
376 EVT getSetCCResultType(EVT VT) const {
377 return TLI.getSetCCResultType(*DAG.getContext(), VT);
384 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
385 /// nodes from the worklist.
386 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
389 explicit WorkListRemover(DAGCombiner &dc)
390 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
392 void NodeDeleted(SDNode *N, SDNode *E) override {
393 DC.removeFromWorkList(N);
398 //===----------------------------------------------------------------------===//
399 // TargetLowering::DAGCombinerInfo implementation
400 //===----------------------------------------------------------------------===//
402 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
403 ((DAGCombiner*)DC)->AddToWorkList(N);
406 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
407 ((DAGCombiner*)DC)->removeFromWorkList(N);
410 SDValue TargetLowering::DAGCombinerInfo::
411 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
412 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
415 SDValue TargetLowering::DAGCombinerInfo::
416 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
417 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
421 SDValue TargetLowering::DAGCombinerInfo::
422 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
423 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
426 void TargetLowering::DAGCombinerInfo::
427 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
428 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
431 //===----------------------------------------------------------------------===//
433 //===----------------------------------------------------------------------===//
435 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
436 /// specified expression for the same cost as the expression itself, or 2 if we
437 /// can compute the negated form more cheaply than the expression itself.
438 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
439 const TargetLowering &TLI,
440 const TargetOptions *Options,
441 unsigned Depth = 0) {
442 // fneg is removable even if it has multiple uses.
443 if (Op.getOpcode() == ISD::FNEG) return 2;
445 // Don't allow anything with multiple uses.
446 if (!Op.hasOneUse()) return 0;
448 // Don't recurse exponentially.
449 if (Depth > 6) return 0;
451 switch (Op.getOpcode()) {
452 default: return false;
453 case ISD::ConstantFP:
454 // Don't invert constant FP values after legalize. The negated constant
455 // isn't necessarily legal.
456 return LegalOperations ? 0 : 1;
458 // FIXME: determine better conditions for this xform.
459 if (!Options->UnsafeFPMath) return 0;
461 // After operation legalization, it might not be legal to create new FSUBs.
462 if (LegalOperations &&
463 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
466 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
467 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
470 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
471 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
474 // We can't turn -(A-B) into B-A when we honor signed zeros.
475 if (!Options->UnsafeFPMath) return 0;
477 // fold (fneg (fsub A, B)) -> (fsub B, A)
482 if (Options->HonorSignDependentRoundingFPMath()) return 0;
484 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
485 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
489 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
495 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
500 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
501 /// returns the newly negated expression.
502 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
503 bool LegalOperations, unsigned Depth = 0) {
504 // fneg is removable even if it has multiple uses.
505 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
507 // Don't allow anything with multiple uses.
508 assert(Op.hasOneUse() && "Unknown reuse!");
510 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
511 switch (Op.getOpcode()) {
512 default: llvm_unreachable("Unknown code");
513 case ISD::ConstantFP: {
514 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
516 return DAG.getConstantFP(V, Op.getValueType());
519 // FIXME: determine better conditions for this xform.
520 assert(DAG.getTarget().Options.UnsafeFPMath);
522 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
523 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
524 DAG.getTargetLoweringInfo(),
525 &DAG.getTarget().Options, Depth+1))
526 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
527 GetNegatedExpression(Op.getOperand(0), DAG,
528 LegalOperations, Depth+1),
530 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
531 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
532 GetNegatedExpression(Op.getOperand(1), DAG,
533 LegalOperations, Depth+1),
536 // We can't turn -(A-B) into B-A when we honor signed zeros.
537 assert(DAG.getTarget().Options.UnsafeFPMath);
539 // fold (fneg (fsub 0, B)) -> B
540 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
541 if (N0CFP->getValueAPF().isZero())
542 return Op.getOperand(1);
544 // fold (fneg (fsub A, B)) -> (fsub B, A)
545 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
546 Op.getOperand(1), Op.getOperand(0));
550 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
552 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
553 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
554 DAG.getTargetLoweringInfo(),
555 &DAG.getTarget().Options, Depth+1))
556 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
557 GetNegatedExpression(Op.getOperand(0), DAG,
558 LegalOperations, Depth+1),
561 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
562 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
564 GetNegatedExpression(Op.getOperand(1), DAG,
565 LegalOperations, Depth+1));
569 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
570 GetNegatedExpression(Op.getOperand(0), DAG,
571 LegalOperations, Depth+1));
573 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
574 GetNegatedExpression(Op.getOperand(0), DAG,
575 LegalOperations, Depth+1),
580 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
581 // that selects between the target values used for true and false, making it
582 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
583 // the appropriate nodes based on the type of node we are checking. This
584 // simplifies life a bit for the callers.
585 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
587 if (N.getOpcode() == ISD::SETCC) {
588 LHS = N.getOperand(0);
589 RHS = N.getOperand(1);
590 CC = N.getOperand(2);
594 if (N.getOpcode() != ISD::SELECT_CC ||
595 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
596 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
599 LHS = N.getOperand(0);
600 RHS = N.getOperand(1);
601 CC = N.getOperand(4);
605 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
606 // one use. If this is true, it allows the users to invert the operation for
607 // free when it is profitable to do so.
608 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
610 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
615 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
616 /// elements are all the same constant or undefined.
617 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
618 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
623 unsigned SplatBitSize;
625 EVT EltVT = N->getValueType(0).getVectorElementType();
626 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
628 EltVT.getSizeInBits() >= SplatBitSize);
631 // \brief Returns the SDNode if it is a constant BuildVector or constant.
632 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
633 if (isa<ConstantSDNode>(N))
635 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
636 if(BV && BV->isConstant())
641 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
643 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
644 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
647 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N))
648 return BV->getConstantSplatValue();
653 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
654 SDValue N0, SDValue N1) {
655 EVT VT = N0.getValueType();
656 if (N0.getOpcode() == Opc) {
657 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
658 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
659 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
660 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
661 if (!OpNode.getNode())
663 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
665 if (N0.hasOneUse()) {
666 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
668 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
669 if (!OpNode.getNode())
671 AddToWorkList(OpNode.getNode());
672 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
677 if (N1.getOpcode() == Opc) {
678 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
679 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
680 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
681 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
682 if (!OpNode.getNode())
684 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
686 if (N1.hasOneUse()) {
687 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
689 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
690 if (!OpNode.getNode())
692 AddToWorkList(OpNode.getNode());
693 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
701 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
703 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
705 DEBUG(dbgs() << "\nReplacing.1 ";
707 dbgs() << "\nWith: ";
708 To[0].getNode()->dump(&DAG);
709 dbgs() << " and " << NumTo-1 << " other values\n";
710 for (unsigned i = 0, e = NumTo; i != e; ++i)
711 assert((!To[i].getNode() ||
712 N->getValueType(i) == To[i].getValueType()) &&
713 "Cannot combine value to value of different type!"));
714 WorkListRemover DeadNodes(*this);
715 DAG.ReplaceAllUsesWith(N, To);
717 // Push the new nodes and any users onto the worklist
718 for (unsigned i = 0, e = NumTo; i != e; ++i) {
719 if (To[i].getNode()) {
720 AddToWorkList(To[i].getNode());
721 AddUsersToWorkList(To[i].getNode());
726 // Finally, if the node is now dead, remove it from the graph. The node
727 // may not be dead if the replacement process recursively simplified to
728 // something else needing this node.
729 if (N->use_empty()) {
730 // Nodes can be reintroduced into the worklist. Make sure we do not
731 // process a node that has been replaced.
732 removeFromWorkList(N);
734 // Finally, since the node is now dead, remove it from the graph.
737 return SDValue(N, 0);
741 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
742 // Replace all uses. If any nodes become isomorphic to other nodes and
743 // are deleted, make sure to remove them from our worklist.
744 WorkListRemover DeadNodes(*this);
745 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
747 // Push the new node and any (possibly new) users onto the worklist.
748 AddToWorkList(TLO.New.getNode());
749 AddUsersToWorkList(TLO.New.getNode());
751 // Finally, if the node is now dead, remove it from the graph. The node
752 // may not be dead if the replacement process recursively simplified to
753 // something else needing this node.
754 if (TLO.Old.getNode()->use_empty()) {
755 removeFromWorkList(TLO.Old.getNode());
757 // If the operands of this node are only used by the node, they will now
758 // be dead. Make sure to visit them first to delete dead nodes early.
759 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
760 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
761 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
763 DAG.DeleteNode(TLO.Old.getNode());
767 /// SimplifyDemandedBits - Check the specified integer node value to see if
768 /// it can be simplified or if things it uses can be simplified by bit
769 /// propagation. If so, return true.
770 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
771 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
772 APInt KnownZero, KnownOne;
773 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
777 AddToWorkList(Op.getNode());
779 // Replace the old value with the new one.
781 DEBUG(dbgs() << "\nReplacing.2 ";
782 TLO.Old.getNode()->dump(&DAG);
783 dbgs() << "\nWith: ";
784 TLO.New.getNode()->dump(&DAG);
787 CommitTargetLoweringOpt(TLO);
791 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
793 EVT VT = Load->getValueType(0);
794 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
796 DEBUG(dbgs() << "\nReplacing.9 ";
798 dbgs() << "\nWith: ";
799 Trunc.getNode()->dump(&DAG);
801 WorkListRemover DeadNodes(*this);
802 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
803 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
804 removeFromWorkList(Load);
805 DAG.DeleteNode(Load);
806 AddToWorkList(Trunc.getNode());
809 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
812 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
813 EVT MemVT = LD->getMemoryVT();
814 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
815 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
817 : LD->getExtensionType();
819 return DAG.getExtLoad(ExtType, dl, PVT,
820 LD->getChain(), LD->getBasePtr(),
821 MemVT, LD->getMemOperand());
824 unsigned Opc = Op.getOpcode();
827 case ISD::AssertSext:
828 return DAG.getNode(ISD::AssertSext, dl, PVT,
829 SExtPromoteOperand(Op.getOperand(0), PVT),
831 case ISD::AssertZext:
832 return DAG.getNode(ISD::AssertZext, dl, PVT,
833 ZExtPromoteOperand(Op.getOperand(0), PVT),
835 case ISD::Constant: {
837 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
838 return DAG.getNode(ExtOpc, dl, PVT, Op);
842 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
844 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
847 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
848 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
850 EVT OldVT = Op.getValueType();
852 bool Replace = false;
853 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
854 if (!NewOp.getNode())
856 AddToWorkList(NewOp.getNode());
859 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
860 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
861 DAG.getValueType(OldVT));
864 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
865 EVT OldVT = Op.getValueType();
867 bool Replace = false;
868 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
869 if (!NewOp.getNode())
871 AddToWorkList(NewOp.getNode());
874 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
875 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
878 /// PromoteIntBinOp - Promote the specified integer binary operation if the
879 /// target indicates it is beneficial. e.g. On x86, it's usually better to
880 /// promote i16 operations to i32 since i16 instructions are longer.
881 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
882 if (!LegalOperations)
885 EVT VT = Op.getValueType();
886 if (VT.isVector() || !VT.isInteger())
889 // If operation type is 'undesirable', e.g. i16 on x86, consider
891 unsigned Opc = Op.getOpcode();
892 if (TLI.isTypeDesirableForOp(Opc, VT))
896 // Consult target whether it is a good idea to promote this operation and
897 // what's the right type to promote it to.
898 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
899 assert(PVT != VT && "Don't know what type to promote to!");
901 bool Replace0 = false;
902 SDValue N0 = Op.getOperand(0);
903 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
907 bool Replace1 = false;
908 SDValue N1 = Op.getOperand(1);
913 NN1 = PromoteOperand(N1, PVT, Replace1);
918 AddToWorkList(NN0.getNode());
920 AddToWorkList(NN1.getNode());
923 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
925 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
927 DEBUG(dbgs() << "\nPromoting ";
928 Op.getNode()->dump(&DAG));
930 return DAG.getNode(ISD::TRUNCATE, dl, VT,
931 DAG.getNode(Opc, dl, PVT, NN0, NN1));
936 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
937 /// target indicates it is beneficial. e.g. On x86, it's usually better to
938 /// promote i16 operations to i32 since i16 instructions are longer.
939 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
940 if (!LegalOperations)
943 EVT VT = Op.getValueType();
944 if (VT.isVector() || !VT.isInteger())
947 // If operation type is 'undesirable', e.g. i16 on x86, consider
949 unsigned Opc = Op.getOpcode();
950 if (TLI.isTypeDesirableForOp(Opc, VT))
954 // Consult target whether it is a good idea to promote this operation and
955 // what's the right type to promote it to.
956 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
957 assert(PVT != VT && "Don't know what type to promote to!");
959 bool Replace = false;
960 SDValue N0 = Op.getOperand(0);
962 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
963 else if (Opc == ISD::SRL)
964 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
966 N0 = PromoteOperand(N0, PVT, Replace);
970 AddToWorkList(N0.getNode());
972 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
974 DEBUG(dbgs() << "\nPromoting ";
975 Op.getNode()->dump(&DAG));
977 return DAG.getNode(ISD::TRUNCATE, dl, VT,
978 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
983 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
984 if (!LegalOperations)
987 EVT VT = Op.getValueType();
988 if (VT.isVector() || !VT.isInteger())
991 // If operation type is 'undesirable', e.g. i16 on x86, consider
993 unsigned Opc = Op.getOpcode();
994 if (TLI.isTypeDesirableForOp(Opc, VT))
998 // Consult target whether it is a good idea to promote this operation and
999 // what's the right type to promote it to.
1000 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1001 assert(PVT != VT && "Don't know what type to promote to!");
1002 // fold (aext (aext x)) -> (aext x)
1003 // fold (aext (zext x)) -> (zext x)
1004 // fold (aext (sext x)) -> (sext x)
1005 DEBUG(dbgs() << "\nPromoting ";
1006 Op.getNode()->dump(&DAG));
1007 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1012 bool DAGCombiner::PromoteLoad(SDValue Op) {
1013 if (!LegalOperations)
1016 EVT VT = Op.getValueType();
1017 if (VT.isVector() || !VT.isInteger())
1020 // If operation type is 'undesirable', e.g. i16 on x86, consider
1022 unsigned Opc = Op.getOpcode();
1023 if (TLI.isTypeDesirableForOp(Opc, VT))
1027 // Consult target whether it is a good idea to promote this operation and
1028 // what's the right type to promote it to.
1029 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1030 assert(PVT != VT && "Don't know what type to promote to!");
1033 SDNode *N = Op.getNode();
1034 LoadSDNode *LD = cast<LoadSDNode>(N);
1035 EVT MemVT = LD->getMemoryVT();
1036 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1037 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1039 : LD->getExtensionType();
1040 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1041 LD->getChain(), LD->getBasePtr(),
1042 MemVT, LD->getMemOperand());
1043 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1045 DEBUG(dbgs() << "\nPromoting ";
1048 Result.getNode()->dump(&DAG);
1050 WorkListRemover DeadNodes(*this);
1051 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1052 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1053 removeFromWorkList(N);
1055 AddToWorkList(Result.getNode());
1062 //===----------------------------------------------------------------------===//
1063 // Main DAG Combiner implementation
1064 //===----------------------------------------------------------------------===//
1066 void DAGCombiner::Run(CombineLevel AtLevel) {
1067 // set the instance variables, so that the various visit routines may use it.
1069 LegalOperations = Level >= AfterLegalizeVectorOps;
1070 LegalTypes = Level >= AfterLegalizeTypes;
1072 // Add all the dag nodes to the worklist.
1073 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1074 E = DAG.allnodes_end(); I != E; ++I)
1077 // Create a dummy node (which is not added to allnodes), that adds a reference
1078 // to the root node, preventing it from being deleted, and tracking any
1079 // changes of the root.
1080 HandleSDNode Dummy(DAG.getRoot());
1082 // The root of the dag may dangle to deleted nodes until the dag combiner is
1083 // done. Set it to null to avoid confusion.
1084 DAG.setRoot(SDValue());
1086 // while the worklist isn't empty, find a node and
1087 // try and combine it.
1088 while (!WorkListContents.empty()) {
1090 // The WorkListOrder holds the SDNodes in order, but it may contain
1092 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1093 // worklist *should* contain, and check the node we want to visit is should
1094 // actually be visited.
1096 N = WorkListOrder.pop_back_val();
1097 } while (!WorkListContents.erase(N));
1099 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1100 // N is deleted from the DAG, since they too may now be dead or may have a
1101 // reduced number of uses, allowing other xforms.
1102 if (N->use_empty() && N != &Dummy) {
1103 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1104 AddToWorkList(N->getOperand(i).getNode());
1110 SDValue RV = combine(N);
1117 // If we get back the same node we passed in, rather than a new node or
1118 // zero, we know that the node must have defined multiple values and
1119 // CombineTo was used. Since CombineTo takes care of the worklist
1120 // mechanics for us, we have no work to do in this case.
1121 if (RV.getNode() == N)
1124 assert(N->getOpcode() != ISD::DELETED_NODE &&
1125 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1126 "Node was deleted but visit returned new node!");
1128 DEBUG(dbgs() << "\nReplacing.3 ";
1130 dbgs() << "\nWith: ";
1131 RV.getNode()->dump(&DAG);
1134 // Transfer debug value.
1135 DAG.TransferDbgValues(SDValue(N, 0), RV);
1136 WorkListRemover DeadNodes(*this);
1137 if (N->getNumValues() == RV.getNode()->getNumValues())
1138 DAG.ReplaceAllUsesWith(N, RV.getNode());
1140 assert(N->getValueType(0) == RV.getValueType() &&
1141 N->getNumValues() == 1 && "Type mismatch");
1143 DAG.ReplaceAllUsesWith(N, &OpV);
1146 // Push the new node and any users onto the worklist
1147 AddToWorkList(RV.getNode());
1148 AddUsersToWorkList(RV.getNode());
1150 // Add any uses of the old node to the worklist in case this node is the
1151 // last one that uses them. They may become dead after this node is
1153 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1154 AddToWorkList(N->getOperand(i).getNode());
1156 // Finally, if the node is now dead, remove it from the graph. The node
1157 // may not be dead if the replacement process recursively simplified to
1158 // something else needing this node.
1159 if (N->use_empty()) {
1160 // Nodes can be reintroduced into the worklist. Make sure we do not
1161 // process a node that has been replaced.
1162 removeFromWorkList(N);
1164 // Finally, since the node is now dead, remove it from the graph.
1169 // If the root changed (e.g. it was a dead load, update the root).
1170 DAG.setRoot(Dummy.getValue());
1171 DAG.RemoveDeadNodes();
1174 SDValue DAGCombiner::visit(SDNode *N) {
1175 switch (N->getOpcode()) {
1177 case ISD::TokenFactor: return visitTokenFactor(N);
1178 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1179 case ISD::ADD: return visitADD(N);
1180 case ISD::SUB: return visitSUB(N);
1181 case ISD::ADDC: return visitADDC(N);
1182 case ISD::SUBC: return visitSUBC(N);
1183 case ISD::ADDE: return visitADDE(N);
1184 case ISD::SUBE: return visitSUBE(N);
1185 case ISD::MUL: return visitMUL(N);
1186 case ISD::SDIV: return visitSDIV(N);
1187 case ISD::UDIV: return visitUDIV(N);
1188 case ISD::SREM: return visitSREM(N);
1189 case ISD::UREM: return visitUREM(N);
1190 case ISD::MULHU: return visitMULHU(N);
1191 case ISD::MULHS: return visitMULHS(N);
1192 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1193 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1194 case ISD::SMULO: return visitSMULO(N);
1195 case ISD::UMULO: return visitUMULO(N);
1196 case ISD::SDIVREM: return visitSDIVREM(N);
1197 case ISD::UDIVREM: return visitUDIVREM(N);
1198 case ISD::AND: return visitAND(N);
1199 case ISD::OR: return visitOR(N);
1200 case ISD::XOR: return visitXOR(N);
1201 case ISD::SHL: return visitSHL(N);
1202 case ISD::SRA: return visitSRA(N);
1203 case ISD::SRL: return visitSRL(N);
1205 case ISD::ROTL: return visitRotate(N);
1206 case ISD::CTLZ: return visitCTLZ(N);
1207 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1208 case ISD::CTTZ: return visitCTTZ(N);
1209 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1210 case ISD::CTPOP: return visitCTPOP(N);
1211 case ISD::SELECT: return visitSELECT(N);
1212 case ISD::VSELECT: return visitVSELECT(N);
1213 case ISD::SELECT_CC: return visitSELECT_CC(N);
1214 case ISD::SETCC: return visitSETCC(N);
1215 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1216 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1217 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1218 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1219 case ISD::TRUNCATE: return visitTRUNCATE(N);
1220 case ISD::BITCAST: return visitBITCAST(N);
1221 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1222 case ISD::FADD: return visitFADD(N);
1223 case ISD::FSUB: return visitFSUB(N);
1224 case ISD::FMUL: return visitFMUL(N);
1225 case ISD::FMA: return visitFMA(N);
1226 case ISD::FDIV: return visitFDIV(N);
1227 case ISD::FREM: return visitFREM(N);
1228 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1229 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1230 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1231 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1232 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1233 case ISD::FP_ROUND: return visitFP_ROUND(N);
1234 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1235 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1236 case ISD::FNEG: return visitFNEG(N);
1237 case ISD::FABS: return visitFABS(N);
1238 case ISD::FFLOOR: return visitFFLOOR(N);
1239 case ISD::FCEIL: return visitFCEIL(N);
1240 case ISD::FTRUNC: return visitFTRUNC(N);
1241 case ISD::BRCOND: return visitBRCOND(N);
1242 case ISD::BR_CC: return visitBR_CC(N);
1243 case ISD::LOAD: return visitLOAD(N);
1244 case ISD::STORE: return visitSTORE(N);
1245 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1246 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1247 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1248 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1249 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1250 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1251 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1256 SDValue DAGCombiner::combine(SDNode *N) {
1257 SDValue RV = visit(N);
1259 // If nothing happened, try a target-specific DAG combine.
1260 if (!RV.getNode()) {
1261 assert(N->getOpcode() != ISD::DELETED_NODE &&
1262 "Node was deleted but visit returned NULL!");
1264 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1265 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1267 // Expose the DAG combiner to the target combiner impls.
1268 TargetLowering::DAGCombinerInfo
1269 DagCombineInfo(DAG, Level, false, this);
1271 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1275 // If nothing happened still, try promoting the operation.
1276 if (!RV.getNode()) {
1277 switch (N->getOpcode()) {
1285 RV = PromoteIntBinOp(SDValue(N, 0));
1290 RV = PromoteIntShiftOp(SDValue(N, 0));
1292 case ISD::SIGN_EXTEND:
1293 case ISD::ZERO_EXTEND:
1294 case ISD::ANY_EXTEND:
1295 RV = PromoteExtend(SDValue(N, 0));
1298 if (PromoteLoad(SDValue(N, 0)))
1304 // If N is a commutative binary node, try commuting it to enable more
1306 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1307 N->getNumValues() == 1) {
1308 SDValue N0 = N->getOperand(0);
1309 SDValue N1 = N->getOperand(1);
1311 // Constant operands are canonicalized to RHS.
1312 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1313 SDValue Ops[] = { N1, N0 };
1314 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1317 return SDValue(CSENode, 0);
1324 /// getInputChainForNode - Given a node, return its input chain if it has one,
1325 /// otherwise return a null sd operand.
1326 static SDValue getInputChainForNode(SDNode *N) {
1327 if (unsigned NumOps = N->getNumOperands()) {
1328 if (N->getOperand(0).getValueType() == MVT::Other)
1329 return N->getOperand(0);
1330 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1331 return N->getOperand(NumOps-1);
1332 for (unsigned i = 1; i < NumOps-1; ++i)
1333 if (N->getOperand(i).getValueType() == MVT::Other)
1334 return N->getOperand(i);
1339 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1340 // If N has two operands, where one has an input chain equal to the other,
1341 // the 'other' chain is redundant.
1342 if (N->getNumOperands() == 2) {
1343 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1344 return N->getOperand(0);
1345 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1346 return N->getOperand(1);
1349 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1350 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1351 SmallPtrSet<SDNode*, 16> SeenOps;
1352 bool Changed = false; // If we should replace this token factor.
1354 // Start out with this token factor.
1357 // Iterate through token factors. The TFs grows when new token factors are
1359 for (unsigned i = 0; i < TFs.size(); ++i) {
1360 SDNode *TF = TFs[i];
1362 // Check each of the operands.
1363 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1364 SDValue Op = TF->getOperand(i);
1366 switch (Op.getOpcode()) {
1367 case ISD::EntryToken:
1368 // Entry tokens don't need to be added to the list. They are
1373 case ISD::TokenFactor:
1374 if (Op.hasOneUse() &&
1375 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1376 // Queue up for processing.
1377 TFs.push_back(Op.getNode());
1378 // Clean up in case the token factor is removed.
1379 AddToWorkList(Op.getNode());
1386 // Only add if it isn't already in the list.
1387 if (SeenOps.insert(Op.getNode()))
1398 // If we've change things around then replace token factor.
1401 // The entry token is the only possible outcome.
1402 Result = DAG.getEntryNode();
1404 // New and improved token factor.
1405 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1408 // Don't add users to work list.
1409 return CombineTo(N, Result, false);
1415 /// MERGE_VALUES can always be eliminated.
1416 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1417 WorkListRemover DeadNodes(*this);
1418 // Replacing results may cause a different MERGE_VALUES to suddenly
1419 // be CSE'd with N, and carry its uses with it. Iterate until no
1420 // uses remain, to ensure that the node can be safely deleted.
1421 // First add the users of this node to the work list so that they
1422 // can be tried again once they have new operands.
1423 AddUsersToWorkList(N);
1425 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1426 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1427 } while (!N->use_empty());
1428 removeFromWorkList(N);
1430 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1434 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1435 SelectionDAG &DAG) {
1436 EVT VT = N0.getValueType();
1437 SDValue N00 = N0.getOperand(0);
1438 SDValue N01 = N0.getOperand(1);
1439 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1441 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1442 isa<ConstantSDNode>(N00.getOperand(1))) {
1443 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1444 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1445 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1446 N00.getOperand(0), N01),
1447 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1448 N00.getOperand(1), N01));
1449 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1455 SDValue DAGCombiner::visitADD(SDNode *N) {
1456 SDValue N0 = N->getOperand(0);
1457 SDValue N1 = N->getOperand(1);
1458 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1459 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1460 EVT VT = N0.getValueType();
1463 if (VT.isVector()) {
1464 SDValue FoldedVOp = SimplifyVBinOp(N);
1465 if (FoldedVOp.getNode()) return FoldedVOp;
1467 // fold (add x, 0) -> x, vector edition
1468 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1470 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1474 // fold (add x, undef) -> undef
1475 if (N0.getOpcode() == ISD::UNDEF)
1477 if (N1.getOpcode() == ISD::UNDEF)
1479 // fold (add c1, c2) -> c1+c2
1481 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1482 // canonicalize constant to RHS
1484 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1485 // fold (add x, 0) -> x
1486 if (N1C && N1C->isNullValue())
1488 // fold (add Sym, c) -> Sym+c
1489 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1490 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1491 GA->getOpcode() == ISD::GlobalAddress)
1492 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1494 (uint64_t)N1C->getSExtValue());
1495 // fold ((c1-A)+c2) -> (c1+c2)-A
1496 if (N1C && N0.getOpcode() == ISD::SUB)
1497 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1498 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1499 DAG.getConstant(N1C->getAPIntValue()+
1500 N0C->getAPIntValue(), VT),
1503 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1506 // fold ((0-A) + B) -> B-A
1507 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1508 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1509 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1510 // fold (A + (0-B)) -> A-B
1511 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1512 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1513 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1514 // fold (A+(B-A)) -> B
1515 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1516 return N1.getOperand(0);
1517 // fold ((B-A)+A) -> B
1518 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1519 return N0.getOperand(0);
1520 // fold (A+(B-(A+C))) to (B-C)
1521 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1522 N0 == N1.getOperand(1).getOperand(0))
1523 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1524 N1.getOperand(1).getOperand(1));
1525 // fold (A+(B-(C+A))) to (B-C)
1526 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1527 N0 == N1.getOperand(1).getOperand(1))
1528 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1529 N1.getOperand(1).getOperand(0));
1530 // fold (A+((B-A)+or-C)) to (B+or-C)
1531 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1532 N1.getOperand(0).getOpcode() == ISD::SUB &&
1533 N0 == N1.getOperand(0).getOperand(1))
1534 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1535 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1537 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1538 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1539 SDValue N00 = N0.getOperand(0);
1540 SDValue N01 = N0.getOperand(1);
1541 SDValue N10 = N1.getOperand(0);
1542 SDValue N11 = N1.getOperand(1);
1544 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1545 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1546 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1547 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1550 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1551 return SDValue(N, 0);
1553 // fold (a+b) -> (a|b) iff a and b share no bits.
1554 if (VT.isInteger() && !VT.isVector()) {
1555 APInt LHSZero, LHSOne;
1556 APInt RHSZero, RHSOne;
1557 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1559 if (LHSZero.getBoolValue()) {
1560 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1562 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1563 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1564 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1565 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1566 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1571 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1572 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1573 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1574 if (Result.getNode()) return Result;
1576 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1577 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1578 if (Result.getNode()) return Result;
1581 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1582 if (N1.getOpcode() == ISD::SHL &&
1583 N1.getOperand(0).getOpcode() == ISD::SUB)
1584 if (ConstantSDNode *C =
1585 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1586 if (C->getAPIntValue() == 0)
1587 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1588 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1589 N1.getOperand(0).getOperand(1),
1591 if (N0.getOpcode() == ISD::SHL &&
1592 N0.getOperand(0).getOpcode() == ISD::SUB)
1593 if (ConstantSDNode *C =
1594 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1595 if (C->getAPIntValue() == 0)
1596 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1597 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1598 N0.getOperand(0).getOperand(1),
1601 if (N1.getOpcode() == ISD::AND) {
1602 SDValue AndOp0 = N1.getOperand(0);
1603 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1604 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1605 unsigned DestBits = VT.getScalarType().getSizeInBits();
1607 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1608 // and similar xforms where the inner op is either ~0 or 0.
1609 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1611 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1615 // add (sext i1), X -> sub X, (zext i1)
1616 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1617 N0.getOperand(0).getValueType() == MVT::i1 &&
1618 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1620 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1621 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1627 SDValue DAGCombiner::visitADDC(SDNode *N) {
1628 SDValue N0 = N->getOperand(0);
1629 SDValue N1 = N->getOperand(1);
1630 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1631 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1632 EVT VT = N0.getValueType();
1634 // If the flag result is dead, turn this into an ADD.
1635 if (!N->hasAnyUseOfValue(1))
1636 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1637 DAG.getNode(ISD::CARRY_FALSE,
1638 SDLoc(N), MVT::Glue));
1640 // canonicalize constant to RHS.
1642 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1644 // fold (addc x, 0) -> x + no carry out
1645 if (N1C && N1C->isNullValue())
1646 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1647 SDLoc(N), MVT::Glue));
1649 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1650 APInt LHSZero, LHSOne;
1651 APInt RHSZero, RHSOne;
1652 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1654 if (LHSZero.getBoolValue()) {
1655 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1657 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1658 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1659 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1660 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1661 DAG.getNode(ISD::CARRY_FALSE,
1662 SDLoc(N), MVT::Glue));
1668 SDValue DAGCombiner::visitADDE(SDNode *N) {
1669 SDValue N0 = N->getOperand(0);
1670 SDValue N1 = N->getOperand(1);
1671 SDValue CarryIn = N->getOperand(2);
1672 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1673 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1675 // canonicalize constant to RHS
1677 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1680 // fold (adde x, y, false) -> (addc x, y)
1681 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1682 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1687 // Since it may not be valid to emit a fold to zero for vector initializers
1688 // check if we can before folding.
1689 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1691 bool LegalOperations, bool LegalTypes) {
1693 return DAG.getConstant(0, VT);
1694 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1695 return DAG.getConstant(0, VT);
1699 SDValue DAGCombiner::visitSUB(SDNode *N) {
1700 SDValue N0 = N->getOperand(0);
1701 SDValue N1 = N->getOperand(1);
1702 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1703 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1704 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1705 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1706 EVT VT = N0.getValueType();
1709 if (VT.isVector()) {
1710 SDValue FoldedVOp = SimplifyVBinOp(N);
1711 if (FoldedVOp.getNode()) return FoldedVOp;
1713 // fold (sub x, 0) -> x, vector edition
1714 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1718 // fold (sub x, x) -> 0
1719 // FIXME: Refactor this and xor and other similar operations together.
1721 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1722 // fold (sub c1, c2) -> c1-c2
1724 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1725 // fold (sub x, c) -> (add x, -c)
1727 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1728 DAG.getConstant(-N1C->getAPIntValue(), VT));
1729 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1730 if (N0C && N0C->isAllOnesValue())
1731 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1732 // fold A-(A-B) -> B
1733 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1734 return N1.getOperand(1);
1735 // fold (A+B)-A -> B
1736 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1737 return N0.getOperand(1);
1738 // fold (A+B)-B -> A
1739 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1740 return N0.getOperand(0);
1741 // fold C2-(A+C1) -> (C2-C1)-A
1742 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1743 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1745 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1748 // fold ((A+(B+or-C))-B) -> A+or-C
1749 if (N0.getOpcode() == ISD::ADD &&
1750 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1751 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1752 N0.getOperand(1).getOperand(0) == N1)
1753 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1754 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1755 // fold ((A+(C+B))-B) -> A+C
1756 if (N0.getOpcode() == ISD::ADD &&
1757 N0.getOperand(1).getOpcode() == ISD::ADD &&
1758 N0.getOperand(1).getOperand(1) == N1)
1759 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1760 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1761 // fold ((A-(B-C))-C) -> A-B
1762 if (N0.getOpcode() == ISD::SUB &&
1763 N0.getOperand(1).getOpcode() == ISD::SUB &&
1764 N0.getOperand(1).getOperand(1) == N1)
1765 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1766 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1768 // If either operand of a sub is undef, the result is undef
1769 if (N0.getOpcode() == ISD::UNDEF)
1771 if (N1.getOpcode() == ISD::UNDEF)
1774 // If the relocation model supports it, consider symbol offsets.
1775 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1776 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1777 // fold (sub Sym, c) -> Sym-c
1778 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1779 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1781 (uint64_t)N1C->getSExtValue());
1782 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1783 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1784 if (GA->getGlobal() == GB->getGlobal())
1785 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1792 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1793 SDValue N0 = N->getOperand(0);
1794 SDValue N1 = N->getOperand(1);
1795 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1796 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1797 EVT VT = N0.getValueType();
1799 // If the flag result is dead, turn this into an SUB.
1800 if (!N->hasAnyUseOfValue(1))
1801 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1802 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1805 // fold (subc x, x) -> 0 + no borrow
1807 return CombineTo(N, DAG.getConstant(0, VT),
1808 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1811 // fold (subc x, 0) -> x + no borrow
1812 if (N1C && N1C->isNullValue())
1813 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1816 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1817 if (N0C && N0C->isAllOnesValue())
1818 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1819 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1825 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1826 SDValue N0 = N->getOperand(0);
1827 SDValue N1 = N->getOperand(1);
1828 SDValue CarryIn = N->getOperand(2);
1830 // fold (sube x, y, false) -> (subc x, y)
1831 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1832 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1837 SDValue DAGCombiner::visitMUL(SDNode *N) {
1838 SDValue N0 = N->getOperand(0);
1839 SDValue N1 = N->getOperand(1);
1840 EVT VT = N0.getValueType();
1842 // fold (mul x, undef) -> 0
1843 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1844 return DAG.getConstant(0, VT);
1846 bool N0IsConst = false;
1847 bool N1IsConst = false;
1848 APInt ConstValue0, ConstValue1;
1850 if (VT.isVector()) {
1851 SDValue FoldedVOp = SimplifyVBinOp(N);
1852 if (FoldedVOp.getNode()) return FoldedVOp;
1854 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1855 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1857 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1858 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1860 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1861 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1865 // fold (mul c1, c2) -> c1*c2
1866 if (N0IsConst && N1IsConst)
1867 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1869 // canonicalize constant to RHS
1870 if (N0IsConst && !N1IsConst)
1871 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1872 // fold (mul x, 0) -> 0
1873 if (N1IsConst && ConstValue1 == 0)
1875 // We require a splat of the entire scalar bit width for non-contiguous
1878 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1879 // fold (mul x, 1) -> x
1880 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1882 // fold (mul x, -1) -> 0-x
1883 if (N1IsConst && ConstValue1.isAllOnesValue())
1884 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1885 DAG.getConstant(0, VT), N0);
1886 // fold (mul x, (1 << c)) -> x << c
1887 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1888 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1889 DAG.getConstant(ConstValue1.logBase2(),
1890 getShiftAmountTy(N0.getValueType())));
1891 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1892 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1893 unsigned Log2Val = (-ConstValue1).logBase2();
1894 // FIXME: If the input is something that is easily negated (e.g. a
1895 // single-use add), we should put the negate there.
1896 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1897 DAG.getConstant(0, VT),
1898 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1899 DAG.getConstant(Log2Val,
1900 getShiftAmountTy(N0.getValueType()))));
1904 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1905 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1906 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1907 isa<ConstantSDNode>(N0.getOperand(1)))) {
1908 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1909 N1, N0.getOperand(1));
1910 AddToWorkList(C3.getNode());
1911 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1912 N0.getOperand(0), C3);
1915 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1918 SDValue Sh(nullptr,0), Y(nullptr,0);
1919 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1920 if (N0.getOpcode() == ISD::SHL &&
1921 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1922 isa<ConstantSDNode>(N0.getOperand(1))) &&
1923 N0.getNode()->hasOneUse()) {
1925 } else if (N1.getOpcode() == ISD::SHL &&
1926 isa<ConstantSDNode>(N1.getOperand(1)) &&
1927 N1.getNode()->hasOneUse()) {
1932 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1933 Sh.getOperand(0), Y);
1934 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1935 Mul, Sh.getOperand(1));
1939 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1940 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1941 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1942 isa<ConstantSDNode>(N0.getOperand(1))))
1943 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1944 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1945 N0.getOperand(0), N1),
1946 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1947 N0.getOperand(1), N1));
1950 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1957 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1958 SDValue N0 = N->getOperand(0);
1959 SDValue N1 = N->getOperand(1);
1960 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1961 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1962 EVT VT = N->getValueType(0);
1965 if (VT.isVector()) {
1966 SDValue FoldedVOp = SimplifyVBinOp(N);
1967 if (FoldedVOp.getNode()) return FoldedVOp;
1970 // fold (sdiv c1, c2) -> c1/c2
1971 if (N0C && N1C && !N1C->isNullValue())
1972 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1973 // fold (sdiv X, 1) -> X
1974 if (N1C && N1C->getAPIntValue() == 1LL)
1976 // fold (sdiv X, -1) -> 0-X
1977 if (N1C && N1C->isAllOnesValue())
1978 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1979 DAG.getConstant(0, VT), N0);
1980 // If we know the sign bits of both operands are zero, strength reduce to a
1981 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1982 if (!VT.isVector()) {
1983 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1984 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
1988 const APInt *Divisor = nullptr;
1990 Divisor = &N1C->getAPIntValue();
1991 } else if (N1.getValueType().isVector() &&
1992 N1->getOpcode() == ISD::BUILD_VECTOR) {
1993 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N->getOperand(1));
1994 if (ConstantSDNode *C = BV->getConstantSplatValue())
1995 Divisor = &C->getAPIntValue();
1998 // fold (sdiv X, pow2) -> simple ops after legalize
1999 if (Divisor && !!*Divisor &&
2000 (Divisor->isPowerOf2() || (-*Divisor).isPowerOf2())) {
2001 // If dividing by powers of two is cheap, then don't perform the following
2003 if (TLI.isPow2DivCheap())
2006 unsigned lg2 = Divisor->countTrailingZeros();
2008 // Splat the sign bit into the register
2010 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2011 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2012 getShiftAmountTy(N0.getValueType())));
2013 AddToWorkList(SGN.getNode());
2015 // Add (N0 < 0) ? abs2 - 1 : 0;
2017 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2018 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2019 getShiftAmountTy(SGN.getValueType())));
2020 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2021 AddToWorkList(SRL.getNode());
2022 AddToWorkList(ADD.getNode()); // Divide by pow2
2023 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2024 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2026 // If we're dividing by a positive value, we're done. Otherwise, we must
2027 // negate the result.
2028 if (Divisor->isNonNegative())
2031 AddToWorkList(SRA.getNode());
2032 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2035 // if integer divide is expensive and we satisfy the requirements, emit an
2036 // alternate sequence.
2037 if ((N1C || N1->getOpcode() == ISD::BUILD_VECTOR) && !TLI.isIntDivCheap()) {
2038 SDValue Op = BuildSDIV(N);
2039 if (Op.getNode()) return Op;
2043 if (N0.getOpcode() == ISD::UNDEF)
2044 return DAG.getConstant(0, VT);
2045 // X / undef -> undef
2046 if (N1.getOpcode() == ISD::UNDEF)
2052 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2053 SDValue N0 = N->getOperand(0);
2054 SDValue N1 = N->getOperand(1);
2055 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
2056 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2057 EVT VT = N->getValueType(0);
2060 if (VT.isVector()) {
2061 SDValue FoldedVOp = SimplifyVBinOp(N);
2062 if (FoldedVOp.getNode()) return FoldedVOp;
2065 // fold (udiv c1, c2) -> c1/c2
2066 if (N0C && N1C && !N1C->isNullValue())
2067 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2068 // fold (udiv x, (1 << c)) -> x >>u c
2069 if (N1C && N1C->getAPIntValue().isPowerOf2())
2070 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2071 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2072 getShiftAmountTy(N0.getValueType())));
2073 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2074 if (N1.getOpcode() == ISD::SHL) {
2075 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2076 if (SHC->getAPIntValue().isPowerOf2()) {
2077 EVT ADDVT = N1.getOperand(1).getValueType();
2078 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2080 DAG.getConstant(SHC->getAPIntValue()
2083 AddToWorkList(Add.getNode());
2084 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2088 // fold (udiv x, c) -> alternate
2089 if ((N1C || N1->getOpcode() == ISD::BUILD_VECTOR) && !TLI.isIntDivCheap()) {
2090 SDValue Op = BuildUDIV(N);
2091 if (Op.getNode()) return Op;
2095 if (N0.getOpcode() == ISD::UNDEF)
2096 return DAG.getConstant(0, VT);
2097 // X / undef -> undef
2098 if (N1.getOpcode() == ISD::UNDEF)
2104 SDValue DAGCombiner::visitSREM(SDNode *N) {
2105 SDValue N0 = N->getOperand(0);
2106 SDValue N1 = N->getOperand(1);
2107 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2108 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2109 EVT VT = N->getValueType(0);
2111 // fold (srem c1, c2) -> c1%c2
2112 if (N0C && N1C && !N1C->isNullValue())
2113 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2114 // If we know the sign bits of both operands are zero, strength reduce to a
2115 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2116 if (!VT.isVector()) {
2117 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2118 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2121 // If X/C can be simplified by the division-by-constant logic, lower
2122 // X%C to the equivalent of X-X/C*C.
2123 if (N1C && !N1C->isNullValue()) {
2124 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2125 AddToWorkList(Div.getNode());
2126 SDValue OptimizedDiv = combine(Div.getNode());
2127 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2128 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2130 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2131 AddToWorkList(Mul.getNode());
2137 if (N0.getOpcode() == ISD::UNDEF)
2138 return DAG.getConstant(0, VT);
2139 // X % undef -> undef
2140 if (N1.getOpcode() == ISD::UNDEF)
2146 SDValue DAGCombiner::visitUREM(SDNode *N) {
2147 SDValue N0 = N->getOperand(0);
2148 SDValue N1 = N->getOperand(1);
2149 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2150 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2151 EVT VT = N->getValueType(0);
2153 // fold (urem c1, c2) -> c1%c2
2154 if (N0C && N1C && !N1C->isNullValue())
2155 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2156 // fold (urem x, pow2) -> (and x, pow2-1)
2157 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2158 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2159 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2160 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2161 if (N1.getOpcode() == ISD::SHL) {
2162 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2163 if (SHC->getAPIntValue().isPowerOf2()) {
2165 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2166 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2168 AddToWorkList(Add.getNode());
2169 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2174 // If X/C can be simplified by the division-by-constant logic, lower
2175 // X%C to the equivalent of X-X/C*C.
2176 if (N1C && !N1C->isNullValue()) {
2177 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2178 AddToWorkList(Div.getNode());
2179 SDValue OptimizedDiv = combine(Div.getNode());
2180 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2181 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2183 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2184 AddToWorkList(Mul.getNode());
2190 if (N0.getOpcode() == ISD::UNDEF)
2191 return DAG.getConstant(0, VT);
2192 // X % undef -> undef
2193 if (N1.getOpcode() == ISD::UNDEF)
2199 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2200 SDValue N0 = N->getOperand(0);
2201 SDValue N1 = N->getOperand(1);
2202 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2203 EVT VT = N->getValueType(0);
2206 // fold (mulhs x, 0) -> 0
2207 if (N1C && N1C->isNullValue())
2209 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2210 if (N1C && N1C->getAPIntValue() == 1)
2211 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2212 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2213 getShiftAmountTy(N0.getValueType())));
2214 // fold (mulhs x, undef) -> 0
2215 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2216 return DAG.getConstant(0, VT);
2218 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2220 if (VT.isSimple() && !VT.isVector()) {
2221 MVT Simple = VT.getSimpleVT();
2222 unsigned SimpleSize = Simple.getSizeInBits();
2223 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2224 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2225 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2226 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2227 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2228 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2229 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2230 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2237 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2238 SDValue N0 = N->getOperand(0);
2239 SDValue N1 = N->getOperand(1);
2240 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2241 EVT VT = N->getValueType(0);
2244 // fold (mulhu x, 0) -> 0
2245 if (N1C && N1C->isNullValue())
2247 // fold (mulhu x, 1) -> 0
2248 if (N1C && N1C->getAPIntValue() == 1)
2249 return DAG.getConstant(0, N0.getValueType());
2250 // fold (mulhu x, undef) -> 0
2251 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2252 return DAG.getConstant(0, VT);
2254 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2256 if (VT.isSimple() && !VT.isVector()) {
2257 MVT Simple = VT.getSimpleVT();
2258 unsigned SimpleSize = Simple.getSizeInBits();
2259 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2260 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2261 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2262 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2263 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2264 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2265 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2266 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2273 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2274 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2275 /// that are being performed. Return true if a simplification was made.
2277 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2279 // If the high half is not needed, just compute the low half.
2280 bool HiExists = N->hasAnyUseOfValue(1);
2282 (!LegalOperations ||
2283 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2284 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2285 N->op_begin(), N->getNumOperands());
2286 return CombineTo(N, Res, Res);
2289 // If the low half is not needed, just compute the high half.
2290 bool LoExists = N->hasAnyUseOfValue(0);
2292 (!LegalOperations ||
2293 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2294 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2295 N->op_begin(), N->getNumOperands());
2296 return CombineTo(N, Res, Res);
2299 // If both halves are used, return as it is.
2300 if (LoExists && HiExists)
2303 // If the two computed results can be simplified separately, separate them.
2305 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2306 N->op_begin(), N->getNumOperands());
2307 AddToWorkList(Lo.getNode());
2308 SDValue LoOpt = combine(Lo.getNode());
2309 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2310 (!LegalOperations ||
2311 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2312 return CombineTo(N, LoOpt, LoOpt);
2316 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2317 N->op_begin(), N->getNumOperands());
2318 AddToWorkList(Hi.getNode());
2319 SDValue HiOpt = combine(Hi.getNode());
2320 if (HiOpt.getNode() && HiOpt != Hi &&
2321 (!LegalOperations ||
2322 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2323 return CombineTo(N, HiOpt, HiOpt);
2329 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2330 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2331 if (Res.getNode()) return Res;
2333 EVT VT = N->getValueType(0);
2336 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2338 if (VT.isSimple() && !VT.isVector()) {
2339 MVT Simple = VT.getSimpleVT();
2340 unsigned SimpleSize = Simple.getSizeInBits();
2341 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2342 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2343 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2344 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2345 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2346 // Compute the high part as N1.
2347 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2348 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2349 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2350 // Compute the low part as N0.
2351 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2352 return CombineTo(N, Lo, Hi);
2359 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2360 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2361 if (Res.getNode()) return Res;
2363 EVT VT = N->getValueType(0);
2366 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2368 if (VT.isSimple() && !VT.isVector()) {
2369 MVT Simple = VT.getSimpleVT();
2370 unsigned SimpleSize = Simple.getSizeInBits();
2371 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2372 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2373 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2374 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2375 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2376 // Compute the high part as N1.
2377 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2378 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2379 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2380 // Compute the low part as N0.
2381 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2382 return CombineTo(N, Lo, Hi);
2389 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2390 // (smulo x, 2) -> (saddo x, x)
2391 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2392 if (C2->getAPIntValue() == 2)
2393 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2394 N->getOperand(0), N->getOperand(0));
2399 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2400 // (umulo x, 2) -> (uaddo x, x)
2401 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2402 if (C2->getAPIntValue() == 2)
2403 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2404 N->getOperand(0), N->getOperand(0));
2409 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2410 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2411 if (Res.getNode()) return Res;
2416 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2417 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2418 if (Res.getNode()) return Res;
2423 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2424 /// two operands of the same opcode, try to simplify it.
2425 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2426 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2427 EVT VT = N0.getValueType();
2428 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2430 // Bail early if none of these transforms apply.
2431 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2433 // For each of OP in AND/OR/XOR:
2434 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2435 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2436 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2437 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2439 // do not sink logical op inside of a vector extend, since it may combine
2441 EVT Op0VT = N0.getOperand(0).getValueType();
2442 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2443 N0.getOpcode() == ISD::SIGN_EXTEND ||
2444 // Avoid infinite looping with PromoteIntBinOp.
2445 (N0.getOpcode() == ISD::ANY_EXTEND &&
2446 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2447 (N0.getOpcode() == ISD::TRUNCATE &&
2448 (!TLI.isZExtFree(VT, Op0VT) ||
2449 !TLI.isTruncateFree(Op0VT, VT)) &&
2450 TLI.isTypeLegal(Op0VT))) &&
2452 Op0VT == N1.getOperand(0).getValueType() &&
2453 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2454 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2455 N0.getOperand(0).getValueType(),
2456 N0.getOperand(0), N1.getOperand(0));
2457 AddToWorkList(ORNode.getNode());
2458 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2461 // For each of OP in SHL/SRL/SRA/AND...
2462 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2463 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2464 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2465 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2466 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2467 N0.getOperand(1) == N1.getOperand(1)) {
2468 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2469 N0.getOperand(0).getValueType(),
2470 N0.getOperand(0), N1.getOperand(0));
2471 AddToWorkList(ORNode.getNode());
2472 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2473 ORNode, N0.getOperand(1));
2476 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2477 // Only perform this optimization after type legalization and before
2478 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2479 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2480 // we don't want to undo this promotion.
2481 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2483 if ((N0.getOpcode() == ISD::BITCAST ||
2484 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2485 Level == AfterLegalizeTypes) {
2486 SDValue In0 = N0.getOperand(0);
2487 SDValue In1 = N1.getOperand(0);
2488 EVT In0Ty = In0.getValueType();
2489 EVT In1Ty = In1.getValueType();
2491 // If both incoming values are integers, and the original types are the
2493 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2494 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2495 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2496 AddToWorkList(Op.getNode());
2501 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2502 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2503 // If both shuffles use the same mask, and both shuffle within a single
2504 // vector, then it is worthwhile to move the swizzle after the operation.
2505 // The type-legalizer generates this pattern when loading illegal
2506 // vector types from memory. In many cases this allows additional shuffle
2508 // There are other cases where moving the shuffle after the xor/and/or
2509 // is profitable even if shuffles don't perform a swizzle.
2510 // If both shuffles use the same mask, and both shuffles have the same first
2511 // or second operand, then it might still be profitable to move the shuffle
2512 // after the xor/and/or operation.
2513 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2514 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2515 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2517 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2518 "Inputs to shuffles are not the same type");
2520 // Check that both shuffles use the same mask. The masks are known to be of
2521 // the same length because the result vector type is the same.
2522 // Check also that shuffles have only one use to avoid introducing extra
2524 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2525 SVN0->getMask().equals(SVN1->getMask())) {
2526 SDValue ShOp = N0->getOperand(1);
2528 // Don't try to fold this node if it requires introducing a
2529 // build vector of all zeros that might be illegal at this stage.
2530 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2532 ShOp = DAG.getConstant(0, VT);
2537 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2538 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2539 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2540 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2541 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2542 N0->getOperand(0), N1->getOperand(0));
2543 AddToWorkList(NewNode.getNode());
2544 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2545 &SVN0->getMask()[0]);
2548 // Don't try to fold this node if it requires introducing a
2549 // build vector of all zeros that might be illegal at this stage.
2550 ShOp = N0->getOperand(0);
2551 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2553 ShOp = DAG.getConstant(0, VT);
2558 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2559 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2560 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2561 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2562 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2563 N0->getOperand(1), N1->getOperand(1));
2564 AddToWorkList(NewNode.getNode());
2565 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2566 &SVN0->getMask()[0]);
2574 SDValue DAGCombiner::visitAND(SDNode *N) {
2575 SDValue N0 = N->getOperand(0);
2576 SDValue N1 = N->getOperand(1);
2577 SDValue LL, LR, RL, RR, CC0, CC1;
2578 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2579 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2580 EVT VT = N1.getValueType();
2581 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2584 if (VT.isVector()) {
2585 SDValue FoldedVOp = SimplifyVBinOp(N);
2586 if (FoldedVOp.getNode()) return FoldedVOp;
2588 // fold (and x, 0) -> 0, vector edition
2589 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2591 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2594 // fold (and x, -1) -> x, vector edition
2595 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2597 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2601 // fold (and x, undef) -> 0
2602 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2603 return DAG.getConstant(0, VT);
2604 // fold (and c1, c2) -> c1&c2
2606 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2607 // canonicalize constant to RHS
2609 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2610 // fold (and x, -1) -> x
2611 if (N1C && N1C->isAllOnesValue())
2613 // if (and x, c) is known to be zero, return 0
2614 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2615 APInt::getAllOnesValue(BitWidth)))
2616 return DAG.getConstant(0, VT);
2618 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2621 // fold (and (or x, C), D) -> D if (C & D) == D
2622 if (N1C && N0.getOpcode() == ISD::OR)
2623 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2624 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2626 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2627 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2628 SDValue N0Op0 = N0.getOperand(0);
2629 APInt Mask = ~N1C->getAPIntValue();
2630 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2631 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2632 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2633 N0.getValueType(), N0Op0);
2635 // Replace uses of the AND with uses of the Zero extend node.
2638 // We actually want to replace all uses of the any_extend with the
2639 // zero_extend, to avoid duplicating things. This will later cause this
2640 // AND to be folded.
2641 CombineTo(N0.getNode(), Zext);
2642 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2645 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2646 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2647 // already be zero by virtue of the width of the base type of the load.
2649 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2651 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2652 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2653 N0.getOpcode() == ISD::LOAD) {
2654 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2655 N0 : N0.getOperand(0) );
2657 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2658 // This can be a pure constant or a vector splat, in which case we treat the
2659 // vector as a scalar and use the splat value.
2660 APInt Constant = APInt::getNullValue(1);
2661 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2662 Constant = C->getAPIntValue();
2663 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2664 APInt SplatValue, SplatUndef;
2665 unsigned SplatBitSize;
2667 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2668 SplatBitSize, HasAnyUndefs);
2670 // Undef bits can contribute to a possible optimisation if set, so
2672 SplatValue |= SplatUndef;
2674 // The splat value may be something like "0x00FFFFFF", which means 0 for
2675 // the first vector value and FF for the rest, repeating. We need a mask
2676 // that will apply equally to all members of the vector, so AND all the
2677 // lanes of the constant together.
2678 EVT VT = Vector->getValueType(0);
2679 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2681 // If the splat value has been compressed to a bitlength lower
2682 // than the size of the vector lane, we need to re-expand it to
2684 if (BitWidth > SplatBitSize)
2685 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2686 SplatBitSize < BitWidth;
2687 SplatBitSize = SplatBitSize * 2)
2688 SplatValue |= SplatValue.shl(SplatBitSize);
2690 Constant = APInt::getAllOnesValue(BitWidth);
2691 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2692 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2696 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2697 // actually legal and isn't going to get expanded, else this is a false
2699 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2700 Load->getMemoryVT());
2702 // Resize the constant to the same size as the original memory access before
2703 // extension. If it is still the AllOnesValue then this AND is completely
2706 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2709 switch (Load->getExtensionType()) {
2710 default: B = false; break;
2711 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2713 case ISD::NON_EXTLOAD: B = true; break;
2716 if (B && Constant.isAllOnesValue()) {
2717 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2718 // preserve semantics once we get rid of the AND.
2719 SDValue NewLoad(Load, 0);
2720 if (Load->getExtensionType() == ISD::EXTLOAD) {
2721 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2722 Load->getValueType(0), SDLoc(Load),
2723 Load->getChain(), Load->getBasePtr(),
2724 Load->getOffset(), Load->getMemoryVT(),
2725 Load->getMemOperand());
2726 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2727 if (Load->getNumValues() == 3) {
2728 // PRE/POST_INC loads have 3 values.
2729 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2730 NewLoad.getValue(2) };
2731 CombineTo(Load, To, 3, true);
2733 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2737 // Fold the AND away, taking care not to fold to the old load node if we
2739 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2741 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2744 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2745 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2746 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2747 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2749 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2750 LL.getValueType().isInteger()) {
2751 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2752 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2753 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2754 LR.getValueType(), LL, RL);
2755 AddToWorkList(ORNode.getNode());
2756 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2758 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2759 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2760 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2761 LR.getValueType(), LL, RL);
2762 AddToWorkList(ANDNode.getNode());
2763 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2765 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2766 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2767 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2768 LR.getValueType(), LL, RL);
2769 AddToWorkList(ORNode.getNode());
2770 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2773 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2774 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2775 Op0 == Op1 && LL.getValueType().isInteger() &&
2776 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2777 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2778 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2779 cast<ConstantSDNode>(RR)->isNullValue()))) {
2780 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2781 LL, DAG.getConstant(1, LL.getValueType()));
2782 AddToWorkList(ADDNode.getNode());
2783 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2784 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2786 // canonicalize equivalent to ll == rl
2787 if (LL == RR && LR == RL) {
2788 Op1 = ISD::getSetCCSwappedOperands(Op1);
2791 if (LL == RL && LR == RR) {
2792 bool isInteger = LL.getValueType().isInteger();
2793 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2794 if (Result != ISD::SETCC_INVALID &&
2795 (!LegalOperations ||
2796 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2797 TLI.isOperationLegal(ISD::SETCC,
2798 getSetCCResultType(N0.getSimpleValueType())))))
2799 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2804 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2805 if (N0.getOpcode() == N1.getOpcode()) {
2806 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2807 if (Tmp.getNode()) return Tmp;
2810 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2811 // fold (and (sra)) -> (and (srl)) when possible.
2812 if (!VT.isVector() &&
2813 SimplifyDemandedBits(SDValue(N, 0)))
2814 return SDValue(N, 0);
2816 // fold (zext_inreg (extload x)) -> (zextload x)
2817 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2818 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2819 EVT MemVT = LN0->getMemoryVT();
2820 // If we zero all the possible extended bits, then we can turn this into
2821 // a zextload if we are running before legalize or the operation is legal.
2822 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2823 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2824 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2825 ((!LegalOperations && !LN0->isVolatile()) ||
2826 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2827 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2828 LN0->getChain(), LN0->getBasePtr(),
2829 MemVT, LN0->getMemOperand());
2831 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2832 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2835 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2836 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2838 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2839 EVT MemVT = LN0->getMemoryVT();
2840 // If we zero all the possible extended bits, then we can turn this into
2841 // a zextload if we are running before legalize or the operation is legal.
2842 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2843 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2844 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2845 ((!LegalOperations && !LN0->isVolatile()) ||
2846 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2847 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2848 LN0->getChain(), LN0->getBasePtr(),
2849 MemVT, LN0->getMemOperand());
2851 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2852 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2856 // fold (and (load x), 255) -> (zextload x, i8)
2857 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2858 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2859 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2860 (N0.getOpcode() == ISD::ANY_EXTEND &&
2861 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2862 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2863 LoadSDNode *LN0 = HasAnyExt
2864 ? cast<LoadSDNode>(N0.getOperand(0))
2865 : cast<LoadSDNode>(N0);
2866 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2867 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2868 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2869 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2870 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2871 EVT LoadedVT = LN0->getMemoryVT();
2873 if (ExtVT == LoadedVT &&
2874 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2875 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2878 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2879 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2880 LN0->getMemOperand());
2882 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2883 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2886 // Do not change the width of a volatile load.
2887 // Do not generate loads of non-round integer types since these can
2888 // be expensive (and would be wrong if the type is not byte sized).
2889 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2890 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2891 EVT PtrType = LN0->getOperand(1).getValueType();
2893 unsigned Alignment = LN0->getAlignment();
2894 SDValue NewPtr = LN0->getBasePtr();
2896 // For big endian targets, we need to add an offset to the pointer
2897 // to load the correct bytes. For little endian systems, we merely
2898 // need to read fewer bytes from the same pointer.
2899 if (TLI.isBigEndian()) {
2900 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2901 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2902 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2903 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2904 NewPtr, DAG.getConstant(PtrOff, PtrType));
2905 Alignment = MinAlign(Alignment, PtrOff);
2908 AddToWorkList(NewPtr.getNode());
2910 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2912 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2913 LN0->getChain(), NewPtr,
2914 LN0->getPointerInfo(),
2915 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2916 Alignment, LN0->getTBAAInfo());
2918 CombineTo(LN0, Load, Load.getValue(1));
2919 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2925 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2926 VT.getSizeInBits() <= 64) {
2927 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2928 APInt ADDC = ADDI->getAPIntValue();
2929 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2930 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2931 // immediate for an add, but it is legal if its top c2 bits are set,
2932 // transform the ADD so the immediate doesn't need to be materialized
2934 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2935 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2936 SRLI->getZExtValue());
2937 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2939 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2941 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2942 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2943 CombineTo(N0.getNode(), NewAdd);
2944 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2952 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2953 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2954 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2955 N0.getOperand(1), false);
2956 if (BSwap.getNode())
2963 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2965 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2966 bool DemandHighBits) {
2967 if (!LegalOperations)
2970 EVT VT = N->getValueType(0);
2971 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2973 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2976 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2977 bool LookPassAnd0 = false;
2978 bool LookPassAnd1 = false;
2979 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2981 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2983 if (N0.getOpcode() == ISD::AND) {
2984 if (!N0.getNode()->hasOneUse())
2986 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2987 if (!N01C || N01C->getZExtValue() != 0xFF00)
2989 N0 = N0.getOperand(0);
2990 LookPassAnd0 = true;
2993 if (N1.getOpcode() == ISD::AND) {
2994 if (!N1.getNode()->hasOneUse())
2996 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2997 if (!N11C || N11C->getZExtValue() != 0xFF)
2999 N1 = N1.getOperand(0);
3000 LookPassAnd1 = true;
3003 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3005 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3007 if (!N0.getNode()->hasOneUse() ||
3008 !N1.getNode()->hasOneUse())
3011 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3012 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3015 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3018 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3019 SDValue N00 = N0->getOperand(0);
3020 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3021 if (!N00.getNode()->hasOneUse())
3023 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3024 if (!N001C || N001C->getZExtValue() != 0xFF)
3026 N00 = N00.getOperand(0);
3027 LookPassAnd0 = true;
3030 SDValue N10 = N1->getOperand(0);
3031 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3032 if (!N10.getNode()->hasOneUse())
3034 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3035 if (!N101C || N101C->getZExtValue() != 0xFF00)
3037 N10 = N10.getOperand(0);
3038 LookPassAnd1 = true;
3044 // Make sure everything beyond the low halfword gets set to zero since the SRL
3045 // 16 will clear the top bits.
3046 unsigned OpSizeInBits = VT.getSizeInBits();
3047 if (DemandHighBits && OpSizeInBits > 16) {
3048 // If the left-shift isn't masked out then the only way this is a bswap is
3049 // if all bits beyond the low 8 are 0. In that case the entire pattern
3050 // reduces to a left shift anyway: leave it for other parts of the combiner.
3054 // However, if the right shift isn't masked out then it might be because
3055 // it's not needed. See if we can spot that too.
3056 if (!LookPassAnd1 &&
3057 !DAG.MaskedValueIsZero(
3058 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3062 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3063 if (OpSizeInBits > 16)
3064 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3065 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3069 /// isBSwapHWordElement - Return true if the specified node is an element
3070 /// that makes up a 32-bit packed halfword byteswap. i.e.
3071 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3072 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3073 if (!N.getNode()->hasOneUse())
3076 unsigned Opc = N.getOpcode();
3077 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3080 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3085 switch (N1C->getZExtValue()) {
3088 case 0xFF: Num = 0; break;
3089 case 0xFF00: Num = 1; break;
3090 case 0xFF0000: Num = 2; break;
3091 case 0xFF000000: Num = 3; break;
3094 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3095 SDValue N0 = N.getOperand(0);
3096 if (Opc == ISD::AND) {
3097 if (Num == 0 || Num == 2) {
3099 // (x >> 8) & 0xff0000
3100 if (N0.getOpcode() != ISD::SRL)
3102 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3103 if (!C || C->getZExtValue() != 8)
3106 // (x << 8) & 0xff00
3107 // (x << 8) & 0xff000000
3108 if (N0.getOpcode() != ISD::SHL)
3110 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3111 if (!C || C->getZExtValue() != 8)
3114 } else if (Opc == ISD::SHL) {
3116 // (x & 0xff0000) << 8
3117 if (Num != 0 && Num != 2)
3119 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3120 if (!C || C->getZExtValue() != 8)
3122 } else { // Opc == ISD::SRL
3123 // (x & 0xff00) >> 8
3124 // (x & 0xff000000) >> 8
3125 if (Num != 1 && Num != 3)
3127 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3128 if (!C || C->getZExtValue() != 8)
3135 Parts[Num] = N0.getOperand(0).getNode();
3139 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3140 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3141 /// => (rotl (bswap x), 16)
3142 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3143 if (!LegalOperations)
3146 EVT VT = N->getValueType(0);
3149 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3152 SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3154 // (or (or (and), (and)), (or (and), (and)))
3155 // (or (or (or (and), (and)), (and)), (and))
3156 if (N0.getOpcode() != ISD::OR)
3158 SDValue N00 = N0.getOperand(0);
3159 SDValue N01 = N0.getOperand(1);
3161 if (N1.getOpcode() == ISD::OR &&
3162 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3163 // (or (or (and), (and)), (or (and), (and)))
3164 SDValue N000 = N00.getOperand(0);
3165 if (!isBSwapHWordElement(N000, Parts))
3168 SDValue N001 = N00.getOperand(1);
3169 if (!isBSwapHWordElement(N001, Parts))
3171 SDValue N010 = N01.getOperand(0);
3172 if (!isBSwapHWordElement(N010, Parts))
3174 SDValue N011 = N01.getOperand(1);
3175 if (!isBSwapHWordElement(N011, Parts))
3178 // (or (or (or (and), (and)), (and)), (and))
3179 if (!isBSwapHWordElement(N1, Parts))
3181 if (!isBSwapHWordElement(N01, Parts))
3183 if (N00.getOpcode() != ISD::OR)
3185 SDValue N000 = N00.getOperand(0);
3186 if (!isBSwapHWordElement(N000, Parts))
3188 SDValue N001 = N00.getOperand(1);
3189 if (!isBSwapHWordElement(N001, Parts))
3193 // Make sure the parts are all coming from the same node.
3194 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3197 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3198 SDValue(Parts[0],0));
3200 // Result of the bswap should be rotated by 16. If it's not legal, then
3201 // do (x << 16) | (x >> 16).
3202 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3203 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3204 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3205 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3206 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3207 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3208 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3209 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3212 SDValue DAGCombiner::visitOR(SDNode *N) {
3213 SDValue N0 = N->getOperand(0);
3214 SDValue N1 = N->getOperand(1);
3215 SDValue LL, LR, RL, RR, CC0, CC1;
3216 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3217 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3218 EVT VT = N1.getValueType();
3221 if (VT.isVector()) {
3222 SDValue FoldedVOp = SimplifyVBinOp(N);
3223 if (FoldedVOp.getNode()) return FoldedVOp;
3225 // fold (or x, 0) -> x, vector edition
3226 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3228 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3231 // fold (or x, -1) -> -1, vector edition
3232 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3234 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3237 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3238 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3239 // Do this only if the resulting shuffle is legal.
3240 if (isa<ShuffleVectorSDNode>(N0) &&
3241 isa<ShuffleVectorSDNode>(N1) &&
3242 N0->getOperand(1) == N1->getOperand(1) &&
3243 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3244 bool CanFold = true;
3245 unsigned NumElts = VT.getVectorNumElements();
3246 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3247 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3248 // We construct two shuffle masks:
3249 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3250 // and N1 as the second operand.
3251 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3252 // and N0 as the second operand.
3253 // We do this because OR is commutable and therefore there might be
3254 // two ways to fold this node into a shuffle.
3255 SmallVector<int,4> Mask1;
3256 SmallVector<int,4> Mask2;
3258 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3259 int M0 = SV0->getMaskElt(i);
3260 int M1 = SV1->getMaskElt(i);
3262 // Both shuffle indexes are undef. Propagate Undef.
3263 if (M0 < 0 && M1 < 0) {
3264 Mask1.push_back(M0);
3265 Mask2.push_back(M0);
3269 if (M0 < 0 || M1 < 0 ||
3270 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3271 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3276 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3277 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3281 // Fold this sequence only if the resulting shuffle is 'legal'.
3282 if (TLI.isShuffleMaskLegal(Mask1, VT))
3283 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3284 N1->getOperand(0), &Mask1[0]);
3285 if (TLI.isShuffleMaskLegal(Mask2, VT))
3286 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3287 N0->getOperand(0), &Mask2[0]);
3292 // fold (or x, undef) -> -1
3293 if (!LegalOperations &&
3294 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3295 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3296 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3298 // fold (or c1, c2) -> c1|c2
3300 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3301 // canonicalize constant to RHS
3303 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3304 // fold (or x, 0) -> x
3305 if (N1C && N1C->isNullValue())
3307 // fold (or x, -1) -> -1
3308 if (N1C && N1C->isAllOnesValue())
3310 // fold (or x, c) -> c iff (x & ~c) == 0
3311 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3314 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3315 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3316 if (BSwap.getNode())
3318 BSwap = MatchBSwapHWordLow(N, N0, N1);
3319 if (BSwap.getNode())
3323 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3326 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3327 // iff (c1 & c2) == 0.
3328 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3329 isa<ConstantSDNode>(N0.getOperand(1))) {
3330 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3331 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3332 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3335 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3336 DAG.getNode(ISD::OR, SDLoc(N0), VT,
3337 N0.getOperand(0), N1), COR);
3340 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3341 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3342 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3343 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3345 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3346 LL.getValueType().isInteger()) {
3347 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3348 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3349 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3350 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3351 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3352 LR.getValueType(), LL, RL);
3353 AddToWorkList(ORNode.getNode());
3354 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3356 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3357 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3358 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3359 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3360 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3361 LR.getValueType(), LL, RL);
3362 AddToWorkList(ANDNode.getNode());
3363 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3366 // canonicalize equivalent to ll == rl
3367 if (LL == RR && LR == RL) {
3368 Op1 = ISD::getSetCCSwappedOperands(Op1);
3371 if (LL == RL && LR == RR) {
3372 bool isInteger = LL.getValueType().isInteger();
3373 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3374 if (Result != ISD::SETCC_INVALID &&
3375 (!LegalOperations ||
3376 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3377 TLI.isOperationLegal(ISD::SETCC,
3378 getSetCCResultType(N0.getValueType())))))
3379 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3384 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3385 if (N0.getOpcode() == N1.getOpcode()) {
3386 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3387 if (Tmp.getNode()) return Tmp;
3390 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3391 if (N0.getOpcode() == ISD::AND &&
3392 N1.getOpcode() == ISD::AND &&
3393 N0.getOperand(1).getOpcode() == ISD::Constant &&
3394 N1.getOperand(1).getOpcode() == ISD::Constant &&
3395 // Don't increase # computations.
3396 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3397 // We can only do this xform if we know that bits from X that are set in C2
3398 // but not in C1 are already zero. Likewise for Y.
3399 const APInt &LHSMask =
3400 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3401 const APInt &RHSMask =
3402 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3404 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3405 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3406 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3407 N0.getOperand(0), N1.getOperand(0));
3408 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3409 DAG.getConstant(LHSMask | RHSMask, VT));
3413 // See if this is some rotate idiom.
3414 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3415 return SDValue(Rot, 0);
3417 // Simplify the operands using demanded-bits information.
3418 if (!VT.isVector() &&
3419 SimplifyDemandedBits(SDValue(N, 0)))
3420 return SDValue(N, 0);
3425 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3426 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3427 if (Op.getOpcode() == ISD::AND) {
3428 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3429 Mask = Op.getOperand(1);
3430 Op = Op.getOperand(0);
3436 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3444 // Return true if we can prove that, whenever Neg and Pos are both in the
3445 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3446 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3448 // (or (shift1 X, Neg), (shift2 X, Pos))
3450 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3451 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3452 // to consider shift amounts with defined behavior.
3453 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3454 // If OpSize is a power of 2 then:
3456 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3457 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3459 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3460 // for the stronger condition:
3462 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3464 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3465 // we can just replace Neg with Neg' for the rest of the function.
3467 // In other cases we check for the even stronger condition:
3469 // Neg == OpSize - Pos [B]
3471 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3472 // behavior if Pos == 0 (and consequently Neg == OpSize).
3474 // We could actually use [A] whenever OpSize is a power of 2, but the
3475 // only extra cases that it would match are those uninteresting ones
3476 // where Neg and Pos are never in range at the same time. E.g. for
3477 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3478 // as well as (sub 32, Pos), but:
3480 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3482 // always invokes undefined behavior for 32-bit X.
3484 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3485 unsigned MaskLoBits = 0;
3486 if (Neg.getOpcode() == ISD::AND &&
3487 isPowerOf2_64(OpSize) &&
3488 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3489 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3490 Neg = Neg.getOperand(0);
3491 MaskLoBits = Log2_64(OpSize);
3494 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3495 if (Neg.getOpcode() != ISD::SUB)
3497 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3500 SDValue NegOp1 = Neg.getOperand(1);
3502 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3503 // Pos'. The truncation is redundant for the purpose of the equality.
3505 Pos.getOpcode() == ISD::AND &&
3506 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3507 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3508 Pos = Pos.getOperand(0);
3510 // The condition we need is now:
3512 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3514 // If NegOp1 == Pos then we need:
3516 // OpSize & Mask == NegC & Mask
3518 // (because "x & Mask" is a truncation and distributes through subtraction).
3521 Width = NegC->getAPIntValue();
3522 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3523 // Then the condition we want to prove becomes:
3525 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3527 // which, again because "x & Mask" is a truncation, becomes:
3529 // NegC & Mask == (OpSize - PosC) & Mask
3530 // OpSize & Mask == (NegC + PosC) & Mask
3531 else if (Pos.getOpcode() == ISD::ADD &&
3532 Pos.getOperand(0) == NegOp1 &&
3533 Pos.getOperand(1).getOpcode() == ISD::Constant)
3534 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3535 NegC->getAPIntValue());
3539 // Now we just need to check that OpSize & Mask == Width & Mask.
3541 // Opsize & Mask is 0 since Mask is Opsize - 1.
3542 return Width.getLoBits(MaskLoBits) == 0;
3543 return Width == OpSize;
3546 // A subroutine of MatchRotate used once we have found an OR of two opposite
3547 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3548 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3549 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3550 // Neg with outer conversions stripped away.
3551 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3552 SDValue Neg, SDValue InnerPos,
3553 SDValue InnerNeg, unsigned PosOpcode,
3554 unsigned NegOpcode, SDLoc DL) {
3555 // fold (or (shl x, (*ext y)),
3556 // (srl x, (*ext (sub 32, y)))) ->
3557 // (rotl x, y) or (rotr x, (sub 32, y))
3559 // fold (or (shl x, (*ext (sub 32, y))),
3560 // (srl x, (*ext y))) ->
3561 // (rotr x, y) or (rotl x, (sub 32, y))
3562 EVT VT = Shifted.getValueType();
3563 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3564 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3565 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3566 HasPos ? Pos : Neg).getNode();
3572 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3573 // idioms for rotate, and if the target supports rotation instructions, generate
3575 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3576 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3577 EVT VT = LHS.getValueType();
3578 if (!TLI.isTypeLegal(VT)) return nullptr;
3580 // The target must have at least one rotate flavor.
3581 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3582 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3583 if (!HasROTL && !HasROTR) return nullptr;
3585 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3586 SDValue LHSShift; // The shift.
3587 SDValue LHSMask; // AND value if any.
3588 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3589 return nullptr; // Not part of a rotate.
3591 SDValue RHSShift; // The shift.
3592 SDValue RHSMask; // AND value if any.
3593 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3594 return nullptr; // Not part of a rotate.
3596 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3597 return nullptr; // Not shifting the same value.
3599 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3600 return nullptr; // Shifts must disagree.
3602 // Canonicalize shl to left side in a shl/srl pair.
3603 if (RHSShift.getOpcode() == ISD::SHL) {
3604 std::swap(LHS, RHS);
3605 std::swap(LHSShift, RHSShift);
3606 std::swap(LHSMask , RHSMask );
3609 unsigned OpSizeInBits = VT.getSizeInBits();
3610 SDValue LHSShiftArg = LHSShift.getOperand(0);
3611 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3612 SDValue RHSShiftArg = RHSShift.getOperand(0);
3613 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3615 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3616 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3617 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3618 RHSShiftAmt.getOpcode() == ISD::Constant) {
3619 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3620 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3621 if ((LShVal + RShVal) != OpSizeInBits)
3624 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3625 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3627 // If there is an AND of either shifted operand, apply it to the result.
3628 if (LHSMask.getNode() || RHSMask.getNode()) {
3629 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3631 if (LHSMask.getNode()) {
3632 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3633 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3635 if (RHSMask.getNode()) {
3636 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3637 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3640 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3643 return Rot.getNode();
3646 // If there is a mask here, and we have a variable shift, we can't be sure
3647 // that we're masking out the right stuff.
3648 if (LHSMask.getNode() || RHSMask.getNode())
3651 // If the shift amount is sign/zext/any-extended just peel it off.
3652 SDValue LExtOp0 = LHSShiftAmt;
3653 SDValue RExtOp0 = RHSShiftAmt;
3654 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3655 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3656 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3657 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3658 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3659 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3660 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3661 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3662 LExtOp0 = LHSShiftAmt.getOperand(0);
3663 RExtOp0 = RHSShiftAmt.getOperand(0);
3666 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3667 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3671 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3672 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3679 SDValue DAGCombiner::visitXOR(SDNode *N) {
3680 SDValue N0 = N->getOperand(0);
3681 SDValue N1 = N->getOperand(1);
3682 SDValue LHS, RHS, CC;
3683 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3684 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3685 EVT VT = N0.getValueType();
3688 if (VT.isVector()) {
3689 SDValue FoldedVOp = SimplifyVBinOp(N);
3690 if (FoldedVOp.getNode()) return FoldedVOp;
3692 // fold (xor x, 0) -> x, vector edition
3693 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3695 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3699 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3700 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3701 return DAG.getConstant(0, VT);
3702 // fold (xor x, undef) -> undef
3703 if (N0.getOpcode() == ISD::UNDEF)
3705 if (N1.getOpcode() == ISD::UNDEF)
3707 // fold (xor c1, c2) -> c1^c2
3709 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3710 // canonicalize constant to RHS
3712 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3713 // fold (xor x, 0) -> x
3714 if (N1C && N1C->isNullValue())
3717 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3721 // fold !(x cc y) -> (x !cc y)
3722 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3723 bool isInt = LHS.getValueType().isInteger();
3724 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3727 if (!LegalOperations ||
3728 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3729 switch (N0.getOpcode()) {
3731 llvm_unreachable("Unhandled SetCC Equivalent!");
3733 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3734 case ISD::SELECT_CC:
3735 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3736 N0.getOperand(3), NotCC);
3741 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3742 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3743 N0.getNode()->hasOneUse() &&
3744 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3745 SDValue V = N0.getOperand(0);
3746 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3747 DAG.getConstant(1, V.getValueType()));
3748 AddToWorkList(V.getNode());
3749 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3752 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3753 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3754 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3755 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3756 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3757 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3758 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3759 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3760 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3761 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3764 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3765 if (N1C && N1C->isAllOnesValue() &&
3766 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3767 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3768 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3769 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3770 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3771 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3772 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3773 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3776 // fold (xor (and x, y), y) -> (and (not x), y)
3777 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3778 N0->getOperand(1) == N1) {
3779 SDValue X = N0->getOperand(0);
3780 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3781 AddToWorkList(NotX.getNode());
3782 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3784 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3785 if (N1C && N0.getOpcode() == ISD::XOR) {
3786 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3787 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3789 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3790 DAG.getConstant(N1C->getAPIntValue() ^
3791 N00C->getAPIntValue(), VT));
3793 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3794 DAG.getConstant(N1C->getAPIntValue() ^
3795 N01C->getAPIntValue(), VT));
3797 // fold (xor x, x) -> 0
3799 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3801 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3802 if (N0.getOpcode() == N1.getOpcode()) {
3803 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3804 if (Tmp.getNode()) return Tmp;
3807 // Simplify the expression using non-local knowledge.
3808 if (!VT.isVector() &&
3809 SimplifyDemandedBits(SDValue(N, 0)))
3810 return SDValue(N, 0);
3815 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3816 /// the shift amount is a constant.
3817 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3818 // We can't and shouldn't fold opaque constants.
3819 if (Amt->isOpaque())
3822 SDNode *LHS = N->getOperand(0).getNode();
3823 if (!LHS->hasOneUse()) return SDValue();
3825 // We want to pull some binops through shifts, so that we have (and (shift))
3826 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3827 // thing happens with address calculations, so it's important to canonicalize
3829 bool HighBitSet = false; // Can we transform this if the high bit is set?
3831 switch (LHS->getOpcode()) {
3832 default: return SDValue();
3835 HighBitSet = false; // We can only transform sra if the high bit is clear.
3838 HighBitSet = true; // We can only transform sra if the high bit is set.
3841 if (N->getOpcode() != ISD::SHL)
3842 return SDValue(); // only shl(add) not sr[al](add).
3843 HighBitSet = false; // We can only transform sra if the high bit is clear.
3847 // We require the RHS of the binop to be a constant and not opaque as well.
3848 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3849 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3851 // FIXME: disable this unless the input to the binop is a shift by a constant.
3852 // If it is not a shift, it pessimizes some common cases like:
3854 // void foo(int *X, int i) { X[i & 1235] = 1; }
3855 // int bar(int *X, int i) { return X[i & 255]; }
3856 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3857 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3858 BinOpLHSVal->getOpcode() != ISD::SRA &&
3859 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3860 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3863 EVT VT = N->getValueType(0);
3865 // If this is a signed shift right, and the high bit is modified by the
3866 // logical operation, do not perform the transformation. The highBitSet
3867 // boolean indicates the value of the high bit of the constant which would
3868 // cause it to be modified for this operation.
3869 if (N->getOpcode() == ISD::SRA) {
3870 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3871 if (BinOpRHSSignSet != HighBitSet)
3875 // Fold the constants, shifting the binop RHS by the shift amount.
3876 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3878 LHS->getOperand(1), N->getOperand(1));
3879 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3881 // Create the new shift.
3882 SDValue NewShift = DAG.getNode(N->getOpcode(),
3883 SDLoc(LHS->getOperand(0)),
3884 VT, LHS->getOperand(0), N->getOperand(1));
3886 // Create the new binop.
3887 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3890 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3891 assert(N->getOpcode() == ISD::TRUNCATE);
3892 assert(N->getOperand(0).getOpcode() == ISD::AND);
3894 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3895 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3896 SDValue N01 = N->getOperand(0).getOperand(1);
3898 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3899 EVT TruncVT = N->getValueType(0);
3900 SDValue N00 = N->getOperand(0).getOperand(0);
3901 APInt TruncC = N01C->getAPIntValue();
3902 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3904 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3905 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3906 DAG.getConstant(TruncC, TruncVT));
3913 SDValue DAGCombiner::visitRotate(SDNode *N) {
3914 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3915 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3916 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3917 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3918 if (NewOp1.getNode())
3919 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3920 N->getOperand(0), NewOp1);
3925 SDValue DAGCombiner::visitSHL(SDNode *N) {
3926 SDValue N0 = N->getOperand(0);
3927 SDValue N1 = N->getOperand(1);
3928 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3929 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3930 EVT VT = N0.getValueType();
3931 unsigned OpSizeInBits = VT.getScalarSizeInBits();
3934 if (VT.isVector()) {
3935 SDValue FoldedVOp = SimplifyVBinOp(N);
3936 if (FoldedVOp.getNode()) return FoldedVOp;
3938 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3939 // If setcc produces all-one true value then:
3940 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
3941 if (N1CV && N1CV->isConstant()) {
3942 if (N0.getOpcode() == ISD::AND &&
3943 TLI.getBooleanContents(true) ==
3944 TargetLowering::ZeroOrNegativeOneBooleanContent) {
3945 SDValue N00 = N0->getOperand(0);
3946 SDValue N01 = N0->getOperand(1);
3947 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
3949 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC) {
3950 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3952 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3955 N1C = isConstOrConstSplat(N1);
3960 // fold (shl c1, c2) -> c1<<c2
3962 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3963 // fold (shl 0, x) -> 0
3964 if (N0C && N0C->isNullValue())
3966 // fold (shl x, c >= size(x)) -> undef
3967 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3968 return DAG.getUNDEF(VT);
3969 // fold (shl x, 0) -> x
3970 if (N1C && N1C->isNullValue())
3972 // fold (shl undef, x) -> 0
3973 if (N0.getOpcode() == ISD::UNDEF)
3974 return DAG.getConstant(0, VT);
3975 // if (shl x, c) is known to be zero, return 0
3976 if (DAG.MaskedValueIsZero(SDValue(N, 0),
3977 APInt::getAllOnesValue(OpSizeInBits)))
3978 return DAG.getConstant(0, VT);
3979 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3980 if (N1.getOpcode() == ISD::TRUNCATE &&
3981 N1.getOperand(0).getOpcode() == ISD::AND) {
3982 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
3983 if (NewOp1.getNode())
3984 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
3987 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3988 return SDValue(N, 0);
3990 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3991 if (N1C && N0.getOpcode() == ISD::SHL) {
3992 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
3993 uint64_t c1 = N0C1->getZExtValue();
3994 uint64_t c2 = N1C->getZExtValue();
3995 if (c1 + c2 >= OpSizeInBits)
3996 return DAG.getConstant(0, VT);
3997 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3998 DAG.getConstant(c1 + c2, N1.getValueType()));
4002 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4003 // For this to be valid, the second form must not preserve any of the bits
4004 // that are shifted out by the inner shift in the first form. This means
4005 // the outer shift size must be >= the number of bits added by the ext.
4006 // As a corollary, we don't care what kind of ext it is.
4007 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4008 N0.getOpcode() == ISD::ANY_EXTEND ||
4009 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4010 N0.getOperand(0).getOpcode() == ISD::SHL) {
4011 SDValue N0Op0 = N0.getOperand(0);
4012 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4013 uint64_t c1 = N0Op0C1->getZExtValue();
4014 uint64_t c2 = N1C->getZExtValue();
4015 EVT InnerShiftVT = N0Op0.getValueType();
4016 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4017 if (c2 >= OpSizeInBits - InnerShiftSize) {
4018 if (c1 + c2 >= OpSizeInBits)
4019 return DAG.getConstant(0, VT);
4020 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4021 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4022 N0Op0->getOperand(0)),
4023 DAG.getConstant(c1 + c2, N1.getValueType()));
4028 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4029 // Only fold this if the inner zext has no other uses to avoid increasing
4030 // the total number of instructions.
4031 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4032 N0.getOperand(0).getOpcode() == ISD::SRL) {
4033 SDValue N0Op0 = N0.getOperand(0);
4034 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4035 uint64_t c1 = N0Op0C1->getZExtValue();
4036 if (c1 < VT.getScalarSizeInBits()) {
4037 uint64_t c2 = N1C->getZExtValue();
4039 SDValue NewOp0 = N0.getOperand(0);
4040 EVT CountVT = NewOp0.getOperand(1).getValueType();
4041 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4042 NewOp0, DAG.getConstant(c2, CountVT));
4043 AddToWorkList(NewSHL.getNode());
4044 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4050 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4051 // (and (srl x, (sub c1, c2), MASK)
4052 // Only fold this if the inner shift has no other uses -- if it does, folding
4053 // this will increase the total number of instructions.
4054 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4055 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4056 uint64_t c1 = N0C1->getZExtValue();
4057 if (c1 < OpSizeInBits) {
4058 uint64_t c2 = N1C->getZExtValue();
4059 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4062 Mask = Mask.shl(c2 - c1);
4063 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4064 DAG.getConstant(c2 - c1, N1.getValueType()));
4066 Mask = Mask.lshr(c1 - c2);
4067 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4068 DAG.getConstant(c1 - c2, N1.getValueType()));
4070 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4071 DAG.getConstant(Mask, VT));
4075 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4076 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4077 unsigned BitSize = VT.getScalarSizeInBits();
4078 SDValue HiBitsMask =
4079 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4080 BitSize - N1C->getZExtValue()), VT);
4081 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4086 SDValue NewSHL = visitShiftByConstant(N, N1C);
4087 if (NewSHL.getNode())
4094 SDValue DAGCombiner::visitSRA(SDNode *N) {
4095 SDValue N0 = N->getOperand(0);
4096 SDValue N1 = N->getOperand(1);
4097 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4098 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4099 EVT VT = N0.getValueType();
4100 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4103 if (VT.isVector()) {
4104 SDValue FoldedVOp = SimplifyVBinOp(N);
4105 if (FoldedVOp.getNode()) return FoldedVOp;
4107 N1C = isConstOrConstSplat(N1);
4110 // fold (sra c1, c2) -> (sra c1, c2)
4112 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4113 // fold (sra 0, x) -> 0
4114 if (N0C && N0C->isNullValue())
4116 // fold (sra -1, x) -> -1
4117 if (N0C && N0C->isAllOnesValue())
4119 // fold (sra x, (setge c, size(x))) -> undef
4120 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4121 return DAG.getUNDEF(VT);
4122 // fold (sra x, 0) -> x
4123 if (N1C && N1C->isNullValue())
4125 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4127 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4128 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4129 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4131 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4132 ExtVT, VT.getVectorNumElements());
4133 if ((!LegalOperations ||
4134 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4135 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4136 N0.getOperand(0), DAG.getValueType(ExtVT));
4139 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4140 if (N1C && N0.getOpcode() == ISD::SRA) {
4141 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4142 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4143 if (Sum >= OpSizeInBits)
4144 Sum = OpSizeInBits - 1;
4145 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4146 DAG.getConstant(Sum, N1.getValueType()));
4150 // fold (sra (shl X, m), (sub result_size, n))
4151 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4152 // result_size - n != m.
4153 // If truncate is free for the target sext(shl) is likely to result in better
4155 if (N0.getOpcode() == ISD::SHL && N1C) {
4156 // Get the two constanst of the shifts, CN0 = m, CN = n.
4157 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4159 LLVMContext &Ctx = *DAG.getContext();
4160 // Determine what the truncate's result bitsize and type would be.
4161 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4164 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4166 // Determine the residual right-shift amount.
4167 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4169 // If the shift is not a no-op (in which case this should be just a sign
4170 // extend already), the truncated to type is legal, sign_extend is legal
4171 // on that type, and the truncate to that type is both legal and free,
4172 // perform the transform.
4173 if ((ShiftAmt > 0) &&
4174 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4175 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4176 TLI.isTruncateFree(VT, TruncVT)) {
4178 SDValue Amt = DAG.getConstant(ShiftAmt,
4179 getShiftAmountTy(N0.getOperand(0).getValueType()));
4180 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4181 N0.getOperand(0), Amt);
4182 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4184 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4185 N->getValueType(0), Trunc);
4190 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4191 if (N1.getOpcode() == ISD::TRUNCATE &&
4192 N1.getOperand(0).getOpcode() == ISD::AND) {
4193 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4194 if (NewOp1.getNode())
4195 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4198 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4199 // if c1 is equal to the number of bits the trunc removes
4200 if (N0.getOpcode() == ISD::TRUNCATE &&
4201 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4202 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4203 N0.getOperand(0).hasOneUse() &&
4204 N0.getOperand(0).getOperand(1).hasOneUse() &&
4206 SDValue N0Op0 = N0.getOperand(0);
4207 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4208 unsigned LargeShiftVal = LargeShift->getZExtValue();
4209 EVT LargeVT = N0Op0.getValueType();
4211 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4213 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4214 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4215 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4216 N0Op0.getOperand(0), Amt);
4217 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4222 // Simplify, based on bits shifted out of the LHS.
4223 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4224 return SDValue(N, 0);
4227 // If the sign bit is known to be zero, switch this to a SRL.
4228 if (DAG.SignBitIsZero(N0))
4229 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4232 SDValue NewSRA = visitShiftByConstant(N, N1C);
4233 if (NewSRA.getNode())
4240 SDValue DAGCombiner::visitSRL(SDNode *N) {
4241 SDValue N0 = N->getOperand(0);
4242 SDValue N1 = N->getOperand(1);
4243 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4244 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4245 EVT VT = N0.getValueType();
4246 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4249 if (VT.isVector()) {
4250 SDValue FoldedVOp = SimplifyVBinOp(N);
4251 if (FoldedVOp.getNode()) return FoldedVOp;
4253 N1C = isConstOrConstSplat(N1);
4256 // fold (srl c1, c2) -> c1 >>u c2
4258 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4259 // fold (srl 0, x) -> 0
4260 if (N0C && N0C->isNullValue())
4262 // fold (srl x, c >= size(x)) -> undef
4263 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4264 return DAG.getUNDEF(VT);
4265 // fold (srl x, 0) -> x
4266 if (N1C && N1C->isNullValue())
4268 // if (srl x, c) is known to be zero, return 0
4269 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4270 APInt::getAllOnesValue(OpSizeInBits)))
4271 return DAG.getConstant(0, VT);
4273 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4274 if (N1C && N0.getOpcode() == ISD::SRL) {
4275 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4276 uint64_t c1 = N01C->getZExtValue();
4277 uint64_t c2 = N1C->getZExtValue();
4278 if (c1 + c2 >= OpSizeInBits)
4279 return DAG.getConstant(0, VT);
4280 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4281 DAG.getConstant(c1 + c2, N1.getValueType()));
4285 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4286 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4287 N0.getOperand(0).getOpcode() == ISD::SRL &&
4288 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4290 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4291 uint64_t c2 = N1C->getZExtValue();
4292 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4293 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4294 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4295 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4296 if (c1 + OpSizeInBits == InnerShiftSize) {
4297 if (c1 + c2 >= InnerShiftSize)
4298 return DAG.getConstant(0, VT);
4299 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4300 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4301 N0.getOperand(0)->getOperand(0),
4302 DAG.getConstant(c1 + c2, ShiftCountVT)));
4306 // fold (srl (shl x, c), c) -> (and x, cst2)
4307 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4308 unsigned BitSize = N0.getScalarValueSizeInBits();
4309 if (BitSize <= 64) {
4310 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4311 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4312 DAG.getConstant(~0ULL >> ShAmt, VT));
4316 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4317 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4318 // Shifting in all undef bits?
4319 EVT SmallVT = N0.getOperand(0).getValueType();
4320 unsigned BitSize = SmallVT.getScalarSizeInBits();
4321 if (N1C->getZExtValue() >= BitSize)
4322 return DAG.getUNDEF(VT);
4324 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4325 uint64_t ShiftAmt = N1C->getZExtValue();
4326 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4328 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4329 AddToWorkList(SmallShift.getNode());
4330 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4331 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4332 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4333 DAG.getConstant(Mask, VT));
4337 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4338 // bit, which is unmodified by sra.
4339 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4340 if (N0.getOpcode() == ISD::SRA)
4341 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4344 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4345 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4346 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4347 APInt KnownZero, KnownOne;
4348 DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
4350 // If any of the input bits are KnownOne, then the input couldn't be all
4351 // zeros, thus the result of the srl will always be zero.
4352 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4354 // If all of the bits input the to ctlz node are known to be zero, then
4355 // the result of the ctlz is "32" and the result of the shift is one.
4356 APInt UnknownBits = ~KnownZero;
4357 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4359 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4360 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4361 // Okay, we know that only that the single bit specified by UnknownBits
4362 // could be set on input to the CTLZ node. If this bit is set, the SRL
4363 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4364 // to an SRL/XOR pair, which is likely to simplify more.
4365 unsigned ShAmt = UnknownBits.countTrailingZeros();
4366 SDValue Op = N0.getOperand(0);
4369 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4370 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4371 AddToWorkList(Op.getNode());
4374 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4375 Op, DAG.getConstant(1, VT));
4379 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4380 if (N1.getOpcode() == ISD::TRUNCATE &&
4381 N1.getOperand(0).getOpcode() == ISD::AND) {
4382 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4383 if (NewOp1.getNode())
4384 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4387 // fold operands of srl based on knowledge that the low bits are not
4389 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4390 return SDValue(N, 0);
4393 SDValue NewSRL = visitShiftByConstant(N, N1C);
4394 if (NewSRL.getNode())
4398 // Attempt to convert a srl of a load into a narrower zero-extending load.
4399 SDValue NarrowLoad = ReduceLoadWidth(N);
4400 if (NarrowLoad.getNode())
4403 // Here is a common situation. We want to optimize:
4406 // %b = and i32 %a, 2
4407 // %c = srl i32 %b, 1
4408 // brcond i32 %c ...
4414 // %c = setcc eq %b, 0
4417 // However when after the source operand of SRL is optimized into AND, the SRL
4418 // itself may not be optimized further. Look for it and add the BRCOND into
4420 if (N->hasOneUse()) {
4421 SDNode *Use = *N->use_begin();
4422 if (Use->getOpcode() == ISD::BRCOND)
4424 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4425 // Also look pass the truncate.
4426 Use = *Use->use_begin();
4427 if (Use->getOpcode() == ISD::BRCOND)
4435 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4436 SDValue N0 = N->getOperand(0);
4437 EVT VT = N->getValueType(0);
4439 // fold (ctlz c1) -> c2
4440 if (isa<ConstantSDNode>(N0))
4441 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4445 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4446 SDValue N0 = N->getOperand(0);
4447 EVT VT = N->getValueType(0);
4449 // fold (ctlz_zero_undef c1) -> c2
4450 if (isa<ConstantSDNode>(N0))
4451 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4455 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4456 SDValue N0 = N->getOperand(0);
4457 EVT VT = N->getValueType(0);
4459 // fold (cttz c1) -> c2
4460 if (isa<ConstantSDNode>(N0))
4461 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4465 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4466 SDValue N0 = N->getOperand(0);
4467 EVT VT = N->getValueType(0);
4469 // fold (cttz_zero_undef c1) -> c2
4470 if (isa<ConstantSDNode>(N0))
4471 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4475 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4476 SDValue N0 = N->getOperand(0);
4477 EVT VT = N->getValueType(0);
4479 // fold (ctpop c1) -> c2
4480 if (isa<ConstantSDNode>(N0))
4481 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4485 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4486 SDValue N0 = N->getOperand(0);
4487 SDValue N1 = N->getOperand(1);
4488 SDValue N2 = N->getOperand(2);
4489 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4490 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4491 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4492 EVT VT = N->getValueType(0);
4493 EVT VT0 = N0.getValueType();
4495 // fold (select C, X, X) -> X
4498 // fold (select true, X, Y) -> X
4499 if (N0C && !N0C->isNullValue())
4501 // fold (select false, X, Y) -> Y
4502 if (N0C && N0C->isNullValue())
4504 // fold (select C, 1, X) -> (or C, X)
4505 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4506 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4507 // fold (select C, 0, 1) -> (xor C, 1)
4508 if (VT.isInteger() &&
4511 TLI.getBooleanContents(false) ==
4512 TargetLowering::ZeroOrOneBooleanContent)) &&
4513 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4516 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4517 N0, DAG.getConstant(1, VT0));
4518 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4519 N0, DAG.getConstant(1, VT0));
4520 AddToWorkList(XORNode.getNode());
4522 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4523 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4525 // fold (select C, 0, X) -> (and (not C), X)
4526 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4527 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4528 AddToWorkList(NOTNode.getNode());
4529 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4531 // fold (select C, X, 1) -> (or (not C), X)
4532 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4533 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4534 AddToWorkList(NOTNode.getNode());
4535 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4537 // fold (select C, X, 0) -> (and C, X)
4538 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4539 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4540 // fold (select X, X, Y) -> (or X, Y)
4541 // fold (select X, 1, Y) -> (or X, Y)
4542 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4543 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4544 // fold (select X, Y, X) -> (and X, Y)
4545 // fold (select X, Y, 0) -> (and X, Y)
4546 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4547 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4549 // If we can fold this based on the true/false value, do so.
4550 if (SimplifySelectOps(N, N1, N2))
4551 return SDValue(N, 0); // Don't revisit N.
4553 // fold selects based on a setcc into other things, such as min/max/abs
4554 if (N0.getOpcode() == ISD::SETCC) {
4556 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4557 // having to say they don't support SELECT_CC on every type the DAG knows
4558 // about, since there is no way to mark an opcode illegal at all value types
4559 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4560 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4561 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4562 N0.getOperand(0), N0.getOperand(1),
4563 N1, N2, N0.getOperand(2));
4564 return SimplifySelect(SDLoc(N), N0, N1, N2);
4571 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4574 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4576 // Split the inputs.
4577 SDValue Lo, Hi, LL, LH, RL, RH;
4578 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4579 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4581 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4582 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4584 return std::make_pair(Lo, Hi);
4587 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4588 SDValue N0 = N->getOperand(0);
4589 SDValue N1 = N->getOperand(1);
4590 SDValue N2 = N->getOperand(2);
4593 // Canonicalize integer abs.
4594 // vselect (setg[te] X, 0), X, -X ->
4595 // vselect (setgt X, -1), X, -X ->
4596 // vselect (setl[te] X, 0), -X, X ->
4597 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4598 if (N0.getOpcode() == ISD::SETCC) {
4599 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4600 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4602 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4604 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4605 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4606 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4607 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4608 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4609 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4610 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4613 EVT VT = LHS.getValueType();
4614 SDValue Shift = DAG.getNode(
4615 ISD::SRA, DL, VT, LHS,
4616 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4617 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4618 AddToWorkList(Shift.getNode());
4619 AddToWorkList(Add.getNode());
4620 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4624 // If the VSELECT result requires splitting and the mask is provided by a
4625 // SETCC, then split both nodes and its operands before legalization. This
4626 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4627 // and enables future optimizations (e.g. min/max pattern matching on X86).
4628 if (N0.getOpcode() == ISD::SETCC) {
4629 EVT VT = N->getValueType(0);
4631 // Check if any splitting is required.
4632 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4633 TargetLowering::TypeSplitVector)
4636 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4637 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4638 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4639 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4641 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4642 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4644 // Add the new VSELECT nodes to the work list in case they need to be split
4646 AddToWorkList(Lo.getNode());
4647 AddToWorkList(Hi.getNode());
4649 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4652 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4653 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4655 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4656 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4662 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4663 SDValue N0 = N->getOperand(0);
4664 SDValue N1 = N->getOperand(1);
4665 SDValue N2 = N->getOperand(2);
4666 SDValue N3 = N->getOperand(3);
4667 SDValue N4 = N->getOperand(4);
4668 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4670 // fold select_cc lhs, rhs, x, x, cc -> x
4674 // Determine if the condition we're dealing with is constant
4675 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4676 N0, N1, CC, SDLoc(N), false);
4677 if (SCC.getNode()) {
4678 AddToWorkList(SCC.getNode());
4680 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4681 if (!SCCC->isNullValue())
4682 return N2; // cond always true -> true val
4684 return N3; // cond always false -> false val
4687 // Fold to a simpler select_cc
4688 if (SCC.getOpcode() == ISD::SETCC)
4689 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4690 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4694 // If we can fold this based on the true/false value, do so.
4695 if (SimplifySelectOps(N, N2, N3))
4696 return SDValue(N, 0); // Don't revisit N.
4698 // fold select_cc into other things, such as min/max/abs
4699 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4702 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4703 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4704 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4708 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4709 // dag node into a ConstantSDNode or a build_vector of constants.
4710 // This function is called by the DAGCombiner when visiting sext/zext/aext
4711 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4712 // Vector extends are not folded if operations are legal; this is to
4713 // avoid introducing illegal build_vector dag nodes.
4714 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4715 SelectionDAG &DAG, bool LegalTypes,
4716 bool LegalOperations) {
4717 unsigned Opcode = N->getOpcode();
4718 SDValue N0 = N->getOperand(0);
4719 EVT VT = N->getValueType(0);
4721 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4722 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4724 // fold (sext c1) -> c1
4725 // fold (zext c1) -> c1
4726 // fold (aext c1) -> c1
4727 if (isa<ConstantSDNode>(N0))
4728 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4730 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4731 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4732 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4733 EVT SVT = VT.getScalarType();
4734 if (!(VT.isVector() &&
4735 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4736 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4739 // We can fold this node into a build_vector.
4740 unsigned VTBits = SVT.getSizeInBits();
4741 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4742 unsigned ShAmt = VTBits - EVTBits;
4743 SmallVector<SDValue, 8> Elts;
4744 unsigned NumElts = N0->getNumOperands();
4747 for (unsigned i=0; i != NumElts; ++i) {
4748 SDValue Op = N0->getOperand(i);
4749 if (Op->getOpcode() == ISD::UNDEF) {
4750 Elts.push_back(DAG.getUNDEF(SVT));
4754 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4755 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4756 if (Opcode == ISD::SIGN_EXTEND)
4757 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4760 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4764 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4767 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4768 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4769 // transformation. Returns true if extension are possible and the above
4770 // mentioned transformation is profitable.
4771 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4773 SmallVectorImpl<SDNode *> &ExtendNodes,
4774 const TargetLowering &TLI) {
4775 bool HasCopyToRegUses = false;
4776 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4777 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4778 UE = N0.getNode()->use_end();
4783 if (UI.getUse().getResNo() != N0.getResNo())
4785 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4786 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4787 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4788 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4789 // Sign bits will be lost after a zext.
4792 for (unsigned i = 0; i != 2; ++i) {
4793 SDValue UseOp = User->getOperand(i);
4796 if (!isa<ConstantSDNode>(UseOp))
4801 ExtendNodes.push_back(User);
4804 // If truncates aren't free and there are users we can't
4805 // extend, it isn't worthwhile.
4808 // Remember if this value is live-out.
4809 if (User->getOpcode() == ISD::CopyToReg)
4810 HasCopyToRegUses = true;
4813 if (HasCopyToRegUses) {
4814 bool BothLiveOut = false;
4815 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4817 SDUse &Use = UI.getUse();
4818 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4824 // Both unextended and extended values are live out. There had better be
4825 // a good reason for the transformation.
4826 return ExtendNodes.size();
4831 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4832 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4833 ISD::NodeType ExtType) {
4834 // Extend SetCC uses if necessary.
4835 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4836 SDNode *SetCC = SetCCs[i];
4837 SmallVector<SDValue, 4> Ops;
4839 for (unsigned j = 0; j != 2; ++j) {
4840 SDValue SOp = SetCC->getOperand(j);
4842 Ops.push_back(ExtLoad);
4844 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4847 Ops.push_back(SetCC->getOperand(2));
4848 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
4852 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4853 SDValue N0 = N->getOperand(0);
4854 EVT VT = N->getValueType(0);
4856 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4858 return SDValue(Res, 0);
4860 // fold (sext (sext x)) -> (sext x)
4861 // fold (sext (aext x)) -> (sext x)
4862 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4863 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4866 if (N0.getOpcode() == ISD::TRUNCATE) {
4867 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4868 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4869 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4870 if (NarrowLoad.getNode()) {
4871 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4872 if (NarrowLoad.getNode() != N0.getNode()) {
4873 CombineTo(N0.getNode(), NarrowLoad);
4874 // CombineTo deleted the truncate, if needed, but not what's under it.
4877 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4880 // See if the value being truncated is already sign extended. If so, just
4881 // eliminate the trunc/sext pair.
4882 SDValue Op = N0.getOperand(0);
4883 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4884 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4885 unsigned DestBits = VT.getScalarType().getSizeInBits();
4886 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4888 if (OpBits == DestBits) {
4889 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4890 // bits, it is already ready.
4891 if (NumSignBits > DestBits-MidBits)
4893 } else if (OpBits < DestBits) {
4894 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4895 // bits, just sext from i32.
4896 if (NumSignBits > OpBits-MidBits)
4897 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4899 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4900 // bits, just truncate to i32.
4901 if (NumSignBits > OpBits-MidBits)
4902 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4905 // fold (sext (truncate x)) -> (sextinreg x).
4906 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4907 N0.getValueType())) {
4908 if (OpBits < DestBits)
4909 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4910 else if (OpBits > DestBits)
4911 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4912 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4913 DAG.getValueType(N0.getValueType()));
4917 // fold (sext (load x)) -> (sext (truncate (sextload x)))
4918 // None of the supported targets knows how to perform load and sign extend
4919 // on vectors in one instruction. We only perform this transformation on
4921 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4922 ISD::isUNINDEXEDLoad(N0.getNode()) &&
4923 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4924 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4925 bool DoXform = true;
4926 SmallVector<SDNode*, 4> SetCCs;
4927 if (!N0.hasOneUse())
4928 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4930 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4931 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4933 LN0->getBasePtr(), N0.getValueType(),
4934 LN0->getMemOperand());
4935 CombineTo(N, ExtLoad);
4936 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4937 N0.getValueType(), ExtLoad);
4938 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4939 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4941 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4945 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4946 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4947 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4948 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4949 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4950 EVT MemVT = LN0->getMemoryVT();
4951 if ((!LegalOperations && !LN0->isVolatile()) ||
4952 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4953 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4955 LN0->getBasePtr(), MemVT,
4956 LN0->getMemOperand());
4957 CombineTo(N, ExtLoad);
4958 CombineTo(N0.getNode(),
4959 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4960 N0.getValueType(), ExtLoad),
4961 ExtLoad.getValue(1));
4962 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4966 // fold (sext (and/or/xor (load x), cst)) ->
4967 // (and/or/xor (sextload x), (sext cst))
4968 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4969 N0.getOpcode() == ISD::XOR) &&
4970 isa<LoadSDNode>(N0.getOperand(0)) &&
4971 N0.getOperand(1).getOpcode() == ISD::Constant &&
4972 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4973 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4974 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4975 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
4976 bool DoXform = true;
4977 SmallVector<SDNode*, 4> SetCCs;
4978 if (!N0.hasOneUse())
4979 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4982 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
4983 LN0->getChain(), LN0->getBasePtr(),
4985 LN0->getMemOperand());
4986 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4987 Mask = Mask.sext(VT.getSizeInBits());
4988 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4989 ExtLoad, DAG.getConstant(Mask, VT));
4990 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4991 SDLoc(N0.getOperand(0)),
4992 N0.getOperand(0).getValueType(), ExtLoad);
4994 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4995 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4997 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5002 if (N0.getOpcode() == ISD::SETCC) {
5003 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5004 // Only do this before legalize for now.
5005 if (VT.isVector() && !LegalOperations &&
5006 TLI.getBooleanContents(true) ==
5007 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5008 EVT N0VT = N0.getOperand(0).getValueType();
5009 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5010 // of the same size as the compared operands. Only optimize sext(setcc())
5011 // if this is the case.
5012 EVT SVT = getSetCCResultType(N0VT);
5014 // We know that the # elements of the results is the same as the
5015 // # elements of the compare (and the # elements of the compare result
5016 // for that matter). Check to see that they are the same size. If so,
5017 // we know that the element size of the sext'd result matches the
5018 // element size of the compare operands.
5019 if (VT.getSizeInBits() == SVT.getSizeInBits())
5020 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5022 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5024 // If the desired elements are smaller or larger than the source
5025 // elements we can use a matching integer vector type and then
5026 // truncate/sign extend
5027 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5028 if (SVT == MatchingVectorType) {
5029 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5030 N0.getOperand(0), N0.getOperand(1),
5031 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5032 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5036 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5037 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5039 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5041 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5042 NegOne, DAG.getConstant(0, VT),
5043 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5044 if (SCC.getNode()) return SCC;
5046 if (!VT.isVector()) {
5047 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5048 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5050 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5051 SDValue SetCC = DAG.getSetCC(DL,
5053 N0.getOperand(0), N0.getOperand(1), CC);
5054 EVT SelectVT = getSetCCResultType(VT);
5055 return DAG.getSelect(DL, VT,
5056 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5057 NegOne, DAG.getConstant(0, VT));
5063 // fold (sext x) -> (zext x) if the sign bit is known zero.
5064 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5065 DAG.SignBitIsZero(N0))
5066 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5071 // isTruncateOf - If N is a truncate of some other value, return true, record
5072 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5073 // This function computes KnownZero to avoid a duplicated call to
5074 // ComputeMaskedBits in the caller.
5075 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5078 if (N->getOpcode() == ISD::TRUNCATE) {
5079 Op = N->getOperand(0);
5080 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5084 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5085 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5088 SDValue Op0 = N->getOperand(0);
5089 SDValue Op1 = N->getOperand(1);
5090 assert(Op0.getValueType() == Op1.getValueType());
5092 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5093 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5094 if (COp0 && COp0->isNullValue())
5096 else if (COp1 && COp1->isNullValue())
5101 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5103 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5109 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5110 SDValue N0 = N->getOperand(0);
5111 EVT VT = N->getValueType(0);
5113 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5115 return SDValue(Res, 0);
5117 // fold (zext (zext x)) -> (zext x)
5118 // fold (zext (aext x)) -> (zext x)
5119 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5120 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5123 // fold (zext (truncate x)) -> (zext x) or
5124 // (zext (truncate x)) -> (truncate x)
5125 // This is valid when the truncated bits of x are already zero.
5126 // FIXME: We should extend this to work for vectors too.
5129 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5130 APInt TruncatedBits =
5131 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5132 APInt(Op.getValueSizeInBits(), 0) :
5133 APInt::getBitsSet(Op.getValueSizeInBits(),
5134 N0.getValueSizeInBits(),
5135 std::min(Op.getValueSizeInBits(),
5136 VT.getSizeInBits()));
5137 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5138 if (VT.bitsGT(Op.getValueType()))
5139 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5140 if (VT.bitsLT(Op.getValueType()))
5141 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5147 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5148 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5149 if (N0.getOpcode() == ISD::TRUNCATE) {
5150 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5151 if (NarrowLoad.getNode()) {
5152 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5153 if (NarrowLoad.getNode() != N0.getNode()) {
5154 CombineTo(N0.getNode(), NarrowLoad);
5155 // CombineTo deleted the truncate, if needed, but not what's under it.
5158 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5162 // fold (zext (truncate x)) -> (and x, mask)
5163 if (N0.getOpcode() == ISD::TRUNCATE &&
5164 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5166 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5167 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5168 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5169 if (NarrowLoad.getNode()) {
5170 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5171 if (NarrowLoad.getNode() != N0.getNode()) {
5172 CombineTo(N0.getNode(), NarrowLoad);
5173 // CombineTo deleted the truncate, if needed, but not what's under it.
5176 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5179 SDValue Op = N0.getOperand(0);
5180 if (Op.getValueType().bitsLT(VT)) {
5181 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5182 AddToWorkList(Op.getNode());
5183 } else if (Op.getValueType().bitsGT(VT)) {
5184 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5185 AddToWorkList(Op.getNode());
5187 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5188 N0.getValueType().getScalarType());
5191 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5192 // if either of the casts is not free.
5193 if (N0.getOpcode() == ISD::AND &&
5194 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5195 N0.getOperand(1).getOpcode() == ISD::Constant &&
5196 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5197 N0.getValueType()) ||
5198 !TLI.isZExtFree(N0.getValueType(), VT))) {
5199 SDValue X = N0.getOperand(0).getOperand(0);
5200 if (X.getValueType().bitsLT(VT)) {
5201 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5202 } else if (X.getValueType().bitsGT(VT)) {
5203 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5205 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5206 Mask = Mask.zext(VT.getSizeInBits());
5207 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5208 X, DAG.getConstant(Mask, VT));
5211 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5212 // None of the supported targets knows how to perform load and vector_zext
5213 // on vectors in one instruction. We only perform this transformation on
5215 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5216 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5217 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5218 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5219 bool DoXform = true;
5220 SmallVector<SDNode*, 4> SetCCs;
5221 if (!N0.hasOneUse())
5222 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5224 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5225 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5227 LN0->getBasePtr(), N0.getValueType(),
5228 LN0->getMemOperand());
5229 CombineTo(N, ExtLoad);
5230 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5231 N0.getValueType(), ExtLoad);
5232 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5234 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5236 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5240 // fold (zext (and/or/xor (load x), cst)) ->
5241 // (and/or/xor (zextload x), (zext cst))
5242 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5243 N0.getOpcode() == ISD::XOR) &&
5244 isa<LoadSDNode>(N0.getOperand(0)) &&
5245 N0.getOperand(1).getOpcode() == ISD::Constant &&
5246 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5247 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5248 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5249 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5250 bool DoXform = true;
5251 SmallVector<SDNode*, 4> SetCCs;
5252 if (!N0.hasOneUse())
5253 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5256 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5257 LN0->getChain(), LN0->getBasePtr(),
5259 LN0->getMemOperand());
5260 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5261 Mask = Mask.zext(VT.getSizeInBits());
5262 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5263 ExtLoad, DAG.getConstant(Mask, VT));
5264 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5265 SDLoc(N0.getOperand(0)),
5266 N0.getOperand(0).getValueType(), ExtLoad);
5268 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5269 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5271 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5276 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5277 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5278 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5279 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5280 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5281 EVT MemVT = LN0->getMemoryVT();
5282 if ((!LegalOperations && !LN0->isVolatile()) ||
5283 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5284 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5286 LN0->getBasePtr(), MemVT,
5287 LN0->getMemOperand());
5288 CombineTo(N, ExtLoad);
5289 CombineTo(N0.getNode(),
5290 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5292 ExtLoad.getValue(1));
5293 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5297 if (N0.getOpcode() == ISD::SETCC) {
5298 if (!LegalOperations && VT.isVector() &&
5299 N0.getValueType().getVectorElementType() == MVT::i1) {
5300 EVT N0VT = N0.getOperand(0).getValueType();
5301 if (getSetCCResultType(N0VT) == N0.getValueType())
5304 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5305 // Only do this before legalize for now.
5306 EVT EltVT = VT.getVectorElementType();
5307 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5308 DAG.getConstant(1, EltVT));
5309 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5310 // We know that the # elements of the results is the same as the
5311 // # elements of the compare (and the # elements of the compare result
5312 // for that matter). Check to see that they are the same size. If so,
5313 // we know that the element size of the sext'd result matches the
5314 // element size of the compare operands.
5315 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5316 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5318 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5319 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5322 // If the desired elements are smaller or larger than the source
5323 // elements we can use a matching integer vector type and then
5324 // truncate/sign extend
5325 EVT MatchingElementType =
5326 EVT::getIntegerVT(*DAG.getContext(),
5327 N0VT.getScalarType().getSizeInBits());
5328 EVT MatchingVectorType =
5329 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5330 N0VT.getVectorNumElements());
5332 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5334 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5335 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5336 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5337 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5340 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5342 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5343 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5344 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5345 if (SCC.getNode()) return SCC;
5348 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5349 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5350 isa<ConstantSDNode>(N0.getOperand(1)) &&
5351 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5353 SDValue ShAmt = N0.getOperand(1);
5354 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5355 if (N0.getOpcode() == ISD::SHL) {
5356 SDValue InnerZExt = N0.getOperand(0);
5357 // If the original shl may be shifting out bits, do not perform this
5359 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5360 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5361 if (ShAmtVal > KnownZeroBits)
5367 // Ensure that the shift amount is wide enough for the shifted value.
5368 if (VT.getSizeInBits() >= 256)
5369 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5371 return DAG.getNode(N0.getOpcode(), DL, VT,
5372 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5379 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5380 SDValue N0 = N->getOperand(0);
5381 EVT VT = N->getValueType(0);
5383 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5385 return SDValue(Res, 0);
5387 // fold (aext (aext x)) -> (aext x)
5388 // fold (aext (zext x)) -> (zext x)
5389 // fold (aext (sext x)) -> (sext x)
5390 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5391 N0.getOpcode() == ISD::ZERO_EXTEND ||
5392 N0.getOpcode() == ISD::SIGN_EXTEND)
5393 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5395 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5396 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5397 if (N0.getOpcode() == ISD::TRUNCATE) {
5398 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5399 if (NarrowLoad.getNode()) {
5400 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5401 if (NarrowLoad.getNode() != N0.getNode()) {
5402 CombineTo(N0.getNode(), NarrowLoad);
5403 // CombineTo deleted the truncate, if needed, but not what's under it.
5406 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5410 // fold (aext (truncate x))
5411 if (N0.getOpcode() == ISD::TRUNCATE) {
5412 SDValue TruncOp = N0.getOperand(0);
5413 if (TruncOp.getValueType() == VT)
5414 return TruncOp; // x iff x size == zext size.
5415 if (TruncOp.getValueType().bitsGT(VT))
5416 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5417 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5420 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5421 // if the trunc is not free.
5422 if (N0.getOpcode() == ISD::AND &&
5423 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5424 N0.getOperand(1).getOpcode() == ISD::Constant &&
5425 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5426 N0.getValueType())) {
5427 SDValue X = N0.getOperand(0).getOperand(0);
5428 if (X.getValueType().bitsLT(VT)) {
5429 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5430 } else if (X.getValueType().bitsGT(VT)) {
5431 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5433 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5434 Mask = Mask.zext(VT.getSizeInBits());
5435 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5436 X, DAG.getConstant(Mask, VT));
5439 // fold (aext (load x)) -> (aext (truncate (extload x)))
5440 // None of the supported targets knows how to perform load and any_ext
5441 // on vectors in one instruction. We only perform this transformation on
5443 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5444 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5445 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5446 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5447 bool DoXform = true;
5448 SmallVector<SDNode*, 4> SetCCs;
5449 if (!N0.hasOneUse())
5450 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5452 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5453 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5455 LN0->getBasePtr(), N0.getValueType(),
5456 LN0->getMemOperand());
5457 CombineTo(N, ExtLoad);
5458 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5459 N0.getValueType(), ExtLoad);
5460 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5461 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5463 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5467 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5468 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5469 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5470 if (N0.getOpcode() == ISD::LOAD &&
5471 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5473 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5474 ISD::LoadExtType ExtType = LN0->getExtensionType();
5475 EVT MemVT = LN0->getMemoryVT();
5476 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5477 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5478 VT, LN0->getChain(), LN0->getBasePtr(),
5479 MemVT, LN0->getMemOperand());
5480 CombineTo(N, ExtLoad);
5481 CombineTo(N0.getNode(),
5482 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5483 N0.getValueType(), ExtLoad),
5484 ExtLoad.getValue(1));
5485 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5489 if (N0.getOpcode() == ISD::SETCC) {
5491 // aext(setcc) -> vsetcc
5492 // aext(setcc) -> truncate(vsetcc)
5493 // aext(setcc) -> aext(vsetcc)
5494 // Only do this before legalize for now.
5495 if (VT.isVector() && !LegalOperations) {
5496 EVT N0VT = N0.getOperand(0).getValueType();
5497 // We know that the # elements of the results is the same as the
5498 // # elements of the compare (and the # elements of the compare result
5499 // for that matter). Check to see that they are the same size. If so,
5500 // we know that the element size of the sext'd result matches the
5501 // element size of the compare operands.
5502 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5503 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5505 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5506 // If the desired elements are smaller or larger than the source
5507 // elements we can use a matching integer vector type and then
5508 // truncate/any extend
5510 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5512 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5514 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5515 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5519 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5521 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5522 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5523 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5531 /// GetDemandedBits - See if the specified operand can be simplified with the
5532 /// knowledge that only the bits specified by Mask are used. If so, return the
5533 /// simpler operand, otherwise return a null SDValue.
5534 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5535 switch (V.getOpcode()) {
5537 case ISD::Constant: {
5538 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5539 assert(CV && "Const value should be ConstSDNode.");
5540 const APInt &CVal = CV->getAPIntValue();
5541 APInt NewVal = CVal & Mask;
5543 return DAG.getConstant(NewVal, V.getValueType());
5548 // If the LHS or RHS don't contribute bits to the or, drop them.
5549 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5550 return V.getOperand(1);
5551 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5552 return V.getOperand(0);
5555 // Only look at single-use SRLs.
5556 if (!V.getNode()->hasOneUse())
5558 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5559 // See if we can recursively simplify the LHS.
5560 unsigned Amt = RHSC->getZExtValue();
5562 // Watch out for shift count overflow though.
5563 if (Amt >= Mask.getBitWidth()) break;
5564 APInt NewMask = Mask << Amt;
5565 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5566 if (SimplifyLHS.getNode())
5567 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5568 SimplifyLHS, V.getOperand(1));
5574 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5575 /// bits and then truncated to a narrower type and where N is a multiple
5576 /// of number of bits of the narrower type, transform it to a narrower load
5577 /// from address + N / num of bits of new type. If the result is to be
5578 /// extended, also fold the extension to form a extending load.
5579 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5580 unsigned Opc = N->getOpcode();
5582 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5583 SDValue N0 = N->getOperand(0);
5584 EVT VT = N->getValueType(0);
5587 // This transformation isn't valid for vector loads.
5591 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5593 if (Opc == ISD::SIGN_EXTEND_INREG) {
5594 ExtType = ISD::SEXTLOAD;
5595 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5596 } else if (Opc == ISD::SRL) {
5597 // Another special-case: SRL is basically zero-extending a narrower value.
5598 ExtType = ISD::ZEXTLOAD;
5600 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5601 if (!N01) return SDValue();
5602 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5603 VT.getSizeInBits() - N01->getZExtValue());
5605 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5608 unsigned EVTBits = ExtVT.getSizeInBits();
5610 // Do not generate loads of non-round integer types since these can
5611 // be expensive (and would be wrong if the type is not byte sized).
5612 if (!ExtVT.isRound())
5616 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5617 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5618 ShAmt = N01->getZExtValue();
5619 // Is the shift amount a multiple of size of VT?
5620 if ((ShAmt & (EVTBits-1)) == 0) {
5621 N0 = N0.getOperand(0);
5622 // Is the load width a multiple of size of VT?
5623 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5627 // At this point, we must have a load or else we can't do the transform.
5628 if (!isa<LoadSDNode>(N0)) return SDValue();
5630 // Because a SRL must be assumed to *need* to zero-extend the high bits
5631 // (as opposed to anyext the high bits), we can't combine the zextload
5632 // lowering of SRL and an sextload.
5633 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5636 // If the shift amount is larger than the input type then we're not
5637 // accessing any of the loaded bytes. If the load was a zextload/extload
5638 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5639 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5644 // If the load is shifted left (and the result isn't shifted back right),
5645 // we can fold the truncate through the shift.
5646 unsigned ShLeftAmt = 0;
5647 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5648 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5649 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5650 ShLeftAmt = N01->getZExtValue();
5651 N0 = N0.getOperand(0);
5655 // If we haven't found a load, we can't narrow it. Don't transform one with
5656 // multiple uses, this would require adding a new load.
5657 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5660 // Don't change the width of a volatile load.
5661 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5662 if (LN0->isVolatile())
5665 // Verify that we are actually reducing a load width here.
5666 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5669 // For the transform to be legal, the load must produce only two values
5670 // (the value loaded and the chain). Don't transform a pre-increment
5671 // load, for example, which produces an extra value. Otherwise the
5672 // transformation is not equivalent, and the downstream logic to replace
5673 // uses gets things wrong.
5674 if (LN0->getNumValues() > 2)
5677 // If the load that we're shrinking is an extload and we're not just
5678 // discarding the extension we can't simply shrink the load. Bail.
5679 // TODO: It would be possible to merge the extensions in some cases.
5680 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5681 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5684 EVT PtrType = N0.getOperand(1).getValueType();
5686 if (PtrType == MVT::Untyped || PtrType.isExtended())
5687 // It's not possible to generate a constant of extended or untyped type.
5690 // For big endian targets, we need to adjust the offset to the pointer to
5691 // load the correct bytes.
5692 if (TLI.isBigEndian()) {
5693 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5694 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5695 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5698 uint64_t PtrOff = ShAmt / 8;
5699 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5700 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5701 PtrType, LN0->getBasePtr(),
5702 DAG.getConstant(PtrOff, PtrType));
5703 AddToWorkList(NewPtr.getNode());
5706 if (ExtType == ISD::NON_EXTLOAD)
5707 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5708 LN0->getPointerInfo().getWithOffset(PtrOff),
5709 LN0->isVolatile(), LN0->isNonTemporal(),
5710 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5712 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5713 LN0->getPointerInfo().getWithOffset(PtrOff),
5714 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5715 NewAlign, LN0->getTBAAInfo());
5717 // Replace the old load's chain with the new load's chain.
5718 WorkListRemover DeadNodes(*this);
5719 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5721 // Shift the result left, if we've swallowed a left shift.
5722 SDValue Result = Load;
5723 if (ShLeftAmt != 0) {
5724 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5725 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5727 // If the shift amount is as large as the result size (but, presumably,
5728 // no larger than the source) then the useful bits of the result are
5729 // zero; we can't simply return the shortened shift, because the result
5730 // of that operation is undefined.
5731 if (ShLeftAmt >= VT.getSizeInBits())
5732 Result = DAG.getConstant(0, VT);
5734 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5735 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5738 // Return the new loaded value.
5742 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5743 SDValue N0 = N->getOperand(0);
5744 SDValue N1 = N->getOperand(1);
5745 EVT VT = N->getValueType(0);
5746 EVT EVT = cast<VTSDNode>(N1)->getVT();
5747 unsigned VTBits = VT.getScalarType().getSizeInBits();
5748 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5750 // fold (sext_in_reg c1) -> c1
5751 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5752 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5754 // If the input is already sign extended, just drop the extension.
5755 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5758 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5759 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5760 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5761 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5762 N0.getOperand(0), N1);
5764 // fold (sext_in_reg (sext x)) -> (sext x)
5765 // fold (sext_in_reg (aext x)) -> (sext x)
5766 // if x is small enough.
5767 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5768 SDValue N00 = N0.getOperand(0);
5769 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5770 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5771 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5774 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5775 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5776 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5778 // fold operands of sext_in_reg based on knowledge that the top bits are not
5780 if (SimplifyDemandedBits(SDValue(N, 0)))
5781 return SDValue(N, 0);
5783 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5784 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5785 SDValue NarrowLoad = ReduceLoadWidth(N);
5786 if (NarrowLoad.getNode())
5789 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5790 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5791 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5792 if (N0.getOpcode() == ISD::SRL) {
5793 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5794 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5795 // We can turn this into an SRA iff the input to the SRL is already sign
5797 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5798 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5799 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5800 N0.getOperand(0), N0.getOperand(1));
5804 // fold (sext_inreg (extload x)) -> (sextload x)
5805 if (ISD::isEXTLoad(N0.getNode()) &&
5806 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5807 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5808 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5809 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5810 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5811 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5813 LN0->getBasePtr(), EVT,
5814 LN0->getMemOperand());
5815 CombineTo(N, ExtLoad);
5816 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5817 AddToWorkList(ExtLoad.getNode());
5818 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5820 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5821 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5823 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5824 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5825 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5826 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5827 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5829 LN0->getBasePtr(), EVT,
5830 LN0->getMemOperand());
5831 CombineTo(N, ExtLoad);
5832 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5833 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5836 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5837 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5838 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5839 N0.getOperand(1), false);
5840 if (BSwap.getNode())
5841 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5845 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5846 // into a build_vector.
5847 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5848 SmallVector<SDValue, 8> Elts;
5849 unsigned NumElts = N0->getNumOperands();
5850 unsigned ShAmt = VTBits - EVTBits;
5852 for (unsigned i = 0; i != NumElts; ++i) {
5853 SDValue Op = N0->getOperand(i);
5854 if (Op->getOpcode() == ISD::UNDEF) {
5859 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5860 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5861 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5862 Op.getValueType()));
5865 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
5871 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5872 SDValue N0 = N->getOperand(0);
5873 EVT VT = N->getValueType(0);
5874 bool isLE = TLI.isLittleEndian();
5877 if (N0.getValueType() == N->getValueType(0))
5879 // fold (truncate c1) -> c1
5880 if (isa<ConstantSDNode>(N0))
5881 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5882 // fold (truncate (truncate x)) -> (truncate x)
5883 if (N0.getOpcode() == ISD::TRUNCATE)
5884 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5885 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5886 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5887 N0.getOpcode() == ISD::SIGN_EXTEND ||
5888 N0.getOpcode() == ISD::ANY_EXTEND) {
5889 if (N0.getOperand(0).getValueType().bitsLT(VT))
5890 // if the source is smaller than the dest, we still need an extend
5891 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5893 if (N0.getOperand(0).getValueType().bitsGT(VT))
5894 // if the source is larger than the dest, than we just need the truncate
5895 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5896 // if the source and dest are the same type, we can drop both the extend
5897 // and the truncate.
5898 return N0.getOperand(0);
5901 // Fold extract-and-trunc into a narrow extract. For example:
5902 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5903 // i32 y = TRUNCATE(i64 x)
5905 // v16i8 b = BITCAST (v2i64 val)
5906 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5908 // Note: We only run this optimization after type legalization (which often
5909 // creates this pattern) and before operation legalization after which
5910 // we need to be more careful about the vector instructions that we generate.
5911 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5912 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
5914 EVT VecTy = N0.getOperand(0).getValueType();
5915 EVT ExTy = N0.getValueType();
5916 EVT TrTy = N->getValueType(0);
5918 unsigned NumElem = VecTy.getVectorNumElements();
5919 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5921 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5922 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5924 SDValue EltNo = N0->getOperand(1);
5925 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5926 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5927 EVT IndexTy = TLI.getVectorIdxTy();
5928 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5930 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5931 NVT, N0.getOperand(0));
5933 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5935 DAG.getConstant(Index, IndexTy));
5939 // Fold a series of buildvector, bitcast, and truncate if possible.
5941 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5942 // (2xi32 (buildvector x, y)).
5943 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5944 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5945 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5946 N0.getOperand(0).hasOneUse()) {
5948 SDValue BuildVect = N0.getOperand(0);
5949 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5950 EVT TruncVecEltTy = VT.getVectorElementType();
5952 // Check that the element types match.
5953 if (BuildVectEltTy == TruncVecEltTy) {
5954 // Now we only need to compute the offset of the truncated elements.
5955 unsigned BuildVecNumElts = BuildVect.getNumOperands();
5956 unsigned TruncVecNumElts = VT.getVectorNumElements();
5957 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5959 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5960 "Invalid number of elements");
5962 SmallVector<SDValue, 8> Opnds;
5963 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5964 Opnds.push_back(BuildVect.getOperand(i));
5966 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
5970 // See if we can simplify the input to this truncate through knowledge that
5971 // only the low bits are being used.
5972 // For example "trunc (or (shl x, 8), y)" // -> trunc y
5973 // Currently we only perform this optimization on scalars because vectors
5974 // may have different active low bits.
5975 if (!VT.isVector()) {
5977 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5978 VT.getSizeInBits()));
5979 if (Shorter.getNode())
5980 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
5982 // fold (truncate (load x)) -> (smaller load x)
5983 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5984 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5985 SDValue Reduced = ReduceLoadWidth(N);
5986 if (Reduced.getNode())
5988 // Handle the case where the load remains an extending load even
5989 // after truncation.
5990 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
5991 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5992 if (!LN0->isVolatile() &&
5993 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
5994 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
5995 VT, LN0->getChain(), LN0->getBasePtr(),
5997 LN0->getMemOperand());
5998 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6003 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6004 // where ... are all 'undef'.
6005 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6006 SmallVector<EVT, 8> VTs;
6009 unsigned NumDefs = 0;
6011 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6012 SDValue X = N0.getOperand(i);
6013 if (X.getOpcode() != ISD::UNDEF) {
6018 // Stop if more than one members are non-undef.
6021 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6022 VT.getVectorElementType(),
6023 X.getValueType().getVectorNumElements()));
6027 return DAG.getUNDEF(VT);
6030 assert(V.getNode() && "The single defined operand is empty!");
6031 SmallVector<SDValue, 8> Opnds;
6032 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6034 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6037 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6038 AddToWorkList(NV.getNode());
6039 Opnds.push_back(NV);
6041 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6045 // Simplify the operands using demanded-bits information.
6046 if (!VT.isVector() &&
6047 SimplifyDemandedBits(SDValue(N, 0)))
6048 return SDValue(N, 0);
6053 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6054 SDValue Elt = N->getOperand(i);
6055 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6056 return Elt.getNode();
6057 return Elt.getOperand(Elt.getResNo()).getNode();
6060 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6061 /// if load locations are consecutive.
6062 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6063 assert(N->getOpcode() == ISD::BUILD_PAIR);
6065 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6066 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6067 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6068 LD1->getAddressSpace() != LD2->getAddressSpace())
6070 EVT LD1VT = LD1->getValueType(0);
6072 if (ISD::isNON_EXTLoad(LD2) &&
6074 // If both are volatile this would reduce the number of volatile loads.
6075 // If one is volatile it might be ok, but play conservative and bail out.
6076 !LD1->isVolatile() &&
6077 !LD2->isVolatile() &&
6078 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6079 unsigned Align = LD1->getAlignment();
6080 unsigned NewAlign = TLI.getDataLayout()->
6081 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6083 if (NewAlign <= Align &&
6084 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6085 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6086 LD1->getBasePtr(), LD1->getPointerInfo(),
6087 false, false, false, Align);
6093 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6094 SDValue N0 = N->getOperand(0);
6095 EVT VT = N->getValueType(0);
6097 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6098 // Only do this before legalize, since afterward the target may be depending
6099 // on the bitconvert.
6100 // First check to see if this is all constant.
6102 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6104 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6106 EVT DestEltVT = N->getValueType(0).getVectorElementType();
6107 assert(!DestEltVT.isVector() &&
6108 "Element type of vector ValueType must not be vector!");
6110 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6113 // If the input is a constant, let getNode fold it.
6114 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6115 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6116 if (Res.getNode() != N) {
6117 if (!LegalOperations ||
6118 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6121 // Folding it resulted in an illegal node, and it's too late to
6122 // do that. Clean up the old node and forego the transformation.
6123 // Ideally this won't happen very often, because instcombine
6124 // and the earlier dagcombine runs (where illegal nodes are
6125 // permitted) should have folded most of them already.
6126 DAG.DeleteNode(Res.getNode());
6130 // (conv (conv x, t1), t2) -> (conv x, t2)
6131 if (N0.getOpcode() == ISD::BITCAST)
6132 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6135 // fold (conv (load x)) -> (load (conv*)x)
6136 // If the resultant load doesn't need a higher alignment than the original!
6137 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6138 // Do not change the width of a volatile load.
6139 !cast<LoadSDNode>(N0)->isVolatile() &&
6140 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6141 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6142 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6143 unsigned Align = TLI.getDataLayout()->
6144 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6145 unsigned OrigAlign = LN0->getAlignment();
6147 if (Align <= OrigAlign) {
6148 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6149 LN0->getBasePtr(), LN0->getPointerInfo(),
6150 LN0->isVolatile(), LN0->isNonTemporal(),
6151 LN0->isInvariant(), OrigAlign,
6152 LN0->getTBAAInfo());
6154 CombineTo(N0.getNode(),
6155 DAG.getNode(ISD::BITCAST, SDLoc(N0),
6156 N0.getValueType(), Load),
6162 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6163 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6164 // This often reduces constant pool loads.
6165 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6166 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6167 N0.getNode()->hasOneUse() && VT.isInteger() &&
6168 !VT.isVector() && !N0.getValueType().isVector()) {
6169 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6171 AddToWorkList(NewConv.getNode());
6173 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6174 if (N0.getOpcode() == ISD::FNEG)
6175 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6176 NewConv, DAG.getConstant(SignBit, VT));
6177 assert(N0.getOpcode() == ISD::FABS);
6178 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6179 NewConv, DAG.getConstant(~SignBit, VT));
6182 // fold (bitconvert (fcopysign cst, x)) ->
6183 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6184 // Note that we don't handle (copysign x, cst) because this can always be
6185 // folded to an fneg or fabs.
6186 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6187 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6188 VT.isInteger() && !VT.isVector()) {
6189 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6190 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6191 if (isTypeLegal(IntXVT)) {
6192 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6193 IntXVT, N0.getOperand(1));
6194 AddToWorkList(X.getNode());
6196 // If X has a different width than the result/lhs, sext it or truncate it.
6197 unsigned VTWidth = VT.getSizeInBits();
6198 if (OrigXWidth < VTWidth) {
6199 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6200 AddToWorkList(X.getNode());
6201 } else if (OrigXWidth > VTWidth) {
6202 // To get the sign bit in the right place, we have to shift it right
6203 // before truncating.
6204 X = DAG.getNode(ISD::SRL, SDLoc(X),
6205 X.getValueType(), X,
6206 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6207 AddToWorkList(X.getNode());
6208 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6209 AddToWorkList(X.getNode());
6212 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6213 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6214 X, DAG.getConstant(SignBit, VT));
6215 AddToWorkList(X.getNode());
6217 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6218 VT, N0.getOperand(0));
6219 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6220 Cst, DAG.getConstant(~SignBit, VT));
6221 AddToWorkList(Cst.getNode());
6223 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6227 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6228 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6229 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6230 if (CombineLD.getNode())
6237 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6238 EVT VT = N->getValueType(0);
6239 return CombineConsecutiveLoads(N, VT);
6242 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6243 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
6244 /// destination element value type.
6245 SDValue DAGCombiner::
6246 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6247 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6249 // If this is already the right type, we're done.
6250 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6252 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6253 unsigned DstBitSize = DstEltVT.getSizeInBits();
6255 // If this is a conversion of N elements of one type to N elements of another
6256 // type, convert each element. This handles FP<->INT cases.
6257 if (SrcBitSize == DstBitSize) {
6258 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6259 BV->getValueType(0).getVectorNumElements());
6261 // Due to the FP element handling below calling this routine recursively,
6262 // we can end up with a scalar-to-vector node here.
6263 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6264 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6265 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6266 DstEltVT, BV->getOperand(0)));
6268 SmallVector<SDValue, 8> Ops;
6269 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6270 SDValue Op = BV->getOperand(i);
6271 // If the vector element type is not legal, the BUILD_VECTOR operands
6272 // are promoted and implicitly truncated. Make that explicit here.
6273 if (Op.getValueType() != SrcEltVT)
6274 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6275 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6277 AddToWorkList(Ops.back().getNode());
6279 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6282 // Otherwise, we're growing or shrinking the elements. To avoid having to
6283 // handle annoying details of growing/shrinking FP values, we convert them to
6285 if (SrcEltVT.isFloatingPoint()) {
6286 // Convert the input float vector to a int vector where the elements are the
6288 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6289 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6290 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6294 // Now we know the input is an integer vector. If the output is a FP type,
6295 // convert to integer first, then to FP of the right size.
6296 if (DstEltVT.isFloatingPoint()) {
6297 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6298 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6299 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6301 // Next, convert to FP elements of the same size.
6302 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6305 // Okay, we know the src/dst types are both integers of differing types.
6306 // Handling growing first.
6307 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6308 if (SrcBitSize < DstBitSize) {
6309 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6311 SmallVector<SDValue, 8> Ops;
6312 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6313 i += NumInputsPerOutput) {
6314 bool isLE = TLI.isLittleEndian();
6315 APInt NewBits = APInt(DstBitSize, 0);
6316 bool EltIsUndef = true;
6317 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6318 // Shift the previously computed bits over.
6319 NewBits <<= SrcBitSize;
6320 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6321 if (Op.getOpcode() == ISD::UNDEF) continue;
6324 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6325 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6329 Ops.push_back(DAG.getUNDEF(DstEltVT));
6331 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6334 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6335 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6338 // Finally, this must be the case where we are shrinking elements: each input
6339 // turns into multiple outputs.
6340 bool isS2V = ISD::isScalarToVector(BV);
6341 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6342 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6343 NumOutputsPerInput*BV->getNumOperands());
6344 SmallVector<SDValue, 8> Ops;
6346 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6347 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6348 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6349 Ops.push_back(DAG.getUNDEF(DstEltVT));
6353 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6354 getAPIntValue().zextOrTrunc(SrcBitSize);
6356 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6357 APInt ThisVal = OpVal.trunc(DstBitSize);
6358 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6359 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6360 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6361 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6363 OpVal = OpVal.lshr(DstBitSize);
6366 // For big endian targets, swap the order of the pieces of each element.
6367 if (TLI.isBigEndian())
6368 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6371 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6374 SDValue DAGCombiner::visitFADD(SDNode *N) {
6375 SDValue N0 = N->getOperand(0);
6376 SDValue N1 = N->getOperand(1);
6377 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6378 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6379 EVT VT = N->getValueType(0);
6382 if (VT.isVector()) {
6383 SDValue FoldedVOp = SimplifyVBinOp(N);
6384 if (FoldedVOp.getNode()) return FoldedVOp;
6387 // fold (fadd c1, c2) -> c1 + c2
6389 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6390 // canonicalize constant to RHS
6391 if (N0CFP && !N1CFP)
6392 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6393 // fold (fadd A, 0) -> A
6394 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6395 N1CFP->getValueAPF().isZero())
6397 // fold (fadd A, (fneg B)) -> (fsub A, B)
6398 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6399 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6400 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6401 GetNegatedExpression(N1, DAG, LegalOperations));
6402 // fold (fadd (fneg A), B) -> (fsub B, A)
6403 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6404 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6405 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6406 GetNegatedExpression(N0, DAG, LegalOperations));
6408 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6409 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6410 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6411 isa<ConstantFPSDNode>(N0.getOperand(1)))
6412 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6413 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6414 N0.getOperand(1), N1));
6416 // No FP constant should be created after legalization as Instruction
6417 // Selection pass has hard time in dealing with FP constant.
6419 // We don't need test this condition for transformation like following, as
6420 // the DAG being transformed implies it is legal to take FP constant as
6423 // (fadd (fmul c, x), x) -> (fmul c+1, x)
6425 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6427 // If allow, fold (fadd (fneg x), x) -> 0.0
6428 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6429 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6430 return DAG.getConstantFP(0.0, VT);
6432 // If allow, fold (fadd x, (fneg x)) -> 0.0
6433 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6434 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6435 return DAG.getConstantFP(0.0, VT);
6437 // In unsafe math mode, we can fold chains of FADD's of the same value
6438 // into multiplications. This transform is not safe in general because
6439 // we are reducing the number of rounding steps.
6440 if (DAG.getTarget().Options.UnsafeFPMath &&
6441 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6443 if (N0.getOpcode() == ISD::FMUL) {
6444 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6445 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6447 // (fadd (fmul c, x), x) -> (fmul x, c+1)
6448 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6449 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6451 DAG.getConstantFP(1.0, VT));
6452 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6456 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6457 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6458 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6460 DAG.getConstantFP(1.0, VT));
6461 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6465 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6466 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6467 N1.getOperand(0) == N1.getOperand(1) &&
6468 N0.getOperand(1) == N1.getOperand(0)) {
6469 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6471 DAG.getConstantFP(2.0, VT));
6472 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6473 N0.getOperand(1), NewCFP);
6476 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6477 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6478 N1.getOperand(0) == N1.getOperand(1) &&
6479 N0.getOperand(0) == N1.getOperand(0)) {
6480 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6482 DAG.getConstantFP(2.0, VT));
6483 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6484 N0.getOperand(0), NewCFP);
6488 if (N1.getOpcode() == ISD::FMUL) {
6489 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6490 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6492 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6493 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6494 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6496 DAG.getConstantFP(1.0, VT));
6497 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6501 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6502 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6503 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6505 DAG.getConstantFP(1.0, VT));
6506 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6511 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6512 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6513 N0.getOperand(0) == N0.getOperand(1) &&
6514 N1.getOperand(1) == N0.getOperand(0)) {
6515 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6517 DAG.getConstantFP(2.0, VT));
6518 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6519 N1.getOperand(1), NewCFP);
6522 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6523 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6524 N0.getOperand(0) == N0.getOperand(1) &&
6525 N1.getOperand(0) == N0.getOperand(0)) {
6526 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6528 DAG.getConstantFP(2.0, VT));
6529 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6530 N1.getOperand(0), NewCFP);
6534 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6535 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6536 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6537 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6538 (N0.getOperand(0) == N1))
6539 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6540 N1, DAG.getConstantFP(3.0, VT));
6543 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6544 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6545 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6546 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6547 N1.getOperand(0) == N0)
6548 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6549 N0, DAG.getConstantFP(3.0, VT));
6552 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6553 if (AllowNewFpConst &&
6554 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6555 N0.getOperand(0) == N0.getOperand(1) &&
6556 N1.getOperand(0) == N1.getOperand(1) &&
6557 N0.getOperand(0) == N1.getOperand(0))
6558 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6560 DAG.getConstantFP(4.0, VT));
6563 // FADD -> FMA combines:
6564 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6565 DAG.getTarget().Options.UnsafeFPMath) &&
6566 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6567 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6569 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6570 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6571 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6572 N0.getOperand(0), N0.getOperand(1), N1);
6574 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6575 // Note: Commutes FADD operands.
6576 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6577 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6578 N1.getOperand(0), N1.getOperand(1), N0);
6584 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6585 SDValue N0 = N->getOperand(0);
6586 SDValue N1 = N->getOperand(1);
6587 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6588 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6589 EVT VT = N->getValueType(0);
6593 if (VT.isVector()) {
6594 SDValue FoldedVOp = SimplifyVBinOp(N);
6595 if (FoldedVOp.getNode()) return FoldedVOp;
6598 // fold (fsub c1, c2) -> c1-c2
6600 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6601 // fold (fsub A, 0) -> A
6602 if (DAG.getTarget().Options.UnsafeFPMath &&
6603 N1CFP && N1CFP->getValueAPF().isZero())
6605 // fold (fsub 0, B) -> -B
6606 if (DAG.getTarget().Options.UnsafeFPMath &&
6607 N0CFP && N0CFP->getValueAPF().isZero()) {
6608 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6609 return GetNegatedExpression(N1, DAG, LegalOperations);
6610 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6611 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6613 // fold (fsub A, (fneg B)) -> (fadd A, B)
6614 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6615 return DAG.getNode(ISD::FADD, dl, VT, N0,
6616 GetNegatedExpression(N1, DAG, LegalOperations));
6618 // If 'unsafe math' is enabled, fold
6619 // (fsub x, x) -> 0.0 &
6620 // (fsub x, (fadd x, y)) -> (fneg y) &
6621 // (fsub x, (fadd y, x)) -> (fneg y)
6622 if (DAG.getTarget().Options.UnsafeFPMath) {
6624 return DAG.getConstantFP(0.0f, VT);
6626 if (N1.getOpcode() == ISD::FADD) {
6627 SDValue N10 = N1->getOperand(0);
6628 SDValue N11 = N1->getOperand(1);
6630 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6631 &DAG.getTarget().Options))
6632 return GetNegatedExpression(N11, DAG, LegalOperations);
6634 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6635 &DAG.getTarget().Options))
6636 return GetNegatedExpression(N10, DAG, LegalOperations);
6640 // FSUB -> FMA combines:
6641 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6642 DAG.getTarget().Options.UnsafeFPMath) &&
6643 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6644 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6646 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6647 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6648 return DAG.getNode(ISD::FMA, dl, VT,
6649 N0.getOperand(0), N0.getOperand(1),
6650 DAG.getNode(ISD::FNEG, dl, VT, N1));
6652 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6653 // Note: Commutes FSUB operands.
6654 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6655 return DAG.getNode(ISD::FMA, dl, VT,
6656 DAG.getNode(ISD::FNEG, dl, VT,
6658 N1.getOperand(1), N0);
6660 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6661 if (N0.getOpcode() == ISD::FNEG &&
6662 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6663 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6664 SDValue N00 = N0.getOperand(0).getOperand(0);
6665 SDValue N01 = N0.getOperand(0).getOperand(1);
6666 return DAG.getNode(ISD::FMA, dl, VT,
6667 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6668 DAG.getNode(ISD::FNEG, dl, VT, N1));
6675 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6676 SDValue N0 = N->getOperand(0);
6677 SDValue N1 = N->getOperand(1);
6678 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6679 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6680 EVT VT = N->getValueType(0);
6681 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6684 if (VT.isVector()) {
6685 SDValue FoldedVOp = SimplifyVBinOp(N);
6686 if (FoldedVOp.getNode()) return FoldedVOp;
6689 // fold (fmul c1, c2) -> c1*c2
6691 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6692 // canonicalize constant to RHS
6693 if (N0CFP && !N1CFP)
6694 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6695 // fold (fmul A, 0) -> 0
6696 if (DAG.getTarget().Options.UnsafeFPMath &&
6697 N1CFP && N1CFP->getValueAPF().isZero())
6699 // fold (fmul A, 0) -> 0, vector edition.
6700 if (DAG.getTarget().Options.UnsafeFPMath &&
6701 ISD::isBuildVectorAllZeros(N1.getNode()))
6703 // fold (fmul A, 1.0) -> A
6704 if (N1CFP && N1CFP->isExactlyValue(1.0))
6706 // fold (fmul X, 2.0) -> (fadd X, X)
6707 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6708 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6709 // fold (fmul X, -1.0) -> (fneg X)
6710 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6711 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6712 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6714 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6715 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6716 &DAG.getTarget().Options)) {
6717 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6718 &DAG.getTarget().Options)) {
6719 // Both can be negated for free, check to see if at least one is cheaper
6721 if (LHSNeg == 2 || RHSNeg == 2)
6722 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6723 GetNegatedExpression(N0, DAG, LegalOperations),
6724 GetNegatedExpression(N1, DAG, LegalOperations));
6728 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6729 if (DAG.getTarget().Options.UnsafeFPMath &&
6730 N1CFP && N0.getOpcode() == ISD::FMUL &&
6731 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6732 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6733 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6734 N0.getOperand(1), N1));
6739 SDValue DAGCombiner::visitFMA(SDNode *N) {
6740 SDValue N0 = N->getOperand(0);
6741 SDValue N1 = N->getOperand(1);
6742 SDValue N2 = N->getOperand(2);
6743 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6744 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6745 EVT VT = N->getValueType(0);
6748 if (DAG.getTarget().Options.UnsafeFPMath) {
6749 if (N0CFP && N0CFP->isZero())
6751 if (N1CFP && N1CFP->isZero())
6754 if (N0CFP && N0CFP->isExactlyValue(1.0))
6755 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6756 if (N1CFP && N1CFP->isExactlyValue(1.0))
6757 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6759 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6760 if (N0CFP && !N1CFP)
6761 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6763 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6764 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6765 N2.getOpcode() == ISD::FMUL &&
6766 N0 == N2.getOperand(0) &&
6767 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6768 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6769 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6773 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6774 if (DAG.getTarget().Options.UnsafeFPMath &&
6775 N0.getOpcode() == ISD::FMUL && N1CFP &&
6776 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6777 return DAG.getNode(ISD::FMA, dl, VT,
6779 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6783 // (fma x, 1, y) -> (fadd x, y)
6784 // (fma x, -1, y) -> (fadd (fneg x), y)
6786 if (N1CFP->isExactlyValue(1.0))
6787 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6789 if (N1CFP->isExactlyValue(-1.0) &&
6790 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6791 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6792 AddToWorkList(RHSNeg.getNode());
6793 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6797 // (fma x, c, x) -> (fmul x, (c+1))
6798 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6799 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6800 DAG.getNode(ISD::FADD, dl, VT,
6801 N1, DAG.getConstantFP(1.0, VT)));
6803 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6804 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6805 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6806 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6807 DAG.getNode(ISD::FADD, dl, VT,
6808 N1, DAG.getConstantFP(-1.0, VT)));
6814 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6815 SDValue N0 = N->getOperand(0);
6816 SDValue N1 = N->getOperand(1);
6817 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6818 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6819 EVT VT = N->getValueType(0);
6820 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6823 if (VT.isVector()) {
6824 SDValue FoldedVOp = SimplifyVBinOp(N);
6825 if (FoldedVOp.getNode()) return FoldedVOp;
6828 // fold (fdiv c1, c2) -> c1/c2
6830 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6832 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6833 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6834 // Compute the reciprocal 1.0 / c2.
6835 APFloat N1APF = N1CFP->getValueAPF();
6836 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6837 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6838 // Only do the transform if the reciprocal is a legal fp immediate that
6839 // isn't too nasty (eg NaN, denormal, ...).
6840 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6841 (!LegalOperations ||
6842 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6843 // backend)... we should handle this gracefully after Legalize.
6844 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6845 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6846 TLI.isFPImmLegal(Recip, VT)))
6847 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6848 DAG.getConstantFP(Recip, VT));
6851 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6852 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6853 &DAG.getTarget().Options)) {
6854 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6855 &DAG.getTarget().Options)) {
6856 // Both can be negated for free, check to see if at least one is cheaper
6858 if (LHSNeg == 2 || RHSNeg == 2)
6859 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6860 GetNegatedExpression(N0, DAG, LegalOperations),
6861 GetNegatedExpression(N1, DAG, LegalOperations));
6868 SDValue DAGCombiner::visitFREM(SDNode *N) {
6869 SDValue N0 = N->getOperand(0);
6870 SDValue N1 = N->getOperand(1);
6871 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6872 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6873 EVT VT = N->getValueType(0);
6875 // fold (frem c1, c2) -> fmod(c1,c2)
6877 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6882 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6883 SDValue N0 = N->getOperand(0);
6884 SDValue N1 = N->getOperand(1);
6885 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6886 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6887 EVT VT = N->getValueType(0);
6889 if (N0CFP && N1CFP) // Constant fold
6890 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6893 const APFloat& V = N1CFP->getValueAPF();
6894 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6895 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6896 if (!V.isNegative()) {
6897 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6898 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6900 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6901 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6902 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6906 // copysign(fabs(x), y) -> copysign(x, y)
6907 // copysign(fneg(x), y) -> copysign(x, y)
6908 // copysign(copysign(x,z), y) -> copysign(x, y)
6909 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6910 N0.getOpcode() == ISD::FCOPYSIGN)
6911 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6912 N0.getOperand(0), N1);
6914 // copysign(x, abs(y)) -> abs(x)
6915 if (N1.getOpcode() == ISD::FABS)
6916 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6918 // copysign(x, copysign(y,z)) -> copysign(x, z)
6919 if (N1.getOpcode() == ISD::FCOPYSIGN)
6920 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6921 N0, N1.getOperand(1));
6923 // copysign(x, fp_extend(y)) -> copysign(x, y)
6924 // copysign(x, fp_round(y)) -> copysign(x, y)
6925 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6926 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6927 N0, N1.getOperand(0));
6932 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6933 SDValue N0 = N->getOperand(0);
6934 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6935 EVT VT = N->getValueType(0);
6936 EVT OpVT = N0.getValueType();
6938 // fold (sint_to_fp c1) -> c1fp
6940 // ...but only if the target supports immediate floating-point values
6941 (!LegalOperations ||
6942 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6943 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6945 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6946 // but UINT_TO_FP is legal on this target, try to convert.
6947 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6948 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6949 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6950 if (DAG.SignBitIsZero(N0))
6951 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6954 // The next optimizations are desirable only if SELECT_CC can be lowered.
6955 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6956 // having to say they don't support SELECT_CC on every type the DAG knows
6957 // about, since there is no way to mark an opcode illegal at all value types
6958 // (See also visitSELECT)
6959 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6960 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6961 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6963 (!LegalOperations ||
6964 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6966 { N0.getOperand(0), N0.getOperand(1),
6967 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6969 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
6972 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6973 // (select_cc x, y, 1.0, 0.0,, cc)
6974 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6975 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6976 (!LegalOperations ||
6977 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6979 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6980 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6981 N0.getOperand(0).getOperand(2) };
6982 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
6989 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6990 SDValue N0 = N->getOperand(0);
6991 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6992 EVT VT = N->getValueType(0);
6993 EVT OpVT = N0.getValueType();
6995 // fold (uint_to_fp c1) -> c1fp
6997 // ...but only if the target supports immediate floating-point values
6998 (!LegalOperations ||
6999 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7000 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7002 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7003 // but SINT_TO_FP is legal on this target, try to convert.
7004 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7005 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7006 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7007 if (DAG.SignBitIsZero(N0))
7008 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7011 // The next optimizations are desirable only if SELECT_CC can be lowered.
7012 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
7013 // having to say they don't support SELECT_CC on every type the DAG knows
7014 // about, since there is no way to mark an opcode illegal at all value types
7015 // (See also visitSELECT)
7016 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
7017 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7019 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7020 (!LegalOperations ||
7021 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7023 { N0.getOperand(0), N0.getOperand(1),
7024 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7026 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7033 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7034 SDValue N0 = N->getOperand(0);
7035 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7036 EVT VT = N->getValueType(0);
7038 // fold (fp_to_sint c1fp) -> c1
7040 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7045 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7046 SDValue N0 = N->getOperand(0);
7047 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7048 EVT VT = N->getValueType(0);
7050 // fold (fp_to_uint c1fp) -> c1
7052 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7057 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7058 SDValue N0 = N->getOperand(0);
7059 SDValue N1 = N->getOperand(1);
7060 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7061 EVT VT = N->getValueType(0);
7063 // fold (fp_round c1fp) -> c1fp
7065 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7067 // fold (fp_round (fp_extend x)) -> x
7068 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7069 return N0.getOperand(0);
7071 // fold (fp_round (fp_round x)) -> (fp_round x)
7072 if (N0.getOpcode() == ISD::FP_ROUND) {
7073 // This is a value preserving truncation if both round's are.
7074 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7075 N0.getNode()->getConstantOperandVal(1) == 1;
7076 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7077 DAG.getIntPtrConstant(IsTrunc));
7080 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7081 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7082 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7083 N0.getOperand(0), N1);
7084 AddToWorkList(Tmp.getNode());
7085 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7086 Tmp, N0.getOperand(1));
7092 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7093 SDValue N0 = N->getOperand(0);
7094 EVT VT = N->getValueType(0);
7095 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7096 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7098 // fold (fp_round_inreg c1fp) -> c1fp
7099 if (N0CFP && isTypeLegal(EVT)) {
7100 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7101 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7107 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7108 SDValue N0 = N->getOperand(0);
7109 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7110 EVT VT = N->getValueType(0);
7112 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7113 if (N->hasOneUse() &&
7114 N->use_begin()->getOpcode() == ISD::FP_ROUND)
7117 // fold (fp_extend c1fp) -> c1fp
7119 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7121 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7123 if (N0.getOpcode() == ISD::FP_ROUND
7124 && N0.getNode()->getConstantOperandVal(1) == 1) {
7125 SDValue In = N0.getOperand(0);
7126 if (In.getValueType() == VT) return In;
7127 if (VT.bitsLT(In.getValueType()))
7128 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7129 In, N0.getOperand(1));
7130 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7133 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7134 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7135 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7136 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
7137 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7138 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7140 LN0->getBasePtr(), N0.getValueType(),
7141 LN0->getMemOperand());
7142 CombineTo(N, ExtLoad);
7143 CombineTo(N0.getNode(),
7144 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7145 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7146 ExtLoad.getValue(1));
7147 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7153 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7154 SDValue N0 = N->getOperand(0);
7155 EVT VT = N->getValueType(0);
7157 if (VT.isVector()) {
7158 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7159 if (FoldedVOp.getNode()) return FoldedVOp;
7162 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7163 &DAG.getTarget().Options))
7164 return GetNegatedExpression(N0, DAG, LegalOperations);
7166 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7167 // constant pool values.
7168 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7170 N0.getNode()->hasOneUse() &&
7171 N0.getOperand(0).getValueType().isInteger()) {
7172 SDValue Int = N0.getOperand(0);
7173 EVT IntVT = Int.getValueType();
7174 if (IntVT.isInteger() && !IntVT.isVector()) {
7175 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7176 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7177 AddToWorkList(Int.getNode());
7178 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7183 // (fneg (fmul c, x)) -> (fmul -c, x)
7184 if (N0.getOpcode() == ISD::FMUL) {
7185 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7187 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7189 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7196 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7197 SDValue N0 = N->getOperand(0);
7198 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7199 EVT VT = N->getValueType(0);
7201 // fold (fceil c1) -> fceil(c1)
7203 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7208 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7209 SDValue N0 = N->getOperand(0);
7210 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7211 EVT VT = N->getValueType(0);
7213 // fold (ftrunc c1) -> ftrunc(c1)
7215 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7220 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7221 SDValue N0 = N->getOperand(0);
7222 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7223 EVT VT = N->getValueType(0);
7225 // fold (ffloor c1) -> ffloor(c1)
7227 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7232 SDValue DAGCombiner::visitFABS(SDNode *N) {
7233 SDValue N0 = N->getOperand(0);
7234 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7235 EVT VT = N->getValueType(0);
7237 if (VT.isVector()) {
7238 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7239 if (FoldedVOp.getNode()) return FoldedVOp;
7242 // fold (fabs c1) -> fabs(c1)
7244 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7245 // fold (fabs (fabs x)) -> (fabs x)
7246 if (N0.getOpcode() == ISD::FABS)
7247 return N->getOperand(0);
7248 // fold (fabs (fneg x)) -> (fabs x)
7249 // fold (fabs (fcopysign x, y)) -> (fabs x)
7250 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7251 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7253 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7254 // constant pool values.
7255 if (!TLI.isFAbsFree(VT) &&
7256 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7257 N0.getOperand(0).getValueType().isInteger() &&
7258 !N0.getOperand(0).getValueType().isVector()) {
7259 SDValue Int = N0.getOperand(0);
7260 EVT IntVT = Int.getValueType();
7261 if (IntVT.isInteger() && !IntVT.isVector()) {
7262 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7263 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7264 AddToWorkList(Int.getNode());
7265 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7266 N->getValueType(0), Int);
7273 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7274 SDValue Chain = N->getOperand(0);
7275 SDValue N1 = N->getOperand(1);
7276 SDValue N2 = N->getOperand(2);
7278 // If N is a constant we could fold this into a fallthrough or unconditional
7279 // branch. However that doesn't happen very often in normal code, because
7280 // Instcombine/SimplifyCFG should have handled the available opportunities.
7281 // If we did this folding here, it would be necessary to update the
7282 // MachineBasicBlock CFG, which is awkward.
7284 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7286 if (N1.getOpcode() == ISD::SETCC &&
7287 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7288 N1.getOperand(0).getValueType())) {
7289 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7290 Chain, N1.getOperand(2),
7291 N1.getOperand(0), N1.getOperand(1), N2);
7294 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7295 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7296 (N1.getOperand(0).hasOneUse() &&
7297 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7298 SDNode *Trunc = nullptr;
7299 if (N1.getOpcode() == ISD::TRUNCATE) {
7300 // Look pass the truncate.
7301 Trunc = N1.getNode();
7302 N1 = N1.getOperand(0);
7305 // Match this pattern so that we can generate simpler code:
7308 // %b = and i32 %a, 2
7309 // %c = srl i32 %b, 1
7310 // brcond i32 %c ...
7315 // %b = and i32 %a, 2
7316 // %c = setcc eq %b, 0
7319 // This applies only when the AND constant value has one bit set and the
7320 // SRL constant is equal to the log2 of the AND constant. The back-end is
7321 // smart enough to convert the result into a TEST/JMP sequence.
7322 SDValue Op0 = N1.getOperand(0);
7323 SDValue Op1 = N1.getOperand(1);
7325 if (Op0.getOpcode() == ISD::AND &&
7326 Op1.getOpcode() == ISD::Constant) {
7327 SDValue AndOp1 = Op0.getOperand(1);
7329 if (AndOp1.getOpcode() == ISD::Constant) {
7330 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7332 if (AndConst.isPowerOf2() &&
7333 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7335 DAG.getSetCC(SDLoc(N),
7336 getSetCCResultType(Op0.getValueType()),
7337 Op0, DAG.getConstant(0, Op0.getValueType()),
7340 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7341 MVT::Other, Chain, SetCC, N2);
7342 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7343 // will convert it back to (X & C1) >> C2.
7344 CombineTo(N, NewBRCond, false);
7345 // Truncate is dead.
7347 removeFromWorkList(Trunc);
7348 DAG.DeleteNode(Trunc);
7350 // Replace the uses of SRL with SETCC
7351 WorkListRemover DeadNodes(*this);
7352 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7353 removeFromWorkList(N1.getNode());
7354 DAG.DeleteNode(N1.getNode());
7355 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7361 // Restore N1 if the above transformation doesn't match.
7362 N1 = N->getOperand(1);
7365 // Transform br(xor(x, y)) -> br(x != y)
7366 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7367 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7368 SDNode *TheXor = N1.getNode();
7369 SDValue Op0 = TheXor->getOperand(0);
7370 SDValue Op1 = TheXor->getOperand(1);
7371 if (Op0.getOpcode() == Op1.getOpcode()) {
7372 // Avoid missing important xor optimizations.
7373 SDValue Tmp = visitXOR(TheXor);
7374 if (Tmp.getNode()) {
7375 if (Tmp.getNode() != TheXor) {
7376 DEBUG(dbgs() << "\nReplacing.8 ";
7378 dbgs() << "\nWith: ";
7379 Tmp.getNode()->dump(&DAG);
7381 WorkListRemover DeadNodes(*this);
7382 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7383 removeFromWorkList(TheXor);
7384 DAG.DeleteNode(TheXor);
7385 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7386 MVT::Other, Chain, Tmp, N2);
7389 // visitXOR has changed XOR's operands or replaced the XOR completely,
7391 return SDValue(N, 0);
7395 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7397 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7398 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7399 Op0.getOpcode() == ISD::XOR) {
7400 TheXor = Op0.getNode();
7404 EVT SetCCVT = N1.getValueType();
7406 SetCCVT = getSetCCResultType(SetCCVT);
7407 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7410 Equal ? ISD::SETEQ : ISD::SETNE);
7411 // Replace the uses of XOR with SETCC
7412 WorkListRemover DeadNodes(*this);
7413 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7414 removeFromWorkList(N1.getNode());
7415 DAG.DeleteNode(N1.getNode());
7416 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7417 MVT::Other, Chain, SetCC, N2);
7424 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7426 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7427 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7428 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7430 // If N is a constant we could fold this into a fallthrough or unconditional
7431 // branch. However that doesn't happen very often in normal code, because
7432 // Instcombine/SimplifyCFG should have handled the available opportunities.
7433 // If we did this folding here, it would be necessary to update the
7434 // MachineBasicBlock CFG, which is awkward.
7436 // Use SimplifySetCC to simplify SETCC's.
7437 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7438 CondLHS, CondRHS, CC->get(), SDLoc(N),
7440 if (Simp.getNode()) AddToWorkList(Simp.getNode());
7442 // fold to a simpler setcc
7443 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7444 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7445 N->getOperand(0), Simp.getOperand(2),
7446 Simp.getOperand(0), Simp.getOperand(1),
7452 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7453 /// uses N as its base pointer and that N may be folded in the load / store
7454 /// addressing mode.
7455 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7457 const TargetLowering &TLI) {
7459 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7460 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7462 VT = Use->getValueType(0);
7463 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7464 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7466 VT = ST->getValue().getValueType();
7470 TargetLowering::AddrMode AM;
7471 if (N->getOpcode() == ISD::ADD) {
7472 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7475 AM.BaseOffs = Offset->getSExtValue();
7479 } else if (N->getOpcode() == ISD::SUB) {
7480 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7483 AM.BaseOffs = -Offset->getSExtValue();
7490 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7493 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7494 /// pre-indexed load / store when the base pointer is an add or subtract
7495 /// and it has other uses besides the load / store. After the
7496 /// transformation, the new indexed load / store has effectively folded
7497 /// the add / subtract in and all of its other uses are redirected to the
7498 /// new load / store.
7499 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7500 if (Level < AfterLegalizeDAG)
7506 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7507 if (LD->isIndexed())
7509 VT = LD->getMemoryVT();
7510 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7511 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7513 Ptr = LD->getBasePtr();
7514 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7515 if (ST->isIndexed())
7517 VT = ST->getMemoryVT();
7518 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7519 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7521 Ptr = ST->getBasePtr();
7527 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7528 // out. There is no reason to make this a preinc/predec.
7529 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7530 Ptr.getNode()->hasOneUse())
7533 // Ask the target to do addressing mode selection.
7536 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7537 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7540 // Backends without true r+i pre-indexed forms may need to pass a
7541 // constant base with a variable offset so that constant coercion
7542 // will work with the patterns in canonical form.
7543 bool Swapped = false;
7544 if (isa<ConstantSDNode>(BasePtr)) {
7545 std::swap(BasePtr, Offset);
7549 // Don't create a indexed load / store with zero offset.
7550 if (isa<ConstantSDNode>(Offset) &&
7551 cast<ConstantSDNode>(Offset)->isNullValue())
7554 // Try turning it into a pre-indexed load / store except when:
7555 // 1) The new base ptr is a frame index.
7556 // 2) If N is a store and the new base ptr is either the same as or is a
7557 // predecessor of the value being stored.
7558 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7559 // that would create a cycle.
7560 // 4) All uses are load / store ops that use it as old base ptr.
7562 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7563 // (plus the implicit offset) to a register to preinc anyway.
7564 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7569 SDValue Val = cast<StoreSDNode>(N)->getValue();
7570 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7574 // If the offset is a constant, there may be other adds of constants that
7575 // can be folded with this one. We should do this to avoid having to keep
7576 // a copy of the original base pointer.
7577 SmallVector<SDNode *, 16> OtherUses;
7578 if (isa<ConstantSDNode>(Offset))
7579 for (SDNode *Use : BasePtr.getNode()->uses()) {
7580 if (Use == Ptr.getNode())
7583 if (Use->isPredecessorOf(N))
7586 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7591 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7592 if (Op1.getNode() == BasePtr.getNode())
7593 std::swap(Op0, Op1);
7594 assert(Op0.getNode() == BasePtr.getNode() &&
7595 "Use of ADD/SUB but not an operand");
7597 if (!isa<ConstantSDNode>(Op1)) {
7602 // FIXME: In some cases, we can be smarter about this.
7603 if (Op1.getValueType() != Offset.getValueType()) {
7608 OtherUses.push_back(Use);
7612 std::swap(BasePtr, Offset);
7614 // Now check for #3 and #4.
7615 bool RealUse = false;
7617 // Caches for hasPredecessorHelper
7618 SmallPtrSet<const SDNode *, 32> Visited;
7619 SmallVector<const SDNode *, 16> Worklist;
7621 for (SDNode *Use : Ptr.getNode()->uses()) {
7624 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7627 // If Ptr may be folded in addressing mode of other use, then it's
7628 // not profitable to do this transformation.
7629 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7638 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7639 BasePtr, Offset, AM);
7641 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7642 BasePtr, Offset, AM);
7645 DEBUG(dbgs() << "\nReplacing.4 ";
7647 dbgs() << "\nWith: ";
7648 Result.getNode()->dump(&DAG);
7650 WorkListRemover DeadNodes(*this);
7652 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7653 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7655 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7658 // Finally, since the node is now dead, remove it from the graph.
7662 std::swap(BasePtr, Offset);
7664 // Replace other uses of BasePtr that can be updated to use Ptr
7665 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7666 unsigned OffsetIdx = 1;
7667 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7669 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7670 BasePtr.getNode() && "Expected BasePtr operand");
7672 // We need to replace ptr0 in the following expression:
7673 // x0 * offset0 + y0 * ptr0 = t0
7675 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7677 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7678 // indexed load/store and the expresion that needs to be re-written.
7680 // Therefore, we have:
7681 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7683 ConstantSDNode *CN =
7684 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7686 APInt Offset0 = CN->getAPIntValue();
7687 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7689 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7690 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7691 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7692 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7694 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7696 APInt CNV = Offset0;
7697 if (X0 < 0) CNV = -CNV;
7698 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7699 else CNV = CNV - Offset1;
7701 // We can now generate the new expression.
7702 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7703 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7705 SDValue NewUse = DAG.getNode(Opcode,
7706 SDLoc(OtherUses[i]),
7707 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7708 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7709 removeFromWorkList(OtherUses[i]);
7710 DAG.DeleteNode(OtherUses[i]);
7713 // Replace the uses of Ptr with uses of the updated base value.
7714 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7715 removeFromWorkList(Ptr.getNode());
7716 DAG.DeleteNode(Ptr.getNode());
7721 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7722 /// add / sub of the base pointer node into a post-indexed load / store.
7723 /// The transformation folded the add / subtract into the new indexed
7724 /// load / store effectively and all of its uses are redirected to the
7725 /// new load / store.
7726 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7727 if (Level < AfterLegalizeDAG)
7733 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7734 if (LD->isIndexed())
7736 VT = LD->getMemoryVT();
7737 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7738 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7740 Ptr = LD->getBasePtr();
7741 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7742 if (ST->isIndexed())
7744 VT = ST->getMemoryVT();
7745 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7746 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7748 Ptr = ST->getBasePtr();
7754 if (Ptr.getNode()->hasOneUse())
7757 for (SDNode *Op : Ptr.getNode()->uses()) {
7759 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7764 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7765 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7766 // Don't create a indexed load / store with zero offset.
7767 if (isa<ConstantSDNode>(Offset) &&
7768 cast<ConstantSDNode>(Offset)->isNullValue())
7771 // Try turning it into a post-indexed load / store except when
7772 // 1) All uses are load / store ops that use it as base ptr (and
7773 // it may be folded as addressing mmode).
7774 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7775 // nor a successor of N. Otherwise, if Op is folded that would
7778 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7782 bool TryNext = false;
7783 for (SDNode *Use : BasePtr.getNode()->uses()) {
7784 if (Use == Ptr.getNode())
7787 // If all the uses are load / store addresses, then don't do the
7789 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7790 bool RealUse = false;
7791 for (SDNode *UseUse : Use->uses()) {
7792 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7807 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7808 SDValue Result = isLoad
7809 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7810 BasePtr, Offset, AM)
7811 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7812 BasePtr, Offset, AM);
7815 DEBUG(dbgs() << "\nReplacing.5 ";
7817 dbgs() << "\nWith: ";
7818 Result.getNode()->dump(&DAG);
7820 WorkListRemover DeadNodes(*this);
7822 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7823 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7825 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7828 // Finally, since the node is now dead, remove it from the graph.
7831 // Replace the uses of Use with uses of the updated base value.
7832 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7833 Result.getValue(isLoad ? 1 : 0));
7834 removeFromWorkList(Op);
7844 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7845 LoadSDNode *LD = cast<LoadSDNode>(N);
7846 SDValue Chain = LD->getChain();
7847 SDValue Ptr = LD->getBasePtr();
7849 // If load is not volatile and there are no uses of the loaded value (and
7850 // the updated indexed value in case of indexed loads), change uses of the
7851 // chain value into uses of the chain input (i.e. delete the dead load).
7852 if (!LD->isVolatile()) {
7853 if (N->getValueType(1) == MVT::Other) {
7855 if (!N->hasAnyUseOfValue(0)) {
7856 // It's not safe to use the two value CombineTo variant here. e.g.
7857 // v1, chain2 = load chain1, loc
7858 // v2, chain3 = load chain2, loc
7860 // Now we replace use of chain2 with chain1. This makes the second load
7861 // isomorphic to the one we are deleting, and thus makes this load live.
7862 DEBUG(dbgs() << "\nReplacing.6 ";
7864 dbgs() << "\nWith chain: ";
7865 Chain.getNode()->dump(&DAG);
7867 WorkListRemover DeadNodes(*this);
7868 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7870 if (N->use_empty()) {
7871 removeFromWorkList(N);
7875 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7879 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7880 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7881 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7882 DEBUG(dbgs() << "\nReplacing.7 ";
7884 dbgs() << "\nWith: ";
7885 Undef.getNode()->dump(&DAG);
7886 dbgs() << " and 2 other values\n");
7887 WorkListRemover DeadNodes(*this);
7888 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7889 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7890 DAG.getUNDEF(N->getValueType(1)));
7891 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7892 removeFromWorkList(N);
7894 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7899 // If this load is directly stored, replace the load value with the stored
7901 // TODO: Handle store large -> read small portion.
7902 // TODO: Handle TRUNCSTORE/LOADEXT
7903 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7904 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7905 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7906 if (PrevST->getBasePtr() == Ptr &&
7907 PrevST->getValue().getValueType() == N->getValueType(0))
7908 return CombineTo(N, Chain.getOperand(1), Chain);
7912 // Try to infer better alignment information than the load already has.
7913 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7914 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7915 if (Align > LD->getMemOperand()->getBaseAlignment()) {
7917 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7918 LD->getValueType(0),
7919 Chain, Ptr, LD->getPointerInfo(),
7921 LD->isVolatile(), LD->isNonTemporal(), Align,
7923 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7928 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7929 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7931 if (CombinerAAOnlyFunc.getNumOccurrences() &&
7932 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
7935 if (UseAA && LD->isUnindexed()) {
7936 // Walk up chain skipping non-aliasing memory nodes.
7937 SDValue BetterChain = FindBetterChain(N, Chain);
7939 // If there is a better chain.
7940 if (Chain != BetterChain) {
7943 // Replace the chain to void dependency.
7944 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7945 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7946 BetterChain, Ptr, LD->getMemOperand());
7948 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7949 LD->getValueType(0),
7950 BetterChain, Ptr, LD->getMemoryVT(),
7951 LD->getMemOperand());
7954 // Create token factor to keep old chain connected.
7955 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7956 MVT::Other, Chain, ReplLoad.getValue(1));
7958 // Make sure the new and old chains are cleaned up.
7959 AddToWorkList(Token.getNode());
7961 // Replace uses with load result and token factor. Don't add users
7963 return CombineTo(N, ReplLoad.getValue(0), Token, false);
7967 // Try transforming N to an indexed load.
7968 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7969 return SDValue(N, 0);
7971 // Try to slice up N to more direct loads if the slices are mapped to
7972 // different register banks or pairing can take place.
7974 return SDValue(N, 0);
7980 /// \brief Helper structure used to slice a load in smaller loads.
7981 /// Basically a slice is obtained from the following sequence:
7982 /// Origin = load Ty1, Base
7983 /// Shift = srl Ty1 Origin, CstTy Amount
7984 /// Inst = trunc Shift to Ty2
7986 /// Then, it will be rewriten into:
7987 /// Slice = load SliceTy, Base + SliceOffset
7988 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
7990 /// SliceTy is deduced from the number of bits that are actually used to
7992 struct LoadedSlice {
7993 /// \brief Helper structure used to compute the cost of a slice.
7995 /// Are we optimizing for code size.
8000 unsigned CrossRegisterBanksCopies;
8004 Cost(bool ForCodeSize = false)
8005 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8006 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8008 /// \brief Get the cost of one isolated slice.
8009 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8010 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8011 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8012 EVT TruncType = LS.Inst->getValueType(0);
8013 EVT LoadedType = LS.getLoadedType();
8014 if (TruncType != LoadedType &&
8015 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8019 /// \brief Account for slicing gain in the current cost.
8020 /// Slicing provide a few gains like removing a shift or a
8021 /// truncate. This method allows to grow the cost of the original
8022 /// load with the gain from this slice.
8023 void addSliceGain(const LoadedSlice &LS) {
8024 // Each slice saves a truncate.
8025 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8026 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8027 LS.Inst->getOperand(0).getValueType()))
8029 // If there is a shift amount, this slice gets rid of it.
8032 // If this slice can merge a cross register bank copy, account for it.
8033 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8034 ++CrossRegisterBanksCopies;
8037 Cost &operator+=(const Cost &RHS) {
8039 Truncates += RHS.Truncates;
8040 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8046 bool operator==(const Cost &RHS) const {
8047 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8048 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8049 ZExts == RHS.ZExts && Shift == RHS.Shift;
8052 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8054 bool operator<(const Cost &RHS) const {
8055 // Assume cross register banks copies are as expensive as loads.
8056 // FIXME: Do we want some more target hooks?
8057 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8058 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8059 // Unless we are optimizing for code size, consider the
8060 // expensive operation first.
8061 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8062 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8063 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8064 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8067 bool operator>(const Cost &RHS) const { return RHS < *this; }
8069 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8071 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8073 // The last instruction that represent the slice. This should be a
8074 // truncate instruction.
8076 // The original load instruction.
8078 // The right shift amount in bits from the original load.
8080 // The DAG from which Origin came from.
8081 // This is used to get some contextual information about legal types, etc.
8084 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8085 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8086 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8088 LoadedSlice(const LoadedSlice &LS)
8089 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8091 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8092 /// \return Result is \p BitWidth and has used bits set to 1 and
8093 /// not used bits set to 0.
8094 APInt getUsedBits() const {
8095 // Reproduce the trunc(lshr) sequence:
8096 // - Start from the truncated value.
8097 // - Zero extend to the desired bit width.
8099 assert(Origin && "No original load to compare against.");
8100 unsigned BitWidth = Origin->getValueSizeInBits(0);
8101 assert(Inst && "This slice is not bound to an instruction");
8102 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8103 "Extracted slice is bigger than the whole type!");
8104 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8105 UsedBits.setAllBits();
8106 UsedBits = UsedBits.zext(BitWidth);
8111 /// \brief Get the size of the slice to be loaded in bytes.
8112 unsigned getLoadedSize() const {
8113 unsigned SliceSize = getUsedBits().countPopulation();
8114 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8115 return SliceSize / 8;
8118 /// \brief Get the type that will be loaded for this slice.
8119 /// Note: This may not be the final type for the slice.
8120 EVT getLoadedType() const {
8121 assert(DAG && "Missing context");
8122 LLVMContext &Ctxt = *DAG->getContext();
8123 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8126 /// \brief Get the alignment of the load used for this slice.
8127 unsigned getAlignment() const {
8128 unsigned Alignment = Origin->getAlignment();
8129 unsigned Offset = getOffsetFromBase();
8131 Alignment = MinAlign(Alignment, Alignment + Offset);
8135 /// \brief Check if this slice can be rewritten with legal operations.
8136 bool isLegal() const {
8137 // An invalid slice is not legal.
8138 if (!Origin || !Inst || !DAG)
8141 // Offsets are for indexed load only, we do not handle that.
8142 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8145 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8147 // Check that the type is legal.
8148 EVT SliceType = getLoadedType();
8149 if (!TLI.isTypeLegal(SliceType))
8152 // Check that the load is legal for this type.
8153 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8156 // Check that the offset can be computed.
8157 // 1. Check its type.
8158 EVT PtrType = Origin->getBasePtr().getValueType();
8159 if (PtrType == MVT::Untyped || PtrType.isExtended())
8162 // 2. Check that it fits in the immediate.
8163 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8166 // 3. Check that the computation is legal.
8167 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8170 // Check that the zext is legal if it needs one.
8171 EVT TruncateType = Inst->getValueType(0);
8172 if (TruncateType != SliceType &&
8173 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8179 /// \brief Get the offset in bytes of this slice in the original chunk of
8181 /// \pre DAG != nullptr.
8182 uint64_t getOffsetFromBase() const {
8183 assert(DAG && "Missing context.");
8185 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8186 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8187 uint64_t Offset = Shift / 8;
8188 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8189 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8190 "The size of the original loaded type is not a multiple of a"
8192 // If Offset is bigger than TySizeInBytes, it means we are loading all
8193 // zeros. This should have been optimized before in the process.
8194 assert(TySizeInBytes > Offset &&
8195 "Invalid shift amount for given loaded size");
8197 Offset = TySizeInBytes - Offset - getLoadedSize();
8201 /// \brief Generate the sequence of instructions to load the slice
8202 /// represented by this object and redirect the uses of this slice to
8203 /// this new sequence of instructions.
8204 /// \pre this->Inst && this->Origin are valid Instructions and this
8205 /// object passed the legal check: LoadedSlice::isLegal returned true.
8206 /// \return The last instruction of the sequence used to load the slice.
8207 SDValue loadSlice() const {
8208 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8209 const SDValue &OldBaseAddr = Origin->getBasePtr();
8210 SDValue BaseAddr = OldBaseAddr;
8211 // Get the offset in that chunk of bytes w.r.t. the endianess.
8212 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8213 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8215 // BaseAddr = BaseAddr + Offset.
8216 EVT ArithType = BaseAddr.getValueType();
8217 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8218 DAG->getConstant(Offset, ArithType));
8221 // Create the type of the loaded slice according to its size.
8222 EVT SliceType = getLoadedType();
8224 // Create the load for the slice.
8225 SDValue LastInst = DAG->getLoad(
8226 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8227 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8228 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8229 // If the final type is not the same as the loaded type, this means that
8230 // we have to pad with zero. Create a zero extend for that.
8231 EVT FinalType = Inst->getValueType(0);
8232 if (SliceType != FinalType)
8234 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8238 /// \brief Check if this slice can be merged with an expensive cross register
8239 /// bank copy. E.g.,
8241 /// f = bitcast i32 i to float
8242 bool canMergeExpensiveCrossRegisterBankCopy() const {
8243 if (!Inst || !Inst->hasOneUse())
8245 SDNode *Use = *Inst->use_begin();
8246 if (Use->getOpcode() != ISD::BITCAST)
8248 assert(DAG && "Missing context");
8249 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8250 EVT ResVT = Use->getValueType(0);
8251 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8252 const TargetRegisterClass *ArgRC =
8253 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8254 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8257 // At this point, we know that we perform a cross-register-bank copy.
8258 // Check if it is expensive.
8259 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8260 // Assume bitcasts are cheap, unless both register classes do not
8261 // explicitly share a common sub class.
8262 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8265 // Check if it will be merged with the load.
8266 // 1. Check the alignment constraint.
8267 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8268 ResVT.getTypeForEVT(*DAG->getContext()));
8270 if (RequiredAlignment > getAlignment())
8273 // 2. Check that the load is a legal operation for that type.
8274 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8277 // 3. Check that we do not have a zext in the way.
8278 if (Inst->getValueType(0) != getLoadedType())
8286 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8287 /// \p UsedBits looks like 0..0 1..1 0..0.
8288 static bool areUsedBitsDense(const APInt &UsedBits) {
8289 // If all the bits are one, this is dense!
8290 if (UsedBits.isAllOnesValue())
8293 // Get rid of the unused bits on the right.
8294 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8295 // Get rid of the unused bits on the left.
8296 if (NarrowedUsedBits.countLeadingZeros())
8297 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8298 // Check that the chunk of bits is completely used.
8299 return NarrowedUsedBits.isAllOnesValue();
8302 /// \brief Check whether or not \p First and \p Second are next to each other
8303 /// in memory. This means that there is no hole between the bits loaded
8304 /// by \p First and the bits loaded by \p Second.
8305 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8306 const LoadedSlice &Second) {
8307 assert(First.Origin == Second.Origin && First.Origin &&
8308 "Unable to match different memory origins.");
8309 APInt UsedBits = First.getUsedBits();
8310 assert((UsedBits & Second.getUsedBits()) == 0 &&
8311 "Slices are not supposed to overlap.");
8312 UsedBits |= Second.getUsedBits();
8313 return areUsedBitsDense(UsedBits);
8316 /// \brief Adjust the \p GlobalLSCost according to the target
8317 /// paring capabilities and the layout of the slices.
8318 /// \pre \p GlobalLSCost should account for at least as many loads as
8319 /// there is in the slices in \p LoadedSlices.
8320 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8321 LoadedSlice::Cost &GlobalLSCost) {
8322 unsigned NumberOfSlices = LoadedSlices.size();
8323 // If there is less than 2 elements, no pairing is possible.
8324 if (NumberOfSlices < 2)
8327 // Sort the slices so that elements that are likely to be next to each
8328 // other in memory are next to each other in the list.
8329 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8330 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8331 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8332 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8334 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8335 // First (resp. Second) is the first (resp. Second) potentially candidate
8336 // to be placed in a paired load.
8337 const LoadedSlice *First = nullptr;
8338 const LoadedSlice *Second = nullptr;
8339 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8340 // Set the beginning of the pair.
8343 Second = &LoadedSlices[CurrSlice];
8345 // If First is NULL, it means we start a new pair.
8346 // Get to the next slice.
8350 EVT LoadedType = First->getLoadedType();
8352 // If the types of the slices are different, we cannot pair them.
8353 if (LoadedType != Second->getLoadedType())
8356 // Check if the target supplies paired loads for this type.
8357 unsigned RequiredAlignment = 0;
8358 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8359 // move to the next pair, this type is hopeless.
8363 // Check if we meet the alignment requirement.
8364 if (RequiredAlignment > First->getAlignment())
8367 // Check that both loads are next to each other in memory.
8368 if (!areSlicesNextToEachOther(*First, *Second))
8371 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8372 --GlobalLSCost.Loads;
8373 // Move to the next pair.
8378 /// \brief Check the profitability of all involved LoadedSlice.
8379 /// Currently, it is considered profitable if there is exactly two
8380 /// involved slices (1) which are (2) next to each other in memory, and
8381 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8383 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8384 /// the elements themselves.
8386 /// FIXME: When the cost model will be mature enough, we can relax
8387 /// constraints (1) and (2).
8388 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8389 const APInt &UsedBits, bool ForCodeSize) {
8390 unsigned NumberOfSlices = LoadedSlices.size();
8391 if (StressLoadSlicing)
8392 return NumberOfSlices > 1;
8395 if (NumberOfSlices != 2)
8399 if (!areUsedBitsDense(UsedBits))
8403 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8404 // The original code has one big load.
8406 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8407 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8408 // Accumulate the cost of all the slices.
8409 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8410 GlobalSlicingCost += SliceCost;
8412 // Account as cost in the original configuration the gain obtained
8413 // with the current slices.
8414 OrigCost.addSliceGain(LS);
8417 // If the target supports paired load, adjust the cost accordingly.
8418 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8419 return OrigCost > GlobalSlicingCost;
8422 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8423 /// operations, split it in the various pieces being extracted.
8425 /// This sort of thing is introduced by SROA.
8426 /// This slicing takes care not to insert overlapping loads.
8427 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8428 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8429 if (Level < AfterLegalizeDAG)
8432 LoadSDNode *LD = cast<LoadSDNode>(N);
8433 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8434 !LD->getValueType(0).isInteger())
8437 // Keep track of already used bits to detect overlapping values.
8438 // In that case, we will just abort the transformation.
8439 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8441 SmallVector<LoadedSlice, 4> LoadedSlices;
8443 // Check if this load is used as several smaller chunks of bits.
8444 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8445 // of computation for each trunc.
8446 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8447 UI != UIEnd; ++UI) {
8448 // Skip the uses of the chain.
8449 if (UI.getUse().getResNo() != 0)
8455 // Check if this is a trunc(lshr).
8456 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8457 isa<ConstantSDNode>(User->getOperand(1))) {
8458 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8459 User = *User->use_begin();
8462 // At this point, User is a Truncate, iff we encountered, trunc or
8464 if (User->getOpcode() != ISD::TRUNCATE)
8467 // The width of the type must be a power of 2 and greater than 8-bits.
8468 // Otherwise the load cannot be represented in LLVM IR.
8469 // Moreover, if we shifted with a non-8-bits multiple, the slice
8470 // will be across several bytes. We do not support that.
8471 unsigned Width = User->getValueSizeInBits(0);
8472 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8475 // Build the slice for this chain of computations.
8476 LoadedSlice LS(User, LD, Shift, &DAG);
8477 APInt CurrentUsedBits = LS.getUsedBits();
8479 // Check if this slice overlaps with another.
8480 if ((CurrentUsedBits & UsedBits) != 0)
8482 // Update the bits used globally.
8483 UsedBits |= CurrentUsedBits;
8485 // Check if the new slice would be legal.
8489 // Record the slice.
8490 LoadedSlices.push_back(LS);
8493 // Abort slicing if it does not seem to be profitable.
8494 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8499 // Rewrite each chain to use an independent load.
8500 // By construction, each chain can be represented by a unique load.
8502 // Prepare the argument for the new token factor for all the slices.
8503 SmallVector<SDValue, 8> ArgChains;
8504 for (SmallVectorImpl<LoadedSlice>::const_iterator
8505 LSIt = LoadedSlices.begin(),
8506 LSItEnd = LoadedSlices.end();
8507 LSIt != LSItEnd; ++LSIt) {
8508 SDValue SliceInst = LSIt->loadSlice();
8509 CombineTo(LSIt->Inst, SliceInst, true);
8510 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8511 SliceInst = SliceInst.getOperand(0);
8512 assert(SliceInst->getOpcode() == ISD::LOAD &&
8513 "It takes more than a zext to get to the loaded slice!!");
8514 ArgChains.push_back(SliceInst.getValue(1));
8517 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8519 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8523 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8524 /// load is having specific bytes cleared out. If so, return the byte size
8525 /// being masked out and the shift amount.
8526 static std::pair<unsigned, unsigned>
8527 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8528 std::pair<unsigned, unsigned> Result(0, 0);
8530 // Check for the structure we're looking for.
8531 if (V->getOpcode() != ISD::AND ||
8532 !isa<ConstantSDNode>(V->getOperand(1)) ||
8533 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8536 // Check the chain and pointer.
8537 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8538 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
8540 // The store should be chained directly to the load or be an operand of a
8542 if (LD == Chain.getNode())
8544 else if (Chain->getOpcode() != ISD::TokenFactor)
8545 return Result; // Fail.
8548 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8549 if (Chain->getOperand(i).getNode() == LD) {
8553 if (!isOk) return Result;
8556 // This only handles simple types.
8557 if (V.getValueType() != MVT::i16 &&
8558 V.getValueType() != MVT::i32 &&
8559 V.getValueType() != MVT::i64)
8562 // Check the constant mask. Invert it so that the bits being masked out are
8563 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8564 // follow the sign bit for uniformity.
8565 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8566 unsigned NotMaskLZ = countLeadingZeros(NotMask);
8567 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
8568 unsigned NotMaskTZ = countTrailingZeros(NotMask);
8569 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8570 if (NotMaskLZ == 64) return Result; // All zero mask.
8572 // See if we have a continuous run of bits. If so, we have 0*1+0*
8573 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8576 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8577 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8578 NotMaskLZ -= 64-V.getValueSizeInBits();
8580 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8581 switch (MaskedBytes) {
8585 default: return Result; // All one mask, or 5-byte mask.
8588 // Verify that the first bit starts at a multiple of mask so that the access
8589 // is aligned the same as the access width.
8590 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8592 Result.first = MaskedBytes;
8593 Result.second = NotMaskTZ/8;
8598 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8599 /// provides a value as specified by MaskInfo. If so, replace the specified
8600 /// store with a narrower store of truncated IVal.
8602 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8603 SDValue IVal, StoreSDNode *St,
8605 unsigned NumBytes = MaskInfo.first;
8606 unsigned ByteShift = MaskInfo.second;
8607 SelectionDAG &DAG = DC->getDAG();
8609 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8610 // that uses this. If not, this is not a replacement.
8611 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8612 ByteShift*8, (ByteShift+NumBytes)*8);
8613 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8615 // Check that it is legal on the target to do this. It is legal if the new
8616 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8618 MVT VT = MVT::getIntegerVT(NumBytes*8);
8619 if (!DC->isTypeLegal(VT))
8622 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8623 // shifted by ByteShift and truncated down to NumBytes.
8625 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8626 DAG.getConstant(ByteShift*8,
8627 DC->getShiftAmountTy(IVal.getValueType())));
8629 // Figure out the offset for the store and the alignment of the access.
8631 unsigned NewAlign = St->getAlignment();
8633 if (DAG.getTargetLoweringInfo().isLittleEndian())
8634 StOffset = ByteShift;
8636 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8638 SDValue Ptr = St->getBasePtr();
8640 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8641 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8642 NewAlign = MinAlign(NewAlign, StOffset);
8645 // Truncate down to the new size.
8646 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8649 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8650 St->getPointerInfo().getWithOffset(StOffset),
8651 false, false, NewAlign).getNode();
8655 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8656 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8657 /// of the loaded bits, try narrowing the load and store if it would end up
8658 /// being a win for performance or code size.
8659 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8660 StoreSDNode *ST = cast<StoreSDNode>(N);
8661 if (ST->isVolatile())
8664 SDValue Chain = ST->getChain();
8665 SDValue Value = ST->getValue();
8666 SDValue Ptr = ST->getBasePtr();
8667 EVT VT = Value.getValueType();
8669 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8672 unsigned Opc = Value.getOpcode();
8674 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8675 // is a byte mask indicating a consecutive number of bytes, check to see if
8676 // Y is known to provide just those bytes. If so, we try to replace the
8677 // load + replace + store sequence with a single (narrower) store, which makes
8679 if (Opc == ISD::OR) {
8680 std::pair<unsigned, unsigned> MaskedLoad;
8681 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8682 if (MaskedLoad.first)
8683 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8684 Value.getOperand(1), ST,this))
8685 return SDValue(NewST, 0);
8687 // Or is commutative, so try swapping X and Y.
8688 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8689 if (MaskedLoad.first)
8690 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8691 Value.getOperand(0), ST,this))
8692 return SDValue(NewST, 0);
8695 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8696 Value.getOperand(1).getOpcode() != ISD::Constant)
8699 SDValue N0 = Value.getOperand(0);
8700 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8701 Chain == SDValue(N0.getNode(), 1)) {
8702 LoadSDNode *LD = cast<LoadSDNode>(N0);
8703 if (LD->getBasePtr() != Ptr ||
8704 LD->getPointerInfo().getAddrSpace() !=
8705 ST->getPointerInfo().getAddrSpace())
8708 // Find the type to narrow it the load / op / store to.
8709 SDValue N1 = Value.getOperand(1);
8710 unsigned BitWidth = N1.getValueSizeInBits();
8711 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8712 if (Opc == ISD::AND)
8713 Imm ^= APInt::getAllOnesValue(BitWidth);
8714 if (Imm == 0 || Imm.isAllOnesValue())
8716 unsigned ShAmt = Imm.countTrailingZeros();
8717 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8718 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8719 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8720 while (NewBW < BitWidth &&
8721 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8722 TLI.isNarrowingProfitable(VT, NewVT))) {
8723 NewBW = NextPowerOf2(NewBW);
8724 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8726 if (NewBW >= BitWidth)
8729 // If the lsb changed does not start at the type bitwidth boundary,
8730 // start at the previous one.
8732 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8733 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8734 std::min(BitWidth, ShAmt + NewBW));
8735 if ((Imm & Mask) == Imm) {
8736 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8737 if (Opc == ISD::AND)
8738 NewImm ^= APInt::getAllOnesValue(NewBW);
8739 uint64_t PtrOff = ShAmt / 8;
8740 // For big endian targets, we need to adjust the offset to the pointer to
8741 // load the correct bytes.
8742 if (TLI.isBigEndian())
8743 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8745 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8746 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8747 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8750 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8751 Ptr.getValueType(), Ptr,
8752 DAG.getConstant(PtrOff, Ptr.getValueType()));
8753 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8754 LD->getChain(), NewPtr,
8755 LD->getPointerInfo().getWithOffset(PtrOff),
8756 LD->isVolatile(), LD->isNonTemporal(),
8757 LD->isInvariant(), NewAlign,
8759 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8760 DAG.getConstant(NewImm, NewVT));
8761 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8763 ST->getPointerInfo().getWithOffset(PtrOff),
8764 false, false, NewAlign);
8766 AddToWorkList(NewPtr.getNode());
8767 AddToWorkList(NewLD.getNode());
8768 AddToWorkList(NewVal.getNode());
8769 WorkListRemover DeadNodes(*this);
8770 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8779 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8780 /// if the load value isn't used by any other operations, then consider
8781 /// transforming the pair to integer load / store operations if the target
8782 /// deems the transformation profitable.
8783 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8784 StoreSDNode *ST = cast<StoreSDNode>(N);
8785 SDValue Chain = ST->getChain();
8786 SDValue Value = ST->getValue();
8787 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8788 Value.hasOneUse() &&
8789 Chain == SDValue(Value.getNode(), 1)) {
8790 LoadSDNode *LD = cast<LoadSDNode>(Value);
8791 EVT VT = LD->getMemoryVT();
8792 if (!VT.isFloatingPoint() ||
8793 VT != ST->getMemoryVT() ||
8794 LD->isNonTemporal() ||
8795 ST->isNonTemporal() ||
8796 LD->getPointerInfo().getAddrSpace() != 0 ||
8797 ST->getPointerInfo().getAddrSpace() != 0)
8800 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8801 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8802 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8803 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8804 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8807 unsigned LDAlign = LD->getAlignment();
8808 unsigned STAlign = ST->getAlignment();
8809 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8810 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8811 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8814 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8815 LD->getChain(), LD->getBasePtr(),
8816 LD->getPointerInfo(),
8817 false, false, false, LDAlign);
8819 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8820 NewLD, ST->getBasePtr(),
8821 ST->getPointerInfo(),
8822 false, false, STAlign);
8824 AddToWorkList(NewLD.getNode());
8825 AddToWorkList(NewST.getNode());
8826 WorkListRemover DeadNodes(*this);
8827 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8835 /// Helper struct to parse and store a memory address as base + index + offset.
8836 /// We ignore sign extensions when it is safe to do so.
8837 /// The following two expressions are not equivalent. To differentiate we need
8838 /// to store whether there was a sign extension involved in the index
8840 /// (load (i64 add (i64 copyfromreg %c)
8841 /// (i64 signextend (add (i8 load %index)
8845 /// (load (i64 add (i64 copyfromreg %c)
8846 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8848 struct BaseIndexOffset {
8852 bool IsIndexSignExt;
8854 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8856 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8857 bool IsIndexSignExt) :
8858 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8860 bool equalBaseIndex(const BaseIndexOffset &Other) {
8861 return Other.Base == Base && Other.Index == Index &&
8862 Other.IsIndexSignExt == IsIndexSignExt;
8865 /// Parses tree in Ptr for base, index, offset addresses.
8866 static BaseIndexOffset match(SDValue Ptr) {
8867 bool IsIndexSignExt = false;
8869 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8870 // instruction, then it could be just the BASE or everything else we don't
8871 // know how to handle. Just use Ptr as BASE and give up.
8872 if (Ptr->getOpcode() != ISD::ADD)
8873 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8875 // We know that we have at least an ADD instruction. Try to pattern match
8876 // the simple case of BASE + OFFSET.
8877 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8878 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8879 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8883 // Inside a loop the current BASE pointer is calculated using an ADD and a
8884 // MUL instruction. In this case Ptr is the actual BASE pointer.
8885 // (i64 add (i64 %array_ptr)
8886 // (i64 mul (i64 %induction_var)
8887 // (i64 %element_size)))
8888 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8889 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8891 // Look at Base + Index + Offset cases.
8892 SDValue Base = Ptr->getOperand(0);
8893 SDValue IndexOffset = Ptr->getOperand(1);
8895 // Skip signextends.
8896 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8897 IndexOffset = IndexOffset->getOperand(0);
8898 IsIndexSignExt = true;
8901 // Either the case of Base + Index (no offset) or something else.
8902 if (IndexOffset->getOpcode() != ISD::ADD)
8903 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8905 // Now we have the case of Base + Index + offset.
8906 SDValue Index = IndexOffset->getOperand(0);
8907 SDValue Offset = IndexOffset->getOperand(1);
8909 if (!isa<ConstantSDNode>(Offset))
8910 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8912 // Ignore signextends.
8913 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8914 Index = Index->getOperand(0);
8915 IsIndexSignExt = true;
8916 } else IsIndexSignExt = false;
8918 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8919 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8923 /// Holds a pointer to an LSBaseSDNode as well as information on where it
8924 /// is located in a sequence of memory operations connected by a chain.
8926 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8927 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8928 // Ptr to the mem node.
8929 LSBaseSDNode *MemNode;
8930 // Offset from the base ptr.
8931 int64_t OffsetFromBase;
8932 // What is the sequence number of this mem node.
8933 // Lowest mem operand in the DAG starts at zero.
8934 unsigned SequenceNum;
8937 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8938 EVT MemVT = St->getMemoryVT();
8939 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
8940 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8941 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
8943 // Don't merge vectors into wider inputs.
8944 if (MemVT.isVector() || !MemVT.isSimple())
8947 // Perform an early exit check. Do not bother looking at stored values that
8948 // are not constants or loads.
8949 SDValue StoredVal = St->getValue();
8950 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8951 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8955 // Only look at ends of store sequences.
8956 SDValue Chain = SDValue(St, 1);
8957 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8960 // This holds the base pointer, index, and the offset in bytes from the base
8962 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
8964 // We must have a base and an offset.
8965 if (!BasePtr.Base.getNode())
8968 // Do not handle stores to undef base pointers.
8969 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
8972 // Save the LoadSDNodes that we find in the chain.
8973 // We need to make sure that these nodes do not interfere with
8974 // any of the store nodes.
8975 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8977 // Save the StoreSDNodes that we find in the chain.
8978 SmallVector<MemOpLink, 8> StoreNodes;
8980 // Walk up the chain and look for nodes with offsets from the same
8981 // base pointer. Stop when reaching an instruction with a different kind
8982 // or instruction which has a different base pointer.
8984 StoreSDNode *Index = St;
8986 // If the chain has more than one use, then we can't reorder the mem ops.
8987 if (Index != St && !SDValue(Index, 1)->hasOneUse())
8990 // Find the base pointer and offset for this memory node.
8991 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
8993 // Check that the base pointer is the same as the original one.
8994 if (!Ptr.equalBaseIndex(BasePtr))
8997 // Check that the alignment is the same.
8998 if (Index->getAlignment() != St->getAlignment())
9001 // The memory operands must not be volatile.
9002 if (Index->isVolatile() || Index->isIndexed())
9006 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9007 if (St->isTruncatingStore())
9010 // The stored memory type must be the same.
9011 if (Index->getMemoryVT() != MemVT)
9014 // We do not allow unaligned stores because we want to prevent overriding
9016 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9019 // We found a potential memory operand to merge.
9020 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9022 // Find the next memory operand in the chain. If the next operand in the
9023 // chain is a store then move up and continue the scan with the next
9024 // memory operand. If the next operand is a load save it and use alias
9025 // information to check if it interferes with anything.
9026 SDNode *NextInChain = Index->getChain().getNode();
9028 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9029 // We found a store node. Use it for the next iteration.
9032 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9033 if (Ldn->isVolatile()) {
9038 // Save the load node for later. Continue the scan.
9039 AliasLoadNodes.push_back(Ldn);
9040 NextInChain = Ldn->getChain().getNode();
9049 // Check if there is anything to merge.
9050 if (StoreNodes.size() < 2)
9053 // Sort the memory operands according to their distance from the base pointer.
9054 std::sort(StoreNodes.begin(), StoreNodes.end(),
9055 [](MemOpLink LHS, MemOpLink RHS) {
9056 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9057 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9058 LHS.SequenceNum > RHS.SequenceNum);
9061 // Scan the memory operations on the chain and find the first non-consecutive
9062 // store memory address.
9063 unsigned LastConsecutiveStore = 0;
9064 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9065 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9067 // Check that the addresses are consecutive starting from the second
9068 // element in the list of stores.
9070 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9071 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9076 // Check if this store interferes with any of the loads that we found.
9077 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9078 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9082 // We found a load that alias with this store. Stop the sequence.
9086 // Mark this node as useful.
9087 LastConsecutiveStore = i;
9090 // The node with the lowest store address.
9091 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9093 // Store the constants into memory as one consecutive store.
9095 unsigned LastLegalType = 0;
9096 unsigned LastLegalVectorType = 0;
9097 bool NonZero = false;
9098 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9099 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9100 SDValue StoredVal = St->getValue();
9102 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9103 NonZero |= !C->isNullValue();
9104 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9105 NonZero |= !C->getConstantFPValue()->isNullValue();
9111 // Find a legal type for the constant store.
9112 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9113 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9114 if (TLI.isTypeLegal(StoreTy))
9115 LastLegalType = i+1;
9116 // Or check whether a truncstore is legal.
9117 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9118 TargetLowering::TypePromoteInteger) {
9119 EVT LegalizedStoredValueTy =
9120 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9121 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9122 LastLegalType = i+1;
9125 // Find a legal type for the vector store.
9126 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9127 if (TLI.isTypeLegal(Ty))
9128 LastLegalVectorType = i + 1;
9131 // We only use vectors if the constant is known to be zero and the
9132 // function is not marked with the noimplicitfloat attribute.
9133 if (NonZero || NoVectors)
9134 LastLegalVectorType = 0;
9136 // Check if we found a legal integer type to store.
9137 if (LastLegalType == 0 && LastLegalVectorType == 0)
9140 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9141 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9143 // Make sure we have something to merge.
9147 unsigned EarliestNodeUsed = 0;
9148 for (unsigned i=0; i < NumElem; ++i) {
9149 // Find a chain for the new wide-store operand. Notice that some
9150 // of the store nodes that we found may not be selected for inclusion
9151 // in the wide store. The chain we use needs to be the chain of the
9152 // earliest store node which is *used* and replaced by the wide store.
9153 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9154 EarliestNodeUsed = i;
9157 // The earliest Node in the DAG.
9158 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9159 SDLoc DL(StoreNodes[0].MemNode);
9163 // Find a legal type for the vector store.
9164 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9165 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9166 StoredVal = DAG.getConstant(0, Ty);
9168 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9169 APInt StoreInt(StoreBW, 0);
9171 // Construct a single integer constant which is made of the smaller
9173 bool IsLE = TLI.isLittleEndian();
9174 for (unsigned i = 0; i < NumElem ; ++i) {
9175 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9176 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9177 SDValue Val = St->getValue();
9178 StoreInt<<=ElementSizeBytes*8;
9179 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9180 StoreInt|=C->getAPIntValue().zext(StoreBW);
9181 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9182 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9184 assert(false && "Invalid constant element type");
9188 // Create the new Load and Store operations.
9189 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9190 StoredVal = DAG.getConstant(StoreInt, StoreTy);
9193 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9194 FirstInChain->getBasePtr(),
9195 FirstInChain->getPointerInfo(),
9197 FirstInChain->getAlignment());
9199 // Replace the first store with the new store
9200 CombineTo(EarliestOp, NewStore);
9201 // Erase all other stores.
9202 for (unsigned i = 0; i < NumElem ; ++i) {
9203 if (StoreNodes[i].MemNode == EarliestOp)
9205 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9206 // ReplaceAllUsesWith will replace all uses that existed when it was
9207 // called, but graph optimizations may cause new ones to appear. For
9208 // example, the case in pr14333 looks like
9210 // St's chain -> St -> another store -> X
9212 // And the only difference from St to the other store is the chain.
9213 // When we change it's chain to be St's chain they become identical,
9214 // get CSEed and the net result is that X is now a use of St.
9215 // Since we know that St is redundant, just iterate.
9216 while (!St->use_empty())
9217 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9218 removeFromWorkList(St);
9225 // Below we handle the case of multiple consecutive stores that
9226 // come from multiple consecutive loads. We merge them into a single
9227 // wide load and a single wide store.
9229 // Look for load nodes which are used by the stored values.
9230 SmallVector<MemOpLink, 8> LoadNodes;
9232 // Find acceptable loads. Loads need to have the same chain (token factor),
9233 // must not be zext, volatile, indexed, and they must be consecutive.
9234 BaseIndexOffset LdBasePtr;
9235 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9236 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9237 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9240 // Loads must only have one use.
9241 if (!Ld->hasNUsesOfValue(1, 0))
9244 // Check that the alignment is the same as the stores.
9245 if (Ld->getAlignment() != St->getAlignment())
9248 // The memory operands must not be volatile.
9249 if (Ld->isVolatile() || Ld->isIndexed())
9252 // We do not accept ext loads.
9253 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9256 // The stored memory type must be the same.
9257 if (Ld->getMemoryVT() != MemVT)
9260 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9261 // If this is not the first ptr that we check.
9262 if (LdBasePtr.Base.getNode()) {
9263 // The base ptr must be the same.
9264 if (!LdPtr.equalBaseIndex(LdBasePtr))
9267 // Check that all other base pointers are the same as this one.
9271 // We found a potential memory operand to merge.
9272 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9275 if (LoadNodes.size() < 2)
9278 // Scan the memory operations on the chain and find the first non-consecutive
9279 // load memory address. These variables hold the index in the store node
9281 unsigned LastConsecutiveLoad = 0;
9282 // This variable refers to the size and not index in the array.
9283 unsigned LastLegalVectorType = 0;
9284 unsigned LastLegalIntegerType = 0;
9285 StartAddress = LoadNodes[0].OffsetFromBase;
9286 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9287 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9288 // All loads much share the same chain.
9289 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9292 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9293 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9295 LastConsecutiveLoad = i;
9297 // Find a legal type for the vector store.
9298 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9299 if (TLI.isTypeLegal(StoreTy))
9300 LastLegalVectorType = i + 1;
9302 // Find a legal type for the integer store.
9303 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9304 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9305 if (TLI.isTypeLegal(StoreTy))
9306 LastLegalIntegerType = i + 1;
9307 // Or check whether a truncstore and extload is legal.
9308 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9309 TargetLowering::TypePromoteInteger) {
9310 EVT LegalizedStoredValueTy =
9311 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9312 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9313 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9314 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9315 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9316 LastLegalIntegerType = i+1;
9320 // Only use vector types if the vector type is larger than the integer type.
9321 // If they are the same, use integers.
9322 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9323 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9325 // We add +1 here because the LastXXX variables refer to location while
9326 // the NumElem refers to array/index size.
9327 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9328 NumElem = std::min(LastLegalType, NumElem);
9333 // The earliest Node in the DAG.
9334 unsigned EarliestNodeUsed = 0;
9335 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9336 for (unsigned i=1; i<NumElem; ++i) {
9337 // Find a chain for the new wide-store operand. Notice that some
9338 // of the store nodes that we found may not be selected for inclusion
9339 // in the wide store. The chain we use needs to be the chain of the
9340 // earliest store node which is *used* and replaced by the wide store.
9341 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9342 EarliestNodeUsed = i;
9345 // Find if it is better to use vectors or integers to load and store
9349 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9351 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9352 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9355 SDLoc LoadDL(LoadNodes[0].MemNode);
9356 SDLoc StoreDL(StoreNodes[0].MemNode);
9358 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9359 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9360 FirstLoad->getChain(),
9361 FirstLoad->getBasePtr(),
9362 FirstLoad->getPointerInfo(),
9363 false, false, false,
9364 FirstLoad->getAlignment());
9366 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9367 FirstInChain->getBasePtr(),
9368 FirstInChain->getPointerInfo(), false, false,
9369 FirstInChain->getAlignment());
9371 // Replace one of the loads with the new load.
9372 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9373 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9374 SDValue(NewLoad.getNode(), 1));
9376 // Remove the rest of the load chains.
9377 for (unsigned i = 1; i < NumElem ; ++i) {
9378 // Replace all chain users of the old load nodes with the chain of the new
9380 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9381 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9384 // Replace the first store with the new store.
9385 CombineTo(EarliestOp, NewStore);
9386 // Erase all other stores.
9387 for (unsigned i = 0; i < NumElem ; ++i) {
9388 // Remove all Store nodes.
9389 if (StoreNodes[i].MemNode == EarliestOp)
9391 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9392 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9393 removeFromWorkList(St);
9400 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9401 StoreSDNode *ST = cast<StoreSDNode>(N);
9402 SDValue Chain = ST->getChain();
9403 SDValue Value = ST->getValue();
9404 SDValue Ptr = ST->getBasePtr();
9406 // If this is a store of a bit convert, store the input value if the
9407 // resultant store does not need a higher alignment than the original.
9408 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9409 ST->isUnindexed()) {
9410 unsigned OrigAlign = ST->getAlignment();
9411 EVT SVT = Value.getOperand(0).getValueType();
9412 unsigned Align = TLI.getDataLayout()->
9413 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9414 if (Align <= OrigAlign &&
9415 ((!LegalOperations && !ST->isVolatile()) ||
9416 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9417 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9418 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9419 ST->isNonTemporal(), OrigAlign,
9423 // Turn 'store undef, Ptr' -> nothing.
9424 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9427 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9428 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9429 // NOTE: If the original store is volatile, this transform must not increase
9430 // the number of stores. For example, on x86-32 an f64 can be stored in one
9431 // processor operation but an i64 (which is not legal) requires two. So the
9432 // transform should not be done in this case.
9433 if (Value.getOpcode() != ISD::TargetConstantFP) {
9435 switch (CFP->getSimpleValueType(0).SimpleTy) {
9436 default: llvm_unreachable("Unknown FP type");
9437 case MVT::f16: // We don't do this for these yet.
9443 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9444 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9445 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9446 bitcastToAPInt().getZExtValue(), MVT::i32);
9447 return DAG.getStore(Chain, SDLoc(N), Tmp,
9448 Ptr, ST->getMemOperand());
9452 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9453 !ST->isVolatile()) ||
9454 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9455 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9456 getZExtValue(), MVT::i64);
9457 return DAG.getStore(Chain, SDLoc(N), Tmp,
9458 Ptr, ST->getMemOperand());
9461 if (!ST->isVolatile() &&
9462 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9463 // Many FP stores are not made apparent until after legalize, e.g. for
9464 // argument passing. Since this is so common, custom legalize the
9465 // 64-bit integer store into two 32-bit stores.
9466 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9467 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9468 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9469 if (TLI.isBigEndian()) std::swap(Lo, Hi);
9471 unsigned Alignment = ST->getAlignment();
9472 bool isVolatile = ST->isVolatile();
9473 bool isNonTemporal = ST->isNonTemporal();
9474 const MDNode *TBAAInfo = ST->getTBAAInfo();
9476 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9477 Ptr, ST->getPointerInfo(),
9478 isVolatile, isNonTemporal,
9479 ST->getAlignment(), TBAAInfo);
9480 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9481 DAG.getConstant(4, Ptr.getValueType()));
9482 Alignment = MinAlign(Alignment, 4U);
9483 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9484 Ptr, ST->getPointerInfo().getWithOffset(4),
9485 isVolatile, isNonTemporal,
9486 Alignment, TBAAInfo);
9487 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9496 // Try to infer better alignment information than the store already has.
9497 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9498 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9499 if (Align > ST->getAlignment())
9500 return DAG.getTruncStore(Chain, SDLoc(N), Value,
9501 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9502 ST->isVolatile(), ST->isNonTemporal(), Align,
9507 // Try transforming a pair floating point load / store ops to integer
9508 // load / store ops.
9509 SDValue NewST = TransformFPLoadStorePair(N);
9510 if (NewST.getNode())
9513 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9514 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9516 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9517 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9520 if (UseAA && ST->isUnindexed()) {
9521 // Walk up chain skipping non-aliasing memory nodes.
9522 SDValue BetterChain = FindBetterChain(N, Chain);
9524 // If there is a better chain.
9525 if (Chain != BetterChain) {
9528 // Replace the chain to avoid dependency.
9529 if (ST->isTruncatingStore()) {
9530 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9531 ST->getMemoryVT(), ST->getMemOperand());
9533 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9534 ST->getMemOperand());
9537 // Create token to keep both nodes around.
9538 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9539 MVT::Other, Chain, ReplStore);
9541 // Make sure the new and old chains are cleaned up.
9542 AddToWorkList(Token.getNode());
9544 // Don't add users to work list.
9545 return CombineTo(N, Token, false);
9549 // Try transforming N to an indexed store.
9550 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9551 return SDValue(N, 0);
9553 // FIXME: is there such a thing as a truncating indexed store?
9554 if (ST->isTruncatingStore() && ST->isUnindexed() &&
9555 Value.getValueType().isInteger()) {
9556 // See if we can simplify the input to this truncstore with knowledge that
9557 // only the low bits are being used. For example:
9558 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
9560 GetDemandedBits(Value,
9561 APInt::getLowBitsSet(
9562 Value.getValueType().getScalarType().getSizeInBits(),
9563 ST->getMemoryVT().getScalarType().getSizeInBits()));
9564 AddToWorkList(Value.getNode());
9565 if (Shorter.getNode())
9566 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9567 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9569 // Otherwise, see if we can simplify the operation with
9570 // SimplifyDemandedBits, which only works if the value has a single use.
9571 if (SimplifyDemandedBits(Value,
9572 APInt::getLowBitsSet(
9573 Value.getValueType().getScalarType().getSizeInBits(),
9574 ST->getMemoryVT().getScalarType().getSizeInBits())))
9575 return SDValue(N, 0);
9578 // If this is a load followed by a store to the same location, then the store
9580 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9581 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9582 ST->isUnindexed() && !ST->isVolatile() &&
9583 // There can't be any side effects between the load and store, such as
9585 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9586 // The store is dead, remove it.
9591 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9592 // truncating store. We can do this even if this is already a truncstore.
9593 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9594 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9595 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9596 ST->getMemoryVT())) {
9597 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9598 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9601 // Only perform this optimization before the types are legal, because we
9602 // don't want to perform this optimization on every DAGCombine invocation.
9604 bool EverChanged = false;
9607 // There can be multiple store sequences on the same chain.
9608 // Keep trying to merge store sequences until we are unable to do so
9609 // or until we merge the last store on the chain.
9610 bool Changed = MergeConsecutiveStores(ST);
9611 EverChanged |= Changed;
9612 if (!Changed) break;
9613 } while (ST->getOpcode() != ISD::DELETED_NODE);
9616 return SDValue(N, 0);
9619 return ReduceLoadOpStoreWidth(N);
9622 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9623 SDValue InVec = N->getOperand(0);
9624 SDValue InVal = N->getOperand(1);
9625 SDValue EltNo = N->getOperand(2);
9628 // If the inserted element is an UNDEF, just use the input vector.
9629 if (InVal.getOpcode() == ISD::UNDEF)
9632 EVT VT = InVec.getValueType();
9634 // If we can't generate a legal BUILD_VECTOR, exit
9635 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9638 // Check that we know which element is being inserted
9639 if (!isa<ConstantSDNode>(EltNo))
9641 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9643 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9644 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9646 SmallVector<SDValue, 8> Ops;
9647 // Do not combine these two vectors if the output vector will not replace
9648 // the input vector.
9649 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9650 Ops.append(InVec.getNode()->op_begin(),
9651 InVec.getNode()->op_end());
9652 } else if (InVec.getOpcode() == ISD::UNDEF) {
9653 unsigned NElts = VT.getVectorNumElements();
9654 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9659 // Insert the element
9660 if (Elt < Ops.size()) {
9661 // All the operands of BUILD_VECTOR must have the same type;
9662 // we enforce that here.
9663 EVT OpVT = Ops[0].getValueType();
9664 if (InVal.getValueType() != OpVT)
9665 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9666 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9667 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9671 // Return the new vector
9672 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
9675 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9676 // (vextract (scalar_to_vector val, 0) -> val
9677 SDValue InVec = N->getOperand(0);
9678 EVT VT = InVec.getValueType();
9679 EVT NVT = N->getValueType(0);
9681 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9682 // Check if the result type doesn't match the inserted element type. A
9683 // SCALAR_TO_VECTOR may truncate the inserted element and the
9684 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9685 SDValue InOp = InVec.getOperand(0);
9686 if (InOp.getValueType() != NVT) {
9687 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9688 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9693 SDValue EltNo = N->getOperand(1);
9694 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9696 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9697 // We only perform this optimization before the op legalization phase because
9698 // we may introduce new vector instructions which are not backed by TD
9699 // patterns. For example on AVX, extracting elements from a wide vector
9700 // without using extract_subvector. However, if we can find an underlying
9701 // scalar value, then we can always use that.
9702 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9704 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9705 int NumElem = VT.getVectorNumElements();
9706 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9707 // Find the new index to extract from.
9708 int OrigElt = SVOp->getMaskElt(Elt);
9710 // Extracting an undef index is undef.
9712 return DAG.getUNDEF(NVT);
9714 // Select the right vector half to extract from.
9716 if (OrigElt < NumElem) {
9717 SVInVec = InVec->getOperand(0);
9719 SVInVec = InVec->getOperand(1);
9723 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9724 SDValue InOp = SVInVec.getOperand(OrigElt);
9725 if (InOp.getValueType() != NVT) {
9726 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9727 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9733 // FIXME: We should handle recursing on other vector shuffles and
9734 // scalar_to_vector here as well.
9736 if (!LegalOperations) {
9737 EVT IndexTy = TLI.getVectorIdxTy();
9738 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9739 SVInVec, DAG.getConstant(OrigElt, IndexTy));
9743 // Perform only after legalization to ensure build_vector / vector_shuffle
9744 // optimizations have already been done.
9745 if (!LegalOperations) return SDValue();
9747 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9748 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9749 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9752 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9753 bool NewLoad = false;
9754 bool BCNumEltsChanged = false;
9755 EVT ExtVT = VT.getVectorElementType();
9758 // If the result of load has to be truncated, then it's not necessarily
9760 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9763 if (InVec.getOpcode() == ISD::BITCAST) {
9764 // Don't duplicate a load with other uses.
9765 if (!InVec.hasOneUse())
9768 EVT BCVT = InVec.getOperand(0).getValueType();
9769 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9771 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9772 BCNumEltsChanged = true;
9773 InVec = InVec.getOperand(0);
9774 ExtVT = BCVT.getVectorElementType();
9778 LoadSDNode *LN0 = nullptr;
9779 const ShuffleVectorSDNode *SVN = nullptr;
9780 if (ISD::isNormalLoad(InVec.getNode())) {
9781 LN0 = cast<LoadSDNode>(InVec);
9782 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9783 InVec.getOperand(0).getValueType() == ExtVT &&
9784 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9785 // Don't duplicate a load with other uses.
9786 if (!InVec.hasOneUse())
9789 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9790 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9791 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9793 // (load $addr+1*size)
9795 // Don't duplicate a load with other uses.
9796 if (!InVec.hasOneUse())
9799 // If the bit convert changed the number of elements, it is unsafe
9800 // to examine the mask.
9801 if (BCNumEltsChanged)
9804 // Select the input vector, guarding against out of range extract vector.
9805 unsigned NumElems = VT.getVectorNumElements();
9806 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9807 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9809 if (InVec.getOpcode() == ISD::BITCAST) {
9810 // Don't duplicate a load with other uses.
9811 if (!InVec.hasOneUse())
9814 InVec = InVec.getOperand(0);
9816 if (ISD::isNormalLoad(InVec.getNode())) {
9817 LN0 = cast<LoadSDNode>(InVec);
9818 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9822 // Make sure we found a non-volatile load and the extractelement is
9824 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9827 // If Idx was -1 above, Elt is going to be -1, so just return undef.
9829 return DAG.getUNDEF(LVT);
9831 unsigned Align = LN0->getAlignment();
9833 // Check the resultant load doesn't need a higher alignment than the
9837 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9839 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9845 SDValue NewPtr = LN0->getBasePtr();
9846 unsigned PtrOff = 0;
9849 PtrOff = LVT.getSizeInBits() * Elt / 8;
9850 EVT PtrType = NewPtr.getValueType();
9851 if (TLI.isBigEndian())
9852 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9853 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9854 DAG.getConstant(PtrOff, PtrType));
9857 // The replacement we need to do here is a little tricky: we need to
9858 // replace an extractelement of a load with a load.
9859 // Use ReplaceAllUsesOfValuesWith to do the replacement.
9860 // Note that this replacement assumes that the extractvalue is the only
9861 // use of the load; that's okay because we don't want to perform this
9862 // transformation in other cases anyway.
9865 if (NVT.bitsGT(LVT)) {
9866 // If the result type of vextract is wider than the load, then issue an
9867 // extending load instead.
9868 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9869 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9870 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9871 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9872 LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9873 Align, LN0->getTBAAInfo());
9874 Chain = Load.getValue(1);
9876 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9877 LN0->getPointerInfo().getWithOffset(PtrOff),
9878 LN0->isVolatile(), LN0->isNonTemporal(),
9879 LN0->isInvariant(), Align, LN0->getTBAAInfo());
9880 Chain = Load.getValue(1);
9881 if (NVT.bitsLT(LVT))
9882 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
9884 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
9886 WorkListRemover DeadNodes(*this);
9887 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
9888 SDValue To[] = { Load, Chain };
9889 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9890 // Since we're explcitly calling ReplaceAllUses, add the new node to the
9891 // worklist explicitly as well.
9892 AddToWorkList(Load.getNode());
9893 AddUsersToWorkList(Load.getNode()); // Add users too
9894 // Make sure to revisit this node to clean it up; it will usually be dead.
9896 return SDValue(N, 0);
9902 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
9903 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9904 // We perform this optimization post type-legalization because
9905 // the type-legalizer often scalarizes integer-promoted vectors.
9906 // Performing this optimization before may create bit-casts which
9907 // will be type-legalized to complex code sequences.
9908 // We perform this optimization only before the operation legalizer because we
9909 // may introduce illegal operations.
9910 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9913 unsigned NumInScalars = N->getNumOperands();
9915 EVT VT = N->getValueType(0);
9917 // Check to see if this is a BUILD_VECTOR of a bunch of values
9918 // which come from any_extend or zero_extend nodes. If so, we can create
9919 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
9920 // optimizations. We do not handle sign-extend because we can't fill the sign
9922 EVT SourceType = MVT::Other;
9923 bool AllAnyExt = true;
9925 for (unsigned i = 0; i != NumInScalars; ++i) {
9926 SDValue In = N->getOperand(i);
9927 // Ignore undef inputs.
9928 if (In.getOpcode() == ISD::UNDEF) continue;
9930 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
9931 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9933 // Abort if the element is not an extension.
9934 if (!ZeroExt && !AnyExt) {
9935 SourceType = MVT::Other;
9939 // The input is a ZeroExt or AnyExt. Check the original type.
9940 EVT InTy = In.getOperand(0).getValueType();
9942 // Check that all of the widened source types are the same.
9943 if (SourceType == MVT::Other)
9946 else if (InTy != SourceType) {
9947 // Multiple income types. Abort.
9948 SourceType = MVT::Other;
9952 // Check if all of the extends are ANY_EXTENDs.
9953 AllAnyExt &= AnyExt;
9956 // In order to have valid types, all of the inputs must be extended from the
9957 // same source type and all of the inputs must be any or zero extend.
9958 // Scalar sizes must be a power of two.
9959 EVT OutScalarTy = VT.getScalarType();
9960 bool ValidTypes = SourceType != MVT::Other &&
9961 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9962 isPowerOf2_32(SourceType.getSizeInBits());
9964 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9965 // turn into a single shuffle instruction.
9969 bool isLE = TLI.isLittleEndian();
9970 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
9971 assert(ElemRatio > 1 && "Invalid element size ratio");
9972 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
9973 DAG.getConstant(0, SourceType);
9975 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
9976 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
9978 // Populate the new build_vector
9979 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9980 SDValue Cast = N->getOperand(i);
9981 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
9982 Cast.getOpcode() == ISD::ZERO_EXTEND ||
9983 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
9985 if (Cast.getOpcode() == ISD::UNDEF)
9986 In = DAG.getUNDEF(SourceType);
9988 In = Cast->getOperand(0);
9989 unsigned Index = isLE ? (i * ElemRatio) :
9990 (i * ElemRatio + (ElemRatio - 1));
9992 assert(Index < Ops.size() && "Invalid index");
9996 // The type of the new BUILD_VECTOR node.
9997 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
9998 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
9999 "Invalid vector size");
10000 // Check if the new vector type is legal.
10001 if (!isTypeLegal(VecVT)) return SDValue();
10003 // Make the new BUILD_VECTOR.
10004 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10006 // The new BUILD_VECTOR node has the potential to be further optimized.
10007 AddToWorkList(BV.getNode());
10008 // Bitcast to the desired type.
10009 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10012 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10013 EVT VT = N->getValueType(0);
10015 unsigned NumInScalars = N->getNumOperands();
10018 EVT SrcVT = MVT::Other;
10019 unsigned Opcode = ISD::DELETED_NODE;
10020 unsigned NumDefs = 0;
10022 for (unsigned i = 0; i != NumInScalars; ++i) {
10023 SDValue In = N->getOperand(i);
10024 unsigned Opc = In.getOpcode();
10026 if (Opc == ISD::UNDEF)
10029 // If all scalar values are floats and converted from integers.
10030 if (Opcode == ISD::DELETED_NODE &&
10031 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10038 EVT InVT = In.getOperand(0).getValueType();
10040 // If all scalar values are typed differently, bail out. It's chosen to
10041 // simplify BUILD_VECTOR of integer types.
10042 if (SrcVT == MVT::Other)
10049 // If the vector has just one element defined, it's not worth to fold it into
10050 // a vectorized one.
10054 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10055 && "Should only handle conversion from integer to float.");
10056 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10058 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10060 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10063 SmallVector<SDValue, 8> Opnds;
10064 for (unsigned i = 0; i != NumInScalars; ++i) {
10065 SDValue In = N->getOperand(i);
10067 if (In.getOpcode() == ISD::UNDEF)
10068 Opnds.push_back(DAG.getUNDEF(SrcVT));
10070 Opnds.push_back(In.getOperand(0));
10072 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10073 AddToWorkList(BV.getNode());
10075 return DAG.getNode(Opcode, dl, VT, BV);
10078 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10079 unsigned NumInScalars = N->getNumOperands();
10081 EVT VT = N->getValueType(0);
10083 // A vector built entirely of undefs is undef.
10084 if (ISD::allOperandsUndef(N))
10085 return DAG.getUNDEF(VT);
10087 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10091 V = reduceBuildVecConvertToConvertBuildVec(N);
10095 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10096 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10097 // at most two distinct vectors, turn this into a shuffle node.
10099 // May only combine to shuffle after legalize if shuffle is legal.
10100 if (LegalOperations &&
10101 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10104 SDValue VecIn1, VecIn2;
10105 for (unsigned i = 0; i != NumInScalars; ++i) {
10106 // Ignore undef inputs.
10107 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10109 // If this input is something other than a EXTRACT_VECTOR_ELT with a
10110 // constant index, bail out.
10111 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10112 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10113 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10117 // We allow up to two distinct input vectors.
10118 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10119 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10122 if (!VecIn1.getNode()) {
10123 VecIn1 = ExtractedFromVec;
10124 } else if (!VecIn2.getNode()) {
10125 VecIn2 = ExtractedFromVec;
10127 // Too many inputs.
10128 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10133 // If everything is good, we can make a shuffle operation.
10134 if (VecIn1.getNode()) {
10135 SmallVector<int, 8> Mask;
10136 for (unsigned i = 0; i != NumInScalars; ++i) {
10137 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10138 Mask.push_back(-1);
10142 // If extracting from the first vector, just use the index directly.
10143 SDValue Extract = N->getOperand(i);
10144 SDValue ExtVal = Extract.getOperand(1);
10145 if (Extract.getOperand(0) == VecIn1) {
10146 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10147 if (ExtIndex > VT.getVectorNumElements())
10150 Mask.push_back(ExtIndex);
10154 // Otherwise, use InIdx + VecSize
10155 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10156 Mask.push_back(Idx+NumInScalars);
10159 // We can't generate a shuffle node with mismatched input and output types.
10160 // Attempt to transform a single input vector to the correct type.
10161 if ((VT != VecIn1.getValueType())) {
10162 // We don't support shuffeling between TWO values of different types.
10163 if (VecIn2.getNode())
10166 // We only support widening of vectors which are half the size of the
10167 // output registers. For example XMM->YMM widening on X86 with AVX.
10168 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10171 // If the input vector type has a different base type to the output
10172 // vector type, bail out.
10173 if (VecIn1.getValueType().getVectorElementType() !=
10174 VT.getVectorElementType())
10177 // Widen the input vector by adding undef values.
10178 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10179 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10182 // If VecIn2 is unused then change it to undef.
10183 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10185 // Check that we were able to transform all incoming values to the same
10187 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10188 VecIn1.getValueType() != VT)
10191 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10192 if (!isTypeLegal(VT))
10195 // Return the new VECTOR_SHUFFLE node.
10199 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10205 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10206 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10207 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10208 // inputs come from at most two distinct vectors, turn this into a shuffle
10211 // If we only have one input vector, we don't need to do any concatenation.
10212 if (N->getNumOperands() == 1)
10213 return N->getOperand(0);
10215 // Check if all of the operands are undefs.
10216 EVT VT = N->getValueType(0);
10217 if (ISD::allOperandsUndef(N))
10218 return DAG.getUNDEF(VT);
10220 // Optimize concat_vectors where one of the vectors is undef.
10221 if (N->getNumOperands() == 2 &&
10222 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10223 SDValue In = N->getOperand(0);
10224 assert(In.getValueType().isVector() && "Must concat vectors");
10226 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10227 if (In->getOpcode() == ISD::BITCAST &&
10228 !In->getOperand(0)->getValueType(0).isVector()) {
10229 SDValue Scalar = In->getOperand(0);
10230 EVT SclTy = Scalar->getValueType(0);
10232 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10235 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10236 VT.getSizeInBits() / SclTy.getSizeInBits());
10237 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10240 SDLoc dl = SDLoc(N);
10241 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10242 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10246 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10247 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10248 if (N->getNumOperands() == 2 &&
10249 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10250 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10251 EVT VT = N->getValueType(0);
10252 SDValue N0 = N->getOperand(0);
10253 SDValue N1 = N->getOperand(1);
10254 SmallVector<SDValue, 8> Opnds;
10255 unsigned BuildVecNumElts = N0.getNumOperands();
10257 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10258 Opnds.push_back(N0.getOperand(i));
10259 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10260 Opnds.push_back(N1.getOperand(i));
10262 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10265 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10266 // nodes often generate nop CONCAT_VECTOR nodes.
10267 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10268 // place the incoming vectors at the exact same location.
10269 SDValue SingleSource = SDValue();
10270 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10272 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10273 SDValue Op = N->getOperand(i);
10275 if (Op.getOpcode() == ISD::UNDEF)
10278 // Check if this is the identity extract:
10279 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10282 // Find the single incoming vector for the extract_subvector.
10283 if (SingleSource.getNode()) {
10284 if (Op.getOperand(0) != SingleSource)
10287 SingleSource = Op.getOperand(0);
10289 // Check the source type is the same as the type of the result.
10290 // If not, this concat may extend the vector, so we can not
10291 // optimize it away.
10292 if (SingleSource.getValueType() != N->getValueType(0))
10296 unsigned IdentityIndex = i * PartNumElem;
10297 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10298 // The extract index must be constant.
10302 // Check that we are reading from the identity index.
10303 if (CS->getZExtValue() != IdentityIndex)
10307 if (SingleSource.getNode())
10308 return SingleSource;
10313 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10314 EVT NVT = N->getValueType(0);
10315 SDValue V = N->getOperand(0);
10317 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10319 // (extract_subvec (concat V1, V2, ...), i)
10322 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10324 if (V->getOperand(0).getValueType() != NVT)
10326 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10327 unsigned NumElems = NVT.getVectorNumElements();
10328 assert((Idx % NumElems) == 0 &&
10329 "IDX in concat is not a multiple of the result vector length.");
10330 return V->getOperand(Idx / NumElems);
10334 if (V->getOpcode() == ISD::BITCAST)
10335 V = V.getOperand(0);
10337 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10339 // Handle only simple case where vector being inserted and vector
10340 // being extracted are of same type, and are half size of larger vectors.
10341 EVT BigVT = V->getOperand(0).getValueType();
10342 EVT SmallVT = V->getOperand(1).getValueType();
10343 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10346 // Only handle cases where both indexes are constants with the same type.
10347 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10348 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10350 if (InsIdx && ExtIdx &&
10351 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10352 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10354 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10356 // indices are equal or bit offsets are equal => V1
10357 // otherwise => (extract_subvec V1, ExtIdx)
10358 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10359 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10360 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10361 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10362 DAG.getNode(ISD::BITCAST, dl,
10363 N->getOperand(0).getValueType(),
10364 V->getOperand(0)), N->getOperand(1));
10371 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10372 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10373 EVT VT = N->getValueType(0);
10374 unsigned NumElts = VT.getVectorNumElements();
10376 SDValue N0 = N->getOperand(0);
10377 SDValue N1 = N->getOperand(1);
10378 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10380 SmallVector<SDValue, 4> Ops;
10381 EVT ConcatVT = N0.getOperand(0).getValueType();
10382 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10383 unsigned NumConcats = NumElts / NumElemsPerConcat;
10385 // Look at every vector that's inserted. We're looking for exact
10386 // subvector-sized copies from a concatenated vector
10387 for (unsigned I = 0; I != NumConcats; ++I) {
10388 // Make sure we're dealing with a copy.
10389 unsigned Begin = I * NumElemsPerConcat;
10390 bool AllUndef = true, NoUndef = true;
10391 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10392 if (SVN->getMaskElt(J) >= 0)
10399 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10402 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10403 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10406 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10407 if (FirstElt < N0.getNumOperands())
10408 Ops.push_back(N0.getOperand(FirstElt));
10410 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10412 } else if (AllUndef) {
10413 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10414 } else { // Mixed with general masks and undefs, can't do optimization.
10419 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10422 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10423 EVT VT = N->getValueType(0);
10424 unsigned NumElts = VT.getVectorNumElements();
10426 SDValue N0 = N->getOperand(0);
10427 SDValue N1 = N->getOperand(1);
10429 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10431 // Canonicalize shuffle undef, undef -> undef
10432 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10433 return DAG.getUNDEF(VT);
10435 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10437 // Canonicalize shuffle v, v -> v, undef
10439 SmallVector<int, 8> NewMask;
10440 for (unsigned i = 0; i != NumElts; ++i) {
10441 int Idx = SVN->getMaskElt(i);
10442 if (Idx >= (int)NumElts) Idx -= NumElts;
10443 NewMask.push_back(Idx);
10445 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10449 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10450 if (N0.getOpcode() == ISD::UNDEF) {
10451 SmallVector<int, 8> NewMask;
10452 for (unsigned i = 0; i != NumElts; ++i) {
10453 int Idx = SVN->getMaskElt(i);
10455 if (Idx >= (int)NumElts)
10458 Idx = -1; // remove reference to lhs
10460 NewMask.push_back(Idx);
10462 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10466 // Remove references to rhs if it is undef
10467 if (N1.getOpcode() == ISD::UNDEF) {
10468 bool Changed = false;
10469 SmallVector<int, 8> NewMask;
10470 for (unsigned i = 0; i != NumElts; ++i) {
10471 int Idx = SVN->getMaskElt(i);
10472 if (Idx >= (int)NumElts) {
10476 NewMask.push_back(Idx);
10479 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10482 // If it is a splat, check if the argument vector is another splat or a
10483 // build_vector with all scalar elements the same.
10484 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10485 SDNode *V = N0.getNode();
10487 // If this is a bit convert that changes the element type of the vector but
10488 // not the number of vector elements, look through it. Be careful not to
10489 // look though conversions that change things like v4f32 to v2f64.
10490 if (V->getOpcode() == ISD::BITCAST) {
10491 SDValue ConvInput = V->getOperand(0);
10492 if (ConvInput.getValueType().isVector() &&
10493 ConvInput.getValueType().getVectorNumElements() == NumElts)
10494 V = ConvInput.getNode();
10497 if (V->getOpcode() == ISD::BUILD_VECTOR) {
10498 assert(V->getNumOperands() == NumElts &&
10499 "BUILD_VECTOR has wrong number of operands");
10501 bool AllSame = true;
10502 for (unsigned i = 0; i != NumElts; ++i) {
10503 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10504 Base = V->getOperand(i);
10508 // Splat of <u, u, u, u>, return <u, u, u, u>
10509 if (!Base.getNode())
10511 for (unsigned i = 0; i != NumElts; ++i) {
10512 if (V->getOperand(i) != Base) {
10517 // Splat of <x, x, x, x>, return <x, x, x, x>
10523 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10524 Level < AfterLegalizeVectorOps &&
10525 (N1.getOpcode() == ISD::UNDEF ||
10526 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10527 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10528 SDValue V = partitionShuffleOfConcats(N, DAG);
10534 // If this shuffle node is simply a swizzle of another shuffle node,
10535 // and it reverses the swizzle of the previous shuffle then we can
10536 // optimize shuffle(shuffle(x, undef), undef) -> x.
10537 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10538 N1.getOpcode() == ISD::UNDEF) {
10540 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10542 // Shuffle nodes can only reverse shuffles with a single non-undef value.
10543 if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10546 // The incoming shuffle must be of the same type as the result of the
10547 // current shuffle.
10548 assert(OtherSV->getOperand(0).getValueType() == VT &&
10549 "Shuffle types don't match");
10551 for (unsigned i = 0; i != NumElts; ++i) {
10552 int Idx = SVN->getMaskElt(i);
10553 assert(Idx < (int)NumElts && "Index references undef operand");
10554 // Next, this index comes from the first value, which is the incoming
10555 // shuffle. Adopt the incoming index.
10557 Idx = OtherSV->getMaskElt(Idx);
10559 // The combined shuffle must map each index to itself.
10560 if (Idx >= 0 && (unsigned)Idx != i)
10564 return OtherSV->getOperand(0);
10570 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10571 SDValue N0 = N->getOperand(0);
10572 SDValue N2 = N->getOperand(2);
10574 // If the input vector is a concatenation, and the insert replaces
10575 // one of the halves, we can optimize into a single concat_vectors.
10576 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10577 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10578 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10579 EVT VT = N->getValueType(0);
10581 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10582 // (concat_vectors Z, Y)
10584 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10585 N->getOperand(1), N0.getOperand(1));
10587 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10588 // (concat_vectors X, Z)
10589 if (InsIdx == VT.getVectorNumElements()/2)
10590 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10591 N0.getOperand(0), N->getOperand(1));
10597 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10598 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10599 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10600 /// vector_shuffle V, Zero, <0, 4, 2, 4>
10601 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10602 EVT VT = N->getValueType(0);
10604 SDValue LHS = N->getOperand(0);
10605 SDValue RHS = N->getOperand(1);
10606 if (N->getOpcode() == ISD::AND) {
10607 if (RHS.getOpcode() == ISD::BITCAST)
10608 RHS = RHS.getOperand(0);
10609 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10610 SmallVector<int, 8> Indices;
10611 unsigned NumElts = RHS.getNumOperands();
10612 for (unsigned i = 0; i != NumElts; ++i) {
10613 SDValue Elt = RHS.getOperand(i);
10614 if (!isa<ConstantSDNode>(Elt))
10617 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10618 Indices.push_back(i);
10619 else if (cast<ConstantSDNode>(Elt)->isNullValue())
10620 Indices.push_back(NumElts);
10625 // Let's see if the target supports this vector_shuffle.
10626 EVT RVT = RHS.getValueType();
10627 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10630 // Return the new VECTOR_SHUFFLE node.
10631 EVT EltVT = RVT.getVectorElementType();
10632 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10633 DAG.getConstant(0, EltVT));
10634 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
10635 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10636 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10637 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10644 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10645 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10646 assert(N->getValueType(0).isVector() &&
10647 "SimplifyVBinOp only works on vectors!");
10649 SDValue LHS = N->getOperand(0);
10650 SDValue RHS = N->getOperand(1);
10651 SDValue Shuffle = XformToShuffleWithZero(N);
10652 if (Shuffle.getNode()) return Shuffle;
10654 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10656 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10657 RHS.getOpcode() == ISD::BUILD_VECTOR) {
10658 // Check if both vectors are constants. If not bail out.
10659 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10660 cast<BuildVectorSDNode>(RHS)->isConstant()))
10663 SmallVector<SDValue, 8> Ops;
10664 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10665 SDValue LHSOp = LHS.getOperand(i);
10666 SDValue RHSOp = RHS.getOperand(i);
10668 // Can't fold divide by zero.
10669 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10670 N->getOpcode() == ISD::FDIV) {
10671 if ((RHSOp.getOpcode() == ISD::Constant &&
10672 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10673 (RHSOp.getOpcode() == ISD::ConstantFP &&
10674 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10678 EVT VT = LHSOp.getValueType();
10679 EVT RVT = RHSOp.getValueType();
10681 // Integer BUILD_VECTOR operands may have types larger than the element
10682 // size (e.g., when the element type is not legal). Prior to type
10683 // legalization, the types may not match between the two BUILD_VECTORS.
10684 // Truncate one of the operands to make them match.
10685 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10686 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10688 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10692 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10694 if (FoldOp.getOpcode() != ISD::UNDEF &&
10695 FoldOp.getOpcode() != ISD::Constant &&
10696 FoldOp.getOpcode() != ISD::ConstantFP)
10698 Ops.push_back(FoldOp);
10699 AddToWorkList(FoldOp.getNode());
10702 if (Ops.size() == LHS.getNumOperands())
10703 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
10709 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10710 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10711 assert(N->getValueType(0).isVector() &&
10712 "SimplifyVUnaryOp only works on vectors!");
10714 SDValue N0 = N->getOperand(0);
10716 if (N0.getOpcode() != ISD::BUILD_VECTOR)
10719 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10720 SmallVector<SDValue, 8> Ops;
10721 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10722 SDValue Op = N0.getOperand(i);
10723 if (Op.getOpcode() != ISD::UNDEF &&
10724 Op.getOpcode() != ISD::ConstantFP)
10726 EVT EltVT = Op.getValueType();
10727 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
10728 if (FoldOp.getOpcode() != ISD::UNDEF &&
10729 FoldOp.getOpcode() != ISD::ConstantFP)
10731 Ops.push_back(FoldOp);
10732 AddToWorkList(FoldOp.getNode());
10735 if (Ops.size() != N0.getNumOperands())
10738 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
10741 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10742 SDValue N1, SDValue N2){
10743 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10745 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
10746 cast<CondCodeSDNode>(N0.getOperand(2))->get());
10748 // If we got a simplified select_cc node back from SimplifySelectCC, then
10749 // break it down into a new SETCC node, and a new SELECT node, and then return
10750 // the SELECT node, since we were called with a SELECT node.
10751 if (SCC.getNode()) {
10752 // Check to see if we got a select_cc back (to turn into setcc/select).
10753 // Otherwise, just return whatever node we got back, like fabs.
10754 if (SCC.getOpcode() == ISD::SELECT_CC) {
10755 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
10757 SCC.getOperand(0), SCC.getOperand(1),
10758 SCC.getOperand(4));
10759 AddToWorkList(SETCC.getNode());
10760 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10761 SCC.getOperand(2), SCC.getOperand(3), SETCC);
10769 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10770 /// are the two values being selected between, see if we can simplify the
10771 /// select. Callers of this should assume that TheSelect is deleted if this
10772 /// returns true. As such, they should return the appropriate thing (e.g. the
10773 /// node) back to the top-level of the DAG combiner loop to avoid it being
10775 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
10778 // Cannot simplify select with vector condition
10779 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10781 // If this is a select from two identical things, try to pull the operation
10782 // through the select.
10783 if (LHS.getOpcode() != RHS.getOpcode() ||
10784 !LHS.hasOneUse() || !RHS.hasOneUse())
10787 // If this is a load and the token chain is identical, replace the select
10788 // of two loads with a load through a select of the address to load from.
10789 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10790 // constants have been dropped into the constant pool.
10791 if (LHS.getOpcode() == ISD::LOAD) {
10792 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10793 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
10795 // Token chains must be identical.
10796 if (LHS.getOperand(0) != RHS.getOperand(0) ||
10797 // Do not let this transformation reduce the number of volatile loads.
10798 LLD->isVolatile() || RLD->isVolatile() ||
10799 // If this is an EXTLOAD, the VT's must match.
10800 LLD->getMemoryVT() != RLD->getMemoryVT() ||
10801 // If this is an EXTLOAD, the kind of extension must match.
10802 (LLD->getExtensionType() != RLD->getExtensionType() &&
10803 // The only exception is if one of the extensions is anyext.
10804 LLD->getExtensionType() != ISD::EXTLOAD &&
10805 RLD->getExtensionType() != ISD::EXTLOAD) ||
10806 // FIXME: this discards src value information. This is
10807 // over-conservative. It would be beneficial to be able to remember
10808 // both potential memory locations. Since we are discarding
10809 // src value info, don't do the transformation if the memory
10810 // locations are not in the default address space.
10811 LLD->getPointerInfo().getAddrSpace() != 0 ||
10812 RLD->getPointerInfo().getAddrSpace() != 0 ||
10813 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10814 LLD->getBasePtr().getValueType()))
10817 // Check that the select condition doesn't reach either load. If so,
10818 // folding this will induce a cycle into the DAG. If not, this is safe to
10819 // xform, so create a select of the addresses.
10821 if (TheSelect->getOpcode() == ISD::SELECT) {
10822 SDNode *CondNode = TheSelect->getOperand(0).getNode();
10823 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10824 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10826 // The loads must not depend on one another.
10827 if (LLD->isPredecessorOf(RLD) ||
10828 RLD->isPredecessorOf(LLD))
10830 Addr = DAG.getSelect(SDLoc(TheSelect),
10831 LLD->getBasePtr().getValueType(),
10832 TheSelect->getOperand(0), LLD->getBasePtr(),
10833 RLD->getBasePtr());
10834 } else { // Otherwise SELECT_CC
10835 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10836 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10838 if ((LLD->hasAnyUseOfValue(1) &&
10839 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
10840 (RLD->hasAnyUseOfValue(1) &&
10841 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
10844 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
10845 LLD->getBasePtr().getValueType(),
10846 TheSelect->getOperand(0),
10847 TheSelect->getOperand(1),
10848 LLD->getBasePtr(), RLD->getBasePtr(),
10849 TheSelect->getOperand(4));
10853 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10854 Load = DAG.getLoad(TheSelect->getValueType(0),
10856 // FIXME: Discards pointer and TBAA info.
10857 LLD->getChain(), Addr, MachinePointerInfo(),
10858 LLD->isVolatile(), LLD->isNonTemporal(),
10859 LLD->isInvariant(), LLD->getAlignment());
10861 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10862 RLD->getExtensionType() : LLD->getExtensionType(),
10864 TheSelect->getValueType(0),
10865 // FIXME: Discards pointer and TBAA info.
10866 LLD->getChain(), Addr, MachinePointerInfo(),
10867 LLD->getMemoryVT(), LLD->isVolatile(),
10868 LLD->isNonTemporal(), LLD->getAlignment());
10871 // Users of the select now use the result of the load.
10872 CombineTo(TheSelect, Load);
10874 // Users of the old loads now use the new load's chain. We know the
10875 // old-load value is dead now.
10876 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10877 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10884 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10885 /// where 'cond' is the comparison specified by CC.
10886 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
10887 SDValue N2, SDValue N3,
10888 ISD::CondCode CC, bool NotExtCompare) {
10889 // (x ? y : y) -> y.
10890 if (N2 == N3) return N2;
10892 EVT VT = N2.getValueType();
10893 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10894 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10895 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
10897 // Determine if the condition we're dealing with is constant
10898 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
10899 N0, N1, CC, DL, false);
10900 if (SCC.getNode()) AddToWorkList(SCC.getNode());
10901 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
10903 // fold select_cc true, x, y -> x
10904 if (SCCC && !SCCC->isNullValue())
10906 // fold select_cc false, x, y -> y
10907 if (SCCC && SCCC->isNullValue())
10910 // Check to see if we can simplify the select into an fabs node
10911 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10912 // Allow either -0.0 or 0.0
10913 if (CFP->getValueAPF().isZero()) {
10914 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10915 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10916 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10917 N2 == N3.getOperand(0))
10918 return DAG.getNode(ISD::FABS, DL, VT, N0);
10920 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10921 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10922 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10923 N2.getOperand(0) == N3)
10924 return DAG.getNode(ISD::FABS, DL, VT, N3);
10928 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10929 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10930 // in it. This is a win when the constant is not otherwise available because
10931 // it replaces two constant pool loads with one. We only do this if the FP
10932 // type is known to be legal, because if it isn't, then we are before legalize
10933 // types an we want the other legalization to happen first (e.g. to avoid
10934 // messing with soft float) and if the ConstantFP is not legal, because if
10935 // it is legal, we may not need to store the FP constant in a constant pool.
10936 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10937 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10938 if (TLI.isTypeLegal(N2.getValueType()) &&
10939 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10940 TargetLowering::Legal &&
10941 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
10942 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
10943 // If both constants have multiple uses, then we won't need to do an
10944 // extra load, they are likely around in registers for other users.
10945 (TV->hasOneUse() || FV->hasOneUse())) {
10946 Constant *Elts[] = {
10947 const_cast<ConstantFP*>(FV->getConstantFPValue()),
10948 const_cast<ConstantFP*>(TV->getConstantFPValue())
10950 Type *FPTy = Elts[0]->getType();
10951 const DataLayout &TD = *TLI.getDataLayout();
10953 // Create a ConstantArray of the two constants.
10954 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
10955 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10956 TD.getPrefTypeAlignment(FPTy));
10957 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10959 // Get the offsets to the 0 and 1 element of the array so that we can
10960 // select between them.
10961 SDValue Zero = DAG.getIntPtrConstant(0);
10962 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
10963 SDValue One = DAG.getIntPtrConstant(EltSize);
10965 SDValue Cond = DAG.getSetCC(DL,
10966 getSetCCResultType(N0.getValueType()),
10968 AddToWorkList(Cond.getNode());
10969 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
10971 AddToWorkList(CstOffset.getNode());
10972 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
10974 AddToWorkList(CPIdx.getNode());
10975 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
10976 MachinePointerInfo::getConstantPool(), false,
10977 false, false, Alignment);
10982 // Check to see if we can perform the "gzip trick", transforming
10983 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
10984 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
10985 (N1C->isNullValue() || // (a < 0) ? b : 0
10986 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
10987 EVT XType = N0.getValueType();
10988 EVT AType = N2.getValueType();
10989 if (XType.bitsGE(AType)) {
10990 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
10991 // single-bit constant.
10992 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
10993 unsigned ShCtV = N2C->getAPIntValue().logBase2();
10994 ShCtV = XType.getSizeInBits()-ShCtV-1;
10995 SDValue ShCt = DAG.getConstant(ShCtV,
10996 getShiftAmountTy(N0.getValueType()));
10997 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
10999 AddToWorkList(Shift.getNode());
11001 if (XType.bitsGT(AType)) {
11002 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11003 AddToWorkList(Shift.getNode());
11006 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11009 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11011 DAG.getConstant(XType.getSizeInBits()-1,
11012 getShiftAmountTy(N0.getValueType())));
11013 AddToWorkList(Shift.getNode());
11015 if (XType.bitsGT(AType)) {
11016 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11017 AddToWorkList(Shift.getNode());
11020 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11024 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11025 // where y is has a single bit set.
11026 // A plaintext description would be, we can turn the SELECT_CC into an AND
11027 // when the condition can be materialized as an all-ones register. Any
11028 // single bit-test can be materialized as an all-ones register with
11029 // shift-left and shift-right-arith.
11030 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11031 N0->getValueType(0) == VT &&
11032 N1C && N1C->isNullValue() &&
11033 N2C && N2C->isNullValue()) {
11034 SDValue AndLHS = N0->getOperand(0);
11035 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11036 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11037 // Shift the tested bit over the sign bit.
11038 APInt AndMask = ConstAndRHS->getAPIntValue();
11040 DAG.getConstant(AndMask.countLeadingZeros(),
11041 getShiftAmountTy(AndLHS.getValueType()));
11042 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11044 // Now arithmetic right shift it all the way over, so the result is either
11045 // all-ones, or zero.
11047 DAG.getConstant(AndMask.getBitWidth()-1,
11048 getShiftAmountTy(Shl.getValueType()));
11049 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11051 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11055 // fold select C, 16, 0 -> shl C, 4
11056 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11057 TLI.getBooleanContents(N0.getValueType().isVector()) ==
11058 TargetLowering::ZeroOrOneBooleanContent) {
11060 // If the caller doesn't want us to simplify this into a zext of a compare,
11062 if (NotExtCompare && N2C->getAPIntValue() == 1)
11065 // Get a SetCC of the condition
11066 // NOTE: Don't create a SETCC if it's not legal on this target.
11067 if (!LegalOperations ||
11068 TLI.isOperationLegal(ISD::SETCC,
11069 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11071 // cast from setcc result type to select result type
11073 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11075 if (N2.getValueType().bitsLT(SCC.getValueType()))
11076 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11077 N2.getValueType());
11079 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11080 N2.getValueType(), SCC);
11082 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11083 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11084 N2.getValueType(), SCC);
11087 AddToWorkList(SCC.getNode());
11088 AddToWorkList(Temp.getNode());
11090 if (N2C->getAPIntValue() == 1)
11093 // shl setcc result by log2 n2c
11094 return DAG.getNode(
11095 ISD::SHL, DL, N2.getValueType(), Temp,
11096 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11097 getShiftAmountTy(Temp.getValueType())));
11101 // Check to see if this is the equivalent of setcc
11102 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11103 // otherwise, go ahead with the folds.
11104 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11105 EVT XType = N0.getValueType();
11106 if (!LegalOperations ||
11107 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11108 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11109 if (Res.getValueType() != VT)
11110 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11114 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11115 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11116 (!LegalOperations ||
11117 TLI.isOperationLegal(ISD::CTLZ, XType))) {
11118 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11119 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11120 DAG.getConstant(Log2_32(XType.getSizeInBits()),
11121 getShiftAmountTy(Ctlz.getValueType())));
11123 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11124 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11125 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11126 XType, DAG.getConstant(0, XType), N0);
11127 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11128 return DAG.getNode(ISD::SRL, DL, XType,
11129 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11130 DAG.getConstant(XType.getSizeInBits()-1,
11131 getShiftAmountTy(XType)));
11133 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11134 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11135 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11136 DAG.getConstant(XType.getSizeInBits()-1,
11137 getShiftAmountTy(N0.getValueType())));
11138 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11142 // Check to see if this is an integer abs.
11143 // select_cc setg[te] X, 0, X, -X ->
11144 // select_cc setgt X, -1, X, -X ->
11145 // select_cc setl[te] X, 0, -X, X ->
11146 // select_cc setlt X, 1, -X, X ->
11147 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11149 ConstantSDNode *SubC = nullptr;
11150 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11151 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11152 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11153 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11154 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11155 (N1C->isOne() && CC == ISD::SETLT)) &&
11156 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11157 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11159 EVT XType = N0.getValueType();
11160 if (SubC && SubC->isNullValue() && XType.isInteger()) {
11161 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11163 DAG.getConstant(XType.getSizeInBits()-1,
11164 getShiftAmountTy(N0.getValueType())));
11165 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11167 AddToWorkList(Shift.getNode());
11168 AddToWorkList(Add.getNode());
11169 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11176 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11177 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11178 SDValue N1, ISD::CondCode Cond,
11179 SDLoc DL, bool foldBooleans) {
11180 TargetLowering::DAGCombinerInfo
11181 DagCombineInfo(DAG, Level, false, this);
11182 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11185 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11186 /// return a DAG expression to select that will generate the same value by
11187 /// multiplying by a magic number. See:
11188 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11189 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11190 const APInt *Divisor;
11191 if (N->getValueType(0).isVector()) {
11192 // Handle splat vectors.
11193 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N->getOperand(1));
11194 if (ConstantSDNode *C = BV->getConstantSplatValue())
11195 Divisor = &C->getAPIntValue();
11199 Divisor = &cast<ConstantSDNode>(N->getOperand(1))->getAPIntValue();
11202 // Avoid division by zero.
11206 std::vector<SDNode*> Built;
11207 SDValue S = TLI.BuildSDIV(N, *Divisor, DAG, LegalOperations, &Built);
11209 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
11211 AddToWorkList(*ii);
11215 /// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant,
11216 /// return a DAG expression to select that will generate the same value by
11217 /// multiplying by a magic number. See:
11218 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11219 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11220 const APInt *Divisor;
11221 if (N->getValueType(0).isVector()) {
11222 // Handle splat vectors.
11223 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N->getOperand(1));
11224 if (ConstantSDNode *C = BV->getConstantSplatValue())
11225 Divisor = &C->getAPIntValue();
11229 Divisor = &cast<ConstantSDNode>(N->getOperand(1))->getAPIntValue();
11232 // Avoid division by zero.
11236 std::vector<SDNode*> Built;
11237 SDValue S = TLI.BuildUDIV(N, *Divisor, DAG, LegalOperations, &Built);
11239 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
11241 AddToWorkList(*ii);
11245 /// FindBaseOffset - Return true if base is a frame index, which is known not
11246 // to alias with anything but itself. Provides base object and offset as
11248 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11249 const GlobalValue *&GV, const void *&CV) {
11250 // Assume it is a primitive operation.
11251 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11253 // If it's an adding a simple constant then integrate the offset.
11254 if (Base.getOpcode() == ISD::ADD) {
11255 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11256 Base = Base.getOperand(0);
11257 Offset += C->getZExtValue();
11261 // Return the underlying GlobalValue, and update the Offset. Return false
11262 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11263 // by multiple nodes with different offsets.
11264 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11265 GV = G->getGlobal();
11266 Offset += G->getOffset();
11270 // Return the underlying Constant value, and update the Offset. Return false
11271 // for ConstantSDNodes since the same constant pool entry may be represented
11272 // by multiple nodes with different offsets.
11273 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11274 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11275 : (const void *)C->getConstVal();
11276 Offset += C->getOffset();
11279 // If it's any of the following then it can't alias with anything but itself.
11280 return isa<FrameIndexSDNode>(Base);
11283 /// isAlias - Return true if there is any possibility that the two addresses
11285 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11286 // If they are the same then they must be aliases.
11287 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11289 // If they are both volatile then they cannot be reordered.
11290 if (Op0->isVolatile() && Op1->isVolatile()) return true;
11292 // Gather base node and offset information.
11293 SDValue Base1, Base2;
11294 int64_t Offset1, Offset2;
11295 const GlobalValue *GV1, *GV2;
11296 const void *CV1, *CV2;
11297 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11298 Base1, Offset1, GV1, CV1);
11299 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11300 Base2, Offset2, GV2, CV2);
11302 // If they have a same base address then check to see if they overlap.
11303 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11304 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11305 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11307 // It is possible for different frame indices to alias each other, mostly
11308 // when tail call optimization reuses return address slots for arguments.
11309 // To catch this case, look up the actual index of frame indices to compute
11310 // the real alias relationship.
11311 if (isFrameIndex1 && isFrameIndex2) {
11312 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11313 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11314 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11315 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11316 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11319 // Otherwise, if we know what the bases are, and they aren't identical, then
11320 // we know they cannot alias.
11321 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11324 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11325 // compared to the size and offset of the access, we may be able to prove they
11326 // do not alias. This check is conservative for now to catch cases created by
11327 // splitting vector types.
11328 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11329 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11330 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11331 Op1->getMemoryVT().getSizeInBits() >> 3) &&
11332 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11333 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11334 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11336 // There is no overlap between these relatively aligned accesses of similar
11337 // size, return no alias.
11338 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11339 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11343 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11344 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11346 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11347 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11351 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11352 // Use alias analysis information.
11353 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11354 Op1->getSrcValueOffset());
11355 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11356 Op0->getSrcValueOffset() - MinOffset;
11357 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11358 Op1->getSrcValueOffset() - MinOffset;
11359 AliasAnalysis::AliasResult AAResult =
11360 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11362 UseTBAA ? Op0->getTBAAInfo() : nullptr),
11363 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11365 UseTBAA ? Op1->getTBAAInfo() : nullptr));
11366 if (AAResult == AliasAnalysis::NoAlias)
11370 // Otherwise we have to assume they alias.
11374 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11375 /// looking for aliasing nodes and adding them to the Aliases vector.
11376 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11377 SmallVectorImpl<SDValue> &Aliases) {
11378 SmallVector<SDValue, 8> Chains; // List of chains to visit.
11379 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
11381 // Get alias information for node.
11382 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11385 Chains.push_back(OriginalChain);
11386 unsigned Depth = 0;
11388 // Look at each chain and determine if it is an alias. If so, add it to the
11389 // aliases list. If not, then continue up the chain looking for the next
11391 while (!Chains.empty()) {
11392 SDValue Chain = Chains.back();
11395 // For TokenFactor nodes, look at each operand and only continue up the
11396 // chain until we find two aliases. If we've seen two aliases, assume we'll
11397 // find more and revert to original chain since the xform is unlikely to be
11400 // FIXME: The depth check could be made to return the last non-aliasing
11401 // chain we found before we hit a tokenfactor rather than the original
11403 if (Depth > 6 || Aliases.size() == 2) {
11405 Aliases.push_back(OriginalChain);
11409 // Don't bother if we've been before.
11410 if (!Visited.insert(Chain.getNode()))
11413 switch (Chain.getOpcode()) {
11414 case ISD::EntryToken:
11415 // Entry token is ideal chain operand, but handled in FindBetterChain.
11420 // Get alias information for Chain.
11421 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11422 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11424 // If chain is alias then stop here.
11425 if (!(IsLoad && IsOpLoad) &&
11426 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11427 Aliases.push_back(Chain);
11429 // Look further up the chain.
11430 Chains.push_back(Chain.getOperand(0));
11436 case ISD::TokenFactor:
11437 // We have to check each of the operands of the token factor for "small"
11438 // token factors, so we queue them up. Adding the operands to the queue
11439 // (stack) in reverse order maintains the original order and increases the
11440 // likelihood that getNode will find a matching token factor (CSE.)
11441 if (Chain.getNumOperands() > 16) {
11442 Aliases.push_back(Chain);
11445 for (unsigned n = Chain.getNumOperands(); n;)
11446 Chains.push_back(Chain.getOperand(--n));
11451 // For all other instructions we will just have to take what we can get.
11452 Aliases.push_back(Chain);
11457 // We need to be careful here to also search for aliases through the
11458 // value operand of a store, etc. Consider the following situation:
11460 // L1 = load Token1, %52
11461 // S1 = store Token1, L1, %51
11462 // L2 = load Token1, %52+8
11463 // S2 = store Token1, L2, %51+8
11464 // Token2 = Token(S1, S2)
11465 // L3 = load Token2, %53
11466 // S3 = store Token2, L3, %52
11467 // L4 = load Token2, %53+8
11468 // S4 = store Token2, L4, %52+8
11469 // If we search for aliases of S3 (which loads address %52), and we look
11470 // only through the chain, then we'll miss the trivial dependence on L1
11471 // (which also loads from %52). We then might change all loads and
11472 // stores to use Token1 as their chain operand, which could result in
11473 // copying %53 into %52 before copying %52 into %51 (which should
11476 // The problem is, however, that searching for such data dependencies
11477 // can become expensive, and the cost is not directly related to the
11478 // chain depth. Instead, we'll rule out such configurations here by
11479 // insisting that we've visited all chain users (except for users
11480 // of the original chain, which is not necessary). When doing this,
11481 // we need to look through nodes we don't care about (otherwise, things
11482 // like register copies will interfere with trivial cases).
11484 SmallVector<const SDNode *, 16> Worklist;
11485 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11486 IE = Visited.end(); I != IE; ++I)
11487 if (*I != OriginalChain.getNode())
11488 Worklist.push_back(*I);
11490 while (!Worklist.empty()) {
11491 const SDNode *M = Worklist.pop_back_val();
11493 // We have already visited M, and want to make sure we've visited any uses
11494 // of M that we care about. For uses that we've not visisted, and don't
11495 // care about, queue them to the worklist.
11497 for (SDNode::use_iterator UI = M->use_begin(),
11498 UIE = M->use_end(); UI != UIE; ++UI)
11499 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11500 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11501 // We've not visited this use, and we care about it (it could have an
11502 // ordering dependency with the original node).
11504 Aliases.push_back(OriginalChain);
11508 // We've not visited this use, but we don't care about it. Mark it as
11509 // visited and enqueue it to the worklist.
11510 Worklist.push_back(*UI);
11515 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11516 /// for a better chain (aliasing node.)
11517 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11518 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
11520 // Accumulate all the aliases to this node.
11521 GatherAllAliases(N, OldChain, Aliases);
11523 // If no operands then chain to entry token.
11524 if (Aliases.size() == 0)
11525 return DAG.getEntryNode();
11527 // If a single operand then chain to it. We don't need to revisit it.
11528 if (Aliases.size() == 1)
11531 // Construct a custom tailored token factor.
11532 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
11535 // SelectionDAG::Combine - This is the entry point for the file.
11537 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11538 CodeGenOpt::Level OptLevel) {
11539 /// run - This is the main entry point to this class.
11541 DAGCombiner(*this, AA, OptLevel).Run(Level);