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/SetVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetLowering.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
43 #define DEBUG_TYPE "dagcombine"
45 STATISTIC(NodesCombined , "Number of dag nodes combined");
46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
48 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
49 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
50 STATISTIC(SlicedLoads, "Number of load sliced");
54 CombinerAA("combiner-alias-analysis", cl::Hidden,
55 cl::desc("Enable DAG combiner alias-analysis heuristics"));
58 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59 cl::desc("Enable DAG combiner's use of IR alias analysis"));
62 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63 cl::desc("Enable DAG combiner's use of TBAA"));
66 static cl::opt<std::string>
67 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68 cl::desc("Only use DAG-combiner alias analysis in this"
72 /// Hidden option to stress test load slicing, i.e., when this option
73 /// is enabled, load slicing bypasses most of its profitability guards.
75 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76 cl::desc("Bypass the profitability model of load "
80 //------------------------------ DAGCombiner ---------------------------------//
84 const TargetLowering &TLI;
86 CodeGenOpt::Level OptLevel;
91 /// \brief Worklist of all of the nodes that need to be simplified.
93 /// This must behave as a stack -- new nodes to process are pushed onto the
94 /// back and when processing we pop off of the back.
96 /// The worklist will not contain duplicates but may contain null entries
97 /// due to nodes being deleted from the underlying DAG.
98 SmallVector<SDNode *, 64> Worklist;
100 /// \brief Mapping from an SDNode to its position on the worklist.
102 /// This is used to find and remove nodes from the worklist (by nulling
103 /// them) when they are deleted from the underlying DAG. It relies on
104 /// stable indices of nodes within the worklist.
105 DenseMap<SDNode *, unsigned> WorklistMap;
107 /// \brief Set of nodes which have been combined (at least once).
109 /// This is used to allow us to reliably add any operands of a DAG node
110 /// which have not yet been combined to the worklist.
111 SmallPtrSet<SDNode *, 64> CombinedNodes;
113 // AA - Used for DAG load/store alias analysis.
116 /// AddUsersToWorklist - When an instruction is simplified, add all users of
117 /// the instruction to the work lists because they might get more simplified
120 void AddUsersToWorklist(SDNode *N) {
121 for (SDNode *Node : N->uses())
125 /// visit - call the node-specific routine that knows how to fold each
126 /// particular type of node.
127 SDValue visit(SDNode *N);
130 /// AddToWorklist - Add to the work list making sure its instance is at the
131 /// back (next to be processed.)
132 void AddToWorklist(SDNode *N) {
133 // Skip handle nodes as they can't usefully be combined and confuse the
134 // zero-use deletion strategy.
135 if (N->getOpcode() == ISD::HANDLENODE)
138 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
139 Worklist.push_back(N);
142 /// removeFromWorklist - remove all instances of N from the worklist.
144 void removeFromWorklist(SDNode *N) {
145 CombinedNodes.erase(N);
147 auto It = WorklistMap.find(N);
148 if (It == WorklistMap.end())
149 return; // Not in the worklist.
151 // Null out the entry rather than erasing it to avoid a linear operation.
152 Worklist[It->second] = nullptr;
153 WorklistMap.erase(It);
156 void deleteAndRecombine(SDNode *N);
157 bool recursivelyDeleteUnusedNodes(SDNode *N);
159 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
162 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
163 return CombineTo(N, &Res, 1, AddTo);
166 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
168 SDValue To[] = { Res0, Res1 };
169 return CombineTo(N, To, 2, AddTo);
172 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
176 /// SimplifyDemandedBits - Check the specified integer node value to see if
177 /// it can be simplified or if things it uses can be simplified by bit
178 /// propagation. If so, return true.
179 bool SimplifyDemandedBits(SDValue Op) {
180 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181 APInt Demanded = APInt::getAllOnesValue(BitWidth);
182 return SimplifyDemandedBits(Op, Demanded);
185 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
187 bool CombineToPreIndexedLoadStore(SDNode *N);
188 bool CombineToPostIndexedLoadStore(SDNode *N);
189 bool SliceUpLoad(SDNode *N);
191 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
192 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
193 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
194 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
195 SDValue PromoteIntBinOp(SDValue Op);
196 SDValue PromoteIntShiftOp(SDValue Op);
197 SDValue PromoteExtend(SDValue Op);
198 bool PromoteLoad(SDValue Op);
200 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
201 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
202 ISD::NodeType ExtType);
204 /// combine - call the node-specific routine that knows how to fold each
205 /// particular type of node. If that doesn't do anything, try the
206 /// target-specific DAG combines.
207 SDValue combine(SDNode *N);
209 // Visitation implementation - Implement dag node combining for different
210 // node types. The semantics are as follows:
212 // SDValue.getNode() == 0 - No change was made
213 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
214 // otherwise - N should be replaced by the returned Operand.
216 SDValue visitTokenFactor(SDNode *N);
217 SDValue visitMERGE_VALUES(SDNode *N);
218 SDValue visitADD(SDNode *N);
219 SDValue visitSUB(SDNode *N);
220 SDValue visitADDC(SDNode *N);
221 SDValue visitSUBC(SDNode *N);
222 SDValue visitADDE(SDNode *N);
223 SDValue visitSUBE(SDNode *N);
224 SDValue visitMUL(SDNode *N);
225 SDValue visitSDIV(SDNode *N);
226 SDValue visitUDIV(SDNode *N);
227 SDValue visitSREM(SDNode *N);
228 SDValue visitUREM(SDNode *N);
229 SDValue visitMULHU(SDNode *N);
230 SDValue visitMULHS(SDNode *N);
231 SDValue visitSMUL_LOHI(SDNode *N);
232 SDValue visitUMUL_LOHI(SDNode *N);
233 SDValue visitSMULO(SDNode *N);
234 SDValue visitUMULO(SDNode *N);
235 SDValue visitSDIVREM(SDNode *N);
236 SDValue visitUDIVREM(SDNode *N);
237 SDValue visitAND(SDNode *N);
238 SDValue visitOR(SDNode *N);
239 SDValue visitXOR(SDNode *N);
240 SDValue SimplifyVBinOp(SDNode *N);
241 SDValue SimplifyVUnaryOp(SDNode *N);
242 SDValue visitSHL(SDNode *N);
243 SDValue visitSRA(SDNode *N);
244 SDValue visitSRL(SDNode *N);
245 SDValue visitRotate(SDNode *N);
246 SDValue visitCTLZ(SDNode *N);
247 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
248 SDValue visitCTTZ(SDNode *N);
249 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
250 SDValue visitCTPOP(SDNode *N);
251 SDValue visitSELECT(SDNode *N);
252 SDValue visitVSELECT(SDNode *N);
253 SDValue visitSELECT_CC(SDNode *N);
254 SDValue visitSETCC(SDNode *N);
255 SDValue visitSIGN_EXTEND(SDNode *N);
256 SDValue visitZERO_EXTEND(SDNode *N);
257 SDValue visitANY_EXTEND(SDNode *N);
258 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
259 SDValue visitTRUNCATE(SDNode *N);
260 SDValue visitBITCAST(SDNode *N);
261 SDValue visitBUILD_PAIR(SDNode *N);
262 SDValue visitFADD(SDNode *N);
263 SDValue visitFSUB(SDNode *N);
264 SDValue visitFMUL(SDNode *N);
265 SDValue visitFMA(SDNode *N);
266 SDValue visitFDIV(SDNode *N);
267 SDValue visitFREM(SDNode *N);
268 SDValue visitFCOPYSIGN(SDNode *N);
269 SDValue visitSINT_TO_FP(SDNode *N);
270 SDValue visitUINT_TO_FP(SDNode *N);
271 SDValue visitFP_TO_SINT(SDNode *N);
272 SDValue visitFP_TO_UINT(SDNode *N);
273 SDValue visitFP_ROUND(SDNode *N);
274 SDValue visitFP_ROUND_INREG(SDNode *N);
275 SDValue visitFP_EXTEND(SDNode *N);
276 SDValue visitFNEG(SDNode *N);
277 SDValue visitFABS(SDNode *N);
278 SDValue visitFCEIL(SDNode *N);
279 SDValue visitFTRUNC(SDNode *N);
280 SDValue visitFFLOOR(SDNode *N);
281 SDValue visitBRCOND(SDNode *N);
282 SDValue visitBR_CC(SDNode *N);
283 SDValue visitLOAD(SDNode *N);
284 SDValue visitSTORE(SDNode *N);
285 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
286 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
287 SDValue visitBUILD_VECTOR(SDNode *N);
288 SDValue visitCONCAT_VECTORS(SDNode *N);
289 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
290 SDValue visitVECTOR_SHUFFLE(SDNode *N);
291 SDValue visitINSERT_SUBVECTOR(SDNode *N);
293 SDValue XformToShuffleWithZero(SDNode *N);
294 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
296 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
298 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
299 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
300 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
301 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
302 SDValue N3, ISD::CondCode CC,
303 bool NotExtCompare = false);
304 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
305 SDLoc DL, bool foldBooleans = true);
307 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
309 bool isOneUseSetCC(SDValue N) const;
311 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
313 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
314 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
315 SDValue BuildSDIV(SDNode *N);
316 SDValue BuildSDIVPow2(SDNode *N);
317 SDValue BuildUDIV(SDNode *N);
318 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
319 bool DemandHighBits = true);
320 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
321 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
322 SDValue InnerPos, SDValue InnerNeg,
323 unsigned PosOpcode, unsigned NegOpcode,
325 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
326 SDValue ReduceLoadWidth(SDNode *N);
327 SDValue ReduceLoadOpStoreWidth(SDNode *N);
328 SDValue TransformFPLoadStorePair(SDNode *N);
329 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
330 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
332 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
334 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
335 /// looking for aliasing nodes and adding them to the Aliases vector.
336 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
337 SmallVectorImpl<SDValue> &Aliases);
339 /// isAlias - Return true if there is any possibility that the two addresses
341 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
343 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
344 /// looking for a better chain (aliasing node.)
345 SDValue FindBetterChain(SDNode *N, SDValue Chain);
347 /// Merge consecutive store operations into a wide store.
348 /// This optimization uses wide integers or vectors when possible.
349 /// \return True if some memory operations were changed.
350 bool MergeConsecutiveStores(StoreSDNode *N);
352 /// \brief Try to transform a truncation where C is a constant:
353 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
355 /// \p N needs to be a truncation and its first operand an AND. Other
356 /// requirements are checked by the function (e.g. that trunc is
357 /// single-use) and if missed an empty SDValue is returned.
358 SDValue distributeTruncateThroughAnd(SDNode *N);
361 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
362 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
363 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
364 AttributeSet FnAttrs =
365 DAG.getMachineFunction().getFunction()->getAttributes();
367 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
368 Attribute::OptimizeForSize) ||
369 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
372 /// Run - runs the dag combiner on all nodes in the work list
373 void Run(CombineLevel AtLevel);
375 SelectionDAG &getDAG() const { return DAG; }
377 /// getShiftAmountTy - Returns a type large enough to hold any valid
378 /// shift amount - before type legalization these can be huge.
379 EVT getShiftAmountTy(EVT LHSTy) {
380 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
381 if (LHSTy.isVector())
383 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
384 : TLI.getPointerTy();
387 /// isTypeLegal - This method returns true if we are running before type
388 /// legalization or if the specified VT is legal.
389 bool isTypeLegal(const EVT &VT) {
390 if (!LegalTypes) return true;
391 return TLI.isTypeLegal(VT);
394 /// getSetCCResultType - Convenience wrapper around
395 /// TargetLowering::getSetCCResultType
396 EVT getSetCCResultType(EVT VT) const {
397 return TLI.getSetCCResultType(*DAG.getContext(), VT);
404 /// WorklistRemover - This class is a DAGUpdateListener that removes any deleted
405 /// nodes from the worklist.
406 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
409 explicit WorklistRemover(DAGCombiner &dc)
410 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
412 void NodeDeleted(SDNode *N, SDNode *E) override {
413 DC.removeFromWorklist(N);
418 //===----------------------------------------------------------------------===//
419 // TargetLowering::DAGCombinerInfo implementation
420 //===----------------------------------------------------------------------===//
422 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
423 ((DAGCombiner*)DC)->AddToWorklist(N);
426 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
427 ((DAGCombiner*)DC)->removeFromWorklist(N);
430 SDValue TargetLowering::DAGCombinerInfo::
431 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
432 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
435 SDValue TargetLowering::DAGCombinerInfo::
436 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
437 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
441 SDValue TargetLowering::DAGCombinerInfo::
442 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
443 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
446 void TargetLowering::DAGCombinerInfo::
447 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
448 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
451 //===----------------------------------------------------------------------===//
453 //===----------------------------------------------------------------------===//
455 void DAGCombiner::deleteAndRecombine(SDNode *N) {
456 removeFromWorklist(N);
458 // If the operands of this node are only used by the node, they will now be
459 // dead. Make sure to re-visit them and recursively delete dead nodes.
460 for (const SDValue &Op : N->ops())
462 AddToWorklist(Op.getNode());
467 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
468 /// specified expression for the same cost as the expression itself, or 2 if we
469 /// can compute the negated form more cheaply than the expression itself.
470 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
471 const TargetLowering &TLI,
472 const TargetOptions *Options,
473 unsigned Depth = 0) {
474 // fneg is removable even if it has multiple uses.
475 if (Op.getOpcode() == ISD::FNEG) return 2;
477 // Don't allow anything with multiple uses.
478 if (!Op.hasOneUse()) return 0;
480 // Don't recurse exponentially.
481 if (Depth > 6) return 0;
483 switch (Op.getOpcode()) {
484 default: return false;
485 case ISD::ConstantFP:
486 // Don't invert constant FP values after legalize. The negated constant
487 // isn't necessarily legal.
488 return LegalOperations ? 0 : 1;
490 // FIXME: determine better conditions for this xform.
491 if (!Options->UnsafeFPMath) return 0;
493 // After operation legalization, it might not be legal to create new FSUBs.
494 if (LegalOperations &&
495 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
498 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
499 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
502 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
503 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
506 // We can't turn -(A-B) into B-A when we honor signed zeros.
507 if (!Options->UnsafeFPMath) return 0;
509 // fold (fneg (fsub A, B)) -> (fsub B, A)
514 if (Options->HonorSignDependentRoundingFPMath()) return 0;
516 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
517 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
521 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
527 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
532 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
533 /// returns the newly negated expression.
534 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
535 bool LegalOperations, unsigned Depth = 0) {
536 // fneg is removable even if it has multiple uses.
537 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
539 // Don't allow anything with multiple uses.
540 assert(Op.hasOneUse() && "Unknown reuse!");
542 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
543 switch (Op.getOpcode()) {
544 default: llvm_unreachable("Unknown code");
545 case ISD::ConstantFP: {
546 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
548 return DAG.getConstantFP(V, Op.getValueType());
551 // FIXME: determine better conditions for this xform.
552 assert(DAG.getTarget().Options.UnsafeFPMath);
554 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
555 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
556 DAG.getTargetLoweringInfo(),
557 &DAG.getTarget().Options, Depth+1))
558 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
559 GetNegatedExpression(Op.getOperand(0), DAG,
560 LegalOperations, Depth+1),
562 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
563 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
564 GetNegatedExpression(Op.getOperand(1), DAG,
565 LegalOperations, Depth+1),
568 // We can't turn -(A-B) into B-A when we honor signed zeros.
569 assert(DAG.getTarget().Options.UnsafeFPMath);
571 // fold (fneg (fsub 0, B)) -> B
572 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
573 if (N0CFP->getValueAPF().isZero())
574 return Op.getOperand(1);
576 // fold (fneg (fsub A, B)) -> (fsub B, A)
577 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
578 Op.getOperand(1), Op.getOperand(0));
582 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
584 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
585 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
586 DAG.getTargetLoweringInfo(),
587 &DAG.getTarget().Options, Depth+1))
588 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
589 GetNegatedExpression(Op.getOperand(0), DAG,
590 LegalOperations, Depth+1),
593 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
594 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
596 GetNegatedExpression(Op.getOperand(1), DAG,
597 LegalOperations, Depth+1));
601 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
602 GetNegatedExpression(Op.getOperand(0), DAG,
603 LegalOperations, Depth+1));
605 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
606 GetNegatedExpression(Op.getOperand(0), DAG,
607 LegalOperations, Depth+1),
612 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
613 // that selects between the target values used for true and false, making it
614 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
615 // the appropriate nodes based on the type of node we are checking. This
616 // simplifies life a bit for the callers.
617 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
619 if (N.getOpcode() == ISD::SETCC) {
620 LHS = N.getOperand(0);
621 RHS = N.getOperand(1);
622 CC = N.getOperand(2);
626 if (N.getOpcode() != ISD::SELECT_CC ||
627 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
628 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
631 LHS = N.getOperand(0);
632 RHS = N.getOperand(1);
633 CC = N.getOperand(4);
637 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
638 // one use. If this is true, it allows the users to invert the operation for
639 // free when it is profitable to do so.
640 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
642 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
647 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
648 /// elements are all the same constant or undefined.
649 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
650 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
655 unsigned SplatBitSize;
657 EVT EltVT = N->getValueType(0).getVectorElementType();
658 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
660 EltVT.getSizeInBits() >= SplatBitSize);
663 // \brief Returns the SDNode if it is a constant BuildVector or constant.
664 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
665 if (isa<ConstantSDNode>(N))
667 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
668 if(BV && BV->isConstant())
673 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
675 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
676 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
679 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
680 BitVector UndefElements;
681 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
683 // BuildVectors can truncate their operands. Ignore that case here.
684 // FIXME: We blindly ignore splats which include undef which is overly
686 if (CN && UndefElements.none() &&
687 CN->getValueType(0) == N.getValueType().getScalarType())
694 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
695 SDValue N0, SDValue N1) {
696 EVT VT = N0.getValueType();
697 if (N0.getOpcode() == Opc) {
698 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
699 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
700 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
701 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
702 if (!OpNode.getNode())
704 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
706 if (N0.hasOneUse()) {
707 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
709 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
710 if (!OpNode.getNode())
712 AddToWorklist(OpNode.getNode());
713 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
718 if (N1.getOpcode() == Opc) {
719 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
720 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
721 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
722 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
723 if (!OpNode.getNode())
725 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
727 if (N1.hasOneUse()) {
728 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
730 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
731 if (!OpNode.getNode())
733 AddToWorklist(OpNode.getNode());
734 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
742 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
744 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
746 DEBUG(dbgs() << "\nReplacing.1 ";
748 dbgs() << "\nWith: ";
749 To[0].getNode()->dump(&DAG);
750 dbgs() << " and " << NumTo-1 << " other values\n";
751 for (unsigned i = 0, e = NumTo; i != e; ++i)
752 assert((!To[i].getNode() ||
753 N->getValueType(i) == To[i].getValueType()) &&
754 "Cannot combine value to value of different type!"));
755 WorklistRemover DeadNodes(*this);
756 DAG.ReplaceAllUsesWith(N, To);
758 // Push the new nodes and any users onto the worklist
759 for (unsigned i = 0, e = NumTo; i != e; ++i) {
760 if (To[i].getNode()) {
761 AddToWorklist(To[i].getNode());
762 AddUsersToWorklist(To[i].getNode());
767 // Finally, if the node is now dead, remove it from the graph. The node
768 // may not be dead if the replacement process recursively simplified to
769 // something else needing this node.
771 deleteAndRecombine(N);
772 return SDValue(N, 0);
776 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
777 // Replace all uses. If any nodes become isomorphic to other nodes and
778 // are deleted, make sure to remove them from our worklist.
779 WorklistRemover DeadNodes(*this);
780 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
782 // Push the new node and any (possibly new) users onto the worklist.
783 AddToWorklist(TLO.New.getNode());
784 AddUsersToWorklist(TLO.New.getNode());
786 // Finally, if the node is now dead, remove it from the graph. The node
787 // may not be dead if the replacement process recursively simplified to
788 // something else needing this node.
789 if (TLO.Old.getNode()->use_empty())
790 deleteAndRecombine(TLO.Old.getNode());
793 /// SimplifyDemandedBits - Check the specified integer node value to see if
794 /// it can be simplified or if things it uses can be simplified by bit
795 /// propagation. If so, return true.
796 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
797 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
798 APInt KnownZero, KnownOne;
799 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
803 AddToWorklist(Op.getNode());
805 // Replace the old value with the new one.
807 DEBUG(dbgs() << "\nReplacing.2 ";
808 TLO.Old.getNode()->dump(&DAG);
809 dbgs() << "\nWith: ";
810 TLO.New.getNode()->dump(&DAG);
813 CommitTargetLoweringOpt(TLO);
817 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
819 EVT VT = Load->getValueType(0);
820 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
822 DEBUG(dbgs() << "\nReplacing.9 ";
824 dbgs() << "\nWith: ";
825 Trunc.getNode()->dump(&DAG);
827 WorklistRemover DeadNodes(*this);
828 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
829 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
830 deleteAndRecombine(Load);
831 AddToWorklist(Trunc.getNode());
834 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
837 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
838 EVT MemVT = LD->getMemoryVT();
839 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
840 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
842 : LD->getExtensionType();
844 return DAG.getExtLoad(ExtType, dl, PVT,
845 LD->getChain(), LD->getBasePtr(),
846 MemVT, LD->getMemOperand());
849 unsigned Opc = Op.getOpcode();
852 case ISD::AssertSext:
853 return DAG.getNode(ISD::AssertSext, dl, PVT,
854 SExtPromoteOperand(Op.getOperand(0), PVT),
856 case ISD::AssertZext:
857 return DAG.getNode(ISD::AssertZext, dl, PVT,
858 ZExtPromoteOperand(Op.getOperand(0), PVT),
860 case ISD::Constant: {
862 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
863 return DAG.getNode(ExtOpc, dl, PVT, Op);
867 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
869 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
872 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
873 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
875 EVT OldVT = Op.getValueType();
877 bool Replace = false;
878 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
879 if (!NewOp.getNode())
881 AddToWorklist(NewOp.getNode());
884 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
885 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
886 DAG.getValueType(OldVT));
889 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
890 EVT OldVT = Op.getValueType();
892 bool Replace = false;
893 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
894 if (!NewOp.getNode())
896 AddToWorklist(NewOp.getNode());
899 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
900 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
903 /// PromoteIntBinOp - Promote the specified integer binary operation if the
904 /// target indicates it is beneficial. e.g. On x86, it's usually better to
905 /// promote i16 operations to i32 since i16 instructions are longer.
906 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
907 if (!LegalOperations)
910 EVT VT = Op.getValueType();
911 if (VT.isVector() || !VT.isInteger())
914 // If operation type is 'undesirable', e.g. i16 on x86, consider
916 unsigned Opc = Op.getOpcode();
917 if (TLI.isTypeDesirableForOp(Opc, VT))
921 // Consult target whether it is a good idea to promote this operation and
922 // what's the right type to promote it to.
923 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
924 assert(PVT != VT && "Don't know what type to promote to!");
926 bool Replace0 = false;
927 SDValue N0 = Op.getOperand(0);
928 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
932 bool Replace1 = false;
933 SDValue N1 = Op.getOperand(1);
938 NN1 = PromoteOperand(N1, PVT, Replace1);
943 AddToWorklist(NN0.getNode());
945 AddToWorklist(NN1.getNode());
948 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
950 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
952 DEBUG(dbgs() << "\nPromoting ";
953 Op.getNode()->dump(&DAG));
955 return DAG.getNode(ISD::TRUNCATE, dl, VT,
956 DAG.getNode(Opc, dl, PVT, NN0, NN1));
961 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
962 /// target indicates it is beneficial. e.g. On x86, it's usually better to
963 /// promote i16 operations to i32 since i16 instructions are longer.
964 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
965 if (!LegalOperations)
968 EVT VT = Op.getValueType();
969 if (VT.isVector() || !VT.isInteger())
972 // If operation type is 'undesirable', e.g. i16 on x86, consider
974 unsigned Opc = Op.getOpcode();
975 if (TLI.isTypeDesirableForOp(Opc, VT))
979 // Consult target whether it is a good idea to promote this operation and
980 // what's the right type to promote it to.
981 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
982 assert(PVT != VT && "Don't know what type to promote to!");
984 bool Replace = false;
985 SDValue N0 = Op.getOperand(0);
987 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
988 else if (Opc == ISD::SRL)
989 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
991 N0 = PromoteOperand(N0, PVT, Replace);
995 AddToWorklist(N0.getNode());
997 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
999 DEBUG(dbgs() << "\nPromoting ";
1000 Op.getNode()->dump(&DAG));
1002 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1003 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1008 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1009 if (!LegalOperations)
1012 EVT VT = Op.getValueType();
1013 if (VT.isVector() || !VT.isInteger())
1016 // If operation type is 'undesirable', e.g. i16 on x86, consider
1018 unsigned Opc = Op.getOpcode();
1019 if (TLI.isTypeDesirableForOp(Opc, VT))
1023 // Consult target whether it is a good idea to promote this operation and
1024 // what's the right type to promote it to.
1025 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1026 assert(PVT != VT && "Don't know what type to promote to!");
1027 // fold (aext (aext x)) -> (aext x)
1028 // fold (aext (zext x)) -> (zext x)
1029 // fold (aext (sext x)) -> (sext x)
1030 DEBUG(dbgs() << "\nPromoting ";
1031 Op.getNode()->dump(&DAG));
1032 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1037 bool DAGCombiner::PromoteLoad(SDValue Op) {
1038 if (!LegalOperations)
1041 EVT VT = Op.getValueType();
1042 if (VT.isVector() || !VT.isInteger())
1045 // If operation type is 'undesirable', e.g. i16 on x86, consider
1047 unsigned Opc = Op.getOpcode();
1048 if (TLI.isTypeDesirableForOp(Opc, VT))
1052 // Consult target whether it is a good idea to promote this operation and
1053 // what's the right type to promote it to.
1054 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1055 assert(PVT != VT && "Don't know what type to promote to!");
1058 SDNode *N = Op.getNode();
1059 LoadSDNode *LD = cast<LoadSDNode>(N);
1060 EVT MemVT = LD->getMemoryVT();
1061 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1062 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1064 : LD->getExtensionType();
1065 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1066 LD->getChain(), LD->getBasePtr(),
1067 MemVT, LD->getMemOperand());
1068 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1070 DEBUG(dbgs() << "\nPromoting ";
1073 Result.getNode()->dump(&DAG);
1075 WorklistRemover DeadNodes(*this);
1076 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1077 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1078 deleteAndRecombine(N);
1079 AddToWorklist(Result.getNode());
1085 /// \brief Recursively delete a node which has no uses and any operands for
1086 /// which it is the only use.
1088 /// Note that this both deletes the nodes and removes them from the worklist.
1089 /// It also adds any nodes who have had a user deleted to the worklist as they
1090 /// may now have only one use and subject to other combines.
1091 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1092 if (!N->use_empty())
1095 SmallSetVector<SDNode *, 16> Nodes;
1098 N = Nodes.pop_back_val();
1102 if (N->use_empty()) {
1103 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1104 Nodes.insert(N->getOperand(i).getNode());
1106 removeFromWorklist(N);
1111 } while (!Nodes.empty());
1115 //===----------------------------------------------------------------------===//
1116 // Main DAG Combiner implementation
1117 //===----------------------------------------------------------------------===//
1119 void DAGCombiner::Run(CombineLevel AtLevel) {
1120 // set the instance variables, so that the various visit routines may use it.
1122 LegalOperations = Level >= AfterLegalizeVectorOps;
1123 LegalTypes = Level >= AfterLegalizeTypes;
1125 // Add all the dag nodes to the worklist.
1126 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1127 E = DAG.allnodes_end(); I != E; ++I)
1130 // Create a dummy node (which is not added to allnodes), that adds a reference
1131 // to the root node, preventing it from being deleted, and tracking any
1132 // changes of the root.
1133 HandleSDNode Dummy(DAG.getRoot());
1135 // while the worklist isn't empty, find a node and
1136 // try and combine it.
1137 while (!WorklistMap.empty()) {
1139 // The Worklist holds the SDNodes in order, but it may contain null entries.
1141 N = Worklist.pop_back_val();
1144 bool GoodWorklistEntry = WorklistMap.erase(N);
1145 (void)GoodWorklistEntry;
1146 assert(GoodWorklistEntry &&
1147 "Found a worklist entry without a corresponding map entry!");
1149 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1150 // N is deleted from the DAG, since they too may now be dead or may have a
1151 // reduced number of uses, allowing other xforms.
1152 if (recursivelyDeleteUnusedNodes(N))
1155 // Add any operands of the new node which have not yet been combined to the
1156 // worklist as well. Because the worklist uniques things already, this
1157 // won't repeatedly process the same operand.
1158 CombinedNodes.insert(N);
1159 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1160 if (!CombinedNodes.count(N->getOperand(i).getNode()))
1161 AddToWorklist(N->getOperand(i).getNode());
1163 WorklistRemover DeadNodes(*this);
1165 // If this combine is running after legalizing the DAG, re-legalize any
1166 // nodes pulled off the worklist.
1167 if (Level == AfterLegalizeDAG) {
1168 SmallSetVector<SDNode *, 16> UpdatedNodes;
1169 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1171 for (SDNode *LN : UpdatedNodes) {
1173 AddUsersToWorklist(LN);
1179 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1181 SDValue RV = combine(N);
1188 // If we get back the same node we passed in, rather than a new node or
1189 // zero, we know that the node must have defined multiple values and
1190 // CombineTo was used. Since CombineTo takes care of the worklist
1191 // mechanics for us, we have no work to do in this case.
1192 if (RV.getNode() == N)
1195 assert(N->getOpcode() != ISD::DELETED_NODE &&
1196 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1197 "Node was deleted but visit returned new node!");
1199 DEBUG(dbgs() << " ... into: ";
1200 RV.getNode()->dump(&DAG));
1202 // Transfer debug value.
1203 DAG.TransferDbgValues(SDValue(N, 0), RV);
1204 if (N->getNumValues() == RV.getNode()->getNumValues())
1205 DAG.ReplaceAllUsesWith(N, RV.getNode());
1207 assert(N->getValueType(0) == RV.getValueType() &&
1208 N->getNumValues() == 1 && "Type mismatch");
1210 DAG.ReplaceAllUsesWith(N, &OpV);
1213 // Push the new node and any users onto the worklist
1214 AddToWorklist(RV.getNode());
1215 AddUsersToWorklist(RV.getNode());
1217 // Finally, if the node is now dead, remove it from the graph. The node
1218 // may not be dead if the replacement process recursively simplified to
1219 // something else needing this node. This will also take care of adding any
1220 // operands which have lost a user to the worklist.
1221 recursivelyDeleteUnusedNodes(N);
1224 // If the root changed (e.g. it was a dead load, update the root).
1225 DAG.setRoot(Dummy.getValue());
1226 DAG.RemoveDeadNodes();
1229 SDValue DAGCombiner::visit(SDNode *N) {
1230 switch (N->getOpcode()) {
1232 case ISD::TokenFactor: return visitTokenFactor(N);
1233 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1234 case ISD::ADD: return visitADD(N);
1235 case ISD::SUB: return visitSUB(N);
1236 case ISD::ADDC: return visitADDC(N);
1237 case ISD::SUBC: return visitSUBC(N);
1238 case ISD::ADDE: return visitADDE(N);
1239 case ISD::SUBE: return visitSUBE(N);
1240 case ISD::MUL: return visitMUL(N);
1241 case ISD::SDIV: return visitSDIV(N);
1242 case ISD::UDIV: return visitUDIV(N);
1243 case ISD::SREM: return visitSREM(N);
1244 case ISD::UREM: return visitUREM(N);
1245 case ISD::MULHU: return visitMULHU(N);
1246 case ISD::MULHS: return visitMULHS(N);
1247 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1248 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1249 case ISD::SMULO: return visitSMULO(N);
1250 case ISD::UMULO: return visitUMULO(N);
1251 case ISD::SDIVREM: return visitSDIVREM(N);
1252 case ISD::UDIVREM: return visitUDIVREM(N);
1253 case ISD::AND: return visitAND(N);
1254 case ISD::OR: return visitOR(N);
1255 case ISD::XOR: return visitXOR(N);
1256 case ISD::SHL: return visitSHL(N);
1257 case ISD::SRA: return visitSRA(N);
1258 case ISD::SRL: return visitSRL(N);
1260 case ISD::ROTL: return visitRotate(N);
1261 case ISD::CTLZ: return visitCTLZ(N);
1262 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1263 case ISD::CTTZ: return visitCTTZ(N);
1264 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1265 case ISD::CTPOP: return visitCTPOP(N);
1266 case ISD::SELECT: return visitSELECT(N);
1267 case ISD::VSELECT: return visitVSELECT(N);
1268 case ISD::SELECT_CC: return visitSELECT_CC(N);
1269 case ISD::SETCC: return visitSETCC(N);
1270 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1271 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1272 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1273 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1274 case ISD::TRUNCATE: return visitTRUNCATE(N);
1275 case ISD::BITCAST: return visitBITCAST(N);
1276 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1277 case ISD::FADD: return visitFADD(N);
1278 case ISD::FSUB: return visitFSUB(N);
1279 case ISD::FMUL: return visitFMUL(N);
1280 case ISD::FMA: return visitFMA(N);
1281 case ISD::FDIV: return visitFDIV(N);
1282 case ISD::FREM: return visitFREM(N);
1283 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1284 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1285 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1286 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1287 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1288 case ISD::FP_ROUND: return visitFP_ROUND(N);
1289 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1290 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1291 case ISD::FNEG: return visitFNEG(N);
1292 case ISD::FABS: return visitFABS(N);
1293 case ISD::FFLOOR: return visitFFLOOR(N);
1294 case ISD::FCEIL: return visitFCEIL(N);
1295 case ISD::FTRUNC: return visitFTRUNC(N);
1296 case ISD::BRCOND: return visitBRCOND(N);
1297 case ISD::BR_CC: return visitBR_CC(N);
1298 case ISD::LOAD: return visitLOAD(N);
1299 case ISD::STORE: return visitSTORE(N);
1300 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1301 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1302 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1303 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1304 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1305 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1306 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1311 SDValue DAGCombiner::combine(SDNode *N) {
1312 SDValue RV = visit(N);
1314 // If nothing happened, try a target-specific DAG combine.
1315 if (!RV.getNode()) {
1316 assert(N->getOpcode() != ISD::DELETED_NODE &&
1317 "Node was deleted but visit returned NULL!");
1319 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1320 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1322 // Expose the DAG combiner to the target combiner impls.
1323 TargetLowering::DAGCombinerInfo
1324 DagCombineInfo(DAG, Level, false, this);
1326 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1330 // If nothing happened still, try promoting the operation.
1331 if (!RV.getNode()) {
1332 switch (N->getOpcode()) {
1340 RV = PromoteIntBinOp(SDValue(N, 0));
1345 RV = PromoteIntShiftOp(SDValue(N, 0));
1347 case ISD::SIGN_EXTEND:
1348 case ISD::ZERO_EXTEND:
1349 case ISD::ANY_EXTEND:
1350 RV = PromoteExtend(SDValue(N, 0));
1353 if (PromoteLoad(SDValue(N, 0)))
1359 // If N is a commutative binary node, try commuting it to enable more
1361 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1362 N->getNumValues() == 1) {
1363 SDValue N0 = N->getOperand(0);
1364 SDValue N1 = N->getOperand(1);
1366 // Constant operands are canonicalized to RHS.
1367 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1368 SDValue Ops[] = {N1, N0};
1370 if (const BinaryWithFlagsSDNode *BinNode =
1371 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1372 CSENode = DAG.getNodeIfExists(
1373 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1374 BinNode->hasNoSignedWrap(), BinNode->isExact());
1376 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1379 return SDValue(CSENode, 0);
1386 /// getInputChainForNode - Given a node, return its input chain if it has one,
1387 /// otherwise return a null sd operand.
1388 static SDValue getInputChainForNode(SDNode *N) {
1389 if (unsigned NumOps = N->getNumOperands()) {
1390 if (N->getOperand(0).getValueType() == MVT::Other)
1391 return N->getOperand(0);
1392 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1393 return N->getOperand(NumOps-1);
1394 for (unsigned i = 1; i < NumOps-1; ++i)
1395 if (N->getOperand(i).getValueType() == MVT::Other)
1396 return N->getOperand(i);
1401 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1402 // If N has two operands, where one has an input chain equal to the other,
1403 // the 'other' chain is redundant.
1404 if (N->getNumOperands() == 2) {
1405 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1406 return N->getOperand(0);
1407 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1408 return N->getOperand(1);
1411 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1412 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1413 SmallPtrSet<SDNode*, 16> SeenOps;
1414 bool Changed = false; // If we should replace this token factor.
1416 // Start out with this token factor.
1419 // Iterate through token factors. The TFs grows when new token factors are
1421 for (unsigned i = 0; i < TFs.size(); ++i) {
1422 SDNode *TF = TFs[i];
1424 // Check each of the operands.
1425 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1426 SDValue Op = TF->getOperand(i);
1428 switch (Op.getOpcode()) {
1429 case ISD::EntryToken:
1430 // Entry tokens don't need to be added to the list. They are
1435 case ISD::TokenFactor:
1436 if (Op.hasOneUse() &&
1437 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1438 // Queue up for processing.
1439 TFs.push_back(Op.getNode());
1440 // Clean up in case the token factor is removed.
1441 AddToWorklist(Op.getNode());
1448 // Only add if it isn't already in the list.
1449 if (SeenOps.insert(Op.getNode()))
1460 // If we've change things around then replace token factor.
1463 // The entry token is the only possible outcome.
1464 Result = DAG.getEntryNode();
1466 // New and improved token factor.
1467 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1470 // Don't add users to work list.
1471 return CombineTo(N, Result, false);
1477 /// MERGE_VALUES can always be eliminated.
1478 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1479 WorklistRemover DeadNodes(*this);
1480 // Replacing results may cause a different MERGE_VALUES to suddenly
1481 // be CSE'd with N, and carry its uses with it. Iterate until no
1482 // uses remain, to ensure that the node can be safely deleted.
1483 // First add the users of this node to the work list so that they
1484 // can be tried again once they have new operands.
1485 AddUsersToWorklist(N);
1487 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1488 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1489 } while (!N->use_empty());
1490 deleteAndRecombine(N);
1491 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1495 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1496 SelectionDAG &DAG) {
1497 EVT VT = N0.getValueType();
1498 SDValue N00 = N0.getOperand(0);
1499 SDValue N01 = N0.getOperand(1);
1500 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1502 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1503 isa<ConstantSDNode>(N00.getOperand(1))) {
1504 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1505 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1506 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1507 N00.getOperand(0), N01),
1508 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1509 N00.getOperand(1), N01));
1510 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1516 SDValue DAGCombiner::visitADD(SDNode *N) {
1517 SDValue N0 = N->getOperand(0);
1518 SDValue N1 = N->getOperand(1);
1519 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1520 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1521 EVT VT = N0.getValueType();
1524 if (VT.isVector()) {
1525 SDValue FoldedVOp = SimplifyVBinOp(N);
1526 if (FoldedVOp.getNode()) return FoldedVOp;
1528 // fold (add x, 0) -> x, vector edition
1529 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1531 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1535 // fold (add x, undef) -> undef
1536 if (N0.getOpcode() == ISD::UNDEF)
1538 if (N1.getOpcode() == ISD::UNDEF)
1540 // fold (add c1, c2) -> c1+c2
1542 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1543 // canonicalize constant to RHS
1545 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1546 // fold (add x, 0) -> x
1547 if (N1C && N1C->isNullValue())
1549 // fold (add Sym, c) -> Sym+c
1550 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1551 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1552 GA->getOpcode() == ISD::GlobalAddress)
1553 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1555 (uint64_t)N1C->getSExtValue());
1556 // fold ((c1-A)+c2) -> (c1+c2)-A
1557 if (N1C && N0.getOpcode() == ISD::SUB)
1558 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1559 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1560 DAG.getConstant(N1C->getAPIntValue()+
1561 N0C->getAPIntValue(), VT),
1564 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1567 // fold ((0-A) + B) -> B-A
1568 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1569 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1570 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1571 // fold (A + (0-B)) -> A-B
1572 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1573 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1574 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1575 // fold (A+(B-A)) -> B
1576 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1577 return N1.getOperand(0);
1578 // fold ((B-A)+A) -> B
1579 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1580 return N0.getOperand(0);
1581 // fold (A+(B-(A+C))) to (B-C)
1582 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1583 N0 == N1.getOperand(1).getOperand(0))
1584 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1585 N1.getOperand(1).getOperand(1));
1586 // fold (A+(B-(C+A))) to (B-C)
1587 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1588 N0 == N1.getOperand(1).getOperand(1))
1589 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1590 N1.getOperand(1).getOperand(0));
1591 // fold (A+((B-A)+or-C)) to (B+or-C)
1592 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1593 N1.getOperand(0).getOpcode() == ISD::SUB &&
1594 N0 == N1.getOperand(0).getOperand(1))
1595 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1596 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1598 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1599 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1600 SDValue N00 = N0.getOperand(0);
1601 SDValue N01 = N0.getOperand(1);
1602 SDValue N10 = N1.getOperand(0);
1603 SDValue N11 = N1.getOperand(1);
1605 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1606 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1607 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1608 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1611 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1612 return SDValue(N, 0);
1614 // fold (a+b) -> (a|b) iff a and b share no bits.
1615 if (VT.isInteger() && !VT.isVector()) {
1616 APInt LHSZero, LHSOne;
1617 APInt RHSZero, RHSOne;
1618 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1620 if (LHSZero.getBoolValue()) {
1621 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1623 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1624 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1625 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1626 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1627 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1632 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1633 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1634 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1635 if (Result.getNode()) return Result;
1637 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1638 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1639 if (Result.getNode()) return Result;
1642 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1643 if (N1.getOpcode() == ISD::SHL &&
1644 N1.getOperand(0).getOpcode() == ISD::SUB)
1645 if (ConstantSDNode *C =
1646 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1647 if (C->getAPIntValue() == 0)
1648 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1649 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1650 N1.getOperand(0).getOperand(1),
1652 if (N0.getOpcode() == ISD::SHL &&
1653 N0.getOperand(0).getOpcode() == ISD::SUB)
1654 if (ConstantSDNode *C =
1655 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1656 if (C->getAPIntValue() == 0)
1657 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1658 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1659 N0.getOperand(0).getOperand(1),
1662 if (N1.getOpcode() == ISD::AND) {
1663 SDValue AndOp0 = N1.getOperand(0);
1664 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1665 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1666 unsigned DestBits = VT.getScalarType().getSizeInBits();
1668 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1669 // and similar xforms where the inner op is either ~0 or 0.
1670 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1672 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1676 // add (sext i1), X -> sub X, (zext i1)
1677 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1678 N0.getOperand(0).getValueType() == MVT::i1 &&
1679 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1681 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1682 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1688 SDValue DAGCombiner::visitADDC(SDNode *N) {
1689 SDValue N0 = N->getOperand(0);
1690 SDValue N1 = N->getOperand(1);
1691 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1692 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1693 EVT VT = N0.getValueType();
1695 // If the flag result is dead, turn this into an ADD.
1696 if (!N->hasAnyUseOfValue(1))
1697 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1698 DAG.getNode(ISD::CARRY_FALSE,
1699 SDLoc(N), MVT::Glue));
1701 // canonicalize constant to RHS.
1703 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1705 // fold (addc x, 0) -> x + no carry out
1706 if (N1C && N1C->isNullValue())
1707 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1708 SDLoc(N), MVT::Glue));
1710 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1711 APInt LHSZero, LHSOne;
1712 APInt RHSZero, RHSOne;
1713 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1715 if (LHSZero.getBoolValue()) {
1716 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1718 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1719 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1720 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1721 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1722 DAG.getNode(ISD::CARRY_FALSE,
1723 SDLoc(N), MVT::Glue));
1729 SDValue DAGCombiner::visitADDE(SDNode *N) {
1730 SDValue N0 = N->getOperand(0);
1731 SDValue N1 = N->getOperand(1);
1732 SDValue CarryIn = N->getOperand(2);
1733 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1734 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1736 // canonicalize constant to RHS
1738 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1741 // fold (adde x, y, false) -> (addc x, y)
1742 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1743 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1748 // Since it may not be valid to emit a fold to zero for vector initializers
1749 // check if we can before folding.
1750 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1752 bool LegalOperations, bool LegalTypes) {
1754 return DAG.getConstant(0, VT);
1755 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1756 return DAG.getConstant(0, VT);
1760 SDValue DAGCombiner::visitSUB(SDNode *N) {
1761 SDValue N0 = N->getOperand(0);
1762 SDValue N1 = N->getOperand(1);
1763 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1764 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1765 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1766 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1767 EVT VT = N0.getValueType();
1770 if (VT.isVector()) {
1771 SDValue FoldedVOp = SimplifyVBinOp(N);
1772 if (FoldedVOp.getNode()) return FoldedVOp;
1774 // fold (sub x, 0) -> x, vector edition
1775 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1779 // fold (sub x, x) -> 0
1780 // FIXME: Refactor this and xor and other similar operations together.
1782 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1783 // fold (sub c1, c2) -> c1-c2
1785 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1786 // fold (sub x, c) -> (add x, -c)
1788 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1789 DAG.getConstant(-N1C->getAPIntValue(), VT));
1790 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1791 if (N0C && N0C->isAllOnesValue())
1792 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1793 // fold A-(A-B) -> B
1794 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1795 return N1.getOperand(1);
1796 // fold (A+B)-A -> B
1797 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1798 return N0.getOperand(1);
1799 // fold (A+B)-B -> A
1800 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1801 return N0.getOperand(0);
1802 // fold C2-(A+C1) -> (C2-C1)-A
1803 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1804 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1806 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1809 // fold ((A+(B+or-C))-B) -> A+or-C
1810 if (N0.getOpcode() == ISD::ADD &&
1811 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1812 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1813 N0.getOperand(1).getOperand(0) == N1)
1814 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1815 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1816 // fold ((A+(C+B))-B) -> A+C
1817 if (N0.getOpcode() == ISD::ADD &&
1818 N0.getOperand(1).getOpcode() == ISD::ADD &&
1819 N0.getOperand(1).getOperand(1) == N1)
1820 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1821 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1822 // fold ((A-(B-C))-C) -> A-B
1823 if (N0.getOpcode() == ISD::SUB &&
1824 N0.getOperand(1).getOpcode() == ISD::SUB &&
1825 N0.getOperand(1).getOperand(1) == N1)
1826 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1827 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1829 // If either operand of a sub is undef, the result is undef
1830 if (N0.getOpcode() == ISD::UNDEF)
1832 if (N1.getOpcode() == ISD::UNDEF)
1835 // If the relocation model supports it, consider symbol offsets.
1836 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1837 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1838 // fold (sub Sym, c) -> Sym-c
1839 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1840 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1842 (uint64_t)N1C->getSExtValue());
1843 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1844 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1845 if (GA->getGlobal() == GB->getGlobal())
1846 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1853 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1854 SDValue N0 = N->getOperand(0);
1855 SDValue N1 = N->getOperand(1);
1856 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1857 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1858 EVT VT = N0.getValueType();
1860 // If the flag result is dead, turn this into an SUB.
1861 if (!N->hasAnyUseOfValue(1))
1862 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1863 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1866 // fold (subc x, x) -> 0 + no borrow
1868 return CombineTo(N, DAG.getConstant(0, VT),
1869 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1872 // fold (subc x, 0) -> x + no borrow
1873 if (N1C && N1C->isNullValue())
1874 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1877 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1878 if (N0C && N0C->isAllOnesValue())
1879 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1880 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1886 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1887 SDValue N0 = N->getOperand(0);
1888 SDValue N1 = N->getOperand(1);
1889 SDValue CarryIn = N->getOperand(2);
1891 // fold (sube x, y, false) -> (subc x, y)
1892 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1893 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1898 SDValue DAGCombiner::visitMUL(SDNode *N) {
1899 SDValue N0 = N->getOperand(0);
1900 SDValue N1 = N->getOperand(1);
1901 EVT VT = N0.getValueType();
1903 // fold (mul x, undef) -> 0
1904 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1905 return DAG.getConstant(0, VT);
1907 bool N0IsConst = false;
1908 bool N1IsConst = false;
1909 APInt ConstValue0, ConstValue1;
1911 if (VT.isVector()) {
1912 SDValue FoldedVOp = SimplifyVBinOp(N);
1913 if (FoldedVOp.getNode()) return FoldedVOp;
1915 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1916 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1918 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1919 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1921 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1922 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1926 // fold (mul c1, c2) -> c1*c2
1927 if (N0IsConst && N1IsConst)
1928 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1930 // canonicalize constant to RHS
1931 if (N0IsConst && !N1IsConst)
1932 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1933 // fold (mul x, 0) -> 0
1934 if (N1IsConst && ConstValue1 == 0)
1936 // We require a splat of the entire scalar bit width for non-contiguous
1939 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1940 // fold (mul x, 1) -> x
1941 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1943 // fold (mul x, -1) -> 0-x
1944 if (N1IsConst && ConstValue1.isAllOnesValue())
1945 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1946 DAG.getConstant(0, VT), N0);
1947 // fold (mul x, (1 << c)) -> x << c
1948 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1949 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1950 DAG.getConstant(ConstValue1.logBase2(),
1951 getShiftAmountTy(N0.getValueType())));
1952 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1953 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1954 unsigned Log2Val = (-ConstValue1).logBase2();
1955 // FIXME: If the input is something that is easily negated (e.g. a
1956 // single-use add), we should put the negate there.
1957 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1958 DAG.getConstant(0, VT),
1959 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1960 DAG.getConstant(Log2Val,
1961 getShiftAmountTy(N0.getValueType()))));
1965 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1966 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1967 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1968 isa<ConstantSDNode>(N0.getOperand(1)))) {
1969 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1970 N1, N0.getOperand(1));
1971 AddToWorklist(C3.getNode());
1972 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1973 N0.getOperand(0), C3);
1976 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1979 SDValue Sh(nullptr,0), Y(nullptr,0);
1980 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1981 if (N0.getOpcode() == ISD::SHL &&
1982 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1983 isa<ConstantSDNode>(N0.getOperand(1))) &&
1984 N0.getNode()->hasOneUse()) {
1986 } else if (N1.getOpcode() == ISD::SHL &&
1987 isa<ConstantSDNode>(N1.getOperand(1)) &&
1988 N1.getNode()->hasOneUse()) {
1993 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1994 Sh.getOperand(0), Y);
1995 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1996 Mul, Sh.getOperand(1));
2000 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2001 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2002 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2003 isa<ConstantSDNode>(N0.getOperand(1))))
2004 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2005 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2006 N0.getOperand(0), N1),
2007 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2008 N0.getOperand(1), N1));
2011 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2018 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2019 SDValue N0 = N->getOperand(0);
2020 SDValue N1 = N->getOperand(1);
2021 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2022 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2023 EVT VT = N->getValueType(0);
2026 if (VT.isVector()) {
2027 SDValue FoldedVOp = SimplifyVBinOp(N);
2028 if (FoldedVOp.getNode()) return FoldedVOp;
2031 // fold (sdiv c1, c2) -> c1/c2
2032 if (N0C && N1C && !N1C->isNullValue())
2033 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2034 // fold (sdiv X, 1) -> X
2035 if (N1C && N1C->getAPIntValue() == 1LL)
2037 // fold (sdiv X, -1) -> 0-X
2038 if (N1C && N1C->isAllOnesValue())
2039 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2040 DAG.getConstant(0, VT), N0);
2041 // If we know the sign bits of both operands are zero, strength reduce to a
2042 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2043 if (!VT.isVector()) {
2044 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2045 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2049 // fold (sdiv X, pow2) -> simple ops after legalize
2050 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2051 (-N1C->getAPIntValue()).isPowerOf2())) {
2052 // If dividing by powers of two is cheap, then don't perform the following
2054 if (TLI.isPow2DivCheap())
2057 // Target-specific implementation of sdiv x, pow2.
2058 SDValue Res = BuildSDIVPow2(N);
2062 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2064 // Splat the sign bit into the register
2066 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2067 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2068 getShiftAmountTy(N0.getValueType())));
2069 AddToWorklist(SGN.getNode());
2071 // Add (N0 < 0) ? abs2 - 1 : 0;
2073 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2074 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2075 getShiftAmountTy(SGN.getValueType())));
2076 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2077 AddToWorklist(SRL.getNode());
2078 AddToWorklist(ADD.getNode()); // Divide by pow2
2079 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2080 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2082 // If we're dividing by a positive value, we're done. Otherwise, we must
2083 // negate the result.
2084 if (N1C->getAPIntValue().isNonNegative())
2087 AddToWorklist(SRA.getNode());
2088 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2091 // if integer divide is expensive and we satisfy the requirements, emit an
2092 // alternate sequence.
2093 if (N1C && !TLI.isIntDivCheap()) {
2094 SDValue Op = BuildSDIV(N);
2095 if (Op.getNode()) return Op;
2099 if (N0.getOpcode() == ISD::UNDEF)
2100 return DAG.getConstant(0, VT);
2101 // X / undef -> undef
2102 if (N1.getOpcode() == ISD::UNDEF)
2108 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2109 SDValue N0 = N->getOperand(0);
2110 SDValue N1 = N->getOperand(1);
2111 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2112 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2113 EVT VT = N->getValueType(0);
2116 if (VT.isVector()) {
2117 SDValue FoldedVOp = SimplifyVBinOp(N);
2118 if (FoldedVOp.getNode()) return FoldedVOp;
2121 // fold (udiv c1, c2) -> c1/c2
2122 if (N0C && N1C && !N1C->isNullValue())
2123 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2124 // fold (udiv x, (1 << c)) -> x >>u c
2125 if (N1C && N1C->getAPIntValue().isPowerOf2())
2126 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2127 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2128 getShiftAmountTy(N0.getValueType())));
2129 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2130 if (N1.getOpcode() == ISD::SHL) {
2131 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2132 if (SHC->getAPIntValue().isPowerOf2()) {
2133 EVT ADDVT = N1.getOperand(1).getValueType();
2134 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2136 DAG.getConstant(SHC->getAPIntValue()
2139 AddToWorklist(Add.getNode());
2140 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2144 // fold (udiv x, c) -> alternate
2145 if (N1C && !TLI.isIntDivCheap()) {
2146 SDValue Op = BuildUDIV(N);
2147 if (Op.getNode()) return Op;
2151 if (N0.getOpcode() == ISD::UNDEF)
2152 return DAG.getConstant(0, VT);
2153 // X / undef -> undef
2154 if (N1.getOpcode() == ISD::UNDEF)
2160 SDValue DAGCombiner::visitSREM(SDNode *N) {
2161 SDValue N0 = N->getOperand(0);
2162 SDValue N1 = N->getOperand(1);
2163 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2164 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2165 EVT VT = N->getValueType(0);
2167 // fold (srem c1, c2) -> c1%c2
2168 if (N0C && N1C && !N1C->isNullValue())
2169 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2170 // If we know the sign bits of both operands are zero, strength reduce to a
2171 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2172 if (!VT.isVector()) {
2173 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2174 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2177 // If X/C can be simplified by the division-by-constant logic, lower
2178 // X%C to the equivalent of X-X/C*C.
2179 if (N1C && !N1C->isNullValue()) {
2180 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2181 AddToWorklist(Div.getNode());
2182 SDValue OptimizedDiv = combine(Div.getNode());
2183 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2184 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2186 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2187 AddToWorklist(Mul.getNode());
2193 if (N0.getOpcode() == ISD::UNDEF)
2194 return DAG.getConstant(0, VT);
2195 // X % undef -> undef
2196 if (N1.getOpcode() == ISD::UNDEF)
2202 SDValue DAGCombiner::visitUREM(SDNode *N) {
2203 SDValue N0 = N->getOperand(0);
2204 SDValue N1 = N->getOperand(1);
2205 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2206 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2207 EVT VT = N->getValueType(0);
2209 // fold (urem c1, c2) -> c1%c2
2210 if (N0C && N1C && !N1C->isNullValue())
2211 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2212 // fold (urem x, pow2) -> (and x, pow2-1)
2213 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2214 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2215 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2216 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2217 if (N1.getOpcode() == ISD::SHL) {
2218 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2219 if (SHC->getAPIntValue().isPowerOf2()) {
2221 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2222 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2224 AddToWorklist(Add.getNode());
2225 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2230 // If X/C can be simplified by the division-by-constant logic, lower
2231 // X%C to the equivalent of X-X/C*C.
2232 if (N1C && !N1C->isNullValue()) {
2233 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2234 AddToWorklist(Div.getNode());
2235 SDValue OptimizedDiv = combine(Div.getNode());
2236 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2237 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2239 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2240 AddToWorklist(Mul.getNode());
2246 if (N0.getOpcode() == ISD::UNDEF)
2247 return DAG.getConstant(0, VT);
2248 // X % undef -> undef
2249 if (N1.getOpcode() == ISD::UNDEF)
2255 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2256 SDValue N0 = N->getOperand(0);
2257 SDValue N1 = N->getOperand(1);
2258 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2259 EVT VT = N->getValueType(0);
2262 // fold (mulhs x, 0) -> 0
2263 if (N1C && N1C->isNullValue())
2265 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2266 if (N1C && N1C->getAPIntValue() == 1)
2267 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2268 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2269 getShiftAmountTy(N0.getValueType())));
2270 // fold (mulhs x, undef) -> 0
2271 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2272 return DAG.getConstant(0, VT);
2274 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2276 if (VT.isSimple() && !VT.isVector()) {
2277 MVT Simple = VT.getSimpleVT();
2278 unsigned SimpleSize = Simple.getSizeInBits();
2279 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2280 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2281 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2282 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2283 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2284 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2285 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2286 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2293 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2294 SDValue N0 = N->getOperand(0);
2295 SDValue N1 = N->getOperand(1);
2296 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2297 EVT VT = N->getValueType(0);
2300 // fold (mulhu x, 0) -> 0
2301 if (N1C && N1C->isNullValue())
2303 // fold (mulhu x, 1) -> 0
2304 if (N1C && N1C->getAPIntValue() == 1)
2305 return DAG.getConstant(0, N0.getValueType());
2306 // fold (mulhu x, undef) -> 0
2307 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2308 return DAG.getConstant(0, VT);
2310 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2312 if (VT.isSimple() && !VT.isVector()) {
2313 MVT Simple = VT.getSimpleVT();
2314 unsigned SimpleSize = Simple.getSizeInBits();
2315 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2316 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2317 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2318 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2319 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2320 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2321 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2322 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2329 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2330 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2331 /// that are being performed. Return true if a simplification was made.
2333 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2335 // If the high half is not needed, just compute the low half.
2336 bool HiExists = N->hasAnyUseOfValue(1);
2338 (!LegalOperations ||
2339 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2340 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2341 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2342 return CombineTo(N, Res, Res);
2345 // If the low half is not needed, just compute the high half.
2346 bool LoExists = N->hasAnyUseOfValue(0);
2348 (!LegalOperations ||
2349 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2350 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2351 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2352 return CombineTo(N, Res, Res);
2355 // If both halves are used, return as it is.
2356 if (LoExists && HiExists)
2359 // If the two computed results can be simplified separately, separate them.
2361 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2362 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2363 AddToWorklist(Lo.getNode());
2364 SDValue LoOpt = combine(Lo.getNode());
2365 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2366 (!LegalOperations ||
2367 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2368 return CombineTo(N, LoOpt, LoOpt);
2372 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2373 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2374 AddToWorklist(Hi.getNode());
2375 SDValue HiOpt = combine(Hi.getNode());
2376 if (HiOpt.getNode() && HiOpt != Hi &&
2377 (!LegalOperations ||
2378 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2379 return CombineTo(N, HiOpt, HiOpt);
2385 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2386 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2387 if (Res.getNode()) return Res;
2389 EVT VT = N->getValueType(0);
2392 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2394 if (VT.isSimple() && !VT.isVector()) {
2395 MVT Simple = VT.getSimpleVT();
2396 unsigned SimpleSize = Simple.getSizeInBits();
2397 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2398 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2399 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2400 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2401 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2402 // Compute the high part as N1.
2403 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2404 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2405 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2406 // Compute the low part as N0.
2407 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2408 return CombineTo(N, Lo, Hi);
2415 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2416 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2417 if (Res.getNode()) return Res;
2419 EVT VT = N->getValueType(0);
2422 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2424 if (VT.isSimple() && !VT.isVector()) {
2425 MVT Simple = VT.getSimpleVT();
2426 unsigned SimpleSize = Simple.getSizeInBits();
2427 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2428 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2429 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2430 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2431 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2432 // Compute the high part as N1.
2433 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2434 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2435 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2436 // Compute the low part as N0.
2437 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2438 return CombineTo(N, Lo, Hi);
2445 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2446 // (smulo x, 2) -> (saddo x, x)
2447 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2448 if (C2->getAPIntValue() == 2)
2449 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2450 N->getOperand(0), N->getOperand(0));
2455 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2456 // (umulo x, 2) -> (uaddo x, x)
2457 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2458 if (C2->getAPIntValue() == 2)
2459 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2460 N->getOperand(0), N->getOperand(0));
2465 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2466 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2467 if (Res.getNode()) return Res;
2472 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2473 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2474 if (Res.getNode()) return Res;
2479 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2480 /// two operands of the same opcode, try to simplify it.
2481 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2482 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2483 EVT VT = N0.getValueType();
2484 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2486 // Bail early if none of these transforms apply.
2487 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2489 // For each of OP in AND/OR/XOR:
2490 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2491 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2492 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2493 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2495 // do not sink logical op inside of a vector extend, since it may combine
2497 EVT Op0VT = N0.getOperand(0).getValueType();
2498 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2499 N0.getOpcode() == ISD::SIGN_EXTEND ||
2500 // Avoid infinite looping with PromoteIntBinOp.
2501 (N0.getOpcode() == ISD::ANY_EXTEND &&
2502 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2503 (N0.getOpcode() == ISD::TRUNCATE &&
2504 (!TLI.isZExtFree(VT, Op0VT) ||
2505 !TLI.isTruncateFree(Op0VT, VT)) &&
2506 TLI.isTypeLegal(Op0VT))) &&
2508 Op0VT == N1.getOperand(0).getValueType() &&
2509 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2510 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2511 N0.getOperand(0).getValueType(),
2512 N0.getOperand(0), N1.getOperand(0));
2513 AddToWorklist(ORNode.getNode());
2514 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2517 // For each of OP in SHL/SRL/SRA/AND...
2518 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2519 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2520 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2521 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2522 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2523 N0.getOperand(1) == N1.getOperand(1)) {
2524 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2525 N0.getOperand(0).getValueType(),
2526 N0.getOperand(0), N1.getOperand(0));
2527 AddToWorklist(ORNode.getNode());
2528 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2529 ORNode, N0.getOperand(1));
2532 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2533 // Only perform this optimization after type legalization and before
2534 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2535 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2536 // we don't want to undo this promotion.
2537 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2539 if ((N0.getOpcode() == ISD::BITCAST ||
2540 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2541 Level == AfterLegalizeTypes) {
2542 SDValue In0 = N0.getOperand(0);
2543 SDValue In1 = N1.getOperand(0);
2544 EVT In0Ty = In0.getValueType();
2545 EVT In1Ty = In1.getValueType();
2547 // If both incoming values are integers, and the original types are the
2549 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2550 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2551 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2552 AddToWorklist(Op.getNode());
2557 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2558 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2559 // If both shuffles use the same mask, and both shuffle within a single
2560 // vector, then it is worthwhile to move the swizzle after the operation.
2561 // The type-legalizer generates this pattern when loading illegal
2562 // vector types from memory. In many cases this allows additional shuffle
2564 // There are other cases where moving the shuffle after the xor/and/or
2565 // is profitable even if shuffles don't perform a swizzle.
2566 // If both shuffles use the same mask, and both shuffles have the same first
2567 // or second operand, then it might still be profitable to move the shuffle
2568 // after the xor/and/or operation.
2569 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2570 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2571 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2573 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2574 "Inputs to shuffles are not the same type");
2576 // Check that both shuffles use the same mask. The masks are known to be of
2577 // the same length because the result vector type is the same.
2578 // Check also that shuffles have only one use to avoid introducing extra
2580 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2581 SVN0->getMask().equals(SVN1->getMask())) {
2582 SDValue ShOp = N0->getOperand(1);
2584 // Don't try to fold this node if it requires introducing a
2585 // build vector of all zeros that might be illegal at this stage.
2586 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2588 ShOp = DAG.getConstant(0, VT);
2593 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2594 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2595 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2596 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2597 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2598 N0->getOperand(0), N1->getOperand(0));
2599 AddToWorklist(NewNode.getNode());
2600 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2601 &SVN0->getMask()[0]);
2604 // Don't try to fold this node if it requires introducing a
2605 // build vector of all zeros that might be illegal at this stage.
2606 ShOp = N0->getOperand(0);
2607 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2609 ShOp = DAG.getConstant(0, VT);
2614 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2615 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2616 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2617 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2618 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2619 N0->getOperand(1), N1->getOperand(1));
2620 AddToWorklist(NewNode.getNode());
2621 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2622 &SVN0->getMask()[0]);
2630 SDValue DAGCombiner::visitAND(SDNode *N) {
2631 SDValue N0 = N->getOperand(0);
2632 SDValue N1 = N->getOperand(1);
2633 SDValue LL, LR, RL, RR, CC0, CC1;
2634 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2635 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2636 EVT VT = N1.getValueType();
2637 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2640 if (VT.isVector()) {
2641 SDValue FoldedVOp = SimplifyVBinOp(N);
2642 if (FoldedVOp.getNode()) return FoldedVOp;
2644 // fold (and x, 0) -> 0, vector edition
2645 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2647 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2650 // fold (and x, -1) -> x, vector edition
2651 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2653 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2657 // fold (and x, undef) -> 0
2658 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2659 return DAG.getConstant(0, VT);
2660 // fold (and c1, c2) -> c1&c2
2662 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2663 // canonicalize constant to RHS
2665 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2666 // fold (and x, -1) -> x
2667 if (N1C && N1C->isAllOnesValue())
2669 // if (and x, c) is known to be zero, return 0
2670 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2671 APInt::getAllOnesValue(BitWidth)))
2672 return DAG.getConstant(0, VT);
2674 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2677 // fold (and (or x, C), D) -> D if (C & D) == D
2678 if (N1C && N0.getOpcode() == ISD::OR)
2679 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2680 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2682 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2683 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2684 SDValue N0Op0 = N0.getOperand(0);
2685 APInt Mask = ~N1C->getAPIntValue();
2686 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2687 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2688 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2689 N0.getValueType(), N0Op0);
2691 // Replace uses of the AND with uses of the Zero extend node.
2694 // We actually want to replace all uses of the any_extend with the
2695 // zero_extend, to avoid duplicating things. This will later cause this
2696 // AND to be folded.
2697 CombineTo(N0.getNode(), Zext);
2698 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2701 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2702 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2703 // already be zero by virtue of the width of the base type of the load.
2705 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2707 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2708 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2709 N0.getOpcode() == ISD::LOAD) {
2710 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2711 N0 : N0.getOperand(0) );
2713 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2714 // This can be a pure constant or a vector splat, in which case we treat the
2715 // vector as a scalar and use the splat value.
2716 APInt Constant = APInt::getNullValue(1);
2717 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2718 Constant = C->getAPIntValue();
2719 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2720 APInt SplatValue, SplatUndef;
2721 unsigned SplatBitSize;
2723 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2724 SplatBitSize, HasAnyUndefs);
2726 // Undef bits can contribute to a possible optimisation if set, so
2728 SplatValue |= SplatUndef;
2730 // The splat value may be something like "0x00FFFFFF", which means 0 for
2731 // the first vector value and FF for the rest, repeating. We need a mask
2732 // that will apply equally to all members of the vector, so AND all the
2733 // lanes of the constant together.
2734 EVT VT = Vector->getValueType(0);
2735 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2737 // If the splat value has been compressed to a bitlength lower
2738 // than the size of the vector lane, we need to re-expand it to
2740 if (BitWidth > SplatBitSize)
2741 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2742 SplatBitSize < BitWidth;
2743 SplatBitSize = SplatBitSize * 2)
2744 SplatValue |= SplatValue.shl(SplatBitSize);
2746 Constant = APInt::getAllOnesValue(BitWidth);
2747 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2748 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2752 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2753 // actually legal and isn't going to get expanded, else this is a false
2755 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2756 Load->getMemoryVT());
2758 // Resize the constant to the same size as the original memory access before
2759 // extension. If it is still the AllOnesValue then this AND is completely
2762 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2765 switch (Load->getExtensionType()) {
2766 default: B = false; break;
2767 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2769 case ISD::NON_EXTLOAD: B = true; break;
2772 if (B && Constant.isAllOnesValue()) {
2773 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2774 // preserve semantics once we get rid of the AND.
2775 SDValue NewLoad(Load, 0);
2776 if (Load->getExtensionType() == ISD::EXTLOAD) {
2777 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2778 Load->getValueType(0), SDLoc(Load),
2779 Load->getChain(), Load->getBasePtr(),
2780 Load->getOffset(), Load->getMemoryVT(),
2781 Load->getMemOperand());
2782 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2783 if (Load->getNumValues() == 3) {
2784 // PRE/POST_INC loads have 3 values.
2785 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2786 NewLoad.getValue(2) };
2787 CombineTo(Load, To, 3, true);
2789 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2793 // Fold the AND away, taking care not to fold to the old load node if we
2795 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2797 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2800 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2801 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2802 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2803 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2805 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2806 LL.getValueType().isInteger()) {
2807 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2808 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2809 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2810 LR.getValueType(), LL, RL);
2811 AddToWorklist(ORNode.getNode());
2812 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2814 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2815 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2816 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2817 LR.getValueType(), LL, RL);
2818 AddToWorklist(ANDNode.getNode());
2819 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2821 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2822 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2823 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2824 LR.getValueType(), LL, RL);
2825 AddToWorklist(ORNode.getNode());
2826 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2829 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2830 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2831 Op0 == Op1 && LL.getValueType().isInteger() &&
2832 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2833 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2834 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2835 cast<ConstantSDNode>(RR)->isNullValue()))) {
2836 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2837 LL, DAG.getConstant(1, LL.getValueType()));
2838 AddToWorklist(ADDNode.getNode());
2839 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2840 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2842 // canonicalize equivalent to ll == rl
2843 if (LL == RR && LR == RL) {
2844 Op1 = ISD::getSetCCSwappedOperands(Op1);
2847 if (LL == RL && LR == RR) {
2848 bool isInteger = LL.getValueType().isInteger();
2849 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2850 if (Result != ISD::SETCC_INVALID &&
2851 (!LegalOperations ||
2852 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2853 TLI.isOperationLegal(ISD::SETCC,
2854 getSetCCResultType(N0.getSimpleValueType())))))
2855 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2860 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2861 if (N0.getOpcode() == N1.getOpcode()) {
2862 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2863 if (Tmp.getNode()) return Tmp;
2866 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2867 // fold (and (sra)) -> (and (srl)) when possible.
2868 if (!VT.isVector() &&
2869 SimplifyDemandedBits(SDValue(N, 0)))
2870 return SDValue(N, 0);
2872 // fold (zext_inreg (extload x)) -> (zextload x)
2873 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2874 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2875 EVT MemVT = LN0->getMemoryVT();
2876 // If we zero all the possible extended bits, then we can turn this into
2877 // a zextload if we are running before legalize or the operation is legal.
2878 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2879 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2880 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2881 ((!LegalOperations && !LN0->isVolatile()) ||
2882 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2883 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2884 LN0->getChain(), LN0->getBasePtr(),
2885 MemVT, LN0->getMemOperand());
2887 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2888 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2891 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2892 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2894 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2895 EVT MemVT = LN0->getMemoryVT();
2896 // If we zero all the possible extended bits, then we can turn this into
2897 // a zextload if we are running before legalize or the operation is legal.
2898 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2899 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2900 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2901 ((!LegalOperations && !LN0->isVolatile()) ||
2902 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2903 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2904 LN0->getChain(), LN0->getBasePtr(),
2905 MemVT, LN0->getMemOperand());
2907 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2908 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2912 // fold (and (load x), 255) -> (zextload x, i8)
2913 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2914 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2915 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2916 (N0.getOpcode() == ISD::ANY_EXTEND &&
2917 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2918 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2919 LoadSDNode *LN0 = HasAnyExt
2920 ? cast<LoadSDNode>(N0.getOperand(0))
2921 : cast<LoadSDNode>(N0);
2922 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2923 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2924 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2925 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2926 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2927 EVT LoadedVT = LN0->getMemoryVT();
2929 if (ExtVT == LoadedVT &&
2930 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2931 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2934 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2935 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2936 LN0->getMemOperand());
2938 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2939 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2942 // Do not change the width of a volatile load.
2943 // Do not generate loads of non-round integer types since these can
2944 // be expensive (and would be wrong if the type is not byte sized).
2945 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2946 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2947 EVT PtrType = LN0->getOperand(1).getValueType();
2949 unsigned Alignment = LN0->getAlignment();
2950 SDValue NewPtr = LN0->getBasePtr();
2952 // For big endian targets, we need to add an offset to the pointer
2953 // to load the correct bytes. For little endian systems, we merely
2954 // need to read fewer bytes from the same pointer.
2955 if (TLI.isBigEndian()) {
2956 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2957 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2958 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2959 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2960 NewPtr, DAG.getConstant(PtrOff, PtrType));
2961 Alignment = MinAlign(Alignment, PtrOff);
2964 AddToWorklist(NewPtr.getNode());
2966 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2968 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2969 LN0->getChain(), NewPtr,
2970 LN0->getPointerInfo(),
2971 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2972 LN0->isInvariant(), Alignment, LN0->getAAInfo());
2974 CombineTo(LN0, Load, Load.getValue(1));
2975 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2981 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2982 VT.getSizeInBits() <= 64) {
2983 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2984 APInt ADDC = ADDI->getAPIntValue();
2985 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2986 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2987 // immediate for an add, but it is legal if its top c2 bits are set,
2988 // transform the ADD so the immediate doesn't need to be materialized
2990 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2991 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2992 SRLI->getZExtValue());
2993 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2995 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2997 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2998 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2999 CombineTo(N0.getNode(), NewAdd);
3000 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3008 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3009 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3010 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3011 N0.getOperand(1), false);
3012 if (BSwap.getNode())
3019 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
3021 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3022 bool DemandHighBits) {
3023 if (!LegalOperations)
3026 EVT VT = N->getValueType(0);
3027 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3029 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3032 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3033 bool LookPassAnd0 = false;
3034 bool LookPassAnd1 = false;
3035 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3037 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3039 if (N0.getOpcode() == ISD::AND) {
3040 if (!N0.getNode()->hasOneUse())
3042 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3043 if (!N01C || N01C->getZExtValue() != 0xFF00)
3045 N0 = N0.getOperand(0);
3046 LookPassAnd0 = true;
3049 if (N1.getOpcode() == ISD::AND) {
3050 if (!N1.getNode()->hasOneUse())
3052 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3053 if (!N11C || N11C->getZExtValue() != 0xFF)
3055 N1 = N1.getOperand(0);
3056 LookPassAnd1 = true;
3059 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3061 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3063 if (!N0.getNode()->hasOneUse() ||
3064 !N1.getNode()->hasOneUse())
3067 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3068 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3071 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3074 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3075 SDValue N00 = N0->getOperand(0);
3076 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3077 if (!N00.getNode()->hasOneUse())
3079 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3080 if (!N001C || N001C->getZExtValue() != 0xFF)
3082 N00 = N00.getOperand(0);
3083 LookPassAnd0 = true;
3086 SDValue N10 = N1->getOperand(0);
3087 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3088 if (!N10.getNode()->hasOneUse())
3090 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3091 if (!N101C || N101C->getZExtValue() != 0xFF00)
3093 N10 = N10.getOperand(0);
3094 LookPassAnd1 = true;
3100 // Make sure everything beyond the low halfword gets set to zero since the SRL
3101 // 16 will clear the top bits.
3102 unsigned OpSizeInBits = VT.getSizeInBits();
3103 if (DemandHighBits && OpSizeInBits > 16) {
3104 // If the left-shift isn't masked out then the only way this is a bswap is
3105 // if all bits beyond the low 8 are 0. In that case the entire pattern
3106 // reduces to a left shift anyway: leave it for other parts of the combiner.
3110 // However, if the right shift isn't masked out then it might be because
3111 // it's not needed. See if we can spot that too.
3112 if (!LookPassAnd1 &&
3113 !DAG.MaskedValueIsZero(
3114 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3118 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3119 if (OpSizeInBits > 16)
3120 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3121 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3125 /// isBSwapHWordElement - Return true if the specified node is an element
3126 /// that makes up a 32-bit packed halfword byteswap. i.e.
3127 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3128 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3129 if (!N.getNode()->hasOneUse())
3132 unsigned Opc = N.getOpcode();
3133 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3136 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3141 switch (N1C->getZExtValue()) {
3144 case 0xFF: Num = 0; break;
3145 case 0xFF00: Num = 1; break;
3146 case 0xFF0000: Num = 2; break;
3147 case 0xFF000000: Num = 3; break;
3150 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3151 SDValue N0 = N.getOperand(0);
3152 if (Opc == ISD::AND) {
3153 if (Num == 0 || Num == 2) {
3155 // (x >> 8) & 0xff0000
3156 if (N0.getOpcode() != ISD::SRL)
3158 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3159 if (!C || C->getZExtValue() != 8)
3162 // (x << 8) & 0xff00
3163 // (x << 8) & 0xff000000
3164 if (N0.getOpcode() != ISD::SHL)
3166 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3167 if (!C || C->getZExtValue() != 8)
3170 } else if (Opc == ISD::SHL) {
3172 // (x & 0xff0000) << 8
3173 if (Num != 0 && Num != 2)
3175 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3176 if (!C || C->getZExtValue() != 8)
3178 } else { // Opc == ISD::SRL
3179 // (x & 0xff00) >> 8
3180 // (x & 0xff000000) >> 8
3181 if (Num != 1 && Num != 3)
3183 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3184 if (!C || C->getZExtValue() != 8)
3191 Parts[Num] = N0.getOperand(0).getNode();
3195 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3196 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3197 /// => (rotl (bswap x), 16)
3198 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3199 if (!LegalOperations)
3202 EVT VT = N->getValueType(0);
3205 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3208 SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3210 // (or (or (and), (and)), (or (and), (and)))
3211 // (or (or (or (and), (and)), (and)), (and))
3212 if (N0.getOpcode() != ISD::OR)
3214 SDValue N00 = N0.getOperand(0);
3215 SDValue N01 = N0.getOperand(1);
3217 if (N1.getOpcode() == ISD::OR &&
3218 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3219 // (or (or (and), (and)), (or (and), (and)))
3220 SDValue N000 = N00.getOperand(0);
3221 if (!isBSwapHWordElement(N000, Parts))
3224 SDValue N001 = N00.getOperand(1);
3225 if (!isBSwapHWordElement(N001, Parts))
3227 SDValue N010 = N01.getOperand(0);
3228 if (!isBSwapHWordElement(N010, Parts))
3230 SDValue N011 = N01.getOperand(1);
3231 if (!isBSwapHWordElement(N011, Parts))
3234 // (or (or (or (and), (and)), (and)), (and))
3235 if (!isBSwapHWordElement(N1, Parts))
3237 if (!isBSwapHWordElement(N01, Parts))
3239 if (N00.getOpcode() != ISD::OR)
3241 SDValue N000 = N00.getOperand(0);
3242 if (!isBSwapHWordElement(N000, Parts))
3244 SDValue N001 = N00.getOperand(1);
3245 if (!isBSwapHWordElement(N001, Parts))
3249 // Make sure the parts are all coming from the same node.
3250 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3253 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3254 SDValue(Parts[0],0));
3256 // Result of the bswap should be rotated by 16. If it's not legal, then
3257 // do (x << 16) | (x >> 16).
3258 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3259 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3260 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3261 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3262 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3263 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3264 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3265 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3268 SDValue DAGCombiner::visitOR(SDNode *N) {
3269 SDValue N0 = N->getOperand(0);
3270 SDValue N1 = N->getOperand(1);
3271 SDValue LL, LR, RL, RR, CC0, CC1;
3272 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3273 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3274 EVT VT = N1.getValueType();
3277 if (VT.isVector()) {
3278 SDValue FoldedVOp = SimplifyVBinOp(N);
3279 if (FoldedVOp.getNode()) return FoldedVOp;
3281 // fold (or x, 0) -> x, vector edition
3282 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3284 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3287 // fold (or x, -1) -> -1, vector edition
3288 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3290 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3293 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3294 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3295 // Do this only if the resulting shuffle is legal.
3296 if (isa<ShuffleVectorSDNode>(N0) &&
3297 isa<ShuffleVectorSDNode>(N1) &&
3298 // Avoid folding a node with illegal type.
3299 TLI.isTypeLegal(VT) &&
3300 N0->getOperand(1) == N1->getOperand(1) &&
3301 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3302 bool CanFold = true;
3303 unsigned NumElts = VT.getVectorNumElements();
3304 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3305 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3306 // We construct two shuffle masks:
3307 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3308 // and N1 as the second operand.
3309 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3310 // and N0 as the second operand.
3311 // We do this because OR is commutable and therefore there might be
3312 // two ways to fold this node into a shuffle.
3313 SmallVector<int,4> Mask1;
3314 SmallVector<int,4> Mask2;
3316 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3317 int M0 = SV0->getMaskElt(i);
3318 int M1 = SV1->getMaskElt(i);
3320 // Both shuffle indexes are undef. Propagate Undef.
3321 if (M0 < 0 && M1 < 0) {
3322 Mask1.push_back(M0);
3323 Mask2.push_back(M0);
3327 if (M0 < 0 || M1 < 0 ||
3328 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3329 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3334 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3335 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3339 // Fold this sequence only if the resulting shuffle is 'legal'.
3340 if (TLI.isShuffleMaskLegal(Mask1, VT))
3341 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3342 N1->getOperand(0), &Mask1[0]);
3343 if (TLI.isShuffleMaskLegal(Mask2, VT))
3344 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3345 N0->getOperand(0), &Mask2[0]);
3350 // fold (or x, undef) -> -1
3351 if (!LegalOperations &&
3352 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3353 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3354 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3356 // fold (or c1, c2) -> c1|c2
3358 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3359 // canonicalize constant to RHS
3361 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3362 // fold (or x, 0) -> x
3363 if (N1C && N1C->isNullValue())
3365 // fold (or x, -1) -> -1
3366 if (N1C && N1C->isAllOnesValue())
3368 // fold (or x, c) -> c iff (x & ~c) == 0
3369 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3372 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3373 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3374 if (BSwap.getNode())
3376 BSwap = MatchBSwapHWordLow(N, N0, N1);
3377 if (BSwap.getNode())
3381 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3384 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3385 // iff (c1 & c2) == 0.
3386 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3387 isa<ConstantSDNode>(N0.getOperand(1))) {
3388 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3389 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3390 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3393 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3394 DAG.getNode(ISD::OR, SDLoc(N0), VT,
3395 N0.getOperand(0), N1), COR);
3398 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3399 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3400 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3401 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3403 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3404 LL.getValueType().isInteger()) {
3405 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3406 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3407 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3408 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3409 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3410 LR.getValueType(), LL, RL);
3411 AddToWorklist(ORNode.getNode());
3412 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3414 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3415 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3416 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3417 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3418 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3419 LR.getValueType(), LL, RL);
3420 AddToWorklist(ANDNode.getNode());
3421 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3424 // canonicalize equivalent to ll == rl
3425 if (LL == RR && LR == RL) {
3426 Op1 = ISD::getSetCCSwappedOperands(Op1);
3429 if (LL == RL && LR == RR) {
3430 bool isInteger = LL.getValueType().isInteger();
3431 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3432 if (Result != ISD::SETCC_INVALID &&
3433 (!LegalOperations ||
3434 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3435 TLI.isOperationLegal(ISD::SETCC,
3436 getSetCCResultType(N0.getValueType())))))
3437 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3442 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3443 if (N0.getOpcode() == N1.getOpcode()) {
3444 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3445 if (Tmp.getNode()) return Tmp;
3448 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3449 if (N0.getOpcode() == ISD::AND &&
3450 N1.getOpcode() == ISD::AND &&
3451 N0.getOperand(1).getOpcode() == ISD::Constant &&
3452 N1.getOperand(1).getOpcode() == ISD::Constant &&
3453 // Don't increase # computations.
3454 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3455 // We can only do this xform if we know that bits from X that are set in C2
3456 // but not in C1 are already zero. Likewise for Y.
3457 const APInt &LHSMask =
3458 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3459 const APInt &RHSMask =
3460 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3462 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3463 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3464 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3465 N0.getOperand(0), N1.getOperand(0));
3466 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3467 DAG.getConstant(LHSMask | RHSMask, VT));
3471 // See if this is some rotate idiom.
3472 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3473 return SDValue(Rot, 0);
3475 // Simplify the operands using demanded-bits information.
3476 if (!VT.isVector() &&
3477 SimplifyDemandedBits(SDValue(N, 0)))
3478 return SDValue(N, 0);
3483 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3484 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3485 if (Op.getOpcode() == ISD::AND) {
3486 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3487 Mask = Op.getOperand(1);
3488 Op = Op.getOperand(0);
3494 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3502 // Return true if we can prove that, whenever Neg and Pos are both in the
3503 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3504 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3506 // (or (shift1 X, Neg), (shift2 X, Pos))
3508 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3509 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3510 // to consider shift amounts with defined behavior.
3511 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3512 // If OpSize is a power of 2 then:
3514 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3515 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3517 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3518 // for the stronger condition:
3520 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3522 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3523 // we can just replace Neg with Neg' for the rest of the function.
3525 // In other cases we check for the even stronger condition:
3527 // Neg == OpSize - Pos [B]
3529 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3530 // behavior if Pos == 0 (and consequently Neg == OpSize).
3532 // We could actually use [A] whenever OpSize is a power of 2, but the
3533 // only extra cases that it would match are those uninteresting ones
3534 // where Neg and Pos are never in range at the same time. E.g. for
3535 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3536 // as well as (sub 32, Pos), but:
3538 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3540 // always invokes undefined behavior for 32-bit X.
3542 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3543 unsigned MaskLoBits = 0;
3544 if (Neg.getOpcode() == ISD::AND &&
3545 isPowerOf2_64(OpSize) &&
3546 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3547 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3548 Neg = Neg.getOperand(0);
3549 MaskLoBits = Log2_64(OpSize);
3552 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3553 if (Neg.getOpcode() != ISD::SUB)
3555 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3558 SDValue NegOp1 = Neg.getOperand(1);
3560 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3561 // Pos'. The truncation is redundant for the purpose of the equality.
3563 Pos.getOpcode() == ISD::AND &&
3564 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3565 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3566 Pos = Pos.getOperand(0);
3568 // The condition we need is now:
3570 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3572 // If NegOp1 == Pos then we need:
3574 // OpSize & Mask == NegC & Mask
3576 // (because "x & Mask" is a truncation and distributes through subtraction).
3579 Width = NegC->getAPIntValue();
3580 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3581 // Then the condition we want to prove becomes:
3583 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3585 // which, again because "x & Mask" is a truncation, becomes:
3587 // NegC & Mask == (OpSize - PosC) & Mask
3588 // OpSize & Mask == (NegC + PosC) & Mask
3589 else if (Pos.getOpcode() == ISD::ADD &&
3590 Pos.getOperand(0) == NegOp1 &&
3591 Pos.getOperand(1).getOpcode() == ISD::Constant)
3592 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3593 NegC->getAPIntValue());
3597 // Now we just need to check that OpSize & Mask == Width & Mask.
3599 // Opsize & Mask is 0 since Mask is Opsize - 1.
3600 return Width.getLoBits(MaskLoBits) == 0;
3601 return Width == OpSize;
3604 // A subroutine of MatchRotate used once we have found an OR of two opposite
3605 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3606 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3607 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3608 // Neg with outer conversions stripped away.
3609 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3610 SDValue Neg, SDValue InnerPos,
3611 SDValue InnerNeg, unsigned PosOpcode,
3612 unsigned NegOpcode, SDLoc DL) {
3613 // fold (or (shl x, (*ext y)),
3614 // (srl x, (*ext (sub 32, y)))) ->
3615 // (rotl x, y) or (rotr x, (sub 32, y))
3617 // fold (or (shl x, (*ext (sub 32, y))),
3618 // (srl x, (*ext y))) ->
3619 // (rotr x, y) or (rotl x, (sub 32, y))
3620 EVT VT = Shifted.getValueType();
3621 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3622 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3623 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3624 HasPos ? Pos : Neg).getNode();
3630 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3631 // idioms for rotate, and if the target supports rotation instructions, generate
3633 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3634 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3635 EVT VT = LHS.getValueType();
3636 if (!TLI.isTypeLegal(VT)) return nullptr;
3638 // The target must have at least one rotate flavor.
3639 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3640 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3641 if (!HasROTL && !HasROTR) return nullptr;
3643 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3644 SDValue LHSShift; // The shift.
3645 SDValue LHSMask; // AND value if any.
3646 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3647 return nullptr; // Not part of a rotate.
3649 SDValue RHSShift; // The shift.
3650 SDValue RHSMask; // AND value if any.
3651 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3652 return nullptr; // Not part of a rotate.
3654 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3655 return nullptr; // Not shifting the same value.
3657 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3658 return nullptr; // Shifts must disagree.
3660 // Canonicalize shl to left side in a shl/srl pair.
3661 if (RHSShift.getOpcode() == ISD::SHL) {
3662 std::swap(LHS, RHS);
3663 std::swap(LHSShift, RHSShift);
3664 std::swap(LHSMask , RHSMask );
3667 unsigned OpSizeInBits = VT.getSizeInBits();
3668 SDValue LHSShiftArg = LHSShift.getOperand(0);
3669 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3670 SDValue RHSShiftArg = RHSShift.getOperand(0);
3671 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3673 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3674 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3675 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3676 RHSShiftAmt.getOpcode() == ISD::Constant) {
3677 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3678 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3679 if ((LShVal + RShVal) != OpSizeInBits)
3682 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3683 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3685 // If there is an AND of either shifted operand, apply it to the result.
3686 if (LHSMask.getNode() || RHSMask.getNode()) {
3687 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3689 if (LHSMask.getNode()) {
3690 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3691 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3693 if (RHSMask.getNode()) {
3694 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3695 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3698 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3701 return Rot.getNode();
3704 // If there is a mask here, and we have a variable shift, we can't be sure
3705 // that we're masking out the right stuff.
3706 if (LHSMask.getNode() || RHSMask.getNode())
3709 // If the shift amount is sign/zext/any-extended just peel it off.
3710 SDValue LExtOp0 = LHSShiftAmt;
3711 SDValue RExtOp0 = RHSShiftAmt;
3712 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3713 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3714 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3715 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3716 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3717 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3718 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3719 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3720 LExtOp0 = LHSShiftAmt.getOperand(0);
3721 RExtOp0 = RHSShiftAmt.getOperand(0);
3724 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3725 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3729 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3730 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3737 SDValue DAGCombiner::visitXOR(SDNode *N) {
3738 SDValue N0 = N->getOperand(0);
3739 SDValue N1 = N->getOperand(1);
3740 SDValue LHS, RHS, CC;
3741 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3742 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3743 EVT VT = N0.getValueType();
3746 if (VT.isVector()) {
3747 SDValue FoldedVOp = SimplifyVBinOp(N);
3748 if (FoldedVOp.getNode()) return FoldedVOp;
3750 // fold (xor x, 0) -> x, vector edition
3751 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3753 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3757 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3758 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3759 return DAG.getConstant(0, VT);
3760 // fold (xor x, undef) -> undef
3761 if (N0.getOpcode() == ISD::UNDEF)
3763 if (N1.getOpcode() == ISD::UNDEF)
3765 // fold (xor c1, c2) -> c1^c2
3767 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3768 // canonicalize constant to RHS
3770 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3771 // fold (xor x, 0) -> x
3772 if (N1C && N1C->isNullValue())
3775 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3779 // fold !(x cc y) -> (x !cc y)
3780 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3781 bool isInt = LHS.getValueType().isInteger();
3782 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3785 if (!LegalOperations ||
3786 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3787 switch (N0.getOpcode()) {
3789 llvm_unreachable("Unhandled SetCC Equivalent!");
3791 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3792 case ISD::SELECT_CC:
3793 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3794 N0.getOperand(3), NotCC);
3799 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3800 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3801 N0.getNode()->hasOneUse() &&
3802 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3803 SDValue V = N0.getOperand(0);
3804 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3805 DAG.getConstant(1, V.getValueType()));
3806 AddToWorklist(V.getNode());
3807 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3810 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3811 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3812 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3813 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3814 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3815 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3816 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3817 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3818 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3819 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3822 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3823 if (N1C && N1C->isAllOnesValue() &&
3824 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3825 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3826 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3827 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3828 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3829 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3830 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3831 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3834 // fold (xor (and x, y), y) -> (and (not x), y)
3835 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3836 N0->getOperand(1) == N1) {
3837 SDValue X = N0->getOperand(0);
3838 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3839 AddToWorklist(NotX.getNode());
3840 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3842 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3843 if (N1C && N0.getOpcode() == ISD::XOR) {
3844 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3845 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3847 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3848 DAG.getConstant(N1C->getAPIntValue() ^
3849 N00C->getAPIntValue(), VT));
3851 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3852 DAG.getConstant(N1C->getAPIntValue() ^
3853 N01C->getAPIntValue(), VT));
3855 // fold (xor x, x) -> 0
3857 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3859 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3860 if (N0.getOpcode() == N1.getOpcode()) {
3861 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3862 if (Tmp.getNode()) return Tmp;
3865 // Simplify the expression using non-local knowledge.
3866 if (!VT.isVector() &&
3867 SimplifyDemandedBits(SDValue(N, 0)))
3868 return SDValue(N, 0);
3873 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3874 /// the shift amount is a constant.
3875 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3876 // We can't and shouldn't fold opaque constants.
3877 if (Amt->isOpaque())
3880 SDNode *LHS = N->getOperand(0).getNode();
3881 if (!LHS->hasOneUse()) return SDValue();
3883 // We want to pull some binops through shifts, so that we have (and (shift))
3884 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3885 // thing happens with address calculations, so it's important to canonicalize
3887 bool HighBitSet = false; // Can we transform this if the high bit is set?
3889 switch (LHS->getOpcode()) {
3890 default: return SDValue();
3893 HighBitSet = false; // We can only transform sra if the high bit is clear.
3896 HighBitSet = true; // We can only transform sra if the high bit is set.
3899 if (N->getOpcode() != ISD::SHL)
3900 return SDValue(); // only shl(add) not sr[al](add).
3901 HighBitSet = false; // We can only transform sra if the high bit is clear.
3905 // We require the RHS of the binop to be a constant and not opaque as well.
3906 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3907 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3909 // FIXME: disable this unless the input to the binop is a shift by a constant.
3910 // If it is not a shift, it pessimizes some common cases like:
3912 // void foo(int *X, int i) { X[i & 1235] = 1; }
3913 // int bar(int *X, int i) { return X[i & 255]; }
3914 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3915 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3916 BinOpLHSVal->getOpcode() != ISD::SRA &&
3917 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3918 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3921 EVT VT = N->getValueType(0);
3923 // If this is a signed shift right, and the high bit is modified by the
3924 // logical operation, do not perform the transformation. The highBitSet
3925 // boolean indicates the value of the high bit of the constant which would
3926 // cause it to be modified for this operation.
3927 if (N->getOpcode() == ISD::SRA) {
3928 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3929 if (BinOpRHSSignSet != HighBitSet)
3933 if (!TLI.isDesirableToCommuteWithShift(LHS))
3936 // Fold the constants, shifting the binop RHS by the shift amount.
3937 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3939 LHS->getOperand(1), N->getOperand(1));
3940 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3942 // Create the new shift.
3943 SDValue NewShift = DAG.getNode(N->getOpcode(),
3944 SDLoc(LHS->getOperand(0)),
3945 VT, LHS->getOperand(0), N->getOperand(1));
3947 // Create the new binop.
3948 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3951 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3952 assert(N->getOpcode() == ISD::TRUNCATE);
3953 assert(N->getOperand(0).getOpcode() == ISD::AND);
3955 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3956 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3957 SDValue N01 = N->getOperand(0).getOperand(1);
3959 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3960 EVT TruncVT = N->getValueType(0);
3961 SDValue N00 = N->getOperand(0).getOperand(0);
3962 APInt TruncC = N01C->getAPIntValue();
3963 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3965 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3966 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3967 DAG.getConstant(TruncC, TruncVT));
3974 SDValue DAGCombiner::visitRotate(SDNode *N) {
3975 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3976 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3977 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3978 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3979 if (NewOp1.getNode())
3980 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3981 N->getOperand(0), NewOp1);
3986 SDValue DAGCombiner::visitSHL(SDNode *N) {
3987 SDValue N0 = N->getOperand(0);
3988 SDValue N1 = N->getOperand(1);
3989 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3990 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3991 EVT VT = N0.getValueType();
3992 unsigned OpSizeInBits = VT.getScalarSizeInBits();
3995 if (VT.isVector()) {
3996 SDValue FoldedVOp = SimplifyVBinOp(N);
3997 if (FoldedVOp.getNode()) return FoldedVOp;
3999 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4000 // If setcc produces all-one true value then:
4001 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4002 if (N1CV && N1CV->isConstant()) {
4003 if (N0.getOpcode() == ISD::AND) {
4004 SDValue N00 = N0->getOperand(0);
4005 SDValue N01 = N0->getOperand(1);
4006 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4008 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4009 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4010 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4011 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4013 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4016 N1C = isConstOrConstSplat(N1);
4021 // fold (shl c1, c2) -> c1<<c2
4023 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4024 // fold (shl 0, x) -> 0
4025 if (N0C && N0C->isNullValue())
4027 // fold (shl x, c >= size(x)) -> undef
4028 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4029 return DAG.getUNDEF(VT);
4030 // fold (shl x, 0) -> x
4031 if (N1C && N1C->isNullValue())
4033 // fold (shl undef, x) -> 0
4034 if (N0.getOpcode() == ISD::UNDEF)
4035 return DAG.getConstant(0, VT);
4036 // if (shl x, c) is known to be zero, return 0
4037 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4038 APInt::getAllOnesValue(OpSizeInBits)))
4039 return DAG.getConstant(0, VT);
4040 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4041 if (N1.getOpcode() == ISD::TRUNCATE &&
4042 N1.getOperand(0).getOpcode() == ISD::AND) {
4043 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4044 if (NewOp1.getNode())
4045 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4048 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4049 return SDValue(N, 0);
4051 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4052 if (N1C && N0.getOpcode() == ISD::SHL) {
4053 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4054 uint64_t c1 = N0C1->getZExtValue();
4055 uint64_t c2 = N1C->getZExtValue();
4056 if (c1 + c2 >= OpSizeInBits)
4057 return DAG.getConstant(0, VT);
4058 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4059 DAG.getConstant(c1 + c2, N1.getValueType()));
4063 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4064 // For this to be valid, the second form must not preserve any of the bits
4065 // that are shifted out by the inner shift in the first form. This means
4066 // the outer shift size must be >= the number of bits added by the ext.
4067 // As a corollary, we don't care what kind of ext it is.
4068 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4069 N0.getOpcode() == ISD::ANY_EXTEND ||
4070 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4071 N0.getOperand(0).getOpcode() == ISD::SHL) {
4072 SDValue N0Op0 = N0.getOperand(0);
4073 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4074 uint64_t c1 = N0Op0C1->getZExtValue();
4075 uint64_t c2 = N1C->getZExtValue();
4076 EVT InnerShiftVT = N0Op0.getValueType();
4077 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4078 if (c2 >= OpSizeInBits - InnerShiftSize) {
4079 if (c1 + c2 >= OpSizeInBits)
4080 return DAG.getConstant(0, VT);
4081 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4082 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4083 N0Op0->getOperand(0)),
4084 DAG.getConstant(c1 + c2, N1.getValueType()));
4089 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4090 // Only fold this if the inner zext has no other uses to avoid increasing
4091 // the total number of instructions.
4092 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4093 N0.getOperand(0).getOpcode() == ISD::SRL) {
4094 SDValue N0Op0 = N0.getOperand(0);
4095 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4096 uint64_t c1 = N0Op0C1->getZExtValue();
4097 if (c1 < VT.getScalarSizeInBits()) {
4098 uint64_t c2 = N1C->getZExtValue();
4100 SDValue NewOp0 = N0.getOperand(0);
4101 EVT CountVT = NewOp0.getOperand(1).getValueType();
4102 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4103 NewOp0, DAG.getConstant(c2, CountVT));
4104 AddToWorklist(NewSHL.getNode());
4105 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4111 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4112 // (and (srl x, (sub c1, c2), MASK)
4113 // Only fold this if the inner shift has no other uses -- if it does, folding
4114 // this will increase the total number of instructions.
4115 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4116 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4117 uint64_t c1 = N0C1->getZExtValue();
4118 if (c1 < OpSizeInBits) {
4119 uint64_t c2 = N1C->getZExtValue();
4120 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4123 Mask = Mask.shl(c2 - c1);
4124 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4125 DAG.getConstant(c2 - c1, N1.getValueType()));
4127 Mask = Mask.lshr(c1 - c2);
4128 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4129 DAG.getConstant(c1 - c2, N1.getValueType()));
4131 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4132 DAG.getConstant(Mask, VT));
4136 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4137 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4138 unsigned BitSize = VT.getScalarSizeInBits();
4139 SDValue HiBitsMask =
4140 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4141 BitSize - N1C->getZExtValue()), VT);
4142 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4147 SDValue NewSHL = visitShiftByConstant(N, N1C);
4148 if (NewSHL.getNode())
4155 SDValue DAGCombiner::visitSRA(SDNode *N) {
4156 SDValue N0 = N->getOperand(0);
4157 SDValue N1 = N->getOperand(1);
4158 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4159 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4160 EVT VT = N0.getValueType();
4161 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4164 if (VT.isVector()) {
4165 SDValue FoldedVOp = SimplifyVBinOp(N);
4166 if (FoldedVOp.getNode()) return FoldedVOp;
4168 N1C = isConstOrConstSplat(N1);
4171 // fold (sra c1, c2) -> (sra c1, c2)
4173 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4174 // fold (sra 0, x) -> 0
4175 if (N0C && N0C->isNullValue())
4177 // fold (sra -1, x) -> -1
4178 if (N0C && N0C->isAllOnesValue())
4180 // fold (sra x, (setge c, size(x))) -> undef
4181 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4182 return DAG.getUNDEF(VT);
4183 // fold (sra x, 0) -> x
4184 if (N1C && N1C->isNullValue())
4186 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4188 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4189 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4190 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4192 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4193 ExtVT, VT.getVectorNumElements());
4194 if ((!LegalOperations ||
4195 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4196 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4197 N0.getOperand(0), DAG.getValueType(ExtVT));
4200 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4201 if (N1C && N0.getOpcode() == ISD::SRA) {
4202 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4203 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4204 if (Sum >= OpSizeInBits)
4205 Sum = OpSizeInBits - 1;
4206 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4207 DAG.getConstant(Sum, N1.getValueType()));
4211 // fold (sra (shl X, m), (sub result_size, n))
4212 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4213 // result_size - n != m.
4214 // If truncate is free for the target sext(shl) is likely to result in better
4216 if (N0.getOpcode() == ISD::SHL && N1C) {
4217 // Get the two constanst of the shifts, CN0 = m, CN = n.
4218 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4220 LLVMContext &Ctx = *DAG.getContext();
4221 // Determine what the truncate's result bitsize and type would be.
4222 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4225 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4227 // Determine the residual right-shift amount.
4228 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4230 // If the shift is not a no-op (in which case this should be just a sign
4231 // extend already), the truncated to type is legal, sign_extend is legal
4232 // on that type, and the truncate to that type is both legal and free,
4233 // perform the transform.
4234 if ((ShiftAmt > 0) &&
4235 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4236 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4237 TLI.isTruncateFree(VT, TruncVT)) {
4239 SDValue Amt = DAG.getConstant(ShiftAmt,
4240 getShiftAmountTy(N0.getOperand(0).getValueType()));
4241 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4242 N0.getOperand(0), Amt);
4243 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4245 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4246 N->getValueType(0), Trunc);
4251 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4252 if (N1.getOpcode() == ISD::TRUNCATE &&
4253 N1.getOperand(0).getOpcode() == ISD::AND) {
4254 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4255 if (NewOp1.getNode())
4256 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4259 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4260 // if c1 is equal to the number of bits the trunc removes
4261 if (N0.getOpcode() == ISD::TRUNCATE &&
4262 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4263 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4264 N0.getOperand(0).hasOneUse() &&
4265 N0.getOperand(0).getOperand(1).hasOneUse() &&
4267 SDValue N0Op0 = N0.getOperand(0);
4268 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4269 unsigned LargeShiftVal = LargeShift->getZExtValue();
4270 EVT LargeVT = N0Op0.getValueType();
4272 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4274 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4275 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4276 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4277 N0Op0.getOperand(0), Amt);
4278 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4283 // Simplify, based on bits shifted out of the LHS.
4284 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4285 return SDValue(N, 0);
4288 // If the sign bit is known to be zero, switch this to a SRL.
4289 if (DAG.SignBitIsZero(N0))
4290 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4293 SDValue NewSRA = visitShiftByConstant(N, N1C);
4294 if (NewSRA.getNode())
4301 SDValue DAGCombiner::visitSRL(SDNode *N) {
4302 SDValue N0 = N->getOperand(0);
4303 SDValue N1 = N->getOperand(1);
4304 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4305 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4306 EVT VT = N0.getValueType();
4307 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4310 if (VT.isVector()) {
4311 SDValue FoldedVOp = SimplifyVBinOp(N);
4312 if (FoldedVOp.getNode()) return FoldedVOp;
4314 N1C = isConstOrConstSplat(N1);
4317 // fold (srl c1, c2) -> c1 >>u c2
4319 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4320 // fold (srl 0, x) -> 0
4321 if (N0C && N0C->isNullValue())
4323 // fold (srl x, c >= size(x)) -> undef
4324 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4325 return DAG.getUNDEF(VT);
4326 // fold (srl x, 0) -> x
4327 if (N1C && N1C->isNullValue())
4329 // if (srl x, c) is known to be zero, return 0
4330 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4331 APInt::getAllOnesValue(OpSizeInBits)))
4332 return DAG.getConstant(0, VT);
4334 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4335 if (N1C && N0.getOpcode() == ISD::SRL) {
4336 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4337 uint64_t c1 = N01C->getZExtValue();
4338 uint64_t c2 = N1C->getZExtValue();
4339 if (c1 + c2 >= OpSizeInBits)
4340 return DAG.getConstant(0, VT);
4341 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4342 DAG.getConstant(c1 + c2, N1.getValueType()));
4346 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4347 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4348 N0.getOperand(0).getOpcode() == ISD::SRL &&
4349 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4351 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4352 uint64_t c2 = N1C->getZExtValue();
4353 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4354 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4355 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4356 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4357 if (c1 + OpSizeInBits == InnerShiftSize) {
4358 if (c1 + c2 >= InnerShiftSize)
4359 return DAG.getConstant(0, VT);
4360 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4361 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4362 N0.getOperand(0)->getOperand(0),
4363 DAG.getConstant(c1 + c2, ShiftCountVT)));
4367 // fold (srl (shl x, c), c) -> (and x, cst2)
4368 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4369 unsigned BitSize = N0.getScalarValueSizeInBits();
4370 if (BitSize <= 64) {
4371 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4372 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4373 DAG.getConstant(~0ULL >> ShAmt, VT));
4377 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4378 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4379 // Shifting in all undef bits?
4380 EVT SmallVT = N0.getOperand(0).getValueType();
4381 unsigned BitSize = SmallVT.getScalarSizeInBits();
4382 if (N1C->getZExtValue() >= BitSize)
4383 return DAG.getUNDEF(VT);
4385 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4386 uint64_t ShiftAmt = N1C->getZExtValue();
4387 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4389 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4390 AddToWorklist(SmallShift.getNode());
4391 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4392 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4393 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4394 DAG.getConstant(Mask, VT));
4398 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4399 // bit, which is unmodified by sra.
4400 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4401 if (N0.getOpcode() == ISD::SRA)
4402 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4405 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4406 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4407 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4408 APInt KnownZero, KnownOne;
4409 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4411 // If any of the input bits are KnownOne, then the input couldn't be all
4412 // zeros, thus the result of the srl will always be zero.
4413 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4415 // If all of the bits input the to ctlz node are known to be zero, then
4416 // the result of the ctlz is "32" and the result of the shift is one.
4417 APInt UnknownBits = ~KnownZero;
4418 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4420 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4421 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4422 // Okay, we know that only that the single bit specified by UnknownBits
4423 // could be set on input to the CTLZ node. If this bit is set, the SRL
4424 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4425 // to an SRL/XOR pair, which is likely to simplify more.
4426 unsigned ShAmt = UnknownBits.countTrailingZeros();
4427 SDValue Op = N0.getOperand(0);
4430 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4431 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4432 AddToWorklist(Op.getNode());
4435 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4436 Op, DAG.getConstant(1, VT));
4440 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4441 if (N1.getOpcode() == ISD::TRUNCATE &&
4442 N1.getOperand(0).getOpcode() == ISD::AND) {
4443 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4444 if (NewOp1.getNode())
4445 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4448 // fold operands of srl based on knowledge that the low bits are not
4450 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4451 return SDValue(N, 0);
4454 SDValue NewSRL = visitShiftByConstant(N, N1C);
4455 if (NewSRL.getNode())
4459 // Attempt to convert a srl of a load into a narrower zero-extending load.
4460 SDValue NarrowLoad = ReduceLoadWidth(N);
4461 if (NarrowLoad.getNode())
4464 // Here is a common situation. We want to optimize:
4467 // %b = and i32 %a, 2
4468 // %c = srl i32 %b, 1
4469 // brcond i32 %c ...
4475 // %c = setcc eq %b, 0
4478 // However when after the source operand of SRL is optimized into AND, the SRL
4479 // itself may not be optimized further. Look for it and add the BRCOND into
4481 if (N->hasOneUse()) {
4482 SDNode *Use = *N->use_begin();
4483 if (Use->getOpcode() == ISD::BRCOND)
4485 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4486 // Also look pass the truncate.
4487 Use = *Use->use_begin();
4488 if (Use->getOpcode() == ISD::BRCOND)
4496 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4497 SDValue N0 = N->getOperand(0);
4498 EVT VT = N->getValueType(0);
4500 // fold (ctlz c1) -> c2
4501 if (isa<ConstantSDNode>(N0))
4502 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4506 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4507 SDValue N0 = N->getOperand(0);
4508 EVT VT = N->getValueType(0);
4510 // fold (ctlz_zero_undef c1) -> c2
4511 if (isa<ConstantSDNode>(N0))
4512 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4516 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4517 SDValue N0 = N->getOperand(0);
4518 EVT VT = N->getValueType(0);
4520 // fold (cttz c1) -> c2
4521 if (isa<ConstantSDNode>(N0))
4522 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4526 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4527 SDValue N0 = N->getOperand(0);
4528 EVT VT = N->getValueType(0);
4530 // fold (cttz_zero_undef c1) -> c2
4531 if (isa<ConstantSDNode>(N0))
4532 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4536 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4537 SDValue N0 = N->getOperand(0);
4538 EVT VT = N->getValueType(0);
4540 // fold (ctpop c1) -> c2
4541 if (isa<ConstantSDNode>(N0))
4542 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4546 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4547 SDValue N0 = N->getOperand(0);
4548 SDValue N1 = N->getOperand(1);
4549 SDValue N2 = N->getOperand(2);
4550 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4551 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4552 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4553 EVT VT = N->getValueType(0);
4554 EVT VT0 = N0.getValueType();
4556 // fold (select C, X, X) -> X
4559 // fold (select true, X, Y) -> X
4560 if (N0C && !N0C->isNullValue())
4562 // fold (select false, X, Y) -> Y
4563 if (N0C && N0C->isNullValue())
4565 // fold (select C, 1, X) -> (or C, X)
4566 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4567 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4568 // fold (select C, 0, 1) -> (xor C, 1)
4569 // We can't do this reliably if integer based booleans have different contents
4570 // to floating point based booleans. This is because we can't tell whether we
4571 // have an integer-based boolean or a floating-point-based boolean unless we
4572 // can find the SETCC that produced it and inspect its operands. This is
4573 // fairly easy if C is the SETCC node, but it can potentially be
4574 // undiscoverable (or not reasonably discoverable). For example, it could be
4575 // in another basic block or it could require searching a complicated
4577 if (VT.isInteger() &&
4578 (VT0 == MVT::i1 || (VT0.isInteger() &&
4579 TLI.getBooleanContents(false, false) ==
4580 TLI.getBooleanContents(false, true) &&
4581 TLI.getBooleanContents(false, false) ==
4582 TargetLowering::ZeroOrOneBooleanContent)) &&
4583 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4586 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4587 N0, DAG.getConstant(1, VT0));
4588 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4589 N0, DAG.getConstant(1, VT0));
4590 AddToWorklist(XORNode.getNode());
4592 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4593 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4595 // fold (select C, 0, X) -> (and (not C), X)
4596 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4597 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4598 AddToWorklist(NOTNode.getNode());
4599 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4601 // fold (select C, X, 1) -> (or (not C), X)
4602 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4603 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4604 AddToWorklist(NOTNode.getNode());
4605 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4607 // fold (select C, X, 0) -> (and C, X)
4608 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4609 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4610 // fold (select X, X, Y) -> (or X, Y)
4611 // fold (select X, 1, Y) -> (or X, Y)
4612 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4613 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4614 // fold (select X, Y, X) -> (and X, Y)
4615 // fold (select X, Y, 0) -> (and X, Y)
4616 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4617 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4619 // If we can fold this based on the true/false value, do so.
4620 if (SimplifySelectOps(N, N1, N2))
4621 return SDValue(N, 0); // Don't revisit N.
4623 // fold selects based on a setcc into other things, such as min/max/abs
4624 if (N0.getOpcode() == ISD::SETCC) {
4625 if ((!LegalOperations &&
4626 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4627 TLI.isOperationLegal(ISD::SELECT_CC, VT))
4628 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4629 N0.getOperand(0), N0.getOperand(1),
4630 N1, N2, N0.getOperand(2));
4631 return SimplifySelect(SDLoc(N), N0, N1, N2);
4638 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4641 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4643 // Split the inputs.
4644 SDValue Lo, Hi, LL, LH, RL, RH;
4645 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4646 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4648 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4649 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4651 return std::make_pair(Lo, Hi);
4654 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4655 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4656 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4658 SDValue Cond = N->getOperand(0);
4659 SDValue LHS = N->getOperand(1);
4660 SDValue RHS = N->getOperand(2);
4661 MVT VT = N->getSimpleValueType(0);
4662 int NumElems = VT.getVectorNumElements();
4663 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4664 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4665 Cond.getOpcode() == ISD::BUILD_VECTOR);
4667 // We're sure we have an even number of elements due to the
4668 // concat_vectors we have as arguments to vselect.
4669 // Skip BV elements until we find one that's not an UNDEF
4670 // After we find an UNDEF element, keep looping until we get to half the
4671 // length of the BV and see if all the non-undef nodes are the same.
4672 ConstantSDNode *BottomHalf = nullptr;
4673 for (int i = 0; i < NumElems / 2; ++i) {
4674 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4677 if (BottomHalf == nullptr)
4678 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4679 else if (Cond->getOperand(i).getNode() != BottomHalf)
4683 // Do the same for the second half of the BuildVector
4684 ConstantSDNode *TopHalf = nullptr;
4685 for (int i = NumElems / 2; i < NumElems; ++i) {
4686 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4689 if (TopHalf == nullptr)
4690 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4691 else if (Cond->getOperand(i).getNode() != TopHalf)
4695 assert(TopHalf && BottomHalf &&
4696 "One half of the selector was all UNDEFs and the other was all the "
4697 "same value. This should have been addressed before this function.");
4699 ISD::CONCAT_VECTORS, dl, VT,
4700 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4701 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4704 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4705 SDValue N0 = N->getOperand(0);
4706 SDValue N1 = N->getOperand(1);
4707 SDValue N2 = N->getOperand(2);
4710 // Canonicalize integer abs.
4711 // vselect (setg[te] X, 0), X, -X ->
4712 // vselect (setgt X, -1), X, -X ->
4713 // vselect (setl[te] X, 0), -X, X ->
4714 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4715 if (N0.getOpcode() == ISD::SETCC) {
4716 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4717 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4719 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4721 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4722 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4723 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4724 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4725 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4726 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4727 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4730 EVT VT = LHS.getValueType();
4731 SDValue Shift = DAG.getNode(
4732 ISD::SRA, DL, VT, LHS,
4733 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4734 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4735 AddToWorklist(Shift.getNode());
4736 AddToWorklist(Add.getNode());
4737 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4741 // If the VSELECT result requires splitting and the mask is provided by a
4742 // SETCC, then split both nodes and its operands before legalization. This
4743 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4744 // and enables future optimizations (e.g. min/max pattern matching on X86).
4745 if (N0.getOpcode() == ISD::SETCC) {
4746 EVT VT = N->getValueType(0);
4748 // Check if any splitting is required.
4749 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4750 TargetLowering::TypeSplitVector)
4753 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4754 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4755 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4756 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4758 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4759 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4761 // Add the new VSELECT nodes to the work list in case they need to be split
4763 AddToWorklist(Lo.getNode());
4764 AddToWorklist(Hi.getNode());
4766 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4769 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4770 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4772 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4773 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4776 // The ConvertSelectToConcatVector function is assuming both the above
4777 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4779 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4780 N2.getOpcode() == ISD::CONCAT_VECTORS &&
4781 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4782 SDValue CV = ConvertSelectToConcatVector(N, DAG);
4790 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4791 SDValue N0 = N->getOperand(0);
4792 SDValue N1 = N->getOperand(1);
4793 SDValue N2 = N->getOperand(2);
4794 SDValue N3 = N->getOperand(3);
4795 SDValue N4 = N->getOperand(4);
4796 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4798 // fold select_cc lhs, rhs, x, x, cc -> x
4802 // Determine if the condition we're dealing with is constant
4803 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4804 N0, N1, CC, SDLoc(N), false);
4805 if (SCC.getNode()) {
4806 AddToWorklist(SCC.getNode());
4808 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4809 if (!SCCC->isNullValue())
4810 return N2; // cond always true -> true val
4812 return N3; // cond always false -> false val
4815 // Fold to a simpler select_cc
4816 if (SCC.getOpcode() == ISD::SETCC)
4817 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4818 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4822 // If we can fold this based on the true/false value, do so.
4823 if (SimplifySelectOps(N, N2, N3))
4824 return SDValue(N, 0); // Don't revisit N.
4826 // fold select_cc into other things, such as min/max/abs
4827 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4830 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4831 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4832 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4836 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4837 // dag node into a ConstantSDNode or a build_vector of constants.
4838 // This function is called by the DAGCombiner when visiting sext/zext/aext
4839 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4840 // Vector extends are not folded if operations are legal; this is to
4841 // avoid introducing illegal build_vector dag nodes.
4842 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4843 SelectionDAG &DAG, bool LegalTypes,
4844 bool LegalOperations) {
4845 unsigned Opcode = N->getOpcode();
4846 SDValue N0 = N->getOperand(0);
4847 EVT VT = N->getValueType(0);
4849 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4850 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4852 // fold (sext c1) -> c1
4853 // fold (zext c1) -> c1
4854 // fold (aext c1) -> c1
4855 if (isa<ConstantSDNode>(N0))
4856 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4858 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4859 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4860 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4861 EVT SVT = VT.getScalarType();
4862 if (!(VT.isVector() &&
4863 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4864 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4867 // We can fold this node into a build_vector.
4868 unsigned VTBits = SVT.getSizeInBits();
4869 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4870 unsigned ShAmt = VTBits - EVTBits;
4871 SmallVector<SDValue, 8> Elts;
4872 unsigned NumElts = N0->getNumOperands();
4875 for (unsigned i=0; i != NumElts; ++i) {
4876 SDValue Op = N0->getOperand(i);
4877 if (Op->getOpcode() == ISD::UNDEF) {
4878 Elts.push_back(DAG.getUNDEF(SVT));
4882 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4883 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4884 if (Opcode == ISD::SIGN_EXTEND)
4885 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4888 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4892 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4895 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4896 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4897 // transformation. Returns true if extension are possible and the above
4898 // mentioned transformation is profitable.
4899 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4901 SmallVectorImpl<SDNode *> &ExtendNodes,
4902 const TargetLowering &TLI) {
4903 bool HasCopyToRegUses = false;
4904 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4905 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4906 UE = N0.getNode()->use_end();
4911 if (UI.getUse().getResNo() != N0.getResNo())
4913 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4914 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4915 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4916 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4917 // Sign bits will be lost after a zext.
4920 for (unsigned i = 0; i != 2; ++i) {
4921 SDValue UseOp = User->getOperand(i);
4924 if (!isa<ConstantSDNode>(UseOp))
4929 ExtendNodes.push_back(User);
4932 // If truncates aren't free and there are users we can't
4933 // extend, it isn't worthwhile.
4936 // Remember if this value is live-out.
4937 if (User->getOpcode() == ISD::CopyToReg)
4938 HasCopyToRegUses = true;
4941 if (HasCopyToRegUses) {
4942 bool BothLiveOut = false;
4943 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4945 SDUse &Use = UI.getUse();
4946 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4952 // Both unextended and extended values are live out. There had better be
4953 // a good reason for the transformation.
4954 return ExtendNodes.size();
4959 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4960 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4961 ISD::NodeType ExtType) {
4962 // Extend SetCC uses if necessary.
4963 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4964 SDNode *SetCC = SetCCs[i];
4965 SmallVector<SDValue, 4> Ops;
4967 for (unsigned j = 0; j != 2; ++j) {
4968 SDValue SOp = SetCC->getOperand(j);
4970 Ops.push_back(ExtLoad);
4972 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4975 Ops.push_back(SetCC->getOperand(2));
4976 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
4980 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4981 SDValue N0 = N->getOperand(0);
4982 EVT VT = N->getValueType(0);
4984 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4986 return SDValue(Res, 0);
4988 // fold (sext (sext x)) -> (sext x)
4989 // fold (sext (aext x)) -> (sext x)
4990 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4991 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4994 if (N0.getOpcode() == ISD::TRUNCATE) {
4995 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4996 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4997 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4998 if (NarrowLoad.getNode()) {
4999 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5000 if (NarrowLoad.getNode() != N0.getNode()) {
5001 CombineTo(N0.getNode(), NarrowLoad);
5002 // CombineTo deleted the truncate, if needed, but not what's under it.
5005 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5008 // See if the value being truncated is already sign extended. If so, just
5009 // eliminate the trunc/sext pair.
5010 SDValue Op = N0.getOperand(0);
5011 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5012 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5013 unsigned DestBits = VT.getScalarType().getSizeInBits();
5014 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5016 if (OpBits == DestBits) {
5017 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5018 // bits, it is already ready.
5019 if (NumSignBits > DestBits-MidBits)
5021 } else if (OpBits < DestBits) {
5022 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5023 // bits, just sext from i32.
5024 if (NumSignBits > OpBits-MidBits)
5025 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5027 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5028 // bits, just truncate to i32.
5029 if (NumSignBits > OpBits-MidBits)
5030 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5033 // fold (sext (truncate x)) -> (sextinreg x).
5034 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5035 N0.getValueType())) {
5036 if (OpBits < DestBits)
5037 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5038 else if (OpBits > DestBits)
5039 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5040 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5041 DAG.getValueType(N0.getValueType()));
5045 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5046 // None of the supported targets knows how to perform load and sign extend
5047 // on vectors in one instruction. We only perform this transformation on
5049 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5050 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5051 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5052 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5053 bool DoXform = true;
5054 SmallVector<SDNode*, 4> SetCCs;
5055 if (!N0.hasOneUse())
5056 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5058 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5059 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5061 LN0->getBasePtr(), N0.getValueType(),
5062 LN0->getMemOperand());
5063 CombineTo(N, ExtLoad);
5064 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5065 N0.getValueType(), ExtLoad);
5066 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5067 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5069 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5073 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5074 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5075 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5076 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5077 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5078 EVT MemVT = LN0->getMemoryVT();
5079 if ((!LegalOperations && !LN0->isVolatile()) ||
5080 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5081 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5083 LN0->getBasePtr(), MemVT,
5084 LN0->getMemOperand());
5085 CombineTo(N, ExtLoad);
5086 CombineTo(N0.getNode(),
5087 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5088 N0.getValueType(), ExtLoad),
5089 ExtLoad.getValue(1));
5090 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5094 // fold (sext (and/or/xor (load x), cst)) ->
5095 // (and/or/xor (sextload x), (sext cst))
5096 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5097 N0.getOpcode() == ISD::XOR) &&
5098 isa<LoadSDNode>(N0.getOperand(0)) &&
5099 N0.getOperand(1).getOpcode() == ISD::Constant &&
5100 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5101 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5102 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5103 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5104 bool DoXform = true;
5105 SmallVector<SDNode*, 4> SetCCs;
5106 if (!N0.hasOneUse())
5107 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5110 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5111 LN0->getChain(), LN0->getBasePtr(),
5113 LN0->getMemOperand());
5114 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5115 Mask = Mask.sext(VT.getSizeInBits());
5116 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5117 ExtLoad, DAG.getConstant(Mask, VT));
5118 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5119 SDLoc(N0.getOperand(0)),
5120 N0.getOperand(0).getValueType(), ExtLoad);
5122 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5123 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5125 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5130 if (N0.getOpcode() == ISD::SETCC) {
5131 EVT N0VT = N0.getOperand(0).getValueType();
5132 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5133 // Only do this before legalize for now.
5134 if (VT.isVector() && !LegalOperations &&
5135 TLI.getBooleanContents(N0VT) ==
5136 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5137 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5138 // of the same size as the compared operands. Only optimize sext(setcc())
5139 // if this is the case.
5140 EVT SVT = getSetCCResultType(N0VT);
5142 // We know that the # elements of the results is the same as the
5143 // # elements of the compare (and the # elements of the compare result
5144 // for that matter). Check to see that they are the same size. If so,
5145 // we know that the element size of the sext'd result matches the
5146 // element size of the compare operands.
5147 if (VT.getSizeInBits() == SVT.getSizeInBits())
5148 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5150 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5152 // If the desired elements are smaller or larger than the source
5153 // elements we can use a matching integer vector type and then
5154 // truncate/sign extend
5155 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5156 if (SVT == MatchingVectorType) {
5157 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5158 N0.getOperand(0), N0.getOperand(1),
5159 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5160 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5164 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5165 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5167 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5169 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5170 NegOne, DAG.getConstant(0, VT),
5171 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5172 if (SCC.getNode()) return SCC;
5174 if (!VT.isVector()) {
5175 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5176 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5178 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5179 SDValue SetCC = DAG.getSetCC(DL,
5181 N0.getOperand(0), N0.getOperand(1), CC);
5182 EVT SelectVT = getSetCCResultType(VT);
5183 return DAG.getSelect(DL, VT,
5184 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5185 NegOne, DAG.getConstant(0, VT));
5191 // fold (sext x) -> (zext x) if the sign bit is known zero.
5192 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5193 DAG.SignBitIsZero(N0))
5194 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5199 // isTruncateOf - If N is a truncate of some other value, return true, record
5200 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5201 // This function computes KnownZero to avoid a duplicated call to
5202 // computeKnownBits in the caller.
5203 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5206 if (N->getOpcode() == ISD::TRUNCATE) {
5207 Op = N->getOperand(0);
5208 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5212 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5213 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5216 SDValue Op0 = N->getOperand(0);
5217 SDValue Op1 = N->getOperand(1);
5218 assert(Op0.getValueType() == Op1.getValueType());
5220 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5221 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5222 if (COp0 && COp0->isNullValue())
5224 else if (COp1 && COp1->isNullValue())
5229 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5231 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5237 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5238 SDValue N0 = N->getOperand(0);
5239 EVT VT = N->getValueType(0);
5241 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5243 return SDValue(Res, 0);
5245 // fold (zext (zext x)) -> (zext x)
5246 // fold (zext (aext x)) -> (zext x)
5247 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5248 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5251 // fold (zext (truncate x)) -> (zext x) or
5252 // (zext (truncate x)) -> (truncate x)
5253 // This is valid when the truncated bits of x are already zero.
5254 // FIXME: We should extend this to work for vectors too.
5257 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5258 APInt TruncatedBits =
5259 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5260 APInt(Op.getValueSizeInBits(), 0) :
5261 APInt::getBitsSet(Op.getValueSizeInBits(),
5262 N0.getValueSizeInBits(),
5263 std::min(Op.getValueSizeInBits(),
5264 VT.getSizeInBits()));
5265 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5266 if (VT.bitsGT(Op.getValueType()))
5267 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5268 if (VT.bitsLT(Op.getValueType()))
5269 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5275 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5276 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5277 if (N0.getOpcode() == ISD::TRUNCATE) {
5278 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5279 if (NarrowLoad.getNode()) {
5280 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5281 if (NarrowLoad.getNode() != N0.getNode()) {
5282 CombineTo(N0.getNode(), NarrowLoad);
5283 // CombineTo deleted the truncate, if needed, but not what's under it.
5286 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5290 // fold (zext (truncate x)) -> (and x, mask)
5291 if (N0.getOpcode() == ISD::TRUNCATE &&
5292 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5294 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5295 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5296 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5297 if (NarrowLoad.getNode()) {
5298 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5299 if (NarrowLoad.getNode() != N0.getNode()) {
5300 CombineTo(N0.getNode(), NarrowLoad);
5301 // CombineTo deleted the truncate, if needed, but not what's under it.
5304 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5307 SDValue Op = N0.getOperand(0);
5308 if (Op.getValueType().bitsLT(VT)) {
5309 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5310 AddToWorklist(Op.getNode());
5311 } else if (Op.getValueType().bitsGT(VT)) {
5312 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5313 AddToWorklist(Op.getNode());
5315 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5316 N0.getValueType().getScalarType());
5319 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5320 // if either of the casts is not free.
5321 if (N0.getOpcode() == ISD::AND &&
5322 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5323 N0.getOperand(1).getOpcode() == ISD::Constant &&
5324 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5325 N0.getValueType()) ||
5326 !TLI.isZExtFree(N0.getValueType(), VT))) {
5327 SDValue X = N0.getOperand(0).getOperand(0);
5328 if (X.getValueType().bitsLT(VT)) {
5329 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5330 } else if (X.getValueType().bitsGT(VT)) {
5331 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5333 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5334 Mask = Mask.zext(VT.getSizeInBits());
5335 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5336 X, DAG.getConstant(Mask, VT));
5339 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5340 // None of the supported targets knows how to perform load and vector_zext
5341 // on vectors in one instruction. We only perform this transformation on
5343 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5344 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5345 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5346 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5347 bool DoXform = true;
5348 SmallVector<SDNode*, 4> SetCCs;
5349 if (!N0.hasOneUse())
5350 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5352 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5353 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5355 LN0->getBasePtr(), N0.getValueType(),
5356 LN0->getMemOperand());
5357 CombineTo(N, ExtLoad);
5358 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5359 N0.getValueType(), ExtLoad);
5360 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5362 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5364 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5368 // fold (zext (and/or/xor (load x), cst)) ->
5369 // (and/or/xor (zextload x), (zext cst))
5370 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5371 N0.getOpcode() == ISD::XOR) &&
5372 isa<LoadSDNode>(N0.getOperand(0)) &&
5373 N0.getOperand(1).getOpcode() == ISD::Constant &&
5374 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5375 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5376 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5377 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5378 bool DoXform = true;
5379 SmallVector<SDNode*, 4> SetCCs;
5380 if (!N0.hasOneUse())
5381 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5384 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5385 LN0->getChain(), LN0->getBasePtr(),
5387 LN0->getMemOperand());
5388 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5389 Mask = Mask.zext(VT.getSizeInBits());
5390 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5391 ExtLoad, DAG.getConstant(Mask, VT));
5392 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5393 SDLoc(N0.getOperand(0)),
5394 N0.getOperand(0).getValueType(), ExtLoad);
5396 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5397 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5399 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5404 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5405 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5406 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5407 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5408 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5409 EVT MemVT = LN0->getMemoryVT();
5410 if ((!LegalOperations && !LN0->isVolatile()) ||
5411 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5412 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5414 LN0->getBasePtr(), MemVT,
5415 LN0->getMemOperand());
5416 CombineTo(N, ExtLoad);
5417 CombineTo(N0.getNode(),
5418 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5420 ExtLoad.getValue(1));
5421 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5425 if (N0.getOpcode() == ISD::SETCC) {
5426 if (!LegalOperations && VT.isVector() &&
5427 N0.getValueType().getVectorElementType() == MVT::i1) {
5428 EVT N0VT = N0.getOperand(0).getValueType();
5429 if (getSetCCResultType(N0VT) == N0.getValueType())
5432 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5433 // Only do this before legalize for now.
5434 EVT EltVT = VT.getVectorElementType();
5435 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5436 DAG.getConstant(1, EltVT));
5437 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5438 // We know that the # elements of the results is the same as the
5439 // # elements of the compare (and the # elements of the compare result
5440 // for that matter). Check to see that they are the same size. If so,
5441 // we know that the element size of the sext'd result matches the
5442 // element size of the compare operands.
5443 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5444 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5446 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5447 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5450 // If the desired elements are smaller or larger than the source
5451 // elements we can use a matching integer vector type and then
5452 // truncate/sign extend
5453 EVT MatchingElementType =
5454 EVT::getIntegerVT(*DAG.getContext(),
5455 N0VT.getScalarType().getSizeInBits());
5456 EVT MatchingVectorType =
5457 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5458 N0VT.getVectorNumElements());
5460 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5462 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5463 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5464 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5465 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5468 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5470 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5471 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5472 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5473 if (SCC.getNode()) return SCC;
5476 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5477 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5478 isa<ConstantSDNode>(N0.getOperand(1)) &&
5479 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5481 SDValue ShAmt = N0.getOperand(1);
5482 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5483 if (N0.getOpcode() == ISD::SHL) {
5484 SDValue InnerZExt = N0.getOperand(0);
5485 // If the original shl may be shifting out bits, do not perform this
5487 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5488 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5489 if (ShAmtVal > KnownZeroBits)
5495 // Ensure that the shift amount is wide enough for the shifted value.
5496 if (VT.getSizeInBits() >= 256)
5497 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5499 return DAG.getNode(N0.getOpcode(), DL, VT,
5500 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5507 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5508 SDValue N0 = N->getOperand(0);
5509 EVT VT = N->getValueType(0);
5511 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5513 return SDValue(Res, 0);
5515 // fold (aext (aext x)) -> (aext x)
5516 // fold (aext (zext x)) -> (zext x)
5517 // fold (aext (sext x)) -> (sext x)
5518 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5519 N0.getOpcode() == ISD::ZERO_EXTEND ||
5520 N0.getOpcode() == ISD::SIGN_EXTEND)
5521 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5523 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5524 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5525 if (N0.getOpcode() == ISD::TRUNCATE) {
5526 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5527 if (NarrowLoad.getNode()) {
5528 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5529 if (NarrowLoad.getNode() != N0.getNode()) {
5530 CombineTo(N0.getNode(), NarrowLoad);
5531 // CombineTo deleted the truncate, if needed, but not what's under it.
5534 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5538 // fold (aext (truncate x))
5539 if (N0.getOpcode() == ISD::TRUNCATE) {
5540 SDValue TruncOp = N0.getOperand(0);
5541 if (TruncOp.getValueType() == VT)
5542 return TruncOp; // x iff x size == zext size.
5543 if (TruncOp.getValueType().bitsGT(VT))
5544 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5545 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5548 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5549 // if the trunc is not free.
5550 if (N0.getOpcode() == ISD::AND &&
5551 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5552 N0.getOperand(1).getOpcode() == ISD::Constant &&
5553 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5554 N0.getValueType())) {
5555 SDValue X = N0.getOperand(0).getOperand(0);
5556 if (X.getValueType().bitsLT(VT)) {
5557 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5558 } else if (X.getValueType().bitsGT(VT)) {
5559 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5561 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5562 Mask = Mask.zext(VT.getSizeInBits());
5563 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5564 X, DAG.getConstant(Mask, VT));
5567 // fold (aext (load x)) -> (aext (truncate (extload x)))
5568 // None of the supported targets knows how to perform load and any_ext
5569 // on vectors in one instruction. We only perform this transformation on
5571 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5572 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5573 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
5574 bool DoXform = true;
5575 SmallVector<SDNode*, 4> SetCCs;
5576 if (!N0.hasOneUse())
5577 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5579 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5580 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5582 LN0->getBasePtr(), N0.getValueType(),
5583 LN0->getMemOperand());
5584 CombineTo(N, ExtLoad);
5585 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5586 N0.getValueType(), ExtLoad);
5587 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5588 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5590 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5594 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5595 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5596 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5597 if (N0.getOpcode() == ISD::LOAD &&
5598 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5600 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5601 ISD::LoadExtType ExtType = LN0->getExtensionType();
5602 EVT MemVT = LN0->getMemoryVT();
5603 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5604 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5605 VT, LN0->getChain(), LN0->getBasePtr(),
5606 MemVT, LN0->getMemOperand());
5607 CombineTo(N, ExtLoad);
5608 CombineTo(N0.getNode(),
5609 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5610 N0.getValueType(), ExtLoad),
5611 ExtLoad.getValue(1));
5612 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5616 if (N0.getOpcode() == ISD::SETCC) {
5618 // aext(setcc) -> vsetcc
5619 // aext(setcc) -> truncate(vsetcc)
5620 // aext(setcc) -> aext(vsetcc)
5621 // Only do this before legalize for now.
5622 if (VT.isVector() && !LegalOperations) {
5623 EVT N0VT = N0.getOperand(0).getValueType();
5624 // We know that the # elements of the results is the same as the
5625 // # elements of the compare (and the # elements of the compare result
5626 // for that matter). Check to see that they are the same size. If so,
5627 // we know that the element size of the sext'd result matches the
5628 // element size of the compare operands.
5629 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5630 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5632 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5633 // If the desired elements are smaller or larger than the source
5634 // elements we can use a matching integer vector type and then
5635 // truncate/any extend
5637 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5639 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5641 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5642 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5646 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5648 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5649 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5650 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5658 /// GetDemandedBits - See if the specified operand can be simplified with the
5659 /// knowledge that only the bits specified by Mask are used. If so, return the
5660 /// simpler operand, otherwise return a null SDValue.
5661 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5662 switch (V.getOpcode()) {
5664 case ISD::Constant: {
5665 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5666 assert(CV && "Const value should be ConstSDNode.");
5667 const APInt &CVal = CV->getAPIntValue();
5668 APInt NewVal = CVal & Mask;
5670 return DAG.getConstant(NewVal, V.getValueType());
5675 // If the LHS or RHS don't contribute bits to the or, drop them.
5676 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5677 return V.getOperand(1);
5678 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5679 return V.getOperand(0);
5682 // Only look at single-use SRLs.
5683 if (!V.getNode()->hasOneUse())
5685 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5686 // See if we can recursively simplify the LHS.
5687 unsigned Amt = RHSC->getZExtValue();
5689 // Watch out for shift count overflow though.
5690 if (Amt >= Mask.getBitWidth()) break;
5691 APInt NewMask = Mask << Amt;
5692 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5693 if (SimplifyLHS.getNode())
5694 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5695 SimplifyLHS, V.getOperand(1));
5701 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5702 /// bits and then truncated to a narrower type and where N is a multiple
5703 /// of number of bits of the narrower type, transform it to a narrower load
5704 /// from address + N / num of bits of new type. If the result is to be
5705 /// extended, also fold the extension to form a extending load.
5706 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5707 unsigned Opc = N->getOpcode();
5709 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5710 SDValue N0 = N->getOperand(0);
5711 EVT VT = N->getValueType(0);
5714 // This transformation isn't valid for vector loads.
5718 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5720 if (Opc == ISD::SIGN_EXTEND_INREG) {
5721 ExtType = ISD::SEXTLOAD;
5722 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5723 } else if (Opc == ISD::SRL) {
5724 // Another special-case: SRL is basically zero-extending a narrower value.
5725 ExtType = ISD::ZEXTLOAD;
5727 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5728 if (!N01) return SDValue();
5729 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5730 VT.getSizeInBits() - N01->getZExtValue());
5732 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5735 unsigned EVTBits = ExtVT.getSizeInBits();
5737 // Do not generate loads of non-round integer types since these can
5738 // be expensive (and would be wrong if the type is not byte sized).
5739 if (!ExtVT.isRound())
5743 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5744 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5745 ShAmt = N01->getZExtValue();
5746 // Is the shift amount a multiple of size of VT?
5747 if ((ShAmt & (EVTBits-1)) == 0) {
5748 N0 = N0.getOperand(0);
5749 // Is the load width a multiple of size of VT?
5750 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5754 // At this point, we must have a load or else we can't do the transform.
5755 if (!isa<LoadSDNode>(N0)) return SDValue();
5757 // Because a SRL must be assumed to *need* to zero-extend the high bits
5758 // (as opposed to anyext the high bits), we can't combine the zextload
5759 // lowering of SRL and an sextload.
5760 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5763 // If the shift amount is larger than the input type then we're not
5764 // accessing any of the loaded bytes. If the load was a zextload/extload
5765 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5766 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5771 // If the load is shifted left (and the result isn't shifted back right),
5772 // we can fold the truncate through the shift.
5773 unsigned ShLeftAmt = 0;
5774 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5775 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5776 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5777 ShLeftAmt = N01->getZExtValue();
5778 N0 = N0.getOperand(0);
5782 // If we haven't found a load, we can't narrow it. Don't transform one with
5783 // multiple uses, this would require adding a new load.
5784 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5787 // Don't change the width of a volatile load.
5788 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5789 if (LN0->isVolatile())
5792 // Verify that we are actually reducing a load width here.
5793 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5796 // For the transform to be legal, the load must produce only two values
5797 // (the value loaded and the chain). Don't transform a pre-increment
5798 // load, for example, which produces an extra value. Otherwise the
5799 // transformation is not equivalent, and the downstream logic to replace
5800 // uses gets things wrong.
5801 if (LN0->getNumValues() > 2)
5804 // If the load that we're shrinking is an extload and we're not just
5805 // discarding the extension we can't simply shrink the load. Bail.
5806 // TODO: It would be possible to merge the extensions in some cases.
5807 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5808 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5811 EVT PtrType = N0.getOperand(1).getValueType();
5813 if (PtrType == MVT::Untyped || PtrType.isExtended())
5814 // It's not possible to generate a constant of extended or untyped type.
5817 // For big endian targets, we need to adjust the offset to the pointer to
5818 // load the correct bytes.
5819 if (TLI.isBigEndian()) {
5820 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5821 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5822 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5825 uint64_t PtrOff = ShAmt / 8;
5826 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5827 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5828 PtrType, LN0->getBasePtr(),
5829 DAG.getConstant(PtrOff, PtrType));
5830 AddToWorklist(NewPtr.getNode());
5833 if (ExtType == ISD::NON_EXTLOAD)
5834 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5835 LN0->getPointerInfo().getWithOffset(PtrOff),
5836 LN0->isVolatile(), LN0->isNonTemporal(),
5837 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5839 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5840 LN0->getPointerInfo().getWithOffset(PtrOff),
5841 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5842 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5844 // Replace the old load's chain with the new load's chain.
5845 WorklistRemover DeadNodes(*this);
5846 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5848 // Shift the result left, if we've swallowed a left shift.
5849 SDValue Result = Load;
5850 if (ShLeftAmt != 0) {
5851 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5852 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5854 // If the shift amount is as large as the result size (but, presumably,
5855 // no larger than the source) then the useful bits of the result are
5856 // zero; we can't simply return the shortened shift, because the result
5857 // of that operation is undefined.
5858 if (ShLeftAmt >= VT.getSizeInBits())
5859 Result = DAG.getConstant(0, VT);
5861 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5862 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5865 // Return the new loaded value.
5869 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5870 SDValue N0 = N->getOperand(0);
5871 SDValue N1 = N->getOperand(1);
5872 EVT VT = N->getValueType(0);
5873 EVT EVT = cast<VTSDNode>(N1)->getVT();
5874 unsigned VTBits = VT.getScalarType().getSizeInBits();
5875 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5877 // fold (sext_in_reg c1) -> c1
5878 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5879 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5881 // If the input is already sign extended, just drop the extension.
5882 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5885 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5886 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5887 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5888 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5889 N0.getOperand(0), N1);
5891 // fold (sext_in_reg (sext x)) -> (sext x)
5892 // fold (sext_in_reg (aext x)) -> (sext x)
5893 // if x is small enough.
5894 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5895 SDValue N00 = N0.getOperand(0);
5896 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5897 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5898 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5901 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5902 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5903 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5905 // fold operands of sext_in_reg based on knowledge that the top bits are not
5907 if (SimplifyDemandedBits(SDValue(N, 0)))
5908 return SDValue(N, 0);
5910 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5911 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5912 SDValue NarrowLoad = ReduceLoadWidth(N);
5913 if (NarrowLoad.getNode())
5916 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5917 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5918 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5919 if (N0.getOpcode() == ISD::SRL) {
5920 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5921 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5922 // We can turn this into an SRA iff the input to the SRL is already sign
5924 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5925 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5926 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5927 N0.getOperand(0), N0.getOperand(1));
5931 // fold (sext_inreg (extload x)) -> (sextload x)
5932 if (ISD::isEXTLoad(N0.getNode()) &&
5933 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5934 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5935 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5936 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5937 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5938 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5940 LN0->getBasePtr(), EVT,
5941 LN0->getMemOperand());
5942 CombineTo(N, ExtLoad);
5943 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5944 AddToWorklist(ExtLoad.getNode());
5945 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5947 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5948 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5950 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5951 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5952 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5953 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5954 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5956 LN0->getBasePtr(), EVT,
5957 LN0->getMemOperand());
5958 CombineTo(N, ExtLoad);
5959 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5960 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5963 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5964 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5965 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5966 N0.getOperand(1), false);
5967 if (BSwap.getNode())
5968 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5972 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5973 // into a build_vector.
5974 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5975 SmallVector<SDValue, 8> Elts;
5976 unsigned NumElts = N0->getNumOperands();
5977 unsigned ShAmt = VTBits - EVTBits;
5979 for (unsigned i = 0; i != NumElts; ++i) {
5980 SDValue Op = N0->getOperand(i);
5981 if (Op->getOpcode() == ISD::UNDEF) {
5986 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5987 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5988 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5989 Op.getValueType()));
5992 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
5998 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5999 SDValue N0 = N->getOperand(0);
6000 EVT VT = N->getValueType(0);
6001 bool isLE = TLI.isLittleEndian();
6004 if (N0.getValueType() == N->getValueType(0))
6006 // fold (truncate c1) -> c1
6007 if (isa<ConstantSDNode>(N0))
6008 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6009 // fold (truncate (truncate x)) -> (truncate x)
6010 if (N0.getOpcode() == ISD::TRUNCATE)
6011 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6012 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6013 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6014 N0.getOpcode() == ISD::SIGN_EXTEND ||
6015 N0.getOpcode() == ISD::ANY_EXTEND) {
6016 if (N0.getOperand(0).getValueType().bitsLT(VT))
6017 // if the source is smaller than the dest, we still need an extend
6018 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6020 if (N0.getOperand(0).getValueType().bitsGT(VT))
6021 // if the source is larger than the dest, than we just need the truncate
6022 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6023 // if the source and dest are the same type, we can drop both the extend
6024 // and the truncate.
6025 return N0.getOperand(0);
6028 // Fold extract-and-trunc into a narrow extract. For example:
6029 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6030 // i32 y = TRUNCATE(i64 x)
6032 // v16i8 b = BITCAST (v2i64 val)
6033 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6035 // Note: We only run this optimization after type legalization (which often
6036 // creates this pattern) and before operation legalization after which
6037 // we need to be more careful about the vector instructions that we generate.
6038 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6039 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6041 EVT VecTy = N0.getOperand(0).getValueType();
6042 EVT ExTy = N0.getValueType();
6043 EVT TrTy = N->getValueType(0);
6045 unsigned NumElem = VecTy.getVectorNumElements();
6046 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6048 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6049 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6051 SDValue EltNo = N0->getOperand(1);
6052 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6053 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6054 EVT IndexTy = TLI.getVectorIdxTy();
6055 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6057 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6058 NVT, N0.getOperand(0));
6060 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6062 DAG.getConstant(Index, IndexTy));
6066 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6067 if (N0.getOpcode() == ISD::SELECT) {
6068 EVT SrcVT = N0.getValueType();
6069 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6070 TLI.isTruncateFree(SrcVT, VT)) {
6072 SDValue Cond = N0.getOperand(0);
6073 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6074 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6075 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6079 // Fold a series of buildvector, bitcast, and truncate if possible.
6081 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6082 // (2xi32 (buildvector x, y)).
6083 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6084 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6085 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6086 N0.getOperand(0).hasOneUse()) {
6088 SDValue BuildVect = N0.getOperand(0);
6089 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6090 EVT TruncVecEltTy = VT.getVectorElementType();
6092 // Check that the element types match.
6093 if (BuildVectEltTy == TruncVecEltTy) {
6094 // Now we only need to compute the offset of the truncated elements.
6095 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6096 unsigned TruncVecNumElts = VT.getVectorNumElements();
6097 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6099 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6100 "Invalid number of elements");
6102 SmallVector<SDValue, 8> Opnds;
6103 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6104 Opnds.push_back(BuildVect.getOperand(i));
6106 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6110 // See if we can simplify the input to this truncate through knowledge that
6111 // only the low bits are being used.
6112 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6113 // Currently we only perform this optimization on scalars because vectors
6114 // may have different active low bits.
6115 if (!VT.isVector()) {
6117 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6118 VT.getSizeInBits()));
6119 if (Shorter.getNode())
6120 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6122 // fold (truncate (load x)) -> (smaller load x)
6123 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6124 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6125 SDValue Reduced = ReduceLoadWidth(N);
6126 if (Reduced.getNode())
6128 // Handle the case where the load remains an extending load even
6129 // after truncation.
6130 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6131 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6132 if (!LN0->isVolatile() &&
6133 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6134 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6135 VT, LN0->getChain(), LN0->getBasePtr(),
6137 LN0->getMemOperand());
6138 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6143 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6144 // where ... are all 'undef'.
6145 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6146 SmallVector<EVT, 8> VTs;
6149 unsigned NumDefs = 0;
6151 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6152 SDValue X = N0.getOperand(i);
6153 if (X.getOpcode() != ISD::UNDEF) {
6158 // Stop if more than one members are non-undef.
6161 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6162 VT.getVectorElementType(),
6163 X.getValueType().getVectorNumElements()));
6167 return DAG.getUNDEF(VT);
6170 assert(V.getNode() && "The single defined operand is empty!");
6171 SmallVector<SDValue, 8> Opnds;
6172 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6174 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6177 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6178 AddToWorklist(NV.getNode());
6179 Opnds.push_back(NV);
6181 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6185 // Simplify the operands using demanded-bits information.
6186 if (!VT.isVector() &&
6187 SimplifyDemandedBits(SDValue(N, 0)))
6188 return SDValue(N, 0);
6193 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6194 SDValue Elt = N->getOperand(i);
6195 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6196 return Elt.getNode();
6197 return Elt.getOperand(Elt.getResNo()).getNode();
6200 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6201 /// if load locations are consecutive.
6202 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6203 assert(N->getOpcode() == ISD::BUILD_PAIR);
6205 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6206 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6207 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6208 LD1->getAddressSpace() != LD2->getAddressSpace())
6210 EVT LD1VT = LD1->getValueType(0);
6212 if (ISD::isNON_EXTLoad(LD2) &&
6214 // If both are volatile this would reduce the number of volatile loads.
6215 // If one is volatile it might be ok, but play conservative and bail out.
6216 !LD1->isVolatile() &&
6217 !LD2->isVolatile() &&
6218 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6219 unsigned Align = LD1->getAlignment();
6220 unsigned NewAlign = TLI.getDataLayout()->
6221 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6223 if (NewAlign <= Align &&
6224 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6225 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6226 LD1->getBasePtr(), LD1->getPointerInfo(),
6227 false, false, false, Align);
6233 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6234 SDValue N0 = N->getOperand(0);
6235 EVT VT = N->getValueType(0);
6237 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6238 // Only do this before legalize, since afterward the target may be depending
6239 // on the bitconvert.
6240 // First check to see if this is all constant.
6242 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6244 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6246 EVT DestEltVT = N->getValueType(0).getVectorElementType();
6247 assert(!DestEltVT.isVector() &&
6248 "Element type of vector ValueType must not be vector!");
6250 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6253 // If the input is a constant, let getNode fold it.
6254 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6255 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6256 if (Res.getNode() != N) {
6257 if (!LegalOperations ||
6258 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6261 // Folding it resulted in an illegal node, and it's too late to
6262 // do that. Clean up the old node and forego the transformation.
6263 // Ideally this won't happen very often, because instcombine
6264 // and the earlier dagcombine runs (where illegal nodes are
6265 // permitted) should have folded most of them already.
6266 deleteAndRecombine(Res.getNode());
6270 // (conv (conv x, t1), t2) -> (conv x, t2)
6271 if (N0.getOpcode() == ISD::BITCAST)
6272 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6275 // fold (conv (load x)) -> (load (conv*)x)
6276 // If the resultant load doesn't need a higher alignment than the original!
6277 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6278 // Do not change the width of a volatile load.
6279 !cast<LoadSDNode>(N0)->isVolatile() &&
6280 // Do not remove the cast if the types differ in endian layout.
6281 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6282 TLI.hasBigEndianPartOrdering(VT) &&
6283 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6284 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6285 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6286 unsigned Align = TLI.getDataLayout()->
6287 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6288 unsigned OrigAlign = LN0->getAlignment();
6290 if (Align <= OrigAlign) {
6291 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6292 LN0->getBasePtr(), LN0->getPointerInfo(),
6293 LN0->isVolatile(), LN0->isNonTemporal(),
6294 LN0->isInvariant(), OrigAlign,
6297 CombineTo(N0.getNode(),
6298 DAG.getNode(ISD::BITCAST, SDLoc(N0),
6299 N0.getValueType(), Load),
6305 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6306 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6307 // This often reduces constant pool loads.
6308 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6309 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6310 N0.getNode()->hasOneUse() && VT.isInteger() &&
6311 !VT.isVector() && !N0.getValueType().isVector()) {
6312 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6314 AddToWorklist(NewConv.getNode());
6316 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6317 if (N0.getOpcode() == ISD::FNEG)
6318 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6319 NewConv, DAG.getConstant(SignBit, VT));
6320 assert(N0.getOpcode() == ISD::FABS);
6321 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6322 NewConv, DAG.getConstant(~SignBit, VT));
6325 // fold (bitconvert (fcopysign cst, x)) ->
6326 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6327 // Note that we don't handle (copysign x, cst) because this can always be
6328 // folded to an fneg or fabs.
6329 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6330 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6331 VT.isInteger() && !VT.isVector()) {
6332 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6333 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6334 if (isTypeLegal(IntXVT)) {
6335 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6336 IntXVT, N0.getOperand(1));
6337 AddToWorklist(X.getNode());
6339 // If X has a different width than the result/lhs, sext it or truncate it.
6340 unsigned VTWidth = VT.getSizeInBits();
6341 if (OrigXWidth < VTWidth) {
6342 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6343 AddToWorklist(X.getNode());
6344 } else if (OrigXWidth > VTWidth) {
6345 // To get the sign bit in the right place, we have to shift it right
6346 // before truncating.
6347 X = DAG.getNode(ISD::SRL, SDLoc(X),
6348 X.getValueType(), X,
6349 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6350 AddToWorklist(X.getNode());
6351 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6352 AddToWorklist(X.getNode());
6355 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6356 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6357 X, DAG.getConstant(SignBit, VT));
6358 AddToWorklist(X.getNode());
6360 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6361 VT, N0.getOperand(0));
6362 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6363 Cst, DAG.getConstant(~SignBit, VT));
6364 AddToWorklist(Cst.getNode());
6366 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6370 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6371 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6372 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6373 if (CombineLD.getNode())
6380 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6381 EVT VT = N->getValueType(0);
6382 return CombineConsecutiveLoads(N, VT);
6385 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6386 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
6387 /// destination element value type.
6388 SDValue DAGCombiner::
6389 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6390 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6392 // If this is already the right type, we're done.
6393 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6395 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6396 unsigned DstBitSize = DstEltVT.getSizeInBits();
6398 // If this is a conversion of N elements of one type to N elements of another
6399 // type, convert each element. This handles FP<->INT cases.
6400 if (SrcBitSize == DstBitSize) {
6401 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6402 BV->getValueType(0).getVectorNumElements());
6404 // Due to the FP element handling below calling this routine recursively,
6405 // we can end up with a scalar-to-vector node here.
6406 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6407 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6408 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6409 DstEltVT, BV->getOperand(0)));
6411 SmallVector<SDValue, 8> Ops;
6412 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6413 SDValue Op = BV->getOperand(i);
6414 // If the vector element type is not legal, the BUILD_VECTOR operands
6415 // are promoted and implicitly truncated. Make that explicit here.
6416 if (Op.getValueType() != SrcEltVT)
6417 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6418 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6420 AddToWorklist(Ops.back().getNode());
6422 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6425 // Otherwise, we're growing or shrinking the elements. To avoid having to
6426 // handle annoying details of growing/shrinking FP values, we convert them to
6428 if (SrcEltVT.isFloatingPoint()) {
6429 // Convert the input float vector to a int vector where the elements are the
6431 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6432 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6433 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6437 // Now we know the input is an integer vector. If the output is a FP type,
6438 // convert to integer first, then to FP of the right size.
6439 if (DstEltVT.isFloatingPoint()) {
6440 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6441 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6442 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6444 // Next, convert to FP elements of the same size.
6445 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6448 // Okay, we know the src/dst types are both integers of differing types.
6449 // Handling growing first.
6450 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6451 if (SrcBitSize < DstBitSize) {
6452 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6454 SmallVector<SDValue, 8> Ops;
6455 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6456 i += NumInputsPerOutput) {
6457 bool isLE = TLI.isLittleEndian();
6458 APInt NewBits = APInt(DstBitSize, 0);
6459 bool EltIsUndef = true;
6460 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6461 // Shift the previously computed bits over.
6462 NewBits <<= SrcBitSize;
6463 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6464 if (Op.getOpcode() == ISD::UNDEF) continue;
6467 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6468 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6472 Ops.push_back(DAG.getUNDEF(DstEltVT));
6474 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6477 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6478 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6481 // Finally, this must be the case where we are shrinking elements: each input
6482 // turns into multiple outputs.
6483 bool isS2V = ISD::isScalarToVector(BV);
6484 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6485 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6486 NumOutputsPerInput*BV->getNumOperands());
6487 SmallVector<SDValue, 8> Ops;
6489 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6490 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6491 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6492 Ops.push_back(DAG.getUNDEF(DstEltVT));
6496 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6497 getAPIntValue().zextOrTrunc(SrcBitSize);
6499 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6500 APInt ThisVal = OpVal.trunc(DstBitSize);
6501 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6502 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6503 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6504 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6506 OpVal = OpVal.lshr(DstBitSize);
6509 // For big endian targets, swap the order of the pieces of each element.
6510 if (TLI.isBigEndian())
6511 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6514 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6517 SDValue DAGCombiner::visitFADD(SDNode *N) {
6518 SDValue N0 = N->getOperand(0);
6519 SDValue N1 = N->getOperand(1);
6520 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6521 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6522 EVT VT = N->getValueType(0);
6525 if (VT.isVector()) {
6526 SDValue FoldedVOp = SimplifyVBinOp(N);
6527 if (FoldedVOp.getNode()) return FoldedVOp;
6530 // fold (fadd c1, c2) -> c1 + c2
6532 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6533 // canonicalize constant to RHS
6534 if (N0CFP && !N1CFP)
6535 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6536 // fold (fadd A, 0) -> A
6537 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6538 N1CFP->getValueAPF().isZero())
6540 // fold (fadd A, (fneg B)) -> (fsub A, B)
6541 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6542 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6543 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6544 GetNegatedExpression(N1, DAG, LegalOperations));
6545 // fold (fadd (fneg A), B) -> (fsub B, A)
6546 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6547 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6548 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6549 GetNegatedExpression(N0, DAG, LegalOperations));
6551 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6552 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6553 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6554 isa<ConstantFPSDNode>(N0.getOperand(1)))
6555 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6556 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6557 N0.getOperand(1), N1));
6559 // No FP constant should be created after legalization as Instruction
6560 // Selection pass has hard time in dealing with FP constant.
6562 // We don't need test this condition for transformation like following, as
6563 // the DAG being transformed implies it is legal to take FP constant as
6566 // (fadd (fmul c, x), x) -> (fmul c+1, x)
6568 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6570 // If allow, fold (fadd (fneg x), x) -> 0.0
6571 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6572 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6573 return DAG.getConstantFP(0.0, VT);
6575 // If allow, fold (fadd x, (fneg x)) -> 0.0
6576 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6577 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6578 return DAG.getConstantFP(0.0, VT);
6580 // In unsafe math mode, we can fold chains of FADD's of the same value
6581 // into multiplications. This transform is not safe in general because
6582 // we are reducing the number of rounding steps.
6583 if (DAG.getTarget().Options.UnsafeFPMath &&
6584 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6586 if (N0.getOpcode() == ISD::FMUL) {
6587 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6588 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6590 // (fadd (fmul c, x), x) -> (fmul x, c+1)
6591 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
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 (fmul x, c), x) -> (fmul x, c+1)
6600 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
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,
6608 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6609 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6610 N1.getOperand(0) == N1.getOperand(1) &&
6611 N0.getOperand(1) == N1.getOperand(0)) {
6612 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6614 DAG.getConstantFP(2.0, VT));
6615 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6616 N0.getOperand(1), NewCFP);
6619 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6620 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6621 N1.getOperand(0) == N1.getOperand(1) &&
6622 N0.getOperand(0) == N1.getOperand(0)) {
6623 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6625 DAG.getConstantFP(2.0, VT));
6626 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6627 N0.getOperand(0), NewCFP);
6631 if (N1.getOpcode() == ISD::FMUL) {
6632 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6633 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6635 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6636 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6637 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6639 DAG.getConstantFP(1.0, VT));
6640 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6644 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6645 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6646 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6648 DAG.getConstantFP(1.0, VT));
6649 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6654 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6655 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6656 N0.getOperand(0) == N0.getOperand(1) &&
6657 N1.getOperand(1) == N0.getOperand(0)) {
6658 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6660 DAG.getConstantFP(2.0, VT));
6661 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6662 N1.getOperand(1), NewCFP);
6665 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6666 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6667 N0.getOperand(0) == N0.getOperand(1) &&
6668 N1.getOperand(0) == N0.getOperand(0)) {
6669 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6671 DAG.getConstantFP(2.0, VT));
6672 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6673 N1.getOperand(0), NewCFP);
6677 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6678 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6679 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6680 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6681 (N0.getOperand(0) == N1))
6682 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6683 N1, DAG.getConstantFP(3.0, VT));
6686 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6687 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6688 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6689 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6690 N1.getOperand(0) == N0)
6691 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6692 N0, DAG.getConstantFP(3.0, VT));
6695 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6696 if (AllowNewFpConst &&
6697 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6698 N0.getOperand(0) == N0.getOperand(1) &&
6699 N1.getOperand(0) == N1.getOperand(1) &&
6700 N0.getOperand(0) == N1.getOperand(0))
6701 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6703 DAG.getConstantFP(4.0, VT));
6706 // FADD -> FMA combines:
6707 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6708 DAG.getTarget().Options.UnsafeFPMath) &&
6709 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6710 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6712 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6713 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6714 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6715 N0.getOperand(0), N0.getOperand(1), N1);
6717 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6718 // Note: Commutes FADD operands.
6719 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6720 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6721 N1.getOperand(0), N1.getOperand(1), N0);
6727 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6728 SDValue N0 = N->getOperand(0);
6729 SDValue N1 = N->getOperand(1);
6730 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6731 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6732 EVT VT = N->getValueType(0);
6736 if (VT.isVector()) {
6737 SDValue FoldedVOp = SimplifyVBinOp(N);
6738 if (FoldedVOp.getNode()) return FoldedVOp;
6741 // fold (fsub c1, c2) -> c1-c2
6743 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6744 // fold (fsub A, 0) -> A
6745 if (DAG.getTarget().Options.UnsafeFPMath &&
6746 N1CFP && N1CFP->getValueAPF().isZero())
6748 // fold (fsub 0, B) -> -B
6749 if (DAG.getTarget().Options.UnsafeFPMath &&
6750 N0CFP && N0CFP->getValueAPF().isZero()) {
6751 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6752 return GetNegatedExpression(N1, DAG, LegalOperations);
6753 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6754 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6756 // fold (fsub A, (fneg B)) -> (fadd A, B)
6757 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6758 return DAG.getNode(ISD::FADD, dl, VT, N0,
6759 GetNegatedExpression(N1, DAG, LegalOperations));
6761 // If 'unsafe math' is enabled, fold
6762 // (fsub x, x) -> 0.0 &
6763 // (fsub x, (fadd x, y)) -> (fneg y) &
6764 // (fsub x, (fadd y, x)) -> (fneg y)
6765 if (DAG.getTarget().Options.UnsafeFPMath) {
6767 return DAG.getConstantFP(0.0f, VT);
6769 if (N1.getOpcode() == ISD::FADD) {
6770 SDValue N10 = N1->getOperand(0);
6771 SDValue N11 = N1->getOperand(1);
6773 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6774 &DAG.getTarget().Options))
6775 return GetNegatedExpression(N11, DAG, LegalOperations);
6777 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6778 &DAG.getTarget().Options))
6779 return GetNegatedExpression(N10, DAG, LegalOperations);
6783 // FSUB -> FMA combines:
6784 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6785 DAG.getTarget().Options.UnsafeFPMath) &&
6786 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6787 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6789 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6790 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6791 return DAG.getNode(ISD::FMA, dl, VT,
6792 N0.getOperand(0), N0.getOperand(1),
6793 DAG.getNode(ISD::FNEG, dl, VT, N1));
6795 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6796 // Note: Commutes FSUB operands.
6797 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6798 return DAG.getNode(ISD::FMA, dl, VT,
6799 DAG.getNode(ISD::FNEG, dl, VT,
6801 N1.getOperand(1), N0);
6803 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6804 if (N0.getOpcode() == ISD::FNEG &&
6805 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6806 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6807 SDValue N00 = N0.getOperand(0).getOperand(0);
6808 SDValue N01 = N0.getOperand(0).getOperand(1);
6809 return DAG.getNode(ISD::FMA, dl, VT,
6810 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6811 DAG.getNode(ISD::FNEG, dl, VT, N1));
6818 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6819 SDValue N0 = N->getOperand(0);
6820 SDValue N1 = N->getOperand(1);
6821 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6822 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6823 EVT VT = N->getValueType(0);
6824 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6827 if (VT.isVector()) {
6828 SDValue FoldedVOp = SimplifyVBinOp(N);
6829 if (FoldedVOp.getNode()) return FoldedVOp;
6832 // fold (fmul c1, c2) -> c1*c2
6834 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6835 // canonicalize constant to RHS
6836 if (N0CFP && !N1CFP)
6837 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6838 // fold (fmul A, 0) -> 0
6839 if (DAG.getTarget().Options.UnsafeFPMath &&
6840 N1CFP && N1CFP->getValueAPF().isZero())
6842 // fold (fmul A, 0) -> 0, vector edition.
6843 if (DAG.getTarget().Options.UnsafeFPMath &&
6844 ISD::isBuildVectorAllZeros(N1.getNode()))
6846 // fold (fmul A, 1.0) -> A
6847 if (N1CFP && N1CFP->isExactlyValue(1.0))
6849 // fold (fmul X, 2.0) -> (fadd X, X)
6850 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6851 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6852 // fold (fmul X, -1.0) -> (fneg X)
6853 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6854 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6855 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6857 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6858 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6859 &DAG.getTarget().Options)) {
6860 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6861 &DAG.getTarget().Options)) {
6862 // Both can be negated for free, check to see if at least one is cheaper
6864 if (LHSNeg == 2 || RHSNeg == 2)
6865 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6866 GetNegatedExpression(N0, DAG, LegalOperations),
6867 GetNegatedExpression(N1, DAG, LegalOperations));
6871 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6872 if (DAG.getTarget().Options.UnsafeFPMath &&
6873 N1CFP && N0.getOpcode() == ISD::FMUL &&
6874 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6875 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6876 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6877 N0.getOperand(1), N1));
6882 SDValue DAGCombiner::visitFMA(SDNode *N) {
6883 SDValue N0 = N->getOperand(0);
6884 SDValue N1 = N->getOperand(1);
6885 SDValue N2 = N->getOperand(2);
6886 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6887 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6888 EVT VT = N->getValueType(0);
6892 // Constant fold FMA.
6893 if (isa<ConstantFPSDNode>(N0) &&
6894 isa<ConstantFPSDNode>(N1) &&
6895 isa<ConstantFPSDNode>(N2)) {
6896 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
6899 if (DAG.getTarget().Options.UnsafeFPMath) {
6900 if (N0CFP && N0CFP->isZero())
6902 if (N1CFP && N1CFP->isZero())
6905 if (N0CFP && N0CFP->isExactlyValue(1.0))
6906 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6907 if (N1CFP && N1CFP->isExactlyValue(1.0))
6908 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6910 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6911 if (N0CFP && !N1CFP)
6912 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6914 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6915 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6916 N2.getOpcode() == ISD::FMUL &&
6917 N0 == N2.getOperand(0) &&
6918 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6919 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6920 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6924 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6925 if (DAG.getTarget().Options.UnsafeFPMath &&
6926 N0.getOpcode() == ISD::FMUL && N1CFP &&
6927 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6928 return DAG.getNode(ISD::FMA, dl, VT,
6930 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6934 // (fma x, 1, y) -> (fadd x, y)
6935 // (fma x, -1, y) -> (fadd (fneg x), y)
6937 if (N1CFP->isExactlyValue(1.0))
6938 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6940 if (N1CFP->isExactlyValue(-1.0) &&
6941 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6942 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6943 AddToWorklist(RHSNeg.getNode());
6944 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6948 // (fma x, c, x) -> (fmul x, (c+1))
6949 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6950 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6951 DAG.getNode(ISD::FADD, dl, VT,
6952 N1, DAG.getConstantFP(1.0, VT)));
6954 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6955 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6956 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6957 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6958 DAG.getNode(ISD::FADD, dl, VT,
6959 N1, DAG.getConstantFP(-1.0, VT)));
6965 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6966 SDValue N0 = N->getOperand(0);
6967 SDValue N1 = N->getOperand(1);
6968 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6969 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6970 EVT VT = N->getValueType(0);
6971 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6974 if (VT.isVector()) {
6975 SDValue FoldedVOp = SimplifyVBinOp(N);
6976 if (FoldedVOp.getNode()) return FoldedVOp;
6979 // fold (fdiv c1, c2) -> c1/c2
6981 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6983 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6984 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6985 // Compute the reciprocal 1.0 / c2.
6986 APFloat N1APF = N1CFP->getValueAPF();
6987 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6988 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6989 // Only do the transform if the reciprocal is a legal fp immediate that
6990 // isn't too nasty (eg NaN, denormal, ...).
6991 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6992 (!LegalOperations ||
6993 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6994 // backend)... we should handle this gracefully after Legalize.
6995 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6996 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6997 TLI.isFPImmLegal(Recip, VT)))
6998 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6999 DAG.getConstantFP(Recip, VT));
7002 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7003 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
7004 &DAG.getTarget().Options)) {
7005 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
7006 &DAG.getTarget().Options)) {
7007 // Both can be negated for free, check to see if at least one is cheaper
7009 if (LHSNeg == 2 || RHSNeg == 2)
7010 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7011 GetNegatedExpression(N0, DAG, LegalOperations),
7012 GetNegatedExpression(N1, DAG, LegalOperations));
7019 SDValue DAGCombiner::visitFREM(SDNode *N) {
7020 SDValue N0 = N->getOperand(0);
7021 SDValue N1 = N->getOperand(1);
7022 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7023 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7024 EVT VT = N->getValueType(0);
7026 // fold (frem c1, c2) -> fmod(c1,c2)
7028 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7033 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7034 SDValue N0 = N->getOperand(0);
7035 SDValue N1 = N->getOperand(1);
7036 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7037 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7038 EVT VT = N->getValueType(0);
7040 if (N0CFP && N1CFP) // Constant fold
7041 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7044 const APFloat& V = N1CFP->getValueAPF();
7045 // copysign(x, c1) -> fabs(x) iff ispos(c1)
7046 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7047 if (!V.isNegative()) {
7048 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7049 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7051 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7052 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7053 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7057 // copysign(fabs(x), y) -> copysign(x, y)
7058 // copysign(fneg(x), y) -> copysign(x, y)
7059 // copysign(copysign(x,z), y) -> copysign(x, y)
7060 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7061 N0.getOpcode() == ISD::FCOPYSIGN)
7062 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7063 N0.getOperand(0), N1);
7065 // copysign(x, abs(y)) -> abs(x)
7066 if (N1.getOpcode() == ISD::FABS)
7067 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7069 // copysign(x, copysign(y,z)) -> copysign(x, z)
7070 if (N1.getOpcode() == ISD::FCOPYSIGN)
7071 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7072 N0, N1.getOperand(1));
7074 // copysign(x, fp_extend(y)) -> copysign(x, y)
7075 // copysign(x, fp_round(y)) -> copysign(x, y)
7076 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7077 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7078 N0, N1.getOperand(0));
7083 SDValue DAGCombiner::visitSINT_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 (sint_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::SINT_TO_FP, SDLoc(N), VT, N0);
7096 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7097 // but UINT_TO_FP is legal on this target, try to convert.
7098 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7099 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7100 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7101 if (DAG.SignBitIsZero(N0))
7102 return DAG.getNode(ISD::UINT_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 (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7108 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
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);
7119 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7120 // (select_cc x, y, 1.0, 0.0,, cc)
7121 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7122 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7123 (!LegalOperations ||
7124 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7126 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7127 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7128 N0.getOperand(0).getOperand(2) };
7129 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7136 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7137 SDValue N0 = N->getOperand(0);
7138 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7139 EVT VT = N->getValueType(0);
7140 EVT OpVT = N0.getValueType();
7142 // fold (uint_to_fp c1) -> c1fp
7144 // ...but only if the target supports immediate floating-point values
7145 (!LegalOperations ||
7146 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7147 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7149 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7150 // but SINT_TO_FP is legal on this target, try to convert.
7151 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7152 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7153 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7154 if (DAG.SignBitIsZero(N0))
7155 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7158 // The next optimizations are desirable only if SELECT_CC can be lowered.
7159 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7160 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7162 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7163 (!LegalOperations ||
7164 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7166 { N0.getOperand(0), N0.getOperand(1),
7167 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7169 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7176 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7177 SDValue N0 = N->getOperand(0);
7178 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7179 EVT VT = N->getValueType(0);
7181 // fold (fp_to_sint c1fp) -> c1
7183 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7188 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7189 SDValue N0 = N->getOperand(0);
7190 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7191 EVT VT = N->getValueType(0);
7193 // fold (fp_to_uint c1fp) -> c1
7195 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7200 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7201 SDValue N0 = N->getOperand(0);
7202 SDValue N1 = N->getOperand(1);
7203 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7204 EVT VT = N->getValueType(0);
7206 // fold (fp_round c1fp) -> c1fp
7208 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7210 // fold (fp_round (fp_extend x)) -> x
7211 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7212 return N0.getOperand(0);
7214 // fold (fp_round (fp_round x)) -> (fp_round x)
7215 if (N0.getOpcode() == ISD::FP_ROUND) {
7216 // This is a value preserving truncation if both round's are.
7217 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7218 N0.getNode()->getConstantOperandVal(1) == 1;
7219 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7220 DAG.getIntPtrConstant(IsTrunc));
7223 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7224 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7225 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7226 N0.getOperand(0), N1);
7227 AddToWorklist(Tmp.getNode());
7228 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7229 Tmp, N0.getOperand(1));
7235 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7236 SDValue N0 = N->getOperand(0);
7237 EVT VT = N->getValueType(0);
7238 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7239 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7241 // fold (fp_round_inreg c1fp) -> c1fp
7242 if (N0CFP && isTypeLegal(EVT)) {
7243 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7244 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7250 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7251 SDValue N0 = N->getOperand(0);
7252 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7253 EVT VT = N->getValueType(0);
7255 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7256 if (N->hasOneUse() &&
7257 N->use_begin()->getOpcode() == ISD::FP_ROUND)
7260 // fold (fp_extend c1fp) -> c1fp
7262 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7264 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7266 if (N0.getOpcode() == ISD::FP_ROUND
7267 && N0.getNode()->getConstantOperandVal(1) == 1) {
7268 SDValue In = N0.getOperand(0);
7269 if (In.getValueType() == VT) return In;
7270 if (VT.bitsLT(In.getValueType()))
7271 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7272 In, N0.getOperand(1));
7273 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7276 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7277 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7278 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
7279 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7280 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7282 LN0->getBasePtr(), N0.getValueType(),
7283 LN0->getMemOperand());
7284 CombineTo(N, ExtLoad);
7285 CombineTo(N0.getNode(),
7286 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7287 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7288 ExtLoad.getValue(1));
7289 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7295 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7296 SDValue N0 = N->getOperand(0);
7297 EVT VT = N->getValueType(0);
7299 // Constant fold FNEG.
7300 if (isa<ConstantFPSDNode>(N0))
7301 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7303 if (VT.isVector()) {
7304 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7305 if (FoldedVOp.getNode()) return FoldedVOp;
7308 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7309 &DAG.getTarget().Options))
7310 return GetNegatedExpression(N0, DAG, LegalOperations);
7312 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7313 // constant pool values.
7314 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7316 N0.getNode()->hasOneUse() &&
7317 N0.getOperand(0).getValueType().isInteger()) {
7318 SDValue Int = N0.getOperand(0);
7319 EVT IntVT = Int.getValueType();
7320 if (IntVT.isInteger() && !IntVT.isVector()) {
7321 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7322 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7323 AddToWorklist(Int.getNode());
7324 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7329 // (fneg (fmul c, x)) -> (fmul -c, x)
7330 if (N0.getOpcode() == ISD::FMUL) {
7331 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7333 APFloat CVal = CFP1->getValueAPF();
7335 if (Level >= AfterLegalizeDAG &&
7336 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7337 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7339 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7340 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7347 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7348 SDValue N0 = N->getOperand(0);
7349 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7350 EVT VT = N->getValueType(0);
7352 // fold (fceil c1) -> fceil(c1)
7354 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7359 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7360 SDValue N0 = N->getOperand(0);
7361 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7362 EVT VT = N->getValueType(0);
7364 // fold (ftrunc c1) -> ftrunc(c1)
7366 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7371 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7372 SDValue N0 = N->getOperand(0);
7373 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7374 EVT VT = N->getValueType(0);
7376 // fold (ffloor c1) -> ffloor(c1)
7378 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7383 SDValue DAGCombiner::visitFABS(SDNode *N) {
7384 SDValue N0 = N->getOperand(0);
7385 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7386 EVT VT = N->getValueType(0);
7388 if (VT.isVector()) {
7389 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7390 if (FoldedVOp.getNode()) return FoldedVOp;
7393 // fold (fabs c1) -> fabs(c1)
7395 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7396 // fold (fabs (fabs x)) -> (fabs x)
7397 if (N0.getOpcode() == ISD::FABS)
7398 return N->getOperand(0);
7399 // fold (fabs (fneg x)) -> (fabs x)
7400 // fold (fabs (fcopysign x, y)) -> (fabs x)
7401 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7402 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7404 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7405 // constant pool values.
7406 if (!TLI.isFAbsFree(VT) &&
7407 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7408 N0.getOperand(0).getValueType().isInteger() &&
7409 !N0.getOperand(0).getValueType().isVector()) {
7410 SDValue Int = N0.getOperand(0);
7411 EVT IntVT = Int.getValueType();
7412 if (IntVT.isInteger() && !IntVT.isVector()) {
7413 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7414 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7415 AddToWorklist(Int.getNode());
7416 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7417 N->getValueType(0), Int);
7424 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7425 SDValue Chain = N->getOperand(0);
7426 SDValue N1 = N->getOperand(1);
7427 SDValue N2 = N->getOperand(2);
7429 // If N is a constant we could fold this into a fallthrough or unconditional
7430 // branch. However that doesn't happen very often in normal code, because
7431 // Instcombine/SimplifyCFG should have handled the available opportunities.
7432 // If we did this folding here, it would be necessary to update the
7433 // MachineBasicBlock CFG, which is awkward.
7435 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7437 if (N1.getOpcode() == ISD::SETCC &&
7438 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7439 N1.getOperand(0).getValueType())) {
7440 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7441 Chain, N1.getOperand(2),
7442 N1.getOperand(0), N1.getOperand(1), N2);
7445 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7446 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7447 (N1.getOperand(0).hasOneUse() &&
7448 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7449 SDNode *Trunc = nullptr;
7450 if (N1.getOpcode() == ISD::TRUNCATE) {
7451 // Look pass the truncate.
7452 Trunc = N1.getNode();
7453 N1 = N1.getOperand(0);
7456 // Match this pattern so that we can generate simpler code:
7459 // %b = and i32 %a, 2
7460 // %c = srl i32 %b, 1
7461 // brcond i32 %c ...
7466 // %b = and i32 %a, 2
7467 // %c = setcc eq %b, 0
7470 // This applies only when the AND constant value has one bit set and the
7471 // SRL constant is equal to the log2 of the AND constant. The back-end is
7472 // smart enough to convert the result into a TEST/JMP sequence.
7473 SDValue Op0 = N1.getOperand(0);
7474 SDValue Op1 = N1.getOperand(1);
7476 if (Op0.getOpcode() == ISD::AND &&
7477 Op1.getOpcode() == ISD::Constant) {
7478 SDValue AndOp1 = Op0.getOperand(1);
7480 if (AndOp1.getOpcode() == ISD::Constant) {
7481 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7483 if (AndConst.isPowerOf2() &&
7484 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7486 DAG.getSetCC(SDLoc(N),
7487 getSetCCResultType(Op0.getValueType()),
7488 Op0, DAG.getConstant(0, Op0.getValueType()),
7491 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7492 MVT::Other, Chain, SetCC, N2);
7493 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7494 // will convert it back to (X & C1) >> C2.
7495 CombineTo(N, NewBRCond, false);
7496 // Truncate is dead.
7498 deleteAndRecombine(Trunc);
7499 // Replace the uses of SRL with SETCC
7500 WorklistRemover DeadNodes(*this);
7501 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7502 deleteAndRecombine(N1.getNode());
7503 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7509 // Restore N1 if the above transformation doesn't match.
7510 N1 = N->getOperand(1);
7513 // Transform br(xor(x, y)) -> br(x != y)
7514 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7515 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7516 SDNode *TheXor = N1.getNode();
7517 SDValue Op0 = TheXor->getOperand(0);
7518 SDValue Op1 = TheXor->getOperand(1);
7519 if (Op0.getOpcode() == Op1.getOpcode()) {
7520 // Avoid missing important xor optimizations.
7521 SDValue Tmp = visitXOR(TheXor);
7522 if (Tmp.getNode()) {
7523 if (Tmp.getNode() != TheXor) {
7524 DEBUG(dbgs() << "\nReplacing.8 ";
7526 dbgs() << "\nWith: ";
7527 Tmp.getNode()->dump(&DAG);
7529 WorklistRemover DeadNodes(*this);
7530 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7531 deleteAndRecombine(TheXor);
7532 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7533 MVT::Other, Chain, Tmp, N2);
7536 // visitXOR has changed XOR's operands or replaced the XOR completely,
7538 return SDValue(N, 0);
7542 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7544 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7545 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7546 Op0.getOpcode() == ISD::XOR) {
7547 TheXor = Op0.getNode();
7551 EVT SetCCVT = N1.getValueType();
7553 SetCCVT = getSetCCResultType(SetCCVT);
7554 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7557 Equal ? ISD::SETEQ : ISD::SETNE);
7558 // Replace the uses of XOR with SETCC
7559 WorklistRemover DeadNodes(*this);
7560 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7561 deleteAndRecombine(N1.getNode());
7562 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7563 MVT::Other, Chain, SetCC, N2);
7570 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7572 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7573 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7574 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7576 // If N is a constant we could fold this into a fallthrough or unconditional
7577 // branch. However that doesn't happen very often in normal code, because
7578 // Instcombine/SimplifyCFG should have handled the available opportunities.
7579 // If we did this folding here, it would be necessary to update the
7580 // MachineBasicBlock CFG, which is awkward.
7582 // Use SimplifySetCC to simplify SETCC's.
7583 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7584 CondLHS, CondRHS, CC->get(), SDLoc(N),
7586 if (Simp.getNode()) AddToWorklist(Simp.getNode());
7588 // fold to a simpler setcc
7589 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7590 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7591 N->getOperand(0), Simp.getOperand(2),
7592 Simp.getOperand(0), Simp.getOperand(1),
7598 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7599 /// uses N as its base pointer and that N may be folded in the load / store
7600 /// addressing mode.
7601 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7603 const TargetLowering &TLI) {
7605 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7606 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7608 VT = Use->getValueType(0);
7609 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7610 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7612 VT = ST->getValue().getValueType();
7616 TargetLowering::AddrMode AM;
7617 if (N->getOpcode() == ISD::ADD) {
7618 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7621 AM.BaseOffs = Offset->getSExtValue();
7625 } else if (N->getOpcode() == ISD::SUB) {
7626 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7629 AM.BaseOffs = -Offset->getSExtValue();
7636 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7639 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7640 /// pre-indexed load / store when the base pointer is an add or subtract
7641 /// and it has other uses besides the load / store. After the
7642 /// transformation, the new indexed load / store has effectively folded
7643 /// the add / subtract in and all of its other uses are redirected to the
7644 /// new load / store.
7645 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7646 if (Level < AfterLegalizeDAG)
7652 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7653 if (LD->isIndexed())
7655 VT = LD->getMemoryVT();
7656 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7657 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7659 Ptr = LD->getBasePtr();
7660 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7661 if (ST->isIndexed())
7663 VT = ST->getMemoryVT();
7664 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7665 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7667 Ptr = ST->getBasePtr();
7673 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7674 // out. There is no reason to make this a preinc/predec.
7675 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7676 Ptr.getNode()->hasOneUse())
7679 // Ask the target to do addressing mode selection.
7682 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7683 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7686 // Backends without true r+i pre-indexed forms may need to pass a
7687 // constant base with a variable offset so that constant coercion
7688 // will work with the patterns in canonical form.
7689 bool Swapped = false;
7690 if (isa<ConstantSDNode>(BasePtr)) {
7691 std::swap(BasePtr, Offset);
7695 // Don't create a indexed load / store with zero offset.
7696 if (isa<ConstantSDNode>(Offset) &&
7697 cast<ConstantSDNode>(Offset)->isNullValue())
7700 // Try turning it into a pre-indexed load / store except when:
7701 // 1) The new base ptr is a frame index.
7702 // 2) If N is a store and the new base ptr is either the same as or is a
7703 // predecessor of the value being stored.
7704 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7705 // that would create a cycle.
7706 // 4) All uses are load / store ops that use it as old base ptr.
7708 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7709 // (plus the implicit offset) to a register to preinc anyway.
7710 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7715 SDValue Val = cast<StoreSDNode>(N)->getValue();
7716 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7720 // If the offset is a constant, there may be other adds of constants that
7721 // can be folded with this one. We should do this to avoid having to keep
7722 // a copy of the original base pointer.
7723 SmallVector<SDNode *, 16> OtherUses;
7724 if (isa<ConstantSDNode>(Offset))
7725 for (SDNode *Use : BasePtr.getNode()->uses()) {
7726 if (Use == Ptr.getNode())
7729 if (Use->isPredecessorOf(N))
7732 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7737 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7738 if (Op1.getNode() == BasePtr.getNode())
7739 std::swap(Op0, Op1);
7740 assert(Op0.getNode() == BasePtr.getNode() &&
7741 "Use of ADD/SUB but not an operand");
7743 if (!isa<ConstantSDNode>(Op1)) {
7748 // FIXME: In some cases, we can be smarter about this.
7749 if (Op1.getValueType() != Offset.getValueType()) {
7754 OtherUses.push_back(Use);
7758 std::swap(BasePtr, Offset);
7760 // Now check for #3 and #4.
7761 bool RealUse = false;
7763 // Caches for hasPredecessorHelper
7764 SmallPtrSet<const SDNode *, 32> Visited;
7765 SmallVector<const SDNode *, 16> Worklist;
7767 for (SDNode *Use : Ptr.getNode()->uses()) {
7770 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7773 // If Ptr may be folded in addressing mode of other use, then it's
7774 // not profitable to do this transformation.
7775 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7784 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7785 BasePtr, Offset, AM);
7787 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7788 BasePtr, Offset, AM);
7791 DEBUG(dbgs() << "\nReplacing.4 ";
7793 dbgs() << "\nWith: ";
7794 Result.getNode()->dump(&DAG);
7796 WorklistRemover DeadNodes(*this);
7798 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7799 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7801 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7804 // Finally, since the node is now dead, remove it from the graph.
7805 deleteAndRecombine(N);
7808 std::swap(BasePtr, Offset);
7810 // Replace other uses of BasePtr that can be updated to use Ptr
7811 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7812 unsigned OffsetIdx = 1;
7813 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7815 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7816 BasePtr.getNode() && "Expected BasePtr operand");
7818 // We need to replace ptr0 in the following expression:
7819 // x0 * offset0 + y0 * ptr0 = t0
7821 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7823 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7824 // indexed load/store and the expresion that needs to be re-written.
7826 // Therefore, we have:
7827 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7829 ConstantSDNode *CN =
7830 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7832 APInt Offset0 = CN->getAPIntValue();
7833 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7835 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7836 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7837 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7838 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7840 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7842 APInt CNV = Offset0;
7843 if (X0 < 0) CNV = -CNV;
7844 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7845 else CNV = CNV - Offset1;
7847 // We can now generate the new expression.
7848 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7849 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7851 SDValue NewUse = DAG.getNode(Opcode,
7852 SDLoc(OtherUses[i]),
7853 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7854 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7855 deleteAndRecombine(OtherUses[i]);
7858 // Replace the uses of Ptr with uses of the updated base value.
7859 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7860 deleteAndRecombine(Ptr.getNode());
7865 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7866 /// add / sub of the base pointer node into a post-indexed load / store.
7867 /// The transformation folded the add / subtract into the new indexed
7868 /// load / store effectively and all of its uses are redirected to the
7869 /// new load / store.
7870 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7871 if (Level < AfterLegalizeDAG)
7877 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7878 if (LD->isIndexed())
7880 VT = LD->getMemoryVT();
7881 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7882 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7884 Ptr = LD->getBasePtr();
7885 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7886 if (ST->isIndexed())
7888 VT = ST->getMemoryVT();
7889 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7890 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7892 Ptr = ST->getBasePtr();
7898 if (Ptr.getNode()->hasOneUse())
7901 for (SDNode *Op : Ptr.getNode()->uses()) {
7903 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7908 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7909 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7910 // Don't create a indexed load / store with zero offset.
7911 if (isa<ConstantSDNode>(Offset) &&
7912 cast<ConstantSDNode>(Offset)->isNullValue())
7915 // Try turning it into a post-indexed load / store except when
7916 // 1) All uses are load / store ops that use it as base ptr (and
7917 // it may be folded as addressing mmode).
7918 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7919 // nor a successor of N. Otherwise, if Op is folded that would
7922 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7926 bool TryNext = false;
7927 for (SDNode *Use : BasePtr.getNode()->uses()) {
7928 if (Use == Ptr.getNode())
7931 // If all the uses are load / store addresses, then don't do the
7933 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7934 bool RealUse = false;
7935 for (SDNode *UseUse : Use->uses()) {
7936 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7951 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7952 SDValue Result = isLoad
7953 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7954 BasePtr, Offset, AM)
7955 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7956 BasePtr, Offset, AM);
7959 DEBUG(dbgs() << "\nReplacing.5 ";
7961 dbgs() << "\nWith: ";
7962 Result.getNode()->dump(&DAG);
7964 WorklistRemover DeadNodes(*this);
7966 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7967 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7969 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7972 // Finally, since the node is now dead, remove it from the graph.
7973 deleteAndRecombine(N);
7975 // Replace the uses of Use with uses of the updated base value.
7976 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7977 Result.getValue(isLoad ? 1 : 0));
7978 deleteAndRecombine(Op);
7987 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7988 LoadSDNode *LD = cast<LoadSDNode>(N);
7989 SDValue Chain = LD->getChain();
7990 SDValue Ptr = LD->getBasePtr();
7992 // If load is not volatile and there are no uses of the loaded value (and
7993 // the updated indexed value in case of indexed loads), change uses of the
7994 // chain value into uses of the chain input (i.e. delete the dead load).
7995 if (!LD->isVolatile()) {
7996 if (N->getValueType(1) == MVT::Other) {
7998 if (!N->hasAnyUseOfValue(0)) {
7999 // It's not safe to use the two value CombineTo variant here. e.g.
8000 // v1, chain2 = load chain1, loc
8001 // v2, chain3 = load chain2, loc
8003 // Now we replace use of chain2 with chain1. This makes the second load
8004 // isomorphic to the one we are deleting, and thus makes this load live.
8005 DEBUG(dbgs() << "\nReplacing.6 ";
8007 dbgs() << "\nWith chain: ";
8008 Chain.getNode()->dump(&DAG);
8010 WorklistRemover DeadNodes(*this);
8011 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8014 deleteAndRecombine(N);
8016 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8020 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8021 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
8022 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8023 DEBUG(dbgs() << "\nReplacing.7 ";
8025 dbgs() << "\nWith: ";
8026 Undef.getNode()->dump(&DAG);
8027 dbgs() << " and 2 other values\n");
8028 WorklistRemover DeadNodes(*this);
8029 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8030 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
8031 DAG.getUNDEF(N->getValueType(1)));
8032 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8033 deleteAndRecombine(N);
8034 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8039 // If this load is directly stored, replace the load value with the stored
8041 // TODO: Handle store large -> read small portion.
8042 // TODO: Handle TRUNCSTORE/LOADEXT
8043 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8044 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8045 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8046 if (PrevST->getBasePtr() == Ptr &&
8047 PrevST->getValue().getValueType() == N->getValueType(0))
8048 return CombineTo(N, Chain.getOperand(1), Chain);
8052 // Try to infer better alignment information than the load already has.
8053 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8054 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8055 if (Align > LD->getMemOperand()->getBaseAlignment()) {
8057 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8058 LD->getValueType(0),
8059 Chain, Ptr, LD->getPointerInfo(),
8061 LD->isVolatile(), LD->isNonTemporal(),
8062 LD->isInvariant(), Align, LD->getAAInfo());
8063 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8068 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8069 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
8071 if (CombinerAAOnlyFunc.getNumOccurrences() &&
8072 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8075 if (UseAA && LD->isUnindexed()) {
8076 // Walk up chain skipping non-aliasing memory nodes.
8077 SDValue BetterChain = FindBetterChain(N, Chain);
8079 // If there is a better chain.
8080 if (Chain != BetterChain) {
8083 // Replace the chain to void dependency.
8084 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8085 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8086 BetterChain, Ptr, LD->getMemOperand());
8088 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8089 LD->getValueType(0),
8090 BetterChain, Ptr, LD->getMemoryVT(),
8091 LD->getMemOperand());
8094 // Create token factor to keep old chain connected.
8095 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8096 MVT::Other, Chain, ReplLoad.getValue(1));
8098 // Make sure the new and old chains are cleaned up.
8099 AddToWorklist(Token.getNode());
8101 // Replace uses with load result and token factor. Don't add users
8103 return CombineTo(N, ReplLoad.getValue(0), Token, false);
8107 // Try transforming N to an indexed load.
8108 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8109 return SDValue(N, 0);
8111 // Try to slice up N to more direct loads if the slices are mapped to
8112 // different register banks or pairing can take place.
8114 return SDValue(N, 0);
8120 /// \brief Helper structure used to slice a load in smaller loads.
8121 /// Basically a slice is obtained from the following sequence:
8122 /// Origin = load Ty1, Base
8123 /// Shift = srl Ty1 Origin, CstTy Amount
8124 /// Inst = trunc Shift to Ty2
8126 /// Then, it will be rewriten into:
8127 /// Slice = load SliceTy, Base + SliceOffset
8128 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8130 /// SliceTy is deduced from the number of bits that are actually used to
8132 struct LoadedSlice {
8133 /// \brief Helper structure used to compute the cost of a slice.
8135 /// Are we optimizing for code size.
8140 unsigned CrossRegisterBanksCopies;
8144 Cost(bool ForCodeSize = false)
8145 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8146 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8148 /// \brief Get the cost of one isolated slice.
8149 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8150 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8151 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8152 EVT TruncType = LS.Inst->getValueType(0);
8153 EVT LoadedType = LS.getLoadedType();
8154 if (TruncType != LoadedType &&
8155 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8159 /// \brief Account for slicing gain in the current cost.
8160 /// Slicing provide a few gains like removing a shift or a
8161 /// truncate. This method allows to grow the cost of the original
8162 /// load with the gain from this slice.
8163 void addSliceGain(const LoadedSlice &LS) {
8164 // Each slice saves a truncate.
8165 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8166 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8167 LS.Inst->getOperand(0).getValueType()))
8169 // If there is a shift amount, this slice gets rid of it.
8172 // If this slice can merge a cross register bank copy, account for it.
8173 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8174 ++CrossRegisterBanksCopies;
8177 Cost &operator+=(const Cost &RHS) {
8179 Truncates += RHS.Truncates;
8180 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8186 bool operator==(const Cost &RHS) const {
8187 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8188 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8189 ZExts == RHS.ZExts && Shift == RHS.Shift;
8192 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8194 bool operator<(const Cost &RHS) const {
8195 // Assume cross register banks copies are as expensive as loads.
8196 // FIXME: Do we want some more target hooks?
8197 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8198 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8199 // Unless we are optimizing for code size, consider the
8200 // expensive operation first.
8201 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8202 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8203 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8204 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8207 bool operator>(const Cost &RHS) const { return RHS < *this; }
8209 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8211 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8213 // The last instruction that represent the slice. This should be a
8214 // truncate instruction.
8216 // The original load instruction.
8218 // The right shift amount in bits from the original load.
8220 // The DAG from which Origin came from.
8221 // This is used to get some contextual information about legal types, etc.
8224 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8225 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8226 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8228 LoadedSlice(const LoadedSlice &LS)
8229 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8231 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8232 /// \return Result is \p BitWidth and has used bits set to 1 and
8233 /// not used bits set to 0.
8234 APInt getUsedBits() const {
8235 // Reproduce the trunc(lshr) sequence:
8236 // - Start from the truncated value.
8237 // - Zero extend to the desired bit width.
8239 assert(Origin && "No original load to compare against.");
8240 unsigned BitWidth = Origin->getValueSizeInBits(0);
8241 assert(Inst && "This slice is not bound to an instruction");
8242 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8243 "Extracted slice is bigger than the whole type!");
8244 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8245 UsedBits.setAllBits();
8246 UsedBits = UsedBits.zext(BitWidth);
8251 /// \brief Get the size of the slice to be loaded in bytes.
8252 unsigned getLoadedSize() const {
8253 unsigned SliceSize = getUsedBits().countPopulation();
8254 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8255 return SliceSize / 8;
8258 /// \brief Get the type that will be loaded for this slice.
8259 /// Note: This may not be the final type for the slice.
8260 EVT getLoadedType() const {
8261 assert(DAG && "Missing context");
8262 LLVMContext &Ctxt = *DAG->getContext();
8263 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8266 /// \brief Get the alignment of the load used for this slice.
8267 unsigned getAlignment() const {
8268 unsigned Alignment = Origin->getAlignment();
8269 unsigned Offset = getOffsetFromBase();
8271 Alignment = MinAlign(Alignment, Alignment + Offset);
8275 /// \brief Check if this slice can be rewritten with legal operations.
8276 bool isLegal() const {
8277 // An invalid slice is not legal.
8278 if (!Origin || !Inst || !DAG)
8281 // Offsets are for indexed load only, we do not handle that.
8282 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8285 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8287 // Check that the type is legal.
8288 EVT SliceType = getLoadedType();
8289 if (!TLI.isTypeLegal(SliceType))
8292 // Check that the load is legal for this type.
8293 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8296 // Check that the offset can be computed.
8297 // 1. Check its type.
8298 EVT PtrType = Origin->getBasePtr().getValueType();
8299 if (PtrType == MVT::Untyped || PtrType.isExtended())
8302 // 2. Check that it fits in the immediate.
8303 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8306 // 3. Check that the computation is legal.
8307 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8310 // Check that the zext is legal if it needs one.
8311 EVT TruncateType = Inst->getValueType(0);
8312 if (TruncateType != SliceType &&
8313 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8319 /// \brief Get the offset in bytes of this slice in the original chunk of
8321 /// \pre DAG != nullptr.
8322 uint64_t getOffsetFromBase() const {
8323 assert(DAG && "Missing context.");
8325 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8326 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8327 uint64_t Offset = Shift / 8;
8328 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8329 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8330 "The size of the original loaded type is not a multiple of a"
8332 // If Offset is bigger than TySizeInBytes, it means we are loading all
8333 // zeros. This should have been optimized before in the process.
8334 assert(TySizeInBytes > Offset &&
8335 "Invalid shift amount for given loaded size");
8337 Offset = TySizeInBytes - Offset - getLoadedSize();
8341 /// \brief Generate the sequence of instructions to load the slice
8342 /// represented by this object and redirect the uses of this slice to
8343 /// this new sequence of instructions.
8344 /// \pre this->Inst && this->Origin are valid Instructions and this
8345 /// object passed the legal check: LoadedSlice::isLegal returned true.
8346 /// \return The last instruction of the sequence used to load the slice.
8347 SDValue loadSlice() const {
8348 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8349 const SDValue &OldBaseAddr = Origin->getBasePtr();
8350 SDValue BaseAddr = OldBaseAddr;
8351 // Get the offset in that chunk of bytes w.r.t. the endianess.
8352 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8353 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8355 // BaseAddr = BaseAddr + Offset.
8356 EVT ArithType = BaseAddr.getValueType();
8357 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8358 DAG->getConstant(Offset, ArithType));
8361 // Create the type of the loaded slice according to its size.
8362 EVT SliceType = getLoadedType();
8364 // Create the load for the slice.
8365 SDValue LastInst = DAG->getLoad(
8366 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8367 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8368 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8369 // If the final type is not the same as the loaded type, this means that
8370 // we have to pad with zero. Create a zero extend for that.
8371 EVT FinalType = Inst->getValueType(0);
8372 if (SliceType != FinalType)
8374 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8378 /// \brief Check if this slice can be merged with an expensive cross register
8379 /// bank copy. E.g.,
8381 /// f = bitcast i32 i to float
8382 bool canMergeExpensiveCrossRegisterBankCopy() const {
8383 if (!Inst || !Inst->hasOneUse())
8385 SDNode *Use = *Inst->use_begin();
8386 if (Use->getOpcode() != ISD::BITCAST)
8388 assert(DAG && "Missing context");
8389 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8390 EVT ResVT = Use->getValueType(0);
8391 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8392 const TargetRegisterClass *ArgRC =
8393 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8394 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8397 // At this point, we know that we perform a cross-register-bank copy.
8398 // Check if it is expensive.
8399 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8400 // Assume bitcasts are cheap, unless both register classes do not
8401 // explicitly share a common sub class.
8402 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8405 // Check if it will be merged with the load.
8406 // 1. Check the alignment constraint.
8407 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8408 ResVT.getTypeForEVT(*DAG->getContext()));
8410 if (RequiredAlignment > getAlignment())
8413 // 2. Check that the load is a legal operation for that type.
8414 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8417 // 3. Check that we do not have a zext in the way.
8418 if (Inst->getValueType(0) != getLoadedType())
8426 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8427 /// \p UsedBits looks like 0..0 1..1 0..0.
8428 static bool areUsedBitsDense(const APInt &UsedBits) {
8429 // If all the bits are one, this is dense!
8430 if (UsedBits.isAllOnesValue())
8433 // Get rid of the unused bits on the right.
8434 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8435 // Get rid of the unused bits on the left.
8436 if (NarrowedUsedBits.countLeadingZeros())
8437 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8438 // Check that the chunk of bits is completely used.
8439 return NarrowedUsedBits.isAllOnesValue();
8442 /// \brief Check whether or not \p First and \p Second are next to each other
8443 /// in memory. This means that there is no hole between the bits loaded
8444 /// by \p First and the bits loaded by \p Second.
8445 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8446 const LoadedSlice &Second) {
8447 assert(First.Origin == Second.Origin && First.Origin &&
8448 "Unable to match different memory origins.");
8449 APInt UsedBits = First.getUsedBits();
8450 assert((UsedBits & Second.getUsedBits()) == 0 &&
8451 "Slices are not supposed to overlap.");
8452 UsedBits |= Second.getUsedBits();
8453 return areUsedBitsDense(UsedBits);
8456 /// \brief Adjust the \p GlobalLSCost according to the target
8457 /// paring capabilities and the layout of the slices.
8458 /// \pre \p GlobalLSCost should account for at least as many loads as
8459 /// there is in the slices in \p LoadedSlices.
8460 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8461 LoadedSlice::Cost &GlobalLSCost) {
8462 unsigned NumberOfSlices = LoadedSlices.size();
8463 // If there is less than 2 elements, no pairing is possible.
8464 if (NumberOfSlices < 2)
8467 // Sort the slices so that elements that are likely to be next to each
8468 // other in memory are next to each other in the list.
8469 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8470 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8471 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8472 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8474 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8475 // First (resp. Second) is the first (resp. Second) potentially candidate
8476 // to be placed in a paired load.
8477 const LoadedSlice *First = nullptr;
8478 const LoadedSlice *Second = nullptr;
8479 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8480 // Set the beginning of the pair.
8483 Second = &LoadedSlices[CurrSlice];
8485 // If First is NULL, it means we start a new pair.
8486 // Get to the next slice.
8490 EVT LoadedType = First->getLoadedType();
8492 // If the types of the slices are different, we cannot pair them.
8493 if (LoadedType != Second->getLoadedType())
8496 // Check if the target supplies paired loads for this type.
8497 unsigned RequiredAlignment = 0;
8498 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8499 // move to the next pair, this type is hopeless.
8503 // Check if we meet the alignment requirement.
8504 if (RequiredAlignment > First->getAlignment())
8507 // Check that both loads are next to each other in memory.
8508 if (!areSlicesNextToEachOther(*First, *Second))
8511 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8512 --GlobalLSCost.Loads;
8513 // Move to the next pair.
8518 /// \brief Check the profitability of all involved LoadedSlice.
8519 /// Currently, it is considered profitable if there is exactly two
8520 /// involved slices (1) which are (2) next to each other in memory, and
8521 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8523 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8524 /// the elements themselves.
8526 /// FIXME: When the cost model will be mature enough, we can relax
8527 /// constraints (1) and (2).
8528 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8529 const APInt &UsedBits, bool ForCodeSize) {
8530 unsigned NumberOfSlices = LoadedSlices.size();
8531 if (StressLoadSlicing)
8532 return NumberOfSlices > 1;
8535 if (NumberOfSlices != 2)
8539 if (!areUsedBitsDense(UsedBits))
8543 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8544 // The original code has one big load.
8546 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8547 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8548 // Accumulate the cost of all the slices.
8549 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8550 GlobalSlicingCost += SliceCost;
8552 // Account as cost in the original configuration the gain obtained
8553 // with the current slices.
8554 OrigCost.addSliceGain(LS);
8557 // If the target supports paired load, adjust the cost accordingly.
8558 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8559 return OrigCost > GlobalSlicingCost;
8562 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8563 /// operations, split it in the various pieces being extracted.
8565 /// This sort of thing is introduced by SROA.
8566 /// This slicing takes care not to insert overlapping loads.
8567 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8568 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8569 if (Level < AfterLegalizeDAG)
8572 LoadSDNode *LD = cast<LoadSDNode>(N);
8573 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8574 !LD->getValueType(0).isInteger())
8577 // Keep track of already used bits to detect overlapping values.
8578 // In that case, we will just abort the transformation.
8579 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8581 SmallVector<LoadedSlice, 4> LoadedSlices;
8583 // Check if this load is used as several smaller chunks of bits.
8584 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8585 // of computation for each trunc.
8586 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8587 UI != UIEnd; ++UI) {
8588 // Skip the uses of the chain.
8589 if (UI.getUse().getResNo() != 0)
8595 // Check if this is a trunc(lshr).
8596 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8597 isa<ConstantSDNode>(User->getOperand(1))) {
8598 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8599 User = *User->use_begin();
8602 // At this point, User is a Truncate, iff we encountered, trunc or
8604 if (User->getOpcode() != ISD::TRUNCATE)
8607 // The width of the type must be a power of 2 and greater than 8-bits.
8608 // Otherwise the load cannot be represented in LLVM IR.
8609 // Moreover, if we shifted with a non-8-bits multiple, the slice
8610 // will be across several bytes. We do not support that.
8611 unsigned Width = User->getValueSizeInBits(0);
8612 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8615 // Build the slice for this chain of computations.
8616 LoadedSlice LS(User, LD, Shift, &DAG);
8617 APInt CurrentUsedBits = LS.getUsedBits();
8619 // Check if this slice overlaps with another.
8620 if ((CurrentUsedBits & UsedBits) != 0)
8622 // Update the bits used globally.
8623 UsedBits |= CurrentUsedBits;
8625 // Check if the new slice would be legal.
8629 // Record the slice.
8630 LoadedSlices.push_back(LS);
8633 // Abort slicing if it does not seem to be profitable.
8634 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8639 // Rewrite each chain to use an independent load.
8640 // By construction, each chain can be represented by a unique load.
8642 // Prepare the argument for the new token factor for all the slices.
8643 SmallVector<SDValue, 8> ArgChains;
8644 for (SmallVectorImpl<LoadedSlice>::const_iterator
8645 LSIt = LoadedSlices.begin(),
8646 LSItEnd = LoadedSlices.end();
8647 LSIt != LSItEnd; ++LSIt) {
8648 SDValue SliceInst = LSIt->loadSlice();
8649 CombineTo(LSIt->Inst, SliceInst, true);
8650 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8651 SliceInst = SliceInst.getOperand(0);
8652 assert(SliceInst->getOpcode() == ISD::LOAD &&
8653 "It takes more than a zext to get to the loaded slice!!");
8654 ArgChains.push_back(SliceInst.getValue(1));
8657 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8659 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8663 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8664 /// load is having specific bytes cleared out. If so, return the byte size
8665 /// being masked out and the shift amount.
8666 static std::pair<unsigned, unsigned>
8667 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8668 std::pair<unsigned, unsigned> Result(0, 0);
8670 // Check for the structure we're looking for.
8671 if (V->getOpcode() != ISD::AND ||
8672 !isa<ConstantSDNode>(V->getOperand(1)) ||
8673 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8676 // Check the chain and pointer.
8677 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8678 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
8680 // The store should be chained directly to the load or be an operand of a
8682 if (LD == Chain.getNode())
8684 else if (Chain->getOpcode() != ISD::TokenFactor)
8685 return Result; // Fail.
8688 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8689 if (Chain->getOperand(i).getNode() == LD) {
8693 if (!isOk) return Result;
8696 // This only handles simple types.
8697 if (V.getValueType() != MVT::i16 &&
8698 V.getValueType() != MVT::i32 &&
8699 V.getValueType() != MVT::i64)
8702 // Check the constant mask. Invert it so that the bits being masked out are
8703 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8704 // follow the sign bit for uniformity.
8705 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8706 unsigned NotMaskLZ = countLeadingZeros(NotMask);
8707 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
8708 unsigned NotMaskTZ = countTrailingZeros(NotMask);
8709 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8710 if (NotMaskLZ == 64) return Result; // All zero mask.
8712 // See if we have a continuous run of bits. If so, we have 0*1+0*
8713 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8716 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8717 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8718 NotMaskLZ -= 64-V.getValueSizeInBits();
8720 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8721 switch (MaskedBytes) {
8725 default: return Result; // All one mask, or 5-byte mask.
8728 // Verify that the first bit starts at a multiple of mask so that the access
8729 // is aligned the same as the access width.
8730 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8732 Result.first = MaskedBytes;
8733 Result.second = NotMaskTZ/8;
8738 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8739 /// provides a value as specified by MaskInfo. If so, replace the specified
8740 /// store with a narrower store of truncated IVal.
8742 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8743 SDValue IVal, StoreSDNode *St,
8745 unsigned NumBytes = MaskInfo.first;
8746 unsigned ByteShift = MaskInfo.second;
8747 SelectionDAG &DAG = DC->getDAG();
8749 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8750 // that uses this. If not, this is not a replacement.
8751 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8752 ByteShift*8, (ByteShift+NumBytes)*8);
8753 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8755 // Check that it is legal on the target to do this. It is legal if the new
8756 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8758 MVT VT = MVT::getIntegerVT(NumBytes*8);
8759 if (!DC->isTypeLegal(VT))
8762 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8763 // shifted by ByteShift and truncated down to NumBytes.
8765 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8766 DAG.getConstant(ByteShift*8,
8767 DC->getShiftAmountTy(IVal.getValueType())));
8769 // Figure out the offset for the store and the alignment of the access.
8771 unsigned NewAlign = St->getAlignment();
8773 if (DAG.getTargetLoweringInfo().isLittleEndian())
8774 StOffset = ByteShift;
8776 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8778 SDValue Ptr = St->getBasePtr();
8780 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8781 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8782 NewAlign = MinAlign(NewAlign, StOffset);
8785 // Truncate down to the new size.
8786 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8789 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8790 St->getPointerInfo().getWithOffset(StOffset),
8791 false, false, NewAlign).getNode();
8795 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8796 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8797 /// of the loaded bits, try narrowing the load and store if it would end up
8798 /// being a win for performance or code size.
8799 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8800 StoreSDNode *ST = cast<StoreSDNode>(N);
8801 if (ST->isVolatile())
8804 SDValue Chain = ST->getChain();
8805 SDValue Value = ST->getValue();
8806 SDValue Ptr = ST->getBasePtr();
8807 EVT VT = Value.getValueType();
8809 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8812 unsigned Opc = Value.getOpcode();
8814 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8815 // is a byte mask indicating a consecutive number of bytes, check to see if
8816 // Y is known to provide just those bytes. If so, we try to replace the
8817 // load + replace + store sequence with a single (narrower) store, which makes
8819 if (Opc == ISD::OR) {
8820 std::pair<unsigned, unsigned> MaskedLoad;
8821 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8822 if (MaskedLoad.first)
8823 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8824 Value.getOperand(1), ST,this))
8825 return SDValue(NewST, 0);
8827 // Or is commutative, so try swapping X and Y.
8828 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8829 if (MaskedLoad.first)
8830 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8831 Value.getOperand(0), ST,this))
8832 return SDValue(NewST, 0);
8835 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8836 Value.getOperand(1).getOpcode() != ISD::Constant)
8839 SDValue N0 = Value.getOperand(0);
8840 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8841 Chain == SDValue(N0.getNode(), 1)) {
8842 LoadSDNode *LD = cast<LoadSDNode>(N0);
8843 if (LD->getBasePtr() != Ptr ||
8844 LD->getPointerInfo().getAddrSpace() !=
8845 ST->getPointerInfo().getAddrSpace())
8848 // Find the type to narrow it the load / op / store to.
8849 SDValue N1 = Value.getOperand(1);
8850 unsigned BitWidth = N1.getValueSizeInBits();
8851 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8852 if (Opc == ISD::AND)
8853 Imm ^= APInt::getAllOnesValue(BitWidth);
8854 if (Imm == 0 || Imm.isAllOnesValue())
8856 unsigned ShAmt = Imm.countTrailingZeros();
8857 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8858 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8859 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8860 while (NewBW < BitWidth &&
8861 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8862 TLI.isNarrowingProfitable(VT, NewVT))) {
8863 NewBW = NextPowerOf2(NewBW);
8864 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8866 if (NewBW >= BitWidth)
8869 // If the lsb changed does not start at the type bitwidth boundary,
8870 // start at the previous one.
8872 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8873 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8874 std::min(BitWidth, ShAmt + NewBW));
8875 if ((Imm & Mask) == Imm) {
8876 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8877 if (Opc == ISD::AND)
8878 NewImm ^= APInt::getAllOnesValue(NewBW);
8879 uint64_t PtrOff = ShAmt / 8;
8880 // For big endian targets, we need to adjust the offset to the pointer to
8881 // load the correct bytes.
8882 if (TLI.isBigEndian())
8883 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8885 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8886 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8887 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8890 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8891 Ptr.getValueType(), Ptr,
8892 DAG.getConstant(PtrOff, Ptr.getValueType()));
8893 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8894 LD->getChain(), NewPtr,
8895 LD->getPointerInfo().getWithOffset(PtrOff),
8896 LD->isVolatile(), LD->isNonTemporal(),
8897 LD->isInvariant(), NewAlign,
8899 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8900 DAG.getConstant(NewImm, NewVT));
8901 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8903 ST->getPointerInfo().getWithOffset(PtrOff),
8904 false, false, NewAlign);
8906 AddToWorklist(NewPtr.getNode());
8907 AddToWorklist(NewLD.getNode());
8908 AddToWorklist(NewVal.getNode());
8909 WorklistRemover DeadNodes(*this);
8910 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8919 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8920 /// if the load value isn't used by any other operations, then consider
8921 /// transforming the pair to integer load / store operations if the target
8922 /// deems the transformation profitable.
8923 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8924 StoreSDNode *ST = cast<StoreSDNode>(N);
8925 SDValue Chain = ST->getChain();
8926 SDValue Value = ST->getValue();
8927 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8928 Value.hasOneUse() &&
8929 Chain == SDValue(Value.getNode(), 1)) {
8930 LoadSDNode *LD = cast<LoadSDNode>(Value);
8931 EVT VT = LD->getMemoryVT();
8932 if (!VT.isFloatingPoint() ||
8933 VT != ST->getMemoryVT() ||
8934 LD->isNonTemporal() ||
8935 ST->isNonTemporal() ||
8936 LD->getPointerInfo().getAddrSpace() != 0 ||
8937 ST->getPointerInfo().getAddrSpace() != 0)
8940 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8941 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8942 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8943 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8944 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8947 unsigned LDAlign = LD->getAlignment();
8948 unsigned STAlign = ST->getAlignment();
8949 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8950 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8951 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8954 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8955 LD->getChain(), LD->getBasePtr(),
8956 LD->getPointerInfo(),
8957 false, false, false, LDAlign);
8959 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8960 NewLD, ST->getBasePtr(),
8961 ST->getPointerInfo(),
8962 false, false, STAlign);
8964 AddToWorklist(NewLD.getNode());
8965 AddToWorklist(NewST.getNode());
8966 WorklistRemover DeadNodes(*this);
8967 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8975 /// Helper struct to parse and store a memory address as base + index + offset.
8976 /// We ignore sign extensions when it is safe to do so.
8977 /// The following two expressions are not equivalent. To differentiate we need
8978 /// to store whether there was a sign extension involved in the index
8980 /// (load (i64 add (i64 copyfromreg %c)
8981 /// (i64 signextend (add (i8 load %index)
8985 /// (load (i64 add (i64 copyfromreg %c)
8986 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8988 struct BaseIndexOffset {
8992 bool IsIndexSignExt;
8994 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8996 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8997 bool IsIndexSignExt) :
8998 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9000 bool equalBaseIndex(const BaseIndexOffset &Other) {
9001 return Other.Base == Base && Other.Index == Index &&
9002 Other.IsIndexSignExt == IsIndexSignExt;
9005 /// Parses tree in Ptr for base, index, offset addresses.
9006 static BaseIndexOffset match(SDValue Ptr) {
9007 bool IsIndexSignExt = false;
9009 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9010 // instruction, then it could be just the BASE or everything else we don't
9011 // know how to handle. Just use Ptr as BASE and give up.
9012 if (Ptr->getOpcode() != ISD::ADD)
9013 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9015 // We know that we have at least an ADD instruction. Try to pattern match
9016 // the simple case of BASE + OFFSET.
9017 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9018 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9019 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9023 // Inside a loop the current BASE pointer is calculated using an ADD and a
9024 // MUL instruction. In this case Ptr is the actual BASE pointer.
9025 // (i64 add (i64 %array_ptr)
9026 // (i64 mul (i64 %induction_var)
9027 // (i64 %element_size)))
9028 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9029 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9031 // Look at Base + Index + Offset cases.
9032 SDValue Base = Ptr->getOperand(0);
9033 SDValue IndexOffset = Ptr->getOperand(1);
9035 // Skip signextends.
9036 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9037 IndexOffset = IndexOffset->getOperand(0);
9038 IsIndexSignExt = true;
9041 // Either the case of Base + Index (no offset) or something else.
9042 if (IndexOffset->getOpcode() != ISD::ADD)
9043 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9045 // Now we have the case of Base + Index + offset.
9046 SDValue Index = IndexOffset->getOperand(0);
9047 SDValue Offset = IndexOffset->getOperand(1);
9049 if (!isa<ConstantSDNode>(Offset))
9050 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9052 // Ignore signextends.
9053 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9054 Index = Index->getOperand(0);
9055 IsIndexSignExt = true;
9056 } else IsIndexSignExt = false;
9058 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9059 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9063 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9064 /// is located in a sequence of memory operations connected by a chain.
9066 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9067 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9068 // Ptr to the mem node.
9069 LSBaseSDNode *MemNode;
9070 // Offset from the base ptr.
9071 int64_t OffsetFromBase;
9072 // What is the sequence number of this mem node.
9073 // Lowest mem operand in the DAG starts at zero.
9074 unsigned SequenceNum;
9077 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9078 EVT MemVT = St->getMemoryVT();
9079 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9080 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9081 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9083 // Don't merge vectors into wider inputs.
9084 if (MemVT.isVector() || !MemVT.isSimple())
9087 // Perform an early exit check. Do not bother looking at stored values that
9088 // are not constants or loads.
9089 SDValue StoredVal = St->getValue();
9090 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9091 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9095 // Only look at ends of store sequences.
9096 SDValue Chain = SDValue(St, 0);
9097 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9100 // This holds the base pointer, index, and the offset in bytes from the base
9102 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9104 // We must have a base and an offset.
9105 if (!BasePtr.Base.getNode())
9108 // Do not handle stores to undef base pointers.
9109 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9112 // Save the LoadSDNodes that we find in the chain.
9113 // We need to make sure that these nodes do not interfere with
9114 // any of the store nodes.
9115 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9117 // Save the StoreSDNodes that we find in the chain.
9118 SmallVector<MemOpLink, 8> StoreNodes;
9120 // Walk up the chain and look for nodes with offsets from the same
9121 // base pointer. Stop when reaching an instruction with a different kind
9122 // or instruction which has a different base pointer.
9124 StoreSDNode *Index = St;
9126 // If the chain has more than one use, then we can't reorder the mem ops.
9127 if (Index != St && !SDValue(Index, 0)->hasOneUse())
9130 // Find the base pointer and offset for this memory node.
9131 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9133 // Check that the base pointer is the same as the original one.
9134 if (!Ptr.equalBaseIndex(BasePtr))
9137 // Check that the alignment is the same.
9138 if (Index->getAlignment() != St->getAlignment())
9141 // The memory operands must not be volatile.
9142 if (Index->isVolatile() || Index->isIndexed())
9146 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9147 if (St->isTruncatingStore())
9150 // The stored memory type must be the same.
9151 if (Index->getMemoryVT() != MemVT)
9154 // We do not allow unaligned stores because we want to prevent overriding
9156 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9159 // We found a potential memory operand to merge.
9160 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9162 // Find the next memory operand in the chain. If the next operand in the
9163 // chain is a store then move up and continue the scan with the next
9164 // memory operand. If the next operand is a load save it and use alias
9165 // information to check if it interferes with anything.
9166 SDNode *NextInChain = Index->getChain().getNode();
9168 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9169 // We found a store node. Use it for the next iteration.
9172 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9173 if (Ldn->isVolatile()) {
9178 // Save the load node for later. Continue the scan.
9179 AliasLoadNodes.push_back(Ldn);
9180 NextInChain = Ldn->getChain().getNode();
9189 // Check if there is anything to merge.
9190 if (StoreNodes.size() < 2)
9193 // Sort the memory operands according to their distance from the base pointer.
9194 std::sort(StoreNodes.begin(), StoreNodes.end(),
9195 [](MemOpLink LHS, MemOpLink RHS) {
9196 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9197 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9198 LHS.SequenceNum > RHS.SequenceNum);
9201 // Scan the memory operations on the chain and find the first non-consecutive
9202 // store memory address.
9203 unsigned LastConsecutiveStore = 0;
9204 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9205 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9207 // Check that the addresses are consecutive starting from the second
9208 // element in the list of stores.
9210 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9211 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9216 // Check if this store interferes with any of the loads that we found.
9217 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9218 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9222 // We found a load that alias with this store. Stop the sequence.
9226 // Mark this node as useful.
9227 LastConsecutiveStore = i;
9230 // The node with the lowest store address.
9231 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9233 // Store the constants into memory as one consecutive store.
9235 unsigned LastLegalType = 0;
9236 unsigned LastLegalVectorType = 0;
9237 bool NonZero = false;
9238 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9239 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9240 SDValue StoredVal = St->getValue();
9242 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9243 NonZero |= !C->isNullValue();
9244 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9245 NonZero |= !C->getConstantFPValue()->isNullValue();
9251 // Find a legal type for the constant store.
9252 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9253 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9254 if (TLI.isTypeLegal(StoreTy))
9255 LastLegalType = i+1;
9256 // Or check whether a truncstore is legal.
9257 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9258 TargetLowering::TypePromoteInteger) {
9259 EVT LegalizedStoredValueTy =
9260 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9261 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9262 LastLegalType = i+1;
9265 // Find a legal type for the vector store.
9266 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9267 if (TLI.isTypeLegal(Ty))
9268 LastLegalVectorType = i + 1;
9271 // We only use vectors if the constant is known to be zero and the
9272 // function is not marked with the noimplicitfloat attribute.
9273 if (NonZero || NoVectors)
9274 LastLegalVectorType = 0;
9276 // Check if we found a legal integer type to store.
9277 if (LastLegalType == 0 && LastLegalVectorType == 0)
9280 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9281 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9283 // Make sure we have something to merge.
9287 unsigned EarliestNodeUsed = 0;
9288 for (unsigned i=0; i < NumElem; ++i) {
9289 // Find a chain for the new wide-store operand. Notice that some
9290 // of the store nodes that we found may not be selected for inclusion
9291 // in the wide store. The chain we use needs to be the chain of the
9292 // earliest store node which is *used* and replaced by the wide store.
9293 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9294 EarliestNodeUsed = i;
9297 // The earliest Node in the DAG.
9298 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9299 SDLoc DL(StoreNodes[0].MemNode);
9303 // Find a legal type for the vector store.
9304 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9305 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9306 StoredVal = DAG.getConstant(0, Ty);
9308 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9309 APInt StoreInt(StoreBW, 0);
9311 // Construct a single integer constant which is made of the smaller
9313 bool IsLE = TLI.isLittleEndian();
9314 for (unsigned i = 0; i < NumElem ; ++i) {
9315 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9316 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9317 SDValue Val = St->getValue();
9318 StoreInt<<=ElementSizeBytes*8;
9319 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9320 StoreInt|=C->getAPIntValue().zext(StoreBW);
9321 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9322 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9324 assert(false && "Invalid constant element type");
9328 // Create the new Load and Store operations.
9329 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9330 StoredVal = DAG.getConstant(StoreInt, StoreTy);
9333 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9334 FirstInChain->getBasePtr(),
9335 FirstInChain->getPointerInfo(),
9337 FirstInChain->getAlignment());
9339 // Replace the first store with the new store
9340 CombineTo(EarliestOp, NewStore);
9341 // Erase all other stores.
9342 for (unsigned i = 0; i < NumElem ; ++i) {
9343 if (StoreNodes[i].MemNode == EarliestOp)
9345 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9346 // ReplaceAllUsesWith will replace all uses that existed when it was
9347 // called, but graph optimizations may cause new ones to appear. For
9348 // example, the case in pr14333 looks like
9350 // St's chain -> St -> another store -> X
9352 // And the only difference from St to the other store is the chain.
9353 // When we change it's chain to be St's chain they become identical,
9354 // get CSEed and the net result is that X is now a use of St.
9355 // Since we know that St is redundant, just iterate.
9356 while (!St->use_empty())
9357 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9358 deleteAndRecombine(St);
9364 // Below we handle the case of multiple consecutive stores that
9365 // come from multiple consecutive loads. We merge them into a single
9366 // wide load and a single wide store.
9368 // Look for load nodes which are used by the stored values.
9369 SmallVector<MemOpLink, 8> LoadNodes;
9371 // Find acceptable loads. Loads need to have the same chain (token factor),
9372 // must not be zext, volatile, indexed, and they must be consecutive.
9373 BaseIndexOffset LdBasePtr;
9374 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9375 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9376 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9379 // Loads must only have one use.
9380 if (!Ld->hasNUsesOfValue(1, 0))
9383 // Check that the alignment is the same as the stores.
9384 if (Ld->getAlignment() != St->getAlignment())
9387 // The memory operands must not be volatile.
9388 if (Ld->isVolatile() || Ld->isIndexed())
9391 // We do not accept ext loads.
9392 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9395 // The stored memory type must be the same.
9396 if (Ld->getMemoryVT() != MemVT)
9399 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9400 // If this is not the first ptr that we check.
9401 if (LdBasePtr.Base.getNode()) {
9402 // The base ptr must be the same.
9403 if (!LdPtr.equalBaseIndex(LdBasePtr))
9406 // Check that all other base pointers are the same as this one.
9410 // We found a potential memory operand to merge.
9411 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9414 if (LoadNodes.size() < 2)
9417 // If we have load/store pair instructions and we only have two values,
9419 unsigned RequiredAlignment;
9420 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
9421 St->getAlignment() >= RequiredAlignment)
9424 // Scan the memory operations on the chain and find the first non-consecutive
9425 // load memory address. These variables hold the index in the store node
9427 unsigned LastConsecutiveLoad = 0;
9428 // This variable refers to the size and not index in the array.
9429 unsigned LastLegalVectorType = 0;
9430 unsigned LastLegalIntegerType = 0;
9431 StartAddress = LoadNodes[0].OffsetFromBase;
9432 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9433 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9434 // All loads much share the same chain.
9435 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9438 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9439 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9441 LastConsecutiveLoad = i;
9443 // Find a legal type for the vector store.
9444 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9445 if (TLI.isTypeLegal(StoreTy))
9446 LastLegalVectorType = i + 1;
9448 // Find a legal type for the integer store.
9449 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9450 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9451 if (TLI.isTypeLegal(StoreTy))
9452 LastLegalIntegerType = i + 1;
9453 // Or check whether a truncstore and extload is legal.
9454 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9455 TargetLowering::TypePromoteInteger) {
9456 EVT LegalizedStoredValueTy =
9457 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9458 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9459 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9460 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9461 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9462 LastLegalIntegerType = i+1;
9466 // Only use vector types if the vector type is larger than the integer type.
9467 // If they are the same, use integers.
9468 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9469 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9471 // We add +1 here because the LastXXX variables refer to location while
9472 // the NumElem refers to array/index size.
9473 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9474 NumElem = std::min(LastLegalType, NumElem);
9479 // The earliest Node in the DAG.
9480 unsigned EarliestNodeUsed = 0;
9481 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9482 for (unsigned i=1; i<NumElem; ++i) {
9483 // Find a chain for the new wide-store operand. Notice that some
9484 // of the store nodes that we found may not be selected for inclusion
9485 // in the wide store. The chain we use needs to be the chain of the
9486 // earliest store node which is *used* and replaced by the wide store.
9487 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9488 EarliestNodeUsed = i;
9491 // Find if it is better to use vectors or integers to load and store
9495 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9497 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9498 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9501 SDLoc LoadDL(LoadNodes[0].MemNode);
9502 SDLoc StoreDL(StoreNodes[0].MemNode);
9504 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9505 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9506 FirstLoad->getChain(),
9507 FirstLoad->getBasePtr(),
9508 FirstLoad->getPointerInfo(),
9509 false, false, false,
9510 FirstLoad->getAlignment());
9512 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9513 FirstInChain->getBasePtr(),
9514 FirstInChain->getPointerInfo(), false, false,
9515 FirstInChain->getAlignment());
9517 // Replace one of the loads with the new load.
9518 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9519 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9520 SDValue(NewLoad.getNode(), 1));
9522 // Remove the rest of the load chains.
9523 for (unsigned i = 1; i < NumElem ; ++i) {
9524 // Replace all chain users of the old load nodes with the chain of the new
9526 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9527 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9530 // Replace the first store with the new store.
9531 CombineTo(EarliestOp, NewStore);
9532 // Erase all other stores.
9533 for (unsigned i = 0; i < NumElem ; ++i) {
9534 // Remove all Store nodes.
9535 if (StoreNodes[i].MemNode == EarliestOp)
9537 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9538 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9539 deleteAndRecombine(St);
9545 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9546 StoreSDNode *ST = cast<StoreSDNode>(N);
9547 SDValue Chain = ST->getChain();
9548 SDValue Value = ST->getValue();
9549 SDValue Ptr = ST->getBasePtr();
9551 // If this is a store of a bit convert, store the input value if the
9552 // resultant store does not need a higher alignment than the original.
9553 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9554 ST->isUnindexed()) {
9555 unsigned OrigAlign = ST->getAlignment();
9556 EVT SVT = Value.getOperand(0).getValueType();
9557 unsigned Align = TLI.getDataLayout()->
9558 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9559 if (Align <= OrigAlign &&
9560 ((!LegalOperations && !ST->isVolatile()) ||
9561 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9562 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9563 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9564 ST->isNonTemporal(), OrigAlign,
9568 // Turn 'store undef, Ptr' -> nothing.
9569 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9572 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9573 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9574 // NOTE: If the original store is volatile, this transform must not increase
9575 // the number of stores. For example, on x86-32 an f64 can be stored in one
9576 // processor operation but an i64 (which is not legal) requires two. So the
9577 // transform should not be done in this case.
9578 if (Value.getOpcode() != ISD::TargetConstantFP) {
9580 switch (CFP->getSimpleValueType(0).SimpleTy) {
9581 default: llvm_unreachable("Unknown FP type");
9582 case MVT::f16: // We don't do this for these yet.
9588 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9589 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9590 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9591 bitcastToAPInt().getZExtValue(), MVT::i32);
9592 return DAG.getStore(Chain, SDLoc(N), Tmp,
9593 Ptr, ST->getMemOperand());
9597 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9598 !ST->isVolatile()) ||
9599 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9600 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9601 getZExtValue(), MVT::i64);
9602 return DAG.getStore(Chain, SDLoc(N), Tmp,
9603 Ptr, ST->getMemOperand());
9606 if (!ST->isVolatile() &&
9607 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9608 // Many FP stores are not made apparent until after legalize, e.g. for
9609 // argument passing. Since this is so common, custom legalize the
9610 // 64-bit integer store into two 32-bit stores.
9611 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9612 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9613 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9614 if (TLI.isBigEndian()) std::swap(Lo, Hi);
9616 unsigned Alignment = ST->getAlignment();
9617 bool isVolatile = ST->isVolatile();
9618 bool isNonTemporal = ST->isNonTemporal();
9619 AAMDNodes AAInfo = ST->getAAInfo();
9621 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9622 Ptr, ST->getPointerInfo(),
9623 isVolatile, isNonTemporal,
9624 ST->getAlignment(), AAInfo);
9625 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9626 DAG.getConstant(4, Ptr.getValueType()));
9627 Alignment = MinAlign(Alignment, 4U);
9628 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9629 Ptr, ST->getPointerInfo().getWithOffset(4),
9630 isVolatile, isNonTemporal,
9632 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9641 // Try to infer better alignment information than the store already has.
9642 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9643 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9644 if (Align > ST->getAlignment())
9645 return DAG.getTruncStore(Chain, SDLoc(N), Value,
9646 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9647 ST->isVolatile(), ST->isNonTemporal(), Align,
9652 // Try transforming a pair floating point load / store ops to integer
9653 // load / store ops.
9654 SDValue NewST = TransformFPLoadStorePair(N);
9655 if (NewST.getNode())
9658 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9659 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9661 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9662 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9665 if (UseAA && ST->isUnindexed()) {
9666 // Walk up chain skipping non-aliasing memory nodes.
9667 SDValue BetterChain = FindBetterChain(N, Chain);
9669 // If there is a better chain.
9670 if (Chain != BetterChain) {
9673 // Replace the chain to avoid dependency.
9674 if (ST->isTruncatingStore()) {
9675 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9676 ST->getMemoryVT(), ST->getMemOperand());
9678 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9679 ST->getMemOperand());
9682 // Create token to keep both nodes around.
9683 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9684 MVT::Other, Chain, ReplStore);
9686 // Make sure the new and old chains are cleaned up.
9687 AddToWorklist(Token.getNode());
9689 // Don't add users to work list.
9690 return CombineTo(N, Token, false);
9694 // Try transforming N to an indexed store.
9695 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9696 return SDValue(N, 0);
9698 // FIXME: is there such a thing as a truncating indexed store?
9699 if (ST->isTruncatingStore() && ST->isUnindexed() &&
9700 Value.getValueType().isInteger()) {
9701 // See if we can simplify the input to this truncstore with knowledge that
9702 // only the low bits are being used. For example:
9703 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
9705 GetDemandedBits(Value,
9706 APInt::getLowBitsSet(
9707 Value.getValueType().getScalarType().getSizeInBits(),
9708 ST->getMemoryVT().getScalarType().getSizeInBits()));
9709 AddToWorklist(Value.getNode());
9710 if (Shorter.getNode())
9711 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9712 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9714 // Otherwise, see if we can simplify the operation with
9715 // SimplifyDemandedBits, which only works if the value has a single use.
9716 if (SimplifyDemandedBits(Value,
9717 APInt::getLowBitsSet(
9718 Value.getValueType().getScalarType().getSizeInBits(),
9719 ST->getMemoryVT().getScalarType().getSizeInBits())))
9720 return SDValue(N, 0);
9723 // If this is a load followed by a store to the same location, then the store
9725 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9726 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9727 ST->isUnindexed() && !ST->isVolatile() &&
9728 // There can't be any side effects between the load and store, such as
9730 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9731 // The store is dead, remove it.
9736 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9737 // truncating store. We can do this even if this is already a truncstore.
9738 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9739 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9740 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9741 ST->getMemoryVT())) {
9742 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9743 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9746 // Only perform this optimization before the types are legal, because we
9747 // don't want to perform this optimization on every DAGCombine invocation.
9749 bool EverChanged = false;
9752 // There can be multiple store sequences on the same chain.
9753 // Keep trying to merge store sequences until we are unable to do so
9754 // or until we merge the last store on the chain.
9755 bool Changed = MergeConsecutiveStores(ST);
9756 EverChanged |= Changed;
9757 if (!Changed) break;
9758 } while (ST->getOpcode() != ISD::DELETED_NODE);
9761 return SDValue(N, 0);
9764 return ReduceLoadOpStoreWidth(N);
9767 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9768 SDValue InVec = N->getOperand(0);
9769 SDValue InVal = N->getOperand(1);
9770 SDValue EltNo = N->getOperand(2);
9773 // If the inserted element is an UNDEF, just use the input vector.
9774 if (InVal.getOpcode() == ISD::UNDEF)
9777 EVT VT = InVec.getValueType();
9779 // If we can't generate a legal BUILD_VECTOR, exit
9780 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9783 // Check that we know which element is being inserted
9784 if (!isa<ConstantSDNode>(EltNo))
9786 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9788 // Canonicalize insert_vector_elt dag nodes.
9790 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9791 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9793 // Do this only if the child insert_vector node has one use; also
9794 // do this only if indices are both constants and Idx1 < Idx0.
9795 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9796 && isa<ConstantSDNode>(InVec.getOperand(2))) {
9798 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9799 if (Elt < OtherElt) {
9801 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9802 InVec.getOperand(0), InVal, EltNo);
9803 AddToWorklist(NewOp.getNode());
9804 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9805 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9809 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9810 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9812 SmallVector<SDValue, 8> Ops;
9813 // Do not combine these two vectors if the output vector will not replace
9814 // the input vector.
9815 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9816 Ops.append(InVec.getNode()->op_begin(),
9817 InVec.getNode()->op_end());
9818 } else if (InVec.getOpcode() == ISD::UNDEF) {
9819 unsigned NElts = VT.getVectorNumElements();
9820 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9825 // Insert the element
9826 if (Elt < Ops.size()) {
9827 // All the operands of BUILD_VECTOR must have the same type;
9828 // we enforce that here.
9829 EVT OpVT = Ops[0].getValueType();
9830 if (InVal.getValueType() != OpVT)
9831 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9832 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9833 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9837 // Return the new vector
9838 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
9841 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9842 // (vextract (scalar_to_vector val, 0) -> val
9843 SDValue InVec = N->getOperand(0);
9844 EVT VT = InVec.getValueType();
9845 EVT NVT = N->getValueType(0);
9847 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9848 // Check if the result type doesn't match the inserted element type. A
9849 // SCALAR_TO_VECTOR may truncate the inserted element and the
9850 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9851 SDValue InOp = InVec.getOperand(0);
9852 if (InOp.getValueType() != NVT) {
9853 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9854 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9859 SDValue EltNo = N->getOperand(1);
9860 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9862 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9863 // We only perform this optimization before the op legalization phase because
9864 // we may introduce new vector instructions which are not backed by TD
9865 // patterns. For example on AVX, extracting elements from a wide vector
9866 // without using extract_subvector. However, if we can find an underlying
9867 // scalar value, then we can always use that.
9868 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9870 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9871 int NumElem = VT.getVectorNumElements();
9872 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9873 // Find the new index to extract from.
9874 int OrigElt = SVOp->getMaskElt(Elt);
9876 // Extracting an undef index is undef.
9878 return DAG.getUNDEF(NVT);
9880 // Select the right vector half to extract from.
9882 if (OrigElt < NumElem) {
9883 SVInVec = InVec->getOperand(0);
9885 SVInVec = InVec->getOperand(1);
9889 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9890 SDValue InOp = SVInVec.getOperand(OrigElt);
9891 if (InOp.getValueType() != NVT) {
9892 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9893 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9899 // FIXME: We should handle recursing on other vector shuffles and
9900 // scalar_to_vector here as well.
9902 if (!LegalOperations) {
9903 EVT IndexTy = TLI.getVectorIdxTy();
9904 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9905 SVInVec, DAG.getConstant(OrigElt, IndexTy));
9909 // Perform only after legalization to ensure build_vector / vector_shuffle
9910 // optimizations have already been done.
9911 if (!LegalOperations) return SDValue();
9913 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9914 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9915 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9918 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9919 bool NewLoad = false;
9920 bool BCNumEltsChanged = false;
9921 EVT ExtVT = VT.getVectorElementType();
9924 // If the result of load has to be truncated, then it's not necessarily
9926 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9929 if (InVec.getOpcode() == ISD::BITCAST) {
9930 // Don't duplicate a load with other uses.
9931 if (!InVec.hasOneUse())
9934 EVT BCVT = InVec.getOperand(0).getValueType();
9935 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9937 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9938 BCNumEltsChanged = true;
9939 InVec = InVec.getOperand(0);
9940 ExtVT = BCVT.getVectorElementType();
9944 LoadSDNode *LN0 = nullptr;
9945 const ShuffleVectorSDNode *SVN = nullptr;
9946 if (ISD::isNormalLoad(InVec.getNode())) {
9947 LN0 = cast<LoadSDNode>(InVec);
9948 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9949 InVec.getOperand(0).getValueType() == ExtVT &&
9950 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9951 // Don't duplicate a load with other uses.
9952 if (!InVec.hasOneUse())
9955 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9956 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9957 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9959 // (load $addr+1*size)
9961 // Don't duplicate a load with other uses.
9962 if (!InVec.hasOneUse())
9965 // If the bit convert changed the number of elements, it is unsafe
9966 // to examine the mask.
9967 if (BCNumEltsChanged)
9970 // Select the input vector, guarding against out of range extract vector.
9971 unsigned NumElems = VT.getVectorNumElements();
9972 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9973 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9975 if (InVec.getOpcode() == ISD::BITCAST) {
9976 // Don't duplicate a load with other uses.
9977 if (!InVec.hasOneUse())
9980 InVec = InVec.getOperand(0);
9982 if (ISD::isNormalLoad(InVec.getNode())) {
9983 LN0 = cast<LoadSDNode>(InVec);
9984 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9988 // Make sure we found a non-volatile load and the extractelement is
9990 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9993 // If Idx was -1 above, Elt is going to be -1, so just return undef.
9995 return DAG.getUNDEF(LVT);
9997 unsigned Align = LN0->getAlignment();
9999 // Check the resultant load doesn't need a higher alignment than the
10001 unsigned NewAlign =
10002 TLI.getDataLayout()
10003 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
10005 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
10011 SDValue NewPtr = LN0->getBasePtr();
10012 unsigned PtrOff = 0;
10015 PtrOff = LVT.getSizeInBits() * Elt / 8;
10016 EVT PtrType = NewPtr.getValueType();
10017 if (TLI.isBigEndian())
10018 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
10019 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
10020 DAG.getConstant(PtrOff, PtrType));
10023 // The replacement we need to do here is a little tricky: we need to
10024 // replace an extractelement of a load with a load.
10025 // Use ReplaceAllUsesOfValuesWith to do the replacement.
10026 // Note that this replacement assumes that the extractvalue is the only
10027 // use of the load; that's okay because we don't want to perform this
10028 // transformation in other cases anyway.
10031 if (NVT.bitsGT(LVT)) {
10032 // If the result type of vextract is wider than the load, then issue an
10033 // extending load instead.
10034 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
10035 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
10036 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
10037 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
10038 LVT, LN0->isVolatile(), LN0->isNonTemporal(),
10039 LN0->isInvariant(), Align, LN0->getAAInfo());
10040 Chain = Load.getValue(1);
10042 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
10043 LN0->getPointerInfo().getWithOffset(PtrOff),
10044 LN0->isVolatile(), LN0->isNonTemporal(),
10045 LN0->isInvariant(), Align, LN0->getAAInfo());
10046 Chain = Load.getValue(1);
10047 if (NVT.bitsLT(LVT))
10048 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
10050 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
10052 WorklistRemover DeadNodes(*this);
10053 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
10054 SDValue To[] = { Load, Chain };
10055 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10056 // Since we're explcitly calling ReplaceAllUses, add the new node to the
10057 // worklist explicitly as well.
10058 AddToWorklist(Load.getNode());
10059 AddUsersToWorklist(Load.getNode()); // Add users too
10060 // Make sure to revisit this node to clean it up; it will usually be dead.
10062 return SDValue(N, 0);
10068 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10069 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10070 // We perform this optimization post type-legalization because
10071 // the type-legalizer often scalarizes integer-promoted vectors.
10072 // Performing this optimization before may create bit-casts which
10073 // will be type-legalized to complex code sequences.
10074 // We perform this optimization only before the operation legalizer because we
10075 // may introduce illegal operations.
10076 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10079 unsigned NumInScalars = N->getNumOperands();
10081 EVT VT = N->getValueType(0);
10083 // Check to see if this is a BUILD_VECTOR of a bunch of values
10084 // which come from any_extend or zero_extend nodes. If so, we can create
10085 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10086 // optimizations. We do not handle sign-extend because we can't fill the sign
10088 EVT SourceType = MVT::Other;
10089 bool AllAnyExt = true;
10091 for (unsigned i = 0; i != NumInScalars; ++i) {
10092 SDValue In = N->getOperand(i);
10093 // Ignore undef inputs.
10094 if (In.getOpcode() == ISD::UNDEF) continue;
10096 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
10097 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10099 // Abort if the element is not an extension.
10100 if (!ZeroExt && !AnyExt) {
10101 SourceType = MVT::Other;
10105 // The input is a ZeroExt or AnyExt. Check the original type.
10106 EVT InTy = In.getOperand(0).getValueType();
10108 // Check that all of the widened source types are the same.
10109 if (SourceType == MVT::Other)
10112 else if (InTy != SourceType) {
10113 // Multiple income types. Abort.
10114 SourceType = MVT::Other;
10118 // Check if all of the extends are ANY_EXTENDs.
10119 AllAnyExt &= AnyExt;
10122 // In order to have valid types, all of the inputs must be extended from the
10123 // same source type and all of the inputs must be any or zero extend.
10124 // Scalar sizes must be a power of two.
10125 EVT OutScalarTy = VT.getScalarType();
10126 bool ValidTypes = SourceType != MVT::Other &&
10127 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10128 isPowerOf2_32(SourceType.getSizeInBits());
10130 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10131 // turn into a single shuffle instruction.
10135 bool isLE = TLI.isLittleEndian();
10136 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10137 assert(ElemRatio > 1 && "Invalid element size ratio");
10138 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10139 DAG.getConstant(0, SourceType);
10141 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10142 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10144 // Populate the new build_vector
10145 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10146 SDValue Cast = N->getOperand(i);
10147 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10148 Cast.getOpcode() == ISD::ZERO_EXTEND ||
10149 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10151 if (Cast.getOpcode() == ISD::UNDEF)
10152 In = DAG.getUNDEF(SourceType);
10154 In = Cast->getOperand(0);
10155 unsigned Index = isLE ? (i * ElemRatio) :
10156 (i * ElemRatio + (ElemRatio - 1));
10158 assert(Index < Ops.size() && "Invalid index");
10162 // The type of the new BUILD_VECTOR node.
10163 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10164 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10165 "Invalid vector size");
10166 // Check if the new vector type is legal.
10167 if (!isTypeLegal(VecVT)) return SDValue();
10169 // Make the new BUILD_VECTOR.
10170 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10172 // The new BUILD_VECTOR node has the potential to be further optimized.
10173 AddToWorklist(BV.getNode());
10174 // Bitcast to the desired type.
10175 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10178 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10179 EVT VT = N->getValueType(0);
10181 unsigned NumInScalars = N->getNumOperands();
10184 EVT SrcVT = MVT::Other;
10185 unsigned Opcode = ISD::DELETED_NODE;
10186 unsigned NumDefs = 0;
10188 for (unsigned i = 0; i != NumInScalars; ++i) {
10189 SDValue In = N->getOperand(i);
10190 unsigned Opc = In.getOpcode();
10192 if (Opc == ISD::UNDEF)
10195 // If all scalar values are floats and converted from integers.
10196 if (Opcode == ISD::DELETED_NODE &&
10197 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10204 EVT InVT = In.getOperand(0).getValueType();
10206 // If all scalar values are typed differently, bail out. It's chosen to
10207 // simplify BUILD_VECTOR of integer types.
10208 if (SrcVT == MVT::Other)
10215 // If the vector has just one element defined, it's not worth to fold it into
10216 // a vectorized one.
10220 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10221 && "Should only handle conversion from integer to float.");
10222 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10224 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10226 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10229 SmallVector<SDValue, 8> Opnds;
10230 for (unsigned i = 0; i != NumInScalars; ++i) {
10231 SDValue In = N->getOperand(i);
10233 if (In.getOpcode() == ISD::UNDEF)
10234 Opnds.push_back(DAG.getUNDEF(SrcVT));
10236 Opnds.push_back(In.getOperand(0));
10238 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10239 AddToWorklist(BV.getNode());
10241 return DAG.getNode(Opcode, dl, VT, BV);
10244 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10245 unsigned NumInScalars = N->getNumOperands();
10247 EVT VT = N->getValueType(0);
10249 // A vector built entirely of undefs is undef.
10250 if (ISD::allOperandsUndef(N))
10251 return DAG.getUNDEF(VT);
10253 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10257 V = reduceBuildVecConvertToConvertBuildVec(N);
10261 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10262 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10263 // at most two distinct vectors, turn this into a shuffle node.
10265 // May only combine to shuffle after legalize if shuffle is legal.
10266 if (LegalOperations &&
10267 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10270 SDValue VecIn1, VecIn2;
10271 for (unsigned i = 0; i != NumInScalars; ++i) {
10272 // Ignore undef inputs.
10273 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10275 // If this input is something other than a EXTRACT_VECTOR_ELT with a
10276 // constant index, bail out.
10277 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10278 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10279 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10283 // We allow up to two distinct input vectors.
10284 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10285 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10288 if (!VecIn1.getNode()) {
10289 VecIn1 = ExtractedFromVec;
10290 } else if (!VecIn2.getNode()) {
10291 VecIn2 = ExtractedFromVec;
10293 // Too many inputs.
10294 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10299 // If everything is good, we can make a shuffle operation.
10300 if (VecIn1.getNode()) {
10301 SmallVector<int, 8> Mask;
10302 for (unsigned i = 0; i != NumInScalars; ++i) {
10303 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10304 Mask.push_back(-1);
10308 // If extracting from the first vector, just use the index directly.
10309 SDValue Extract = N->getOperand(i);
10310 SDValue ExtVal = Extract.getOperand(1);
10311 if (Extract.getOperand(0) == VecIn1) {
10312 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10313 if (ExtIndex > VT.getVectorNumElements())
10316 Mask.push_back(ExtIndex);
10320 // Otherwise, use InIdx + VecSize
10321 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10322 Mask.push_back(Idx+NumInScalars);
10325 // We can't generate a shuffle node with mismatched input and output types.
10326 // Attempt to transform a single input vector to the correct type.
10327 if ((VT != VecIn1.getValueType())) {
10328 // We don't support shuffeling between TWO values of different types.
10329 if (VecIn2.getNode())
10332 // We only support widening of vectors which are half the size of the
10333 // output registers. For example XMM->YMM widening on X86 with AVX.
10334 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10337 // If the input vector type has a different base type to the output
10338 // vector type, bail out.
10339 if (VecIn1.getValueType().getVectorElementType() !=
10340 VT.getVectorElementType())
10343 // Widen the input vector by adding undef values.
10344 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10345 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10348 // If VecIn2 is unused then change it to undef.
10349 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10351 // Check that we were able to transform all incoming values to the same
10353 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10354 VecIn1.getValueType() != VT)
10357 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10358 if (!isTypeLegal(VT))
10361 // Return the new VECTOR_SHUFFLE node.
10365 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10371 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10372 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10373 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10374 // inputs come from at most two distinct vectors, turn this into a shuffle
10377 // If we only have one input vector, we don't need to do any concatenation.
10378 if (N->getNumOperands() == 1)
10379 return N->getOperand(0);
10381 // Check if all of the operands are undefs.
10382 EVT VT = N->getValueType(0);
10383 if (ISD::allOperandsUndef(N))
10384 return DAG.getUNDEF(VT);
10386 // Optimize concat_vectors where one of the vectors is undef.
10387 if (N->getNumOperands() == 2 &&
10388 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10389 SDValue In = N->getOperand(0);
10390 assert(In.getValueType().isVector() && "Must concat vectors");
10392 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10393 if (In->getOpcode() == ISD::BITCAST &&
10394 !In->getOperand(0)->getValueType(0).isVector()) {
10395 SDValue Scalar = In->getOperand(0);
10396 EVT SclTy = Scalar->getValueType(0);
10398 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10401 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10402 VT.getSizeInBits() / SclTy.getSizeInBits());
10403 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10406 SDLoc dl = SDLoc(N);
10407 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10408 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10412 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10413 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10414 if (N->getNumOperands() == 2 &&
10415 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10416 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10417 EVT VT = N->getValueType(0);
10418 SDValue N0 = N->getOperand(0);
10419 SDValue N1 = N->getOperand(1);
10420 SmallVector<SDValue, 8> Opnds;
10421 unsigned BuildVecNumElts = N0.getNumOperands();
10423 EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10424 EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10425 if (SclTy0.isFloatingPoint()) {
10426 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10427 Opnds.push_back(N0.getOperand(i));
10428 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10429 Opnds.push_back(N1.getOperand(i));
10431 // If BUILD_VECTOR are from built from integer, they may have different
10432 // operand types. Get the smaller type and truncate all operands to it.
10433 EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10434 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10435 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10436 N0.getOperand(i)));
10437 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10438 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10439 N1.getOperand(i)));
10442 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10445 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10446 // nodes often generate nop CONCAT_VECTOR nodes.
10447 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10448 // place the incoming vectors at the exact same location.
10449 SDValue SingleSource = SDValue();
10450 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10452 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10453 SDValue Op = N->getOperand(i);
10455 if (Op.getOpcode() == ISD::UNDEF)
10458 // Check if this is the identity extract:
10459 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10462 // Find the single incoming vector for the extract_subvector.
10463 if (SingleSource.getNode()) {
10464 if (Op.getOperand(0) != SingleSource)
10467 SingleSource = Op.getOperand(0);
10469 // Check the source type is the same as the type of the result.
10470 // If not, this concat may extend the vector, so we can not
10471 // optimize it away.
10472 if (SingleSource.getValueType() != N->getValueType(0))
10476 unsigned IdentityIndex = i * PartNumElem;
10477 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10478 // The extract index must be constant.
10482 // Check that we are reading from the identity index.
10483 if (CS->getZExtValue() != IdentityIndex)
10487 if (SingleSource.getNode())
10488 return SingleSource;
10493 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10494 EVT NVT = N->getValueType(0);
10495 SDValue V = N->getOperand(0);
10497 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10499 // (extract_subvec (concat V1, V2, ...), i)
10502 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10504 if (V->getOperand(0).getValueType() != NVT)
10506 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10507 unsigned NumElems = NVT.getVectorNumElements();
10508 assert((Idx % NumElems) == 0 &&
10509 "IDX in concat is not a multiple of the result vector length.");
10510 return V->getOperand(Idx / NumElems);
10514 if (V->getOpcode() == ISD::BITCAST)
10515 V = V.getOperand(0);
10517 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10519 // Handle only simple case where vector being inserted and vector
10520 // being extracted are of same type, and are half size of larger vectors.
10521 EVT BigVT = V->getOperand(0).getValueType();
10522 EVT SmallVT = V->getOperand(1).getValueType();
10523 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10526 // Only handle cases where both indexes are constants with the same type.
10527 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10528 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10530 if (InsIdx && ExtIdx &&
10531 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10532 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10534 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10536 // indices are equal or bit offsets are equal => V1
10537 // otherwise => (extract_subvec V1, ExtIdx)
10538 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10539 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10540 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10541 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10542 DAG.getNode(ISD::BITCAST, dl,
10543 N->getOperand(0).getValueType(),
10544 V->getOperand(0)), N->getOperand(1));
10551 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10552 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10553 EVT VT = N->getValueType(0);
10554 unsigned NumElts = VT.getVectorNumElements();
10556 SDValue N0 = N->getOperand(0);
10557 SDValue N1 = N->getOperand(1);
10558 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10560 SmallVector<SDValue, 4> Ops;
10561 EVT ConcatVT = N0.getOperand(0).getValueType();
10562 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10563 unsigned NumConcats = NumElts / NumElemsPerConcat;
10565 // Look at every vector that's inserted. We're looking for exact
10566 // subvector-sized copies from a concatenated vector
10567 for (unsigned I = 0; I != NumConcats; ++I) {
10568 // Make sure we're dealing with a copy.
10569 unsigned Begin = I * NumElemsPerConcat;
10570 bool AllUndef = true, NoUndef = true;
10571 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10572 if (SVN->getMaskElt(J) >= 0)
10579 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10582 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10583 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10586 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10587 if (FirstElt < N0.getNumOperands())
10588 Ops.push_back(N0.getOperand(FirstElt));
10590 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10592 } else if (AllUndef) {
10593 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10594 } else { // Mixed with general masks and undefs, can't do optimization.
10599 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10602 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10603 EVT VT = N->getValueType(0);
10604 unsigned NumElts = VT.getVectorNumElements();
10606 SDValue N0 = N->getOperand(0);
10607 SDValue N1 = N->getOperand(1);
10609 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10611 // Canonicalize shuffle undef, undef -> undef
10612 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10613 return DAG.getUNDEF(VT);
10615 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10617 // Canonicalize shuffle v, v -> v, undef
10619 SmallVector<int, 8> NewMask;
10620 for (unsigned i = 0; i != NumElts; ++i) {
10621 int Idx = SVN->getMaskElt(i);
10622 if (Idx >= (int)NumElts) Idx -= NumElts;
10623 NewMask.push_back(Idx);
10625 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10629 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10630 if (N0.getOpcode() == ISD::UNDEF) {
10631 SmallVector<int, 8> NewMask;
10632 for (unsigned i = 0; i != NumElts; ++i) {
10633 int Idx = SVN->getMaskElt(i);
10635 if (Idx >= (int)NumElts)
10638 Idx = -1; // remove reference to lhs
10640 NewMask.push_back(Idx);
10642 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10646 // Remove references to rhs if it is undef
10647 if (N1.getOpcode() == ISD::UNDEF) {
10648 bool Changed = false;
10649 SmallVector<int, 8> NewMask;
10650 for (unsigned i = 0; i != NumElts; ++i) {
10651 int Idx = SVN->getMaskElt(i);
10652 if (Idx >= (int)NumElts) {
10656 NewMask.push_back(Idx);
10659 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10662 // If it is a splat, check if the argument vector is another splat or a
10663 // build_vector with all scalar elements the same.
10664 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10665 SDNode *V = N0.getNode();
10667 // If this is a bit convert that changes the element type of the vector but
10668 // not the number of vector elements, look through it. Be careful not to
10669 // look though conversions that change things like v4f32 to v2f64.
10670 if (V->getOpcode() == ISD::BITCAST) {
10671 SDValue ConvInput = V->getOperand(0);
10672 if (ConvInput.getValueType().isVector() &&
10673 ConvInput.getValueType().getVectorNumElements() == NumElts)
10674 V = ConvInput.getNode();
10677 if (V->getOpcode() == ISD::BUILD_VECTOR) {
10678 assert(V->getNumOperands() == NumElts &&
10679 "BUILD_VECTOR has wrong number of operands");
10681 bool AllSame = true;
10682 for (unsigned i = 0; i != NumElts; ++i) {
10683 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10684 Base = V->getOperand(i);
10688 // Splat of <u, u, u, u>, return <u, u, u, u>
10689 if (!Base.getNode())
10691 for (unsigned i = 0; i != NumElts; ++i) {
10692 if (V->getOperand(i) != Base) {
10697 // Splat of <x, x, x, x>, return <x, x, x, x>
10703 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10704 Level < AfterLegalizeVectorOps &&
10705 (N1.getOpcode() == ISD::UNDEF ||
10706 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10707 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10708 SDValue V = partitionShuffleOfConcats(N, DAG);
10714 // If this shuffle node is simply a swizzle of another shuffle node,
10715 // then try to simplify it.
10716 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10717 N1.getOpcode() == ISD::UNDEF) {
10719 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10721 // The incoming shuffle must be of the same type as the result of the
10722 // current shuffle.
10723 assert(OtherSV->getOperand(0).getValueType() == VT &&
10724 "Shuffle types don't match");
10726 SmallVector<int, 4> Mask;
10727 // Compute the combined shuffle mask.
10728 for (unsigned i = 0; i != NumElts; ++i) {
10729 int Idx = SVN->getMaskElt(i);
10730 assert(Idx < (int)NumElts && "Index references undef operand");
10731 // Next, this index comes from the first value, which is the incoming
10732 // shuffle. Adopt the incoming index.
10734 Idx = OtherSV->getMaskElt(Idx);
10735 Mask.push_back(Idx);
10738 bool CommuteOperands = false;
10739 if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
10740 // To be valid, the combine shuffle mask should only reference elements
10741 // from one of the two vectors in input to the inner shufflevector.
10742 bool IsValidMask = true;
10743 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10744 // See if the combined mask only reference undefs or elements coming
10745 // from the first shufflevector operand.
10746 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
10748 if (!IsValidMask) {
10749 IsValidMask = true;
10750 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10751 // Check that all the elements come from the second shuffle operand.
10752 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
10753 CommuteOperands = IsValidMask;
10756 // Early exit if the combined shuffle mask is not valid.
10761 // See if this pair of shuffles can be safely folded according to either
10762 // of the following rules:
10763 // shuffle(shuffle(x, y), undef) -> x
10764 // shuffle(shuffle(x, undef), undef) -> x
10765 // shuffle(shuffle(x, y), undef) -> y
10766 bool IsIdentityMask = true;
10767 unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
10768 for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
10773 // The combined shuffle must map each index to itself.
10774 IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
10777 if (IsIdentityMask) {
10778 if (CommuteOperands)
10779 // optimize shuffle(shuffle(x, y), undef) -> y.
10780 return OtherSV->getOperand(1);
10782 // optimize shuffle(shuffle(x, undef), undef) -> x
10783 // optimize shuffle(shuffle(x, y), undef) -> x
10784 return OtherSV->getOperand(0);
10787 // It may still be beneficial to combine the two shuffles if the
10788 // resulting shuffle is legal.
10789 if (TLI.isTypeLegal(VT) && TLI.isShuffleMaskLegal(Mask, VT)) {
10790 if (!CommuteOperands)
10791 // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
10792 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
10793 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
10796 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(undef, y, M3)
10797 return DAG.getVectorShuffle(VT, SDLoc(N), N1, N0->getOperand(1),
10802 // Canonicalize shuffles according to rules:
10803 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
10804 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
10805 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
10806 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
10807 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10808 TLI.isTypeLegal(VT)) {
10809 // The incoming shuffle must be of the same type as the result of the
10810 // current shuffle.
10811 assert(N1->getOperand(0).getValueType() == VT &&
10812 "Shuffle types don't match");
10814 SDValue SV0 = N1->getOperand(0);
10815 SDValue SV1 = N1->getOperand(1);
10816 bool HasSameOp0 = N0 == SV0;
10817 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10818 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
10819 // Commute the operands of this shuffle so that next rule
10821 return DAG.getCommutedVectorShuffle(*SVN);
10824 // Try to fold according to rules:
10825 // shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
10826 // shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
10827 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10828 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10829 // Don't try to fold shuffles with illegal type.
10830 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10831 N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
10832 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10834 // The incoming shuffle must be of the same type as the result of the
10835 // current shuffle.
10836 assert(OtherSV->getOperand(0).getValueType() == VT &&
10837 "Shuffle types don't match");
10839 SDValue SV0 = OtherSV->getOperand(0);
10840 SDValue SV1 = OtherSV->getOperand(1);
10841 bool HasSameOp0 = N1 == SV0;
10842 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10843 if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
10847 SmallVector<int, 4> Mask;
10848 // Compute the combined shuffle mask for a shuffle with SV0 as the first
10849 // operand, and SV1 as the second operand.
10850 for (unsigned i = 0; i != NumElts; ++i) {
10851 int Idx = SVN->getMaskElt(i);
10853 // Propagate Undef.
10854 Mask.push_back(Idx);
10858 if (Idx < (int)NumElts) {
10859 Idx = OtherSV->getMaskElt(Idx);
10860 if (IsSV1Undef && Idx >= (int) NumElts)
10861 Idx = -1; // Propagate Undef.
10863 Idx = HasSameOp0 ? Idx - NumElts : Idx;
10865 Mask.push_back(Idx);
10868 // Avoid introducing shuffles with illegal mask.
10869 if (TLI.isShuffleMaskLegal(Mask, VT)) {
10871 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10872 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10873 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
10874 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
10881 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10882 SDValue N0 = N->getOperand(0);
10883 SDValue N2 = N->getOperand(2);
10885 // If the input vector is a concatenation, and the insert replaces
10886 // one of the halves, we can optimize into a single concat_vectors.
10887 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10888 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10889 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10890 EVT VT = N->getValueType(0);
10892 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10893 // (concat_vectors Z, Y)
10895 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10896 N->getOperand(1), N0.getOperand(1));
10898 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10899 // (concat_vectors X, Z)
10900 if (InsIdx == VT.getVectorNumElements()/2)
10901 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10902 N0.getOperand(0), N->getOperand(1));
10908 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10909 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10910 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10911 /// vector_shuffle V, Zero, <0, 4, 2, 4>
10912 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10913 EVT VT = N->getValueType(0);
10915 SDValue LHS = N->getOperand(0);
10916 SDValue RHS = N->getOperand(1);
10917 if (N->getOpcode() == ISD::AND) {
10918 if (RHS.getOpcode() == ISD::BITCAST)
10919 RHS = RHS.getOperand(0);
10920 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10921 SmallVector<int, 8> Indices;
10922 unsigned NumElts = RHS.getNumOperands();
10923 for (unsigned i = 0; i != NumElts; ++i) {
10924 SDValue Elt = RHS.getOperand(i);
10925 if (!isa<ConstantSDNode>(Elt))
10928 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10929 Indices.push_back(i);
10930 else if (cast<ConstantSDNode>(Elt)->isNullValue())
10931 Indices.push_back(NumElts);
10936 // Let's see if the target supports this vector_shuffle.
10937 EVT RVT = RHS.getValueType();
10938 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10941 // Return the new VECTOR_SHUFFLE node.
10942 EVT EltVT = RVT.getVectorElementType();
10943 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10944 DAG.getConstant(0, EltVT));
10945 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
10946 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10947 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10948 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10955 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10956 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10957 assert(N->getValueType(0).isVector() &&
10958 "SimplifyVBinOp only works on vectors!");
10960 SDValue LHS = N->getOperand(0);
10961 SDValue RHS = N->getOperand(1);
10962 SDValue Shuffle = XformToShuffleWithZero(N);
10963 if (Shuffle.getNode()) return Shuffle;
10965 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10967 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10968 RHS.getOpcode() == ISD::BUILD_VECTOR) {
10969 // Check if both vectors are constants. If not bail out.
10970 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10971 cast<BuildVectorSDNode>(RHS)->isConstant()))
10974 SmallVector<SDValue, 8> Ops;
10975 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10976 SDValue LHSOp = LHS.getOperand(i);
10977 SDValue RHSOp = RHS.getOperand(i);
10979 // Can't fold divide by zero.
10980 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10981 N->getOpcode() == ISD::FDIV) {
10982 if ((RHSOp.getOpcode() == ISD::Constant &&
10983 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10984 (RHSOp.getOpcode() == ISD::ConstantFP &&
10985 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10989 EVT VT = LHSOp.getValueType();
10990 EVT RVT = RHSOp.getValueType();
10992 // Integer BUILD_VECTOR operands may have types larger than the element
10993 // size (e.g., when the element type is not legal). Prior to type
10994 // legalization, the types may not match between the two BUILD_VECTORS.
10995 // Truncate one of the operands to make them match.
10996 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10997 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10999 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
11003 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
11005 if (FoldOp.getOpcode() != ISD::UNDEF &&
11006 FoldOp.getOpcode() != ISD::Constant &&
11007 FoldOp.getOpcode() != ISD::ConstantFP)
11009 Ops.push_back(FoldOp);
11010 AddToWorklist(FoldOp.getNode());
11013 if (Ops.size() == LHS.getNumOperands())
11014 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11017 // Type legalization might introduce new shuffles in the DAG.
11018 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11019 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
11020 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11021 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11022 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11023 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11024 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11025 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11027 if (SVN0->getMask().equals(SVN1->getMask())) {
11028 EVT VT = N->getValueType(0);
11029 SDValue UndefVector = LHS.getOperand(1);
11030 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11031 LHS.getOperand(0), RHS.getOperand(0));
11032 AddUsersToWorklist(N);
11033 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11034 &SVN0->getMask()[0]);
11041 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
11042 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11043 assert(N->getValueType(0).isVector() &&
11044 "SimplifyVUnaryOp only works on vectors!");
11046 SDValue N0 = N->getOperand(0);
11048 if (N0.getOpcode() != ISD::BUILD_VECTOR)
11051 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11052 SmallVector<SDValue, 8> Ops;
11053 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11054 SDValue Op = N0.getOperand(i);
11055 if (Op.getOpcode() != ISD::UNDEF &&
11056 Op.getOpcode() != ISD::ConstantFP)
11058 EVT EltVT = Op.getValueType();
11059 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11060 if (FoldOp.getOpcode() != ISD::UNDEF &&
11061 FoldOp.getOpcode() != ISD::ConstantFP)
11063 Ops.push_back(FoldOp);
11064 AddToWorklist(FoldOp.getNode());
11067 if (Ops.size() != N0.getNumOperands())
11070 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11073 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11074 SDValue N1, SDValue N2){
11075 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11077 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11078 cast<CondCodeSDNode>(N0.getOperand(2))->get());
11080 // If we got a simplified select_cc node back from SimplifySelectCC, then
11081 // break it down into a new SETCC node, and a new SELECT node, and then return
11082 // the SELECT node, since we were called with a SELECT node.
11083 if (SCC.getNode()) {
11084 // Check to see if we got a select_cc back (to turn into setcc/select).
11085 // Otherwise, just return whatever node we got back, like fabs.
11086 if (SCC.getOpcode() == ISD::SELECT_CC) {
11087 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11089 SCC.getOperand(0), SCC.getOperand(1),
11090 SCC.getOperand(4));
11091 AddToWorklist(SETCC.getNode());
11092 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
11093 SCC.getOperand(2), SCC.getOperand(3), SETCC);
11101 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
11102 /// are the two values being selected between, see if we can simplify the
11103 /// select. Callers of this should assume that TheSelect is deleted if this
11104 /// returns true. As such, they should return the appropriate thing (e.g. the
11105 /// node) back to the top-level of the DAG combiner loop to avoid it being
11107 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11110 // Cannot simplify select with vector condition
11111 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11113 // If this is a select from two identical things, try to pull the operation
11114 // through the select.
11115 if (LHS.getOpcode() != RHS.getOpcode() ||
11116 !LHS.hasOneUse() || !RHS.hasOneUse())
11119 // If this is a load and the token chain is identical, replace the select
11120 // of two loads with a load through a select of the address to load from.
11121 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11122 // constants have been dropped into the constant pool.
11123 if (LHS.getOpcode() == ISD::LOAD) {
11124 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11125 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11127 // Token chains must be identical.
11128 if (LHS.getOperand(0) != RHS.getOperand(0) ||
11129 // Do not let this transformation reduce the number of volatile loads.
11130 LLD->isVolatile() || RLD->isVolatile() ||
11131 // If this is an EXTLOAD, the VT's must match.
11132 LLD->getMemoryVT() != RLD->getMemoryVT() ||
11133 // If this is an EXTLOAD, the kind of extension must match.
11134 (LLD->getExtensionType() != RLD->getExtensionType() &&
11135 // The only exception is if one of the extensions is anyext.
11136 LLD->getExtensionType() != ISD::EXTLOAD &&
11137 RLD->getExtensionType() != ISD::EXTLOAD) ||
11138 // FIXME: this discards src value information. This is
11139 // over-conservative. It would be beneficial to be able to remember
11140 // both potential memory locations. Since we are discarding
11141 // src value info, don't do the transformation if the memory
11142 // locations are not in the default address space.
11143 LLD->getPointerInfo().getAddrSpace() != 0 ||
11144 RLD->getPointerInfo().getAddrSpace() != 0 ||
11145 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11146 LLD->getBasePtr().getValueType()))
11149 // Check that the select condition doesn't reach either load. If so,
11150 // folding this will induce a cycle into the DAG. If not, this is safe to
11151 // xform, so create a select of the addresses.
11153 if (TheSelect->getOpcode() == ISD::SELECT) {
11154 SDNode *CondNode = TheSelect->getOperand(0).getNode();
11155 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11156 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11158 // The loads must not depend on one another.
11159 if (LLD->isPredecessorOf(RLD) ||
11160 RLD->isPredecessorOf(LLD))
11162 Addr = DAG.getSelect(SDLoc(TheSelect),
11163 LLD->getBasePtr().getValueType(),
11164 TheSelect->getOperand(0), LLD->getBasePtr(),
11165 RLD->getBasePtr());
11166 } else { // Otherwise SELECT_CC
11167 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11168 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11170 if ((LLD->hasAnyUseOfValue(1) &&
11171 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11172 (RLD->hasAnyUseOfValue(1) &&
11173 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11176 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11177 LLD->getBasePtr().getValueType(),
11178 TheSelect->getOperand(0),
11179 TheSelect->getOperand(1),
11180 LLD->getBasePtr(), RLD->getBasePtr(),
11181 TheSelect->getOperand(4));
11185 // It is safe to replace the two loads if they have different alignments,
11186 // but the new load must be the minimum (most restrictive) alignment of the
11188 bool isInvariant = LLD->getAlignment() & RLD->getAlignment();
11189 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
11190 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11191 Load = DAG.getLoad(TheSelect->getValueType(0),
11193 // FIXME: Discards pointer and AA info.
11194 LLD->getChain(), Addr, MachinePointerInfo(),
11195 LLD->isVolatile(), LLD->isNonTemporal(),
11196 isInvariant, Alignment);
11198 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11199 RLD->getExtensionType() : LLD->getExtensionType(),
11201 TheSelect->getValueType(0),
11202 // FIXME: Discards pointer and AA info.
11203 LLD->getChain(), Addr, MachinePointerInfo(),
11204 LLD->getMemoryVT(), LLD->isVolatile(),
11205 LLD->isNonTemporal(), isInvariant, Alignment);
11208 // Users of the select now use the result of the load.
11209 CombineTo(TheSelect, Load);
11211 // Users of the old loads now use the new load's chain. We know the
11212 // old-load value is dead now.
11213 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11214 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11221 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
11222 /// where 'cond' is the comparison specified by CC.
11223 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11224 SDValue N2, SDValue N3,
11225 ISD::CondCode CC, bool NotExtCompare) {
11226 // (x ? y : y) -> y.
11227 if (N2 == N3) return N2;
11229 EVT VT = N2.getValueType();
11230 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11231 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11232 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11234 // Determine if the condition we're dealing with is constant
11235 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11236 N0, N1, CC, DL, false);
11237 if (SCC.getNode()) AddToWorklist(SCC.getNode());
11238 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11240 // fold select_cc true, x, y -> x
11241 if (SCCC && !SCCC->isNullValue())
11243 // fold select_cc false, x, y -> y
11244 if (SCCC && SCCC->isNullValue())
11247 // Check to see if we can simplify the select into an fabs node
11248 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11249 // Allow either -0.0 or 0.0
11250 if (CFP->getValueAPF().isZero()) {
11251 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11252 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11253 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11254 N2 == N3.getOperand(0))
11255 return DAG.getNode(ISD::FABS, DL, VT, N0);
11257 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11258 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11259 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11260 N2.getOperand(0) == N3)
11261 return DAG.getNode(ISD::FABS, DL, VT, N3);
11265 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11266 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11267 // in it. This is a win when the constant is not otherwise available because
11268 // it replaces two constant pool loads with one. We only do this if the FP
11269 // type is known to be legal, because if it isn't, then we are before legalize
11270 // types an we want the other legalization to happen first (e.g. to avoid
11271 // messing with soft float) and if the ConstantFP is not legal, because if
11272 // it is legal, we may not need to store the FP constant in a constant pool.
11273 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11274 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11275 if (TLI.isTypeLegal(N2.getValueType()) &&
11276 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11277 TargetLowering::Legal &&
11278 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11279 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11280 // If both constants have multiple uses, then we won't need to do an
11281 // extra load, they are likely around in registers for other users.
11282 (TV->hasOneUse() || FV->hasOneUse())) {
11283 Constant *Elts[] = {
11284 const_cast<ConstantFP*>(FV->getConstantFPValue()),
11285 const_cast<ConstantFP*>(TV->getConstantFPValue())
11287 Type *FPTy = Elts[0]->getType();
11288 const DataLayout &TD = *TLI.getDataLayout();
11290 // Create a ConstantArray of the two constants.
11291 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11292 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11293 TD.getPrefTypeAlignment(FPTy));
11294 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11296 // Get the offsets to the 0 and 1 element of the array so that we can
11297 // select between them.
11298 SDValue Zero = DAG.getIntPtrConstant(0);
11299 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11300 SDValue One = DAG.getIntPtrConstant(EltSize);
11302 SDValue Cond = DAG.getSetCC(DL,
11303 getSetCCResultType(N0.getValueType()),
11305 AddToWorklist(Cond.getNode());
11306 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11308 AddToWorklist(CstOffset.getNode());
11309 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11311 AddToWorklist(CPIdx.getNode());
11312 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11313 MachinePointerInfo::getConstantPool(), false,
11314 false, false, Alignment);
11319 // Check to see if we can perform the "gzip trick", transforming
11320 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11321 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11322 (N1C->isNullValue() || // (a < 0) ? b : 0
11323 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
11324 EVT XType = N0.getValueType();
11325 EVT AType = N2.getValueType();
11326 if (XType.bitsGE(AType)) {
11327 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11328 // single-bit constant.
11329 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11330 unsigned ShCtV = N2C->getAPIntValue().logBase2();
11331 ShCtV = XType.getSizeInBits()-ShCtV-1;
11332 SDValue ShCt = DAG.getConstant(ShCtV,
11333 getShiftAmountTy(N0.getValueType()));
11334 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11336 AddToWorklist(Shift.getNode());
11338 if (XType.bitsGT(AType)) {
11339 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11340 AddToWorklist(Shift.getNode());
11343 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11346 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11348 DAG.getConstant(XType.getSizeInBits()-1,
11349 getShiftAmountTy(N0.getValueType())));
11350 AddToWorklist(Shift.getNode());
11352 if (XType.bitsGT(AType)) {
11353 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11354 AddToWorklist(Shift.getNode());
11357 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11361 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11362 // where y is has a single bit set.
11363 // A plaintext description would be, we can turn the SELECT_CC into an AND
11364 // when the condition can be materialized as an all-ones register. Any
11365 // single bit-test can be materialized as an all-ones register with
11366 // shift-left and shift-right-arith.
11367 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11368 N0->getValueType(0) == VT &&
11369 N1C && N1C->isNullValue() &&
11370 N2C && N2C->isNullValue()) {
11371 SDValue AndLHS = N0->getOperand(0);
11372 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11373 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11374 // Shift the tested bit over the sign bit.
11375 APInt AndMask = ConstAndRHS->getAPIntValue();
11377 DAG.getConstant(AndMask.countLeadingZeros(),
11378 getShiftAmountTy(AndLHS.getValueType()));
11379 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11381 // Now arithmetic right shift it all the way over, so the result is either
11382 // all-ones, or zero.
11384 DAG.getConstant(AndMask.getBitWidth()-1,
11385 getShiftAmountTy(Shl.getValueType()));
11386 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11388 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11392 // fold select C, 16, 0 -> shl C, 4
11393 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11394 TLI.getBooleanContents(N0.getValueType()) ==
11395 TargetLowering::ZeroOrOneBooleanContent) {
11397 // If the caller doesn't want us to simplify this into a zext of a compare,
11399 if (NotExtCompare && N2C->getAPIntValue() == 1)
11402 // Get a SetCC of the condition
11403 // NOTE: Don't create a SETCC if it's not legal on this target.
11404 if (!LegalOperations ||
11405 TLI.isOperationLegal(ISD::SETCC,
11406 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11408 // cast from setcc result type to select result type
11410 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11412 if (N2.getValueType().bitsLT(SCC.getValueType()))
11413 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11414 N2.getValueType());
11416 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11417 N2.getValueType(), SCC);
11419 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11420 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11421 N2.getValueType(), SCC);
11424 AddToWorklist(SCC.getNode());
11425 AddToWorklist(Temp.getNode());
11427 if (N2C->getAPIntValue() == 1)
11430 // shl setcc result by log2 n2c
11431 return DAG.getNode(
11432 ISD::SHL, DL, N2.getValueType(), Temp,
11433 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11434 getShiftAmountTy(Temp.getValueType())));
11438 // Check to see if this is the equivalent of setcc
11439 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11440 // otherwise, go ahead with the folds.
11441 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11442 EVT XType = N0.getValueType();
11443 if (!LegalOperations ||
11444 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11445 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11446 if (Res.getValueType() != VT)
11447 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11451 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11452 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11453 (!LegalOperations ||
11454 TLI.isOperationLegal(ISD::CTLZ, XType))) {
11455 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11456 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11457 DAG.getConstant(Log2_32(XType.getSizeInBits()),
11458 getShiftAmountTy(Ctlz.getValueType())));
11460 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11461 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11462 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11463 XType, DAG.getConstant(0, XType), N0);
11464 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11465 return DAG.getNode(ISD::SRL, DL, XType,
11466 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11467 DAG.getConstant(XType.getSizeInBits()-1,
11468 getShiftAmountTy(XType)));
11470 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11471 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11472 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11473 DAG.getConstant(XType.getSizeInBits()-1,
11474 getShiftAmountTy(N0.getValueType())));
11475 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11479 // Check to see if this is an integer abs.
11480 // select_cc setg[te] X, 0, X, -X ->
11481 // select_cc setgt X, -1, X, -X ->
11482 // select_cc setl[te] X, 0, -X, X ->
11483 // select_cc setlt X, 1, -X, X ->
11484 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11486 ConstantSDNode *SubC = nullptr;
11487 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11488 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11489 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11490 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11491 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11492 (N1C->isOne() && CC == ISD::SETLT)) &&
11493 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11494 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11496 EVT XType = N0.getValueType();
11497 if (SubC && SubC->isNullValue() && XType.isInteger()) {
11498 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11500 DAG.getConstant(XType.getSizeInBits()-1,
11501 getShiftAmountTy(N0.getValueType())));
11502 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11504 AddToWorklist(Shift.getNode());
11505 AddToWorklist(Add.getNode());
11506 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11513 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11514 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11515 SDValue N1, ISD::CondCode Cond,
11516 SDLoc DL, bool foldBooleans) {
11517 TargetLowering::DAGCombinerInfo
11518 DagCombineInfo(DAG, Level, false, this);
11519 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11522 /// BuildSDIV - Given an ISD::SDIV node expressing a divide by constant, return
11523 /// a DAG expression to select that will generate the same value by multiplying
11524 /// by a magic number. See:
11525 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11526 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11527 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11531 // Avoid division by zero.
11532 if (!C->getAPIntValue())
11535 std::vector<SDNode*> Built;
11537 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11539 for (SDNode *N : Built)
11544 /// BuildSDIVPow2 - Given an ISD::SDIV node expressing a divide by constant
11545 /// power of 2, return a DAG expression to select that will generate the same
11546 /// value by right shifting.
11547 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
11548 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11552 // Avoid division by zero.
11553 if (!C->getAPIntValue())
11556 std::vector<SDNode *> Built;
11557 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
11559 for (SDNode *N : Built)
11564 /// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant,
11565 /// return a DAG expression to select that will generate the same value by
11566 /// multiplying by a magic number. See:
11567 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11568 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11569 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11573 // Avoid division by zero.
11574 if (!C->getAPIntValue())
11577 std::vector<SDNode*> Built;
11579 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11581 for (SDNode *N : Built)
11586 /// FindBaseOffset - Return true if base is a frame index, which is known not
11587 // to alias with anything but itself. Provides base object and offset as
11589 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11590 const GlobalValue *&GV, const void *&CV) {
11591 // Assume it is a primitive operation.
11592 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11594 // If it's an adding a simple constant then integrate the offset.
11595 if (Base.getOpcode() == ISD::ADD) {
11596 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11597 Base = Base.getOperand(0);
11598 Offset += C->getZExtValue();
11602 // Return the underlying GlobalValue, and update the Offset. Return false
11603 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11604 // by multiple nodes with different offsets.
11605 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11606 GV = G->getGlobal();
11607 Offset += G->getOffset();
11611 // Return the underlying Constant value, and update the Offset. Return false
11612 // for ConstantSDNodes since the same constant pool entry may be represented
11613 // by multiple nodes with different offsets.
11614 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11615 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11616 : (const void *)C->getConstVal();
11617 Offset += C->getOffset();
11620 // If it's any of the following then it can't alias with anything but itself.
11621 return isa<FrameIndexSDNode>(Base);
11624 /// isAlias - Return true if there is any possibility that the two addresses
11626 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11627 // If they are the same then they must be aliases.
11628 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11630 // If they are both volatile then they cannot be reordered.
11631 if (Op0->isVolatile() && Op1->isVolatile()) return true;
11633 // Gather base node and offset information.
11634 SDValue Base1, Base2;
11635 int64_t Offset1, Offset2;
11636 const GlobalValue *GV1, *GV2;
11637 const void *CV1, *CV2;
11638 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11639 Base1, Offset1, GV1, CV1);
11640 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11641 Base2, Offset2, GV2, CV2);
11643 // If they have a same base address then check to see if they overlap.
11644 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11645 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11646 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11648 // It is possible for different frame indices to alias each other, mostly
11649 // when tail call optimization reuses return address slots for arguments.
11650 // To catch this case, look up the actual index of frame indices to compute
11651 // the real alias relationship.
11652 if (isFrameIndex1 && isFrameIndex2) {
11653 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11654 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11655 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11656 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11657 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11660 // Otherwise, if we know what the bases are, and they aren't identical, then
11661 // we know they cannot alias.
11662 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11665 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11666 // compared to the size and offset of the access, we may be able to prove they
11667 // do not alias. This check is conservative for now to catch cases created by
11668 // splitting vector types.
11669 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11670 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11671 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11672 Op1->getMemoryVT().getSizeInBits() >> 3) &&
11673 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11674 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11675 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11677 // There is no overlap between these relatively aligned accesses of similar
11678 // size, return no alias.
11679 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11680 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11684 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11685 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11687 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11688 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11692 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11693 // Use alias analysis information.
11694 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11695 Op1->getSrcValueOffset());
11696 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11697 Op0->getSrcValueOffset() - MinOffset;
11698 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11699 Op1->getSrcValueOffset() - MinOffset;
11700 AliasAnalysis::AliasResult AAResult =
11701 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11703 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
11704 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11706 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
11707 if (AAResult == AliasAnalysis::NoAlias)
11711 // Otherwise we have to assume they alias.
11715 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11716 /// looking for aliasing nodes and adding them to the Aliases vector.
11717 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11718 SmallVectorImpl<SDValue> &Aliases) {
11719 SmallVector<SDValue, 8> Chains; // List of chains to visit.
11720 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
11722 // Get alias information for node.
11723 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11726 Chains.push_back(OriginalChain);
11727 unsigned Depth = 0;
11729 // Look at each chain and determine if it is an alias. If so, add it to the
11730 // aliases list. If not, then continue up the chain looking for the next
11732 while (!Chains.empty()) {
11733 SDValue Chain = Chains.back();
11736 // For TokenFactor nodes, look at each operand and only continue up the
11737 // chain until we find two aliases. If we've seen two aliases, assume we'll
11738 // find more and revert to original chain since the xform is unlikely to be
11741 // FIXME: The depth check could be made to return the last non-aliasing
11742 // chain we found before we hit a tokenfactor rather than the original
11744 if (Depth > 6 || Aliases.size() == 2) {
11746 Aliases.push_back(OriginalChain);
11750 // Don't bother if we've been before.
11751 if (!Visited.insert(Chain.getNode()))
11754 switch (Chain.getOpcode()) {
11755 case ISD::EntryToken:
11756 // Entry token is ideal chain operand, but handled in FindBetterChain.
11761 // Get alias information for Chain.
11762 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11763 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11765 // If chain is alias then stop here.
11766 if (!(IsLoad && IsOpLoad) &&
11767 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11768 Aliases.push_back(Chain);
11770 // Look further up the chain.
11771 Chains.push_back(Chain.getOperand(0));
11777 case ISD::TokenFactor:
11778 // We have to check each of the operands of the token factor for "small"
11779 // token factors, so we queue them up. Adding the operands to the queue
11780 // (stack) in reverse order maintains the original order and increases the
11781 // likelihood that getNode will find a matching token factor (CSE.)
11782 if (Chain.getNumOperands() > 16) {
11783 Aliases.push_back(Chain);
11786 for (unsigned n = Chain.getNumOperands(); n;)
11787 Chains.push_back(Chain.getOperand(--n));
11792 // For all other instructions we will just have to take what we can get.
11793 Aliases.push_back(Chain);
11798 // We need to be careful here to also search for aliases through the
11799 // value operand of a store, etc. Consider the following situation:
11801 // L1 = load Token1, %52
11802 // S1 = store Token1, L1, %51
11803 // L2 = load Token1, %52+8
11804 // S2 = store Token1, L2, %51+8
11805 // Token2 = Token(S1, S2)
11806 // L3 = load Token2, %53
11807 // S3 = store Token2, L3, %52
11808 // L4 = load Token2, %53+8
11809 // S4 = store Token2, L4, %52+8
11810 // If we search for aliases of S3 (which loads address %52), and we look
11811 // only through the chain, then we'll miss the trivial dependence on L1
11812 // (which also loads from %52). We then might change all loads and
11813 // stores to use Token1 as their chain operand, which could result in
11814 // copying %53 into %52 before copying %52 into %51 (which should
11817 // The problem is, however, that searching for such data dependencies
11818 // can become expensive, and the cost is not directly related to the
11819 // chain depth. Instead, we'll rule out such configurations here by
11820 // insisting that we've visited all chain users (except for users
11821 // of the original chain, which is not necessary). When doing this,
11822 // we need to look through nodes we don't care about (otherwise, things
11823 // like register copies will interfere with trivial cases).
11825 SmallVector<const SDNode *, 16> Worklist;
11826 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11827 IE = Visited.end(); I != IE; ++I)
11828 if (*I != OriginalChain.getNode())
11829 Worklist.push_back(*I);
11831 while (!Worklist.empty()) {
11832 const SDNode *M = Worklist.pop_back_val();
11834 // We have already visited M, and want to make sure we've visited any uses
11835 // of M that we care about. For uses that we've not visisted, and don't
11836 // care about, queue them to the worklist.
11838 for (SDNode::use_iterator UI = M->use_begin(),
11839 UIE = M->use_end(); UI != UIE; ++UI)
11840 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11841 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11842 // We've not visited this use, and we care about it (it could have an
11843 // ordering dependency with the original node).
11845 Aliases.push_back(OriginalChain);
11849 // We've not visited this use, but we don't care about it. Mark it as
11850 // visited and enqueue it to the worklist.
11851 Worklist.push_back(*UI);
11856 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11857 /// for a better chain (aliasing node.)
11858 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11859 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
11861 // Accumulate all the aliases to this node.
11862 GatherAllAliases(N, OldChain, Aliases);
11864 // If no operands then chain to entry token.
11865 if (Aliases.size() == 0)
11866 return DAG.getEntryNode();
11868 // If a single operand then chain to it. We don't need to revisit it.
11869 if (Aliases.size() == 1)
11872 // Construct a custom tailored token factor.
11873 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
11876 // SelectionDAG::Combine - This is the entry point for the file.
11878 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11879 CodeGenOpt::Level OptLevel) {
11880 /// run - This is the main entry point to this class.
11882 DAGCombiner(*this, AA, OptLevel).Run(Level);