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 // Skip handle nodes as they can't usefully be combined and confuse the
131 // zero-use deletion strategy.
132 if (N->getOpcode() == ISD::HANDLENODE)
135 WorklistContents.insert(N);
136 WorklistOrder.push_back(N);
139 /// removeFromWorklist - remove all instances of N from the worklist.
141 void removeFromWorklist(SDNode *N) {
142 WorklistContents.erase(N);
145 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
148 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
149 return CombineTo(N, &Res, 1, AddTo);
152 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
154 SDValue To[] = { Res0, Res1 };
155 return CombineTo(N, To, 2, AddTo);
158 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
162 /// SimplifyDemandedBits - Check the specified integer node value to see if
163 /// it can be simplified or if things it uses can be simplified by bit
164 /// propagation. If so, return true.
165 bool SimplifyDemandedBits(SDValue Op) {
166 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
167 APInt Demanded = APInt::getAllOnesValue(BitWidth);
168 return SimplifyDemandedBits(Op, Demanded);
171 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
173 bool CombineToPreIndexedLoadStore(SDNode *N);
174 bool CombineToPostIndexedLoadStore(SDNode *N);
175 bool SliceUpLoad(SDNode *N);
177 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
178 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
179 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
180 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
181 SDValue PromoteIntBinOp(SDValue Op);
182 SDValue PromoteIntShiftOp(SDValue Op);
183 SDValue PromoteExtend(SDValue Op);
184 bool PromoteLoad(SDValue Op);
186 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
187 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
188 ISD::NodeType ExtType);
190 /// combine - call the node-specific routine that knows how to fold each
191 /// particular type of node. If that doesn't do anything, try the
192 /// target-specific DAG combines.
193 SDValue combine(SDNode *N);
195 // Visitation implementation - Implement dag node combining for different
196 // node types. The semantics are as follows:
198 // SDValue.getNode() == 0 - No change was made
199 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
200 // otherwise - N should be replaced by the returned Operand.
202 SDValue visitTokenFactor(SDNode *N);
203 SDValue visitMERGE_VALUES(SDNode *N);
204 SDValue visitADD(SDNode *N);
205 SDValue visitSUB(SDNode *N);
206 SDValue visitADDC(SDNode *N);
207 SDValue visitSUBC(SDNode *N);
208 SDValue visitADDE(SDNode *N);
209 SDValue visitSUBE(SDNode *N);
210 SDValue visitMUL(SDNode *N);
211 SDValue visitSDIV(SDNode *N);
212 SDValue visitUDIV(SDNode *N);
213 SDValue visitSREM(SDNode *N);
214 SDValue visitUREM(SDNode *N);
215 SDValue visitMULHU(SDNode *N);
216 SDValue visitMULHS(SDNode *N);
217 SDValue visitSMUL_LOHI(SDNode *N);
218 SDValue visitUMUL_LOHI(SDNode *N);
219 SDValue visitSMULO(SDNode *N);
220 SDValue visitUMULO(SDNode *N);
221 SDValue visitSDIVREM(SDNode *N);
222 SDValue visitUDIVREM(SDNode *N);
223 SDValue visitAND(SDNode *N);
224 SDValue visitOR(SDNode *N);
225 SDValue visitXOR(SDNode *N);
226 SDValue SimplifyVBinOp(SDNode *N);
227 SDValue SimplifyVUnaryOp(SDNode *N);
228 SDValue visitSHL(SDNode *N);
229 SDValue visitSRA(SDNode *N);
230 SDValue visitSRL(SDNode *N);
231 SDValue visitRotate(SDNode *N);
232 SDValue visitCTLZ(SDNode *N);
233 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
234 SDValue visitCTTZ(SDNode *N);
235 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
236 SDValue visitCTPOP(SDNode *N);
237 SDValue visitSELECT(SDNode *N);
238 SDValue visitVSELECT(SDNode *N);
239 SDValue visitSELECT_CC(SDNode *N);
240 SDValue visitSETCC(SDNode *N);
241 SDValue visitSIGN_EXTEND(SDNode *N);
242 SDValue visitZERO_EXTEND(SDNode *N);
243 SDValue visitANY_EXTEND(SDNode *N);
244 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
245 SDValue visitTRUNCATE(SDNode *N);
246 SDValue visitBITCAST(SDNode *N);
247 SDValue visitBUILD_PAIR(SDNode *N);
248 SDValue visitFADD(SDNode *N);
249 SDValue visitFSUB(SDNode *N);
250 SDValue visitFMUL(SDNode *N);
251 SDValue visitFMA(SDNode *N);
252 SDValue visitFDIV(SDNode *N);
253 SDValue visitFREM(SDNode *N);
254 SDValue visitFCOPYSIGN(SDNode *N);
255 SDValue visitSINT_TO_FP(SDNode *N);
256 SDValue visitUINT_TO_FP(SDNode *N);
257 SDValue visitFP_TO_SINT(SDNode *N);
258 SDValue visitFP_TO_UINT(SDNode *N);
259 SDValue visitFP_ROUND(SDNode *N);
260 SDValue visitFP_ROUND_INREG(SDNode *N);
261 SDValue visitFP_EXTEND(SDNode *N);
262 SDValue visitFNEG(SDNode *N);
263 SDValue visitFABS(SDNode *N);
264 SDValue visitFCEIL(SDNode *N);
265 SDValue visitFTRUNC(SDNode *N);
266 SDValue visitFFLOOR(SDNode *N);
267 SDValue visitBRCOND(SDNode *N);
268 SDValue visitBR_CC(SDNode *N);
269 SDValue visitLOAD(SDNode *N);
270 SDValue visitSTORE(SDNode *N);
271 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
272 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
273 SDValue visitBUILD_VECTOR(SDNode *N);
274 SDValue visitCONCAT_VECTORS(SDNode *N);
275 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
276 SDValue visitVECTOR_SHUFFLE(SDNode *N);
277 SDValue visitINSERT_SUBVECTOR(SDNode *N);
279 SDValue XformToShuffleWithZero(SDNode *N);
280 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
282 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
284 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
285 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
286 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
287 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
288 SDValue N3, ISD::CondCode CC,
289 bool NotExtCompare = false);
290 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
291 SDLoc DL, bool foldBooleans = true);
293 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
295 bool isOneUseSetCC(SDValue N) const;
297 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
299 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
300 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
301 SDValue BuildSDIV(SDNode *N);
302 SDValue BuildUDIV(SDNode *N);
303 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
304 bool DemandHighBits = true);
305 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
306 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
307 SDValue InnerPos, SDValue InnerNeg,
308 unsigned PosOpcode, unsigned NegOpcode,
310 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
311 SDValue ReduceLoadWidth(SDNode *N);
312 SDValue ReduceLoadOpStoreWidth(SDNode *N);
313 SDValue TransformFPLoadStorePair(SDNode *N);
314 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
315 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
317 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
319 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
320 /// looking for aliasing nodes and adding them to the Aliases vector.
321 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
322 SmallVectorImpl<SDValue> &Aliases);
324 /// isAlias - Return true if there is any possibility that the two addresses
326 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
328 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
329 /// looking for a better chain (aliasing node.)
330 SDValue FindBetterChain(SDNode *N, SDValue Chain);
332 /// Merge consecutive store operations into a wide store.
333 /// This optimization uses wide integers or vectors when possible.
334 /// \return True if some memory operations were changed.
335 bool MergeConsecutiveStores(StoreSDNode *N);
337 /// \brief Try to transform a truncation where C is a constant:
338 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
340 /// \p N needs to be a truncation and its first operand an AND. Other
341 /// requirements are checked by the function (e.g. that trunc is
342 /// single-use) and if missed an empty SDValue is returned.
343 SDValue distributeTruncateThroughAnd(SDNode *N);
346 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
347 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
348 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
349 AttributeSet FnAttrs =
350 DAG.getMachineFunction().getFunction()->getAttributes();
352 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
353 Attribute::OptimizeForSize) ||
354 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
357 /// Run - runs the dag combiner on all nodes in the work list
358 void Run(CombineLevel AtLevel);
360 SelectionDAG &getDAG() const { return DAG; }
362 /// getShiftAmountTy - Returns a type large enough to hold any valid
363 /// shift amount - before type legalization these can be huge.
364 EVT getShiftAmountTy(EVT LHSTy) {
365 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
366 if (LHSTy.isVector())
368 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
369 : TLI.getPointerTy();
372 /// isTypeLegal - This method returns true if we are running before type
373 /// legalization or if the specified VT is legal.
374 bool isTypeLegal(const EVT &VT) {
375 if (!LegalTypes) return true;
376 return TLI.isTypeLegal(VT);
379 /// getSetCCResultType - Convenience wrapper around
380 /// TargetLowering::getSetCCResultType
381 EVT getSetCCResultType(EVT VT) const {
382 return TLI.getSetCCResultType(*DAG.getContext(), VT);
389 /// WorklistRemover - This class is a DAGUpdateListener that removes any deleted
390 /// nodes from the worklist.
391 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
394 explicit WorklistRemover(DAGCombiner &dc)
395 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
397 void NodeDeleted(SDNode *N, SDNode *E) override {
398 DC.removeFromWorklist(N);
403 //===----------------------------------------------------------------------===//
404 // TargetLowering::DAGCombinerInfo implementation
405 //===----------------------------------------------------------------------===//
407 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
408 ((DAGCombiner*)DC)->AddToWorklist(N);
411 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
412 ((DAGCombiner*)DC)->removeFromWorklist(N);
415 SDValue TargetLowering::DAGCombinerInfo::
416 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
417 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
420 SDValue TargetLowering::DAGCombinerInfo::
421 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
422 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
426 SDValue TargetLowering::DAGCombinerInfo::
427 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
428 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
431 void TargetLowering::DAGCombinerInfo::
432 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
433 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
436 //===----------------------------------------------------------------------===//
438 //===----------------------------------------------------------------------===//
440 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
441 /// specified expression for the same cost as the expression itself, or 2 if we
442 /// can compute the negated form more cheaply than the expression itself.
443 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
444 const TargetLowering &TLI,
445 const TargetOptions *Options,
446 unsigned Depth = 0) {
447 // fneg is removable even if it has multiple uses.
448 if (Op.getOpcode() == ISD::FNEG) return 2;
450 // Don't allow anything with multiple uses.
451 if (!Op.hasOneUse()) return 0;
453 // Don't recurse exponentially.
454 if (Depth > 6) return 0;
456 switch (Op.getOpcode()) {
457 default: return false;
458 case ISD::ConstantFP:
459 // Don't invert constant FP values after legalize. The negated constant
460 // isn't necessarily legal.
461 return LegalOperations ? 0 : 1;
463 // FIXME: determine better conditions for this xform.
464 if (!Options->UnsafeFPMath) return 0;
466 // After operation legalization, it might not be legal to create new FSUBs.
467 if (LegalOperations &&
468 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
471 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
472 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
475 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
476 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
479 // We can't turn -(A-B) into B-A when we honor signed zeros.
480 if (!Options->UnsafeFPMath) return 0;
482 // fold (fneg (fsub A, B)) -> (fsub B, A)
487 if (Options->HonorSignDependentRoundingFPMath()) return 0;
489 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
490 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
494 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
500 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
505 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
506 /// returns the newly negated expression.
507 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
508 bool LegalOperations, unsigned Depth = 0) {
509 // fneg is removable even if it has multiple uses.
510 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
512 // Don't allow anything with multiple uses.
513 assert(Op.hasOneUse() && "Unknown reuse!");
515 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
516 switch (Op.getOpcode()) {
517 default: llvm_unreachable("Unknown code");
518 case ISD::ConstantFP: {
519 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
521 return DAG.getConstantFP(V, Op.getValueType());
524 // FIXME: determine better conditions for this xform.
525 assert(DAG.getTarget().Options.UnsafeFPMath);
527 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
528 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
529 DAG.getTargetLoweringInfo(),
530 &DAG.getTarget().Options, Depth+1))
531 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
532 GetNegatedExpression(Op.getOperand(0), DAG,
533 LegalOperations, Depth+1),
535 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
536 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
537 GetNegatedExpression(Op.getOperand(1), DAG,
538 LegalOperations, Depth+1),
541 // We can't turn -(A-B) into B-A when we honor signed zeros.
542 assert(DAG.getTarget().Options.UnsafeFPMath);
544 // fold (fneg (fsub 0, B)) -> B
545 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
546 if (N0CFP->getValueAPF().isZero())
547 return Op.getOperand(1);
549 // fold (fneg (fsub A, B)) -> (fsub B, A)
550 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
551 Op.getOperand(1), Op.getOperand(0));
555 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
557 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
558 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
559 DAG.getTargetLoweringInfo(),
560 &DAG.getTarget().Options, Depth+1))
561 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
562 GetNegatedExpression(Op.getOperand(0), DAG,
563 LegalOperations, Depth+1),
566 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
567 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
569 GetNegatedExpression(Op.getOperand(1), DAG,
570 LegalOperations, Depth+1));
574 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
575 GetNegatedExpression(Op.getOperand(0), DAG,
576 LegalOperations, Depth+1));
578 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
579 GetNegatedExpression(Op.getOperand(0), DAG,
580 LegalOperations, Depth+1),
585 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
586 // that selects between the target values used for true and false, making it
587 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
588 // the appropriate nodes based on the type of node we are checking. This
589 // simplifies life a bit for the callers.
590 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
592 if (N.getOpcode() == ISD::SETCC) {
593 LHS = N.getOperand(0);
594 RHS = N.getOperand(1);
595 CC = N.getOperand(2);
599 if (N.getOpcode() != ISD::SELECT_CC ||
600 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
601 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
604 LHS = N.getOperand(0);
605 RHS = N.getOperand(1);
606 CC = N.getOperand(4);
610 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
611 // one use. If this is true, it allows the users to invert the operation for
612 // free when it is profitable to do so.
613 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
615 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
620 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
621 /// elements are all the same constant or undefined.
622 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
623 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
628 unsigned SplatBitSize;
630 EVT EltVT = N->getValueType(0).getVectorElementType();
631 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
633 EltVT.getSizeInBits() >= SplatBitSize);
636 // \brief Returns the SDNode if it is a constant BuildVector or constant.
637 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
638 if (isa<ConstantSDNode>(N))
640 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
641 if(BV && BV->isConstant())
646 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
648 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
649 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
652 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
653 BitVector UndefElements;
654 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
656 // BuildVectors can truncate their operands. Ignore that case here.
657 // FIXME: We blindly ignore splats which include undef which is overly
659 if (CN && UndefElements.none() &&
660 CN->getValueType(0) == N.getValueType().getScalarType())
667 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
668 SDValue N0, SDValue N1) {
669 EVT VT = N0.getValueType();
670 if (N0.getOpcode() == Opc) {
671 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
672 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
673 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
674 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
675 if (!OpNode.getNode())
677 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
679 if (N0.hasOneUse()) {
680 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
682 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
683 if (!OpNode.getNode())
685 AddToWorklist(OpNode.getNode());
686 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
691 if (N1.getOpcode() == Opc) {
692 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
693 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
694 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
695 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
696 if (!OpNode.getNode())
698 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
700 if (N1.hasOneUse()) {
701 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
703 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
704 if (!OpNode.getNode())
706 AddToWorklist(OpNode.getNode());
707 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
715 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
717 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
719 DEBUG(dbgs() << "\nReplacing.1 ";
721 dbgs() << "\nWith: ";
722 To[0].getNode()->dump(&DAG);
723 dbgs() << " and " << NumTo-1 << " other values\n";
724 for (unsigned i = 0, e = NumTo; i != e; ++i)
725 assert((!To[i].getNode() ||
726 N->getValueType(i) == To[i].getValueType()) &&
727 "Cannot combine value to value of different type!"));
728 WorklistRemover DeadNodes(*this);
729 DAG.ReplaceAllUsesWith(N, To);
731 // Push the new nodes and any users onto the worklist
732 for (unsigned i = 0, e = NumTo; i != e; ++i) {
733 if (To[i].getNode()) {
734 AddToWorklist(To[i].getNode());
735 AddUsersToWorklist(To[i].getNode());
740 // Finally, if the node is now dead, remove it from the graph. The node
741 // may not be dead if the replacement process recursively simplified to
742 // something else needing this node.
743 if (N->use_empty()) {
744 // Nodes can be reintroduced into the worklist. Make sure we do not
745 // process a node that has been replaced.
746 removeFromWorklist(N);
748 // Finally, since the node is now dead, remove it from the graph.
751 return SDValue(N, 0);
755 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
756 // Replace all uses. If any nodes become isomorphic to other nodes and
757 // are deleted, make sure to remove them from our worklist.
758 WorklistRemover DeadNodes(*this);
759 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
761 // Push the new node and any (possibly new) users onto the worklist.
762 AddToWorklist(TLO.New.getNode());
763 AddUsersToWorklist(TLO.New.getNode());
765 // Finally, if the node is now dead, remove it from the graph. The node
766 // may not be dead if the replacement process recursively simplified to
767 // something else needing this node.
768 if (TLO.Old.getNode()->use_empty()) {
769 removeFromWorklist(TLO.Old.getNode());
771 // If the operands of this node are only used by the node, they will now
772 // be dead. Make sure to visit them first to delete dead nodes early.
773 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
774 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
775 AddToWorklist(TLO.Old.getNode()->getOperand(i).getNode());
777 DAG.DeleteNode(TLO.Old.getNode());
781 /// SimplifyDemandedBits - Check the specified integer node value to see if
782 /// it can be simplified or if things it uses can be simplified by bit
783 /// propagation. If so, return true.
784 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
785 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
786 APInt KnownZero, KnownOne;
787 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
791 AddToWorklist(Op.getNode());
793 // Replace the old value with the new one.
795 DEBUG(dbgs() << "\nReplacing.2 ";
796 TLO.Old.getNode()->dump(&DAG);
797 dbgs() << "\nWith: ";
798 TLO.New.getNode()->dump(&DAG);
801 CommitTargetLoweringOpt(TLO);
805 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
807 EVT VT = Load->getValueType(0);
808 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
810 DEBUG(dbgs() << "\nReplacing.9 ";
812 dbgs() << "\nWith: ";
813 Trunc.getNode()->dump(&DAG);
815 WorklistRemover DeadNodes(*this);
816 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
817 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
818 removeFromWorklist(Load);
819 DAG.DeleteNode(Load);
820 AddToWorklist(Trunc.getNode());
823 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
826 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
827 EVT MemVT = LD->getMemoryVT();
828 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
829 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
831 : LD->getExtensionType();
833 return DAG.getExtLoad(ExtType, dl, PVT,
834 LD->getChain(), LD->getBasePtr(),
835 MemVT, LD->getMemOperand());
838 unsigned Opc = Op.getOpcode();
841 case ISD::AssertSext:
842 return DAG.getNode(ISD::AssertSext, dl, PVT,
843 SExtPromoteOperand(Op.getOperand(0), PVT),
845 case ISD::AssertZext:
846 return DAG.getNode(ISD::AssertZext, dl, PVT,
847 ZExtPromoteOperand(Op.getOperand(0), PVT),
849 case ISD::Constant: {
851 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
852 return DAG.getNode(ExtOpc, dl, PVT, Op);
856 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
858 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
861 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
862 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
864 EVT OldVT = Op.getValueType();
866 bool Replace = false;
867 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
868 if (!NewOp.getNode())
870 AddToWorklist(NewOp.getNode());
873 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
874 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
875 DAG.getValueType(OldVT));
878 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
879 EVT OldVT = Op.getValueType();
881 bool Replace = false;
882 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
883 if (!NewOp.getNode())
885 AddToWorklist(NewOp.getNode());
888 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
889 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
892 /// PromoteIntBinOp - Promote the specified integer binary operation if the
893 /// target indicates it is beneficial. e.g. On x86, it's usually better to
894 /// promote i16 operations to i32 since i16 instructions are longer.
895 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
896 if (!LegalOperations)
899 EVT VT = Op.getValueType();
900 if (VT.isVector() || !VT.isInteger())
903 // If operation type is 'undesirable', e.g. i16 on x86, consider
905 unsigned Opc = Op.getOpcode();
906 if (TLI.isTypeDesirableForOp(Opc, VT))
910 // Consult target whether it is a good idea to promote this operation and
911 // what's the right type to promote it to.
912 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
913 assert(PVT != VT && "Don't know what type to promote to!");
915 bool Replace0 = false;
916 SDValue N0 = Op.getOperand(0);
917 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
921 bool Replace1 = false;
922 SDValue N1 = Op.getOperand(1);
927 NN1 = PromoteOperand(N1, PVT, Replace1);
932 AddToWorklist(NN0.getNode());
934 AddToWorklist(NN1.getNode());
937 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
939 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
941 DEBUG(dbgs() << "\nPromoting ";
942 Op.getNode()->dump(&DAG));
944 return DAG.getNode(ISD::TRUNCATE, dl, VT,
945 DAG.getNode(Opc, dl, PVT, NN0, NN1));
950 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
951 /// target indicates it is beneficial. e.g. On x86, it's usually better to
952 /// promote i16 operations to i32 since i16 instructions are longer.
953 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
954 if (!LegalOperations)
957 EVT VT = Op.getValueType();
958 if (VT.isVector() || !VT.isInteger())
961 // If operation type is 'undesirable', e.g. i16 on x86, consider
963 unsigned Opc = Op.getOpcode();
964 if (TLI.isTypeDesirableForOp(Opc, VT))
968 // Consult target whether it is a good idea to promote this operation and
969 // what's the right type to promote it to.
970 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
971 assert(PVT != VT && "Don't know what type to promote to!");
973 bool Replace = false;
974 SDValue N0 = Op.getOperand(0);
976 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
977 else if (Opc == ISD::SRL)
978 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
980 N0 = PromoteOperand(N0, PVT, Replace);
984 AddToWorklist(N0.getNode());
986 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
988 DEBUG(dbgs() << "\nPromoting ";
989 Op.getNode()->dump(&DAG));
991 return DAG.getNode(ISD::TRUNCATE, dl, VT,
992 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
997 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
998 if (!LegalOperations)
1001 EVT VT = Op.getValueType();
1002 if (VT.isVector() || !VT.isInteger())
1005 // If operation type is 'undesirable', e.g. i16 on x86, consider
1007 unsigned Opc = Op.getOpcode();
1008 if (TLI.isTypeDesirableForOp(Opc, VT))
1012 // Consult target whether it is a good idea to promote this operation and
1013 // what's the right type to promote it to.
1014 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1015 assert(PVT != VT && "Don't know what type to promote to!");
1016 // fold (aext (aext x)) -> (aext x)
1017 // fold (aext (zext x)) -> (zext x)
1018 // fold (aext (sext x)) -> (sext x)
1019 DEBUG(dbgs() << "\nPromoting ";
1020 Op.getNode()->dump(&DAG));
1021 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1026 bool DAGCombiner::PromoteLoad(SDValue Op) {
1027 if (!LegalOperations)
1030 EVT VT = Op.getValueType();
1031 if (VT.isVector() || !VT.isInteger())
1034 // If operation type is 'undesirable', e.g. i16 on x86, consider
1036 unsigned Opc = Op.getOpcode();
1037 if (TLI.isTypeDesirableForOp(Opc, VT))
1041 // Consult target whether it is a good idea to promote this operation and
1042 // what's the right type to promote it to.
1043 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1044 assert(PVT != VT && "Don't know what type to promote to!");
1047 SDNode *N = Op.getNode();
1048 LoadSDNode *LD = cast<LoadSDNode>(N);
1049 EVT MemVT = LD->getMemoryVT();
1050 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1051 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1053 : LD->getExtensionType();
1054 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1055 LD->getChain(), LD->getBasePtr(),
1056 MemVT, LD->getMemOperand());
1057 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1059 DEBUG(dbgs() << "\nPromoting ";
1062 Result.getNode()->dump(&DAG);
1064 WorklistRemover DeadNodes(*this);
1065 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1066 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1067 removeFromWorklist(N);
1069 AddToWorklist(Result.getNode());
1076 //===----------------------------------------------------------------------===//
1077 // Main DAG Combiner implementation
1078 //===----------------------------------------------------------------------===//
1080 void DAGCombiner::Run(CombineLevel AtLevel) {
1081 // set the instance variables, so that the various visit routines may use it.
1083 LegalOperations = Level >= AfterLegalizeVectorOps;
1084 LegalTypes = Level >= AfterLegalizeTypes;
1086 // Add all the dag nodes to the worklist.
1087 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1088 E = DAG.allnodes_end(); I != E; ++I)
1091 // Create a dummy node (which is not added to allnodes), that adds a reference
1092 // to the root node, preventing it from being deleted, and tracking any
1093 // changes of the root.
1094 HandleSDNode Dummy(DAG.getRoot());
1096 // The root of the dag may dangle to deleted nodes until the dag combiner is
1097 // done. Set it to null to avoid confusion.
1098 DAG.setRoot(SDValue());
1100 // while the worklist isn't empty, find a node and
1101 // try and combine it.
1102 while (!WorklistContents.empty()) {
1104 // The WorklistOrder holds the SDNodes in order, but it may contain
1106 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1107 // worklist *should* contain, and check the node we want to visit is should
1108 // actually be visited.
1110 N = WorklistOrder.pop_back_val();
1111 } while (!WorklistContents.erase(N));
1113 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1114 // N is deleted from the DAG, since they too may now be dead or may have a
1115 // reduced number of uses, allowing other xforms.
1116 if (N->use_empty()) {
1117 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1118 AddToWorklist(N->getOperand(i).getNode());
1124 SDValue RV = combine(N);
1131 // If we get back the same node we passed in, rather than a new node or
1132 // zero, we know that the node must have defined multiple values and
1133 // CombineTo was used. Since CombineTo takes care of the worklist
1134 // mechanics for us, we have no work to do in this case.
1135 if (RV.getNode() == N)
1138 assert(N->getOpcode() != ISD::DELETED_NODE &&
1139 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1140 "Node was deleted but visit returned new node!");
1142 DEBUG(dbgs() << "\nReplacing.3 ";
1144 dbgs() << "\nWith: ";
1145 RV.getNode()->dump(&DAG);
1148 // Transfer debug value.
1149 DAG.TransferDbgValues(SDValue(N, 0), RV);
1150 WorklistRemover DeadNodes(*this);
1151 if (N->getNumValues() == RV.getNode()->getNumValues())
1152 DAG.ReplaceAllUsesWith(N, RV.getNode());
1154 assert(N->getValueType(0) == RV.getValueType() &&
1155 N->getNumValues() == 1 && "Type mismatch");
1157 DAG.ReplaceAllUsesWith(N, &OpV);
1160 // Push the new node and any users onto the worklist
1161 AddToWorklist(RV.getNode());
1162 AddUsersToWorklist(RV.getNode());
1164 // Add any uses of the old node to the worklist in case this node is the
1165 // last one that uses them. They may become dead after this node is
1167 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1168 AddToWorklist(N->getOperand(i).getNode());
1170 // Finally, if the node is now dead, remove it from the graph. The node
1171 // may not be dead if the replacement process recursively simplified to
1172 // something else needing this node.
1173 if (N->use_empty()) {
1174 // Nodes can be reintroduced into the worklist. Make sure we do not
1175 // process a node that has been replaced.
1176 removeFromWorklist(N);
1178 // Finally, since the node is now dead, remove it from the graph.
1183 // If the root changed (e.g. it was a dead load, update the root).
1184 DAG.setRoot(Dummy.getValue());
1185 DAG.RemoveDeadNodes();
1188 SDValue DAGCombiner::visit(SDNode *N) {
1189 switch (N->getOpcode()) {
1191 case ISD::TokenFactor: return visitTokenFactor(N);
1192 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1193 case ISD::ADD: return visitADD(N);
1194 case ISD::SUB: return visitSUB(N);
1195 case ISD::ADDC: return visitADDC(N);
1196 case ISD::SUBC: return visitSUBC(N);
1197 case ISD::ADDE: return visitADDE(N);
1198 case ISD::SUBE: return visitSUBE(N);
1199 case ISD::MUL: return visitMUL(N);
1200 case ISD::SDIV: return visitSDIV(N);
1201 case ISD::UDIV: return visitUDIV(N);
1202 case ISD::SREM: return visitSREM(N);
1203 case ISD::UREM: return visitUREM(N);
1204 case ISD::MULHU: return visitMULHU(N);
1205 case ISD::MULHS: return visitMULHS(N);
1206 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1207 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1208 case ISD::SMULO: return visitSMULO(N);
1209 case ISD::UMULO: return visitUMULO(N);
1210 case ISD::SDIVREM: return visitSDIVREM(N);
1211 case ISD::UDIVREM: return visitUDIVREM(N);
1212 case ISD::AND: return visitAND(N);
1213 case ISD::OR: return visitOR(N);
1214 case ISD::XOR: return visitXOR(N);
1215 case ISD::SHL: return visitSHL(N);
1216 case ISD::SRA: return visitSRA(N);
1217 case ISD::SRL: return visitSRL(N);
1219 case ISD::ROTL: return visitRotate(N);
1220 case ISD::CTLZ: return visitCTLZ(N);
1221 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1222 case ISD::CTTZ: return visitCTTZ(N);
1223 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1224 case ISD::CTPOP: return visitCTPOP(N);
1225 case ISD::SELECT: return visitSELECT(N);
1226 case ISD::VSELECT: return visitVSELECT(N);
1227 case ISD::SELECT_CC: return visitSELECT_CC(N);
1228 case ISD::SETCC: return visitSETCC(N);
1229 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1230 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1231 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1232 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1233 case ISD::TRUNCATE: return visitTRUNCATE(N);
1234 case ISD::BITCAST: return visitBITCAST(N);
1235 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1236 case ISD::FADD: return visitFADD(N);
1237 case ISD::FSUB: return visitFSUB(N);
1238 case ISD::FMUL: return visitFMUL(N);
1239 case ISD::FMA: return visitFMA(N);
1240 case ISD::FDIV: return visitFDIV(N);
1241 case ISD::FREM: return visitFREM(N);
1242 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1243 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1244 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1245 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1246 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1247 case ISD::FP_ROUND: return visitFP_ROUND(N);
1248 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1249 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1250 case ISD::FNEG: return visitFNEG(N);
1251 case ISD::FABS: return visitFABS(N);
1252 case ISD::FFLOOR: return visitFFLOOR(N);
1253 case ISD::FCEIL: return visitFCEIL(N);
1254 case ISD::FTRUNC: return visitFTRUNC(N);
1255 case ISD::BRCOND: return visitBRCOND(N);
1256 case ISD::BR_CC: return visitBR_CC(N);
1257 case ISD::LOAD: return visitLOAD(N);
1258 case ISD::STORE: return visitSTORE(N);
1259 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1260 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1261 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1262 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1263 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1264 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1265 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1270 SDValue DAGCombiner::combine(SDNode *N) {
1271 SDValue RV = visit(N);
1273 // If nothing happened, try a target-specific DAG combine.
1274 if (!RV.getNode()) {
1275 assert(N->getOpcode() != ISD::DELETED_NODE &&
1276 "Node was deleted but visit returned NULL!");
1278 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1279 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1281 // Expose the DAG combiner to the target combiner impls.
1282 TargetLowering::DAGCombinerInfo
1283 DagCombineInfo(DAG, Level, false, this);
1285 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1289 // If nothing happened still, try promoting the operation.
1290 if (!RV.getNode()) {
1291 switch (N->getOpcode()) {
1299 RV = PromoteIntBinOp(SDValue(N, 0));
1304 RV = PromoteIntShiftOp(SDValue(N, 0));
1306 case ISD::SIGN_EXTEND:
1307 case ISD::ZERO_EXTEND:
1308 case ISD::ANY_EXTEND:
1309 RV = PromoteExtend(SDValue(N, 0));
1312 if (PromoteLoad(SDValue(N, 0)))
1318 // If N is a commutative binary node, try commuting it to enable more
1320 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1321 N->getNumValues() == 1) {
1322 SDValue N0 = N->getOperand(0);
1323 SDValue N1 = N->getOperand(1);
1325 // Constant operands are canonicalized to RHS.
1326 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1327 SDValue Ops[] = {N1, N0};
1329 if (const BinaryWithFlagsSDNode *BinNode =
1330 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1331 CSENode = DAG.getNodeIfExists(
1332 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1333 BinNode->hasNoSignedWrap(), BinNode->isExact());
1335 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1338 return SDValue(CSENode, 0);
1345 /// getInputChainForNode - Given a node, return its input chain if it has one,
1346 /// otherwise return a null sd operand.
1347 static SDValue getInputChainForNode(SDNode *N) {
1348 if (unsigned NumOps = N->getNumOperands()) {
1349 if (N->getOperand(0).getValueType() == MVT::Other)
1350 return N->getOperand(0);
1351 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1352 return N->getOperand(NumOps-1);
1353 for (unsigned i = 1; i < NumOps-1; ++i)
1354 if (N->getOperand(i).getValueType() == MVT::Other)
1355 return N->getOperand(i);
1360 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1361 // If N has two operands, where one has an input chain equal to the other,
1362 // the 'other' chain is redundant.
1363 if (N->getNumOperands() == 2) {
1364 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1365 return N->getOperand(0);
1366 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1367 return N->getOperand(1);
1370 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1371 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1372 SmallPtrSet<SDNode*, 16> SeenOps;
1373 bool Changed = false; // If we should replace this token factor.
1375 // Start out with this token factor.
1378 // Iterate through token factors. The TFs grows when new token factors are
1380 for (unsigned i = 0; i < TFs.size(); ++i) {
1381 SDNode *TF = TFs[i];
1383 // Check each of the operands.
1384 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1385 SDValue Op = TF->getOperand(i);
1387 switch (Op.getOpcode()) {
1388 case ISD::EntryToken:
1389 // Entry tokens don't need to be added to the list. They are
1394 case ISD::TokenFactor:
1395 if (Op.hasOneUse() &&
1396 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1397 // Queue up for processing.
1398 TFs.push_back(Op.getNode());
1399 // Clean up in case the token factor is removed.
1400 AddToWorklist(Op.getNode());
1407 // Only add if it isn't already in the list.
1408 if (SeenOps.insert(Op.getNode()))
1419 // If we've change things around then replace token factor.
1422 // The entry token is the only possible outcome.
1423 Result = DAG.getEntryNode();
1425 // New and improved token factor.
1426 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1429 // Don't add users to work list.
1430 return CombineTo(N, Result, false);
1436 /// MERGE_VALUES can always be eliminated.
1437 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1438 WorklistRemover DeadNodes(*this);
1439 // Replacing results may cause a different MERGE_VALUES to suddenly
1440 // be CSE'd with N, and carry its uses with it. Iterate until no
1441 // uses remain, to ensure that the node can be safely deleted.
1442 // First add the users of this node to the work list so that they
1443 // can be tried again once they have new operands.
1444 AddUsersToWorklist(N);
1446 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1447 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1448 } while (!N->use_empty());
1449 removeFromWorklist(N);
1451 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1455 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1456 SelectionDAG &DAG) {
1457 EVT VT = N0.getValueType();
1458 SDValue N00 = N0.getOperand(0);
1459 SDValue N01 = N0.getOperand(1);
1460 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1462 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1463 isa<ConstantSDNode>(N00.getOperand(1))) {
1464 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1465 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1466 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1467 N00.getOperand(0), N01),
1468 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1469 N00.getOperand(1), N01));
1470 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1476 SDValue DAGCombiner::visitADD(SDNode *N) {
1477 SDValue N0 = N->getOperand(0);
1478 SDValue N1 = N->getOperand(1);
1479 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1480 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1481 EVT VT = N0.getValueType();
1484 if (VT.isVector()) {
1485 SDValue FoldedVOp = SimplifyVBinOp(N);
1486 if (FoldedVOp.getNode()) return FoldedVOp;
1488 // fold (add x, 0) -> x, vector edition
1489 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1491 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1495 // fold (add x, undef) -> undef
1496 if (N0.getOpcode() == ISD::UNDEF)
1498 if (N1.getOpcode() == ISD::UNDEF)
1500 // fold (add c1, c2) -> c1+c2
1502 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1503 // canonicalize constant to RHS
1505 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1506 // fold (add x, 0) -> x
1507 if (N1C && N1C->isNullValue())
1509 // fold (add Sym, c) -> Sym+c
1510 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1511 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1512 GA->getOpcode() == ISD::GlobalAddress)
1513 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1515 (uint64_t)N1C->getSExtValue());
1516 // fold ((c1-A)+c2) -> (c1+c2)-A
1517 if (N1C && N0.getOpcode() == ISD::SUB)
1518 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1519 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1520 DAG.getConstant(N1C->getAPIntValue()+
1521 N0C->getAPIntValue(), VT),
1524 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1527 // fold ((0-A) + B) -> B-A
1528 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1529 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1530 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1531 // fold (A + (0-B)) -> A-B
1532 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1533 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1534 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1535 // fold (A+(B-A)) -> B
1536 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1537 return N1.getOperand(0);
1538 // fold ((B-A)+A) -> B
1539 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1540 return N0.getOperand(0);
1541 // fold (A+(B-(A+C))) to (B-C)
1542 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1543 N0 == N1.getOperand(1).getOperand(0))
1544 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1545 N1.getOperand(1).getOperand(1));
1546 // fold (A+(B-(C+A))) to (B-C)
1547 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1548 N0 == N1.getOperand(1).getOperand(1))
1549 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1550 N1.getOperand(1).getOperand(0));
1551 // fold (A+((B-A)+or-C)) to (B+or-C)
1552 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1553 N1.getOperand(0).getOpcode() == ISD::SUB &&
1554 N0 == N1.getOperand(0).getOperand(1))
1555 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1556 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1558 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1559 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1560 SDValue N00 = N0.getOperand(0);
1561 SDValue N01 = N0.getOperand(1);
1562 SDValue N10 = N1.getOperand(0);
1563 SDValue N11 = N1.getOperand(1);
1565 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1566 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1567 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1568 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1571 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1572 return SDValue(N, 0);
1574 // fold (a+b) -> (a|b) iff a and b share no bits.
1575 if (VT.isInteger() && !VT.isVector()) {
1576 APInt LHSZero, LHSOne;
1577 APInt RHSZero, RHSOne;
1578 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1580 if (LHSZero.getBoolValue()) {
1581 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1583 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1584 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1585 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1586 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1587 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1592 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1593 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1594 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1595 if (Result.getNode()) return Result;
1597 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1598 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1599 if (Result.getNode()) return Result;
1602 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1603 if (N1.getOpcode() == ISD::SHL &&
1604 N1.getOperand(0).getOpcode() == ISD::SUB)
1605 if (ConstantSDNode *C =
1606 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1607 if (C->getAPIntValue() == 0)
1608 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1609 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1610 N1.getOperand(0).getOperand(1),
1612 if (N0.getOpcode() == ISD::SHL &&
1613 N0.getOperand(0).getOpcode() == ISD::SUB)
1614 if (ConstantSDNode *C =
1615 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1616 if (C->getAPIntValue() == 0)
1617 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1618 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1619 N0.getOperand(0).getOperand(1),
1622 if (N1.getOpcode() == ISD::AND) {
1623 SDValue AndOp0 = N1.getOperand(0);
1624 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1625 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1626 unsigned DestBits = VT.getScalarType().getSizeInBits();
1628 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1629 // and similar xforms where the inner op is either ~0 or 0.
1630 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1632 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1636 // add (sext i1), X -> sub X, (zext i1)
1637 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1638 N0.getOperand(0).getValueType() == MVT::i1 &&
1639 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1641 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1642 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1648 SDValue DAGCombiner::visitADDC(SDNode *N) {
1649 SDValue N0 = N->getOperand(0);
1650 SDValue N1 = N->getOperand(1);
1651 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1652 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1653 EVT VT = N0.getValueType();
1655 // If the flag result is dead, turn this into an ADD.
1656 if (!N->hasAnyUseOfValue(1))
1657 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1658 DAG.getNode(ISD::CARRY_FALSE,
1659 SDLoc(N), MVT::Glue));
1661 // canonicalize constant to RHS.
1663 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1665 // fold (addc x, 0) -> x + no carry out
1666 if (N1C && N1C->isNullValue())
1667 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1668 SDLoc(N), MVT::Glue));
1670 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1671 APInt LHSZero, LHSOne;
1672 APInt RHSZero, RHSOne;
1673 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1675 if (LHSZero.getBoolValue()) {
1676 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1678 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1679 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1680 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1681 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1682 DAG.getNode(ISD::CARRY_FALSE,
1683 SDLoc(N), MVT::Glue));
1689 SDValue DAGCombiner::visitADDE(SDNode *N) {
1690 SDValue N0 = N->getOperand(0);
1691 SDValue N1 = N->getOperand(1);
1692 SDValue CarryIn = N->getOperand(2);
1693 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1694 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1696 // canonicalize constant to RHS
1698 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1701 // fold (adde x, y, false) -> (addc x, y)
1702 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1703 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1708 // Since it may not be valid to emit a fold to zero for vector initializers
1709 // check if we can before folding.
1710 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1712 bool LegalOperations, bool LegalTypes) {
1714 return DAG.getConstant(0, VT);
1715 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1716 return DAG.getConstant(0, VT);
1720 SDValue DAGCombiner::visitSUB(SDNode *N) {
1721 SDValue N0 = N->getOperand(0);
1722 SDValue N1 = N->getOperand(1);
1723 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1724 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1725 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1726 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1727 EVT VT = N0.getValueType();
1730 if (VT.isVector()) {
1731 SDValue FoldedVOp = SimplifyVBinOp(N);
1732 if (FoldedVOp.getNode()) return FoldedVOp;
1734 // fold (sub x, 0) -> x, vector edition
1735 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1739 // fold (sub x, x) -> 0
1740 // FIXME: Refactor this and xor and other similar operations together.
1742 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1743 // fold (sub c1, c2) -> c1-c2
1745 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1746 // fold (sub x, c) -> (add x, -c)
1748 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1749 DAG.getConstant(-N1C->getAPIntValue(), VT));
1750 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1751 if (N0C && N0C->isAllOnesValue())
1752 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1753 // fold A-(A-B) -> B
1754 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1755 return N1.getOperand(1);
1756 // fold (A+B)-A -> B
1757 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1758 return N0.getOperand(1);
1759 // fold (A+B)-B -> A
1760 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1761 return N0.getOperand(0);
1762 // fold C2-(A+C1) -> (C2-C1)-A
1763 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1764 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1766 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1769 // fold ((A+(B+or-C))-B) -> A+or-C
1770 if (N0.getOpcode() == ISD::ADD &&
1771 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1772 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1773 N0.getOperand(1).getOperand(0) == N1)
1774 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1775 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1776 // fold ((A+(C+B))-B) -> A+C
1777 if (N0.getOpcode() == ISD::ADD &&
1778 N0.getOperand(1).getOpcode() == ISD::ADD &&
1779 N0.getOperand(1).getOperand(1) == N1)
1780 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1781 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1782 // fold ((A-(B-C))-C) -> A-B
1783 if (N0.getOpcode() == ISD::SUB &&
1784 N0.getOperand(1).getOpcode() == ISD::SUB &&
1785 N0.getOperand(1).getOperand(1) == N1)
1786 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1787 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1789 // If either operand of a sub is undef, the result is undef
1790 if (N0.getOpcode() == ISD::UNDEF)
1792 if (N1.getOpcode() == ISD::UNDEF)
1795 // If the relocation model supports it, consider symbol offsets.
1796 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1797 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1798 // fold (sub Sym, c) -> Sym-c
1799 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1800 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1802 (uint64_t)N1C->getSExtValue());
1803 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1804 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1805 if (GA->getGlobal() == GB->getGlobal())
1806 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1813 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1814 SDValue N0 = N->getOperand(0);
1815 SDValue N1 = N->getOperand(1);
1816 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1817 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1818 EVT VT = N0.getValueType();
1820 // If the flag result is dead, turn this into an SUB.
1821 if (!N->hasAnyUseOfValue(1))
1822 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1823 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1826 // fold (subc x, x) -> 0 + no borrow
1828 return CombineTo(N, DAG.getConstant(0, VT),
1829 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1832 // fold (subc x, 0) -> x + no borrow
1833 if (N1C && N1C->isNullValue())
1834 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1837 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1838 if (N0C && N0C->isAllOnesValue())
1839 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1840 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1846 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1847 SDValue N0 = N->getOperand(0);
1848 SDValue N1 = N->getOperand(1);
1849 SDValue CarryIn = N->getOperand(2);
1851 // fold (sube x, y, false) -> (subc x, y)
1852 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1853 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1858 SDValue DAGCombiner::visitMUL(SDNode *N) {
1859 SDValue N0 = N->getOperand(0);
1860 SDValue N1 = N->getOperand(1);
1861 EVT VT = N0.getValueType();
1863 // fold (mul x, undef) -> 0
1864 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1865 return DAG.getConstant(0, VT);
1867 bool N0IsConst = false;
1868 bool N1IsConst = false;
1869 APInt ConstValue0, ConstValue1;
1871 if (VT.isVector()) {
1872 SDValue FoldedVOp = SimplifyVBinOp(N);
1873 if (FoldedVOp.getNode()) return FoldedVOp;
1875 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1876 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1878 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1879 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1881 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1882 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1886 // fold (mul c1, c2) -> c1*c2
1887 if (N0IsConst && N1IsConst)
1888 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1890 // canonicalize constant to RHS
1891 if (N0IsConst && !N1IsConst)
1892 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1893 // fold (mul x, 0) -> 0
1894 if (N1IsConst && ConstValue1 == 0)
1896 // We require a splat of the entire scalar bit width for non-contiguous
1899 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1900 // fold (mul x, 1) -> x
1901 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1903 // fold (mul x, -1) -> 0-x
1904 if (N1IsConst && ConstValue1.isAllOnesValue())
1905 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1906 DAG.getConstant(0, VT), N0);
1907 // fold (mul x, (1 << c)) -> x << c
1908 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1909 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1910 DAG.getConstant(ConstValue1.logBase2(),
1911 getShiftAmountTy(N0.getValueType())));
1912 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1913 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1914 unsigned Log2Val = (-ConstValue1).logBase2();
1915 // FIXME: If the input is something that is easily negated (e.g. a
1916 // single-use add), we should put the negate there.
1917 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1918 DAG.getConstant(0, VT),
1919 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1920 DAG.getConstant(Log2Val,
1921 getShiftAmountTy(N0.getValueType()))));
1925 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1926 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1927 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1928 isa<ConstantSDNode>(N0.getOperand(1)))) {
1929 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1930 N1, N0.getOperand(1));
1931 AddToWorklist(C3.getNode());
1932 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1933 N0.getOperand(0), C3);
1936 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1939 SDValue Sh(nullptr,0), Y(nullptr,0);
1940 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1941 if (N0.getOpcode() == ISD::SHL &&
1942 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1943 isa<ConstantSDNode>(N0.getOperand(1))) &&
1944 N0.getNode()->hasOneUse()) {
1946 } else if (N1.getOpcode() == ISD::SHL &&
1947 isa<ConstantSDNode>(N1.getOperand(1)) &&
1948 N1.getNode()->hasOneUse()) {
1953 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1954 Sh.getOperand(0), Y);
1955 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1956 Mul, Sh.getOperand(1));
1960 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1961 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1962 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1963 isa<ConstantSDNode>(N0.getOperand(1))))
1964 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1965 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1966 N0.getOperand(0), N1),
1967 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1968 N0.getOperand(1), N1));
1971 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1978 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1979 SDValue N0 = N->getOperand(0);
1980 SDValue N1 = N->getOperand(1);
1981 ConstantSDNode *N0C = isConstOrConstSplat(N0);
1982 ConstantSDNode *N1C = isConstOrConstSplat(N1);
1983 EVT VT = N->getValueType(0);
1986 if (VT.isVector()) {
1987 SDValue FoldedVOp = SimplifyVBinOp(N);
1988 if (FoldedVOp.getNode()) return FoldedVOp;
1991 // fold (sdiv c1, c2) -> c1/c2
1992 if (N0C && N1C && !N1C->isNullValue())
1993 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1994 // fold (sdiv X, 1) -> X
1995 if (N1C && N1C->getAPIntValue() == 1LL)
1997 // fold (sdiv X, -1) -> 0-X
1998 if (N1C && N1C->isAllOnesValue())
1999 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2000 DAG.getConstant(0, VT), N0);
2001 // If we know the sign bits of both operands are zero, strength reduce to a
2002 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2003 if (!VT.isVector()) {
2004 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2005 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2009 // fold (sdiv X, pow2) -> simple ops after legalize
2010 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2011 (-N1C->getAPIntValue()).isPowerOf2())) {
2012 // If dividing by powers of two is cheap, then don't perform the following
2014 if (TLI.isPow2DivCheap())
2017 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2019 // Splat the sign bit into the register
2021 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2022 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2023 getShiftAmountTy(N0.getValueType())));
2024 AddToWorklist(SGN.getNode());
2026 // Add (N0 < 0) ? abs2 - 1 : 0;
2028 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2029 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2030 getShiftAmountTy(SGN.getValueType())));
2031 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2032 AddToWorklist(SRL.getNode());
2033 AddToWorklist(ADD.getNode()); // Divide by pow2
2034 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2035 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2037 // If we're dividing by a positive value, we're done. Otherwise, we must
2038 // negate the result.
2039 if (N1C->getAPIntValue().isNonNegative())
2042 AddToWorklist(SRA.getNode());
2043 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2046 // if integer divide is expensive and we satisfy the requirements, emit an
2047 // alternate sequence.
2048 if (N1C && !TLI.isIntDivCheap()) {
2049 SDValue Op = BuildSDIV(N);
2050 if (Op.getNode()) return Op;
2054 if (N0.getOpcode() == ISD::UNDEF)
2055 return DAG.getConstant(0, VT);
2056 // X / undef -> undef
2057 if (N1.getOpcode() == ISD::UNDEF)
2063 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2064 SDValue N0 = N->getOperand(0);
2065 SDValue N1 = N->getOperand(1);
2066 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2067 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2068 EVT VT = N->getValueType(0);
2071 if (VT.isVector()) {
2072 SDValue FoldedVOp = SimplifyVBinOp(N);
2073 if (FoldedVOp.getNode()) return FoldedVOp;
2076 // fold (udiv c1, c2) -> c1/c2
2077 if (N0C && N1C && !N1C->isNullValue())
2078 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2079 // fold (udiv x, (1 << c)) -> x >>u c
2080 if (N1C && N1C->getAPIntValue().isPowerOf2())
2081 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2082 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2083 getShiftAmountTy(N0.getValueType())));
2084 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2085 if (N1.getOpcode() == ISD::SHL) {
2086 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2087 if (SHC->getAPIntValue().isPowerOf2()) {
2088 EVT ADDVT = N1.getOperand(1).getValueType();
2089 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2091 DAG.getConstant(SHC->getAPIntValue()
2094 AddToWorklist(Add.getNode());
2095 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2099 // fold (udiv x, c) -> alternate
2100 if (N1C && !TLI.isIntDivCheap()) {
2101 SDValue Op = BuildUDIV(N);
2102 if (Op.getNode()) return Op;
2106 if (N0.getOpcode() == ISD::UNDEF)
2107 return DAG.getConstant(0, VT);
2108 // X / undef -> undef
2109 if (N1.getOpcode() == ISD::UNDEF)
2115 SDValue DAGCombiner::visitSREM(SDNode *N) {
2116 SDValue N0 = N->getOperand(0);
2117 SDValue N1 = N->getOperand(1);
2118 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2119 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2120 EVT VT = N->getValueType(0);
2122 // fold (srem c1, c2) -> c1%c2
2123 if (N0C && N1C && !N1C->isNullValue())
2124 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2125 // If we know the sign bits of both operands are zero, strength reduce to a
2126 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2127 if (!VT.isVector()) {
2128 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2129 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2132 // If X/C can be simplified by the division-by-constant logic, lower
2133 // X%C to the equivalent of X-X/C*C.
2134 if (N1C && !N1C->isNullValue()) {
2135 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2136 AddToWorklist(Div.getNode());
2137 SDValue OptimizedDiv = combine(Div.getNode());
2138 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2139 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2141 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2142 AddToWorklist(Mul.getNode());
2148 if (N0.getOpcode() == ISD::UNDEF)
2149 return DAG.getConstant(0, VT);
2150 // X % undef -> undef
2151 if (N1.getOpcode() == ISD::UNDEF)
2157 SDValue DAGCombiner::visitUREM(SDNode *N) {
2158 SDValue N0 = N->getOperand(0);
2159 SDValue N1 = N->getOperand(1);
2160 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2161 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2162 EVT VT = N->getValueType(0);
2164 // fold (urem c1, c2) -> c1%c2
2165 if (N0C && N1C && !N1C->isNullValue())
2166 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2167 // fold (urem x, pow2) -> (and x, pow2-1)
2168 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2169 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2170 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2171 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2172 if (N1.getOpcode() == ISD::SHL) {
2173 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2174 if (SHC->getAPIntValue().isPowerOf2()) {
2176 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2177 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2179 AddToWorklist(Add.getNode());
2180 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2185 // If X/C can be simplified by the division-by-constant logic, lower
2186 // X%C to the equivalent of X-X/C*C.
2187 if (N1C && !N1C->isNullValue()) {
2188 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2189 AddToWorklist(Div.getNode());
2190 SDValue OptimizedDiv = combine(Div.getNode());
2191 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2192 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2194 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2195 AddToWorklist(Mul.getNode());
2201 if (N0.getOpcode() == ISD::UNDEF)
2202 return DAG.getConstant(0, VT);
2203 // X % undef -> undef
2204 if (N1.getOpcode() == ISD::UNDEF)
2210 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2211 SDValue N0 = N->getOperand(0);
2212 SDValue N1 = N->getOperand(1);
2213 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2214 EVT VT = N->getValueType(0);
2217 // fold (mulhs x, 0) -> 0
2218 if (N1C && N1C->isNullValue())
2220 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2221 if (N1C && N1C->getAPIntValue() == 1)
2222 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2223 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2224 getShiftAmountTy(N0.getValueType())));
2225 // fold (mulhs x, undef) -> 0
2226 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2227 return DAG.getConstant(0, VT);
2229 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2231 if (VT.isSimple() && !VT.isVector()) {
2232 MVT Simple = VT.getSimpleVT();
2233 unsigned SimpleSize = Simple.getSizeInBits();
2234 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2235 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2236 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2237 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2238 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2239 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2240 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2241 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2248 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2249 SDValue N0 = N->getOperand(0);
2250 SDValue N1 = N->getOperand(1);
2251 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2252 EVT VT = N->getValueType(0);
2255 // fold (mulhu x, 0) -> 0
2256 if (N1C && N1C->isNullValue())
2258 // fold (mulhu x, 1) -> 0
2259 if (N1C && N1C->getAPIntValue() == 1)
2260 return DAG.getConstant(0, N0.getValueType());
2261 // fold (mulhu x, undef) -> 0
2262 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2263 return DAG.getConstant(0, VT);
2265 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2267 if (VT.isSimple() && !VT.isVector()) {
2268 MVT Simple = VT.getSimpleVT();
2269 unsigned SimpleSize = Simple.getSizeInBits();
2270 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2271 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2272 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2273 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2274 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2275 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2276 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2277 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2284 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2285 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2286 /// that are being performed. Return true if a simplification was made.
2288 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2290 // If the high half is not needed, just compute the low half.
2291 bool HiExists = N->hasAnyUseOfValue(1);
2293 (!LegalOperations ||
2294 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2295 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2296 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2297 return CombineTo(N, Res, Res);
2300 // If the low half is not needed, just compute the high half.
2301 bool LoExists = N->hasAnyUseOfValue(0);
2303 (!LegalOperations ||
2304 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2305 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2306 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2307 return CombineTo(N, Res, Res);
2310 // If both halves are used, return as it is.
2311 if (LoExists && HiExists)
2314 // If the two computed results can be simplified separately, separate them.
2316 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2317 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2318 AddToWorklist(Lo.getNode());
2319 SDValue LoOpt = combine(Lo.getNode());
2320 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2321 (!LegalOperations ||
2322 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2323 return CombineTo(N, LoOpt, LoOpt);
2327 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2328 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2329 AddToWorklist(Hi.getNode());
2330 SDValue HiOpt = combine(Hi.getNode());
2331 if (HiOpt.getNode() && HiOpt != Hi &&
2332 (!LegalOperations ||
2333 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2334 return CombineTo(N, HiOpt, HiOpt);
2340 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2341 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2342 if (Res.getNode()) return Res;
2344 EVT VT = N->getValueType(0);
2347 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2349 if (VT.isSimple() && !VT.isVector()) {
2350 MVT Simple = VT.getSimpleVT();
2351 unsigned SimpleSize = Simple.getSizeInBits();
2352 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2353 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2354 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2355 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2356 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2357 // Compute the high part as N1.
2358 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2359 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2360 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2361 // Compute the low part as N0.
2362 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2363 return CombineTo(N, Lo, Hi);
2370 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2371 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2372 if (Res.getNode()) return Res;
2374 EVT VT = N->getValueType(0);
2377 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2379 if (VT.isSimple() && !VT.isVector()) {
2380 MVT Simple = VT.getSimpleVT();
2381 unsigned SimpleSize = Simple.getSizeInBits();
2382 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2383 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2384 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2385 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2386 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2387 // Compute the high part as N1.
2388 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2389 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2390 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2391 // Compute the low part as N0.
2392 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2393 return CombineTo(N, Lo, Hi);
2400 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2401 // (smulo x, 2) -> (saddo x, x)
2402 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2403 if (C2->getAPIntValue() == 2)
2404 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2405 N->getOperand(0), N->getOperand(0));
2410 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2411 // (umulo x, 2) -> (uaddo x, x)
2412 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2413 if (C2->getAPIntValue() == 2)
2414 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2415 N->getOperand(0), N->getOperand(0));
2420 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2421 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2422 if (Res.getNode()) return Res;
2427 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2428 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2429 if (Res.getNode()) return Res;
2434 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2435 /// two operands of the same opcode, try to simplify it.
2436 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2437 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2438 EVT VT = N0.getValueType();
2439 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2441 // Bail early if none of these transforms apply.
2442 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2444 // For each of OP in AND/OR/XOR:
2445 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2446 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2447 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2448 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2450 // do not sink logical op inside of a vector extend, since it may combine
2452 EVT Op0VT = N0.getOperand(0).getValueType();
2453 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2454 N0.getOpcode() == ISD::SIGN_EXTEND ||
2455 // Avoid infinite looping with PromoteIntBinOp.
2456 (N0.getOpcode() == ISD::ANY_EXTEND &&
2457 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2458 (N0.getOpcode() == ISD::TRUNCATE &&
2459 (!TLI.isZExtFree(VT, Op0VT) ||
2460 !TLI.isTruncateFree(Op0VT, VT)) &&
2461 TLI.isTypeLegal(Op0VT))) &&
2463 Op0VT == N1.getOperand(0).getValueType() &&
2464 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2465 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2466 N0.getOperand(0).getValueType(),
2467 N0.getOperand(0), N1.getOperand(0));
2468 AddToWorklist(ORNode.getNode());
2469 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2472 // For each of OP in SHL/SRL/SRA/AND...
2473 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2474 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2475 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2476 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2477 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2478 N0.getOperand(1) == N1.getOperand(1)) {
2479 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2480 N0.getOperand(0).getValueType(),
2481 N0.getOperand(0), N1.getOperand(0));
2482 AddToWorklist(ORNode.getNode());
2483 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2484 ORNode, N0.getOperand(1));
2487 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2488 // Only perform this optimization after type legalization and before
2489 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2490 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2491 // we don't want to undo this promotion.
2492 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2494 if ((N0.getOpcode() == ISD::BITCAST ||
2495 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2496 Level == AfterLegalizeTypes) {
2497 SDValue In0 = N0.getOperand(0);
2498 SDValue In1 = N1.getOperand(0);
2499 EVT In0Ty = In0.getValueType();
2500 EVT In1Ty = In1.getValueType();
2502 // If both incoming values are integers, and the original types are the
2504 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2505 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2506 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2507 AddToWorklist(Op.getNode());
2512 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2513 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2514 // If both shuffles use the same mask, and both shuffle within a single
2515 // vector, then it is worthwhile to move the swizzle after the operation.
2516 // The type-legalizer generates this pattern when loading illegal
2517 // vector types from memory. In many cases this allows additional shuffle
2519 // There are other cases where moving the shuffle after the xor/and/or
2520 // is profitable even if shuffles don't perform a swizzle.
2521 // If both shuffles use the same mask, and both shuffles have the same first
2522 // or second operand, then it might still be profitable to move the shuffle
2523 // after the xor/and/or operation.
2524 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2525 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2526 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2528 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2529 "Inputs to shuffles are not the same type");
2531 // Check that both shuffles use the same mask. The masks are known to be of
2532 // the same length because the result vector type is the same.
2533 // Check also that shuffles have only one use to avoid introducing extra
2535 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2536 SVN0->getMask().equals(SVN1->getMask())) {
2537 SDValue ShOp = N0->getOperand(1);
2539 // Don't try to fold this node if it requires introducing a
2540 // build vector of all zeros that might be illegal at this stage.
2541 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2543 ShOp = DAG.getConstant(0, VT);
2548 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2549 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2550 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2551 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2552 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2553 N0->getOperand(0), N1->getOperand(0));
2554 AddToWorklist(NewNode.getNode());
2555 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2556 &SVN0->getMask()[0]);
2559 // Don't try to fold this node if it requires introducing a
2560 // build vector of all zeros that might be illegal at this stage.
2561 ShOp = N0->getOperand(0);
2562 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2564 ShOp = DAG.getConstant(0, VT);
2569 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2570 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2571 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2572 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2573 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2574 N0->getOperand(1), N1->getOperand(1));
2575 AddToWorklist(NewNode.getNode());
2576 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2577 &SVN0->getMask()[0]);
2585 SDValue DAGCombiner::visitAND(SDNode *N) {
2586 SDValue N0 = N->getOperand(0);
2587 SDValue N1 = N->getOperand(1);
2588 SDValue LL, LR, RL, RR, CC0, CC1;
2589 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2590 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2591 EVT VT = N1.getValueType();
2592 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2595 if (VT.isVector()) {
2596 SDValue FoldedVOp = SimplifyVBinOp(N);
2597 if (FoldedVOp.getNode()) return FoldedVOp;
2599 // fold (and x, 0) -> 0, vector edition
2600 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2602 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2605 // fold (and x, -1) -> x, vector edition
2606 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2608 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2612 // fold (and x, undef) -> 0
2613 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2614 return DAG.getConstant(0, VT);
2615 // fold (and c1, c2) -> c1&c2
2617 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2618 // canonicalize constant to RHS
2620 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2621 // fold (and x, -1) -> x
2622 if (N1C && N1C->isAllOnesValue())
2624 // if (and x, c) is known to be zero, return 0
2625 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2626 APInt::getAllOnesValue(BitWidth)))
2627 return DAG.getConstant(0, VT);
2629 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2632 // fold (and (or x, C), D) -> D if (C & D) == D
2633 if (N1C && N0.getOpcode() == ISD::OR)
2634 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2635 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2637 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2638 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2639 SDValue N0Op0 = N0.getOperand(0);
2640 APInt Mask = ~N1C->getAPIntValue();
2641 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2642 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2643 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2644 N0.getValueType(), N0Op0);
2646 // Replace uses of the AND with uses of the Zero extend node.
2649 // We actually want to replace all uses of the any_extend with the
2650 // zero_extend, to avoid duplicating things. This will later cause this
2651 // AND to be folded.
2652 CombineTo(N0.getNode(), Zext);
2653 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2656 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2657 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2658 // already be zero by virtue of the width of the base type of the load.
2660 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2662 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2663 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2664 N0.getOpcode() == ISD::LOAD) {
2665 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2666 N0 : N0.getOperand(0) );
2668 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2669 // This can be a pure constant or a vector splat, in which case we treat the
2670 // vector as a scalar and use the splat value.
2671 APInt Constant = APInt::getNullValue(1);
2672 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2673 Constant = C->getAPIntValue();
2674 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2675 APInt SplatValue, SplatUndef;
2676 unsigned SplatBitSize;
2678 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2679 SplatBitSize, HasAnyUndefs);
2681 // Undef bits can contribute to a possible optimisation if set, so
2683 SplatValue |= SplatUndef;
2685 // The splat value may be something like "0x00FFFFFF", which means 0 for
2686 // the first vector value and FF for the rest, repeating. We need a mask
2687 // that will apply equally to all members of the vector, so AND all the
2688 // lanes of the constant together.
2689 EVT VT = Vector->getValueType(0);
2690 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2692 // If the splat value has been compressed to a bitlength lower
2693 // than the size of the vector lane, we need to re-expand it to
2695 if (BitWidth > SplatBitSize)
2696 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2697 SplatBitSize < BitWidth;
2698 SplatBitSize = SplatBitSize * 2)
2699 SplatValue |= SplatValue.shl(SplatBitSize);
2701 Constant = APInt::getAllOnesValue(BitWidth);
2702 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2703 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2707 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2708 // actually legal and isn't going to get expanded, else this is a false
2710 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2711 Load->getMemoryVT());
2713 // Resize the constant to the same size as the original memory access before
2714 // extension. If it is still the AllOnesValue then this AND is completely
2717 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2720 switch (Load->getExtensionType()) {
2721 default: B = false; break;
2722 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2724 case ISD::NON_EXTLOAD: B = true; break;
2727 if (B && Constant.isAllOnesValue()) {
2728 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2729 // preserve semantics once we get rid of the AND.
2730 SDValue NewLoad(Load, 0);
2731 if (Load->getExtensionType() == ISD::EXTLOAD) {
2732 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2733 Load->getValueType(0), SDLoc(Load),
2734 Load->getChain(), Load->getBasePtr(),
2735 Load->getOffset(), Load->getMemoryVT(),
2736 Load->getMemOperand());
2737 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2738 if (Load->getNumValues() == 3) {
2739 // PRE/POST_INC loads have 3 values.
2740 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2741 NewLoad.getValue(2) };
2742 CombineTo(Load, To, 3, true);
2744 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2748 // Fold the AND away, taking care not to fold to the old load node if we
2750 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2752 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2755 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2756 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2757 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2758 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2760 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2761 LL.getValueType().isInteger()) {
2762 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2763 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2764 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2765 LR.getValueType(), LL, RL);
2766 AddToWorklist(ORNode.getNode());
2767 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2769 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2770 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2771 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2772 LR.getValueType(), LL, RL);
2773 AddToWorklist(ANDNode.getNode());
2774 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2776 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2777 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2778 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2779 LR.getValueType(), LL, RL);
2780 AddToWorklist(ORNode.getNode());
2781 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2784 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2785 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2786 Op0 == Op1 && LL.getValueType().isInteger() &&
2787 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2788 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2789 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2790 cast<ConstantSDNode>(RR)->isNullValue()))) {
2791 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2792 LL, DAG.getConstant(1, LL.getValueType()));
2793 AddToWorklist(ADDNode.getNode());
2794 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2795 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2797 // canonicalize equivalent to ll == rl
2798 if (LL == RR && LR == RL) {
2799 Op1 = ISD::getSetCCSwappedOperands(Op1);
2802 if (LL == RL && LR == RR) {
2803 bool isInteger = LL.getValueType().isInteger();
2804 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2805 if (Result != ISD::SETCC_INVALID &&
2806 (!LegalOperations ||
2807 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2808 TLI.isOperationLegal(ISD::SETCC,
2809 getSetCCResultType(N0.getSimpleValueType())))))
2810 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2815 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2816 if (N0.getOpcode() == N1.getOpcode()) {
2817 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2818 if (Tmp.getNode()) return Tmp;
2821 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2822 // fold (and (sra)) -> (and (srl)) when possible.
2823 if (!VT.isVector() &&
2824 SimplifyDemandedBits(SDValue(N, 0)))
2825 return SDValue(N, 0);
2827 // fold (zext_inreg (extload x)) -> (zextload x)
2828 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2829 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2830 EVT MemVT = LN0->getMemoryVT();
2831 // If we zero all the possible extended bits, then we can turn this into
2832 // a zextload if we are running before legalize or the operation is legal.
2833 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2834 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2835 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2836 ((!LegalOperations && !LN0->isVolatile()) ||
2837 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2838 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2839 LN0->getChain(), LN0->getBasePtr(),
2840 MemVT, LN0->getMemOperand());
2842 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2843 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2846 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2847 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2849 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2850 EVT MemVT = LN0->getMemoryVT();
2851 // If we zero all the possible extended bits, then we can turn this into
2852 // a zextload if we are running before legalize or the operation is legal.
2853 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2854 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2855 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2856 ((!LegalOperations && !LN0->isVolatile()) ||
2857 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2858 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2859 LN0->getChain(), LN0->getBasePtr(),
2860 MemVT, LN0->getMemOperand());
2862 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2863 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2867 // fold (and (load x), 255) -> (zextload x, i8)
2868 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2869 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2870 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2871 (N0.getOpcode() == ISD::ANY_EXTEND &&
2872 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2873 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2874 LoadSDNode *LN0 = HasAnyExt
2875 ? cast<LoadSDNode>(N0.getOperand(0))
2876 : cast<LoadSDNode>(N0);
2877 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2878 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2879 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2880 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2881 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2882 EVT LoadedVT = LN0->getMemoryVT();
2884 if (ExtVT == LoadedVT &&
2885 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2886 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2889 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2890 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2891 LN0->getMemOperand());
2893 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2894 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2897 // Do not change the width of a volatile load.
2898 // Do not generate loads of non-round integer types since these can
2899 // be expensive (and would be wrong if the type is not byte sized).
2900 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2901 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2902 EVT PtrType = LN0->getOperand(1).getValueType();
2904 unsigned Alignment = LN0->getAlignment();
2905 SDValue NewPtr = LN0->getBasePtr();
2907 // For big endian targets, we need to add an offset to the pointer
2908 // to load the correct bytes. For little endian systems, we merely
2909 // need to read fewer bytes from the same pointer.
2910 if (TLI.isBigEndian()) {
2911 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2912 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2913 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2914 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2915 NewPtr, DAG.getConstant(PtrOff, PtrType));
2916 Alignment = MinAlign(Alignment, PtrOff);
2919 AddToWorklist(NewPtr.getNode());
2921 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2923 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2924 LN0->getChain(), NewPtr,
2925 LN0->getPointerInfo(),
2926 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2927 Alignment, LN0->getTBAAInfo());
2929 CombineTo(LN0, Load, Load.getValue(1));
2930 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2936 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2937 VT.getSizeInBits() <= 64) {
2938 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2939 APInt ADDC = ADDI->getAPIntValue();
2940 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2941 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2942 // immediate for an add, but it is legal if its top c2 bits are set,
2943 // transform the ADD so the immediate doesn't need to be materialized
2945 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2946 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2947 SRLI->getZExtValue());
2948 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2950 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2952 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2953 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2954 CombineTo(N0.getNode(), NewAdd);
2955 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2963 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2964 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2965 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2966 N0.getOperand(1), false);
2967 if (BSwap.getNode())
2974 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2976 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2977 bool DemandHighBits) {
2978 if (!LegalOperations)
2981 EVT VT = N->getValueType(0);
2982 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2984 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2987 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2988 bool LookPassAnd0 = false;
2989 bool LookPassAnd1 = false;
2990 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2992 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2994 if (N0.getOpcode() == ISD::AND) {
2995 if (!N0.getNode()->hasOneUse())
2997 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2998 if (!N01C || N01C->getZExtValue() != 0xFF00)
3000 N0 = N0.getOperand(0);
3001 LookPassAnd0 = true;
3004 if (N1.getOpcode() == ISD::AND) {
3005 if (!N1.getNode()->hasOneUse())
3007 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3008 if (!N11C || N11C->getZExtValue() != 0xFF)
3010 N1 = N1.getOperand(0);
3011 LookPassAnd1 = true;
3014 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3016 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3018 if (!N0.getNode()->hasOneUse() ||
3019 !N1.getNode()->hasOneUse())
3022 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3023 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3026 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3029 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3030 SDValue N00 = N0->getOperand(0);
3031 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3032 if (!N00.getNode()->hasOneUse())
3034 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3035 if (!N001C || N001C->getZExtValue() != 0xFF)
3037 N00 = N00.getOperand(0);
3038 LookPassAnd0 = true;
3041 SDValue N10 = N1->getOperand(0);
3042 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3043 if (!N10.getNode()->hasOneUse())
3045 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3046 if (!N101C || N101C->getZExtValue() != 0xFF00)
3048 N10 = N10.getOperand(0);
3049 LookPassAnd1 = true;
3055 // Make sure everything beyond the low halfword gets set to zero since the SRL
3056 // 16 will clear the top bits.
3057 unsigned OpSizeInBits = VT.getSizeInBits();
3058 if (DemandHighBits && OpSizeInBits > 16) {
3059 // If the left-shift isn't masked out then the only way this is a bswap is
3060 // if all bits beyond the low 8 are 0. In that case the entire pattern
3061 // reduces to a left shift anyway: leave it for other parts of the combiner.
3065 // However, if the right shift isn't masked out then it might be because
3066 // it's not needed. See if we can spot that too.
3067 if (!LookPassAnd1 &&
3068 !DAG.MaskedValueIsZero(
3069 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3073 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3074 if (OpSizeInBits > 16)
3075 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3076 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3080 /// isBSwapHWordElement - Return true if the specified node is an element
3081 /// that makes up a 32-bit packed halfword byteswap. i.e.
3082 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3083 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3084 if (!N.getNode()->hasOneUse())
3087 unsigned Opc = N.getOpcode();
3088 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3091 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3096 switch (N1C->getZExtValue()) {
3099 case 0xFF: Num = 0; break;
3100 case 0xFF00: Num = 1; break;
3101 case 0xFF0000: Num = 2; break;
3102 case 0xFF000000: Num = 3; break;
3105 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3106 SDValue N0 = N.getOperand(0);
3107 if (Opc == ISD::AND) {
3108 if (Num == 0 || Num == 2) {
3110 // (x >> 8) & 0xff0000
3111 if (N0.getOpcode() != ISD::SRL)
3113 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3114 if (!C || C->getZExtValue() != 8)
3117 // (x << 8) & 0xff00
3118 // (x << 8) & 0xff000000
3119 if (N0.getOpcode() != ISD::SHL)
3121 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3122 if (!C || C->getZExtValue() != 8)
3125 } else if (Opc == ISD::SHL) {
3127 // (x & 0xff0000) << 8
3128 if (Num != 0 && Num != 2)
3130 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3131 if (!C || C->getZExtValue() != 8)
3133 } else { // Opc == ISD::SRL
3134 // (x & 0xff00) >> 8
3135 // (x & 0xff000000) >> 8
3136 if (Num != 1 && Num != 3)
3138 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3139 if (!C || C->getZExtValue() != 8)
3146 Parts[Num] = N0.getOperand(0).getNode();
3150 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3151 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3152 /// => (rotl (bswap x), 16)
3153 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3154 if (!LegalOperations)
3157 EVT VT = N->getValueType(0);
3160 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3163 SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3165 // (or (or (and), (and)), (or (and), (and)))
3166 // (or (or (or (and), (and)), (and)), (and))
3167 if (N0.getOpcode() != ISD::OR)
3169 SDValue N00 = N0.getOperand(0);
3170 SDValue N01 = N0.getOperand(1);
3172 if (N1.getOpcode() == ISD::OR &&
3173 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3174 // (or (or (and), (and)), (or (and), (and)))
3175 SDValue N000 = N00.getOperand(0);
3176 if (!isBSwapHWordElement(N000, Parts))
3179 SDValue N001 = N00.getOperand(1);
3180 if (!isBSwapHWordElement(N001, Parts))
3182 SDValue N010 = N01.getOperand(0);
3183 if (!isBSwapHWordElement(N010, Parts))
3185 SDValue N011 = N01.getOperand(1);
3186 if (!isBSwapHWordElement(N011, Parts))
3189 // (or (or (or (and), (and)), (and)), (and))
3190 if (!isBSwapHWordElement(N1, Parts))
3192 if (!isBSwapHWordElement(N01, Parts))
3194 if (N00.getOpcode() != ISD::OR)
3196 SDValue N000 = N00.getOperand(0);
3197 if (!isBSwapHWordElement(N000, Parts))
3199 SDValue N001 = N00.getOperand(1);
3200 if (!isBSwapHWordElement(N001, Parts))
3204 // Make sure the parts are all coming from the same node.
3205 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3208 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3209 SDValue(Parts[0],0));
3211 // Result of the bswap should be rotated by 16. If it's not legal, then
3212 // do (x << 16) | (x >> 16).
3213 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3214 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3215 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3216 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3217 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3218 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3219 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3220 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3223 SDValue DAGCombiner::visitOR(SDNode *N) {
3224 SDValue N0 = N->getOperand(0);
3225 SDValue N1 = N->getOperand(1);
3226 SDValue LL, LR, RL, RR, CC0, CC1;
3227 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3228 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3229 EVT VT = N1.getValueType();
3232 if (VT.isVector()) {
3233 SDValue FoldedVOp = SimplifyVBinOp(N);
3234 if (FoldedVOp.getNode()) return FoldedVOp;
3236 // fold (or x, 0) -> x, vector edition
3237 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3239 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3242 // fold (or x, -1) -> -1, vector edition
3243 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3245 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3248 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3249 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3250 // Do this only if the resulting shuffle is legal.
3251 if (isa<ShuffleVectorSDNode>(N0) &&
3252 isa<ShuffleVectorSDNode>(N1) &&
3253 // Avoid folding a node with illegal type.
3254 TLI.isTypeLegal(VT) &&
3255 N0->getOperand(1) == N1->getOperand(1) &&
3256 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3257 bool CanFold = true;
3258 unsigned NumElts = VT.getVectorNumElements();
3259 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3260 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3261 // We construct two shuffle masks:
3262 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3263 // and N1 as the second operand.
3264 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3265 // and N0 as the second operand.
3266 // We do this because OR is commutable and therefore there might be
3267 // two ways to fold this node into a shuffle.
3268 SmallVector<int,4> Mask1;
3269 SmallVector<int,4> Mask2;
3271 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3272 int M0 = SV0->getMaskElt(i);
3273 int M1 = SV1->getMaskElt(i);
3275 // Both shuffle indexes are undef. Propagate Undef.
3276 if (M0 < 0 && M1 < 0) {
3277 Mask1.push_back(M0);
3278 Mask2.push_back(M0);
3282 if (M0 < 0 || M1 < 0 ||
3283 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3284 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3289 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3290 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3294 // Fold this sequence only if the resulting shuffle is 'legal'.
3295 if (TLI.isShuffleMaskLegal(Mask1, VT))
3296 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3297 N1->getOperand(0), &Mask1[0]);
3298 if (TLI.isShuffleMaskLegal(Mask2, VT))
3299 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3300 N0->getOperand(0), &Mask2[0]);
3305 // fold (or x, undef) -> -1
3306 if (!LegalOperations &&
3307 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3308 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3309 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3311 // fold (or c1, c2) -> c1|c2
3313 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3314 // canonicalize constant to RHS
3316 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3317 // fold (or x, 0) -> x
3318 if (N1C && N1C->isNullValue())
3320 // fold (or x, -1) -> -1
3321 if (N1C && N1C->isAllOnesValue())
3323 // fold (or x, c) -> c iff (x & ~c) == 0
3324 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3327 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3328 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3329 if (BSwap.getNode())
3331 BSwap = MatchBSwapHWordLow(N, N0, N1);
3332 if (BSwap.getNode())
3336 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3339 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3340 // iff (c1 & c2) == 0.
3341 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3342 isa<ConstantSDNode>(N0.getOperand(1))) {
3343 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3344 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3345 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3348 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3349 DAG.getNode(ISD::OR, SDLoc(N0), VT,
3350 N0.getOperand(0), N1), COR);
3353 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3354 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3355 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3356 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3358 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3359 LL.getValueType().isInteger()) {
3360 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3361 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3362 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3363 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3364 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3365 LR.getValueType(), LL, RL);
3366 AddToWorklist(ORNode.getNode());
3367 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3369 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3370 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3371 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3372 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3373 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3374 LR.getValueType(), LL, RL);
3375 AddToWorklist(ANDNode.getNode());
3376 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3379 // canonicalize equivalent to ll == rl
3380 if (LL == RR && LR == RL) {
3381 Op1 = ISD::getSetCCSwappedOperands(Op1);
3384 if (LL == RL && LR == RR) {
3385 bool isInteger = LL.getValueType().isInteger();
3386 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3387 if (Result != ISD::SETCC_INVALID &&
3388 (!LegalOperations ||
3389 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3390 TLI.isOperationLegal(ISD::SETCC,
3391 getSetCCResultType(N0.getValueType())))))
3392 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3397 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3398 if (N0.getOpcode() == N1.getOpcode()) {
3399 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3400 if (Tmp.getNode()) return Tmp;
3403 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3404 if (N0.getOpcode() == ISD::AND &&
3405 N1.getOpcode() == ISD::AND &&
3406 N0.getOperand(1).getOpcode() == ISD::Constant &&
3407 N1.getOperand(1).getOpcode() == ISD::Constant &&
3408 // Don't increase # computations.
3409 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3410 // We can only do this xform if we know that bits from X that are set in C2
3411 // but not in C1 are already zero. Likewise for Y.
3412 const APInt &LHSMask =
3413 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3414 const APInt &RHSMask =
3415 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3417 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3418 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3419 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3420 N0.getOperand(0), N1.getOperand(0));
3421 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3422 DAG.getConstant(LHSMask | RHSMask, VT));
3426 // See if this is some rotate idiom.
3427 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3428 return SDValue(Rot, 0);
3430 // Simplify the operands using demanded-bits information.
3431 if (!VT.isVector() &&
3432 SimplifyDemandedBits(SDValue(N, 0)))
3433 return SDValue(N, 0);
3438 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3439 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3440 if (Op.getOpcode() == ISD::AND) {
3441 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3442 Mask = Op.getOperand(1);
3443 Op = Op.getOperand(0);
3449 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3457 // Return true if we can prove that, whenever Neg and Pos are both in the
3458 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3459 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3461 // (or (shift1 X, Neg), (shift2 X, Pos))
3463 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3464 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3465 // to consider shift amounts with defined behavior.
3466 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3467 // If OpSize is a power of 2 then:
3469 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3470 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3472 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3473 // for the stronger condition:
3475 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3477 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3478 // we can just replace Neg with Neg' for the rest of the function.
3480 // In other cases we check for the even stronger condition:
3482 // Neg == OpSize - Pos [B]
3484 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3485 // behavior if Pos == 0 (and consequently Neg == OpSize).
3487 // We could actually use [A] whenever OpSize is a power of 2, but the
3488 // only extra cases that it would match are those uninteresting ones
3489 // where Neg and Pos are never in range at the same time. E.g. for
3490 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3491 // as well as (sub 32, Pos), but:
3493 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3495 // always invokes undefined behavior for 32-bit X.
3497 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3498 unsigned MaskLoBits = 0;
3499 if (Neg.getOpcode() == ISD::AND &&
3500 isPowerOf2_64(OpSize) &&
3501 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3502 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3503 Neg = Neg.getOperand(0);
3504 MaskLoBits = Log2_64(OpSize);
3507 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3508 if (Neg.getOpcode() != ISD::SUB)
3510 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3513 SDValue NegOp1 = Neg.getOperand(1);
3515 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3516 // Pos'. The truncation is redundant for the purpose of the equality.
3518 Pos.getOpcode() == ISD::AND &&
3519 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3520 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3521 Pos = Pos.getOperand(0);
3523 // The condition we need is now:
3525 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3527 // If NegOp1 == Pos then we need:
3529 // OpSize & Mask == NegC & Mask
3531 // (because "x & Mask" is a truncation and distributes through subtraction).
3534 Width = NegC->getAPIntValue();
3535 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3536 // Then the condition we want to prove becomes:
3538 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3540 // which, again because "x & Mask" is a truncation, becomes:
3542 // NegC & Mask == (OpSize - PosC) & Mask
3543 // OpSize & Mask == (NegC + PosC) & Mask
3544 else if (Pos.getOpcode() == ISD::ADD &&
3545 Pos.getOperand(0) == NegOp1 &&
3546 Pos.getOperand(1).getOpcode() == ISD::Constant)
3547 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3548 NegC->getAPIntValue());
3552 // Now we just need to check that OpSize & Mask == Width & Mask.
3554 // Opsize & Mask is 0 since Mask is Opsize - 1.
3555 return Width.getLoBits(MaskLoBits) == 0;
3556 return Width == OpSize;
3559 // A subroutine of MatchRotate used once we have found an OR of two opposite
3560 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3561 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3562 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3563 // Neg with outer conversions stripped away.
3564 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3565 SDValue Neg, SDValue InnerPos,
3566 SDValue InnerNeg, unsigned PosOpcode,
3567 unsigned NegOpcode, SDLoc DL) {
3568 // fold (or (shl x, (*ext y)),
3569 // (srl x, (*ext (sub 32, y)))) ->
3570 // (rotl x, y) or (rotr x, (sub 32, y))
3572 // fold (or (shl x, (*ext (sub 32, y))),
3573 // (srl x, (*ext y))) ->
3574 // (rotr x, y) or (rotl x, (sub 32, y))
3575 EVT VT = Shifted.getValueType();
3576 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3577 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3578 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3579 HasPos ? Pos : Neg).getNode();
3585 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3586 // idioms for rotate, and if the target supports rotation instructions, generate
3588 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3589 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3590 EVT VT = LHS.getValueType();
3591 if (!TLI.isTypeLegal(VT)) return nullptr;
3593 // The target must have at least one rotate flavor.
3594 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3595 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3596 if (!HasROTL && !HasROTR) return nullptr;
3598 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3599 SDValue LHSShift; // The shift.
3600 SDValue LHSMask; // AND value if any.
3601 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3602 return nullptr; // Not part of a rotate.
3604 SDValue RHSShift; // The shift.
3605 SDValue RHSMask; // AND value if any.
3606 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3607 return nullptr; // Not part of a rotate.
3609 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3610 return nullptr; // Not shifting the same value.
3612 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3613 return nullptr; // Shifts must disagree.
3615 // Canonicalize shl to left side in a shl/srl pair.
3616 if (RHSShift.getOpcode() == ISD::SHL) {
3617 std::swap(LHS, RHS);
3618 std::swap(LHSShift, RHSShift);
3619 std::swap(LHSMask , RHSMask );
3622 unsigned OpSizeInBits = VT.getSizeInBits();
3623 SDValue LHSShiftArg = LHSShift.getOperand(0);
3624 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3625 SDValue RHSShiftArg = RHSShift.getOperand(0);
3626 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3628 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3629 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3630 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3631 RHSShiftAmt.getOpcode() == ISD::Constant) {
3632 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3633 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3634 if ((LShVal + RShVal) != OpSizeInBits)
3637 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3638 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3640 // If there is an AND of either shifted operand, apply it to the result.
3641 if (LHSMask.getNode() || RHSMask.getNode()) {
3642 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3644 if (LHSMask.getNode()) {
3645 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3646 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3648 if (RHSMask.getNode()) {
3649 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3650 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3653 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3656 return Rot.getNode();
3659 // If there is a mask here, and we have a variable shift, we can't be sure
3660 // that we're masking out the right stuff.
3661 if (LHSMask.getNode() || RHSMask.getNode())
3664 // If the shift amount is sign/zext/any-extended just peel it off.
3665 SDValue LExtOp0 = LHSShiftAmt;
3666 SDValue RExtOp0 = RHSShiftAmt;
3667 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3668 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3669 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3670 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3671 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3672 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3673 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3674 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3675 LExtOp0 = LHSShiftAmt.getOperand(0);
3676 RExtOp0 = RHSShiftAmt.getOperand(0);
3679 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3680 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3684 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3685 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3692 SDValue DAGCombiner::visitXOR(SDNode *N) {
3693 SDValue N0 = N->getOperand(0);
3694 SDValue N1 = N->getOperand(1);
3695 SDValue LHS, RHS, CC;
3696 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3697 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3698 EVT VT = N0.getValueType();
3701 if (VT.isVector()) {
3702 SDValue FoldedVOp = SimplifyVBinOp(N);
3703 if (FoldedVOp.getNode()) return FoldedVOp;
3705 // fold (xor x, 0) -> x, vector edition
3706 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3708 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3712 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3713 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3714 return DAG.getConstant(0, VT);
3715 // fold (xor x, undef) -> undef
3716 if (N0.getOpcode() == ISD::UNDEF)
3718 if (N1.getOpcode() == ISD::UNDEF)
3720 // fold (xor c1, c2) -> c1^c2
3722 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3723 // canonicalize constant to RHS
3725 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3726 // fold (xor x, 0) -> x
3727 if (N1C && N1C->isNullValue())
3730 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3734 // fold !(x cc y) -> (x !cc y)
3735 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3736 bool isInt = LHS.getValueType().isInteger();
3737 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3740 if (!LegalOperations ||
3741 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3742 switch (N0.getOpcode()) {
3744 llvm_unreachable("Unhandled SetCC Equivalent!");
3746 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3747 case ISD::SELECT_CC:
3748 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3749 N0.getOperand(3), NotCC);
3754 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3755 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3756 N0.getNode()->hasOneUse() &&
3757 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3758 SDValue V = N0.getOperand(0);
3759 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3760 DAG.getConstant(1, V.getValueType()));
3761 AddToWorklist(V.getNode());
3762 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3765 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3766 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3767 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3768 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3769 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3770 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3771 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3772 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3773 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3774 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3777 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3778 if (N1C && N1C->isAllOnesValue() &&
3779 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3780 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3781 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3782 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3783 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3784 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3785 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3786 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3789 // fold (xor (and x, y), y) -> (and (not x), y)
3790 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3791 N0->getOperand(1) == N1) {
3792 SDValue X = N0->getOperand(0);
3793 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3794 AddToWorklist(NotX.getNode());
3795 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3797 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3798 if (N1C && N0.getOpcode() == ISD::XOR) {
3799 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3800 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3802 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3803 DAG.getConstant(N1C->getAPIntValue() ^
3804 N00C->getAPIntValue(), VT));
3806 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3807 DAG.getConstant(N1C->getAPIntValue() ^
3808 N01C->getAPIntValue(), VT));
3810 // fold (xor x, x) -> 0
3812 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3814 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3815 if (N0.getOpcode() == N1.getOpcode()) {
3816 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3817 if (Tmp.getNode()) return Tmp;
3820 // Simplify the expression using non-local knowledge.
3821 if (!VT.isVector() &&
3822 SimplifyDemandedBits(SDValue(N, 0)))
3823 return SDValue(N, 0);
3828 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3829 /// the shift amount is a constant.
3830 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3831 // We can't and shouldn't fold opaque constants.
3832 if (Amt->isOpaque())
3835 SDNode *LHS = N->getOperand(0).getNode();
3836 if (!LHS->hasOneUse()) return SDValue();
3838 // We want to pull some binops through shifts, so that we have (and (shift))
3839 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3840 // thing happens with address calculations, so it's important to canonicalize
3842 bool HighBitSet = false; // Can we transform this if the high bit is set?
3844 switch (LHS->getOpcode()) {
3845 default: return SDValue();
3848 HighBitSet = false; // We can only transform sra if the high bit is clear.
3851 HighBitSet = true; // We can only transform sra if the high bit is set.
3854 if (N->getOpcode() != ISD::SHL)
3855 return SDValue(); // only shl(add) not sr[al](add).
3856 HighBitSet = false; // We can only transform sra if the high bit is clear.
3860 // We require the RHS of the binop to be a constant and not opaque as well.
3861 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3862 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3864 // FIXME: disable this unless the input to the binop is a shift by a constant.
3865 // If it is not a shift, it pessimizes some common cases like:
3867 // void foo(int *X, int i) { X[i & 1235] = 1; }
3868 // int bar(int *X, int i) { return X[i & 255]; }
3869 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3870 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3871 BinOpLHSVal->getOpcode() != ISD::SRA &&
3872 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3873 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3876 EVT VT = N->getValueType(0);
3878 // If this is a signed shift right, and the high bit is modified by the
3879 // logical operation, do not perform the transformation. The highBitSet
3880 // boolean indicates the value of the high bit of the constant which would
3881 // cause it to be modified for this operation.
3882 if (N->getOpcode() == ISD::SRA) {
3883 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3884 if (BinOpRHSSignSet != HighBitSet)
3888 if (!TLI.isDesirableToCommuteWithShift(LHS))
3891 // Fold the constants, shifting the binop RHS by the shift amount.
3892 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3894 LHS->getOperand(1), N->getOperand(1));
3895 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3897 // Create the new shift.
3898 SDValue NewShift = DAG.getNode(N->getOpcode(),
3899 SDLoc(LHS->getOperand(0)),
3900 VT, LHS->getOperand(0), N->getOperand(1));
3902 // Create the new binop.
3903 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3906 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3907 assert(N->getOpcode() == ISD::TRUNCATE);
3908 assert(N->getOperand(0).getOpcode() == ISD::AND);
3910 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3911 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3912 SDValue N01 = N->getOperand(0).getOperand(1);
3914 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3915 EVT TruncVT = N->getValueType(0);
3916 SDValue N00 = N->getOperand(0).getOperand(0);
3917 APInt TruncC = N01C->getAPIntValue();
3918 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3920 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3921 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3922 DAG.getConstant(TruncC, TruncVT));
3929 SDValue DAGCombiner::visitRotate(SDNode *N) {
3930 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3931 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3932 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3933 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3934 if (NewOp1.getNode())
3935 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3936 N->getOperand(0), NewOp1);
3941 SDValue DAGCombiner::visitSHL(SDNode *N) {
3942 SDValue N0 = N->getOperand(0);
3943 SDValue N1 = N->getOperand(1);
3944 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3945 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3946 EVT VT = N0.getValueType();
3947 unsigned OpSizeInBits = VT.getScalarSizeInBits();
3950 if (VT.isVector()) {
3951 SDValue FoldedVOp = SimplifyVBinOp(N);
3952 if (FoldedVOp.getNode()) return FoldedVOp;
3954 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3955 // If setcc produces all-one true value then:
3956 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
3957 if (N1CV && N1CV->isConstant()) {
3958 if (N0.getOpcode() == ISD::AND) {
3959 SDValue N00 = N0->getOperand(0);
3960 SDValue N01 = N0->getOperand(1);
3961 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
3963 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
3964 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
3965 TargetLowering::ZeroOrNegativeOneBooleanContent) {
3966 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3968 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3971 N1C = isConstOrConstSplat(N1);
3976 // fold (shl c1, c2) -> c1<<c2
3978 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3979 // fold (shl 0, x) -> 0
3980 if (N0C && N0C->isNullValue())
3982 // fold (shl x, c >= size(x)) -> undef
3983 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3984 return DAG.getUNDEF(VT);
3985 // fold (shl x, 0) -> x
3986 if (N1C && N1C->isNullValue())
3988 // fold (shl undef, x) -> 0
3989 if (N0.getOpcode() == ISD::UNDEF)
3990 return DAG.getConstant(0, VT);
3991 // if (shl x, c) is known to be zero, return 0
3992 if (DAG.MaskedValueIsZero(SDValue(N, 0),
3993 APInt::getAllOnesValue(OpSizeInBits)))
3994 return DAG.getConstant(0, VT);
3995 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3996 if (N1.getOpcode() == ISD::TRUNCATE &&
3997 N1.getOperand(0).getOpcode() == ISD::AND) {
3998 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
3999 if (NewOp1.getNode())
4000 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4003 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4004 return SDValue(N, 0);
4006 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4007 if (N1C && N0.getOpcode() == ISD::SHL) {
4008 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4009 uint64_t c1 = N0C1->getZExtValue();
4010 uint64_t c2 = N1C->getZExtValue();
4011 if (c1 + c2 >= OpSizeInBits)
4012 return DAG.getConstant(0, VT);
4013 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4014 DAG.getConstant(c1 + c2, N1.getValueType()));
4018 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4019 // For this to be valid, the second form must not preserve any of the bits
4020 // that are shifted out by the inner shift in the first form. This means
4021 // the outer shift size must be >= the number of bits added by the ext.
4022 // As a corollary, we don't care what kind of ext it is.
4023 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4024 N0.getOpcode() == ISD::ANY_EXTEND ||
4025 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4026 N0.getOperand(0).getOpcode() == ISD::SHL) {
4027 SDValue N0Op0 = N0.getOperand(0);
4028 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4029 uint64_t c1 = N0Op0C1->getZExtValue();
4030 uint64_t c2 = N1C->getZExtValue();
4031 EVT InnerShiftVT = N0Op0.getValueType();
4032 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4033 if (c2 >= OpSizeInBits - InnerShiftSize) {
4034 if (c1 + c2 >= OpSizeInBits)
4035 return DAG.getConstant(0, VT);
4036 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4037 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4038 N0Op0->getOperand(0)),
4039 DAG.getConstant(c1 + c2, N1.getValueType()));
4044 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4045 // Only fold this if the inner zext has no other uses to avoid increasing
4046 // the total number of instructions.
4047 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4048 N0.getOperand(0).getOpcode() == ISD::SRL) {
4049 SDValue N0Op0 = N0.getOperand(0);
4050 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4051 uint64_t c1 = N0Op0C1->getZExtValue();
4052 if (c1 < VT.getScalarSizeInBits()) {
4053 uint64_t c2 = N1C->getZExtValue();
4055 SDValue NewOp0 = N0.getOperand(0);
4056 EVT CountVT = NewOp0.getOperand(1).getValueType();
4057 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4058 NewOp0, DAG.getConstant(c2, CountVT));
4059 AddToWorklist(NewSHL.getNode());
4060 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4066 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4067 // (and (srl x, (sub c1, c2), MASK)
4068 // Only fold this if the inner shift has no other uses -- if it does, folding
4069 // this will increase the total number of instructions.
4070 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4071 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4072 uint64_t c1 = N0C1->getZExtValue();
4073 if (c1 < OpSizeInBits) {
4074 uint64_t c2 = N1C->getZExtValue();
4075 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4078 Mask = Mask.shl(c2 - c1);
4079 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4080 DAG.getConstant(c2 - c1, N1.getValueType()));
4082 Mask = Mask.lshr(c1 - c2);
4083 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4084 DAG.getConstant(c1 - c2, N1.getValueType()));
4086 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4087 DAG.getConstant(Mask, VT));
4091 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4092 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4093 unsigned BitSize = VT.getScalarSizeInBits();
4094 SDValue HiBitsMask =
4095 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4096 BitSize - N1C->getZExtValue()), VT);
4097 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4102 SDValue NewSHL = visitShiftByConstant(N, N1C);
4103 if (NewSHL.getNode())
4110 SDValue DAGCombiner::visitSRA(SDNode *N) {
4111 SDValue N0 = N->getOperand(0);
4112 SDValue N1 = N->getOperand(1);
4113 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4114 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4115 EVT VT = N0.getValueType();
4116 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4119 if (VT.isVector()) {
4120 SDValue FoldedVOp = SimplifyVBinOp(N);
4121 if (FoldedVOp.getNode()) return FoldedVOp;
4123 N1C = isConstOrConstSplat(N1);
4126 // fold (sra c1, c2) -> (sra c1, c2)
4128 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4129 // fold (sra 0, x) -> 0
4130 if (N0C && N0C->isNullValue())
4132 // fold (sra -1, x) -> -1
4133 if (N0C && N0C->isAllOnesValue())
4135 // fold (sra x, (setge c, size(x))) -> undef
4136 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4137 return DAG.getUNDEF(VT);
4138 // fold (sra x, 0) -> x
4139 if (N1C && N1C->isNullValue())
4141 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4143 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4144 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4145 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4147 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4148 ExtVT, VT.getVectorNumElements());
4149 if ((!LegalOperations ||
4150 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4151 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4152 N0.getOperand(0), DAG.getValueType(ExtVT));
4155 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4156 if (N1C && N0.getOpcode() == ISD::SRA) {
4157 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4158 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4159 if (Sum >= OpSizeInBits)
4160 Sum = OpSizeInBits - 1;
4161 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4162 DAG.getConstant(Sum, N1.getValueType()));
4166 // fold (sra (shl X, m), (sub result_size, n))
4167 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4168 // result_size - n != m.
4169 // If truncate is free for the target sext(shl) is likely to result in better
4171 if (N0.getOpcode() == ISD::SHL && N1C) {
4172 // Get the two constanst of the shifts, CN0 = m, CN = n.
4173 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4175 LLVMContext &Ctx = *DAG.getContext();
4176 // Determine what the truncate's result bitsize and type would be.
4177 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4180 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4182 // Determine the residual right-shift amount.
4183 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4185 // If the shift is not a no-op (in which case this should be just a sign
4186 // extend already), the truncated to type is legal, sign_extend is legal
4187 // on that type, and the truncate to that type is both legal and free,
4188 // perform the transform.
4189 if ((ShiftAmt > 0) &&
4190 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4191 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4192 TLI.isTruncateFree(VT, TruncVT)) {
4194 SDValue Amt = DAG.getConstant(ShiftAmt,
4195 getShiftAmountTy(N0.getOperand(0).getValueType()));
4196 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4197 N0.getOperand(0), Amt);
4198 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4200 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4201 N->getValueType(0), Trunc);
4206 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4207 if (N1.getOpcode() == ISD::TRUNCATE &&
4208 N1.getOperand(0).getOpcode() == ISD::AND) {
4209 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4210 if (NewOp1.getNode())
4211 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4214 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4215 // if c1 is equal to the number of bits the trunc removes
4216 if (N0.getOpcode() == ISD::TRUNCATE &&
4217 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4218 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4219 N0.getOperand(0).hasOneUse() &&
4220 N0.getOperand(0).getOperand(1).hasOneUse() &&
4222 SDValue N0Op0 = N0.getOperand(0);
4223 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4224 unsigned LargeShiftVal = LargeShift->getZExtValue();
4225 EVT LargeVT = N0Op0.getValueType();
4227 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4229 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4230 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4231 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4232 N0Op0.getOperand(0), Amt);
4233 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4238 // Simplify, based on bits shifted out of the LHS.
4239 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4240 return SDValue(N, 0);
4243 // If the sign bit is known to be zero, switch this to a SRL.
4244 if (DAG.SignBitIsZero(N0))
4245 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4248 SDValue NewSRA = visitShiftByConstant(N, N1C);
4249 if (NewSRA.getNode())
4256 SDValue DAGCombiner::visitSRL(SDNode *N) {
4257 SDValue N0 = N->getOperand(0);
4258 SDValue N1 = N->getOperand(1);
4259 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4260 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4261 EVT VT = N0.getValueType();
4262 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4265 if (VT.isVector()) {
4266 SDValue FoldedVOp = SimplifyVBinOp(N);
4267 if (FoldedVOp.getNode()) return FoldedVOp;
4269 N1C = isConstOrConstSplat(N1);
4272 // fold (srl c1, c2) -> c1 >>u c2
4274 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4275 // fold (srl 0, x) -> 0
4276 if (N0C && N0C->isNullValue())
4278 // fold (srl x, c >= size(x)) -> undef
4279 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4280 return DAG.getUNDEF(VT);
4281 // fold (srl x, 0) -> x
4282 if (N1C && N1C->isNullValue())
4284 // if (srl x, c) is known to be zero, return 0
4285 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4286 APInt::getAllOnesValue(OpSizeInBits)))
4287 return DAG.getConstant(0, VT);
4289 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4290 if (N1C && N0.getOpcode() == ISD::SRL) {
4291 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4292 uint64_t c1 = N01C->getZExtValue();
4293 uint64_t c2 = N1C->getZExtValue();
4294 if (c1 + c2 >= OpSizeInBits)
4295 return DAG.getConstant(0, VT);
4296 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4297 DAG.getConstant(c1 + c2, N1.getValueType()));
4301 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4302 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4303 N0.getOperand(0).getOpcode() == ISD::SRL &&
4304 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4306 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4307 uint64_t c2 = N1C->getZExtValue();
4308 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4309 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4310 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4311 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4312 if (c1 + OpSizeInBits == InnerShiftSize) {
4313 if (c1 + c2 >= InnerShiftSize)
4314 return DAG.getConstant(0, VT);
4315 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4316 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4317 N0.getOperand(0)->getOperand(0),
4318 DAG.getConstant(c1 + c2, ShiftCountVT)));
4322 // fold (srl (shl x, c), c) -> (and x, cst2)
4323 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4324 unsigned BitSize = N0.getScalarValueSizeInBits();
4325 if (BitSize <= 64) {
4326 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4327 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4328 DAG.getConstant(~0ULL >> ShAmt, VT));
4332 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4333 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4334 // Shifting in all undef bits?
4335 EVT SmallVT = N0.getOperand(0).getValueType();
4336 unsigned BitSize = SmallVT.getScalarSizeInBits();
4337 if (N1C->getZExtValue() >= BitSize)
4338 return DAG.getUNDEF(VT);
4340 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4341 uint64_t ShiftAmt = N1C->getZExtValue();
4342 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4344 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4345 AddToWorklist(SmallShift.getNode());
4346 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4347 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4348 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4349 DAG.getConstant(Mask, VT));
4353 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4354 // bit, which is unmodified by sra.
4355 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4356 if (N0.getOpcode() == ISD::SRA)
4357 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4360 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4361 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4362 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4363 APInt KnownZero, KnownOne;
4364 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4366 // If any of the input bits are KnownOne, then the input couldn't be all
4367 // zeros, thus the result of the srl will always be zero.
4368 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4370 // If all of the bits input the to ctlz node are known to be zero, then
4371 // the result of the ctlz is "32" and the result of the shift is one.
4372 APInt UnknownBits = ~KnownZero;
4373 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4375 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4376 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4377 // Okay, we know that only that the single bit specified by UnknownBits
4378 // could be set on input to the CTLZ node. If this bit is set, the SRL
4379 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4380 // to an SRL/XOR pair, which is likely to simplify more.
4381 unsigned ShAmt = UnknownBits.countTrailingZeros();
4382 SDValue Op = N0.getOperand(0);
4385 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4386 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4387 AddToWorklist(Op.getNode());
4390 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4391 Op, DAG.getConstant(1, VT));
4395 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4396 if (N1.getOpcode() == ISD::TRUNCATE &&
4397 N1.getOperand(0).getOpcode() == ISD::AND) {
4398 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4399 if (NewOp1.getNode())
4400 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4403 // fold operands of srl based on knowledge that the low bits are not
4405 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4406 return SDValue(N, 0);
4409 SDValue NewSRL = visitShiftByConstant(N, N1C);
4410 if (NewSRL.getNode())
4414 // Attempt to convert a srl of a load into a narrower zero-extending load.
4415 SDValue NarrowLoad = ReduceLoadWidth(N);
4416 if (NarrowLoad.getNode())
4419 // Here is a common situation. We want to optimize:
4422 // %b = and i32 %a, 2
4423 // %c = srl i32 %b, 1
4424 // brcond i32 %c ...
4430 // %c = setcc eq %b, 0
4433 // However when after the source operand of SRL is optimized into AND, the SRL
4434 // itself may not be optimized further. Look for it and add the BRCOND into
4436 if (N->hasOneUse()) {
4437 SDNode *Use = *N->use_begin();
4438 if (Use->getOpcode() == ISD::BRCOND)
4440 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4441 // Also look pass the truncate.
4442 Use = *Use->use_begin();
4443 if (Use->getOpcode() == ISD::BRCOND)
4451 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4452 SDValue N0 = N->getOperand(0);
4453 EVT VT = N->getValueType(0);
4455 // fold (ctlz c1) -> c2
4456 if (isa<ConstantSDNode>(N0))
4457 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4461 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4462 SDValue N0 = N->getOperand(0);
4463 EVT VT = N->getValueType(0);
4465 // fold (ctlz_zero_undef c1) -> c2
4466 if (isa<ConstantSDNode>(N0))
4467 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4471 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4472 SDValue N0 = N->getOperand(0);
4473 EVT VT = N->getValueType(0);
4475 // fold (cttz c1) -> c2
4476 if (isa<ConstantSDNode>(N0))
4477 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4481 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4482 SDValue N0 = N->getOperand(0);
4483 EVT VT = N->getValueType(0);
4485 // fold (cttz_zero_undef c1) -> c2
4486 if (isa<ConstantSDNode>(N0))
4487 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4491 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4492 SDValue N0 = N->getOperand(0);
4493 EVT VT = N->getValueType(0);
4495 // fold (ctpop c1) -> c2
4496 if (isa<ConstantSDNode>(N0))
4497 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4501 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4502 SDValue N0 = N->getOperand(0);
4503 SDValue N1 = N->getOperand(1);
4504 SDValue N2 = N->getOperand(2);
4505 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4506 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4507 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4508 EVT VT = N->getValueType(0);
4509 EVT VT0 = N0.getValueType();
4511 // fold (select C, X, X) -> X
4514 // fold (select true, X, Y) -> X
4515 if (N0C && !N0C->isNullValue())
4517 // fold (select false, X, Y) -> Y
4518 if (N0C && N0C->isNullValue())
4520 // fold (select C, 1, X) -> (or C, X)
4521 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4522 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4523 // fold (select C, 0, 1) -> (xor C, 1)
4524 // We can't do this reliably if integer based booleans have different contents
4525 // to floating point based booleans. This is because we can't tell whether we
4526 // have an integer-based boolean or a floating-point-based boolean unless we
4527 // can find the SETCC that produced it and inspect its operands. This is
4528 // fairly easy if C is the SETCC node, but it can potentially be
4529 // undiscoverable (or not reasonably discoverable). For example, it could be
4530 // in another basic block or it could require searching a complicated
4532 if (VT.isInteger() &&
4533 (VT0 == MVT::i1 || (VT0.isInteger() &&
4534 TLI.getBooleanContents(false, false) ==
4535 TLI.getBooleanContents(false, true) &&
4536 TLI.getBooleanContents(false, false) ==
4537 TargetLowering::ZeroOrOneBooleanContent)) &&
4538 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4541 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4542 N0, DAG.getConstant(1, VT0));
4543 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4544 N0, DAG.getConstant(1, VT0));
4545 AddToWorklist(XORNode.getNode());
4547 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4548 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4550 // fold (select C, 0, X) -> (and (not C), X)
4551 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4552 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4553 AddToWorklist(NOTNode.getNode());
4554 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4556 // fold (select C, X, 1) -> (or (not C), X)
4557 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4558 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4559 AddToWorklist(NOTNode.getNode());
4560 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4562 // fold (select C, X, 0) -> (and C, X)
4563 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4564 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4565 // fold (select X, X, Y) -> (or X, Y)
4566 // fold (select X, 1, Y) -> (or X, Y)
4567 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4568 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4569 // fold (select X, Y, X) -> (and X, Y)
4570 // fold (select X, Y, 0) -> (and X, Y)
4571 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4572 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4574 // If we can fold this based on the true/false value, do so.
4575 if (SimplifySelectOps(N, N1, N2))
4576 return SDValue(N, 0); // Don't revisit N.
4578 // fold selects based on a setcc into other things, such as min/max/abs
4579 if (N0.getOpcode() == ISD::SETCC) {
4580 if ((!LegalOperations &&
4581 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4582 TLI.isOperationLegal(ISD::SELECT_CC, VT))
4583 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4584 N0.getOperand(0), N0.getOperand(1),
4585 N1, N2, N0.getOperand(2));
4586 return SimplifySelect(SDLoc(N), N0, N1, N2);
4593 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4596 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4598 // Split the inputs.
4599 SDValue Lo, Hi, LL, LH, RL, RH;
4600 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4601 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4603 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4604 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4606 return std::make_pair(Lo, Hi);
4609 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4610 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4611 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4613 SDValue Cond = N->getOperand(0);
4614 SDValue LHS = N->getOperand(1);
4615 SDValue RHS = N->getOperand(2);
4616 MVT VT = N->getSimpleValueType(0);
4617 int NumElems = VT.getVectorNumElements();
4618 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4619 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4620 Cond.getOpcode() == ISD::BUILD_VECTOR);
4622 // We're sure we have an even number of elements due to the
4623 // concat_vectors we have as arguments to vselect.
4624 // Skip BV elements until we find one that's not an UNDEF
4625 // After we find an UNDEF element, keep looping until we get to half the
4626 // length of the BV and see if all the non-undef nodes are the same.
4627 ConstantSDNode *BottomHalf = nullptr;
4628 for (int i = 0; i < NumElems / 2; ++i) {
4629 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4632 if (BottomHalf == nullptr)
4633 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4634 else if (Cond->getOperand(i).getNode() != BottomHalf)
4638 // Do the same for the second half of the BuildVector
4639 ConstantSDNode *TopHalf = nullptr;
4640 for (int i = NumElems / 2; i < NumElems; ++i) {
4641 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4644 if (TopHalf == nullptr)
4645 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4646 else if (Cond->getOperand(i).getNode() != TopHalf)
4650 assert(TopHalf && BottomHalf &&
4651 "One half of the selector was all UNDEFs and the other was all the "
4652 "same value. This should have been addressed before this function.");
4654 ISD::CONCAT_VECTORS, dl, VT,
4655 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4656 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4659 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4660 SDValue N0 = N->getOperand(0);
4661 SDValue N1 = N->getOperand(1);
4662 SDValue N2 = N->getOperand(2);
4665 // Canonicalize integer abs.
4666 // vselect (setg[te] X, 0), X, -X ->
4667 // vselect (setgt X, -1), X, -X ->
4668 // vselect (setl[te] X, 0), -X, X ->
4669 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4670 if (N0.getOpcode() == ISD::SETCC) {
4671 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4672 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4674 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4676 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4677 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4678 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4679 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4680 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4681 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4682 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4685 EVT VT = LHS.getValueType();
4686 SDValue Shift = DAG.getNode(
4687 ISD::SRA, DL, VT, LHS,
4688 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4689 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4690 AddToWorklist(Shift.getNode());
4691 AddToWorklist(Add.getNode());
4692 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4696 // If the VSELECT result requires splitting and the mask is provided by a
4697 // SETCC, then split both nodes and its operands before legalization. This
4698 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4699 // and enables future optimizations (e.g. min/max pattern matching on X86).
4700 if (N0.getOpcode() == ISD::SETCC) {
4701 EVT VT = N->getValueType(0);
4703 // Check if any splitting is required.
4704 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4705 TargetLowering::TypeSplitVector)
4708 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4709 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4710 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4711 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4713 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4714 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4716 // Add the new VSELECT nodes to the work list in case they need to be split
4718 AddToWorklist(Lo.getNode());
4719 AddToWorklist(Hi.getNode());
4721 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4724 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4725 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4727 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4728 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4731 // The ConvertSelectToConcatVector function is assuming both the above
4732 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4734 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4735 N2.getOpcode() == ISD::CONCAT_VECTORS &&
4736 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4737 SDValue CV = ConvertSelectToConcatVector(N, DAG);
4745 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4746 SDValue N0 = N->getOperand(0);
4747 SDValue N1 = N->getOperand(1);
4748 SDValue N2 = N->getOperand(2);
4749 SDValue N3 = N->getOperand(3);
4750 SDValue N4 = N->getOperand(4);
4751 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4753 // fold select_cc lhs, rhs, x, x, cc -> x
4757 // Determine if the condition we're dealing with is constant
4758 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4759 N0, N1, CC, SDLoc(N), false);
4760 if (SCC.getNode()) {
4761 AddToWorklist(SCC.getNode());
4763 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4764 if (!SCCC->isNullValue())
4765 return N2; // cond always true -> true val
4767 return N3; // cond always false -> false val
4770 // Fold to a simpler select_cc
4771 if (SCC.getOpcode() == ISD::SETCC)
4772 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4773 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4777 // If we can fold this based on the true/false value, do so.
4778 if (SimplifySelectOps(N, N2, N3))
4779 return SDValue(N, 0); // Don't revisit N.
4781 // fold select_cc into other things, such as min/max/abs
4782 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4785 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4786 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4787 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4791 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4792 // dag node into a ConstantSDNode or a build_vector of constants.
4793 // This function is called by the DAGCombiner when visiting sext/zext/aext
4794 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4795 // Vector extends are not folded if operations are legal; this is to
4796 // avoid introducing illegal build_vector dag nodes.
4797 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4798 SelectionDAG &DAG, bool LegalTypes,
4799 bool LegalOperations) {
4800 unsigned Opcode = N->getOpcode();
4801 SDValue N0 = N->getOperand(0);
4802 EVT VT = N->getValueType(0);
4804 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4805 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4807 // fold (sext c1) -> c1
4808 // fold (zext c1) -> c1
4809 // fold (aext c1) -> c1
4810 if (isa<ConstantSDNode>(N0))
4811 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4813 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4814 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4815 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4816 EVT SVT = VT.getScalarType();
4817 if (!(VT.isVector() &&
4818 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4819 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4822 // We can fold this node into a build_vector.
4823 unsigned VTBits = SVT.getSizeInBits();
4824 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4825 unsigned ShAmt = VTBits - EVTBits;
4826 SmallVector<SDValue, 8> Elts;
4827 unsigned NumElts = N0->getNumOperands();
4830 for (unsigned i=0; i != NumElts; ++i) {
4831 SDValue Op = N0->getOperand(i);
4832 if (Op->getOpcode() == ISD::UNDEF) {
4833 Elts.push_back(DAG.getUNDEF(SVT));
4837 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4838 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4839 if (Opcode == ISD::SIGN_EXTEND)
4840 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4843 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4847 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4850 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4851 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4852 // transformation. Returns true if extension are possible and the above
4853 // mentioned transformation is profitable.
4854 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4856 SmallVectorImpl<SDNode *> &ExtendNodes,
4857 const TargetLowering &TLI) {
4858 bool HasCopyToRegUses = false;
4859 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4860 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4861 UE = N0.getNode()->use_end();
4866 if (UI.getUse().getResNo() != N0.getResNo())
4868 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4869 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4870 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4871 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4872 // Sign bits will be lost after a zext.
4875 for (unsigned i = 0; i != 2; ++i) {
4876 SDValue UseOp = User->getOperand(i);
4879 if (!isa<ConstantSDNode>(UseOp))
4884 ExtendNodes.push_back(User);
4887 // If truncates aren't free and there are users we can't
4888 // extend, it isn't worthwhile.
4891 // Remember if this value is live-out.
4892 if (User->getOpcode() == ISD::CopyToReg)
4893 HasCopyToRegUses = true;
4896 if (HasCopyToRegUses) {
4897 bool BothLiveOut = false;
4898 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4900 SDUse &Use = UI.getUse();
4901 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4907 // Both unextended and extended values are live out. There had better be
4908 // a good reason for the transformation.
4909 return ExtendNodes.size();
4914 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4915 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4916 ISD::NodeType ExtType) {
4917 // Extend SetCC uses if necessary.
4918 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4919 SDNode *SetCC = SetCCs[i];
4920 SmallVector<SDValue, 4> Ops;
4922 for (unsigned j = 0; j != 2; ++j) {
4923 SDValue SOp = SetCC->getOperand(j);
4925 Ops.push_back(ExtLoad);
4927 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4930 Ops.push_back(SetCC->getOperand(2));
4931 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
4935 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4936 SDValue N0 = N->getOperand(0);
4937 EVT VT = N->getValueType(0);
4939 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4941 return SDValue(Res, 0);
4943 // fold (sext (sext x)) -> (sext x)
4944 // fold (sext (aext x)) -> (sext x)
4945 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4946 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4949 if (N0.getOpcode() == ISD::TRUNCATE) {
4950 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4951 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4952 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4953 if (NarrowLoad.getNode()) {
4954 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4955 if (NarrowLoad.getNode() != N0.getNode()) {
4956 CombineTo(N0.getNode(), NarrowLoad);
4957 // CombineTo deleted the truncate, if needed, but not what's under it.
4960 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4963 // See if the value being truncated is already sign extended. If so, just
4964 // eliminate the trunc/sext pair.
4965 SDValue Op = N0.getOperand(0);
4966 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4967 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4968 unsigned DestBits = VT.getScalarType().getSizeInBits();
4969 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4971 if (OpBits == DestBits) {
4972 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4973 // bits, it is already ready.
4974 if (NumSignBits > DestBits-MidBits)
4976 } else if (OpBits < DestBits) {
4977 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4978 // bits, just sext from i32.
4979 if (NumSignBits > OpBits-MidBits)
4980 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4982 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4983 // bits, just truncate to i32.
4984 if (NumSignBits > OpBits-MidBits)
4985 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4988 // fold (sext (truncate x)) -> (sextinreg x).
4989 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4990 N0.getValueType())) {
4991 if (OpBits < DestBits)
4992 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4993 else if (OpBits > DestBits)
4994 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4995 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4996 DAG.getValueType(N0.getValueType()));
5000 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5001 // None of the supported targets knows how to perform load and sign extend
5002 // on vectors in one instruction. We only perform this transformation on
5004 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5005 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5006 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5007 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5008 bool DoXform = true;
5009 SmallVector<SDNode*, 4> SetCCs;
5010 if (!N0.hasOneUse())
5011 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5013 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5014 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5016 LN0->getBasePtr(), N0.getValueType(),
5017 LN0->getMemOperand());
5018 CombineTo(N, ExtLoad);
5019 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5020 N0.getValueType(), ExtLoad);
5021 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5022 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5024 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5028 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5029 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5030 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5031 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5032 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5033 EVT MemVT = LN0->getMemoryVT();
5034 if ((!LegalOperations && !LN0->isVolatile()) ||
5035 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5036 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5038 LN0->getBasePtr(), MemVT,
5039 LN0->getMemOperand());
5040 CombineTo(N, ExtLoad);
5041 CombineTo(N0.getNode(),
5042 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5043 N0.getValueType(), ExtLoad),
5044 ExtLoad.getValue(1));
5045 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5049 // fold (sext (and/or/xor (load x), cst)) ->
5050 // (and/or/xor (sextload x), (sext cst))
5051 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5052 N0.getOpcode() == ISD::XOR) &&
5053 isa<LoadSDNode>(N0.getOperand(0)) &&
5054 N0.getOperand(1).getOpcode() == ISD::Constant &&
5055 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5056 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5057 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5058 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5059 bool DoXform = true;
5060 SmallVector<SDNode*, 4> SetCCs;
5061 if (!N0.hasOneUse())
5062 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5065 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5066 LN0->getChain(), LN0->getBasePtr(),
5068 LN0->getMemOperand());
5069 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5070 Mask = Mask.sext(VT.getSizeInBits());
5071 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5072 ExtLoad, DAG.getConstant(Mask, VT));
5073 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5074 SDLoc(N0.getOperand(0)),
5075 N0.getOperand(0).getValueType(), ExtLoad);
5077 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5078 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5080 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5085 if (N0.getOpcode() == ISD::SETCC) {
5086 EVT N0VT = N0.getOperand(0).getValueType();
5087 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5088 // Only do this before legalize for now.
5089 if (VT.isVector() && !LegalOperations &&
5090 TLI.getBooleanContents(N0VT) ==
5091 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5092 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5093 // of the same size as the compared operands. Only optimize sext(setcc())
5094 // if this is the case.
5095 EVT SVT = getSetCCResultType(N0VT);
5097 // We know that the # elements of the results is the same as the
5098 // # elements of the compare (and the # elements of the compare result
5099 // for that matter). Check to see that they are the same size. If so,
5100 // we know that the element size of the sext'd result matches the
5101 // element size of the compare operands.
5102 if (VT.getSizeInBits() == SVT.getSizeInBits())
5103 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5105 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5107 // If the desired elements are smaller or larger than the source
5108 // elements we can use a matching integer vector type and then
5109 // truncate/sign extend
5110 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5111 if (SVT == MatchingVectorType) {
5112 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5113 N0.getOperand(0), N0.getOperand(1),
5114 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5115 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5119 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5120 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5122 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5124 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5125 NegOne, DAG.getConstant(0, VT),
5126 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5127 if (SCC.getNode()) return SCC;
5129 if (!VT.isVector()) {
5130 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5131 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5133 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5134 SDValue SetCC = DAG.getSetCC(DL,
5136 N0.getOperand(0), N0.getOperand(1), CC);
5137 EVT SelectVT = getSetCCResultType(VT);
5138 return DAG.getSelect(DL, VT,
5139 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5140 NegOne, DAG.getConstant(0, VT));
5146 // fold (sext x) -> (zext x) if the sign bit is known zero.
5147 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5148 DAG.SignBitIsZero(N0))
5149 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5154 // isTruncateOf - If N is a truncate of some other value, return true, record
5155 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5156 // This function computes KnownZero to avoid a duplicated call to
5157 // computeKnownBits in the caller.
5158 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5161 if (N->getOpcode() == ISD::TRUNCATE) {
5162 Op = N->getOperand(0);
5163 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5167 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5168 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5171 SDValue Op0 = N->getOperand(0);
5172 SDValue Op1 = N->getOperand(1);
5173 assert(Op0.getValueType() == Op1.getValueType());
5175 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5176 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5177 if (COp0 && COp0->isNullValue())
5179 else if (COp1 && COp1->isNullValue())
5184 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5186 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5192 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5193 SDValue N0 = N->getOperand(0);
5194 EVT VT = N->getValueType(0);
5196 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5198 return SDValue(Res, 0);
5200 // fold (zext (zext x)) -> (zext x)
5201 // fold (zext (aext x)) -> (zext x)
5202 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5203 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5206 // fold (zext (truncate x)) -> (zext x) or
5207 // (zext (truncate x)) -> (truncate x)
5208 // This is valid when the truncated bits of x are already zero.
5209 // FIXME: We should extend this to work for vectors too.
5212 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5213 APInt TruncatedBits =
5214 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5215 APInt(Op.getValueSizeInBits(), 0) :
5216 APInt::getBitsSet(Op.getValueSizeInBits(),
5217 N0.getValueSizeInBits(),
5218 std::min(Op.getValueSizeInBits(),
5219 VT.getSizeInBits()));
5220 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5221 if (VT.bitsGT(Op.getValueType()))
5222 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5223 if (VT.bitsLT(Op.getValueType()))
5224 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5230 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5231 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5232 if (N0.getOpcode() == ISD::TRUNCATE) {
5233 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5234 if (NarrowLoad.getNode()) {
5235 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5236 if (NarrowLoad.getNode() != N0.getNode()) {
5237 CombineTo(N0.getNode(), NarrowLoad);
5238 // CombineTo deleted the truncate, if needed, but not what's under it.
5241 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5245 // fold (zext (truncate x)) -> (and x, mask)
5246 if (N0.getOpcode() == ISD::TRUNCATE &&
5247 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5249 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5250 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5251 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5252 if (NarrowLoad.getNode()) {
5253 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5254 if (NarrowLoad.getNode() != N0.getNode()) {
5255 CombineTo(N0.getNode(), NarrowLoad);
5256 // CombineTo deleted the truncate, if needed, but not what's under it.
5259 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5262 SDValue Op = N0.getOperand(0);
5263 if (Op.getValueType().bitsLT(VT)) {
5264 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5265 AddToWorklist(Op.getNode());
5266 } else if (Op.getValueType().bitsGT(VT)) {
5267 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5268 AddToWorklist(Op.getNode());
5270 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5271 N0.getValueType().getScalarType());
5274 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5275 // if either of the casts is not free.
5276 if (N0.getOpcode() == ISD::AND &&
5277 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5278 N0.getOperand(1).getOpcode() == ISD::Constant &&
5279 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5280 N0.getValueType()) ||
5281 !TLI.isZExtFree(N0.getValueType(), VT))) {
5282 SDValue X = N0.getOperand(0).getOperand(0);
5283 if (X.getValueType().bitsLT(VT)) {
5284 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5285 } else if (X.getValueType().bitsGT(VT)) {
5286 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5288 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5289 Mask = Mask.zext(VT.getSizeInBits());
5290 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5291 X, DAG.getConstant(Mask, VT));
5294 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5295 // None of the supported targets knows how to perform load and vector_zext
5296 // on vectors in one instruction. We only perform this transformation on
5298 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5299 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5300 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5301 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5302 bool DoXform = true;
5303 SmallVector<SDNode*, 4> SetCCs;
5304 if (!N0.hasOneUse())
5305 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5307 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5308 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5310 LN0->getBasePtr(), N0.getValueType(),
5311 LN0->getMemOperand());
5312 CombineTo(N, ExtLoad);
5313 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5314 N0.getValueType(), ExtLoad);
5315 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5317 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5319 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5323 // fold (zext (and/or/xor (load x), cst)) ->
5324 // (and/or/xor (zextload x), (zext cst))
5325 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5326 N0.getOpcode() == ISD::XOR) &&
5327 isa<LoadSDNode>(N0.getOperand(0)) &&
5328 N0.getOperand(1).getOpcode() == ISD::Constant &&
5329 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5330 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5331 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5332 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5333 bool DoXform = true;
5334 SmallVector<SDNode*, 4> SetCCs;
5335 if (!N0.hasOneUse())
5336 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5339 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5340 LN0->getChain(), LN0->getBasePtr(),
5342 LN0->getMemOperand());
5343 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5344 Mask = Mask.zext(VT.getSizeInBits());
5345 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5346 ExtLoad, DAG.getConstant(Mask, VT));
5347 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5348 SDLoc(N0.getOperand(0)),
5349 N0.getOperand(0).getValueType(), ExtLoad);
5351 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5352 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5354 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5359 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5360 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5361 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5362 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5363 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5364 EVT MemVT = LN0->getMemoryVT();
5365 if ((!LegalOperations && !LN0->isVolatile()) ||
5366 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5367 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5369 LN0->getBasePtr(), MemVT,
5370 LN0->getMemOperand());
5371 CombineTo(N, ExtLoad);
5372 CombineTo(N0.getNode(),
5373 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5375 ExtLoad.getValue(1));
5376 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5380 if (N0.getOpcode() == ISD::SETCC) {
5381 if (!LegalOperations && VT.isVector() &&
5382 N0.getValueType().getVectorElementType() == MVT::i1) {
5383 EVT N0VT = N0.getOperand(0).getValueType();
5384 if (getSetCCResultType(N0VT) == N0.getValueType())
5387 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5388 // Only do this before legalize for now.
5389 EVT EltVT = VT.getVectorElementType();
5390 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5391 DAG.getConstant(1, EltVT));
5392 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5393 // We know that the # elements of the results is the same as the
5394 // # elements of the compare (and the # elements of the compare result
5395 // for that matter). Check to see that they are the same size. If so,
5396 // we know that the element size of the sext'd result matches the
5397 // element size of the compare operands.
5398 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5399 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5401 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5402 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5405 // If the desired elements are smaller or larger than the source
5406 // elements we can use a matching integer vector type and then
5407 // truncate/sign extend
5408 EVT MatchingElementType =
5409 EVT::getIntegerVT(*DAG.getContext(),
5410 N0VT.getScalarType().getSizeInBits());
5411 EVT MatchingVectorType =
5412 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5413 N0VT.getVectorNumElements());
5415 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5417 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5418 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5419 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5420 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5423 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5425 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5426 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5427 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5428 if (SCC.getNode()) return SCC;
5431 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5432 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5433 isa<ConstantSDNode>(N0.getOperand(1)) &&
5434 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5436 SDValue ShAmt = N0.getOperand(1);
5437 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5438 if (N0.getOpcode() == ISD::SHL) {
5439 SDValue InnerZExt = N0.getOperand(0);
5440 // If the original shl may be shifting out bits, do not perform this
5442 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5443 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5444 if (ShAmtVal > KnownZeroBits)
5450 // Ensure that the shift amount is wide enough for the shifted value.
5451 if (VT.getSizeInBits() >= 256)
5452 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5454 return DAG.getNode(N0.getOpcode(), DL, VT,
5455 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5462 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5463 SDValue N0 = N->getOperand(0);
5464 EVT VT = N->getValueType(0);
5466 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5468 return SDValue(Res, 0);
5470 // fold (aext (aext x)) -> (aext x)
5471 // fold (aext (zext x)) -> (zext x)
5472 // fold (aext (sext x)) -> (sext x)
5473 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5474 N0.getOpcode() == ISD::ZERO_EXTEND ||
5475 N0.getOpcode() == ISD::SIGN_EXTEND)
5476 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5478 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5479 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5480 if (N0.getOpcode() == ISD::TRUNCATE) {
5481 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5482 if (NarrowLoad.getNode()) {
5483 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5484 if (NarrowLoad.getNode() != N0.getNode()) {
5485 CombineTo(N0.getNode(), NarrowLoad);
5486 // CombineTo deleted the truncate, if needed, but not what's under it.
5489 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5493 // fold (aext (truncate x))
5494 if (N0.getOpcode() == ISD::TRUNCATE) {
5495 SDValue TruncOp = N0.getOperand(0);
5496 if (TruncOp.getValueType() == VT)
5497 return TruncOp; // x iff x size == zext size.
5498 if (TruncOp.getValueType().bitsGT(VT))
5499 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5500 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5503 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5504 // if the trunc is not free.
5505 if (N0.getOpcode() == ISD::AND &&
5506 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5507 N0.getOperand(1).getOpcode() == ISD::Constant &&
5508 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5509 N0.getValueType())) {
5510 SDValue X = N0.getOperand(0).getOperand(0);
5511 if (X.getValueType().bitsLT(VT)) {
5512 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5513 } else if (X.getValueType().bitsGT(VT)) {
5514 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5516 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5517 Mask = Mask.zext(VT.getSizeInBits());
5518 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5519 X, DAG.getConstant(Mask, VT));
5522 // fold (aext (load x)) -> (aext (truncate (extload x)))
5523 // None of the supported targets knows how to perform load and any_ext
5524 // on vectors in one instruction. We only perform this transformation on
5526 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5527 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5528 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
5529 bool DoXform = true;
5530 SmallVector<SDNode*, 4> SetCCs;
5531 if (!N0.hasOneUse())
5532 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5534 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5535 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5537 LN0->getBasePtr(), N0.getValueType(),
5538 LN0->getMemOperand());
5539 CombineTo(N, ExtLoad);
5540 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5541 N0.getValueType(), ExtLoad);
5542 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5543 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5545 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5549 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5550 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5551 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5552 if (N0.getOpcode() == ISD::LOAD &&
5553 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5555 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5556 ISD::LoadExtType ExtType = LN0->getExtensionType();
5557 EVT MemVT = LN0->getMemoryVT();
5558 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5559 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5560 VT, LN0->getChain(), LN0->getBasePtr(),
5561 MemVT, LN0->getMemOperand());
5562 CombineTo(N, ExtLoad);
5563 CombineTo(N0.getNode(),
5564 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5565 N0.getValueType(), ExtLoad),
5566 ExtLoad.getValue(1));
5567 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5571 if (N0.getOpcode() == ISD::SETCC) {
5573 // aext(setcc) -> vsetcc
5574 // aext(setcc) -> truncate(vsetcc)
5575 // aext(setcc) -> aext(vsetcc)
5576 // Only do this before legalize for now.
5577 if (VT.isVector() && !LegalOperations) {
5578 EVT N0VT = N0.getOperand(0).getValueType();
5579 // We know that the # elements of the results is the same as the
5580 // # elements of the compare (and the # elements of the compare result
5581 // for that matter). Check to see that they are the same size. If so,
5582 // we know that the element size of the sext'd result matches the
5583 // element size of the compare operands.
5584 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5585 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5587 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5588 // If the desired elements are smaller or larger than the source
5589 // elements we can use a matching integer vector type and then
5590 // truncate/any extend
5592 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5594 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5596 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5597 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5601 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5603 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5604 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5605 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5613 /// GetDemandedBits - See if the specified operand can be simplified with the
5614 /// knowledge that only the bits specified by Mask are used. If so, return the
5615 /// simpler operand, otherwise return a null SDValue.
5616 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5617 switch (V.getOpcode()) {
5619 case ISD::Constant: {
5620 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5621 assert(CV && "Const value should be ConstSDNode.");
5622 const APInt &CVal = CV->getAPIntValue();
5623 APInt NewVal = CVal & Mask;
5625 return DAG.getConstant(NewVal, V.getValueType());
5630 // If the LHS or RHS don't contribute bits to the or, drop them.
5631 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5632 return V.getOperand(1);
5633 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5634 return V.getOperand(0);
5637 // Only look at single-use SRLs.
5638 if (!V.getNode()->hasOneUse())
5640 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5641 // See if we can recursively simplify the LHS.
5642 unsigned Amt = RHSC->getZExtValue();
5644 // Watch out for shift count overflow though.
5645 if (Amt >= Mask.getBitWidth()) break;
5646 APInt NewMask = Mask << Amt;
5647 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5648 if (SimplifyLHS.getNode())
5649 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5650 SimplifyLHS, V.getOperand(1));
5656 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5657 /// bits and then truncated to a narrower type and where N is a multiple
5658 /// of number of bits of the narrower type, transform it to a narrower load
5659 /// from address + N / num of bits of new type. If the result is to be
5660 /// extended, also fold the extension to form a extending load.
5661 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5662 unsigned Opc = N->getOpcode();
5664 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5665 SDValue N0 = N->getOperand(0);
5666 EVT VT = N->getValueType(0);
5669 // This transformation isn't valid for vector loads.
5673 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5675 if (Opc == ISD::SIGN_EXTEND_INREG) {
5676 ExtType = ISD::SEXTLOAD;
5677 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5678 } else if (Opc == ISD::SRL) {
5679 // Another special-case: SRL is basically zero-extending a narrower value.
5680 ExtType = ISD::ZEXTLOAD;
5682 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5683 if (!N01) return SDValue();
5684 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5685 VT.getSizeInBits() - N01->getZExtValue());
5687 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5690 unsigned EVTBits = ExtVT.getSizeInBits();
5692 // Do not generate loads of non-round integer types since these can
5693 // be expensive (and would be wrong if the type is not byte sized).
5694 if (!ExtVT.isRound())
5698 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5699 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5700 ShAmt = N01->getZExtValue();
5701 // Is the shift amount a multiple of size of VT?
5702 if ((ShAmt & (EVTBits-1)) == 0) {
5703 N0 = N0.getOperand(0);
5704 // Is the load width a multiple of size of VT?
5705 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5709 // At this point, we must have a load or else we can't do the transform.
5710 if (!isa<LoadSDNode>(N0)) return SDValue();
5712 // Because a SRL must be assumed to *need* to zero-extend the high bits
5713 // (as opposed to anyext the high bits), we can't combine the zextload
5714 // lowering of SRL and an sextload.
5715 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5718 // If the shift amount is larger than the input type then we're not
5719 // accessing any of the loaded bytes. If the load was a zextload/extload
5720 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5721 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5726 // If the load is shifted left (and the result isn't shifted back right),
5727 // we can fold the truncate through the shift.
5728 unsigned ShLeftAmt = 0;
5729 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5730 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5731 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5732 ShLeftAmt = N01->getZExtValue();
5733 N0 = N0.getOperand(0);
5737 // If we haven't found a load, we can't narrow it. Don't transform one with
5738 // multiple uses, this would require adding a new load.
5739 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5742 // Don't change the width of a volatile load.
5743 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5744 if (LN0->isVolatile())
5747 // Verify that we are actually reducing a load width here.
5748 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5751 // For the transform to be legal, the load must produce only two values
5752 // (the value loaded and the chain). Don't transform a pre-increment
5753 // load, for example, which produces an extra value. Otherwise the
5754 // transformation is not equivalent, and the downstream logic to replace
5755 // uses gets things wrong.
5756 if (LN0->getNumValues() > 2)
5759 // If the load that we're shrinking is an extload and we're not just
5760 // discarding the extension we can't simply shrink the load. Bail.
5761 // TODO: It would be possible to merge the extensions in some cases.
5762 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5763 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5766 EVT PtrType = N0.getOperand(1).getValueType();
5768 if (PtrType == MVT::Untyped || PtrType.isExtended())
5769 // It's not possible to generate a constant of extended or untyped type.
5772 // For big endian targets, we need to adjust the offset to the pointer to
5773 // load the correct bytes.
5774 if (TLI.isBigEndian()) {
5775 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5776 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5777 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5780 uint64_t PtrOff = ShAmt / 8;
5781 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5782 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5783 PtrType, LN0->getBasePtr(),
5784 DAG.getConstant(PtrOff, PtrType));
5785 AddToWorklist(NewPtr.getNode());
5788 if (ExtType == ISD::NON_EXTLOAD)
5789 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5790 LN0->getPointerInfo().getWithOffset(PtrOff),
5791 LN0->isVolatile(), LN0->isNonTemporal(),
5792 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5794 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5795 LN0->getPointerInfo().getWithOffset(PtrOff),
5796 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5797 NewAlign, LN0->getTBAAInfo());
5799 // Replace the old load's chain with the new load's chain.
5800 WorklistRemover DeadNodes(*this);
5801 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5803 // Shift the result left, if we've swallowed a left shift.
5804 SDValue Result = Load;
5805 if (ShLeftAmt != 0) {
5806 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5807 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5809 // If the shift amount is as large as the result size (but, presumably,
5810 // no larger than the source) then the useful bits of the result are
5811 // zero; we can't simply return the shortened shift, because the result
5812 // of that operation is undefined.
5813 if (ShLeftAmt >= VT.getSizeInBits())
5814 Result = DAG.getConstant(0, VT);
5816 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5817 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5820 // Return the new loaded value.
5824 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5825 SDValue N0 = N->getOperand(0);
5826 SDValue N1 = N->getOperand(1);
5827 EVT VT = N->getValueType(0);
5828 EVT EVT = cast<VTSDNode>(N1)->getVT();
5829 unsigned VTBits = VT.getScalarType().getSizeInBits();
5830 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5832 // fold (sext_in_reg c1) -> c1
5833 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5834 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5836 // If the input is already sign extended, just drop the extension.
5837 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5840 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5841 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5842 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5843 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5844 N0.getOperand(0), N1);
5846 // fold (sext_in_reg (sext x)) -> (sext x)
5847 // fold (sext_in_reg (aext x)) -> (sext x)
5848 // if x is small enough.
5849 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5850 SDValue N00 = N0.getOperand(0);
5851 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5852 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5853 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5856 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5857 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5858 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5860 // fold operands of sext_in_reg based on knowledge that the top bits are not
5862 if (SimplifyDemandedBits(SDValue(N, 0)))
5863 return SDValue(N, 0);
5865 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5866 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5867 SDValue NarrowLoad = ReduceLoadWidth(N);
5868 if (NarrowLoad.getNode())
5871 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5872 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5873 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5874 if (N0.getOpcode() == ISD::SRL) {
5875 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5876 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5877 // We can turn this into an SRA iff the input to the SRL is already sign
5879 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5880 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5881 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5882 N0.getOperand(0), N0.getOperand(1));
5886 // fold (sext_inreg (extload x)) -> (sextload x)
5887 if (ISD::isEXTLoad(N0.getNode()) &&
5888 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5889 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5890 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5891 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5892 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5893 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5895 LN0->getBasePtr(), EVT,
5896 LN0->getMemOperand());
5897 CombineTo(N, ExtLoad);
5898 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5899 AddToWorklist(ExtLoad.getNode());
5900 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5902 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5903 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5905 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5906 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5907 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5908 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5909 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5911 LN0->getBasePtr(), EVT,
5912 LN0->getMemOperand());
5913 CombineTo(N, ExtLoad);
5914 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5915 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5918 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5919 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5920 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5921 N0.getOperand(1), false);
5922 if (BSwap.getNode())
5923 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5927 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5928 // into a build_vector.
5929 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5930 SmallVector<SDValue, 8> Elts;
5931 unsigned NumElts = N0->getNumOperands();
5932 unsigned ShAmt = VTBits - EVTBits;
5934 for (unsigned i = 0; i != NumElts; ++i) {
5935 SDValue Op = N0->getOperand(i);
5936 if (Op->getOpcode() == ISD::UNDEF) {
5941 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5942 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5943 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5944 Op.getValueType()));
5947 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
5953 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5954 SDValue N0 = N->getOperand(0);
5955 EVT VT = N->getValueType(0);
5956 bool isLE = TLI.isLittleEndian();
5959 if (N0.getValueType() == N->getValueType(0))
5961 // fold (truncate c1) -> c1
5962 if (isa<ConstantSDNode>(N0))
5963 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5964 // fold (truncate (truncate x)) -> (truncate x)
5965 if (N0.getOpcode() == ISD::TRUNCATE)
5966 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5967 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5968 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5969 N0.getOpcode() == ISD::SIGN_EXTEND ||
5970 N0.getOpcode() == ISD::ANY_EXTEND) {
5971 if (N0.getOperand(0).getValueType().bitsLT(VT))
5972 // if the source is smaller than the dest, we still need an extend
5973 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5975 if (N0.getOperand(0).getValueType().bitsGT(VT))
5976 // if the source is larger than the dest, than we just need the truncate
5977 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5978 // if the source and dest are the same type, we can drop both the extend
5979 // and the truncate.
5980 return N0.getOperand(0);
5983 // Fold extract-and-trunc into a narrow extract. For example:
5984 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5985 // i32 y = TRUNCATE(i64 x)
5987 // v16i8 b = BITCAST (v2i64 val)
5988 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5990 // Note: We only run this optimization after type legalization (which often
5991 // creates this pattern) and before operation legalization after which
5992 // we need to be more careful about the vector instructions that we generate.
5993 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5994 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
5996 EVT VecTy = N0.getOperand(0).getValueType();
5997 EVT ExTy = N0.getValueType();
5998 EVT TrTy = N->getValueType(0);
6000 unsigned NumElem = VecTy.getVectorNumElements();
6001 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6003 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6004 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6006 SDValue EltNo = N0->getOperand(1);
6007 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6008 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6009 EVT IndexTy = TLI.getVectorIdxTy();
6010 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6012 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6013 NVT, N0.getOperand(0));
6015 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6017 DAG.getConstant(Index, IndexTy));
6021 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6022 if (N0.getOpcode() == ISD::SELECT) {
6023 EVT SrcVT = N0.getValueType();
6024 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6025 TLI.isTruncateFree(SrcVT, VT)) {
6027 SDValue Cond = N0.getOperand(0);
6028 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6029 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6030 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6034 // Fold a series of buildvector, bitcast, and truncate if possible.
6036 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6037 // (2xi32 (buildvector x, y)).
6038 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6039 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6040 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6041 N0.getOperand(0).hasOneUse()) {
6043 SDValue BuildVect = N0.getOperand(0);
6044 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6045 EVT TruncVecEltTy = VT.getVectorElementType();
6047 // Check that the element types match.
6048 if (BuildVectEltTy == TruncVecEltTy) {
6049 // Now we only need to compute the offset of the truncated elements.
6050 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6051 unsigned TruncVecNumElts = VT.getVectorNumElements();
6052 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6054 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6055 "Invalid number of elements");
6057 SmallVector<SDValue, 8> Opnds;
6058 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6059 Opnds.push_back(BuildVect.getOperand(i));
6061 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6065 // See if we can simplify the input to this truncate through knowledge that
6066 // only the low bits are being used.
6067 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6068 // Currently we only perform this optimization on scalars because vectors
6069 // may have different active low bits.
6070 if (!VT.isVector()) {
6072 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6073 VT.getSizeInBits()));
6074 if (Shorter.getNode())
6075 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6077 // fold (truncate (load x)) -> (smaller load x)
6078 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6079 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6080 SDValue Reduced = ReduceLoadWidth(N);
6081 if (Reduced.getNode())
6083 // Handle the case where the load remains an extending load even
6084 // after truncation.
6085 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6086 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6087 if (!LN0->isVolatile() &&
6088 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6089 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6090 VT, LN0->getChain(), LN0->getBasePtr(),
6092 LN0->getMemOperand());
6093 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6098 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6099 // where ... are all 'undef'.
6100 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6101 SmallVector<EVT, 8> VTs;
6104 unsigned NumDefs = 0;
6106 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6107 SDValue X = N0.getOperand(i);
6108 if (X.getOpcode() != ISD::UNDEF) {
6113 // Stop if more than one members are non-undef.
6116 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6117 VT.getVectorElementType(),
6118 X.getValueType().getVectorNumElements()));
6122 return DAG.getUNDEF(VT);
6125 assert(V.getNode() && "The single defined operand is empty!");
6126 SmallVector<SDValue, 8> Opnds;
6127 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6129 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6132 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6133 AddToWorklist(NV.getNode());
6134 Opnds.push_back(NV);
6136 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6140 // Simplify the operands using demanded-bits information.
6141 if (!VT.isVector() &&
6142 SimplifyDemandedBits(SDValue(N, 0)))
6143 return SDValue(N, 0);
6148 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6149 SDValue Elt = N->getOperand(i);
6150 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6151 return Elt.getNode();
6152 return Elt.getOperand(Elt.getResNo()).getNode();
6155 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6156 /// if load locations are consecutive.
6157 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6158 assert(N->getOpcode() == ISD::BUILD_PAIR);
6160 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6161 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6162 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6163 LD1->getAddressSpace() != LD2->getAddressSpace())
6165 EVT LD1VT = LD1->getValueType(0);
6167 if (ISD::isNON_EXTLoad(LD2) &&
6169 // If both are volatile this would reduce the number of volatile loads.
6170 // If one is volatile it might be ok, but play conservative and bail out.
6171 !LD1->isVolatile() &&
6172 !LD2->isVolatile() &&
6173 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6174 unsigned Align = LD1->getAlignment();
6175 unsigned NewAlign = TLI.getDataLayout()->
6176 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6178 if (NewAlign <= Align &&
6179 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6180 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6181 LD1->getBasePtr(), LD1->getPointerInfo(),
6182 false, false, false, Align);
6188 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6189 SDValue N0 = N->getOperand(0);
6190 EVT VT = N->getValueType(0);
6192 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6193 // Only do this before legalize, since afterward the target may be depending
6194 // on the bitconvert.
6195 // First check to see if this is all constant.
6197 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6199 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6201 EVT DestEltVT = N->getValueType(0).getVectorElementType();
6202 assert(!DestEltVT.isVector() &&
6203 "Element type of vector ValueType must not be vector!");
6205 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6208 // If the input is a constant, let getNode fold it.
6209 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6210 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6211 if (Res.getNode() != N) {
6212 if (!LegalOperations ||
6213 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6216 // Folding it resulted in an illegal node, and it's too late to
6217 // do that. Clean up the old node and forego the transformation.
6218 // Ideally this won't happen very often, because instcombine
6219 // and the earlier dagcombine runs (where illegal nodes are
6220 // permitted) should have folded most of them already.
6221 DAG.DeleteNode(Res.getNode());
6225 // (conv (conv x, t1), t2) -> (conv x, t2)
6226 if (N0.getOpcode() == ISD::BITCAST)
6227 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6230 // fold (conv (load x)) -> (load (conv*)x)
6231 // If the resultant load doesn't need a higher alignment than the original!
6232 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6233 // Do not change the width of a volatile load.
6234 !cast<LoadSDNode>(N0)->isVolatile() &&
6235 // Do not remove the cast if the types differ in endian layout.
6236 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6237 TLI.hasBigEndianPartOrdering(VT) &&
6238 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6239 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6240 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6241 unsigned Align = TLI.getDataLayout()->
6242 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6243 unsigned OrigAlign = LN0->getAlignment();
6245 if (Align <= OrigAlign) {
6246 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6247 LN0->getBasePtr(), LN0->getPointerInfo(),
6248 LN0->isVolatile(), LN0->isNonTemporal(),
6249 LN0->isInvariant(), OrigAlign,
6250 LN0->getTBAAInfo());
6252 CombineTo(N0.getNode(),
6253 DAG.getNode(ISD::BITCAST, SDLoc(N0),
6254 N0.getValueType(), Load),
6260 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6261 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6262 // This often reduces constant pool loads.
6263 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6264 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6265 N0.getNode()->hasOneUse() && VT.isInteger() &&
6266 !VT.isVector() && !N0.getValueType().isVector()) {
6267 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6269 AddToWorklist(NewConv.getNode());
6271 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6272 if (N0.getOpcode() == ISD::FNEG)
6273 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6274 NewConv, DAG.getConstant(SignBit, VT));
6275 assert(N0.getOpcode() == ISD::FABS);
6276 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6277 NewConv, DAG.getConstant(~SignBit, VT));
6280 // fold (bitconvert (fcopysign cst, x)) ->
6281 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6282 // Note that we don't handle (copysign x, cst) because this can always be
6283 // folded to an fneg or fabs.
6284 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6285 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6286 VT.isInteger() && !VT.isVector()) {
6287 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6288 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6289 if (isTypeLegal(IntXVT)) {
6290 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6291 IntXVT, N0.getOperand(1));
6292 AddToWorklist(X.getNode());
6294 // If X has a different width than the result/lhs, sext it or truncate it.
6295 unsigned VTWidth = VT.getSizeInBits();
6296 if (OrigXWidth < VTWidth) {
6297 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6298 AddToWorklist(X.getNode());
6299 } else if (OrigXWidth > VTWidth) {
6300 // To get the sign bit in the right place, we have to shift it right
6301 // before truncating.
6302 X = DAG.getNode(ISD::SRL, SDLoc(X),
6303 X.getValueType(), X,
6304 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6305 AddToWorklist(X.getNode());
6306 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6307 AddToWorklist(X.getNode());
6310 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6311 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6312 X, DAG.getConstant(SignBit, VT));
6313 AddToWorklist(X.getNode());
6315 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6316 VT, N0.getOperand(0));
6317 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6318 Cst, DAG.getConstant(~SignBit, VT));
6319 AddToWorklist(Cst.getNode());
6321 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6325 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6326 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6327 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6328 if (CombineLD.getNode())
6335 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6336 EVT VT = N->getValueType(0);
6337 return CombineConsecutiveLoads(N, VT);
6340 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6341 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
6342 /// destination element value type.
6343 SDValue DAGCombiner::
6344 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6345 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6347 // If this is already the right type, we're done.
6348 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6350 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6351 unsigned DstBitSize = DstEltVT.getSizeInBits();
6353 // If this is a conversion of N elements of one type to N elements of another
6354 // type, convert each element. This handles FP<->INT cases.
6355 if (SrcBitSize == DstBitSize) {
6356 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6357 BV->getValueType(0).getVectorNumElements());
6359 // Due to the FP element handling below calling this routine recursively,
6360 // we can end up with a scalar-to-vector node here.
6361 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6362 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6363 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6364 DstEltVT, BV->getOperand(0)));
6366 SmallVector<SDValue, 8> Ops;
6367 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6368 SDValue Op = BV->getOperand(i);
6369 // If the vector element type is not legal, the BUILD_VECTOR operands
6370 // are promoted and implicitly truncated. Make that explicit here.
6371 if (Op.getValueType() != SrcEltVT)
6372 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6373 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6375 AddToWorklist(Ops.back().getNode());
6377 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6380 // Otherwise, we're growing or shrinking the elements. To avoid having to
6381 // handle annoying details of growing/shrinking FP values, we convert them to
6383 if (SrcEltVT.isFloatingPoint()) {
6384 // Convert the input float vector to a int vector where the elements are the
6386 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6387 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6388 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6392 // Now we know the input is an integer vector. If the output is a FP type,
6393 // convert to integer first, then to FP of the right size.
6394 if (DstEltVT.isFloatingPoint()) {
6395 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6396 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6397 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6399 // Next, convert to FP elements of the same size.
6400 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6403 // Okay, we know the src/dst types are both integers of differing types.
6404 // Handling growing first.
6405 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6406 if (SrcBitSize < DstBitSize) {
6407 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6409 SmallVector<SDValue, 8> Ops;
6410 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6411 i += NumInputsPerOutput) {
6412 bool isLE = TLI.isLittleEndian();
6413 APInt NewBits = APInt(DstBitSize, 0);
6414 bool EltIsUndef = true;
6415 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6416 // Shift the previously computed bits over.
6417 NewBits <<= SrcBitSize;
6418 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6419 if (Op.getOpcode() == ISD::UNDEF) continue;
6422 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6423 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6427 Ops.push_back(DAG.getUNDEF(DstEltVT));
6429 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6432 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6433 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6436 // Finally, this must be the case where we are shrinking elements: each input
6437 // turns into multiple outputs.
6438 bool isS2V = ISD::isScalarToVector(BV);
6439 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6440 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6441 NumOutputsPerInput*BV->getNumOperands());
6442 SmallVector<SDValue, 8> Ops;
6444 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6445 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6446 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6447 Ops.push_back(DAG.getUNDEF(DstEltVT));
6451 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6452 getAPIntValue().zextOrTrunc(SrcBitSize);
6454 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6455 APInt ThisVal = OpVal.trunc(DstBitSize);
6456 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6457 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6458 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6459 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6461 OpVal = OpVal.lshr(DstBitSize);
6464 // For big endian targets, swap the order of the pieces of each element.
6465 if (TLI.isBigEndian())
6466 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6469 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6472 SDValue DAGCombiner::visitFADD(SDNode *N) {
6473 SDValue N0 = N->getOperand(0);
6474 SDValue N1 = N->getOperand(1);
6475 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6476 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6477 EVT VT = N->getValueType(0);
6480 if (VT.isVector()) {
6481 SDValue FoldedVOp = SimplifyVBinOp(N);
6482 if (FoldedVOp.getNode()) return FoldedVOp;
6485 // fold (fadd c1, c2) -> c1 + c2
6487 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6488 // canonicalize constant to RHS
6489 if (N0CFP && !N1CFP)
6490 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6491 // fold (fadd A, 0) -> A
6492 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6493 N1CFP->getValueAPF().isZero())
6495 // fold (fadd A, (fneg B)) -> (fsub A, B)
6496 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6497 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6498 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6499 GetNegatedExpression(N1, DAG, LegalOperations));
6500 // fold (fadd (fneg A), B) -> (fsub B, A)
6501 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6502 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6503 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6504 GetNegatedExpression(N0, DAG, LegalOperations));
6506 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6507 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6508 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6509 isa<ConstantFPSDNode>(N0.getOperand(1)))
6510 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6511 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6512 N0.getOperand(1), N1));
6514 // No FP constant should be created after legalization as Instruction
6515 // Selection pass has hard time in dealing with FP constant.
6517 // We don't need test this condition for transformation like following, as
6518 // the DAG being transformed implies it is legal to take FP constant as
6521 // (fadd (fmul c, x), x) -> (fmul c+1, x)
6523 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6525 // If allow, fold (fadd (fneg x), x) -> 0.0
6526 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6527 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6528 return DAG.getConstantFP(0.0, VT);
6530 // If allow, fold (fadd x, (fneg x)) -> 0.0
6531 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6532 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6533 return DAG.getConstantFP(0.0, VT);
6535 // In unsafe math mode, we can fold chains of FADD's of the same value
6536 // into multiplications. This transform is not safe in general because
6537 // we are reducing the number of rounding steps.
6538 if (DAG.getTarget().Options.UnsafeFPMath &&
6539 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6541 if (N0.getOpcode() == ISD::FMUL) {
6542 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6543 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6545 // (fadd (fmul c, x), x) -> (fmul x, c+1)
6546 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6547 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6549 DAG.getConstantFP(1.0, VT));
6550 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6554 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6555 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6556 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6558 DAG.getConstantFP(1.0, VT));
6559 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6563 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6564 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6565 N1.getOperand(0) == N1.getOperand(1) &&
6566 N0.getOperand(1) == N1.getOperand(0)) {
6567 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6569 DAG.getConstantFP(2.0, VT));
6570 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6571 N0.getOperand(1), NewCFP);
6574 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6575 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6576 N1.getOperand(0) == N1.getOperand(1) &&
6577 N0.getOperand(0) == N1.getOperand(0)) {
6578 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6580 DAG.getConstantFP(2.0, VT));
6581 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6582 N0.getOperand(0), NewCFP);
6586 if (N1.getOpcode() == ISD::FMUL) {
6587 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6588 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6590 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6591 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6592 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6594 DAG.getConstantFP(1.0, VT));
6595 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6599 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6600 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6601 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6603 DAG.getConstantFP(1.0, VT));
6604 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6609 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6610 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6611 N0.getOperand(0) == N0.getOperand(1) &&
6612 N1.getOperand(1) == N0.getOperand(0)) {
6613 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6615 DAG.getConstantFP(2.0, VT));
6616 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6617 N1.getOperand(1), NewCFP);
6620 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6621 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6622 N0.getOperand(0) == N0.getOperand(1) &&
6623 N1.getOperand(0) == N0.getOperand(0)) {
6624 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6626 DAG.getConstantFP(2.0, VT));
6627 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6628 N1.getOperand(0), NewCFP);
6632 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6633 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6634 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6635 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6636 (N0.getOperand(0) == N1))
6637 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6638 N1, DAG.getConstantFP(3.0, VT));
6641 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6642 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6643 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6644 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6645 N1.getOperand(0) == N0)
6646 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6647 N0, DAG.getConstantFP(3.0, VT));
6650 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6651 if (AllowNewFpConst &&
6652 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6653 N0.getOperand(0) == N0.getOperand(1) &&
6654 N1.getOperand(0) == N1.getOperand(1) &&
6655 N0.getOperand(0) == N1.getOperand(0))
6656 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6658 DAG.getConstantFP(4.0, VT));
6661 // FADD -> FMA combines:
6662 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6663 DAG.getTarget().Options.UnsafeFPMath) &&
6664 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6665 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6667 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6668 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6669 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6670 N0.getOperand(0), N0.getOperand(1), N1);
6672 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6673 // Note: Commutes FADD operands.
6674 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6675 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6676 N1.getOperand(0), N1.getOperand(1), N0);
6682 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6683 SDValue N0 = N->getOperand(0);
6684 SDValue N1 = N->getOperand(1);
6685 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6686 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6687 EVT VT = N->getValueType(0);
6691 if (VT.isVector()) {
6692 SDValue FoldedVOp = SimplifyVBinOp(N);
6693 if (FoldedVOp.getNode()) return FoldedVOp;
6696 // fold (fsub c1, c2) -> c1-c2
6698 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6699 // fold (fsub A, 0) -> A
6700 if (DAG.getTarget().Options.UnsafeFPMath &&
6701 N1CFP && N1CFP->getValueAPF().isZero())
6703 // fold (fsub 0, B) -> -B
6704 if (DAG.getTarget().Options.UnsafeFPMath &&
6705 N0CFP && N0CFP->getValueAPF().isZero()) {
6706 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6707 return GetNegatedExpression(N1, DAG, LegalOperations);
6708 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6709 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6711 // fold (fsub A, (fneg B)) -> (fadd A, B)
6712 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6713 return DAG.getNode(ISD::FADD, dl, VT, N0,
6714 GetNegatedExpression(N1, DAG, LegalOperations));
6716 // If 'unsafe math' is enabled, fold
6717 // (fsub x, x) -> 0.0 &
6718 // (fsub x, (fadd x, y)) -> (fneg y) &
6719 // (fsub x, (fadd y, x)) -> (fneg y)
6720 if (DAG.getTarget().Options.UnsafeFPMath) {
6722 return DAG.getConstantFP(0.0f, VT);
6724 if (N1.getOpcode() == ISD::FADD) {
6725 SDValue N10 = N1->getOperand(0);
6726 SDValue N11 = N1->getOperand(1);
6728 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6729 &DAG.getTarget().Options))
6730 return GetNegatedExpression(N11, DAG, LegalOperations);
6732 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6733 &DAG.getTarget().Options))
6734 return GetNegatedExpression(N10, DAG, LegalOperations);
6738 // FSUB -> FMA combines:
6739 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6740 DAG.getTarget().Options.UnsafeFPMath) &&
6741 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6742 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6744 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6745 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6746 return DAG.getNode(ISD::FMA, dl, VT,
6747 N0.getOperand(0), N0.getOperand(1),
6748 DAG.getNode(ISD::FNEG, dl, VT, N1));
6750 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6751 // Note: Commutes FSUB operands.
6752 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6753 return DAG.getNode(ISD::FMA, dl, VT,
6754 DAG.getNode(ISD::FNEG, dl, VT,
6756 N1.getOperand(1), N0);
6758 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6759 if (N0.getOpcode() == ISD::FNEG &&
6760 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6761 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6762 SDValue N00 = N0.getOperand(0).getOperand(0);
6763 SDValue N01 = N0.getOperand(0).getOperand(1);
6764 return DAG.getNode(ISD::FMA, dl, VT,
6765 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6766 DAG.getNode(ISD::FNEG, dl, VT, N1));
6773 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6774 SDValue N0 = N->getOperand(0);
6775 SDValue N1 = N->getOperand(1);
6776 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6777 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6778 EVT VT = N->getValueType(0);
6779 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6782 if (VT.isVector()) {
6783 SDValue FoldedVOp = SimplifyVBinOp(N);
6784 if (FoldedVOp.getNode()) return FoldedVOp;
6787 // fold (fmul c1, c2) -> c1*c2
6789 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6790 // canonicalize constant to RHS
6791 if (N0CFP && !N1CFP)
6792 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6793 // fold (fmul A, 0) -> 0
6794 if (DAG.getTarget().Options.UnsafeFPMath &&
6795 N1CFP && N1CFP->getValueAPF().isZero())
6797 // fold (fmul A, 0) -> 0, vector edition.
6798 if (DAG.getTarget().Options.UnsafeFPMath &&
6799 ISD::isBuildVectorAllZeros(N1.getNode()))
6801 // fold (fmul A, 1.0) -> A
6802 if (N1CFP && N1CFP->isExactlyValue(1.0))
6804 // fold (fmul X, 2.0) -> (fadd X, X)
6805 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6806 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6807 // fold (fmul X, -1.0) -> (fneg X)
6808 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6809 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6810 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6812 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6813 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6814 &DAG.getTarget().Options)) {
6815 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6816 &DAG.getTarget().Options)) {
6817 // Both can be negated for free, check to see if at least one is cheaper
6819 if (LHSNeg == 2 || RHSNeg == 2)
6820 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6821 GetNegatedExpression(N0, DAG, LegalOperations),
6822 GetNegatedExpression(N1, DAG, LegalOperations));
6826 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6827 if (DAG.getTarget().Options.UnsafeFPMath &&
6828 N1CFP && N0.getOpcode() == ISD::FMUL &&
6829 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6830 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6831 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6832 N0.getOperand(1), N1));
6837 SDValue DAGCombiner::visitFMA(SDNode *N) {
6838 SDValue N0 = N->getOperand(0);
6839 SDValue N1 = N->getOperand(1);
6840 SDValue N2 = N->getOperand(2);
6841 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6842 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6843 EVT VT = N->getValueType(0);
6846 if (DAG.getTarget().Options.UnsafeFPMath) {
6847 if (N0CFP && N0CFP->isZero())
6849 if (N1CFP && N1CFP->isZero())
6852 if (N0CFP && N0CFP->isExactlyValue(1.0))
6853 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6854 if (N1CFP && N1CFP->isExactlyValue(1.0))
6855 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6857 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6858 if (N0CFP && !N1CFP)
6859 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6861 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6862 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6863 N2.getOpcode() == ISD::FMUL &&
6864 N0 == N2.getOperand(0) &&
6865 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6866 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6867 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6871 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6872 if (DAG.getTarget().Options.UnsafeFPMath &&
6873 N0.getOpcode() == ISD::FMUL && N1CFP &&
6874 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6875 return DAG.getNode(ISD::FMA, dl, VT,
6877 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6881 // (fma x, 1, y) -> (fadd x, y)
6882 // (fma x, -1, y) -> (fadd (fneg x), y)
6884 if (N1CFP->isExactlyValue(1.0))
6885 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6887 if (N1CFP->isExactlyValue(-1.0) &&
6888 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6889 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6890 AddToWorklist(RHSNeg.getNode());
6891 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6895 // (fma x, c, x) -> (fmul x, (c+1))
6896 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6897 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6898 DAG.getNode(ISD::FADD, dl, VT,
6899 N1, DAG.getConstantFP(1.0, VT)));
6901 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6902 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6903 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6904 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6905 DAG.getNode(ISD::FADD, dl, VT,
6906 N1, DAG.getConstantFP(-1.0, VT)));
6912 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6913 SDValue N0 = N->getOperand(0);
6914 SDValue N1 = N->getOperand(1);
6915 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6916 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6917 EVT VT = N->getValueType(0);
6918 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6921 if (VT.isVector()) {
6922 SDValue FoldedVOp = SimplifyVBinOp(N);
6923 if (FoldedVOp.getNode()) return FoldedVOp;
6926 // fold (fdiv c1, c2) -> c1/c2
6928 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6930 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6931 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6932 // Compute the reciprocal 1.0 / c2.
6933 APFloat N1APF = N1CFP->getValueAPF();
6934 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6935 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6936 // Only do the transform if the reciprocal is a legal fp immediate that
6937 // isn't too nasty (eg NaN, denormal, ...).
6938 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6939 (!LegalOperations ||
6940 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6941 // backend)... we should handle this gracefully after Legalize.
6942 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6943 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6944 TLI.isFPImmLegal(Recip, VT)))
6945 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6946 DAG.getConstantFP(Recip, VT));
6949 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6950 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6951 &DAG.getTarget().Options)) {
6952 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6953 &DAG.getTarget().Options)) {
6954 // Both can be negated for free, check to see if at least one is cheaper
6956 if (LHSNeg == 2 || RHSNeg == 2)
6957 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6958 GetNegatedExpression(N0, DAG, LegalOperations),
6959 GetNegatedExpression(N1, DAG, LegalOperations));
6966 SDValue DAGCombiner::visitFREM(SDNode *N) {
6967 SDValue N0 = N->getOperand(0);
6968 SDValue N1 = N->getOperand(1);
6969 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6970 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6971 EVT VT = N->getValueType(0);
6973 // fold (frem c1, c2) -> fmod(c1,c2)
6975 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6980 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6981 SDValue N0 = N->getOperand(0);
6982 SDValue N1 = N->getOperand(1);
6983 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6984 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6985 EVT VT = N->getValueType(0);
6987 if (N0CFP && N1CFP) // Constant fold
6988 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6991 const APFloat& V = N1CFP->getValueAPF();
6992 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6993 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6994 if (!V.isNegative()) {
6995 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6996 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6998 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6999 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7000 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7004 // copysign(fabs(x), y) -> copysign(x, y)
7005 // copysign(fneg(x), y) -> copysign(x, y)
7006 // copysign(copysign(x,z), y) -> copysign(x, y)
7007 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7008 N0.getOpcode() == ISD::FCOPYSIGN)
7009 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7010 N0.getOperand(0), N1);
7012 // copysign(x, abs(y)) -> abs(x)
7013 if (N1.getOpcode() == ISD::FABS)
7014 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7016 // copysign(x, copysign(y,z)) -> copysign(x, z)
7017 if (N1.getOpcode() == ISD::FCOPYSIGN)
7018 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7019 N0, N1.getOperand(1));
7021 // copysign(x, fp_extend(y)) -> copysign(x, y)
7022 // copysign(x, fp_round(y)) -> copysign(x, y)
7023 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7024 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7025 N0, N1.getOperand(0));
7030 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7031 SDValue N0 = N->getOperand(0);
7032 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7033 EVT VT = N->getValueType(0);
7034 EVT OpVT = N0.getValueType();
7036 // fold (sint_to_fp c1) -> c1fp
7038 // ...but only if the target supports immediate floating-point values
7039 (!LegalOperations ||
7040 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7041 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7043 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7044 // but UINT_TO_FP is legal on this target, try to convert.
7045 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7046 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7047 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7048 if (DAG.SignBitIsZero(N0))
7049 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7052 // The next optimizations are desirable only if SELECT_CC can be lowered.
7053 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7054 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7055 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7057 (!LegalOperations ||
7058 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7060 { N0.getOperand(0), N0.getOperand(1),
7061 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7063 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7066 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7067 // (select_cc x, y, 1.0, 0.0,, cc)
7068 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7069 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7070 (!LegalOperations ||
7071 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7073 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7074 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7075 N0.getOperand(0).getOperand(2) };
7076 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7083 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7084 SDValue N0 = N->getOperand(0);
7085 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7086 EVT VT = N->getValueType(0);
7087 EVT OpVT = N0.getValueType();
7089 // fold (uint_to_fp c1) -> c1fp
7091 // ...but only if the target supports immediate floating-point values
7092 (!LegalOperations ||
7093 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7094 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7096 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7097 // but SINT_TO_FP is legal on this target, try to convert.
7098 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7099 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7100 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7101 if (DAG.SignBitIsZero(N0))
7102 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7105 // The next optimizations are desirable only if SELECT_CC can be lowered.
7106 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7107 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7109 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7110 (!LegalOperations ||
7111 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7113 { N0.getOperand(0), N0.getOperand(1),
7114 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7116 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7123 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7124 SDValue N0 = N->getOperand(0);
7125 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7126 EVT VT = N->getValueType(0);
7128 // fold (fp_to_sint c1fp) -> c1
7130 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7135 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7136 SDValue N0 = N->getOperand(0);
7137 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7138 EVT VT = N->getValueType(0);
7140 // fold (fp_to_uint c1fp) -> c1
7142 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7147 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7148 SDValue N0 = N->getOperand(0);
7149 SDValue N1 = N->getOperand(1);
7150 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7151 EVT VT = N->getValueType(0);
7153 // fold (fp_round c1fp) -> c1fp
7155 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7157 // fold (fp_round (fp_extend x)) -> x
7158 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7159 return N0.getOperand(0);
7161 // fold (fp_round (fp_round x)) -> (fp_round x)
7162 if (N0.getOpcode() == ISD::FP_ROUND) {
7163 // This is a value preserving truncation if both round's are.
7164 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7165 N0.getNode()->getConstantOperandVal(1) == 1;
7166 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7167 DAG.getIntPtrConstant(IsTrunc));
7170 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7171 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7172 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7173 N0.getOperand(0), N1);
7174 AddToWorklist(Tmp.getNode());
7175 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7176 Tmp, N0.getOperand(1));
7182 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7183 SDValue N0 = N->getOperand(0);
7184 EVT VT = N->getValueType(0);
7185 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7186 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7188 // fold (fp_round_inreg c1fp) -> c1fp
7189 if (N0CFP && isTypeLegal(EVT)) {
7190 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7191 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7197 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7198 SDValue N0 = N->getOperand(0);
7199 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7200 EVT VT = N->getValueType(0);
7202 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7203 if (N->hasOneUse() &&
7204 N->use_begin()->getOpcode() == ISD::FP_ROUND)
7207 // fold (fp_extend c1fp) -> c1fp
7209 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7211 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7213 if (N0.getOpcode() == ISD::FP_ROUND
7214 && N0.getNode()->getConstantOperandVal(1) == 1) {
7215 SDValue In = N0.getOperand(0);
7216 if (In.getValueType() == VT) return In;
7217 if (VT.bitsLT(In.getValueType()))
7218 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7219 In, N0.getOperand(1));
7220 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7223 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7224 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7225 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
7226 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7227 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7229 LN0->getBasePtr(), N0.getValueType(),
7230 LN0->getMemOperand());
7231 CombineTo(N, ExtLoad);
7232 CombineTo(N0.getNode(),
7233 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7234 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7235 ExtLoad.getValue(1));
7236 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7242 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7243 SDValue N0 = N->getOperand(0);
7244 EVT VT = N->getValueType(0);
7246 if (VT.isVector()) {
7247 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7248 if (FoldedVOp.getNode()) return FoldedVOp;
7251 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7252 &DAG.getTarget().Options))
7253 return GetNegatedExpression(N0, DAG, LegalOperations);
7255 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7256 // constant pool values.
7257 // TODO: We can also optimize for vectors here, but we need to make sure
7258 // that the sign mask is created properly for each vector element.
7259 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7261 N0.getNode()->hasOneUse() &&
7262 N0.getOperand(0).getValueType().isInteger()) {
7263 SDValue Int = N0.getOperand(0);
7264 EVT IntVT = Int.getValueType();
7265 if (IntVT.isInteger() && !IntVT.isVector()) {
7266 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7267 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7268 AddToWorklist(Int.getNode());
7269 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7274 // (fneg (fmul c, x)) -> (fmul -c, x)
7275 if (N0.getOpcode() == ISD::FMUL) {
7276 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7278 APFloat CVal = CFP1->getValueAPF();
7280 if (Level >= AfterLegalizeDAG &&
7281 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7282 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7284 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7285 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7292 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7293 SDValue N0 = N->getOperand(0);
7294 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7295 EVT VT = N->getValueType(0);
7297 // fold (fceil c1) -> fceil(c1)
7299 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7304 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7305 SDValue N0 = N->getOperand(0);
7306 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7307 EVT VT = N->getValueType(0);
7309 // fold (ftrunc c1) -> ftrunc(c1)
7311 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7316 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7317 SDValue N0 = N->getOperand(0);
7318 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7319 EVT VT = N->getValueType(0);
7321 // fold (ffloor c1) -> ffloor(c1)
7323 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7328 SDValue DAGCombiner::visitFABS(SDNode *N) {
7329 SDValue N0 = N->getOperand(0);
7330 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7331 EVT VT = N->getValueType(0);
7333 if (VT.isVector()) {
7334 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7335 if (FoldedVOp.getNode()) return FoldedVOp;
7338 // fold (fabs c1) -> fabs(c1)
7340 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7341 // fold (fabs (fabs x)) -> (fabs x)
7342 if (N0.getOpcode() == ISD::FABS)
7343 return N->getOperand(0);
7344 // fold (fabs (fneg x)) -> (fabs x)
7345 // fold (fabs (fcopysign x, y)) -> (fabs x)
7346 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7347 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7349 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7350 // constant pool values.
7351 // TODO: We can also optimize for vectors here, but we need to make sure
7352 // that the sign mask is created properly for each vector element.
7353 if (!TLI.isFAbsFree(VT) &&
7354 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7355 N0.getOperand(0).getValueType().isInteger() &&
7357 SDValue Int = N0.getOperand(0);
7358 EVT IntVT = Int.getValueType();
7359 if (IntVT.isInteger() && !IntVT.isVector()) {
7360 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7361 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7362 AddToWorklist(Int.getNode());
7363 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7364 N->getValueType(0), Int);
7371 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7372 SDValue Chain = N->getOperand(0);
7373 SDValue N1 = N->getOperand(1);
7374 SDValue N2 = N->getOperand(2);
7376 // If N is a constant we could fold this into a fallthrough or unconditional
7377 // branch. However that doesn't happen very often in normal code, because
7378 // Instcombine/SimplifyCFG should have handled the available opportunities.
7379 // If we did this folding here, it would be necessary to update the
7380 // MachineBasicBlock CFG, which is awkward.
7382 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7384 if (N1.getOpcode() == ISD::SETCC &&
7385 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7386 N1.getOperand(0).getValueType())) {
7387 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7388 Chain, N1.getOperand(2),
7389 N1.getOperand(0), N1.getOperand(1), N2);
7392 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7393 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7394 (N1.getOperand(0).hasOneUse() &&
7395 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7396 SDNode *Trunc = nullptr;
7397 if (N1.getOpcode() == ISD::TRUNCATE) {
7398 // Look pass the truncate.
7399 Trunc = N1.getNode();
7400 N1 = N1.getOperand(0);
7403 // Match this pattern so that we can generate simpler code:
7406 // %b = and i32 %a, 2
7407 // %c = srl i32 %b, 1
7408 // brcond i32 %c ...
7413 // %b = and i32 %a, 2
7414 // %c = setcc eq %b, 0
7417 // This applies only when the AND constant value has one bit set and the
7418 // SRL constant is equal to the log2 of the AND constant. The back-end is
7419 // smart enough to convert the result into a TEST/JMP sequence.
7420 SDValue Op0 = N1.getOperand(0);
7421 SDValue Op1 = N1.getOperand(1);
7423 if (Op0.getOpcode() == ISD::AND &&
7424 Op1.getOpcode() == ISD::Constant) {
7425 SDValue AndOp1 = Op0.getOperand(1);
7427 if (AndOp1.getOpcode() == ISD::Constant) {
7428 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7430 if (AndConst.isPowerOf2() &&
7431 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7433 DAG.getSetCC(SDLoc(N),
7434 getSetCCResultType(Op0.getValueType()),
7435 Op0, DAG.getConstant(0, Op0.getValueType()),
7438 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7439 MVT::Other, Chain, SetCC, N2);
7440 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7441 // will convert it back to (X & C1) >> C2.
7442 CombineTo(N, NewBRCond, false);
7443 // Truncate is dead.
7445 removeFromWorklist(Trunc);
7446 DAG.DeleteNode(Trunc);
7448 // Replace the uses of SRL with SETCC
7449 WorklistRemover DeadNodes(*this);
7450 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7451 removeFromWorklist(N1.getNode());
7452 DAG.DeleteNode(N1.getNode());
7453 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7459 // Restore N1 if the above transformation doesn't match.
7460 N1 = N->getOperand(1);
7463 // Transform br(xor(x, y)) -> br(x != y)
7464 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7465 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7466 SDNode *TheXor = N1.getNode();
7467 SDValue Op0 = TheXor->getOperand(0);
7468 SDValue Op1 = TheXor->getOperand(1);
7469 if (Op0.getOpcode() == Op1.getOpcode()) {
7470 // Avoid missing important xor optimizations.
7471 SDValue Tmp = visitXOR(TheXor);
7472 if (Tmp.getNode()) {
7473 if (Tmp.getNode() != TheXor) {
7474 DEBUG(dbgs() << "\nReplacing.8 ";
7476 dbgs() << "\nWith: ";
7477 Tmp.getNode()->dump(&DAG);
7479 WorklistRemover DeadNodes(*this);
7480 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7481 removeFromWorklist(TheXor);
7482 DAG.DeleteNode(TheXor);
7483 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7484 MVT::Other, Chain, Tmp, N2);
7487 // visitXOR has changed XOR's operands or replaced the XOR completely,
7489 return SDValue(N, 0);
7493 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7495 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7496 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7497 Op0.getOpcode() == ISD::XOR) {
7498 TheXor = Op0.getNode();
7502 EVT SetCCVT = N1.getValueType();
7504 SetCCVT = getSetCCResultType(SetCCVT);
7505 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7508 Equal ? ISD::SETEQ : ISD::SETNE);
7509 // Replace the uses of XOR with SETCC
7510 WorklistRemover DeadNodes(*this);
7511 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7512 removeFromWorklist(N1.getNode());
7513 DAG.DeleteNode(N1.getNode());
7514 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7515 MVT::Other, Chain, SetCC, N2);
7522 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7524 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7525 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7526 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7528 // If N is a constant we could fold this into a fallthrough or unconditional
7529 // branch. However that doesn't happen very often in normal code, because
7530 // Instcombine/SimplifyCFG should have handled the available opportunities.
7531 // If we did this folding here, it would be necessary to update the
7532 // MachineBasicBlock CFG, which is awkward.
7534 // Use SimplifySetCC to simplify SETCC's.
7535 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7536 CondLHS, CondRHS, CC->get(), SDLoc(N),
7538 if (Simp.getNode()) AddToWorklist(Simp.getNode());
7540 // fold to a simpler setcc
7541 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7542 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7543 N->getOperand(0), Simp.getOperand(2),
7544 Simp.getOperand(0), Simp.getOperand(1),
7550 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7551 /// uses N as its base pointer and that N may be folded in the load / store
7552 /// addressing mode.
7553 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7555 const TargetLowering &TLI) {
7557 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7558 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7560 VT = Use->getValueType(0);
7561 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7562 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7564 VT = ST->getValue().getValueType();
7568 TargetLowering::AddrMode AM;
7569 if (N->getOpcode() == ISD::ADD) {
7570 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7573 AM.BaseOffs = Offset->getSExtValue();
7577 } else if (N->getOpcode() == ISD::SUB) {
7578 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7581 AM.BaseOffs = -Offset->getSExtValue();
7588 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7591 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7592 /// pre-indexed load / store when the base pointer is an add or subtract
7593 /// and it has other uses besides the load / store. After the
7594 /// transformation, the new indexed load / store has effectively folded
7595 /// the add / subtract in and all of its other uses are redirected to the
7596 /// new load / store.
7597 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7598 if (Level < AfterLegalizeDAG)
7604 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7605 if (LD->isIndexed())
7607 VT = LD->getMemoryVT();
7608 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7609 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7611 Ptr = LD->getBasePtr();
7612 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7613 if (ST->isIndexed())
7615 VT = ST->getMemoryVT();
7616 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7617 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7619 Ptr = ST->getBasePtr();
7625 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7626 // out. There is no reason to make this a preinc/predec.
7627 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7628 Ptr.getNode()->hasOneUse())
7631 // Ask the target to do addressing mode selection.
7634 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7635 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7638 // Backends without true r+i pre-indexed forms may need to pass a
7639 // constant base with a variable offset so that constant coercion
7640 // will work with the patterns in canonical form.
7641 bool Swapped = false;
7642 if (isa<ConstantSDNode>(BasePtr)) {
7643 std::swap(BasePtr, Offset);
7647 // Don't create a indexed load / store with zero offset.
7648 if (isa<ConstantSDNode>(Offset) &&
7649 cast<ConstantSDNode>(Offset)->isNullValue())
7652 // Try turning it into a pre-indexed load / store except when:
7653 // 1) The new base ptr is a frame index.
7654 // 2) If N is a store and the new base ptr is either the same as or is a
7655 // predecessor of the value being stored.
7656 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7657 // that would create a cycle.
7658 // 4) All uses are load / store ops that use it as old base ptr.
7660 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7661 // (plus the implicit offset) to a register to preinc anyway.
7662 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7667 SDValue Val = cast<StoreSDNode>(N)->getValue();
7668 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7672 // If the offset is a constant, there may be other adds of constants that
7673 // can be folded with this one. We should do this to avoid having to keep
7674 // a copy of the original base pointer.
7675 SmallVector<SDNode *, 16> OtherUses;
7676 if (isa<ConstantSDNode>(Offset))
7677 for (SDNode *Use : BasePtr.getNode()->uses()) {
7678 if (Use == Ptr.getNode())
7681 if (Use->isPredecessorOf(N))
7684 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7689 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7690 if (Op1.getNode() == BasePtr.getNode())
7691 std::swap(Op0, Op1);
7692 assert(Op0.getNode() == BasePtr.getNode() &&
7693 "Use of ADD/SUB but not an operand");
7695 if (!isa<ConstantSDNode>(Op1)) {
7700 // FIXME: In some cases, we can be smarter about this.
7701 if (Op1.getValueType() != Offset.getValueType()) {
7706 OtherUses.push_back(Use);
7710 std::swap(BasePtr, Offset);
7712 // Now check for #3 and #4.
7713 bool RealUse = false;
7715 // Caches for hasPredecessorHelper
7716 SmallPtrSet<const SDNode *, 32> Visited;
7717 SmallVector<const SDNode *, 16> Worklist;
7719 for (SDNode *Use : Ptr.getNode()->uses()) {
7722 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7725 // If Ptr may be folded in addressing mode of other use, then it's
7726 // not profitable to do this transformation.
7727 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7736 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7737 BasePtr, Offset, AM);
7739 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7740 BasePtr, Offset, AM);
7743 DEBUG(dbgs() << "\nReplacing.4 ";
7745 dbgs() << "\nWith: ";
7746 Result.getNode()->dump(&DAG);
7748 WorklistRemover DeadNodes(*this);
7750 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7751 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7753 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7756 // Finally, since the node is now dead, remove it from the graph.
7760 std::swap(BasePtr, Offset);
7762 // Replace other uses of BasePtr that can be updated to use Ptr
7763 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7764 unsigned OffsetIdx = 1;
7765 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7767 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7768 BasePtr.getNode() && "Expected BasePtr operand");
7770 // We need to replace ptr0 in the following expression:
7771 // x0 * offset0 + y0 * ptr0 = t0
7773 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7775 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7776 // indexed load/store and the expresion that needs to be re-written.
7778 // Therefore, we have:
7779 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7781 ConstantSDNode *CN =
7782 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7784 APInt Offset0 = CN->getAPIntValue();
7785 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7787 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7788 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7789 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7790 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7792 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7794 APInt CNV = Offset0;
7795 if (X0 < 0) CNV = -CNV;
7796 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7797 else CNV = CNV - Offset1;
7799 // We can now generate the new expression.
7800 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7801 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7803 SDValue NewUse = DAG.getNode(Opcode,
7804 SDLoc(OtherUses[i]),
7805 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7806 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7807 removeFromWorklist(OtherUses[i]);
7808 DAG.DeleteNode(OtherUses[i]);
7811 // Replace the uses of Ptr with uses of the updated base value.
7812 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7813 removeFromWorklist(Ptr.getNode());
7814 DAG.DeleteNode(Ptr.getNode());
7819 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7820 /// add / sub of the base pointer node into a post-indexed load / store.
7821 /// The transformation folded the add / subtract into the new indexed
7822 /// load / store effectively and all of its uses are redirected to the
7823 /// new load / store.
7824 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7825 if (Level < AfterLegalizeDAG)
7831 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7832 if (LD->isIndexed())
7834 VT = LD->getMemoryVT();
7835 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7836 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7838 Ptr = LD->getBasePtr();
7839 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7840 if (ST->isIndexed())
7842 VT = ST->getMemoryVT();
7843 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7844 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7846 Ptr = ST->getBasePtr();
7852 if (Ptr.getNode()->hasOneUse())
7855 for (SDNode *Op : Ptr.getNode()->uses()) {
7857 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7862 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7863 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7864 // Don't create a indexed load / store with zero offset.
7865 if (isa<ConstantSDNode>(Offset) &&
7866 cast<ConstantSDNode>(Offset)->isNullValue())
7869 // Try turning it into a post-indexed load / store except when
7870 // 1) All uses are load / store ops that use it as base ptr (and
7871 // it may be folded as addressing mmode).
7872 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7873 // nor a successor of N. Otherwise, if Op is folded that would
7876 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7880 bool TryNext = false;
7881 for (SDNode *Use : BasePtr.getNode()->uses()) {
7882 if (Use == Ptr.getNode())
7885 // If all the uses are load / store addresses, then don't do the
7887 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7888 bool RealUse = false;
7889 for (SDNode *UseUse : Use->uses()) {
7890 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7905 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7906 SDValue Result = isLoad
7907 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7908 BasePtr, Offset, AM)
7909 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7910 BasePtr, Offset, AM);
7913 DEBUG(dbgs() << "\nReplacing.5 ";
7915 dbgs() << "\nWith: ";
7916 Result.getNode()->dump(&DAG);
7918 WorklistRemover DeadNodes(*this);
7920 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7921 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7923 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7926 // Finally, since the node is now dead, remove it from the graph.
7929 // Replace the uses of Use with uses of the updated base value.
7930 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7931 Result.getValue(isLoad ? 1 : 0));
7932 removeFromWorklist(Op);
7942 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7943 LoadSDNode *LD = cast<LoadSDNode>(N);
7944 SDValue Chain = LD->getChain();
7945 SDValue Ptr = LD->getBasePtr();
7947 // If load is not volatile and there are no uses of the loaded value (and
7948 // the updated indexed value in case of indexed loads), change uses of the
7949 // chain value into uses of the chain input (i.e. delete the dead load).
7950 if (!LD->isVolatile()) {
7951 if (N->getValueType(1) == MVT::Other) {
7953 if (!N->hasAnyUseOfValue(0)) {
7954 // It's not safe to use the two value CombineTo variant here. e.g.
7955 // v1, chain2 = load chain1, loc
7956 // v2, chain3 = load chain2, loc
7958 // Now we replace use of chain2 with chain1. This makes the second load
7959 // isomorphic to the one we are deleting, and thus makes this load live.
7960 DEBUG(dbgs() << "\nReplacing.6 ";
7962 dbgs() << "\nWith chain: ";
7963 Chain.getNode()->dump(&DAG);
7965 WorklistRemover DeadNodes(*this);
7966 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7968 if (N->use_empty()) {
7969 removeFromWorklist(N);
7973 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7977 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7978 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7979 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7980 DEBUG(dbgs() << "\nReplacing.7 ";
7982 dbgs() << "\nWith: ";
7983 Undef.getNode()->dump(&DAG);
7984 dbgs() << " and 2 other values\n");
7985 WorklistRemover DeadNodes(*this);
7986 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7987 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7988 DAG.getUNDEF(N->getValueType(1)));
7989 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7990 removeFromWorklist(N);
7992 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7997 // If this load is directly stored, replace the load value with the stored
7999 // TODO: Handle store large -> read small portion.
8000 // TODO: Handle TRUNCSTORE/LOADEXT
8001 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8002 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8003 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8004 if (PrevST->getBasePtr() == Ptr &&
8005 PrevST->getValue().getValueType() == N->getValueType(0))
8006 return CombineTo(N, Chain.getOperand(1), Chain);
8010 // Try to infer better alignment information than the load already has.
8011 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8012 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8013 if (Align > LD->getMemOperand()->getBaseAlignment()) {
8015 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8016 LD->getValueType(0),
8017 Chain, Ptr, LD->getPointerInfo(),
8019 LD->isVolatile(), LD->isNonTemporal(), Align,
8021 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8026 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8027 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
8029 if (CombinerAAOnlyFunc.getNumOccurrences() &&
8030 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8033 if (UseAA && LD->isUnindexed()) {
8034 // Walk up chain skipping non-aliasing memory nodes.
8035 SDValue BetterChain = FindBetterChain(N, Chain);
8037 // If there is a better chain.
8038 if (Chain != BetterChain) {
8041 // Replace the chain to void dependency.
8042 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8043 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8044 BetterChain, Ptr, LD->getMemOperand());
8046 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8047 LD->getValueType(0),
8048 BetterChain, Ptr, LD->getMemoryVT(),
8049 LD->getMemOperand());
8052 // Create token factor to keep old chain connected.
8053 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8054 MVT::Other, Chain, ReplLoad.getValue(1));
8056 // Make sure the new and old chains are cleaned up.
8057 AddToWorklist(Token.getNode());
8059 // Replace uses with load result and token factor. Don't add users
8061 return CombineTo(N, ReplLoad.getValue(0), Token, false);
8065 // Try transforming N to an indexed load.
8066 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8067 return SDValue(N, 0);
8069 // Try to slice up N to more direct loads if the slices are mapped to
8070 // different register banks or pairing can take place.
8072 return SDValue(N, 0);
8078 /// \brief Helper structure used to slice a load in smaller loads.
8079 /// Basically a slice is obtained from the following sequence:
8080 /// Origin = load Ty1, Base
8081 /// Shift = srl Ty1 Origin, CstTy Amount
8082 /// Inst = trunc Shift to Ty2
8084 /// Then, it will be rewriten into:
8085 /// Slice = load SliceTy, Base + SliceOffset
8086 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8088 /// SliceTy is deduced from the number of bits that are actually used to
8090 struct LoadedSlice {
8091 /// \brief Helper structure used to compute the cost of a slice.
8093 /// Are we optimizing for code size.
8098 unsigned CrossRegisterBanksCopies;
8102 Cost(bool ForCodeSize = false)
8103 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8104 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8106 /// \brief Get the cost of one isolated slice.
8107 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8108 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8109 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8110 EVT TruncType = LS.Inst->getValueType(0);
8111 EVT LoadedType = LS.getLoadedType();
8112 if (TruncType != LoadedType &&
8113 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8117 /// \brief Account for slicing gain in the current cost.
8118 /// Slicing provide a few gains like removing a shift or a
8119 /// truncate. This method allows to grow the cost of the original
8120 /// load with the gain from this slice.
8121 void addSliceGain(const LoadedSlice &LS) {
8122 // Each slice saves a truncate.
8123 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8124 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8125 LS.Inst->getOperand(0).getValueType()))
8127 // If there is a shift amount, this slice gets rid of it.
8130 // If this slice can merge a cross register bank copy, account for it.
8131 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8132 ++CrossRegisterBanksCopies;
8135 Cost &operator+=(const Cost &RHS) {
8137 Truncates += RHS.Truncates;
8138 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8144 bool operator==(const Cost &RHS) const {
8145 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8146 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8147 ZExts == RHS.ZExts && Shift == RHS.Shift;
8150 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8152 bool operator<(const Cost &RHS) const {
8153 // Assume cross register banks copies are as expensive as loads.
8154 // FIXME: Do we want some more target hooks?
8155 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8156 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8157 // Unless we are optimizing for code size, consider the
8158 // expensive operation first.
8159 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8160 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8161 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8162 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8165 bool operator>(const Cost &RHS) const { return RHS < *this; }
8167 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8169 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8171 // The last instruction that represent the slice. This should be a
8172 // truncate instruction.
8174 // The original load instruction.
8176 // The right shift amount in bits from the original load.
8178 // The DAG from which Origin came from.
8179 // This is used to get some contextual information about legal types, etc.
8182 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8183 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8184 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8186 LoadedSlice(const LoadedSlice &LS)
8187 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8189 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8190 /// \return Result is \p BitWidth and has used bits set to 1 and
8191 /// not used bits set to 0.
8192 APInt getUsedBits() const {
8193 // Reproduce the trunc(lshr) sequence:
8194 // - Start from the truncated value.
8195 // - Zero extend to the desired bit width.
8197 assert(Origin && "No original load to compare against.");
8198 unsigned BitWidth = Origin->getValueSizeInBits(0);
8199 assert(Inst && "This slice is not bound to an instruction");
8200 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8201 "Extracted slice is bigger than the whole type!");
8202 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8203 UsedBits.setAllBits();
8204 UsedBits = UsedBits.zext(BitWidth);
8209 /// \brief Get the size of the slice to be loaded in bytes.
8210 unsigned getLoadedSize() const {
8211 unsigned SliceSize = getUsedBits().countPopulation();
8212 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8213 return SliceSize / 8;
8216 /// \brief Get the type that will be loaded for this slice.
8217 /// Note: This may not be the final type for the slice.
8218 EVT getLoadedType() const {
8219 assert(DAG && "Missing context");
8220 LLVMContext &Ctxt = *DAG->getContext();
8221 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8224 /// \brief Get the alignment of the load used for this slice.
8225 unsigned getAlignment() const {
8226 unsigned Alignment = Origin->getAlignment();
8227 unsigned Offset = getOffsetFromBase();
8229 Alignment = MinAlign(Alignment, Alignment + Offset);
8233 /// \brief Check if this slice can be rewritten with legal operations.
8234 bool isLegal() const {
8235 // An invalid slice is not legal.
8236 if (!Origin || !Inst || !DAG)
8239 // Offsets are for indexed load only, we do not handle that.
8240 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8243 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8245 // Check that the type is legal.
8246 EVT SliceType = getLoadedType();
8247 if (!TLI.isTypeLegal(SliceType))
8250 // Check that the load is legal for this type.
8251 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8254 // Check that the offset can be computed.
8255 // 1. Check its type.
8256 EVT PtrType = Origin->getBasePtr().getValueType();
8257 if (PtrType == MVT::Untyped || PtrType.isExtended())
8260 // 2. Check that it fits in the immediate.
8261 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8264 // 3. Check that the computation is legal.
8265 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8268 // Check that the zext is legal if it needs one.
8269 EVT TruncateType = Inst->getValueType(0);
8270 if (TruncateType != SliceType &&
8271 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8277 /// \brief Get the offset in bytes of this slice in the original chunk of
8279 /// \pre DAG != nullptr.
8280 uint64_t getOffsetFromBase() const {
8281 assert(DAG && "Missing context.");
8283 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8284 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8285 uint64_t Offset = Shift / 8;
8286 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8287 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8288 "The size of the original loaded type is not a multiple of a"
8290 // If Offset is bigger than TySizeInBytes, it means we are loading all
8291 // zeros. This should have been optimized before in the process.
8292 assert(TySizeInBytes > Offset &&
8293 "Invalid shift amount for given loaded size");
8295 Offset = TySizeInBytes - Offset - getLoadedSize();
8299 /// \brief Generate the sequence of instructions to load the slice
8300 /// represented by this object and redirect the uses of this slice to
8301 /// this new sequence of instructions.
8302 /// \pre this->Inst && this->Origin are valid Instructions and this
8303 /// object passed the legal check: LoadedSlice::isLegal returned true.
8304 /// \return The last instruction of the sequence used to load the slice.
8305 SDValue loadSlice() const {
8306 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8307 const SDValue &OldBaseAddr = Origin->getBasePtr();
8308 SDValue BaseAddr = OldBaseAddr;
8309 // Get the offset in that chunk of bytes w.r.t. the endianess.
8310 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8311 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8313 // BaseAddr = BaseAddr + Offset.
8314 EVT ArithType = BaseAddr.getValueType();
8315 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8316 DAG->getConstant(Offset, ArithType));
8319 // Create the type of the loaded slice according to its size.
8320 EVT SliceType = getLoadedType();
8322 // Create the load for the slice.
8323 SDValue LastInst = DAG->getLoad(
8324 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8325 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8326 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8327 // If the final type is not the same as the loaded type, this means that
8328 // we have to pad with zero. Create a zero extend for that.
8329 EVT FinalType = Inst->getValueType(0);
8330 if (SliceType != FinalType)
8332 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8336 /// \brief Check if this slice can be merged with an expensive cross register
8337 /// bank copy. E.g.,
8339 /// f = bitcast i32 i to float
8340 bool canMergeExpensiveCrossRegisterBankCopy() const {
8341 if (!Inst || !Inst->hasOneUse())
8343 SDNode *Use = *Inst->use_begin();
8344 if (Use->getOpcode() != ISD::BITCAST)
8346 assert(DAG && "Missing context");
8347 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8348 EVT ResVT = Use->getValueType(0);
8349 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8350 const TargetRegisterClass *ArgRC =
8351 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8352 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8355 // At this point, we know that we perform a cross-register-bank copy.
8356 // Check if it is expensive.
8357 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8358 // Assume bitcasts are cheap, unless both register classes do not
8359 // explicitly share a common sub class.
8360 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8363 // Check if it will be merged with the load.
8364 // 1. Check the alignment constraint.
8365 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8366 ResVT.getTypeForEVT(*DAG->getContext()));
8368 if (RequiredAlignment > getAlignment())
8371 // 2. Check that the load is a legal operation for that type.
8372 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8375 // 3. Check that we do not have a zext in the way.
8376 if (Inst->getValueType(0) != getLoadedType())
8384 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8385 /// \p UsedBits looks like 0..0 1..1 0..0.
8386 static bool areUsedBitsDense(const APInt &UsedBits) {
8387 // If all the bits are one, this is dense!
8388 if (UsedBits.isAllOnesValue())
8391 // Get rid of the unused bits on the right.
8392 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8393 // Get rid of the unused bits on the left.
8394 if (NarrowedUsedBits.countLeadingZeros())
8395 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8396 // Check that the chunk of bits is completely used.
8397 return NarrowedUsedBits.isAllOnesValue();
8400 /// \brief Check whether or not \p First and \p Second are next to each other
8401 /// in memory. This means that there is no hole between the bits loaded
8402 /// by \p First and the bits loaded by \p Second.
8403 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8404 const LoadedSlice &Second) {
8405 assert(First.Origin == Second.Origin && First.Origin &&
8406 "Unable to match different memory origins.");
8407 APInt UsedBits = First.getUsedBits();
8408 assert((UsedBits & Second.getUsedBits()) == 0 &&
8409 "Slices are not supposed to overlap.");
8410 UsedBits |= Second.getUsedBits();
8411 return areUsedBitsDense(UsedBits);
8414 /// \brief Adjust the \p GlobalLSCost according to the target
8415 /// paring capabilities and the layout of the slices.
8416 /// \pre \p GlobalLSCost should account for at least as many loads as
8417 /// there is in the slices in \p LoadedSlices.
8418 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8419 LoadedSlice::Cost &GlobalLSCost) {
8420 unsigned NumberOfSlices = LoadedSlices.size();
8421 // If there is less than 2 elements, no pairing is possible.
8422 if (NumberOfSlices < 2)
8425 // Sort the slices so that elements that are likely to be next to each
8426 // other in memory are next to each other in the list.
8427 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8428 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8429 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8430 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8432 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8433 // First (resp. Second) is the first (resp. Second) potentially candidate
8434 // to be placed in a paired load.
8435 const LoadedSlice *First = nullptr;
8436 const LoadedSlice *Second = nullptr;
8437 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8438 // Set the beginning of the pair.
8441 Second = &LoadedSlices[CurrSlice];
8443 // If First is NULL, it means we start a new pair.
8444 // Get to the next slice.
8448 EVT LoadedType = First->getLoadedType();
8450 // If the types of the slices are different, we cannot pair them.
8451 if (LoadedType != Second->getLoadedType())
8454 // Check if the target supplies paired loads for this type.
8455 unsigned RequiredAlignment = 0;
8456 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8457 // move to the next pair, this type is hopeless.
8461 // Check if we meet the alignment requirement.
8462 if (RequiredAlignment > First->getAlignment())
8465 // Check that both loads are next to each other in memory.
8466 if (!areSlicesNextToEachOther(*First, *Second))
8469 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8470 --GlobalLSCost.Loads;
8471 // Move to the next pair.
8476 /// \brief Check the profitability of all involved LoadedSlice.
8477 /// Currently, it is considered profitable if there is exactly two
8478 /// involved slices (1) which are (2) next to each other in memory, and
8479 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8481 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8482 /// the elements themselves.
8484 /// FIXME: When the cost model will be mature enough, we can relax
8485 /// constraints (1) and (2).
8486 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8487 const APInt &UsedBits, bool ForCodeSize) {
8488 unsigned NumberOfSlices = LoadedSlices.size();
8489 if (StressLoadSlicing)
8490 return NumberOfSlices > 1;
8493 if (NumberOfSlices != 2)
8497 if (!areUsedBitsDense(UsedBits))
8501 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8502 // The original code has one big load.
8504 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8505 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8506 // Accumulate the cost of all the slices.
8507 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8508 GlobalSlicingCost += SliceCost;
8510 // Account as cost in the original configuration the gain obtained
8511 // with the current slices.
8512 OrigCost.addSliceGain(LS);
8515 // If the target supports paired load, adjust the cost accordingly.
8516 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8517 return OrigCost > GlobalSlicingCost;
8520 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8521 /// operations, split it in the various pieces being extracted.
8523 /// This sort of thing is introduced by SROA.
8524 /// This slicing takes care not to insert overlapping loads.
8525 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8526 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8527 if (Level < AfterLegalizeDAG)
8530 LoadSDNode *LD = cast<LoadSDNode>(N);
8531 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8532 !LD->getValueType(0).isInteger())
8535 // Keep track of already used bits to detect overlapping values.
8536 // In that case, we will just abort the transformation.
8537 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8539 SmallVector<LoadedSlice, 4> LoadedSlices;
8541 // Check if this load is used as several smaller chunks of bits.
8542 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8543 // of computation for each trunc.
8544 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8545 UI != UIEnd; ++UI) {
8546 // Skip the uses of the chain.
8547 if (UI.getUse().getResNo() != 0)
8553 // Check if this is a trunc(lshr).
8554 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8555 isa<ConstantSDNode>(User->getOperand(1))) {
8556 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8557 User = *User->use_begin();
8560 // At this point, User is a Truncate, iff we encountered, trunc or
8562 if (User->getOpcode() != ISD::TRUNCATE)
8565 // The width of the type must be a power of 2 and greater than 8-bits.
8566 // Otherwise the load cannot be represented in LLVM IR.
8567 // Moreover, if we shifted with a non-8-bits multiple, the slice
8568 // will be across several bytes. We do not support that.
8569 unsigned Width = User->getValueSizeInBits(0);
8570 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8573 // Build the slice for this chain of computations.
8574 LoadedSlice LS(User, LD, Shift, &DAG);
8575 APInt CurrentUsedBits = LS.getUsedBits();
8577 // Check if this slice overlaps with another.
8578 if ((CurrentUsedBits & UsedBits) != 0)
8580 // Update the bits used globally.
8581 UsedBits |= CurrentUsedBits;
8583 // Check if the new slice would be legal.
8587 // Record the slice.
8588 LoadedSlices.push_back(LS);
8591 // Abort slicing if it does not seem to be profitable.
8592 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8597 // Rewrite each chain to use an independent load.
8598 // By construction, each chain can be represented by a unique load.
8600 // Prepare the argument for the new token factor for all the slices.
8601 SmallVector<SDValue, 8> ArgChains;
8602 for (SmallVectorImpl<LoadedSlice>::const_iterator
8603 LSIt = LoadedSlices.begin(),
8604 LSItEnd = LoadedSlices.end();
8605 LSIt != LSItEnd; ++LSIt) {
8606 SDValue SliceInst = LSIt->loadSlice();
8607 CombineTo(LSIt->Inst, SliceInst, true);
8608 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8609 SliceInst = SliceInst.getOperand(0);
8610 assert(SliceInst->getOpcode() == ISD::LOAD &&
8611 "It takes more than a zext to get to the loaded slice!!");
8612 ArgChains.push_back(SliceInst.getValue(1));
8615 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8617 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8621 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8622 /// load is having specific bytes cleared out. If so, return the byte size
8623 /// being masked out and the shift amount.
8624 static std::pair<unsigned, unsigned>
8625 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8626 std::pair<unsigned, unsigned> Result(0, 0);
8628 // Check for the structure we're looking for.
8629 if (V->getOpcode() != ISD::AND ||
8630 !isa<ConstantSDNode>(V->getOperand(1)) ||
8631 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8634 // Check the chain and pointer.
8635 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8636 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
8638 // The store should be chained directly to the load or be an operand of a
8640 if (LD == Chain.getNode())
8642 else if (Chain->getOpcode() != ISD::TokenFactor)
8643 return Result; // Fail.
8646 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8647 if (Chain->getOperand(i).getNode() == LD) {
8651 if (!isOk) return Result;
8654 // This only handles simple types.
8655 if (V.getValueType() != MVT::i16 &&
8656 V.getValueType() != MVT::i32 &&
8657 V.getValueType() != MVT::i64)
8660 // Check the constant mask. Invert it so that the bits being masked out are
8661 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8662 // follow the sign bit for uniformity.
8663 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8664 unsigned NotMaskLZ = countLeadingZeros(NotMask);
8665 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
8666 unsigned NotMaskTZ = countTrailingZeros(NotMask);
8667 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8668 if (NotMaskLZ == 64) return Result; // All zero mask.
8670 // See if we have a continuous run of bits. If so, we have 0*1+0*
8671 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8674 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8675 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8676 NotMaskLZ -= 64-V.getValueSizeInBits();
8678 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8679 switch (MaskedBytes) {
8683 default: return Result; // All one mask, or 5-byte mask.
8686 // Verify that the first bit starts at a multiple of mask so that the access
8687 // is aligned the same as the access width.
8688 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8690 Result.first = MaskedBytes;
8691 Result.second = NotMaskTZ/8;
8696 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8697 /// provides a value as specified by MaskInfo. If so, replace the specified
8698 /// store with a narrower store of truncated IVal.
8700 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8701 SDValue IVal, StoreSDNode *St,
8703 unsigned NumBytes = MaskInfo.first;
8704 unsigned ByteShift = MaskInfo.second;
8705 SelectionDAG &DAG = DC->getDAG();
8707 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8708 // that uses this. If not, this is not a replacement.
8709 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8710 ByteShift*8, (ByteShift+NumBytes)*8);
8711 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8713 // Check that it is legal on the target to do this. It is legal if the new
8714 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8716 MVT VT = MVT::getIntegerVT(NumBytes*8);
8717 if (!DC->isTypeLegal(VT))
8720 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8721 // shifted by ByteShift and truncated down to NumBytes.
8723 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8724 DAG.getConstant(ByteShift*8,
8725 DC->getShiftAmountTy(IVal.getValueType())));
8727 // Figure out the offset for the store and the alignment of the access.
8729 unsigned NewAlign = St->getAlignment();
8731 if (DAG.getTargetLoweringInfo().isLittleEndian())
8732 StOffset = ByteShift;
8734 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8736 SDValue Ptr = St->getBasePtr();
8738 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8739 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8740 NewAlign = MinAlign(NewAlign, StOffset);
8743 // Truncate down to the new size.
8744 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8747 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8748 St->getPointerInfo().getWithOffset(StOffset),
8749 false, false, NewAlign).getNode();
8753 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8754 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8755 /// of the loaded bits, try narrowing the load and store if it would end up
8756 /// being a win for performance or code size.
8757 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8758 StoreSDNode *ST = cast<StoreSDNode>(N);
8759 if (ST->isVolatile())
8762 SDValue Chain = ST->getChain();
8763 SDValue Value = ST->getValue();
8764 SDValue Ptr = ST->getBasePtr();
8765 EVT VT = Value.getValueType();
8767 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8770 unsigned Opc = Value.getOpcode();
8772 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8773 // is a byte mask indicating a consecutive number of bytes, check to see if
8774 // Y is known to provide just those bytes. If so, we try to replace the
8775 // load + replace + store sequence with a single (narrower) store, which makes
8777 if (Opc == ISD::OR) {
8778 std::pair<unsigned, unsigned> MaskedLoad;
8779 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8780 if (MaskedLoad.first)
8781 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8782 Value.getOperand(1), ST,this))
8783 return SDValue(NewST, 0);
8785 // Or is commutative, so try swapping X and Y.
8786 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8787 if (MaskedLoad.first)
8788 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8789 Value.getOperand(0), ST,this))
8790 return SDValue(NewST, 0);
8793 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8794 Value.getOperand(1).getOpcode() != ISD::Constant)
8797 SDValue N0 = Value.getOperand(0);
8798 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8799 Chain == SDValue(N0.getNode(), 1)) {
8800 LoadSDNode *LD = cast<LoadSDNode>(N0);
8801 if (LD->getBasePtr() != Ptr ||
8802 LD->getPointerInfo().getAddrSpace() !=
8803 ST->getPointerInfo().getAddrSpace())
8806 // Find the type to narrow it the load / op / store to.
8807 SDValue N1 = Value.getOperand(1);
8808 unsigned BitWidth = N1.getValueSizeInBits();
8809 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8810 if (Opc == ISD::AND)
8811 Imm ^= APInt::getAllOnesValue(BitWidth);
8812 if (Imm == 0 || Imm.isAllOnesValue())
8814 unsigned ShAmt = Imm.countTrailingZeros();
8815 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8816 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8817 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8818 while (NewBW < BitWidth &&
8819 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8820 TLI.isNarrowingProfitable(VT, NewVT))) {
8821 NewBW = NextPowerOf2(NewBW);
8822 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8824 if (NewBW >= BitWidth)
8827 // If the lsb changed does not start at the type bitwidth boundary,
8828 // start at the previous one.
8830 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8831 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8832 std::min(BitWidth, ShAmt + NewBW));
8833 if ((Imm & Mask) == Imm) {
8834 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8835 if (Opc == ISD::AND)
8836 NewImm ^= APInt::getAllOnesValue(NewBW);
8837 uint64_t PtrOff = ShAmt / 8;
8838 // For big endian targets, we need to adjust the offset to the pointer to
8839 // load the correct bytes.
8840 if (TLI.isBigEndian())
8841 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8843 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8844 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8845 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8848 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8849 Ptr.getValueType(), Ptr,
8850 DAG.getConstant(PtrOff, Ptr.getValueType()));
8851 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8852 LD->getChain(), NewPtr,
8853 LD->getPointerInfo().getWithOffset(PtrOff),
8854 LD->isVolatile(), LD->isNonTemporal(),
8855 LD->isInvariant(), NewAlign,
8857 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8858 DAG.getConstant(NewImm, NewVT));
8859 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8861 ST->getPointerInfo().getWithOffset(PtrOff),
8862 false, false, NewAlign);
8864 AddToWorklist(NewPtr.getNode());
8865 AddToWorklist(NewLD.getNode());
8866 AddToWorklist(NewVal.getNode());
8867 WorklistRemover DeadNodes(*this);
8868 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8877 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8878 /// if the load value isn't used by any other operations, then consider
8879 /// transforming the pair to integer load / store operations if the target
8880 /// deems the transformation profitable.
8881 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8882 StoreSDNode *ST = cast<StoreSDNode>(N);
8883 SDValue Chain = ST->getChain();
8884 SDValue Value = ST->getValue();
8885 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8886 Value.hasOneUse() &&
8887 Chain == SDValue(Value.getNode(), 1)) {
8888 LoadSDNode *LD = cast<LoadSDNode>(Value);
8889 EVT VT = LD->getMemoryVT();
8890 if (!VT.isFloatingPoint() ||
8891 VT != ST->getMemoryVT() ||
8892 LD->isNonTemporal() ||
8893 ST->isNonTemporal() ||
8894 LD->getPointerInfo().getAddrSpace() != 0 ||
8895 ST->getPointerInfo().getAddrSpace() != 0)
8898 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8899 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8900 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8901 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8902 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8905 unsigned LDAlign = LD->getAlignment();
8906 unsigned STAlign = ST->getAlignment();
8907 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8908 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8909 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8912 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8913 LD->getChain(), LD->getBasePtr(),
8914 LD->getPointerInfo(),
8915 false, false, false, LDAlign);
8917 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8918 NewLD, ST->getBasePtr(),
8919 ST->getPointerInfo(),
8920 false, false, STAlign);
8922 AddToWorklist(NewLD.getNode());
8923 AddToWorklist(NewST.getNode());
8924 WorklistRemover DeadNodes(*this);
8925 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8933 /// Helper struct to parse and store a memory address as base + index + offset.
8934 /// We ignore sign extensions when it is safe to do so.
8935 /// The following two expressions are not equivalent. To differentiate we need
8936 /// to store whether there was a sign extension involved in the index
8938 /// (load (i64 add (i64 copyfromreg %c)
8939 /// (i64 signextend (add (i8 load %index)
8943 /// (load (i64 add (i64 copyfromreg %c)
8944 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8946 struct BaseIndexOffset {
8950 bool IsIndexSignExt;
8952 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8954 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8955 bool IsIndexSignExt) :
8956 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8958 bool equalBaseIndex(const BaseIndexOffset &Other) {
8959 return Other.Base == Base && Other.Index == Index &&
8960 Other.IsIndexSignExt == IsIndexSignExt;
8963 /// Parses tree in Ptr for base, index, offset addresses.
8964 static BaseIndexOffset match(SDValue Ptr) {
8965 bool IsIndexSignExt = false;
8967 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8968 // instruction, then it could be just the BASE or everything else we don't
8969 // know how to handle. Just use Ptr as BASE and give up.
8970 if (Ptr->getOpcode() != ISD::ADD)
8971 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8973 // We know that we have at least an ADD instruction. Try to pattern match
8974 // the simple case of BASE + OFFSET.
8975 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8976 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8977 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8981 // Inside a loop the current BASE pointer is calculated using an ADD and a
8982 // MUL instruction. In this case Ptr is the actual BASE pointer.
8983 // (i64 add (i64 %array_ptr)
8984 // (i64 mul (i64 %induction_var)
8985 // (i64 %element_size)))
8986 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8987 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8989 // Look at Base + Index + Offset cases.
8990 SDValue Base = Ptr->getOperand(0);
8991 SDValue IndexOffset = Ptr->getOperand(1);
8993 // Skip signextends.
8994 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8995 IndexOffset = IndexOffset->getOperand(0);
8996 IsIndexSignExt = true;
8999 // Either the case of Base + Index (no offset) or something else.
9000 if (IndexOffset->getOpcode() != ISD::ADD)
9001 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9003 // Now we have the case of Base + Index + offset.
9004 SDValue Index = IndexOffset->getOperand(0);
9005 SDValue Offset = IndexOffset->getOperand(1);
9007 if (!isa<ConstantSDNode>(Offset))
9008 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9010 // Ignore signextends.
9011 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9012 Index = Index->getOperand(0);
9013 IsIndexSignExt = true;
9014 } else IsIndexSignExt = false;
9016 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9017 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9021 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9022 /// is located in a sequence of memory operations connected by a chain.
9024 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9025 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9026 // Ptr to the mem node.
9027 LSBaseSDNode *MemNode;
9028 // Offset from the base ptr.
9029 int64_t OffsetFromBase;
9030 // What is the sequence number of this mem node.
9031 // Lowest mem operand in the DAG starts at zero.
9032 unsigned SequenceNum;
9035 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9036 EVT MemVT = St->getMemoryVT();
9037 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9038 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9039 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9041 // Don't merge vectors into wider inputs.
9042 if (MemVT.isVector() || !MemVT.isSimple())
9045 // Perform an early exit check. Do not bother looking at stored values that
9046 // are not constants or loads.
9047 SDValue StoredVal = St->getValue();
9048 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9049 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9053 // Only look at ends of store sequences.
9054 SDValue Chain = SDValue(St, 1);
9055 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9058 // This holds the base pointer, index, and the offset in bytes from the base
9060 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9062 // We must have a base and an offset.
9063 if (!BasePtr.Base.getNode())
9066 // Do not handle stores to undef base pointers.
9067 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9070 // Save the LoadSDNodes that we find in the chain.
9071 // We need to make sure that these nodes do not interfere with
9072 // any of the store nodes.
9073 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9075 // Save the StoreSDNodes that we find in the chain.
9076 SmallVector<MemOpLink, 8> StoreNodes;
9078 // Walk up the chain and look for nodes with offsets from the same
9079 // base pointer. Stop when reaching an instruction with a different kind
9080 // or instruction which has a different base pointer.
9082 StoreSDNode *Index = St;
9084 // If the chain has more than one use, then we can't reorder the mem ops.
9085 if (Index != St && !SDValue(Index, 1)->hasOneUse())
9088 // Find the base pointer and offset for this memory node.
9089 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9091 // Check that the base pointer is the same as the original one.
9092 if (!Ptr.equalBaseIndex(BasePtr))
9095 // Check that the alignment is the same.
9096 if (Index->getAlignment() != St->getAlignment())
9099 // The memory operands must not be volatile.
9100 if (Index->isVolatile() || Index->isIndexed())
9104 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9105 if (St->isTruncatingStore())
9108 // The stored memory type must be the same.
9109 if (Index->getMemoryVT() != MemVT)
9112 // We do not allow unaligned stores because we want to prevent overriding
9114 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9117 // We found a potential memory operand to merge.
9118 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9120 // Find the next memory operand in the chain. If the next operand in the
9121 // chain is a store then move up and continue the scan with the next
9122 // memory operand. If the next operand is a load save it and use alias
9123 // information to check if it interferes with anything.
9124 SDNode *NextInChain = Index->getChain().getNode();
9126 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9127 // We found a store node. Use it for the next iteration.
9130 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9131 if (Ldn->isVolatile()) {
9136 // Save the load node for later. Continue the scan.
9137 AliasLoadNodes.push_back(Ldn);
9138 NextInChain = Ldn->getChain().getNode();
9147 // Check if there is anything to merge.
9148 if (StoreNodes.size() < 2)
9151 // Sort the memory operands according to their distance from the base pointer.
9152 std::sort(StoreNodes.begin(), StoreNodes.end(),
9153 [](MemOpLink LHS, MemOpLink RHS) {
9154 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9155 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9156 LHS.SequenceNum > RHS.SequenceNum);
9159 // Scan the memory operations on the chain and find the first non-consecutive
9160 // store memory address.
9161 unsigned LastConsecutiveStore = 0;
9162 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9163 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9165 // Check that the addresses are consecutive starting from the second
9166 // element in the list of stores.
9168 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9169 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9174 // Check if this store interferes with any of the loads that we found.
9175 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9176 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9180 // We found a load that alias with this store. Stop the sequence.
9184 // Mark this node as useful.
9185 LastConsecutiveStore = i;
9188 // The node with the lowest store address.
9189 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9191 // Store the constants into memory as one consecutive store.
9193 unsigned LastLegalType = 0;
9194 unsigned LastLegalVectorType = 0;
9195 bool NonZero = false;
9196 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9197 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9198 SDValue StoredVal = St->getValue();
9200 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9201 NonZero |= !C->isNullValue();
9202 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9203 NonZero |= !C->getConstantFPValue()->isNullValue();
9209 // Find a legal type for the constant store.
9210 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9211 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9212 if (TLI.isTypeLegal(StoreTy))
9213 LastLegalType = i+1;
9214 // Or check whether a truncstore is legal.
9215 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9216 TargetLowering::TypePromoteInteger) {
9217 EVT LegalizedStoredValueTy =
9218 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9219 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9220 LastLegalType = i+1;
9223 // Find a legal type for the vector store.
9224 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9225 if (TLI.isTypeLegal(Ty))
9226 LastLegalVectorType = i + 1;
9229 // We only use vectors if the constant is known to be zero and the
9230 // function is not marked with the noimplicitfloat attribute.
9231 if (NonZero || NoVectors)
9232 LastLegalVectorType = 0;
9234 // Check if we found a legal integer type to store.
9235 if (LastLegalType == 0 && LastLegalVectorType == 0)
9238 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9239 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9241 // Make sure we have something to merge.
9245 unsigned EarliestNodeUsed = 0;
9246 for (unsigned i=0; i < NumElem; ++i) {
9247 // Find a chain for the new wide-store operand. Notice that some
9248 // of the store nodes that we found may not be selected for inclusion
9249 // in the wide store. The chain we use needs to be the chain of the
9250 // earliest store node which is *used* and replaced by the wide store.
9251 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9252 EarliestNodeUsed = i;
9255 // The earliest Node in the DAG.
9256 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9257 SDLoc DL(StoreNodes[0].MemNode);
9261 // Find a legal type for the vector store.
9262 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9263 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9264 StoredVal = DAG.getConstant(0, Ty);
9266 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9267 APInt StoreInt(StoreBW, 0);
9269 // Construct a single integer constant which is made of the smaller
9271 bool IsLE = TLI.isLittleEndian();
9272 for (unsigned i = 0; i < NumElem ; ++i) {
9273 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9274 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9275 SDValue Val = St->getValue();
9276 StoreInt<<=ElementSizeBytes*8;
9277 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9278 StoreInt|=C->getAPIntValue().zext(StoreBW);
9279 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9280 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9282 assert(false && "Invalid constant element type");
9286 // Create the new Load and Store operations.
9287 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9288 StoredVal = DAG.getConstant(StoreInt, StoreTy);
9291 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9292 FirstInChain->getBasePtr(),
9293 FirstInChain->getPointerInfo(),
9295 FirstInChain->getAlignment());
9297 // Replace the first store with the new store
9298 CombineTo(EarliestOp, NewStore);
9299 // Erase all other stores.
9300 for (unsigned i = 0; i < NumElem ; ++i) {
9301 if (StoreNodes[i].MemNode == EarliestOp)
9303 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9304 // ReplaceAllUsesWith will replace all uses that existed when it was
9305 // called, but graph optimizations may cause new ones to appear. For
9306 // example, the case in pr14333 looks like
9308 // St's chain -> St -> another store -> X
9310 // And the only difference from St to the other store is the chain.
9311 // When we change it's chain to be St's chain they become identical,
9312 // get CSEed and the net result is that X is now a use of St.
9313 // Since we know that St is redundant, just iterate.
9314 while (!St->use_empty())
9315 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9316 removeFromWorklist(St);
9323 // Below we handle the case of multiple consecutive stores that
9324 // come from multiple consecutive loads. We merge them into a single
9325 // wide load and a single wide store.
9327 // Look for load nodes which are used by the stored values.
9328 SmallVector<MemOpLink, 8> LoadNodes;
9330 // Find acceptable loads. Loads need to have the same chain (token factor),
9331 // must not be zext, volatile, indexed, and they must be consecutive.
9332 BaseIndexOffset LdBasePtr;
9333 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9334 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9335 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9338 // Loads must only have one use.
9339 if (!Ld->hasNUsesOfValue(1, 0))
9342 // Check that the alignment is the same as the stores.
9343 if (Ld->getAlignment() != St->getAlignment())
9346 // The memory operands must not be volatile.
9347 if (Ld->isVolatile() || Ld->isIndexed())
9350 // We do not accept ext loads.
9351 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9354 // The stored memory type must be the same.
9355 if (Ld->getMemoryVT() != MemVT)
9358 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9359 // If this is not the first ptr that we check.
9360 if (LdBasePtr.Base.getNode()) {
9361 // The base ptr must be the same.
9362 if (!LdPtr.equalBaseIndex(LdBasePtr))
9365 // Check that all other base pointers are the same as this one.
9369 // We found a potential memory operand to merge.
9370 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9373 if (LoadNodes.size() < 2)
9376 // Scan the memory operations on the chain and find the first non-consecutive
9377 // load memory address. These variables hold the index in the store node
9379 unsigned LastConsecutiveLoad = 0;
9380 // This variable refers to the size and not index in the array.
9381 unsigned LastLegalVectorType = 0;
9382 unsigned LastLegalIntegerType = 0;
9383 StartAddress = LoadNodes[0].OffsetFromBase;
9384 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9385 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9386 // All loads much share the same chain.
9387 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9390 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9391 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9393 LastConsecutiveLoad = i;
9395 // Find a legal type for the vector store.
9396 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9397 if (TLI.isTypeLegal(StoreTy))
9398 LastLegalVectorType = i + 1;
9400 // Find a legal type for the integer store.
9401 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9402 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9403 if (TLI.isTypeLegal(StoreTy))
9404 LastLegalIntegerType = i + 1;
9405 // Or check whether a truncstore and extload is legal.
9406 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9407 TargetLowering::TypePromoteInteger) {
9408 EVT LegalizedStoredValueTy =
9409 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9410 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9411 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9412 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9413 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9414 LastLegalIntegerType = i+1;
9418 // Only use vector types if the vector type is larger than the integer type.
9419 // If they are the same, use integers.
9420 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9421 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9423 // We add +1 here because the LastXXX variables refer to location while
9424 // the NumElem refers to array/index size.
9425 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9426 NumElem = std::min(LastLegalType, NumElem);
9431 // The earliest Node in the DAG.
9432 unsigned EarliestNodeUsed = 0;
9433 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9434 for (unsigned i=1; i<NumElem; ++i) {
9435 // Find a chain for the new wide-store operand. Notice that some
9436 // of the store nodes that we found may not be selected for inclusion
9437 // in the wide store. The chain we use needs to be the chain of the
9438 // earliest store node which is *used* and replaced by the wide store.
9439 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9440 EarliestNodeUsed = i;
9443 // Find if it is better to use vectors or integers to load and store
9447 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9449 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9450 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9453 SDLoc LoadDL(LoadNodes[0].MemNode);
9454 SDLoc StoreDL(StoreNodes[0].MemNode);
9456 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9457 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9458 FirstLoad->getChain(),
9459 FirstLoad->getBasePtr(),
9460 FirstLoad->getPointerInfo(),
9461 false, false, false,
9462 FirstLoad->getAlignment());
9464 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9465 FirstInChain->getBasePtr(),
9466 FirstInChain->getPointerInfo(), false, false,
9467 FirstInChain->getAlignment());
9469 // Replace one of the loads with the new load.
9470 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9471 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9472 SDValue(NewLoad.getNode(), 1));
9474 // Remove the rest of the load chains.
9475 for (unsigned i = 1; i < NumElem ; ++i) {
9476 // Replace all chain users of the old load nodes with the chain of the new
9478 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9479 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9482 // Replace the first store with the new store.
9483 CombineTo(EarliestOp, NewStore);
9484 // Erase all other stores.
9485 for (unsigned i = 0; i < NumElem ; ++i) {
9486 // Remove all Store nodes.
9487 if (StoreNodes[i].MemNode == EarliestOp)
9489 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9490 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9491 removeFromWorklist(St);
9498 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9499 StoreSDNode *ST = cast<StoreSDNode>(N);
9500 SDValue Chain = ST->getChain();
9501 SDValue Value = ST->getValue();
9502 SDValue Ptr = ST->getBasePtr();
9504 // If this is a store of a bit convert, store the input value if the
9505 // resultant store does not need a higher alignment than the original.
9506 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9507 ST->isUnindexed()) {
9508 unsigned OrigAlign = ST->getAlignment();
9509 EVT SVT = Value.getOperand(0).getValueType();
9510 unsigned Align = TLI.getDataLayout()->
9511 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9512 if (Align <= OrigAlign &&
9513 ((!LegalOperations && !ST->isVolatile()) ||
9514 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9515 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9516 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9517 ST->isNonTemporal(), OrigAlign,
9521 // Turn 'store undef, Ptr' -> nothing.
9522 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9525 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9526 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9527 // NOTE: If the original store is volatile, this transform must not increase
9528 // the number of stores. For example, on x86-32 an f64 can be stored in one
9529 // processor operation but an i64 (which is not legal) requires two. So the
9530 // transform should not be done in this case.
9531 if (Value.getOpcode() != ISD::TargetConstantFP) {
9533 switch (CFP->getSimpleValueType(0).SimpleTy) {
9534 default: llvm_unreachable("Unknown FP type");
9535 case MVT::f16: // We don't do this for these yet.
9541 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9542 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9543 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9544 bitcastToAPInt().getZExtValue(), MVT::i32);
9545 return DAG.getStore(Chain, SDLoc(N), Tmp,
9546 Ptr, ST->getMemOperand());
9550 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9551 !ST->isVolatile()) ||
9552 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9553 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9554 getZExtValue(), MVT::i64);
9555 return DAG.getStore(Chain, SDLoc(N), Tmp,
9556 Ptr, ST->getMemOperand());
9559 if (!ST->isVolatile() &&
9560 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9561 // Many FP stores are not made apparent until after legalize, e.g. for
9562 // argument passing. Since this is so common, custom legalize the
9563 // 64-bit integer store into two 32-bit stores.
9564 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9565 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9566 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9567 if (TLI.isBigEndian()) std::swap(Lo, Hi);
9569 unsigned Alignment = ST->getAlignment();
9570 bool isVolatile = ST->isVolatile();
9571 bool isNonTemporal = ST->isNonTemporal();
9572 const MDNode *TBAAInfo = ST->getTBAAInfo();
9574 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9575 Ptr, ST->getPointerInfo(),
9576 isVolatile, isNonTemporal,
9577 ST->getAlignment(), TBAAInfo);
9578 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9579 DAG.getConstant(4, Ptr.getValueType()));
9580 Alignment = MinAlign(Alignment, 4U);
9581 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9582 Ptr, ST->getPointerInfo().getWithOffset(4),
9583 isVolatile, isNonTemporal,
9584 Alignment, TBAAInfo);
9585 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9594 // Try to infer better alignment information than the store already has.
9595 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9596 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9597 if (Align > ST->getAlignment())
9598 return DAG.getTruncStore(Chain, SDLoc(N), Value,
9599 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9600 ST->isVolatile(), ST->isNonTemporal(), Align,
9605 // Try transforming a pair floating point load / store ops to integer
9606 // load / store ops.
9607 SDValue NewST = TransformFPLoadStorePair(N);
9608 if (NewST.getNode())
9611 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9612 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9614 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9615 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9618 if (UseAA && ST->isUnindexed()) {
9619 // Walk up chain skipping non-aliasing memory nodes.
9620 SDValue BetterChain = FindBetterChain(N, Chain);
9622 // If there is a better chain.
9623 if (Chain != BetterChain) {
9626 // Replace the chain to avoid dependency.
9627 if (ST->isTruncatingStore()) {
9628 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9629 ST->getMemoryVT(), ST->getMemOperand());
9631 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9632 ST->getMemOperand());
9635 // Create token to keep both nodes around.
9636 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9637 MVT::Other, Chain, ReplStore);
9639 // Make sure the new and old chains are cleaned up.
9640 AddToWorklist(Token.getNode());
9642 // Don't add users to work list.
9643 return CombineTo(N, Token, false);
9647 // Try transforming N to an indexed store.
9648 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9649 return SDValue(N, 0);
9651 // FIXME: is there such a thing as a truncating indexed store?
9652 if (ST->isTruncatingStore() && ST->isUnindexed() &&
9653 Value.getValueType().isInteger()) {
9654 // See if we can simplify the input to this truncstore with knowledge that
9655 // only the low bits are being used. For example:
9656 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
9658 GetDemandedBits(Value,
9659 APInt::getLowBitsSet(
9660 Value.getValueType().getScalarType().getSizeInBits(),
9661 ST->getMemoryVT().getScalarType().getSizeInBits()));
9662 AddToWorklist(Value.getNode());
9663 if (Shorter.getNode())
9664 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9665 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9667 // Otherwise, see if we can simplify the operation with
9668 // SimplifyDemandedBits, which only works if the value has a single use.
9669 if (SimplifyDemandedBits(Value,
9670 APInt::getLowBitsSet(
9671 Value.getValueType().getScalarType().getSizeInBits(),
9672 ST->getMemoryVT().getScalarType().getSizeInBits())))
9673 return SDValue(N, 0);
9676 // If this is a load followed by a store to the same location, then the store
9678 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9679 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9680 ST->isUnindexed() && !ST->isVolatile() &&
9681 // There can't be any side effects between the load and store, such as
9683 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9684 // The store is dead, remove it.
9689 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9690 // truncating store. We can do this even if this is already a truncstore.
9691 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9692 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9693 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9694 ST->getMemoryVT())) {
9695 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9696 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9699 // Only perform this optimization before the types are legal, because we
9700 // don't want to perform this optimization on every DAGCombine invocation.
9702 bool EverChanged = false;
9705 // There can be multiple store sequences on the same chain.
9706 // Keep trying to merge store sequences until we are unable to do so
9707 // or until we merge the last store on the chain.
9708 bool Changed = MergeConsecutiveStores(ST);
9709 EverChanged |= Changed;
9710 if (!Changed) break;
9711 } while (ST->getOpcode() != ISD::DELETED_NODE);
9714 return SDValue(N, 0);
9717 return ReduceLoadOpStoreWidth(N);
9720 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9721 SDValue InVec = N->getOperand(0);
9722 SDValue InVal = N->getOperand(1);
9723 SDValue EltNo = N->getOperand(2);
9726 // If the inserted element is an UNDEF, just use the input vector.
9727 if (InVal.getOpcode() == ISD::UNDEF)
9730 EVT VT = InVec.getValueType();
9732 // If we can't generate a legal BUILD_VECTOR, exit
9733 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9736 // Check that we know which element is being inserted
9737 if (!isa<ConstantSDNode>(EltNo))
9739 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9741 // Canonicalize insert_vector_elt dag nodes.
9743 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9744 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9746 // Do this only if the child insert_vector node has one use; also
9747 // do this only if indices are both constants and Idx1 < Idx0.
9748 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9749 && isa<ConstantSDNode>(InVec.getOperand(2))) {
9751 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9752 if (Elt < OtherElt) {
9754 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9755 InVec.getOperand(0), InVal, EltNo);
9756 AddToWorklist(NewOp.getNode());
9757 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9758 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9762 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9763 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9765 SmallVector<SDValue, 8> Ops;
9766 // Do not combine these two vectors if the output vector will not replace
9767 // the input vector.
9768 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9769 Ops.append(InVec.getNode()->op_begin(),
9770 InVec.getNode()->op_end());
9771 } else if (InVec.getOpcode() == ISD::UNDEF) {
9772 unsigned NElts = VT.getVectorNumElements();
9773 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9778 // Insert the element
9779 if (Elt < Ops.size()) {
9780 // All the operands of BUILD_VECTOR must have the same type;
9781 // we enforce that here.
9782 EVT OpVT = Ops[0].getValueType();
9783 if (InVal.getValueType() != OpVT)
9784 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9785 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9786 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9790 // Return the new vector
9791 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
9794 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9795 // (vextract (scalar_to_vector val, 0) -> val
9796 SDValue InVec = N->getOperand(0);
9797 EVT VT = InVec.getValueType();
9798 EVT NVT = N->getValueType(0);
9800 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9801 // Check if the result type doesn't match the inserted element type. A
9802 // SCALAR_TO_VECTOR may truncate the inserted element and the
9803 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9804 SDValue InOp = InVec.getOperand(0);
9805 if (InOp.getValueType() != NVT) {
9806 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9807 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9812 SDValue EltNo = N->getOperand(1);
9813 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9815 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9816 // We only perform this optimization before the op legalization phase because
9817 // we may introduce new vector instructions which are not backed by TD
9818 // patterns. For example on AVX, extracting elements from a wide vector
9819 // without using extract_subvector. However, if we can find an underlying
9820 // scalar value, then we can always use that.
9821 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9823 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9824 int NumElem = VT.getVectorNumElements();
9825 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9826 // Find the new index to extract from.
9827 int OrigElt = SVOp->getMaskElt(Elt);
9829 // Extracting an undef index is undef.
9831 return DAG.getUNDEF(NVT);
9833 // Select the right vector half to extract from.
9835 if (OrigElt < NumElem) {
9836 SVInVec = InVec->getOperand(0);
9838 SVInVec = InVec->getOperand(1);
9842 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9843 SDValue InOp = SVInVec.getOperand(OrigElt);
9844 if (InOp.getValueType() != NVT) {
9845 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9846 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9852 // FIXME: We should handle recursing on other vector shuffles and
9853 // scalar_to_vector here as well.
9855 if (!LegalOperations) {
9856 EVT IndexTy = TLI.getVectorIdxTy();
9857 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9858 SVInVec, DAG.getConstant(OrigElt, IndexTy));
9862 // Perform only after legalization to ensure build_vector / vector_shuffle
9863 // optimizations have already been done.
9864 if (!LegalOperations) return SDValue();
9866 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9867 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9868 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9871 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9872 bool NewLoad = false;
9873 bool BCNumEltsChanged = false;
9874 EVT ExtVT = VT.getVectorElementType();
9877 // If the result of load has to be truncated, then it's not necessarily
9879 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9882 if (InVec.getOpcode() == ISD::BITCAST) {
9883 // Don't duplicate a load with other uses.
9884 if (!InVec.hasOneUse())
9887 EVT BCVT = InVec.getOperand(0).getValueType();
9888 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9890 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9891 BCNumEltsChanged = true;
9892 InVec = InVec.getOperand(0);
9893 ExtVT = BCVT.getVectorElementType();
9897 LoadSDNode *LN0 = nullptr;
9898 const ShuffleVectorSDNode *SVN = nullptr;
9899 if (ISD::isNormalLoad(InVec.getNode())) {
9900 LN0 = cast<LoadSDNode>(InVec);
9901 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9902 InVec.getOperand(0).getValueType() == ExtVT &&
9903 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9904 // Don't duplicate a load with other uses.
9905 if (!InVec.hasOneUse())
9908 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9909 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9910 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9912 // (load $addr+1*size)
9914 // Don't duplicate a load with other uses.
9915 if (!InVec.hasOneUse())
9918 // If the bit convert changed the number of elements, it is unsafe
9919 // to examine the mask.
9920 if (BCNumEltsChanged)
9923 // Select the input vector, guarding against out of range extract vector.
9924 unsigned NumElems = VT.getVectorNumElements();
9925 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9926 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9928 if (InVec.getOpcode() == ISD::BITCAST) {
9929 // Don't duplicate a load with other uses.
9930 if (!InVec.hasOneUse())
9933 InVec = InVec.getOperand(0);
9935 if (ISD::isNormalLoad(InVec.getNode())) {
9936 LN0 = cast<LoadSDNode>(InVec);
9937 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9941 // Make sure we found a non-volatile load and the extractelement is
9943 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9946 // If Idx was -1 above, Elt is going to be -1, so just return undef.
9948 return DAG.getUNDEF(LVT);
9950 unsigned Align = LN0->getAlignment();
9952 // Check the resultant load doesn't need a higher alignment than the
9956 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9958 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9964 SDValue NewPtr = LN0->getBasePtr();
9965 unsigned PtrOff = 0;
9968 PtrOff = LVT.getSizeInBits() * Elt / 8;
9969 EVT PtrType = NewPtr.getValueType();
9970 if (TLI.isBigEndian())
9971 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9972 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9973 DAG.getConstant(PtrOff, PtrType));
9976 // The replacement we need to do here is a little tricky: we need to
9977 // replace an extractelement of a load with a load.
9978 // Use ReplaceAllUsesOfValuesWith to do the replacement.
9979 // Note that this replacement assumes that the extractvalue is the only
9980 // use of the load; that's okay because we don't want to perform this
9981 // transformation in other cases anyway.
9984 if (NVT.bitsGT(LVT)) {
9985 // If the result type of vextract is wider than the load, then issue an
9986 // extending load instead.
9987 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9988 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9989 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9990 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9991 LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9992 Align, LN0->getTBAAInfo());
9993 Chain = Load.getValue(1);
9995 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9996 LN0->getPointerInfo().getWithOffset(PtrOff),
9997 LN0->isVolatile(), LN0->isNonTemporal(),
9998 LN0->isInvariant(), Align, LN0->getTBAAInfo());
9999 Chain = Load.getValue(1);
10000 if (NVT.bitsLT(LVT))
10001 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
10003 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
10005 WorklistRemover DeadNodes(*this);
10006 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
10007 SDValue To[] = { Load, Chain };
10008 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10009 // Since we're explcitly calling ReplaceAllUses, add the new node to the
10010 // worklist explicitly as well.
10011 AddToWorklist(Load.getNode());
10012 AddUsersToWorklist(Load.getNode()); // Add users too
10013 // Make sure to revisit this node to clean it up; it will usually be dead.
10015 return SDValue(N, 0);
10021 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10022 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10023 // We perform this optimization post type-legalization because
10024 // the type-legalizer often scalarizes integer-promoted vectors.
10025 // Performing this optimization before may create bit-casts which
10026 // will be type-legalized to complex code sequences.
10027 // We perform this optimization only before the operation legalizer because we
10028 // may introduce illegal operations.
10029 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10032 unsigned NumInScalars = N->getNumOperands();
10034 EVT VT = N->getValueType(0);
10036 // Check to see if this is a BUILD_VECTOR of a bunch of values
10037 // which come from any_extend or zero_extend nodes. If so, we can create
10038 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10039 // optimizations. We do not handle sign-extend because we can't fill the sign
10041 EVT SourceType = MVT::Other;
10042 bool AllAnyExt = true;
10044 for (unsigned i = 0; i != NumInScalars; ++i) {
10045 SDValue In = N->getOperand(i);
10046 // Ignore undef inputs.
10047 if (In.getOpcode() == ISD::UNDEF) continue;
10049 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
10050 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10052 // Abort if the element is not an extension.
10053 if (!ZeroExt && !AnyExt) {
10054 SourceType = MVT::Other;
10058 // The input is a ZeroExt or AnyExt. Check the original type.
10059 EVT InTy = In.getOperand(0).getValueType();
10061 // Check that all of the widened source types are the same.
10062 if (SourceType == MVT::Other)
10065 else if (InTy != SourceType) {
10066 // Multiple income types. Abort.
10067 SourceType = MVT::Other;
10071 // Check if all of the extends are ANY_EXTENDs.
10072 AllAnyExt &= AnyExt;
10075 // In order to have valid types, all of the inputs must be extended from the
10076 // same source type and all of the inputs must be any or zero extend.
10077 // Scalar sizes must be a power of two.
10078 EVT OutScalarTy = VT.getScalarType();
10079 bool ValidTypes = SourceType != MVT::Other &&
10080 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10081 isPowerOf2_32(SourceType.getSizeInBits());
10083 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10084 // turn into a single shuffle instruction.
10088 bool isLE = TLI.isLittleEndian();
10089 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10090 assert(ElemRatio > 1 && "Invalid element size ratio");
10091 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10092 DAG.getConstant(0, SourceType);
10094 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10095 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10097 // Populate the new build_vector
10098 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10099 SDValue Cast = N->getOperand(i);
10100 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10101 Cast.getOpcode() == ISD::ZERO_EXTEND ||
10102 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10104 if (Cast.getOpcode() == ISD::UNDEF)
10105 In = DAG.getUNDEF(SourceType);
10107 In = Cast->getOperand(0);
10108 unsigned Index = isLE ? (i * ElemRatio) :
10109 (i * ElemRatio + (ElemRatio - 1));
10111 assert(Index < Ops.size() && "Invalid index");
10115 // The type of the new BUILD_VECTOR node.
10116 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10117 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10118 "Invalid vector size");
10119 // Check if the new vector type is legal.
10120 if (!isTypeLegal(VecVT)) return SDValue();
10122 // Make the new BUILD_VECTOR.
10123 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10125 // The new BUILD_VECTOR node has the potential to be further optimized.
10126 AddToWorklist(BV.getNode());
10127 // Bitcast to the desired type.
10128 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10131 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10132 EVT VT = N->getValueType(0);
10134 unsigned NumInScalars = N->getNumOperands();
10137 EVT SrcVT = MVT::Other;
10138 unsigned Opcode = ISD::DELETED_NODE;
10139 unsigned NumDefs = 0;
10141 for (unsigned i = 0; i != NumInScalars; ++i) {
10142 SDValue In = N->getOperand(i);
10143 unsigned Opc = In.getOpcode();
10145 if (Opc == ISD::UNDEF)
10148 // If all scalar values are floats and converted from integers.
10149 if (Opcode == ISD::DELETED_NODE &&
10150 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10157 EVT InVT = In.getOperand(0).getValueType();
10159 // If all scalar values are typed differently, bail out. It's chosen to
10160 // simplify BUILD_VECTOR of integer types.
10161 if (SrcVT == MVT::Other)
10168 // If the vector has just one element defined, it's not worth to fold it into
10169 // a vectorized one.
10173 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10174 && "Should only handle conversion from integer to float.");
10175 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10177 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10179 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10182 SmallVector<SDValue, 8> Opnds;
10183 for (unsigned i = 0; i != NumInScalars; ++i) {
10184 SDValue In = N->getOperand(i);
10186 if (In.getOpcode() == ISD::UNDEF)
10187 Opnds.push_back(DAG.getUNDEF(SrcVT));
10189 Opnds.push_back(In.getOperand(0));
10191 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10192 AddToWorklist(BV.getNode());
10194 return DAG.getNode(Opcode, dl, VT, BV);
10197 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10198 unsigned NumInScalars = N->getNumOperands();
10200 EVT VT = N->getValueType(0);
10202 // A vector built entirely of undefs is undef.
10203 if (ISD::allOperandsUndef(N))
10204 return DAG.getUNDEF(VT);
10206 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10210 V = reduceBuildVecConvertToConvertBuildVec(N);
10214 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10215 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10216 // at most two distinct vectors, turn this into a shuffle node.
10218 // May only combine to shuffle after legalize if shuffle is legal.
10219 if (LegalOperations &&
10220 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10223 SDValue VecIn1, VecIn2;
10224 for (unsigned i = 0; i != NumInScalars; ++i) {
10225 // Ignore undef inputs.
10226 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10228 // If this input is something other than a EXTRACT_VECTOR_ELT with a
10229 // constant index, bail out.
10230 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10231 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10232 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10236 // We allow up to two distinct input vectors.
10237 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10238 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10241 if (!VecIn1.getNode()) {
10242 VecIn1 = ExtractedFromVec;
10243 } else if (!VecIn2.getNode()) {
10244 VecIn2 = ExtractedFromVec;
10246 // Too many inputs.
10247 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10252 // If everything is good, we can make a shuffle operation.
10253 if (VecIn1.getNode()) {
10254 SmallVector<int, 8> Mask;
10255 for (unsigned i = 0; i != NumInScalars; ++i) {
10256 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10257 Mask.push_back(-1);
10261 // If extracting from the first vector, just use the index directly.
10262 SDValue Extract = N->getOperand(i);
10263 SDValue ExtVal = Extract.getOperand(1);
10264 if (Extract.getOperand(0) == VecIn1) {
10265 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10266 if (ExtIndex > VT.getVectorNumElements())
10269 Mask.push_back(ExtIndex);
10273 // Otherwise, use InIdx + VecSize
10274 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10275 Mask.push_back(Idx+NumInScalars);
10278 // We can't generate a shuffle node with mismatched input and output types.
10279 // Attempt to transform a single input vector to the correct type.
10280 if ((VT != VecIn1.getValueType())) {
10281 // We don't support shuffeling between TWO values of different types.
10282 if (VecIn2.getNode())
10285 // We only support widening of vectors which are half the size of the
10286 // output registers. For example XMM->YMM widening on X86 with AVX.
10287 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10290 // If the input vector type has a different base type to the output
10291 // vector type, bail out.
10292 if (VecIn1.getValueType().getVectorElementType() !=
10293 VT.getVectorElementType())
10296 // Widen the input vector by adding undef values.
10297 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10298 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10301 // If VecIn2 is unused then change it to undef.
10302 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10304 // Check that we were able to transform all incoming values to the same
10306 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10307 VecIn1.getValueType() != VT)
10310 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10311 if (!isTypeLegal(VT))
10314 // Return the new VECTOR_SHUFFLE node.
10318 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10324 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10325 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10326 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10327 // inputs come from at most two distinct vectors, turn this into a shuffle
10330 // If we only have one input vector, we don't need to do any concatenation.
10331 if (N->getNumOperands() == 1)
10332 return N->getOperand(0);
10334 // Check if all of the operands are undefs.
10335 EVT VT = N->getValueType(0);
10336 if (ISD::allOperandsUndef(N))
10337 return DAG.getUNDEF(VT);
10339 // Optimize concat_vectors where one of the vectors is undef.
10340 if (N->getNumOperands() == 2 &&
10341 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10342 SDValue In = N->getOperand(0);
10343 assert(In.getValueType().isVector() && "Must concat vectors");
10345 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10346 if (In->getOpcode() == ISD::BITCAST &&
10347 !In->getOperand(0)->getValueType(0).isVector()) {
10348 SDValue Scalar = In->getOperand(0);
10349 EVT SclTy = Scalar->getValueType(0);
10351 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10354 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10355 VT.getSizeInBits() / SclTy.getSizeInBits());
10356 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10359 SDLoc dl = SDLoc(N);
10360 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10361 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10365 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10366 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10367 if (N->getNumOperands() == 2 &&
10368 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10369 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10370 EVT VT = N->getValueType(0);
10371 SDValue N0 = N->getOperand(0);
10372 SDValue N1 = N->getOperand(1);
10373 SmallVector<SDValue, 8> Opnds;
10374 unsigned BuildVecNumElts = N0.getNumOperands();
10376 EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10377 EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10378 if (SclTy0.isFloatingPoint()) {
10379 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10380 Opnds.push_back(N0.getOperand(i));
10381 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10382 Opnds.push_back(N1.getOperand(i));
10384 // If BUILD_VECTOR are from built from integer, they may have different
10385 // operand types. Get the smaller type and truncate all operands to it.
10386 EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10387 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10388 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10389 N0.getOperand(i)));
10390 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10391 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10392 N1.getOperand(i)));
10395 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10398 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10399 // nodes often generate nop CONCAT_VECTOR nodes.
10400 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10401 // place the incoming vectors at the exact same location.
10402 SDValue SingleSource = SDValue();
10403 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10405 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10406 SDValue Op = N->getOperand(i);
10408 if (Op.getOpcode() == ISD::UNDEF)
10411 // Check if this is the identity extract:
10412 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10415 // Find the single incoming vector for the extract_subvector.
10416 if (SingleSource.getNode()) {
10417 if (Op.getOperand(0) != SingleSource)
10420 SingleSource = Op.getOperand(0);
10422 // Check the source type is the same as the type of the result.
10423 // If not, this concat may extend the vector, so we can not
10424 // optimize it away.
10425 if (SingleSource.getValueType() != N->getValueType(0))
10429 unsigned IdentityIndex = i * PartNumElem;
10430 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10431 // The extract index must be constant.
10435 // Check that we are reading from the identity index.
10436 if (CS->getZExtValue() != IdentityIndex)
10440 if (SingleSource.getNode())
10441 return SingleSource;
10446 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10447 EVT NVT = N->getValueType(0);
10448 SDValue V = N->getOperand(0);
10450 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10452 // (extract_subvec (concat V1, V2, ...), i)
10455 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10457 if (V->getOperand(0).getValueType() != NVT)
10459 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10460 unsigned NumElems = NVT.getVectorNumElements();
10461 assert((Idx % NumElems) == 0 &&
10462 "IDX in concat is not a multiple of the result vector length.");
10463 return V->getOperand(Idx / NumElems);
10467 if (V->getOpcode() == ISD::BITCAST)
10468 V = V.getOperand(0);
10470 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10472 // Handle only simple case where vector being inserted and vector
10473 // being extracted are of same type, and are half size of larger vectors.
10474 EVT BigVT = V->getOperand(0).getValueType();
10475 EVT SmallVT = V->getOperand(1).getValueType();
10476 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10479 // Only handle cases where both indexes are constants with the same type.
10480 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10481 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10483 if (InsIdx && ExtIdx &&
10484 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10485 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10487 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10489 // indices are equal or bit offsets are equal => V1
10490 // otherwise => (extract_subvec V1, ExtIdx)
10491 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10492 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10493 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10494 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10495 DAG.getNode(ISD::BITCAST, dl,
10496 N->getOperand(0).getValueType(),
10497 V->getOperand(0)), N->getOperand(1));
10504 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10505 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10506 EVT VT = N->getValueType(0);
10507 unsigned NumElts = VT.getVectorNumElements();
10509 SDValue N0 = N->getOperand(0);
10510 SDValue N1 = N->getOperand(1);
10511 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10513 SmallVector<SDValue, 4> Ops;
10514 EVT ConcatVT = N0.getOperand(0).getValueType();
10515 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10516 unsigned NumConcats = NumElts / NumElemsPerConcat;
10518 // Look at every vector that's inserted. We're looking for exact
10519 // subvector-sized copies from a concatenated vector
10520 for (unsigned I = 0; I != NumConcats; ++I) {
10521 // Make sure we're dealing with a copy.
10522 unsigned Begin = I * NumElemsPerConcat;
10523 bool AllUndef = true, NoUndef = true;
10524 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10525 if (SVN->getMaskElt(J) >= 0)
10532 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10535 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10536 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10539 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10540 if (FirstElt < N0.getNumOperands())
10541 Ops.push_back(N0.getOperand(FirstElt));
10543 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10545 } else if (AllUndef) {
10546 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10547 } else { // Mixed with general masks and undefs, can't do optimization.
10552 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10555 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10556 EVT VT = N->getValueType(0);
10557 unsigned NumElts = VT.getVectorNumElements();
10559 SDValue N0 = N->getOperand(0);
10560 SDValue N1 = N->getOperand(1);
10562 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10564 // Canonicalize shuffle undef, undef -> undef
10565 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10566 return DAG.getUNDEF(VT);
10568 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10570 // Canonicalize shuffle v, v -> v, undef
10572 SmallVector<int, 8> NewMask;
10573 for (unsigned i = 0; i != NumElts; ++i) {
10574 int Idx = SVN->getMaskElt(i);
10575 if (Idx >= (int)NumElts) Idx -= NumElts;
10576 NewMask.push_back(Idx);
10578 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10582 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10583 if (N0.getOpcode() == ISD::UNDEF) {
10584 SmallVector<int, 8> NewMask;
10585 for (unsigned i = 0; i != NumElts; ++i) {
10586 int Idx = SVN->getMaskElt(i);
10588 if (Idx >= (int)NumElts)
10591 Idx = -1; // remove reference to lhs
10593 NewMask.push_back(Idx);
10595 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10599 // Remove references to rhs if it is undef
10600 if (N1.getOpcode() == ISD::UNDEF) {
10601 bool Changed = false;
10602 SmallVector<int, 8> NewMask;
10603 for (unsigned i = 0; i != NumElts; ++i) {
10604 int Idx = SVN->getMaskElt(i);
10605 if (Idx >= (int)NumElts) {
10609 NewMask.push_back(Idx);
10612 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10615 // If it is a splat, check if the argument vector is another splat or a
10616 // build_vector with all scalar elements the same.
10617 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10618 SDNode *V = N0.getNode();
10620 // If this is a bit convert that changes the element type of the vector but
10621 // not the number of vector elements, look through it. Be careful not to
10622 // look though conversions that change things like v4f32 to v2f64.
10623 if (V->getOpcode() == ISD::BITCAST) {
10624 SDValue ConvInput = V->getOperand(0);
10625 if (ConvInput.getValueType().isVector() &&
10626 ConvInput.getValueType().getVectorNumElements() == NumElts)
10627 V = ConvInput.getNode();
10630 if (V->getOpcode() == ISD::BUILD_VECTOR) {
10631 assert(V->getNumOperands() == NumElts &&
10632 "BUILD_VECTOR has wrong number of operands");
10634 bool AllSame = true;
10635 for (unsigned i = 0; i != NumElts; ++i) {
10636 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10637 Base = V->getOperand(i);
10641 // Splat of <u, u, u, u>, return <u, u, u, u>
10642 if (!Base.getNode())
10644 for (unsigned i = 0; i != NumElts; ++i) {
10645 if (V->getOperand(i) != Base) {
10650 // Splat of <x, x, x, x>, return <x, x, x, x>
10656 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10657 Level < AfterLegalizeVectorOps &&
10658 (N1.getOpcode() == ISD::UNDEF ||
10659 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10660 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10661 SDValue V = partitionShuffleOfConcats(N, DAG);
10667 // If this shuffle node is simply a swizzle of another shuffle node,
10668 // then try to simplify it.
10669 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10670 N1.getOpcode() == ISD::UNDEF) {
10672 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10674 // The incoming shuffle must be of the same type as the result of the
10675 // current shuffle.
10676 assert(OtherSV->getOperand(0).getValueType() == VT &&
10677 "Shuffle types don't match");
10679 SmallVector<int, 4> Mask;
10680 // Compute the combined shuffle mask.
10681 for (unsigned i = 0; i != NumElts; ++i) {
10682 int Idx = SVN->getMaskElt(i);
10683 assert(Idx < (int)NumElts && "Index references undef operand");
10684 // Next, this index comes from the first value, which is the incoming
10685 // shuffle. Adopt the incoming index.
10687 Idx = OtherSV->getMaskElt(Idx);
10688 Mask.push_back(Idx);
10691 bool CommuteOperands = false;
10692 if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
10693 // To be valid, the combine shuffle mask should only reference elements
10694 // from one of the two vectors in input to the inner shufflevector.
10695 bool IsValidMask = true;
10696 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10697 // See if the combined mask only reference undefs or elements coming
10698 // from the first shufflevector operand.
10699 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
10701 if (!IsValidMask) {
10702 IsValidMask = true;
10703 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10704 // Check that all the elements come from the second shuffle operand.
10705 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
10706 CommuteOperands = IsValidMask;
10709 // Early exit if the combined shuffle mask is not valid.
10714 // See if this pair of shuffles can be safely folded according to either
10715 // of the following rules:
10716 // shuffle(shuffle(x, y), undef) -> x
10717 // shuffle(shuffle(x, undef), undef) -> x
10718 // shuffle(shuffle(x, y), undef) -> y
10719 bool IsIdentityMask = true;
10720 unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
10721 for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
10726 // The combined shuffle must map each index to itself.
10727 IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
10730 if (IsIdentityMask) {
10731 if (CommuteOperands)
10732 // optimize shuffle(shuffle(x, y), undef) -> y.
10733 return OtherSV->getOperand(1);
10735 // optimize shuffle(shuffle(x, undef), undef) -> x
10736 // optimize shuffle(shuffle(x, y), undef) -> x
10737 return OtherSV->getOperand(0);
10740 // It may still be beneficial to combine the two shuffles if the
10741 // resulting shuffle is legal.
10742 if (TLI.isTypeLegal(VT) && TLI.isShuffleMaskLegal(Mask, VT)) {
10743 if (!CommuteOperands)
10744 // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
10745 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
10746 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
10749 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(undef, y, M3)
10750 return DAG.getVectorShuffle(VT, SDLoc(N), N1, N0->getOperand(1),
10755 // Canonicalize shuffles according to rules:
10756 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
10757 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
10758 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
10759 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
10760 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10761 TLI.isTypeLegal(VT)) {
10762 // The incoming shuffle must be of the same type as the result of the
10763 // current shuffle.
10764 assert(N1->getOperand(0).getValueType() == VT &&
10765 "Shuffle types don't match");
10767 SDValue SV0 = N1->getOperand(0);
10768 SDValue SV1 = N1->getOperand(1);
10769 bool HasSameOp0 = N0 == SV0;
10770 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10771 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
10772 // Commute the operands of this shuffle so that next rule
10774 return DAG.getCommutedVectorShuffle(*SVN);
10777 // Try to fold according to rules:
10778 // shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
10779 // shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
10780 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10781 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10782 // Don't try to fold shuffles with illegal type.
10783 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10784 N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
10785 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10787 // The incoming shuffle must be of the same type as the result of the
10788 // current shuffle.
10789 assert(OtherSV->getOperand(0).getValueType() == VT &&
10790 "Shuffle types don't match");
10792 SDValue SV0 = OtherSV->getOperand(0);
10793 SDValue SV1 = OtherSV->getOperand(1);
10794 bool HasSameOp0 = N1 == SV0;
10795 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10796 if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
10800 SmallVector<int, 4> Mask;
10801 // Compute the combined shuffle mask for a shuffle with SV0 as the first
10802 // operand, and SV1 as the second operand.
10803 for (unsigned i = 0; i != NumElts; ++i) {
10804 int Idx = SVN->getMaskElt(i);
10806 // Propagate Undef.
10807 Mask.push_back(Idx);
10811 if (Idx < (int)NumElts) {
10812 Idx = OtherSV->getMaskElt(Idx);
10813 if (IsSV1Undef && Idx >= (int) NumElts)
10814 Idx = -1; // Propagate Undef.
10816 Idx = HasSameOp0 ? Idx - NumElts : Idx;
10818 Mask.push_back(Idx);
10821 // Avoid introducing shuffles with illegal mask.
10822 if (TLI.isShuffleMaskLegal(Mask, VT)) {
10824 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10825 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10826 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
10827 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
10834 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10835 SDValue N0 = N->getOperand(0);
10836 SDValue N2 = N->getOperand(2);
10838 // If the input vector is a concatenation, and the insert replaces
10839 // one of the halves, we can optimize into a single concat_vectors.
10840 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10841 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10842 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10843 EVT VT = N->getValueType(0);
10845 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10846 // (concat_vectors Z, Y)
10848 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10849 N->getOperand(1), N0.getOperand(1));
10851 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10852 // (concat_vectors X, Z)
10853 if (InsIdx == VT.getVectorNumElements()/2)
10854 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10855 N0.getOperand(0), N->getOperand(1));
10861 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10862 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10863 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10864 /// vector_shuffle V, Zero, <0, 4, 2, 4>
10865 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10866 EVT VT = N->getValueType(0);
10868 SDValue LHS = N->getOperand(0);
10869 SDValue RHS = N->getOperand(1);
10870 if (N->getOpcode() == ISD::AND) {
10871 if (RHS.getOpcode() == ISD::BITCAST)
10872 RHS = RHS.getOperand(0);
10873 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10874 SmallVector<int, 8> Indices;
10875 unsigned NumElts = RHS.getNumOperands();
10876 for (unsigned i = 0; i != NumElts; ++i) {
10877 SDValue Elt = RHS.getOperand(i);
10878 if (!isa<ConstantSDNode>(Elt))
10881 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10882 Indices.push_back(i);
10883 else if (cast<ConstantSDNode>(Elt)->isNullValue())
10884 Indices.push_back(NumElts);
10889 // Let's see if the target supports this vector_shuffle.
10890 EVT RVT = RHS.getValueType();
10891 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10894 // Return the new VECTOR_SHUFFLE node.
10895 EVT EltVT = RVT.getVectorElementType();
10896 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10897 DAG.getConstant(0, EltVT));
10898 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
10899 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10900 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10901 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10908 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10909 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10910 assert(N->getValueType(0).isVector() &&
10911 "SimplifyVBinOp only works on vectors!");
10913 SDValue LHS = N->getOperand(0);
10914 SDValue RHS = N->getOperand(1);
10915 SDValue Shuffle = XformToShuffleWithZero(N);
10916 if (Shuffle.getNode()) return Shuffle;
10918 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10920 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10921 RHS.getOpcode() == ISD::BUILD_VECTOR) {
10922 // Check if both vectors are constants. If not bail out.
10923 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10924 cast<BuildVectorSDNode>(RHS)->isConstant()))
10927 SmallVector<SDValue, 8> Ops;
10928 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10929 SDValue LHSOp = LHS.getOperand(i);
10930 SDValue RHSOp = RHS.getOperand(i);
10932 // Can't fold divide by zero.
10933 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10934 N->getOpcode() == ISD::FDIV) {
10935 if ((RHSOp.getOpcode() == ISD::Constant &&
10936 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10937 (RHSOp.getOpcode() == ISD::ConstantFP &&
10938 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10942 EVT VT = LHSOp.getValueType();
10943 EVT RVT = RHSOp.getValueType();
10945 // Integer BUILD_VECTOR operands may have types larger than the element
10946 // size (e.g., when the element type is not legal). Prior to type
10947 // legalization, the types may not match between the two BUILD_VECTORS.
10948 // Truncate one of the operands to make them match.
10949 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10950 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10952 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10956 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10958 if (FoldOp.getOpcode() != ISD::UNDEF &&
10959 FoldOp.getOpcode() != ISD::Constant &&
10960 FoldOp.getOpcode() != ISD::ConstantFP)
10962 Ops.push_back(FoldOp);
10963 AddToWorklist(FoldOp.getNode());
10966 if (Ops.size() == LHS.getNumOperands())
10967 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
10970 // Type legalization might introduce new shuffles in the DAG.
10971 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
10972 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
10973 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
10974 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
10975 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
10976 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
10977 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
10978 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
10980 if (SVN0->getMask().equals(SVN1->getMask())) {
10981 EVT VT = N->getValueType(0);
10982 SDValue UndefVector = LHS.getOperand(1);
10983 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
10984 LHS.getOperand(0), RHS.getOperand(0));
10985 AddUsersToWorklist(N);
10986 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
10987 &SVN0->getMask()[0]);
10994 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10995 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10996 assert(N->getValueType(0).isVector() &&
10997 "SimplifyVUnaryOp only works on vectors!");
10999 SDValue N0 = N->getOperand(0);
11001 if (N0.getOpcode() != ISD::BUILD_VECTOR)
11004 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11005 SmallVector<SDValue, 8> Ops;
11006 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11007 SDValue Op = N0.getOperand(i);
11008 if (Op.getOpcode() != ISD::UNDEF &&
11009 Op.getOpcode() != ISD::ConstantFP)
11011 EVT EltVT = Op.getValueType();
11012 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11013 if (FoldOp.getOpcode() != ISD::UNDEF &&
11014 FoldOp.getOpcode() != ISD::ConstantFP)
11016 Ops.push_back(FoldOp);
11017 AddToWorklist(FoldOp.getNode());
11020 if (Ops.size() != N0.getNumOperands())
11023 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11026 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11027 SDValue N1, SDValue N2){
11028 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11030 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11031 cast<CondCodeSDNode>(N0.getOperand(2))->get());
11033 // If we got a simplified select_cc node back from SimplifySelectCC, then
11034 // break it down into a new SETCC node, and a new SELECT node, and then return
11035 // the SELECT node, since we were called with a SELECT node.
11036 if (SCC.getNode()) {
11037 // Check to see if we got a select_cc back (to turn into setcc/select).
11038 // Otherwise, just return whatever node we got back, like fabs.
11039 if (SCC.getOpcode() == ISD::SELECT_CC) {
11040 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11042 SCC.getOperand(0), SCC.getOperand(1),
11043 SCC.getOperand(4));
11044 AddToWorklist(SETCC.getNode());
11045 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
11046 SCC.getOperand(2), SCC.getOperand(3), SETCC);
11054 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
11055 /// are the two values being selected between, see if we can simplify the
11056 /// select. Callers of this should assume that TheSelect is deleted if this
11057 /// returns true. As such, they should return the appropriate thing (e.g. the
11058 /// node) back to the top-level of the DAG combiner loop to avoid it being
11060 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11063 // Cannot simplify select with vector condition
11064 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11066 // If this is a select from two identical things, try to pull the operation
11067 // through the select.
11068 if (LHS.getOpcode() != RHS.getOpcode() ||
11069 !LHS.hasOneUse() || !RHS.hasOneUse())
11072 // If this is a load and the token chain is identical, replace the select
11073 // of two loads with a load through a select of the address to load from.
11074 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11075 // constants have been dropped into the constant pool.
11076 if (LHS.getOpcode() == ISD::LOAD) {
11077 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11078 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11080 // Token chains must be identical.
11081 if (LHS.getOperand(0) != RHS.getOperand(0) ||
11082 // Do not let this transformation reduce the number of volatile loads.
11083 LLD->isVolatile() || RLD->isVolatile() ||
11084 // If this is an EXTLOAD, the VT's must match.
11085 LLD->getMemoryVT() != RLD->getMemoryVT() ||
11086 // If this is an EXTLOAD, the kind of extension must match.
11087 (LLD->getExtensionType() != RLD->getExtensionType() &&
11088 // The only exception is if one of the extensions is anyext.
11089 LLD->getExtensionType() != ISD::EXTLOAD &&
11090 RLD->getExtensionType() != ISD::EXTLOAD) ||
11091 // FIXME: this discards src value information. This is
11092 // over-conservative. It would be beneficial to be able to remember
11093 // both potential memory locations. Since we are discarding
11094 // src value info, don't do the transformation if the memory
11095 // locations are not in the default address space.
11096 LLD->getPointerInfo().getAddrSpace() != 0 ||
11097 RLD->getPointerInfo().getAddrSpace() != 0 ||
11098 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11099 LLD->getBasePtr().getValueType()))
11102 // Check that the select condition doesn't reach either load. If so,
11103 // folding this will induce a cycle into the DAG. If not, this is safe to
11104 // xform, so create a select of the addresses.
11106 if (TheSelect->getOpcode() == ISD::SELECT) {
11107 SDNode *CondNode = TheSelect->getOperand(0).getNode();
11108 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11109 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11111 // The loads must not depend on one another.
11112 if (LLD->isPredecessorOf(RLD) ||
11113 RLD->isPredecessorOf(LLD))
11115 Addr = DAG.getSelect(SDLoc(TheSelect),
11116 LLD->getBasePtr().getValueType(),
11117 TheSelect->getOperand(0), LLD->getBasePtr(),
11118 RLD->getBasePtr());
11119 } else { // Otherwise SELECT_CC
11120 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11121 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11123 if ((LLD->hasAnyUseOfValue(1) &&
11124 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11125 (RLD->hasAnyUseOfValue(1) &&
11126 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11129 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11130 LLD->getBasePtr().getValueType(),
11131 TheSelect->getOperand(0),
11132 TheSelect->getOperand(1),
11133 LLD->getBasePtr(), RLD->getBasePtr(),
11134 TheSelect->getOperand(4));
11138 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11139 Load = DAG.getLoad(TheSelect->getValueType(0),
11141 // FIXME: Discards pointer and TBAA info.
11142 LLD->getChain(), Addr, MachinePointerInfo(),
11143 LLD->isVolatile(), LLD->isNonTemporal(),
11144 LLD->isInvariant(), LLD->getAlignment());
11146 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11147 RLD->getExtensionType() : LLD->getExtensionType(),
11149 TheSelect->getValueType(0),
11150 // FIXME: Discards pointer and TBAA info.
11151 LLD->getChain(), Addr, MachinePointerInfo(),
11152 LLD->getMemoryVT(), LLD->isVolatile(),
11153 LLD->isNonTemporal(), LLD->getAlignment());
11156 // Users of the select now use the result of the load.
11157 CombineTo(TheSelect, Load);
11159 // Users of the old loads now use the new load's chain. We know the
11160 // old-load value is dead now.
11161 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11162 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11169 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
11170 /// where 'cond' is the comparison specified by CC.
11171 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11172 SDValue N2, SDValue N3,
11173 ISD::CondCode CC, bool NotExtCompare) {
11174 // (x ? y : y) -> y.
11175 if (N2 == N3) return N2;
11177 EVT VT = N2.getValueType();
11178 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11179 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11180 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11182 // Determine if the condition we're dealing with is constant
11183 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11184 N0, N1, CC, DL, false);
11185 if (SCC.getNode()) AddToWorklist(SCC.getNode());
11186 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11188 // fold select_cc true, x, y -> x
11189 if (SCCC && !SCCC->isNullValue())
11191 // fold select_cc false, x, y -> y
11192 if (SCCC && SCCC->isNullValue())
11195 // Check to see if we can simplify the select into an fabs node
11196 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11197 // Allow either -0.0 or 0.0
11198 if (CFP->getValueAPF().isZero()) {
11199 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11200 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11201 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11202 N2 == N3.getOperand(0))
11203 return DAG.getNode(ISD::FABS, DL, VT, N0);
11205 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11206 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11207 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11208 N2.getOperand(0) == N3)
11209 return DAG.getNode(ISD::FABS, DL, VT, N3);
11213 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11214 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11215 // in it. This is a win when the constant is not otherwise available because
11216 // it replaces two constant pool loads with one. We only do this if the FP
11217 // type is known to be legal, because if it isn't, then we are before legalize
11218 // types an we want the other legalization to happen first (e.g. to avoid
11219 // messing with soft float) and if the ConstantFP is not legal, because if
11220 // it is legal, we may not need to store the FP constant in a constant pool.
11221 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11222 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11223 if (TLI.isTypeLegal(N2.getValueType()) &&
11224 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11225 TargetLowering::Legal &&
11226 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11227 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11228 // If both constants have multiple uses, then we won't need to do an
11229 // extra load, they are likely around in registers for other users.
11230 (TV->hasOneUse() || FV->hasOneUse())) {
11231 Constant *Elts[] = {
11232 const_cast<ConstantFP*>(FV->getConstantFPValue()),
11233 const_cast<ConstantFP*>(TV->getConstantFPValue())
11235 Type *FPTy = Elts[0]->getType();
11236 const DataLayout &TD = *TLI.getDataLayout();
11238 // Create a ConstantArray of the two constants.
11239 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11240 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11241 TD.getPrefTypeAlignment(FPTy));
11242 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11244 // Get the offsets to the 0 and 1 element of the array so that we can
11245 // select between them.
11246 SDValue Zero = DAG.getIntPtrConstant(0);
11247 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11248 SDValue One = DAG.getIntPtrConstant(EltSize);
11250 SDValue Cond = DAG.getSetCC(DL,
11251 getSetCCResultType(N0.getValueType()),
11253 AddToWorklist(Cond.getNode());
11254 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11256 AddToWorklist(CstOffset.getNode());
11257 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11259 AddToWorklist(CPIdx.getNode());
11260 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11261 MachinePointerInfo::getConstantPool(), false,
11262 false, false, Alignment);
11267 // Check to see if we can perform the "gzip trick", transforming
11268 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11269 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11270 (N1C->isNullValue() || // (a < 0) ? b : 0
11271 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
11272 EVT XType = N0.getValueType();
11273 EVT AType = N2.getValueType();
11274 if (XType.bitsGE(AType)) {
11275 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11276 // single-bit constant.
11277 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11278 unsigned ShCtV = N2C->getAPIntValue().logBase2();
11279 ShCtV = XType.getSizeInBits()-ShCtV-1;
11280 SDValue ShCt = DAG.getConstant(ShCtV,
11281 getShiftAmountTy(N0.getValueType()));
11282 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11284 AddToWorklist(Shift.getNode());
11286 if (XType.bitsGT(AType)) {
11287 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11288 AddToWorklist(Shift.getNode());
11291 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11294 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11296 DAG.getConstant(XType.getSizeInBits()-1,
11297 getShiftAmountTy(N0.getValueType())));
11298 AddToWorklist(Shift.getNode());
11300 if (XType.bitsGT(AType)) {
11301 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11302 AddToWorklist(Shift.getNode());
11305 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11309 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11310 // where y is has a single bit set.
11311 // A plaintext description would be, we can turn the SELECT_CC into an AND
11312 // when the condition can be materialized as an all-ones register. Any
11313 // single bit-test can be materialized as an all-ones register with
11314 // shift-left and shift-right-arith.
11315 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11316 N0->getValueType(0) == VT &&
11317 N1C && N1C->isNullValue() &&
11318 N2C && N2C->isNullValue()) {
11319 SDValue AndLHS = N0->getOperand(0);
11320 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11321 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11322 // Shift the tested bit over the sign bit.
11323 APInt AndMask = ConstAndRHS->getAPIntValue();
11325 DAG.getConstant(AndMask.countLeadingZeros(),
11326 getShiftAmountTy(AndLHS.getValueType()));
11327 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11329 // Now arithmetic right shift it all the way over, so the result is either
11330 // all-ones, or zero.
11332 DAG.getConstant(AndMask.getBitWidth()-1,
11333 getShiftAmountTy(Shl.getValueType()));
11334 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11336 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11340 // fold select C, 16, 0 -> shl C, 4
11341 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11342 TLI.getBooleanContents(N0.getValueType()) ==
11343 TargetLowering::ZeroOrOneBooleanContent) {
11345 // If the caller doesn't want us to simplify this into a zext of a compare,
11347 if (NotExtCompare && N2C->getAPIntValue() == 1)
11350 // Get a SetCC of the condition
11351 // NOTE: Don't create a SETCC if it's not legal on this target.
11352 if (!LegalOperations ||
11353 TLI.isOperationLegal(ISD::SETCC,
11354 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11356 // cast from setcc result type to select result type
11358 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11360 if (N2.getValueType().bitsLT(SCC.getValueType()))
11361 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11362 N2.getValueType());
11364 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11365 N2.getValueType(), SCC);
11367 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11368 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11369 N2.getValueType(), SCC);
11372 AddToWorklist(SCC.getNode());
11373 AddToWorklist(Temp.getNode());
11375 if (N2C->getAPIntValue() == 1)
11378 // shl setcc result by log2 n2c
11379 return DAG.getNode(
11380 ISD::SHL, DL, N2.getValueType(), Temp,
11381 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11382 getShiftAmountTy(Temp.getValueType())));
11386 // Check to see if this is the equivalent of setcc
11387 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11388 // otherwise, go ahead with the folds.
11389 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11390 EVT XType = N0.getValueType();
11391 if (!LegalOperations ||
11392 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11393 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11394 if (Res.getValueType() != VT)
11395 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11399 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11400 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11401 (!LegalOperations ||
11402 TLI.isOperationLegal(ISD::CTLZ, XType))) {
11403 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11404 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11405 DAG.getConstant(Log2_32(XType.getSizeInBits()),
11406 getShiftAmountTy(Ctlz.getValueType())));
11408 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11409 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11410 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11411 XType, DAG.getConstant(0, XType), N0);
11412 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11413 return DAG.getNode(ISD::SRL, DL, XType,
11414 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11415 DAG.getConstant(XType.getSizeInBits()-1,
11416 getShiftAmountTy(XType)));
11418 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11419 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11420 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11421 DAG.getConstant(XType.getSizeInBits()-1,
11422 getShiftAmountTy(N0.getValueType())));
11423 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11427 // Check to see if this is an integer abs.
11428 // select_cc setg[te] X, 0, X, -X ->
11429 // select_cc setgt X, -1, X, -X ->
11430 // select_cc setl[te] X, 0, -X, X ->
11431 // select_cc setlt X, 1, -X, X ->
11432 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11434 ConstantSDNode *SubC = nullptr;
11435 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11436 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11437 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11438 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11439 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11440 (N1C->isOne() && CC == ISD::SETLT)) &&
11441 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11442 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11444 EVT XType = N0.getValueType();
11445 if (SubC && SubC->isNullValue() && XType.isInteger()) {
11446 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11448 DAG.getConstant(XType.getSizeInBits()-1,
11449 getShiftAmountTy(N0.getValueType())));
11450 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11452 AddToWorklist(Shift.getNode());
11453 AddToWorklist(Add.getNode());
11454 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11461 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11462 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11463 SDValue N1, ISD::CondCode Cond,
11464 SDLoc DL, bool foldBooleans) {
11465 TargetLowering::DAGCombinerInfo
11466 DagCombineInfo(DAG, Level, false, this);
11467 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11470 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11471 /// return a DAG expression to select that will generate the same value by
11472 /// multiplying by a magic number. See:
11473 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11474 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11475 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11479 // Avoid division by zero.
11480 if (!C->getAPIntValue())
11483 std::vector<SDNode*> Built;
11485 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11487 for (SDNode *N : Built)
11492 /// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant,
11493 /// return a DAG expression to select that will generate the same value by
11494 /// multiplying by a magic number. See:
11495 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11496 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11497 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11501 // Avoid division by zero.
11502 if (!C->getAPIntValue())
11505 std::vector<SDNode*> Built;
11507 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11509 for (SDNode *N : Built)
11514 /// FindBaseOffset - Return true if base is a frame index, which is known not
11515 // to alias with anything but itself. Provides base object and offset as
11517 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11518 const GlobalValue *&GV, const void *&CV) {
11519 // Assume it is a primitive operation.
11520 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11522 // If it's an adding a simple constant then integrate the offset.
11523 if (Base.getOpcode() == ISD::ADD) {
11524 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11525 Base = Base.getOperand(0);
11526 Offset += C->getZExtValue();
11530 // Return the underlying GlobalValue, and update the Offset. Return false
11531 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11532 // by multiple nodes with different offsets.
11533 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11534 GV = G->getGlobal();
11535 Offset += G->getOffset();
11539 // Return the underlying Constant value, and update the Offset. Return false
11540 // for ConstantSDNodes since the same constant pool entry may be represented
11541 // by multiple nodes with different offsets.
11542 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11543 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11544 : (const void *)C->getConstVal();
11545 Offset += C->getOffset();
11548 // If it's any of the following then it can't alias with anything but itself.
11549 return isa<FrameIndexSDNode>(Base);
11552 /// isAlias - Return true if there is any possibility that the two addresses
11554 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11555 // If they are the same then they must be aliases.
11556 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11558 // If they are both volatile then they cannot be reordered.
11559 if (Op0->isVolatile() && Op1->isVolatile()) return true;
11561 // Gather base node and offset information.
11562 SDValue Base1, Base2;
11563 int64_t Offset1, Offset2;
11564 const GlobalValue *GV1, *GV2;
11565 const void *CV1, *CV2;
11566 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11567 Base1, Offset1, GV1, CV1);
11568 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11569 Base2, Offset2, GV2, CV2);
11571 // If they have a same base address then check to see if they overlap.
11572 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11573 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11574 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11576 // It is possible for different frame indices to alias each other, mostly
11577 // when tail call optimization reuses return address slots for arguments.
11578 // To catch this case, look up the actual index of frame indices to compute
11579 // the real alias relationship.
11580 if (isFrameIndex1 && isFrameIndex2) {
11581 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11582 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11583 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11584 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11585 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11588 // Otherwise, if we know what the bases are, and they aren't identical, then
11589 // we know they cannot alias.
11590 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11593 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11594 // compared to the size and offset of the access, we may be able to prove they
11595 // do not alias. This check is conservative for now to catch cases created by
11596 // splitting vector types.
11597 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11598 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11599 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11600 Op1->getMemoryVT().getSizeInBits() >> 3) &&
11601 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11602 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11603 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11605 // There is no overlap between these relatively aligned accesses of similar
11606 // size, return no alias.
11607 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11608 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11612 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11613 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11615 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11616 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11620 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11621 // Use alias analysis information.
11622 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11623 Op1->getSrcValueOffset());
11624 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11625 Op0->getSrcValueOffset() - MinOffset;
11626 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11627 Op1->getSrcValueOffset() - MinOffset;
11628 AliasAnalysis::AliasResult AAResult =
11629 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11631 UseTBAA ? Op0->getTBAAInfo() : nullptr),
11632 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11634 UseTBAA ? Op1->getTBAAInfo() : nullptr));
11635 if (AAResult == AliasAnalysis::NoAlias)
11639 // Otherwise we have to assume they alias.
11643 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11644 /// looking for aliasing nodes and adding them to the Aliases vector.
11645 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11646 SmallVectorImpl<SDValue> &Aliases) {
11647 SmallVector<SDValue, 8> Chains; // List of chains to visit.
11648 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
11650 // Get alias information for node.
11651 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11654 Chains.push_back(OriginalChain);
11655 unsigned Depth = 0;
11657 // Look at each chain and determine if it is an alias. If so, add it to the
11658 // aliases list. If not, then continue up the chain looking for the next
11660 while (!Chains.empty()) {
11661 SDValue Chain = Chains.back();
11664 // For TokenFactor nodes, look at each operand and only continue up the
11665 // chain until we find two aliases. If we've seen two aliases, assume we'll
11666 // find more and revert to original chain since the xform is unlikely to be
11669 // FIXME: The depth check could be made to return the last non-aliasing
11670 // chain we found before we hit a tokenfactor rather than the original
11672 if (Depth > 6 || Aliases.size() == 2) {
11674 Aliases.push_back(OriginalChain);
11678 // Don't bother if we've been before.
11679 if (!Visited.insert(Chain.getNode()))
11682 switch (Chain.getOpcode()) {
11683 case ISD::EntryToken:
11684 // Entry token is ideal chain operand, but handled in FindBetterChain.
11689 // Get alias information for Chain.
11690 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11691 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11693 // If chain is alias then stop here.
11694 if (!(IsLoad && IsOpLoad) &&
11695 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11696 Aliases.push_back(Chain);
11698 // Look further up the chain.
11699 Chains.push_back(Chain.getOperand(0));
11705 case ISD::TokenFactor:
11706 // We have to check each of the operands of the token factor for "small"
11707 // token factors, so we queue them up. Adding the operands to the queue
11708 // (stack) in reverse order maintains the original order and increases the
11709 // likelihood that getNode will find a matching token factor (CSE.)
11710 if (Chain.getNumOperands() > 16) {
11711 Aliases.push_back(Chain);
11714 for (unsigned n = Chain.getNumOperands(); n;)
11715 Chains.push_back(Chain.getOperand(--n));
11720 // For all other instructions we will just have to take what we can get.
11721 Aliases.push_back(Chain);
11726 // We need to be careful here to also search for aliases through the
11727 // value operand of a store, etc. Consider the following situation:
11729 // L1 = load Token1, %52
11730 // S1 = store Token1, L1, %51
11731 // L2 = load Token1, %52+8
11732 // S2 = store Token1, L2, %51+8
11733 // Token2 = Token(S1, S2)
11734 // L3 = load Token2, %53
11735 // S3 = store Token2, L3, %52
11736 // L4 = load Token2, %53+8
11737 // S4 = store Token2, L4, %52+8
11738 // If we search for aliases of S3 (which loads address %52), and we look
11739 // only through the chain, then we'll miss the trivial dependence on L1
11740 // (which also loads from %52). We then might change all loads and
11741 // stores to use Token1 as their chain operand, which could result in
11742 // copying %53 into %52 before copying %52 into %51 (which should
11745 // The problem is, however, that searching for such data dependencies
11746 // can become expensive, and the cost is not directly related to the
11747 // chain depth. Instead, we'll rule out such configurations here by
11748 // insisting that we've visited all chain users (except for users
11749 // of the original chain, which is not necessary). When doing this,
11750 // we need to look through nodes we don't care about (otherwise, things
11751 // like register copies will interfere with trivial cases).
11753 SmallVector<const SDNode *, 16> Worklist;
11754 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11755 IE = Visited.end(); I != IE; ++I)
11756 if (*I != OriginalChain.getNode())
11757 Worklist.push_back(*I);
11759 while (!Worklist.empty()) {
11760 const SDNode *M = Worklist.pop_back_val();
11762 // We have already visited M, and want to make sure we've visited any uses
11763 // of M that we care about. For uses that we've not visisted, and don't
11764 // care about, queue them to the worklist.
11766 for (SDNode::use_iterator UI = M->use_begin(),
11767 UIE = M->use_end(); UI != UIE; ++UI)
11768 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11769 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11770 // We've not visited this use, and we care about it (it could have an
11771 // ordering dependency with the original node).
11773 Aliases.push_back(OriginalChain);
11777 // We've not visited this use, but we don't care about it. Mark it as
11778 // visited and enqueue it to the worklist.
11779 Worklist.push_back(*UI);
11784 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11785 /// for a better chain (aliasing node.)
11786 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11787 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
11789 // Accumulate all the aliases to this node.
11790 GatherAllAliases(N, OldChain, Aliases);
11792 // If no operands then chain to entry token.
11793 if (Aliases.size() == 0)
11794 return DAG.getEntryNode();
11796 // If a single operand then chain to it. We don't need to revisit it.
11797 if (Aliases.size() == 1)
11800 // Construct a custom tailored token factor.
11801 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
11804 // SelectionDAG::Combine - This is the entry point for the file.
11806 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11807 CodeGenOpt::Level OptLevel) {
11808 /// run - This is the main entry point to this class.
11810 DAGCombiner(*this, AA, OptLevel).Run(Level);