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 #define DEBUG_TYPE "dagcombine"
20 #include "llvm/CodeGen/SelectionDAG.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/LLVMContext.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/PseudoSourceValue.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/Target/TargetFrameInfo.h"
29 #include "llvm/Target/TargetLowering.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetOptions.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/Support/Compiler.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/raw_ostream.h"
44 STATISTIC(NodesCombined , "Number of dag nodes combined");
45 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
46 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
47 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
51 CombinerAA("combiner-alias-analysis", cl::Hidden,
52 cl::desc("Turn on alias analysis during testing"));
55 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
56 cl::desc("Include global information in alias analysis"));
58 //------------------------------ DAGCombiner ---------------------------------//
60 class VISIBILITY_HIDDEN DAGCombiner {
62 const TargetLowering &TLI;
64 CodeGenOpt::Level OptLevel;
68 // Worklist of all of the nodes that need to be simplified.
69 std::vector<SDNode*> WorkList;
71 // AA - Used for DAG load/store alias analysis.
74 /// AddUsersToWorkList - When an instruction is simplified, add all users of
75 /// the instruction to the work lists because they might get more simplified
78 void AddUsersToWorkList(SDNode *N) {
79 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
84 /// visit - call the node-specific routine that knows how to fold each
85 /// particular type of node.
86 SDValue visit(SDNode *N);
89 /// AddToWorkList - Add to the work list making sure it's instance is at the
90 /// the back (next to be processed.)
91 void AddToWorkList(SDNode *N) {
92 removeFromWorkList(N);
93 WorkList.push_back(N);
96 /// removeFromWorkList - remove all instances of N from the worklist.
98 void removeFromWorkList(SDNode *N) {
99 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N),
103 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
106 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
107 return CombineTo(N, &Res, 1, AddTo);
110 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
112 SDValue To[] = { Res0, Res1 };
113 return CombineTo(N, To, 2, AddTo);
116 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
120 /// SimplifyDemandedBits - Check the specified integer node value to see if
121 /// it can be simplified or if things it uses can be simplified by bit
122 /// propagation. If so, return true.
123 bool SimplifyDemandedBits(SDValue Op) {
124 APInt Demanded = APInt::getAllOnesValue(Op.getValueSizeInBits());
125 return SimplifyDemandedBits(Op, Demanded);
128 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
130 bool CombineToPreIndexedLoadStore(SDNode *N);
131 bool CombineToPostIndexedLoadStore(SDNode *N);
134 /// combine - call the node-specific routine that knows how to fold each
135 /// particular type of node. If that doesn't do anything, try the
136 /// target-specific DAG combines.
137 SDValue combine(SDNode *N);
139 // Visitation implementation - Implement dag node combining for different
140 // node types. The semantics are as follows:
142 // SDValue.getNode() == 0 - No change was made
143 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
144 // otherwise - N should be replaced by the returned Operand.
146 SDValue visitTokenFactor(SDNode *N);
147 SDValue visitMERGE_VALUES(SDNode *N);
148 SDValue visitADD(SDNode *N);
149 SDValue visitSUB(SDNode *N);
150 SDValue visitADDC(SDNode *N);
151 SDValue visitADDE(SDNode *N);
152 SDValue visitMUL(SDNode *N);
153 SDValue visitSDIV(SDNode *N);
154 SDValue visitUDIV(SDNode *N);
155 SDValue visitSREM(SDNode *N);
156 SDValue visitUREM(SDNode *N);
157 SDValue visitMULHU(SDNode *N);
158 SDValue visitMULHS(SDNode *N);
159 SDValue visitSMUL_LOHI(SDNode *N);
160 SDValue visitUMUL_LOHI(SDNode *N);
161 SDValue visitSDIVREM(SDNode *N);
162 SDValue visitUDIVREM(SDNode *N);
163 SDValue visitAND(SDNode *N);
164 SDValue visitOR(SDNode *N);
165 SDValue visitXOR(SDNode *N);
166 SDValue SimplifyVBinOp(SDNode *N);
167 SDValue visitSHL(SDNode *N);
168 SDValue visitSRA(SDNode *N);
169 SDValue visitSRL(SDNode *N);
170 SDValue visitCTLZ(SDNode *N);
171 SDValue visitCTTZ(SDNode *N);
172 SDValue visitCTPOP(SDNode *N);
173 SDValue visitSELECT(SDNode *N);
174 SDValue visitSELECT_CC(SDNode *N);
175 SDValue visitSETCC(SDNode *N);
176 SDValue visitSIGN_EXTEND(SDNode *N);
177 SDValue visitZERO_EXTEND(SDNode *N);
178 SDValue visitANY_EXTEND(SDNode *N);
179 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
180 SDValue visitTRUNCATE(SDNode *N);
181 SDValue visitBIT_CONVERT(SDNode *N);
182 SDValue visitBUILD_PAIR(SDNode *N);
183 SDValue visitFADD(SDNode *N);
184 SDValue visitFSUB(SDNode *N);
185 SDValue visitFMUL(SDNode *N);
186 SDValue visitFDIV(SDNode *N);
187 SDValue visitFREM(SDNode *N);
188 SDValue visitFCOPYSIGN(SDNode *N);
189 SDValue visitSINT_TO_FP(SDNode *N);
190 SDValue visitUINT_TO_FP(SDNode *N);
191 SDValue visitFP_TO_SINT(SDNode *N);
192 SDValue visitFP_TO_UINT(SDNode *N);
193 SDValue visitFP_ROUND(SDNode *N);
194 SDValue visitFP_ROUND_INREG(SDNode *N);
195 SDValue visitFP_EXTEND(SDNode *N);
196 SDValue visitFNEG(SDNode *N);
197 SDValue visitFABS(SDNode *N);
198 SDValue visitBRCOND(SDNode *N);
199 SDValue visitBR_CC(SDNode *N);
200 SDValue visitLOAD(SDNode *N);
201 SDValue visitSTORE(SDNode *N);
202 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
203 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
204 SDValue visitBUILD_VECTOR(SDNode *N);
205 SDValue visitCONCAT_VECTORS(SDNode *N);
206 SDValue visitVECTOR_SHUFFLE(SDNode *N);
208 SDValue XformToShuffleWithZero(SDNode *N);
209 SDValue ReassociateOps(unsigned Opc, DebugLoc DL, SDValue LHS, SDValue RHS);
211 SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
213 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
214 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
215 SDValue SimplifySelect(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2);
216 SDValue SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2,
217 SDValue N3, ISD::CondCode CC,
218 bool NotExtCompare = false);
219 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
220 DebugLoc DL, bool foldBooleans = true);
221 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
223 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
224 SDValue ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *, EVT);
225 SDValue BuildSDIV(SDNode *N);
226 SDValue BuildUDIV(SDNode *N);
227 SDNode *MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL);
228 SDValue ReduceLoadWidth(SDNode *N);
229 SDValue ReduceLoadOpStoreWidth(SDNode *N);
231 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
233 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
234 /// looking for aliasing nodes and adding them to the Aliases vector.
235 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
236 SmallVector<SDValue, 8> &Aliases);
238 /// isAlias - Return true if there is any possibility that the two addresses
240 bool isAlias(SDValue Ptr1, int64_t Size1,
241 const Value *SrcValue1, int SrcValueOffset1,
242 SDValue Ptr2, int64_t Size2,
243 const Value *SrcValue2, int SrcValueOffset2) const;
245 /// FindAliasInfo - Extracts the relevant alias information from the memory
246 /// node. Returns true if the operand was a load.
247 bool FindAliasInfo(SDNode *N,
248 SDValue &Ptr, int64_t &Size,
249 const Value *&SrcValue, int &SrcValueOffset) const;
251 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
252 /// looking for a better chain (aliasing node.)
253 SDValue FindBetterChain(SDNode *N, SDValue Chain);
255 /// getShiftAmountTy - Returns a type large enough to hold any valid
256 /// shift amount - before type legalization these can be huge.
257 EVT getShiftAmountTy() {
258 return LegalTypes ? TLI.getShiftAmountTy() : TLI.getPointerTy();
262 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
264 TLI(D.getTargetLoweringInfo()),
267 LegalOperations(false),
271 /// Run - runs the dag combiner on all nodes in the work list
272 void Run(CombineLevel AtLevel);
278 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
279 /// nodes from the worklist.
280 class VISIBILITY_HIDDEN WorkListRemover :
281 public SelectionDAG::DAGUpdateListener {
284 explicit WorkListRemover(DAGCombiner &dc) : DC(dc) {}
286 virtual void NodeDeleted(SDNode *N, SDNode *E) {
287 DC.removeFromWorkList(N);
290 virtual void NodeUpdated(SDNode *N) {
296 //===----------------------------------------------------------------------===//
297 // TargetLowering::DAGCombinerInfo implementation
298 //===----------------------------------------------------------------------===//
300 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
301 ((DAGCombiner*)DC)->AddToWorkList(N);
304 SDValue TargetLowering::DAGCombinerInfo::
305 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
306 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
309 SDValue TargetLowering::DAGCombinerInfo::
310 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
311 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
315 SDValue TargetLowering::DAGCombinerInfo::
316 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
317 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
320 void TargetLowering::DAGCombinerInfo::
321 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
322 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
325 //===----------------------------------------------------------------------===//
327 //===----------------------------------------------------------------------===//
329 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
330 /// specified expression for the same cost as the expression itself, or 2 if we
331 /// can compute the negated form more cheaply than the expression itself.
332 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
333 unsigned Depth = 0) {
334 // No compile time optimizations on this type.
335 if (Op.getValueType() == MVT::ppcf128)
338 // fneg is removable even if it has multiple uses.
339 if (Op.getOpcode() == ISD::FNEG) return 2;
341 // Don't allow anything with multiple uses.
342 if (!Op.hasOneUse()) return 0;
344 // Don't recurse exponentially.
345 if (Depth > 6) return 0;
347 switch (Op.getOpcode()) {
348 default: return false;
349 case ISD::ConstantFP:
350 // Don't invert constant FP values after legalize. The negated constant
351 // isn't necessarily legal.
352 return LegalOperations ? 0 : 1;
354 // FIXME: determine better conditions for this xform.
355 if (!UnsafeFPMath) return 0;
357 // fold (fsub (fadd A, B)) -> (fsub (fneg A), B)
358 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
360 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
361 return isNegatibleForFree(Op.getOperand(1), LegalOperations, Depth+1);
363 // We can't turn -(A-B) into B-A when we honor signed zeros.
364 if (!UnsafeFPMath) return 0;
366 // fold (fneg (fsub A, B)) -> (fsub B, A)
371 if (HonorSignDependentRoundingFPMath()) return 0;
373 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
374 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
377 return isNegatibleForFree(Op.getOperand(1), LegalOperations, Depth+1);
382 return isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1);
386 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
387 /// returns the newly negated expression.
388 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
389 bool LegalOperations, unsigned Depth = 0) {
390 // fneg is removable even if it has multiple uses.
391 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
393 // Don't allow anything with multiple uses.
394 assert(Op.hasOneUse() && "Unknown reuse!");
396 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
397 switch (Op.getOpcode()) {
398 default: llvm_unreachable("Unknown code");
399 case ISD::ConstantFP: {
400 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
402 return DAG.getConstantFP(V, Op.getValueType());
405 // FIXME: determine better conditions for this xform.
406 assert(UnsafeFPMath);
408 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
409 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
410 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
411 GetNegatedExpression(Op.getOperand(0), DAG,
412 LegalOperations, Depth+1),
414 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
415 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
416 GetNegatedExpression(Op.getOperand(1), DAG,
417 LegalOperations, Depth+1),
420 // We can't turn -(A-B) into B-A when we honor signed zeros.
421 assert(UnsafeFPMath);
423 // fold (fneg (fsub 0, B)) -> B
424 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
425 if (N0CFP->getValueAPF().isZero())
426 return Op.getOperand(1);
428 // fold (fneg (fsub A, B)) -> (fsub B, A)
429 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
430 Op.getOperand(1), Op.getOperand(0));
434 assert(!HonorSignDependentRoundingFPMath());
436 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
437 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
438 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
439 GetNegatedExpression(Op.getOperand(0), DAG,
440 LegalOperations, Depth+1),
443 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
444 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
446 GetNegatedExpression(Op.getOperand(1), DAG,
447 LegalOperations, Depth+1));
451 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
452 GetNegatedExpression(Op.getOperand(0), DAG,
453 LegalOperations, Depth+1));
455 return DAG.getNode(ISD::FP_ROUND, Op.getDebugLoc(), Op.getValueType(),
456 GetNegatedExpression(Op.getOperand(0), DAG,
457 LegalOperations, Depth+1),
463 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
464 // that selects between the values 1 and 0, making it equivalent to a setcc.
465 // Also, set the incoming LHS, RHS, and CC references to the appropriate
466 // nodes based on the type of node we are checking. This simplifies life a
467 // bit for the callers.
468 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
470 if (N.getOpcode() == ISD::SETCC) {
471 LHS = N.getOperand(0);
472 RHS = N.getOperand(1);
473 CC = N.getOperand(2);
476 if (N.getOpcode() == ISD::SELECT_CC &&
477 N.getOperand(2).getOpcode() == ISD::Constant &&
478 N.getOperand(3).getOpcode() == ISD::Constant &&
479 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
480 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
481 LHS = N.getOperand(0);
482 RHS = N.getOperand(1);
483 CC = N.getOperand(4);
489 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
490 // one use. If this is true, it allows the users to invert the operation for
491 // free when it is profitable to do so.
492 static bool isOneUseSetCC(SDValue N) {
494 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
499 SDValue DAGCombiner::ReassociateOps(unsigned Opc, DebugLoc DL,
500 SDValue N0, SDValue N1) {
501 EVT VT = N0.getValueType();
502 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
503 if (isa<ConstantSDNode>(N1)) {
504 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
506 DAG.FoldConstantArithmetic(Opc, VT,
507 cast<ConstantSDNode>(N0.getOperand(1)),
508 cast<ConstantSDNode>(N1));
509 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
510 } else if (N0.hasOneUse()) {
511 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
512 SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
513 N0.getOperand(0), N1);
514 AddToWorkList(OpNode.getNode());
515 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
519 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
520 if (isa<ConstantSDNode>(N0)) {
521 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
523 DAG.FoldConstantArithmetic(Opc, VT,
524 cast<ConstantSDNode>(N1.getOperand(1)),
525 cast<ConstantSDNode>(N0));
526 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
527 } else if (N1.hasOneUse()) {
528 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
529 SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
530 N1.getOperand(0), N0);
531 AddToWorkList(OpNode.getNode());
532 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
539 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
541 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
543 DEBUG(errs() << "\nReplacing.1 ";
545 errs() << "\nWith: ";
546 To[0].getNode()->dump(&DAG);
547 errs() << " and " << NumTo-1 << " other values\n";
548 for (unsigned i = 0, e = NumTo; i != e; ++i)
549 assert(N->getValueType(i) == To[i].getValueType() &&
550 "Cannot combine value to value of different type!"));
551 WorkListRemover DeadNodes(*this);
552 DAG.ReplaceAllUsesWith(N, To, &DeadNodes);
555 // Push the new nodes and any users onto the worklist
556 for (unsigned i = 0, e = NumTo; i != e; ++i) {
557 if (To[i].getNode()) {
558 AddToWorkList(To[i].getNode());
559 AddUsersToWorkList(To[i].getNode());
564 // Finally, if the node is now dead, remove it from the graph. The node
565 // may not be dead if the replacement process recursively simplified to
566 // something else needing this node.
567 if (N->use_empty()) {
568 // Nodes can be reintroduced into the worklist. Make sure we do not
569 // process a node that has been replaced.
570 removeFromWorkList(N);
572 // Finally, since the node is now dead, remove it from the graph.
575 return SDValue(N, 0);
579 DAGCombiner::CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &
581 // Replace all uses. If any nodes become isomorphic to other nodes and
582 // are deleted, make sure to remove them from our worklist.
583 WorkListRemover DeadNodes(*this);
584 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, &DeadNodes);
586 // Push the new node and any (possibly new) users onto the worklist.
587 AddToWorkList(TLO.New.getNode());
588 AddUsersToWorkList(TLO.New.getNode());
590 // Finally, if the node is now dead, remove it from the graph. The node
591 // may not be dead if the replacement process recursively simplified to
592 // something else needing this node.
593 if (TLO.Old.getNode()->use_empty()) {
594 removeFromWorkList(TLO.Old.getNode());
596 // If the operands of this node are only used by the node, they will now
597 // be dead. Make sure to visit them first to delete dead nodes early.
598 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
599 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
600 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
602 DAG.DeleteNode(TLO.Old.getNode());
606 /// SimplifyDemandedBits - Check the specified integer node value to see if
607 /// it can be simplified or if things it uses can be simplified by bit
608 /// propagation. If so, return true.
609 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
610 TargetLowering::TargetLoweringOpt TLO(DAG);
611 APInt KnownZero, KnownOne;
612 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
616 AddToWorkList(Op.getNode());
618 // Replace the old value with the new one.
620 DEBUG(errs() << "\nReplacing.2 ";
621 TLO.Old.getNode()->dump(&DAG);
622 errs() << "\nWith: ";
623 TLO.New.getNode()->dump(&DAG);
626 CommitTargetLoweringOpt(TLO);
630 //===----------------------------------------------------------------------===//
631 // Main DAG Combiner implementation
632 //===----------------------------------------------------------------------===//
634 void DAGCombiner::Run(CombineLevel AtLevel) {
635 // set the instance variables, so that the various visit routines may use it.
637 LegalOperations = Level >= NoIllegalOperations;
638 LegalTypes = Level >= NoIllegalTypes;
640 // Add all the dag nodes to the worklist.
641 WorkList.reserve(DAG.allnodes_size());
642 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
643 E = DAG.allnodes_end(); I != E; ++I)
644 WorkList.push_back(I);
646 // Create a dummy node (which is not added to allnodes), that adds a reference
647 // to the root node, preventing it from being deleted, and tracking any
648 // changes of the root.
649 HandleSDNode Dummy(DAG.getRoot());
651 // The root of the dag may dangle to deleted nodes until the dag combiner is
652 // done. Set it to null to avoid confusion.
653 DAG.setRoot(SDValue());
655 // while the worklist isn't empty, inspect the node on the end of it and
656 // try and combine it.
657 while (!WorkList.empty()) {
658 SDNode *N = WorkList.back();
661 // If N has no uses, it is dead. Make sure to revisit all N's operands once
662 // N is deleted from the DAG, since they too may now be dead or may have a
663 // reduced number of uses, allowing other xforms.
664 if (N->use_empty() && N != &Dummy) {
665 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
666 AddToWorkList(N->getOperand(i).getNode());
672 SDValue RV = combine(N);
674 if (RV.getNode() == 0)
679 // If we get back the same node we passed in, rather than a new node or
680 // zero, we know that the node must have defined multiple values and
681 // CombineTo was used. Since CombineTo takes care of the worklist
682 // mechanics for us, we have no work to do in this case.
683 if (RV.getNode() == N)
686 assert(N->getOpcode() != ISD::DELETED_NODE &&
687 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
688 "Node was deleted but visit returned new node!");
690 DEBUG(errs() << "\nReplacing.3 ";
692 errs() << "\nWith: ";
693 RV.getNode()->dump(&DAG);
695 WorkListRemover DeadNodes(*this);
696 if (N->getNumValues() == RV.getNode()->getNumValues())
697 DAG.ReplaceAllUsesWith(N, RV.getNode(), &DeadNodes);
699 assert(N->getValueType(0) == RV.getValueType() &&
700 N->getNumValues() == 1 && "Type mismatch");
702 DAG.ReplaceAllUsesWith(N, &OpV, &DeadNodes);
705 // Push the new node and any users onto the worklist
706 AddToWorkList(RV.getNode());
707 AddUsersToWorkList(RV.getNode());
709 // Add any uses of the old node to the worklist in case this node is the
710 // last one that uses them. They may become dead after this node is
712 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
713 AddToWorkList(N->getOperand(i).getNode());
715 // Finally, if the node is now dead, remove it from the graph. The node
716 // may not be dead if the replacement process recursively simplified to
717 // something else needing this node.
718 if (N->use_empty()) {
719 // Nodes can be reintroduced into the worklist. Make sure we do not
720 // process a node that has been replaced.
721 removeFromWorkList(N);
723 // Finally, since the node is now dead, remove it from the graph.
728 // If the root changed (e.g. it was a dead load, update the root).
729 DAG.setRoot(Dummy.getValue());
732 SDValue DAGCombiner::visit(SDNode *N) {
733 switch(N->getOpcode()) {
735 case ISD::TokenFactor: return visitTokenFactor(N);
736 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
737 case ISD::ADD: return visitADD(N);
738 case ISD::SUB: return visitSUB(N);
739 case ISD::ADDC: return visitADDC(N);
740 case ISD::ADDE: return visitADDE(N);
741 case ISD::MUL: return visitMUL(N);
742 case ISD::SDIV: return visitSDIV(N);
743 case ISD::UDIV: return visitUDIV(N);
744 case ISD::SREM: return visitSREM(N);
745 case ISD::UREM: return visitUREM(N);
746 case ISD::MULHU: return visitMULHU(N);
747 case ISD::MULHS: return visitMULHS(N);
748 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
749 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
750 case ISD::SDIVREM: return visitSDIVREM(N);
751 case ISD::UDIVREM: return visitUDIVREM(N);
752 case ISD::AND: return visitAND(N);
753 case ISD::OR: return visitOR(N);
754 case ISD::XOR: return visitXOR(N);
755 case ISD::SHL: return visitSHL(N);
756 case ISD::SRA: return visitSRA(N);
757 case ISD::SRL: return visitSRL(N);
758 case ISD::CTLZ: return visitCTLZ(N);
759 case ISD::CTTZ: return visitCTTZ(N);
760 case ISD::CTPOP: return visitCTPOP(N);
761 case ISD::SELECT: return visitSELECT(N);
762 case ISD::SELECT_CC: return visitSELECT_CC(N);
763 case ISD::SETCC: return visitSETCC(N);
764 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
765 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
766 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
767 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
768 case ISD::TRUNCATE: return visitTRUNCATE(N);
769 case ISD::BIT_CONVERT: return visitBIT_CONVERT(N);
770 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
771 case ISD::FADD: return visitFADD(N);
772 case ISD::FSUB: return visitFSUB(N);
773 case ISD::FMUL: return visitFMUL(N);
774 case ISD::FDIV: return visitFDIV(N);
775 case ISD::FREM: return visitFREM(N);
776 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
777 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
778 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
779 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
780 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
781 case ISD::FP_ROUND: return visitFP_ROUND(N);
782 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
783 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
784 case ISD::FNEG: return visitFNEG(N);
785 case ISD::FABS: return visitFABS(N);
786 case ISD::BRCOND: return visitBRCOND(N);
787 case ISD::BR_CC: return visitBR_CC(N);
788 case ISD::LOAD: return visitLOAD(N);
789 case ISD::STORE: return visitSTORE(N);
790 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
791 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
792 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
793 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
794 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
799 SDValue DAGCombiner::combine(SDNode *N) {
800 SDValue RV = visit(N);
802 // If nothing happened, try a target-specific DAG combine.
803 if (RV.getNode() == 0) {
804 assert(N->getOpcode() != ISD::DELETED_NODE &&
805 "Node was deleted but visit returned NULL!");
807 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
808 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
810 // Expose the DAG combiner to the target combiner impls.
811 TargetLowering::DAGCombinerInfo
812 DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
814 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
818 // If N is a commutative binary node, try commuting it to enable more
820 if (RV.getNode() == 0 &&
821 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
822 N->getNumValues() == 1) {
823 SDValue N0 = N->getOperand(0);
824 SDValue N1 = N->getOperand(1);
826 // Constant operands are canonicalized to RHS.
827 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
828 SDValue Ops[] = { N1, N0 };
829 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
832 return SDValue(CSENode, 0);
839 /// getInputChainForNode - Given a node, return its input chain if it has one,
840 /// otherwise return a null sd operand.
841 static SDValue getInputChainForNode(SDNode *N) {
842 if (unsigned NumOps = N->getNumOperands()) {
843 if (N->getOperand(0).getValueType() == MVT::Other)
844 return N->getOperand(0);
845 else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
846 return N->getOperand(NumOps-1);
847 for (unsigned i = 1; i < NumOps-1; ++i)
848 if (N->getOperand(i).getValueType() == MVT::Other)
849 return N->getOperand(i);
854 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
855 // If N has two operands, where one has an input chain equal to the other,
856 // the 'other' chain is redundant.
857 if (N->getNumOperands() == 2) {
858 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
859 return N->getOperand(0);
860 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
861 return N->getOperand(1);
864 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
865 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
866 SmallPtrSet<SDNode*, 16> SeenOps;
867 bool Changed = false; // If we should replace this token factor.
869 // Start out with this token factor.
872 // Iterate through token factors. The TFs grows when new token factors are
874 for (unsigned i = 0; i < TFs.size(); ++i) {
877 // Check each of the operands.
878 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
879 SDValue Op = TF->getOperand(i);
881 switch (Op.getOpcode()) {
882 case ISD::EntryToken:
883 // Entry tokens don't need to be added to the list. They are
888 case ISD::TokenFactor:
889 if ((CombinerAA || Op.hasOneUse()) &&
890 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
891 // Queue up for processing.
892 TFs.push_back(Op.getNode());
893 // Clean up in case the token factor is removed.
894 AddToWorkList(Op.getNode());
901 // Only add if it isn't already in the list.
902 if (SeenOps.insert(Op.getNode()))
913 // If we've change things around then replace token factor.
916 // The entry token is the only possible outcome.
917 Result = DAG.getEntryNode();
919 // New and improved token factor.
920 Result = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
921 MVT::Other, &Ops[0], Ops.size());
924 // Don't add users to work list.
925 return CombineTo(N, Result, false);
931 /// MERGE_VALUES can always be eliminated.
932 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
933 WorkListRemover DeadNodes(*this);
934 // Replacing results may cause a different MERGE_VALUES to suddenly
935 // be CSE'd with N, and carry its uses with it. Iterate until no
936 // uses remain, to ensure that the node can be safely deleted.
938 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
939 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i),
941 } while (!N->use_empty());
942 removeFromWorkList(N);
944 return SDValue(N, 0); // Return N so it doesn't get rechecked!
948 SDValue combineShlAddConstant(DebugLoc DL, SDValue N0, SDValue N1,
950 EVT VT = N0.getValueType();
951 SDValue N00 = N0.getOperand(0);
952 SDValue N01 = N0.getOperand(1);
953 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
955 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
956 isa<ConstantSDNode>(N00.getOperand(1))) {
957 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
958 N0 = DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT,
959 DAG.getNode(ISD::SHL, N00.getDebugLoc(), VT,
960 N00.getOperand(0), N01),
961 DAG.getNode(ISD::SHL, N01.getDebugLoc(), VT,
962 N00.getOperand(1), N01));
963 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
969 SDValue DAGCombiner::visitADD(SDNode *N) {
970 SDValue N0 = N->getOperand(0);
971 SDValue N1 = N->getOperand(1);
972 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
973 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
974 EVT VT = N0.getValueType();
978 SDValue FoldedVOp = SimplifyVBinOp(N);
979 if (FoldedVOp.getNode()) return FoldedVOp;
982 // fold (add x, undef) -> undef
983 if (N0.getOpcode() == ISD::UNDEF)
985 if (N1.getOpcode() == ISD::UNDEF)
987 // fold (add c1, c2) -> c1+c2
989 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
990 // canonicalize constant to RHS
992 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0);
993 // fold (add x, 0) -> x
994 if (N1C && N1C->isNullValue())
996 // fold (add Sym, c) -> Sym+c
997 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
998 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
999 GA->getOpcode() == ISD::GlobalAddress)
1000 return DAG.getGlobalAddress(GA->getGlobal(), VT,
1002 (uint64_t)N1C->getSExtValue());
1003 // fold ((c1-A)+c2) -> (c1+c2)-A
1004 if (N1C && N0.getOpcode() == ISD::SUB)
1005 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1006 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1007 DAG.getConstant(N1C->getAPIntValue()+
1008 N0C->getAPIntValue(), VT),
1011 SDValue RADD = ReassociateOps(ISD::ADD, N->getDebugLoc(), N0, N1);
1012 if (RADD.getNode() != 0)
1014 // fold ((0-A) + B) -> B-A
1015 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1016 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1017 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1, N0.getOperand(1));
1018 // fold (A + (0-B)) -> A-B
1019 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1020 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1021 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1.getOperand(1));
1022 // fold (A+(B-A)) -> B
1023 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1024 return N1.getOperand(0);
1025 // fold ((B-A)+A) -> B
1026 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1027 return N0.getOperand(0);
1028 // fold (A+(B-(A+C))) to (B-C)
1029 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1030 N0 == N1.getOperand(1).getOperand(0))
1031 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1032 N1.getOperand(1).getOperand(1));
1033 // fold (A+(B-(C+A))) to (B-C)
1034 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1035 N0 == N1.getOperand(1).getOperand(1))
1036 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1037 N1.getOperand(1).getOperand(0));
1038 // fold (A+((B-A)+or-C)) to (B+or-C)
1039 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1040 N1.getOperand(0).getOpcode() == ISD::SUB &&
1041 N0 == N1.getOperand(0).getOperand(1))
1042 return DAG.getNode(N1.getOpcode(), N->getDebugLoc(), VT,
1043 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1045 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1046 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1047 SDValue N00 = N0.getOperand(0);
1048 SDValue N01 = N0.getOperand(1);
1049 SDValue N10 = N1.getOperand(0);
1050 SDValue N11 = N1.getOperand(1);
1052 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1053 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1054 DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT, N00, N10),
1055 DAG.getNode(ISD::ADD, N1.getDebugLoc(), VT, N01, N11));
1058 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1059 return SDValue(N, 0);
1061 // fold (a+b) -> (a|b) iff a and b share no bits.
1062 if (VT.isInteger() && !VT.isVector()) {
1063 APInt LHSZero, LHSOne;
1064 APInt RHSZero, RHSOne;
1065 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
1066 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1068 if (LHSZero.getBoolValue()) {
1069 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1071 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1072 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1073 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1074 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1075 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1);
1079 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1080 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1081 SDValue Result = combineShlAddConstant(N->getDebugLoc(), N0, N1, DAG);
1082 if (Result.getNode()) return Result;
1084 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1085 SDValue Result = combineShlAddConstant(N->getDebugLoc(), N1, N0, DAG);
1086 if (Result.getNode()) return Result;
1092 SDValue DAGCombiner::visitADDC(SDNode *N) {
1093 SDValue N0 = N->getOperand(0);
1094 SDValue N1 = N->getOperand(1);
1095 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1096 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1097 EVT VT = N0.getValueType();
1099 // If the flag result is dead, turn this into an ADD.
1100 if (N->hasNUsesOfValue(0, 1))
1101 return CombineTo(N, DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0),
1102 DAG.getNode(ISD::CARRY_FALSE,
1103 N->getDebugLoc(), MVT::Flag));
1105 // canonicalize constant to RHS.
1107 return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
1109 // fold (addc x, 0) -> x + no carry out
1110 if (N1C && N1C->isNullValue())
1111 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1112 N->getDebugLoc(), MVT::Flag));
1114 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1115 APInt LHSZero, LHSOne;
1116 APInt RHSZero, RHSOne;
1117 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
1118 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1120 if (LHSZero.getBoolValue()) {
1121 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1123 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1124 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1125 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1126 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1127 return CombineTo(N, DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1),
1128 DAG.getNode(ISD::CARRY_FALSE,
1129 N->getDebugLoc(), MVT::Flag));
1135 SDValue DAGCombiner::visitADDE(SDNode *N) {
1136 SDValue N0 = N->getOperand(0);
1137 SDValue N1 = N->getOperand(1);
1138 SDValue CarryIn = N->getOperand(2);
1139 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1140 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1142 // canonicalize constant to RHS
1144 return DAG.getNode(ISD::ADDE, N->getDebugLoc(), N->getVTList(),
1147 // fold (adde x, y, false) -> (addc x, y)
1148 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1149 return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
1154 SDValue DAGCombiner::visitSUB(SDNode *N) {
1155 SDValue N0 = N->getOperand(0);
1156 SDValue N1 = N->getOperand(1);
1157 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1158 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1159 EVT VT = N0.getValueType();
1162 if (VT.isVector()) {
1163 SDValue FoldedVOp = SimplifyVBinOp(N);
1164 if (FoldedVOp.getNode()) return FoldedVOp;
1167 // fold (sub x, x) -> 0
1169 return DAG.getConstant(0, N->getValueType(0));
1170 // fold (sub c1, c2) -> c1-c2
1172 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1173 // fold (sub x, c) -> (add x, -c)
1175 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0,
1176 DAG.getConstant(-N1C->getAPIntValue(), VT));
1177 // fold (A+B)-A -> B
1178 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1179 return N0.getOperand(1);
1180 // fold (A+B)-B -> A
1181 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1182 return N0.getOperand(0);
1183 // fold ((A+(B+or-C))-B) -> A+or-C
1184 if (N0.getOpcode() == ISD::ADD &&
1185 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1186 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1187 N0.getOperand(1).getOperand(0) == N1)
1188 return DAG.getNode(N0.getOperand(1).getOpcode(), N->getDebugLoc(), VT,
1189 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1190 // fold ((A+(C+B))-B) -> A+C
1191 if (N0.getOpcode() == ISD::ADD &&
1192 N0.getOperand(1).getOpcode() == ISD::ADD &&
1193 N0.getOperand(1).getOperand(1) == N1)
1194 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1195 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1196 // fold ((A-(B-C))-C) -> A-B
1197 if (N0.getOpcode() == ISD::SUB &&
1198 N0.getOperand(1).getOpcode() == ISD::SUB &&
1199 N0.getOperand(1).getOperand(1) == N1)
1200 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1201 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1203 // If either operand of a sub is undef, the result is undef
1204 if (N0.getOpcode() == ISD::UNDEF)
1206 if (N1.getOpcode() == ISD::UNDEF)
1209 // If the relocation model supports it, consider symbol offsets.
1210 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1211 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1212 // fold (sub Sym, c) -> Sym-c
1213 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1214 return DAG.getGlobalAddress(GA->getGlobal(), VT,
1216 (uint64_t)N1C->getSExtValue());
1217 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1218 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1219 if (GA->getGlobal() == GB->getGlobal())
1220 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1227 SDValue DAGCombiner::visitMUL(SDNode *N) {
1228 SDValue N0 = N->getOperand(0);
1229 SDValue N1 = N->getOperand(1);
1230 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1231 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1232 EVT VT = N0.getValueType();
1235 if (VT.isVector()) {
1236 SDValue FoldedVOp = SimplifyVBinOp(N);
1237 if (FoldedVOp.getNode()) return FoldedVOp;
1240 // fold (mul x, undef) -> 0
1241 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1242 return DAG.getConstant(0, VT);
1243 // fold (mul c1, c2) -> c1*c2
1245 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0C, N1C);
1246 // canonicalize constant to RHS
1248 return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, N1, N0);
1249 // fold (mul x, 0) -> 0
1250 if (N1C && N1C->isNullValue())
1252 // fold (mul x, -1) -> 0-x
1253 if (N1C && N1C->isAllOnesValue())
1254 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1255 DAG.getConstant(0, VT), N0);
1256 // fold (mul x, (1 << c)) -> x << c
1257 if (N1C && N1C->getAPIntValue().isPowerOf2())
1258 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1259 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1260 getShiftAmountTy()));
1261 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1262 if (N1C && (-N1C->getAPIntValue()).isPowerOf2()) {
1263 unsigned Log2Val = (-N1C->getAPIntValue()).logBase2();
1264 // FIXME: If the input is something that is easily negated (e.g. a
1265 // single-use add), we should put the negate there.
1266 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1267 DAG.getConstant(0, VT),
1268 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1269 DAG.getConstant(Log2Val, getShiftAmountTy())));
1271 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1272 if (N1C && N0.getOpcode() == ISD::SHL &&
1273 isa<ConstantSDNode>(N0.getOperand(1))) {
1274 SDValue C3 = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1275 N1, N0.getOperand(1));
1276 AddToWorkList(C3.getNode());
1277 return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1278 N0.getOperand(0), C3);
1281 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1284 SDValue Sh(0,0), Y(0,0);
1285 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1286 if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1287 N0.getNode()->hasOneUse()) {
1289 } else if (N1.getOpcode() == ISD::SHL &&
1290 isa<ConstantSDNode>(N1.getOperand(1)) &&
1291 N1.getNode()->hasOneUse()) {
1296 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1297 Sh.getOperand(0), Y);
1298 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1299 Mul, Sh.getOperand(1));
1303 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1304 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1305 isa<ConstantSDNode>(N0.getOperand(1)))
1306 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1307 DAG.getNode(ISD::MUL, N0.getDebugLoc(), VT,
1308 N0.getOperand(0), N1),
1309 DAG.getNode(ISD::MUL, N1.getDebugLoc(), VT,
1310 N0.getOperand(1), N1));
1313 SDValue RMUL = ReassociateOps(ISD::MUL, N->getDebugLoc(), N0, N1);
1314 if (RMUL.getNode() != 0)
1320 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1321 SDValue N0 = N->getOperand(0);
1322 SDValue N1 = N->getOperand(1);
1323 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1324 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1325 EVT VT = N->getValueType(0);
1328 if (VT.isVector()) {
1329 SDValue FoldedVOp = SimplifyVBinOp(N);
1330 if (FoldedVOp.getNode()) return FoldedVOp;
1333 // fold (sdiv c1, c2) -> c1/c2
1334 if (N0C && N1C && !N1C->isNullValue())
1335 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1336 // fold (sdiv X, 1) -> X
1337 if (N1C && N1C->getSExtValue() == 1LL)
1339 // fold (sdiv X, -1) -> 0-X
1340 if (N1C && N1C->isAllOnesValue())
1341 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1342 DAG.getConstant(0, VT), N0);
1343 // If we know the sign bits of both operands are zero, strength reduce to a
1344 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1345 if (!VT.isVector()) {
1346 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1347 return DAG.getNode(ISD::UDIV, N->getDebugLoc(), N1.getValueType(),
1350 // fold (sdiv X, pow2) -> simple ops after legalize
1351 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap() &&
1352 (isPowerOf2_64(N1C->getSExtValue()) ||
1353 isPowerOf2_64(-N1C->getSExtValue()))) {
1354 // If dividing by powers of two is cheap, then don't perform the following
1356 if (TLI.isPow2DivCheap())
1359 int64_t pow2 = N1C->getSExtValue();
1360 int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
1361 unsigned lg2 = Log2_64(abs2);
1363 // Splat the sign bit into the register
1364 SDValue SGN = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
1365 DAG.getConstant(VT.getSizeInBits()-1,
1366 getShiftAmountTy()));
1367 AddToWorkList(SGN.getNode());
1369 // Add (N0 < 0) ? abs2 - 1 : 0;
1370 SDValue SRL = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, SGN,
1371 DAG.getConstant(VT.getSizeInBits() - lg2,
1372 getShiftAmountTy()));
1373 SDValue ADD = DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, SRL);
1374 AddToWorkList(SRL.getNode());
1375 AddToWorkList(ADD.getNode()); // Divide by pow2
1376 SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, ADD,
1377 DAG.getConstant(lg2, getShiftAmountTy()));
1379 // If we're dividing by a positive value, we're done. Otherwise, we must
1380 // negate the result.
1384 AddToWorkList(SRA.getNode());
1385 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1386 DAG.getConstant(0, VT), SRA);
1389 // if integer divide is expensive and we satisfy the requirements, emit an
1390 // alternate sequence.
1391 if (N1C && (N1C->getSExtValue() < -1 || N1C->getSExtValue() > 1) &&
1392 !TLI.isIntDivCheap()) {
1393 SDValue Op = BuildSDIV(N);
1394 if (Op.getNode()) return Op;
1398 if (N0.getOpcode() == ISD::UNDEF)
1399 return DAG.getConstant(0, VT);
1400 // X / undef -> undef
1401 if (N1.getOpcode() == ISD::UNDEF)
1407 SDValue DAGCombiner::visitUDIV(SDNode *N) {
1408 SDValue N0 = N->getOperand(0);
1409 SDValue N1 = N->getOperand(1);
1410 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1411 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1412 EVT VT = N->getValueType(0);
1415 if (VT.isVector()) {
1416 SDValue FoldedVOp = SimplifyVBinOp(N);
1417 if (FoldedVOp.getNode()) return FoldedVOp;
1420 // fold (udiv c1, c2) -> c1/c2
1421 if (N0C && N1C && !N1C->isNullValue())
1422 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
1423 // fold (udiv x, (1 << c)) -> x >>u c
1424 if (N1C && N1C->getAPIntValue().isPowerOf2())
1425 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
1426 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1427 getShiftAmountTy()));
1428 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1429 if (N1.getOpcode() == ISD::SHL) {
1430 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1431 if (SHC->getAPIntValue().isPowerOf2()) {
1432 EVT ADDVT = N1.getOperand(1).getValueType();
1433 SDValue Add = DAG.getNode(ISD::ADD, N->getDebugLoc(), ADDVT,
1435 DAG.getConstant(SHC->getAPIntValue()
1438 AddToWorkList(Add.getNode());
1439 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, Add);
1443 // fold (udiv x, c) -> alternate
1444 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1445 SDValue Op = BuildUDIV(N);
1446 if (Op.getNode()) return Op;
1450 if (N0.getOpcode() == ISD::UNDEF)
1451 return DAG.getConstant(0, VT);
1452 // X / undef -> undef
1453 if (N1.getOpcode() == ISD::UNDEF)
1459 SDValue DAGCombiner::visitSREM(SDNode *N) {
1460 SDValue N0 = N->getOperand(0);
1461 SDValue N1 = N->getOperand(1);
1462 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1463 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1464 EVT VT = N->getValueType(0);
1466 // fold (srem c1, c2) -> c1%c2
1467 if (N0C && N1C && !N1C->isNullValue())
1468 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
1469 // If we know the sign bits of both operands are zero, strength reduce to a
1470 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
1471 if (!VT.isVector()) {
1472 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1473 return DAG.getNode(ISD::UREM, N->getDebugLoc(), VT, N0, N1);
1476 // If X/C can be simplified by the division-by-constant logic, lower
1477 // X%C to the equivalent of X-X/C*C.
1478 if (N1C && !N1C->isNullValue()) {
1479 SDValue Div = DAG.getNode(ISD::SDIV, N->getDebugLoc(), VT, N0, N1);
1480 AddToWorkList(Div.getNode());
1481 SDValue OptimizedDiv = combine(Div.getNode());
1482 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1483 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1485 SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
1486 AddToWorkList(Mul.getNode());
1492 if (N0.getOpcode() == ISD::UNDEF)
1493 return DAG.getConstant(0, VT);
1494 // X % undef -> undef
1495 if (N1.getOpcode() == ISD::UNDEF)
1501 SDValue DAGCombiner::visitUREM(SDNode *N) {
1502 SDValue N0 = N->getOperand(0);
1503 SDValue N1 = N->getOperand(1);
1504 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1505 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1506 EVT VT = N->getValueType(0);
1508 // fold (urem c1, c2) -> c1%c2
1509 if (N0C && N1C && !N1C->isNullValue())
1510 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
1511 // fold (urem x, pow2) -> (and x, pow2-1)
1512 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
1513 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0,
1514 DAG.getConstant(N1C->getAPIntValue()-1,VT));
1515 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
1516 if (N1.getOpcode() == ISD::SHL) {
1517 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1518 if (SHC->getAPIntValue().isPowerOf2()) {
1520 DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1,
1521 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
1523 AddToWorkList(Add.getNode());
1524 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, Add);
1529 // If X/C can be simplified by the division-by-constant logic, lower
1530 // X%C to the equivalent of X-X/C*C.
1531 if (N1C && !N1C->isNullValue()) {
1532 SDValue Div = DAG.getNode(ISD::UDIV, N->getDebugLoc(), VT, N0, N1);
1533 AddToWorkList(Div.getNode());
1534 SDValue OptimizedDiv = combine(Div.getNode());
1535 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1536 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1538 SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
1539 AddToWorkList(Mul.getNode());
1545 if (N0.getOpcode() == ISD::UNDEF)
1546 return DAG.getConstant(0, VT);
1547 // X % undef -> undef
1548 if (N1.getOpcode() == ISD::UNDEF)
1554 SDValue DAGCombiner::visitMULHS(SDNode *N) {
1555 SDValue N0 = N->getOperand(0);
1556 SDValue N1 = N->getOperand(1);
1557 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1558 EVT VT = N->getValueType(0);
1560 // fold (mulhs x, 0) -> 0
1561 if (N1C && N1C->isNullValue())
1563 // fold (mulhs x, 1) -> (sra x, size(x)-1)
1564 if (N1C && N1C->getAPIntValue() == 1)
1565 return DAG.getNode(ISD::SRA, N->getDebugLoc(), N0.getValueType(), N0,
1566 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
1567 getShiftAmountTy()));
1568 // fold (mulhs x, undef) -> 0
1569 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1570 return DAG.getConstant(0, VT);
1575 SDValue DAGCombiner::visitMULHU(SDNode *N) {
1576 SDValue N0 = N->getOperand(0);
1577 SDValue N1 = N->getOperand(1);
1578 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1579 EVT VT = N->getValueType(0);
1581 // fold (mulhu x, 0) -> 0
1582 if (N1C && N1C->isNullValue())
1584 // fold (mulhu x, 1) -> 0
1585 if (N1C && N1C->getAPIntValue() == 1)
1586 return DAG.getConstant(0, N0.getValueType());
1587 // fold (mulhu x, undef) -> 0
1588 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1589 return DAG.getConstant(0, VT);
1594 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
1595 /// compute two values. LoOp and HiOp give the opcodes for the two computations
1596 /// that are being performed. Return true if a simplification was made.
1598 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
1600 // If the high half is not needed, just compute the low half.
1601 bool HiExists = N->hasAnyUseOfValue(1);
1603 (!LegalOperations ||
1604 TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
1605 SDValue Res = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
1606 N->op_begin(), N->getNumOperands());
1607 return CombineTo(N, Res, Res);
1610 // If the low half is not needed, just compute the high half.
1611 bool LoExists = N->hasAnyUseOfValue(0);
1613 (!LegalOperations ||
1614 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
1615 SDValue Res = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
1616 N->op_begin(), N->getNumOperands());
1617 return CombineTo(N, Res, Res);
1620 // If both halves are used, return as it is.
1621 if (LoExists && HiExists)
1624 // If the two computed results can be simplified separately, separate them.
1626 SDValue Lo = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
1627 N->op_begin(), N->getNumOperands());
1628 AddToWorkList(Lo.getNode());
1629 SDValue LoOpt = combine(Lo.getNode());
1630 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
1631 (!LegalOperations ||
1632 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
1633 return CombineTo(N, LoOpt, LoOpt);
1637 SDValue Hi = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
1638 N->op_begin(), N->getNumOperands());
1639 AddToWorkList(Hi.getNode());
1640 SDValue HiOpt = combine(Hi.getNode());
1641 if (HiOpt.getNode() && HiOpt != Hi &&
1642 (!LegalOperations ||
1643 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
1644 return CombineTo(N, HiOpt, HiOpt);
1650 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
1651 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
1652 if (Res.getNode()) return Res;
1657 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
1658 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
1659 if (Res.getNode()) return Res;
1664 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
1665 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
1666 if (Res.getNode()) return Res;
1671 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
1672 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
1673 if (Res.getNode()) return Res;
1678 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
1679 /// two operands of the same opcode, try to simplify it.
1680 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
1681 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
1682 EVT VT = N0.getValueType();
1683 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
1685 // For each of OP in AND/OR/XOR:
1686 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
1687 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
1688 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
1689 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
1690 if ((N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND||
1691 N0.getOpcode() == ISD::SIGN_EXTEND ||
1692 (N0.getOpcode() == ISD::TRUNCATE &&
1693 !TLI.isTruncateFree(N0.getOperand(0).getValueType(), VT))) &&
1694 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
1695 (!LegalOperations ||
1696 TLI.isOperationLegal(N->getOpcode(), N0.getOperand(0).getValueType()))) {
1697 SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
1698 N0.getOperand(0).getValueType(),
1699 N0.getOperand(0), N1.getOperand(0));
1700 AddToWorkList(ORNode.getNode());
1701 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, ORNode);
1704 // For each of OP in SHL/SRL/SRA/AND...
1705 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
1706 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
1707 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
1708 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
1709 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
1710 N0.getOperand(1) == N1.getOperand(1)) {
1711 SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
1712 N0.getOperand(0).getValueType(),
1713 N0.getOperand(0), N1.getOperand(0));
1714 AddToWorkList(ORNode.getNode());
1715 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
1716 ORNode, N0.getOperand(1));
1722 SDValue DAGCombiner::visitAND(SDNode *N) {
1723 SDValue N0 = N->getOperand(0);
1724 SDValue N1 = N->getOperand(1);
1725 SDValue LL, LR, RL, RR, CC0, CC1;
1726 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1727 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1728 EVT VT = N1.getValueType();
1729 unsigned BitWidth = VT.getSizeInBits();
1732 if (VT.isVector()) {
1733 SDValue FoldedVOp = SimplifyVBinOp(N);
1734 if (FoldedVOp.getNode()) return FoldedVOp;
1737 // fold (and x, undef) -> 0
1738 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1739 return DAG.getConstant(0, VT);
1740 // fold (and c1, c2) -> c1&c2
1742 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
1743 // canonicalize constant to RHS
1745 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N1, N0);
1746 // fold (and x, -1) -> x
1747 if (N1C && N1C->isAllOnesValue())
1749 // if (and x, c) is known to be zero, return 0
1750 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
1751 APInt::getAllOnesValue(BitWidth)))
1752 return DAG.getConstant(0, VT);
1754 SDValue RAND = ReassociateOps(ISD::AND, N->getDebugLoc(), N0, N1);
1755 if (RAND.getNode() != 0)
1757 // fold (and (or x, 0xFFFF), 0xFF) -> 0xFF
1758 if (N1C && N0.getOpcode() == ISD::OR)
1759 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
1760 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
1762 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
1763 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
1764 SDValue N0Op0 = N0.getOperand(0);
1765 APInt Mask = ~N1C->getAPIntValue();
1766 Mask.trunc(N0Op0.getValueSizeInBits());
1767 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
1768 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(),
1769 N0.getValueType(), N0Op0);
1771 // Replace uses of the AND with uses of the Zero extend node.
1774 // We actually want to replace all uses of the any_extend with the
1775 // zero_extend, to avoid duplicating things. This will later cause this
1776 // AND to be folded.
1777 CombineTo(N0.getNode(), Zext);
1778 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1781 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
1782 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1783 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1784 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1786 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1787 LL.getValueType().isInteger()) {
1788 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
1789 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
1790 SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
1791 LR.getValueType(), LL, RL);
1792 AddToWorkList(ORNode.getNode());
1793 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
1795 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
1796 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
1797 SDValue ANDNode = DAG.getNode(ISD::AND, N0.getDebugLoc(),
1798 LR.getValueType(), LL, RL);
1799 AddToWorkList(ANDNode.getNode());
1800 return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
1802 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
1803 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
1804 SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
1805 LR.getValueType(), LL, RL);
1806 AddToWorkList(ORNode.getNode());
1807 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
1810 // canonicalize equivalent to ll == rl
1811 if (LL == RR && LR == RL) {
1812 Op1 = ISD::getSetCCSwappedOperands(Op1);
1815 if (LL == RL && LR == RR) {
1816 bool isInteger = LL.getValueType().isInteger();
1817 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
1818 if (Result != ISD::SETCC_INVALID &&
1819 (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
1820 return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
1825 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
1826 if (N0.getOpcode() == N1.getOpcode()) {
1827 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1828 if (Tmp.getNode()) return Tmp;
1831 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
1832 // fold (and (sra)) -> (and (srl)) when possible.
1833 if (!VT.isVector() &&
1834 SimplifyDemandedBits(SDValue(N, 0)))
1835 return SDValue(N, 0);
1836 // fold (zext_inreg (extload x)) -> (zextload x)
1837 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
1838 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1839 EVT EVT = LN0->getMemoryVT();
1840 // If we zero all the possible extended bits, then we can turn this into
1841 // a zextload if we are running before legalize or the operation is legal.
1842 unsigned BitWidth = N1.getValueSizeInBits();
1843 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
1844 BitWidth - EVT.getSizeInBits())) &&
1845 ((!LegalOperations && !LN0->isVolatile()) ||
1846 TLI.isLoadExtLegal(ISD::ZEXTLOAD, EVT))) {
1847 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
1848 LN0->getChain(), LN0->getBasePtr(),
1850 LN0->getSrcValueOffset(), EVT,
1851 LN0->isVolatile(), LN0->getAlignment());
1853 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
1854 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1857 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
1858 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
1860 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1861 EVT EVT = LN0->getMemoryVT();
1862 // If we zero all the possible extended bits, then we can turn this into
1863 // a zextload if we are running before legalize or the operation is legal.
1864 unsigned BitWidth = N1.getValueSizeInBits();
1865 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
1866 BitWidth - EVT.getSizeInBits())) &&
1867 ((!LegalOperations && !LN0->isVolatile()) ||
1868 TLI.isLoadExtLegal(ISD::ZEXTLOAD, EVT))) {
1869 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
1871 LN0->getBasePtr(), LN0->getSrcValue(),
1872 LN0->getSrcValueOffset(), EVT,
1873 LN0->isVolatile(), LN0->getAlignment());
1875 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
1876 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1880 // fold (and (load x), 255) -> (zextload x, i8)
1881 // fold (and (extload x, i16), 255) -> (zextload x, i8)
1882 if (N1C && N0.getOpcode() == ISD::LOAD) {
1883 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1884 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
1885 LN0->isUnindexed() && N0.hasOneUse() &&
1886 // Do not change the width of a volatile load.
1887 !LN0->isVolatile()) {
1888 EVT ExtVT = MVT::Other;
1889 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
1890 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue()))
1891 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
1893 EVT LoadedVT = LN0->getMemoryVT();
1895 // Do not generate loads of non-round integer types since these can
1896 // be expensive (and would be wrong if the type is not byte sized).
1897 if (ExtVT != MVT::Other && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
1898 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
1899 EVT PtrType = N0.getOperand(1).getValueType();
1901 // For big endian targets, we need to add an offset to the pointer to
1902 // load the correct bytes. For little endian systems, we merely need to
1903 // read fewer bytes from the same pointer.
1904 unsigned LVTStoreBytes = LoadedVT.getStoreSizeInBits()/8;
1905 unsigned EVTStoreBytes = ExtVT.getStoreSizeInBits()/8;
1906 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
1907 unsigned Alignment = LN0->getAlignment();
1908 SDValue NewPtr = LN0->getBasePtr();
1910 if (TLI.isBigEndian()) {
1911 NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(), PtrType,
1912 NewPtr, DAG.getConstant(PtrOff, PtrType));
1913 Alignment = MinAlign(Alignment, PtrOff);
1916 AddToWorkList(NewPtr.getNode());
1918 DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), VT, LN0->getChain(),
1919 NewPtr, LN0->getSrcValue(), LN0->getSrcValueOffset(),
1920 ExtVT, LN0->isVolatile(), Alignment);
1922 CombineTo(N0.getNode(), Load, Load.getValue(1));
1923 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1931 SDValue DAGCombiner::visitOR(SDNode *N) {
1932 SDValue N0 = N->getOperand(0);
1933 SDValue N1 = N->getOperand(1);
1934 SDValue LL, LR, RL, RR, CC0, CC1;
1935 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1936 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1937 EVT VT = N1.getValueType();
1940 if (VT.isVector()) {
1941 SDValue FoldedVOp = SimplifyVBinOp(N);
1942 if (FoldedVOp.getNode()) return FoldedVOp;
1945 // fold (or x, undef) -> -1
1946 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1947 return DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
1948 // fold (or c1, c2) -> c1|c2
1950 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
1951 // canonicalize constant to RHS
1953 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N1, N0);
1954 // fold (or x, 0) -> x
1955 if (N1C && N1C->isNullValue())
1957 // fold (or x, -1) -> -1
1958 if (N1C && N1C->isAllOnesValue())
1960 // fold (or x, c) -> c iff (x & ~c) == 0
1961 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
1964 SDValue ROR = ReassociateOps(ISD::OR, N->getDebugLoc(), N0, N1);
1965 if (ROR.getNode() != 0)
1967 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
1968 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
1969 isa<ConstantSDNode>(N0.getOperand(1))) {
1970 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
1971 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
1972 DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
1973 N0.getOperand(0), N1),
1974 DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
1976 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
1977 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1978 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1979 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1981 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1982 LL.getValueType().isInteger()) {
1983 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
1984 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
1985 if (cast<ConstantSDNode>(LR)->isNullValue() &&
1986 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
1987 SDValue ORNode = DAG.getNode(ISD::OR, LR.getDebugLoc(),
1988 LR.getValueType(), LL, RL);
1989 AddToWorkList(ORNode.getNode());
1990 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
1992 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
1993 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
1994 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
1995 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
1996 SDValue ANDNode = DAG.getNode(ISD::AND, LR.getDebugLoc(),
1997 LR.getValueType(), LL, RL);
1998 AddToWorkList(ANDNode.getNode());
1999 return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
2002 // canonicalize equivalent to ll == rl
2003 if (LL == RR && LR == RL) {
2004 Op1 = ISD::getSetCCSwappedOperands(Op1);
2007 if (LL == RL && LR == RR) {
2008 bool isInteger = LL.getValueType().isInteger();
2009 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
2010 if (Result != ISD::SETCC_INVALID &&
2011 (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
2012 return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
2017 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
2018 if (N0.getOpcode() == N1.getOpcode()) {
2019 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2020 if (Tmp.getNode()) return Tmp;
2023 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
2024 if (N0.getOpcode() == ISD::AND &&
2025 N1.getOpcode() == ISD::AND &&
2026 N0.getOperand(1).getOpcode() == ISD::Constant &&
2027 N1.getOperand(1).getOpcode() == ISD::Constant &&
2028 // Don't increase # computations.
2029 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
2030 // We can only do this xform if we know that bits from X that are set in C2
2031 // but not in C1 are already zero. Likewise for Y.
2032 const APInt &LHSMask =
2033 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
2034 const APInt &RHSMask =
2035 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
2037 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
2038 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
2039 SDValue X = DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
2040 N0.getOperand(0), N1.getOperand(0));
2041 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, X,
2042 DAG.getConstant(LHSMask | RHSMask, VT));
2046 // See if this is some rotate idiom.
2047 if (SDNode *Rot = MatchRotate(N0, N1, N->getDebugLoc()))
2048 return SDValue(Rot, 0);
2053 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
2054 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
2055 if (Op.getOpcode() == ISD::AND) {
2056 if (isa<ConstantSDNode>(Op.getOperand(1))) {
2057 Mask = Op.getOperand(1);
2058 Op = Op.getOperand(0);
2064 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
2072 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
2073 // idioms for rotate, and if the target supports rotation instructions, generate
2075 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL) {
2076 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
2077 EVT VT = LHS.getValueType();
2078 if (!TLI.isTypeLegal(VT)) return 0;
2080 // The target must have at least one rotate flavor.
2081 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
2082 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
2083 if (!HasROTL && !HasROTR) return 0;
2085 // Match "(X shl/srl V1) & V2" where V2 may not be present.
2086 SDValue LHSShift; // The shift.
2087 SDValue LHSMask; // AND value if any.
2088 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
2089 return 0; // Not part of a rotate.
2091 SDValue RHSShift; // The shift.
2092 SDValue RHSMask; // AND value if any.
2093 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
2094 return 0; // Not part of a rotate.
2096 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
2097 return 0; // Not shifting the same value.
2099 if (LHSShift.getOpcode() == RHSShift.getOpcode())
2100 return 0; // Shifts must disagree.
2102 // Canonicalize shl to left side in a shl/srl pair.
2103 if (RHSShift.getOpcode() == ISD::SHL) {
2104 std::swap(LHS, RHS);
2105 std::swap(LHSShift, RHSShift);
2106 std::swap(LHSMask , RHSMask );
2109 unsigned OpSizeInBits = VT.getSizeInBits();
2110 SDValue LHSShiftArg = LHSShift.getOperand(0);
2111 SDValue LHSShiftAmt = LHSShift.getOperand(1);
2112 SDValue RHSShiftAmt = RHSShift.getOperand(1);
2114 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
2115 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
2116 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
2117 RHSShiftAmt.getOpcode() == ISD::Constant) {
2118 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
2119 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
2120 if ((LShVal + RShVal) != OpSizeInBits)
2125 Rot = DAG.getNode(ISD::ROTL, DL, VT, LHSShiftArg, LHSShiftAmt);
2127 Rot = DAG.getNode(ISD::ROTR, DL, VT, LHSShiftArg, RHSShiftAmt);
2129 // If there is an AND of either shifted operand, apply it to the result.
2130 if (LHSMask.getNode() || RHSMask.getNode()) {
2131 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
2133 if (LHSMask.getNode()) {
2134 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
2135 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
2137 if (RHSMask.getNode()) {
2138 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
2139 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
2142 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
2145 return Rot.getNode();
2148 // If there is a mask here, and we have a variable shift, we can't be sure
2149 // that we're masking out the right stuff.
2150 if (LHSMask.getNode() || RHSMask.getNode())
2153 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
2154 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
2155 if (RHSShiftAmt.getOpcode() == ISD::SUB &&
2156 LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
2157 if (ConstantSDNode *SUBC =
2158 dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
2159 if (SUBC->getAPIntValue() == OpSizeInBits) {
2161 return DAG.getNode(ISD::ROTL, DL, VT,
2162 LHSShiftArg, LHSShiftAmt).getNode();
2164 return DAG.getNode(ISD::ROTR, DL, VT,
2165 LHSShiftArg, RHSShiftAmt).getNode();
2170 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
2171 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
2172 if (LHSShiftAmt.getOpcode() == ISD::SUB &&
2173 RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
2174 if (ConstantSDNode *SUBC =
2175 dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
2176 if (SUBC->getAPIntValue() == OpSizeInBits) {
2178 return DAG.getNode(ISD::ROTR, DL, VT,
2179 LHSShiftArg, RHSShiftAmt).getNode();
2181 return DAG.getNode(ISD::ROTL, DL, VT,
2182 LHSShiftArg, LHSShiftAmt).getNode();
2187 // Look for sign/zext/any-extended or truncate cases:
2188 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2189 || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2190 || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
2191 || LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
2192 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2193 || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2194 || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
2195 || RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
2196 SDValue LExtOp0 = LHSShiftAmt.getOperand(0);
2197 SDValue RExtOp0 = RHSShiftAmt.getOperand(0);
2198 if (RExtOp0.getOpcode() == ISD::SUB &&
2199 RExtOp0.getOperand(1) == LExtOp0) {
2200 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2202 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2203 // (rotr x, (sub 32, y))
2204 if (ConstantSDNode *SUBC =
2205 dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
2206 if (SUBC->getAPIntValue() == OpSizeInBits) {
2207 return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
2209 HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
2212 } else if (LExtOp0.getOpcode() == ISD::SUB &&
2213 RExtOp0 == LExtOp0.getOperand(1)) {
2214 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
2216 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
2217 // (rotl x, (sub 32, y))
2218 if (ConstantSDNode *SUBC =
2219 dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
2220 if (SUBC->getAPIntValue() == OpSizeInBits) {
2221 return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT,
2223 HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
2232 SDValue DAGCombiner::visitXOR(SDNode *N) {
2233 SDValue N0 = N->getOperand(0);
2234 SDValue N1 = N->getOperand(1);
2235 SDValue LHS, RHS, CC;
2236 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2237 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2238 EVT VT = N0.getValueType();
2241 if (VT.isVector()) {
2242 SDValue FoldedVOp = SimplifyVBinOp(N);
2243 if (FoldedVOp.getNode()) return FoldedVOp;
2246 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
2247 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
2248 return DAG.getConstant(0, VT);
2249 // fold (xor x, undef) -> undef
2250 if (N0.getOpcode() == ISD::UNDEF)
2252 if (N1.getOpcode() == ISD::UNDEF)
2254 // fold (xor c1, c2) -> c1^c2
2256 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
2257 // canonicalize constant to RHS
2259 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
2260 // fold (xor x, 0) -> x
2261 if (N1C && N1C->isNullValue())
2264 SDValue RXOR = ReassociateOps(ISD::XOR, N->getDebugLoc(), N0, N1);
2265 if (RXOR.getNode() != 0)
2268 // fold !(x cc y) -> (x !cc y)
2269 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
2270 bool isInt = LHS.getValueType().isInteger();
2271 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
2274 if (!LegalOperations || TLI.isCondCodeLegal(NotCC, LHS.getValueType())) {
2275 switch (N0.getOpcode()) {
2277 llvm_unreachable("Unhandled SetCC Equivalent!");
2279 return DAG.getSetCC(N->getDebugLoc(), VT, LHS, RHS, NotCC);
2280 case ISD::SELECT_CC:
2281 return DAG.getSelectCC(N->getDebugLoc(), LHS, RHS, N0.getOperand(2),
2282 N0.getOperand(3), NotCC);
2287 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
2288 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
2289 N0.getNode()->hasOneUse() &&
2290 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
2291 SDValue V = N0.getOperand(0);
2292 V = DAG.getNode(ISD::XOR, N0.getDebugLoc(), V.getValueType(), V,
2293 DAG.getConstant(1, V.getValueType()));
2294 AddToWorkList(V.getNode());
2295 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, V);
2298 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
2299 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
2300 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2301 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2302 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
2303 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2304 LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
2305 RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
2306 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
2307 return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
2310 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
2311 if (N1C && N1C->isAllOnesValue() &&
2312 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2313 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2314 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
2315 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2316 LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
2317 RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
2318 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
2319 return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
2322 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
2323 if (N1C && N0.getOpcode() == ISD::XOR) {
2324 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
2325 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2327 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(1),
2328 DAG.getConstant(N1C->getAPIntValue() ^
2329 N00C->getAPIntValue(), VT));
2331 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(0),
2332 DAG.getConstant(N1C->getAPIntValue() ^
2333 N01C->getAPIntValue(), VT));
2335 // fold (xor x, x) -> 0
2337 if (!VT.isVector()) {
2338 return DAG.getConstant(0, VT);
2339 } else if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)){
2340 // Produce a vector of zeros.
2341 SDValue El = DAG.getConstant(0, VT.getVectorElementType());
2342 std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
2343 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
2344 &Ops[0], Ops.size());
2348 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
2349 if (N0.getOpcode() == N1.getOpcode()) {
2350 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2351 if (Tmp.getNode()) return Tmp;
2354 // Simplify the expression using non-local knowledge.
2355 if (!VT.isVector() &&
2356 SimplifyDemandedBits(SDValue(N, 0)))
2357 return SDValue(N, 0);
2362 /// visitShiftByConstant - Handle transforms common to the three shifts, when
2363 /// the shift amount is a constant.
2364 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
2365 SDNode *LHS = N->getOperand(0).getNode();
2366 if (!LHS->hasOneUse()) return SDValue();
2368 // We want to pull some binops through shifts, so that we have (and (shift))
2369 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
2370 // thing happens with address calculations, so it's important to canonicalize
2372 bool HighBitSet = false; // Can we transform this if the high bit is set?
2374 switch (LHS->getOpcode()) {
2375 default: return SDValue();
2378 HighBitSet = false; // We can only transform sra if the high bit is clear.
2381 HighBitSet = true; // We can only transform sra if the high bit is set.
2384 if (N->getOpcode() != ISD::SHL)
2385 return SDValue(); // only shl(add) not sr[al](add).
2386 HighBitSet = false; // We can only transform sra if the high bit is clear.
2390 // We require the RHS of the binop to be a constant as well.
2391 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
2392 if (!BinOpCst) return SDValue();
2394 // FIXME: disable this unless the input to the binop is a shift by a constant.
2395 // If it is not a shift, it pessimizes some common cases like:
2397 // void foo(int *X, int i) { X[i & 1235] = 1; }
2398 // int bar(int *X, int i) { return X[i & 255]; }
2399 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
2400 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
2401 BinOpLHSVal->getOpcode() != ISD::SRA &&
2402 BinOpLHSVal->getOpcode() != ISD::SRL) ||
2403 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
2406 EVT VT = N->getValueType(0);
2408 // If this is a signed shift right, and the high bit is modified by the
2409 // logical operation, do not perform the transformation. The highBitSet
2410 // boolean indicates the value of the high bit of the constant which would
2411 // cause it to be modified for this operation.
2412 if (N->getOpcode() == ISD::SRA) {
2413 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
2414 if (BinOpRHSSignSet != HighBitSet)
2418 // Fold the constants, shifting the binop RHS by the shift amount.
2419 SDValue NewRHS = DAG.getNode(N->getOpcode(), LHS->getOperand(1).getDebugLoc(),
2421 LHS->getOperand(1), N->getOperand(1));
2423 // Create the new shift.
2424 SDValue NewShift = DAG.getNode(N->getOpcode(), LHS->getOperand(0).getDebugLoc(),
2425 VT, LHS->getOperand(0), N->getOperand(1));
2427 // Create the new binop.
2428 return DAG.getNode(LHS->getOpcode(), N->getDebugLoc(), VT, NewShift, NewRHS);
2431 SDValue DAGCombiner::visitSHL(SDNode *N) {
2432 SDValue N0 = N->getOperand(0);
2433 SDValue N1 = N->getOperand(1);
2434 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2435 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2436 EVT VT = N0.getValueType();
2437 unsigned OpSizeInBits = VT.getSizeInBits();
2439 // fold (shl c1, c2) -> c1<<c2
2441 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
2442 // fold (shl 0, x) -> 0
2443 if (N0C && N0C->isNullValue())
2445 // fold (shl x, c >= size(x)) -> undef
2446 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
2447 return DAG.getUNDEF(VT);
2448 // fold (shl x, 0) -> x
2449 if (N1C && N1C->isNullValue())
2451 // if (shl x, c) is known to be zero, return 0
2452 if (DAG.MaskedValueIsZero(SDValue(N, 0),
2453 APInt::getAllOnesValue(VT.getSizeInBits())))
2454 return DAG.getConstant(0, VT);
2455 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
2456 if (N1.getOpcode() == ISD::TRUNCATE &&
2457 N1.getOperand(0).getOpcode() == ISD::AND &&
2458 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
2459 SDValue N101 = N1.getOperand(0).getOperand(1);
2460 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
2461 EVT TruncVT = N1.getValueType();
2462 SDValue N100 = N1.getOperand(0).getOperand(0);
2463 APInt TruncC = N101C->getAPIntValue();
2464 TruncC.trunc(TruncVT.getSizeInBits());
2465 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
2466 DAG.getNode(ISD::AND, N->getDebugLoc(), TruncVT,
2467 DAG.getNode(ISD::TRUNCATE,
2470 DAG.getConstant(TruncC, TruncVT)));
2474 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
2475 return SDValue(N, 0);
2477 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
2478 if (N1C && N0.getOpcode() == ISD::SHL &&
2479 N0.getOperand(1).getOpcode() == ISD::Constant) {
2480 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
2481 uint64_t c2 = N1C->getZExtValue();
2482 if (c1 + c2 > OpSizeInBits)
2483 return DAG.getConstant(0, VT);
2484 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
2485 DAG.getConstant(c1 + c2, N1.getValueType()));
2487 // fold (shl (srl x, c1), c2) -> (shl (and x, (shl -1, c1)), (sub c2, c1)) or
2488 // (srl (and x, (shl -1, c1)), (sub c1, c2))
2489 if (N1C && N0.getOpcode() == ISD::SRL &&
2490 N0.getOperand(1).getOpcode() == ISD::Constant) {
2491 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
2492 if (c1 < VT.getSizeInBits()) {
2493 uint64_t c2 = N1C->getZExtValue();
2494 SDValue HiBitsMask =
2495 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
2496 VT.getSizeInBits() - c1),
2498 SDValue Mask = DAG.getNode(ISD::AND, N0.getDebugLoc(), VT,
2502 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, Mask,
2503 DAG.getConstant(c2-c1, N1.getValueType()));
2505 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, Mask,
2506 DAG.getConstant(c1-c2, N1.getValueType()));
2509 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
2510 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
2511 SDValue HiBitsMask =
2512 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
2513 VT.getSizeInBits() -
2514 N1C->getZExtValue()),
2516 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
2520 return N1C ? visitShiftByConstant(N, N1C->getZExtValue()) : SDValue();
2523 SDValue DAGCombiner::visitSRA(SDNode *N) {
2524 SDValue N0 = N->getOperand(0);
2525 SDValue N1 = N->getOperand(1);
2526 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2527 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2528 EVT VT = N0.getValueType();
2530 // fold (sra c1, c2) -> (sra c1, c2)
2532 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
2533 // fold (sra 0, x) -> 0
2534 if (N0C && N0C->isNullValue())
2536 // fold (sra -1, x) -> -1
2537 if (N0C && N0C->isAllOnesValue())
2539 // fold (sra x, (setge c, size(x))) -> undef
2540 if (N1C && N1C->getZExtValue() >= VT.getSizeInBits())
2541 return DAG.getUNDEF(VT);
2542 // fold (sra x, 0) -> x
2543 if (N1C && N1C->isNullValue())
2545 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
2547 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
2548 unsigned LowBits = VT.getSizeInBits() - (unsigned)N1C->getZExtValue();
2549 EVT EVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
2550 if ((!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, EVT)))
2551 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
2552 N0.getOperand(0), DAG.getValueType(EVT));
2555 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
2556 if (N1C && N0.getOpcode() == ISD::SRA) {
2557 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2558 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
2559 if (Sum >= VT.getSizeInBits()) Sum = VT.getSizeInBits()-1;
2560 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0.getOperand(0),
2561 DAG.getConstant(Sum, N1C->getValueType(0)));
2565 // fold (sra (shl X, m), (sub result_size, n))
2566 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
2567 // result_size - n != m.
2568 // If truncate is free for the target sext(shl) is likely to result in better
2570 if (N0.getOpcode() == ISD::SHL) {
2571 // Get the two constanst of the shifts, CN0 = m, CN = n.
2572 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2574 // Determine what the truncate's result bitsize and type would be.
2575 unsigned VTValSize = VT.getSizeInBits();
2577 EVT::getIntegerVT(*DAG.getContext(), VTValSize - N1C->getZExtValue());
2578 // Determine the residual right-shift amount.
2579 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
2581 // If the shift is not a no-op (in which case this should be just a sign
2582 // extend already), the truncated to type is legal, sign_extend is legal
2583 // on that type, and the the truncate to that type is both legal and free,
2584 // perform the transform.
2585 if ((ShiftAmt > 0) &&
2586 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
2587 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
2588 TLI.isTruncateFree(VT, TruncVT)) {
2590 SDValue Amt = DAG.getConstant(ShiftAmt, getShiftAmountTy());
2591 SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT,
2592 N0.getOperand(0), Amt);
2593 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), TruncVT,
2595 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(),
2596 N->getValueType(0), Trunc);
2601 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
2602 if (N1.getOpcode() == ISD::TRUNCATE &&
2603 N1.getOperand(0).getOpcode() == ISD::AND &&
2604 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
2605 SDValue N101 = N1.getOperand(0).getOperand(1);
2606 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
2607 EVT TruncVT = N1.getValueType();
2608 SDValue N100 = N1.getOperand(0).getOperand(0);
2609 APInt TruncC = N101C->getAPIntValue();
2610 TruncC.trunc(TruncVT.getSizeInBits());
2611 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
2612 DAG.getNode(ISD::AND, N->getDebugLoc(),
2614 DAG.getNode(ISD::TRUNCATE,
2617 DAG.getConstant(TruncC, TruncVT)));
2621 // Simplify, based on bits shifted out of the LHS.
2622 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
2623 return SDValue(N, 0);
2626 // If the sign bit is known to be zero, switch this to a SRL.
2627 if (DAG.SignBitIsZero(N0))
2628 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, N1);
2630 return N1C ? visitShiftByConstant(N, N1C->getZExtValue()) : SDValue();
2633 SDValue DAGCombiner::visitSRL(SDNode *N) {
2634 SDValue N0 = N->getOperand(0);
2635 SDValue N1 = N->getOperand(1);
2636 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2637 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2638 EVT VT = N0.getValueType();
2639 unsigned OpSizeInBits = VT.getSizeInBits();
2641 // fold (srl c1, c2) -> c1 >>u c2
2643 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
2644 // fold (srl 0, x) -> 0
2645 if (N0C && N0C->isNullValue())
2647 // fold (srl x, c >= size(x)) -> undef
2648 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
2649 return DAG.getUNDEF(VT);
2650 // fold (srl x, 0) -> x
2651 if (N1C && N1C->isNullValue())
2653 // if (srl x, c) is known to be zero, return 0
2654 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2655 APInt::getAllOnesValue(OpSizeInBits)))
2656 return DAG.getConstant(0, VT);
2658 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
2659 if (N1C && N0.getOpcode() == ISD::SRL &&
2660 N0.getOperand(1).getOpcode() == ISD::Constant) {
2661 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
2662 uint64_t c2 = N1C->getZExtValue();
2663 if (c1 + c2 > OpSizeInBits)
2664 return DAG.getConstant(0, VT);
2665 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
2666 DAG.getConstant(c1 + c2, N1.getValueType()));
2669 // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
2670 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2671 // Shifting in all undef bits?
2672 EVT SmallVT = N0.getOperand(0).getValueType();
2673 if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
2674 return DAG.getUNDEF(VT);
2676 SDValue SmallShift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), SmallVT,
2677 N0.getOperand(0), N1);
2678 AddToWorkList(SmallShift.getNode());
2679 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, SmallShift);
2682 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
2683 // bit, which is unmodified by sra.
2684 if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
2685 if (N0.getOpcode() == ISD::SRA)
2686 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0), N1);
2689 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
2690 if (N1C && N0.getOpcode() == ISD::CTLZ &&
2691 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
2692 APInt KnownZero, KnownOne;
2693 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
2694 DAG.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
2696 // If any of the input bits are KnownOne, then the input couldn't be all
2697 // zeros, thus the result of the srl will always be zero.
2698 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
2700 // If all of the bits input the to ctlz node are known to be zero, then
2701 // the result of the ctlz is "32" and the result of the shift is one.
2702 APInt UnknownBits = ~KnownZero & Mask;
2703 if (UnknownBits == 0) return DAG.getConstant(1, VT);
2705 // Otherwise, check to see if there is exactly one bit input to the ctlz.
2706 if ((UnknownBits & (UnknownBits - 1)) == 0) {
2707 // Okay, we know that only that the single bit specified by UnknownBits
2708 // could be set on input to the CTLZ node. If this bit is set, the SRL
2709 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
2710 // to an SRL/XOR pair, which is likely to simplify more.
2711 unsigned ShAmt = UnknownBits.countTrailingZeros();
2712 SDValue Op = N0.getOperand(0);
2715 Op = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT, Op,
2716 DAG.getConstant(ShAmt, getShiftAmountTy()));
2717 AddToWorkList(Op.getNode());
2720 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
2721 Op, DAG.getConstant(1, VT));
2725 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
2726 if (N1.getOpcode() == ISD::TRUNCATE &&
2727 N1.getOperand(0).getOpcode() == ISD::AND &&
2728 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
2729 SDValue N101 = N1.getOperand(0).getOperand(1);
2730 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
2731 EVT TruncVT = N1.getValueType();
2732 SDValue N100 = N1.getOperand(0).getOperand(0);
2733 APInt TruncC = N101C->getAPIntValue();
2734 TruncC.trunc(TruncVT.getSizeInBits());
2735 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
2736 DAG.getNode(ISD::AND, N->getDebugLoc(),
2738 DAG.getNode(ISD::TRUNCATE,
2741 DAG.getConstant(TruncC, TruncVT)));
2745 // fold operands of srl based on knowledge that the low bits are not
2747 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
2748 return SDValue(N, 0);
2750 return N1C ? visitShiftByConstant(N, N1C->getZExtValue()) : SDValue();
2753 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
2754 SDValue N0 = N->getOperand(0);
2755 EVT VT = N->getValueType(0);
2757 // fold (ctlz c1) -> c2
2758 if (isa<ConstantSDNode>(N0))
2759 return DAG.getNode(ISD::CTLZ, N->getDebugLoc(), VT, N0);
2763 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
2764 SDValue N0 = N->getOperand(0);
2765 EVT VT = N->getValueType(0);
2767 // fold (cttz c1) -> c2
2768 if (isa<ConstantSDNode>(N0))
2769 return DAG.getNode(ISD::CTTZ, N->getDebugLoc(), VT, N0);
2773 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
2774 SDValue N0 = N->getOperand(0);
2775 EVT VT = N->getValueType(0);
2777 // fold (ctpop c1) -> c2
2778 if (isa<ConstantSDNode>(N0))
2779 return DAG.getNode(ISD::CTPOP, N->getDebugLoc(), VT, N0);
2783 SDValue DAGCombiner::visitSELECT(SDNode *N) {
2784 SDValue N0 = N->getOperand(0);
2785 SDValue N1 = N->getOperand(1);
2786 SDValue N2 = N->getOperand(2);
2787 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2788 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2789 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
2790 EVT VT = N->getValueType(0);
2791 EVT VT0 = N0.getValueType();
2793 // fold (select C, X, X) -> X
2796 // fold (select true, X, Y) -> X
2797 if (N0C && !N0C->isNullValue())
2799 // fold (select false, X, Y) -> Y
2800 if (N0C && N0C->isNullValue())
2802 // fold (select C, 1, X) -> (or C, X)
2803 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
2804 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
2805 // fold (select C, 0, 1) -> (xor C, 1)
2806 if (VT.isInteger() &&
2809 TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent)) &&
2810 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
2813 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT0,
2814 N0, DAG.getConstant(1, VT0));
2815 XORNode = DAG.getNode(ISD::XOR, N0.getDebugLoc(), VT0,
2816 N0, DAG.getConstant(1, VT0));
2817 AddToWorkList(XORNode.getNode());
2819 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, XORNode);
2820 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, XORNode);
2822 // fold (select C, 0, X) -> (and (not C), X)
2823 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
2824 SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
2825 AddToWorkList(NOTNode.getNode());
2826 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, NOTNode, N2);
2828 // fold (select C, X, 1) -> (or (not C), X)
2829 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
2830 SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
2831 AddToWorkList(NOTNode.getNode());
2832 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, NOTNode, N1);
2834 // fold (select C, X, 0) -> (and C, X)
2835 if (VT == MVT::i1 && N2C && N2C->isNullValue())
2836 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
2837 // fold (select X, X, Y) -> (or X, Y)
2838 // fold (select X, 1, Y) -> (or X, Y)
2839 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
2840 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
2841 // fold (select X, Y, X) -> (and X, Y)
2842 // fold (select X, Y, 0) -> (and X, Y)
2843 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
2844 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
2846 // If we can fold this based on the true/false value, do so.
2847 if (SimplifySelectOps(N, N1, N2))
2848 return SDValue(N, 0); // Don't revisit N.
2850 // fold selects based on a setcc into other things, such as min/max/abs
2851 if (N0.getOpcode() == ISD::SETCC) {
2853 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
2854 // having to say they don't support SELECT_CC on every type the DAG knows
2855 // about, since there is no way to mark an opcode illegal at all value types
2856 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
2857 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
2858 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT,
2859 N0.getOperand(0), N0.getOperand(1),
2860 N1, N2, N0.getOperand(2));
2861 return SimplifySelect(N->getDebugLoc(), N0, N1, N2);
2867 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
2868 SDValue N0 = N->getOperand(0);
2869 SDValue N1 = N->getOperand(1);
2870 SDValue N2 = N->getOperand(2);
2871 SDValue N3 = N->getOperand(3);
2872 SDValue N4 = N->getOperand(4);
2873 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
2875 // fold select_cc lhs, rhs, x, x, cc -> x
2879 // Determine if the condition we're dealing with is constant
2880 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
2881 N0, N1, CC, N->getDebugLoc(), false);
2882 if (SCC.getNode()) AddToWorkList(SCC.getNode());
2884 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
2885 if (!SCCC->isNullValue())
2886 return N2; // cond always true -> true val
2888 return N3; // cond always false -> false val
2891 // Fold to a simpler select_cc
2892 if (SCC.getNode() && SCC.getOpcode() == ISD::SETCC)
2893 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), N2.getValueType(),
2894 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
2897 // If we can fold this based on the true/false value, do so.
2898 if (SimplifySelectOps(N, N2, N3))
2899 return SDValue(N, 0); // Don't revisit N.
2901 // fold select_cc into other things, such as min/max/abs
2902 return SimplifySelectCC(N->getDebugLoc(), N0, N1, N2, N3, CC);
2905 SDValue DAGCombiner::visitSETCC(SDNode *N) {
2906 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
2907 cast<CondCodeSDNode>(N->getOperand(2))->get(),
2911 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
2912 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
2913 // transformation. Returns true if extension are possible and the above
2914 // mentioned transformation is profitable.
2915 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
2917 SmallVector<SDNode*, 4> &ExtendNodes,
2918 const TargetLowering &TLI) {
2919 bool HasCopyToRegUses = false;
2920 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
2921 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
2922 UE = N0.getNode()->use_end();
2927 if (UI.getUse().getResNo() != N0.getResNo())
2929 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
2930 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
2931 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
2932 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
2933 // Sign bits will be lost after a zext.
2936 for (unsigned i = 0; i != 2; ++i) {
2937 SDValue UseOp = User->getOperand(i);
2940 if (!isa<ConstantSDNode>(UseOp))
2945 ExtendNodes.push_back(User);
2948 // If truncates aren't free and there are users we can't
2949 // extend, it isn't worthwhile.
2952 // Remember if this value is live-out.
2953 if (User->getOpcode() == ISD::CopyToReg)
2954 HasCopyToRegUses = true;
2957 if (HasCopyToRegUses) {
2958 bool BothLiveOut = false;
2959 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
2961 SDUse &Use = UI.getUse();
2962 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
2968 // Both unextended and extended values are live out. There had better be
2969 // good a reason for the transformation.
2970 return ExtendNodes.size();
2975 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
2976 SDValue N0 = N->getOperand(0);
2977 EVT VT = N->getValueType(0);
2979 // fold (sext c1) -> c1
2980 if (isa<ConstantSDNode>(N0))
2981 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N0);
2983 // fold (sext (sext x)) -> (sext x)
2984 // fold (sext (aext x)) -> (sext x)
2985 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2986 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT,
2989 if (N0.getOpcode() == ISD::TRUNCATE) {
2990 // fold (sext (truncate (load x))) -> (sext (smaller load x))
2991 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
2992 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
2993 if (NarrowLoad.getNode()) {
2994 if (NarrowLoad.getNode() != N0.getNode())
2995 CombineTo(N0.getNode(), NarrowLoad);
2996 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2999 // See if the value being truncated is already sign extended. If so, just
3000 // eliminate the trunc/sext pair.
3001 SDValue Op = N0.getOperand(0);
3002 unsigned OpBits = Op.getValueType().getSizeInBits();
3003 unsigned MidBits = N0.getValueType().getSizeInBits();
3004 unsigned DestBits = VT.getSizeInBits();
3005 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
3007 if (OpBits == DestBits) {
3008 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
3009 // bits, it is already ready.
3010 if (NumSignBits > DestBits-MidBits)
3012 } else if (OpBits < DestBits) {
3013 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
3014 // bits, just sext from i32.
3015 if (NumSignBits > OpBits-MidBits)
3016 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, Op);
3018 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
3019 // bits, just truncate to i32.
3020 if (NumSignBits > OpBits-MidBits)
3021 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
3024 // fold (sext (truncate x)) -> (sextinreg x).
3025 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
3026 N0.getValueType())) {
3027 if (Op.getValueType().bitsLT(VT))
3028 Op = DAG.getNode(ISD::ANY_EXTEND, N0.getDebugLoc(), VT, Op);
3029 else if (Op.getValueType().bitsGT(VT))
3030 Op = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), VT, Op);
3031 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, Op,
3032 DAG.getValueType(N0.getValueType()));
3036 // fold (sext (load x)) -> (sext (truncate (sextload x)))
3037 if (ISD::isNON_EXTLoad(N0.getNode()) &&
3038 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3039 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
3040 bool DoXform = true;
3041 SmallVector<SDNode*, 4> SetCCs;
3042 if (!N0.hasOneUse())
3043 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
3045 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3046 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
3048 LN0->getBasePtr(), LN0->getSrcValue(),
3049 LN0->getSrcValueOffset(),
3051 LN0->isVolatile(), LN0->getAlignment());
3052 CombineTo(N, ExtLoad);
3053 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3054 N0.getValueType(), ExtLoad);
3055 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
3057 // Extend SetCC uses if necessary.
3058 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
3059 SDNode *SetCC = SetCCs[i];
3060 SmallVector<SDValue, 4> Ops;
3062 for (unsigned j = 0; j != 2; ++j) {
3063 SDValue SOp = SetCC->getOperand(j);
3065 Ops.push_back(ExtLoad);
3067 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND,
3068 N->getDebugLoc(), VT, SOp));
3071 Ops.push_back(SetCC->getOperand(2));
3072 CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
3073 SetCC->getValueType(0),
3074 &Ops[0], Ops.size()));
3077 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3081 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
3082 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
3083 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
3084 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
3085 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3086 EVT EVT = LN0->getMemoryVT();
3087 if ((!LegalOperations && !LN0->isVolatile()) ||
3088 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT)) {
3089 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
3091 LN0->getBasePtr(), LN0->getSrcValue(),
3092 LN0->getSrcValueOffset(), EVT,
3093 LN0->isVolatile(), LN0->getAlignment());
3094 CombineTo(N, ExtLoad);
3095 CombineTo(N0.getNode(),
3096 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3097 N0.getValueType(), ExtLoad),
3098 ExtLoad.getValue(1));
3099 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3103 if (N0.getOpcode() == ISD::SETCC) {
3104 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
3105 if (VT.isVector() &&
3106 // We know that the # elements of the results is the same as the
3107 // # elements of the compare (and the # elements of the compare result
3108 // for that matter). Check to see that they are the same size. If so,
3109 // we know that the element size of the sext'd result matches the
3110 // element size of the compare operands.
3111 VT.getSizeInBits() == N0.getOperand(0).getValueType().getSizeInBits() &&
3113 // Only do this before legalize for now.
3115 return DAG.getVSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
3117 cast<CondCodeSDNode>(N0.getOperand(2))->get());
3120 // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
3122 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
3124 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
3125 NegOne, DAG.getConstant(0, VT),
3126 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3127 if (SCC.getNode()) return SCC;
3132 // fold (sext x) -> (zext x) if the sign bit is known zero.
3133 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
3134 DAG.SignBitIsZero(N0))
3135 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
3140 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
3141 SDValue N0 = N->getOperand(0);
3142 EVT VT = N->getValueType(0);
3144 // fold (zext c1) -> c1
3145 if (isa<ConstantSDNode>(N0))
3146 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
3147 // fold (zext (zext x)) -> (zext x)
3148 // fold (zext (aext x)) -> (zext x)
3149 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
3150 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT,
3153 // fold (zext (truncate (load x))) -> (zext (smaller load x))
3154 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
3155 if (N0.getOpcode() == ISD::TRUNCATE) {
3156 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3157 if (NarrowLoad.getNode()) {
3158 if (NarrowLoad.getNode() != N0.getNode())
3159 CombineTo(N0.getNode(), NarrowLoad);
3160 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, NarrowLoad);
3164 // fold (zext (truncate x)) -> (and x, mask)
3165 if (N0.getOpcode() == ISD::TRUNCATE &&
3166 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
3167 SDValue Op = N0.getOperand(0);
3168 if (Op.getValueType().bitsLT(VT)) {
3169 Op = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, Op);
3170 } else if (Op.getValueType().bitsGT(VT)) {
3171 Op = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
3173 return DAG.getZeroExtendInReg(Op, N->getDebugLoc(), N0.getValueType());
3176 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
3177 // if either of the casts is not free.
3178 if (N0.getOpcode() == ISD::AND &&
3179 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
3180 N0.getOperand(1).getOpcode() == ISD::Constant &&
3181 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
3182 N0.getValueType()) ||
3183 !TLI.isZExtFree(N0.getValueType(), VT))) {
3184 SDValue X = N0.getOperand(0).getOperand(0);
3185 if (X.getValueType().bitsLT(VT)) {
3186 X = DAG.getNode(ISD::ANY_EXTEND, X.getDebugLoc(), VT, X);
3187 } else if (X.getValueType().bitsGT(VT)) {
3188 X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
3190 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3191 Mask.zext(VT.getSizeInBits());
3192 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3193 X, DAG.getConstant(Mask, VT));
3196 // fold (zext (load x)) -> (zext (truncate (zextload x)))
3197 if (ISD::isNON_EXTLoad(N0.getNode()) &&
3198 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3199 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
3200 bool DoXform = true;
3201 SmallVector<SDNode*, 4> SetCCs;
3202 if (!N0.hasOneUse())
3203 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
3205 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3206 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
3208 LN0->getBasePtr(), LN0->getSrcValue(),
3209 LN0->getSrcValueOffset(),
3211 LN0->isVolatile(), LN0->getAlignment());
3212 CombineTo(N, ExtLoad);
3213 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3214 N0.getValueType(), ExtLoad);
3215 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
3217 // Extend SetCC uses if necessary.
3218 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
3219 SDNode *SetCC = SetCCs[i];
3220 SmallVector<SDValue, 4> Ops;
3222 for (unsigned j = 0; j != 2; ++j) {
3223 SDValue SOp = SetCC->getOperand(j);
3225 Ops.push_back(ExtLoad);
3227 Ops.push_back(DAG.getNode(ISD::ZERO_EXTEND,
3228 N->getDebugLoc(), VT, SOp));
3231 Ops.push_back(SetCC->getOperand(2));
3232 CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
3233 SetCC->getValueType(0),
3234 &Ops[0], Ops.size()));
3237 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3241 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
3242 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
3243 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
3244 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
3245 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3246 EVT EVT = LN0->getMemoryVT();
3247 if ((!LegalOperations && !LN0->isVolatile()) ||
3248 TLI.isLoadExtLegal(ISD::ZEXTLOAD, EVT)) {
3249 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
3251 LN0->getBasePtr(), LN0->getSrcValue(),
3252 LN0->getSrcValueOffset(), EVT,
3253 LN0->isVolatile(), LN0->getAlignment());
3254 CombineTo(N, ExtLoad);
3255 CombineTo(N0.getNode(),
3256 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), N0.getValueType(),
3258 ExtLoad.getValue(1));
3259 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3263 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3264 if (N0.getOpcode() == ISD::SETCC) {
3266 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
3267 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3268 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3269 if (SCC.getNode()) return SCC;
3275 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
3276 SDValue N0 = N->getOperand(0);
3277 EVT VT = N->getValueType(0);
3279 // fold (aext c1) -> c1
3280 if (isa<ConstantSDNode>(N0))
3281 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, N0);
3282 // fold (aext (aext x)) -> (aext x)
3283 // fold (aext (zext x)) -> (zext x)
3284 // fold (aext (sext x)) -> (sext x)
3285 if (N0.getOpcode() == ISD::ANY_EXTEND ||
3286 N0.getOpcode() == ISD::ZERO_EXTEND ||
3287 N0.getOpcode() == ISD::SIGN_EXTEND)
3288 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, N0.getOperand(0));
3290 // fold (aext (truncate (load x))) -> (aext (smaller load x))
3291 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
3292 if (N0.getOpcode() == ISD::TRUNCATE) {
3293 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3294 if (NarrowLoad.getNode()) {
3295 if (NarrowLoad.getNode() != N0.getNode())
3296 CombineTo(N0.getNode(), NarrowLoad);
3297 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, NarrowLoad);
3301 // fold (aext (truncate x))
3302 if (N0.getOpcode() == ISD::TRUNCATE) {
3303 SDValue TruncOp = N0.getOperand(0);
3304 if (TruncOp.getValueType() == VT)
3305 return TruncOp; // x iff x size == zext size.
3306 if (TruncOp.getValueType().bitsGT(VT))
3307 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, TruncOp);
3308 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, TruncOp);
3311 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
3312 // if the trunc is not free.
3313 if (N0.getOpcode() == ISD::AND &&
3314 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
3315 N0.getOperand(1).getOpcode() == ISD::Constant &&
3316 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
3317 N0.getValueType())) {
3318 SDValue X = N0.getOperand(0).getOperand(0);
3319 if (X.getValueType().bitsLT(VT)) {
3320 X = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, X);
3321 } else if (X.getValueType().bitsGT(VT)) {
3322 X = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, X);
3324 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3325 Mask.zext(VT.getSizeInBits());
3326 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3327 X, DAG.getConstant(Mask, VT));
3330 // fold (aext (load x)) -> (aext (truncate (extload x)))
3331 if (ISD::isNON_EXTLoad(N0.getNode()) &&
3332 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3333 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
3334 bool DoXform = true;
3335 SmallVector<SDNode*, 4> SetCCs;
3336 if (!N0.hasOneUse())
3337 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
3339 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3340 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
3342 LN0->getBasePtr(), LN0->getSrcValue(),
3343 LN0->getSrcValueOffset(),
3345 LN0->isVolatile(), LN0->getAlignment());
3346 CombineTo(N, ExtLoad);
3347 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3348 N0.getValueType(), ExtLoad);
3349 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
3351 // Extend SetCC uses if necessary.
3352 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
3353 SDNode *SetCC = SetCCs[i];
3354 SmallVector<SDValue, 4> Ops;
3356 for (unsigned j = 0; j != 2; ++j) {
3357 SDValue SOp = SetCC->getOperand(j);
3359 Ops.push_back(ExtLoad);
3361 Ops.push_back(DAG.getNode(ISD::ANY_EXTEND,
3362 N->getDebugLoc(), VT, SOp));
3365 Ops.push_back(SetCC->getOperand(2));
3366 CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
3367 SetCC->getValueType(0),
3368 &Ops[0], Ops.size()));
3371 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3375 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
3376 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
3377 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
3378 if (N0.getOpcode() == ISD::LOAD &&
3379 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3381 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3382 EVT EVT = LN0->getMemoryVT();
3383 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), N->getDebugLoc(),
3384 VT, LN0->getChain(), LN0->getBasePtr(),
3386 LN0->getSrcValueOffset(), EVT,
3387 LN0->isVolatile(), LN0->getAlignment());
3388 CombineTo(N, ExtLoad);
3389 CombineTo(N0.getNode(),
3390 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3391 N0.getValueType(), ExtLoad),
3392 ExtLoad.getValue(1));
3393 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3396 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3397 if (N0.getOpcode() == ISD::SETCC) {
3399 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
3400 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3401 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3409 /// GetDemandedBits - See if the specified operand can be simplified with the
3410 /// knowledge that only the bits specified by Mask are used. If so, return the
3411 /// simpler operand, otherwise return a null SDValue.
3412 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
3413 switch (V.getOpcode()) {
3417 // If the LHS or RHS don't contribute bits to the or, drop them.
3418 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
3419 return V.getOperand(1);
3420 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
3421 return V.getOperand(0);
3424 // Only look at single-use SRLs.
3425 if (!V.getNode()->hasOneUse())
3427 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
3428 // See if we can recursively simplify the LHS.
3429 unsigned Amt = RHSC->getZExtValue();
3431 // Watch out for shift count overflow though.
3432 if (Amt >= Mask.getBitWidth()) break;
3433 APInt NewMask = Mask << Amt;
3434 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
3435 if (SimplifyLHS.getNode())
3436 return DAG.getNode(ISD::SRL, V.getDebugLoc(), V.getValueType(),
3437 SimplifyLHS, V.getOperand(1));
3443 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
3444 /// bits and then truncated to a narrower type and where N is a multiple
3445 /// of number of bits of the narrower type, transform it to a narrower load
3446 /// from address + N / num of bits of new type. If the result is to be
3447 /// extended, also fold the extension to form a extending load.
3448 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
3449 unsigned Opc = N->getOpcode();
3450 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
3451 SDValue N0 = N->getOperand(0);
3452 EVT VT = N->getValueType(0);
3455 // This transformation isn't valid for vector loads.
3459 // Special case: SIGN_EXTEND_INREG is basically truncating to EVT then
3461 if (Opc == ISD::SIGN_EXTEND_INREG) {
3462 ExtType = ISD::SEXTLOAD;
3463 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
3464 if (LegalOperations && !TLI.isLoadExtLegal(ISD::SEXTLOAD, ExtVT))
3468 unsigned EVTBits = ExtVT.getSizeInBits();
3470 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse() && ExtVT.isRound()) {
3471 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3472 ShAmt = N01->getZExtValue();
3473 // Is the shift amount a multiple of size of VT?
3474 if ((ShAmt & (EVTBits-1)) == 0) {
3475 N0 = N0.getOperand(0);
3476 // Is the load width a multiple of size of VT?
3477 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
3483 // Do not generate loads of non-round integer types since these can
3484 // be expensive (and would be wrong if the type is not byte sized).
3485 if (isa<LoadSDNode>(N0) && N0.hasOneUse() && ExtVT.isRound() &&
3486 cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits() > EVTBits &&
3487 // Do not change the width of a volatile load.
3488 !cast<LoadSDNode>(N0)->isVolatile()) {
3489 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3490 EVT PtrType = N0.getOperand(1).getValueType();
3492 // For big endian targets, we need to adjust the offset to the pointer to
3493 // load the correct bytes.
3494 if (TLI.isBigEndian()) {
3495 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
3496 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
3497 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
3500 uint64_t PtrOff = ShAmt / 8;
3501 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
3502 SDValue NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(),
3503 PtrType, LN0->getBasePtr(),
3504 DAG.getConstant(PtrOff, PtrType));
3505 AddToWorkList(NewPtr.getNode());
3507 SDValue Load = (ExtType == ISD::NON_EXTLOAD)
3508 ? DAG.getLoad(VT, N0.getDebugLoc(), LN0->getChain(), NewPtr,
3509 LN0->getSrcValue(), LN0->getSrcValueOffset() + PtrOff,
3510 LN0->isVolatile(), NewAlign)
3511 : DAG.getExtLoad(ExtType, N0.getDebugLoc(), VT, LN0->getChain(), NewPtr,
3512 LN0->getSrcValue(), LN0->getSrcValueOffset() + PtrOff,
3513 ExtVT, LN0->isVolatile(), NewAlign);
3515 // Replace the old load's chain with the new load's chain.
3516 WorkListRemover DeadNodes(*this);
3517 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1),
3520 // Return the new loaded value.
3527 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
3528 SDValue N0 = N->getOperand(0);
3529 SDValue N1 = N->getOperand(1);
3530 EVT VT = N->getValueType(0);
3531 EVT EVT = cast<VTSDNode>(N1)->getVT();
3532 unsigned VTBits = VT.getSizeInBits();
3533 unsigned EVTBits = EVT.getSizeInBits();
3535 // fold (sext_in_reg c1) -> c1
3536 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
3537 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, N0, N1);
3539 // If the input is already sign extended, just drop the extension.
3540 if (DAG.ComputeNumSignBits(N0) >= VT.getSizeInBits()-EVTBits+1)
3543 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
3544 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3545 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) {
3546 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
3547 N0.getOperand(0), N1);
3550 // fold (sext_in_reg (sext x)) -> (sext x)
3551 // fold (sext_in_reg (aext x)) -> (sext x)
3552 // if x is small enough.
3553 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
3554 SDValue N00 = N0.getOperand(0);
3555 if (N00.getValueType().getSizeInBits() < EVTBits)
3556 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N00, N1);
3559 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
3560 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
3561 return DAG.getZeroExtendInReg(N0, N->getDebugLoc(), EVT);
3563 // fold operands of sext_in_reg based on knowledge that the top bits are not
3565 if (SimplifyDemandedBits(SDValue(N, 0)))
3566 return SDValue(N, 0);
3568 // fold (sext_in_reg (load x)) -> (smaller sextload x)
3569 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
3570 SDValue NarrowLoad = ReduceLoadWidth(N);
3571 if (NarrowLoad.getNode())
3574 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
3575 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
3576 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
3577 if (N0.getOpcode() == ISD::SRL) {
3578 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
3579 if (ShAmt->getZExtValue()+EVTBits <= VT.getSizeInBits()) {
3580 // We can turn this into an SRA iff the input to the SRL is already sign
3582 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
3583 if (VT.getSizeInBits()-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
3584 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT,
3585 N0.getOperand(0), N0.getOperand(1));
3589 // fold (sext_inreg (extload x)) -> (sextload x)
3590 if (ISD::isEXTLoad(N0.getNode()) &&
3591 ISD::isUNINDEXEDLoad(N0.getNode()) &&
3592 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
3593 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3594 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
3595 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3596 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
3598 LN0->getBasePtr(), LN0->getSrcValue(),
3599 LN0->getSrcValueOffset(), EVT,
3600 LN0->isVolatile(), LN0->getAlignment());
3601 CombineTo(N, ExtLoad);
3602 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3603 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3605 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
3606 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3608 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
3609 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3610 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
3611 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3612 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
3614 LN0->getBasePtr(), LN0->getSrcValue(),
3615 LN0->getSrcValueOffset(), EVT,
3616 LN0->isVolatile(), LN0->getAlignment());
3617 CombineTo(N, ExtLoad);
3618 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3619 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3624 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
3625 SDValue N0 = N->getOperand(0);
3626 EVT VT = N->getValueType(0);
3629 if (N0.getValueType() == N->getValueType(0))
3631 // fold (truncate c1) -> c1
3632 if (isa<ConstantSDNode>(N0))
3633 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0);
3634 // fold (truncate (truncate x)) -> (truncate x)
3635 if (N0.getOpcode() == ISD::TRUNCATE)
3636 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
3637 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
3638 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::SIGN_EXTEND||
3639 N0.getOpcode() == ISD::ANY_EXTEND) {
3640 if (N0.getOperand(0).getValueType().bitsLT(VT))
3641 // if the source is smaller than the dest, we still need an extend
3642 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
3644 else if (N0.getOperand(0).getValueType().bitsGT(VT))
3645 // if the source is larger than the dest, than we just need the truncate
3646 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
3648 // if the source and dest are the same type, we can drop both the extend
3650 return N0.getOperand(0);
3653 // See if we can simplify the input to this truncate through knowledge that
3654 // only the low bits are being used. For example "trunc (or (shl x, 8), y)"
3657 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
3658 VT.getSizeInBits()));
3659 if (Shorter.getNode())
3660 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Shorter);
3662 // fold (truncate (load x)) -> (smaller load x)
3663 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
3664 return ReduceLoadWidth(N);
3667 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
3668 SDValue Elt = N->getOperand(i);
3669 if (Elt.getOpcode() != ISD::MERGE_VALUES)
3670 return Elt.getNode();
3671 return Elt.getOperand(Elt.getResNo()).getNode();
3674 /// CombineConsecutiveLoads - build_pair (load, load) -> load
3675 /// if load locations are consecutive.
3676 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
3677 assert(N->getOpcode() == ISD::BUILD_PAIR);
3679 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
3680 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
3681 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse())
3683 EVT LD1VT = LD1->getValueType(0);
3684 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3686 if (ISD::isNON_EXTLoad(LD2) &&
3688 // If both are volatile this would reduce the number of volatile loads.
3689 // If one is volatile it might be ok, but play conservative and bail out.
3690 !LD1->isVolatile() &&
3691 !LD2->isVolatile() &&
3692 TLI.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1, MFI)) {
3693 unsigned Align = LD1->getAlignment();
3694 unsigned NewAlign = TLI.getTargetData()->
3695 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
3697 if (NewAlign <= Align &&
3698 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
3699 return DAG.getLoad(VT, N->getDebugLoc(), LD1->getChain(),
3700 LD1->getBasePtr(), LD1->getSrcValue(),
3701 LD1->getSrcValueOffset(), false, Align);
3707 SDValue DAGCombiner::visitBIT_CONVERT(SDNode *N) {
3708 SDValue N0 = N->getOperand(0);
3709 EVT VT = N->getValueType(0);
3711 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
3712 // Only do this before legalize, since afterward the target may be depending
3713 // on the bitconvert.
3714 // First check to see if this is all constant.
3716 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
3718 bool isSimple = true;
3719 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
3720 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
3721 N0.getOperand(i).getOpcode() != ISD::Constant &&
3722 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
3727 EVT DestEltVT = N->getValueType(0).getVectorElementType();
3728 assert(!DestEltVT.isVector() &&
3729 "Element type of vector ValueType must not be vector!");
3731 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(N0.getNode(), DestEltVT);
3734 // If the input is a constant, let getNode fold it.
3735 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
3736 SDValue Res = DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, N0);
3737 if (Res.getNode() != N) {
3738 if (!LegalOperations ||
3739 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
3742 // Folding it resulted in an illegal node, and it's too late to
3743 // do that. Clean up the old node and forego the transformation.
3744 // Ideally this won't happen very often, because instcombine
3745 // and the earlier dagcombine runs (where illegal nodes are
3746 // permitted) should have folded most of them already.
3747 DAG.DeleteNode(Res.getNode());
3751 // (conv (conv x, t1), t2) -> (conv x, t2)
3752 if (N0.getOpcode() == ISD::BIT_CONVERT)
3753 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT,
3756 // fold (conv (load x)) -> (load (conv*)x)
3757 // If the resultant load doesn't need a higher alignment than the original!
3758 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
3759 // Do not change the width of a volatile load.
3760 !cast<LoadSDNode>(N0)->isVolatile() &&
3761 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
3762 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3763 unsigned Align = TLI.getTargetData()->
3764 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
3765 unsigned OrigAlign = LN0->getAlignment();
3767 if (Align <= OrigAlign) {
3768 SDValue Load = DAG.getLoad(VT, N->getDebugLoc(), LN0->getChain(),
3770 LN0->getSrcValue(), LN0->getSrcValueOffset(),
3771 LN0->isVolatile(), OrigAlign);
3773 CombineTo(N0.getNode(),
3774 DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(),
3775 N0.getValueType(), Load),
3781 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
3782 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
3783 // This often reduces constant pool loads.
3784 if ((N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FABS) &&
3785 N0.getNode()->hasOneUse() && VT.isInteger() && !VT.isVector()) {
3786 SDValue NewConv = DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(), VT,
3788 AddToWorkList(NewConv.getNode());
3790 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
3791 if (N0.getOpcode() == ISD::FNEG)
3792 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
3793 NewConv, DAG.getConstant(SignBit, VT));
3794 assert(N0.getOpcode() == ISD::FABS);
3795 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3796 NewConv, DAG.getConstant(~SignBit, VT));
3799 // fold (bitconvert (fcopysign cst, x)) ->
3800 // (or (and (bitconvert x), sign), (and cst, (not sign)))
3801 // Note that we don't handle (copysign x, cst) because this can always be
3802 // folded to an fneg or fabs.
3803 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
3804 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
3805 VT.isInteger() && !VT.isVector()) {
3806 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
3807 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
3808 if (TLI.isTypeLegal(IntXVT) || !LegalTypes) {
3809 SDValue X = DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(),
3810 IntXVT, N0.getOperand(1));
3811 AddToWorkList(X.getNode());
3813 // If X has a different width than the result/lhs, sext it or truncate it.
3814 unsigned VTWidth = VT.getSizeInBits();
3815 if (OrigXWidth < VTWidth) {
3816 X = DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, X);
3817 AddToWorkList(X.getNode());
3818 } else if (OrigXWidth > VTWidth) {
3819 // To get the sign bit in the right place, we have to shift it right
3820 // before truncating.
3821 X = DAG.getNode(ISD::SRL, X.getDebugLoc(),
3822 X.getValueType(), X,
3823 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
3824 AddToWorkList(X.getNode());
3825 X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
3826 AddToWorkList(X.getNode());
3829 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
3830 X = DAG.getNode(ISD::AND, X.getDebugLoc(), VT,
3831 X, DAG.getConstant(SignBit, VT));
3832 AddToWorkList(X.getNode());
3834 SDValue Cst = DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(),
3835 VT, N0.getOperand(0));
3836 Cst = DAG.getNode(ISD::AND, Cst.getDebugLoc(), VT,
3837 Cst, DAG.getConstant(~SignBit, VT));
3838 AddToWorkList(Cst.getNode());
3840 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, X, Cst);
3844 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
3845 if (N0.getOpcode() == ISD::BUILD_PAIR) {
3846 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
3847 if (CombineLD.getNode())
3854 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
3855 EVT VT = N->getValueType(0);
3856 return CombineConsecutiveLoads(N, VT);
3859 /// ConstantFoldBIT_CONVERTofBUILD_VECTOR - We know that BV is a build_vector
3860 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
3861 /// destination element value type.
3862 SDValue DAGCombiner::
3863 ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
3864 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
3866 // If this is already the right type, we're done.
3867 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
3869 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
3870 unsigned DstBitSize = DstEltVT.getSizeInBits();
3872 // If this is a conversion of N elements of one type to N elements of another
3873 // type, convert each element. This handles FP<->INT cases.
3874 if (SrcBitSize == DstBitSize) {
3875 SmallVector<SDValue, 8> Ops;
3876 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3877 SDValue Op = BV->getOperand(i);
3878 // If the vector element type is not legal, the BUILD_VECTOR operands
3879 // are promoted and implicitly truncated. Make that explicit here.
3880 if (Op.getValueType() != SrcEltVT)
3881 Op = DAG.getNode(ISD::TRUNCATE, BV->getDebugLoc(), SrcEltVT, Op);
3882 Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, BV->getDebugLoc(),
3884 AddToWorkList(Ops.back().getNode());
3886 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
3887 BV->getValueType(0).getVectorNumElements());
3888 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
3889 &Ops[0], Ops.size());
3892 // Otherwise, we're growing or shrinking the elements. To avoid having to
3893 // handle annoying details of growing/shrinking FP values, we convert them to
3895 if (SrcEltVT.isFloatingPoint()) {
3896 // Convert the input float vector to a int vector where the elements are the
3898 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
3899 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
3900 BV = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, IntVT).getNode();
3904 // Now we know the input is an integer vector. If the output is a FP type,
3905 // convert to integer first, then to FP of the right size.
3906 if (DstEltVT.isFloatingPoint()) {
3907 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
3908 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
3909 SDNode *Tmp = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, TmpVT).getNode();
3911 // Next, convert to FP elements of the same size.
3912 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(Tmp, DstEltVT);
3915 // Okay, we know the src/dst types are both integers of differing types.
3916 // Handling growing first.
3917 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
3918 if (SrcBitSize < DstBitSize) {
3919 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
3921 SmallVector<SDValue, 8> Ops;
3922 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
3923 i += NumInputsPerOutput) {
3924 bool isLE = TLI.isLittleEndian();
3925 APInt NewBits = APInt(DstBitSize, 0);
3926 bool EltIsUndef = true;
3927 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
3928 // Shift the previously computed bits over.
3929 NewBits <<= SrcBitSize;
3930 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
3931 if (Op.getOpcode() == ISD::UNDEF) continue;
3934 NewBits |= (APInt(cast<ConstantSDNode>(Op)->getAPIntValue()).
3935 zextOrTrunc(SrcBitSize).zext(DstBitSize));
3939 Ops.push_back(DAG.getUNDEF(DstEltVT));
3941 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
3944 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
3945 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
3946 &Ops[0], Ops.size());
3949 // Finally, this must be the case where we are shrinking elements: each input
3950 // turns into multiple outputs.
3951 bool isS2V = ISD::isScalarToVector(BV);
3952 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
3953 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
3954 NumOutputsPerInput*BV->getNumOperands());
3955 SmallVector<SDValue, 8> Ops;
3957 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3958 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
3959 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
3960 Ops.push_back(DAG.getUNDEF(DstEltVT));
3964 APInt OpVal = APInt(cast<ConstantSDNode>(BV->getOperand(i))->
3965 getAPIntValue()).zextOrTrunc(SrcBitSize);
3967 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
3968 APInt ThisVal = APInt(OpVal).trunc(DstBitSize);
3969 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
3970 if (isS2V && i == 0 && j == 0 && APInt(ThisVal).zext(SrcBitSize) == OpVal)
3971 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
3972 return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
3974 OpVal = OpVal.lshr(DstBitSize);
3977 // For big endian targets, swap the order of the pieces of each element.
3978 if (TLI.isBigEndian())
3979 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
3982 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
3983 &Ops[0], Ops.size());
3986 SDValue DAGCombiner::visitFADD(SDNode *N) {
3987 SDValue N0 = N->getOperand(0);
3988 SDValue N1 = N->getOperand(1);
3989 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3990 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3991 EVT VT = N->getValueType(0);
3994 if (VT.isVector()) {
3995 SDValue FoldedVOp = SimplifyVBinOp(N);
3996 if (FoldedVOp.getNode()) return FoldedVOp;
3999 // fold (fadd c1, c2) -> (fadd c1, c2)
4000 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4001 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N1);
4002 // canonicalize constant to RHS
4003 if (N0CFP && !N1CFP)
4004 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N0);
4005 // fold (fadd A, 0) -> A
4006 if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
4008 // fold (fadd A, (fneg B)) -> (fsub A, B)
4009 if (isNegatibleForFree(N1, LegalOperations) == 2)
4010 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0,
4011 GetNegatedExpression(N1, DAG, LegalOperations));
4012 // fold (fadd (fneg A), B) -> (fsub B, A)
4013 if (isNegatibleForFree(N0, LegalOperations) == 2)
4014 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N1,
4015 GetNegatedExpression(N0, DAG, LegalOperations));
4017 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
4018 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FADD &&
4019 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
4020 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0.getOperand(0),
4021 DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
4022 N0.getOperand(1), N1));
4027 SDValue DAGCombiner::visitFSUB(SDNode *N) {
4028 SDValue N0 = N->getOperand(0);
4029 SDValue N1 = N->getOperand(1);
4030 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4031 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4032 EVT VT = N->getValueType(0);
4035 if (VT.isVector()) {
4036 SDValue FoldedVOp = SimplifyVBinOp(N);
4037 if (FoldedVOp.getNode()) return FoldedVOp;
4040 // fold (fsub c1, c2) -> c1-c2
4041 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4042 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0, N1);
4043 // fold (fsub A, 0) -> A
4044 if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
4046 // fold (fsub 0, B) -> -B
4047 if (UnsafeFPMath && N0CFP && N0CFP->getValueAPF().isZero()) {
4048 if (isNegatibleForFree(N1, LegalOperations))
4049 return GetNegatedExpression(N1, DAG, LegalOperations);
4050 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
4051 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N1);
4053 // fold (fsub A, (fneg B)) -> (fadd A, B)
4054 if (isNegatibleForFree(N1, LegalOperations))
4055 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0,
4056 GetNegatedExpression(N1, DAG, LegalOperations));
4061 SDValue DAGCombiner::visitFMUL(SDNode *N) {
4062 SDValue N0 = N->getOperand(0);
4063 SDValue N1 = N->getOperand(1);
4064 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4065 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4066 EVT VT = N->getValueType(0);
4069 if (VT.isVector()) {
4070 SDValue FoldedVOp = SimplifyVBinOp(N);
4071 if (FoldedVOp.getNode()) return FoldedVOp;
4074 // fold (fmul c1, c2) -> c1*c2
4075 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4076 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0, N1);
4077 // canonicalize constant to RHS
4078 if (N0CFP && !N1CFP)
4079 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N1, N0);
4080 // fold (fmul A, 0) -> 0
4081 if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
4083 // fold (fmul A, 0) -> 0, vector edition.
4084 if (UnsafeFPMath && ISD::isBuildVectorAllZeros(N1.getNode()))
4086 // fold (fmul X, 2.0) -> (fadd X, X)
4087 if (N1CFP && N1CFP->isExactlyValue(+2.0))
4088 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N0);
4089 // fold (fmul X, -1.0) -> (fneg X)
4090 if (N1CFP && N1CFP->isExactlyValue(-1.0))
4091 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
4092 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N0);
4094 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
4095 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations)) {
4096 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations)) {
4097 // Both can be negated for free, check to see if at least one is cheaper
4099 if (LHSNeg == 2 || RHSNeg == 2)
4100 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
4101 GetNegatedExpression(N0, DAG, LegalOperations),
4102 GetNegatedExpression(N1, DAG, LegalOperations));
4106 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
4107 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
4108 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
4109 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0.getOperand(0),
4110 DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
4111 N0.getOperand(1), N1));
4116 SDValue DAGCombiner::visitFDIV(SDNode *N) {
4117 SDValue N0 = N->getOperand(0);
4118 SDValue N1 = N->getOperand(1);
4119 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4120 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4121 EVT VT = N->getValueType(0);
4124 if (VT.isVector()) {
4125 SDValue FoldedVOp = SimplifyVBinOp(N);
4126 if (FoldedVOp.getNode()) return FoldedVOp;
4129 // fold (fdiv c1, c2) -> c1/c2
4130 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4131 return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT, N0, N1);
4134 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
4135 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations)) {
4136 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations)) {
4137 // Both can be negated for free, check to see if at least one is cheaper
4139 if (LHSNeg == 2 || RHSNeg == 2)
4140 return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT,
4141 GetNegatedExpression(N0, DAG, LegalOperations),
4142 GetNegatedExpression(N1, DAG, LegalOperations));
4149 SDValue DAGCombiner::visitFREM(SDNode *N) {
4150 SDValue N0 = N->getOperand(0);
4151 SDValue N1 = N->getOperand(1);
4152 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4153 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4154 EVT VT = N->getValueType(0);
4156 // fold (frem c1, c2) -> fmod(c1,c2)
4157 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4158 return DAG.getNode(ISD::FREM, N->getDebugLoc(), VT, N0, N1);
4163 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
4164 SDValue N0 = N->getOperand(0);
4165 SDValue N1 = N->getOperand(1);
4166 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4167 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4168 EVT VT = N->getValueType(0);
4170 if (N0CFP && N1CFP && VT != MVT::ppcf128) // Constant fold
4171 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, N0, N1);
4174 const APFloat& V = N1CFP->getValueAPF();
4175 // copysign(x, c1) -> fabs(x) iff ispos(c1)
4176 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
4177 if (!V.isNegative()) {
4178 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
4179 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
4181 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
4182 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT,
4183 DAG.getNode(ISD::FABS, N0.getDebugLoc(), VT, N0));
4187 // copysign(fabs(x), y) -> copysign(x, y)
4188 // copysign(fneg(x), y) -> copysign(x, y)
4189 // copysign(copysign(x,z), y) -> copysign(x, y)
4190 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
4191 N0.getOpcode() == ISD::FCOPYSIGN)
4192 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
4193 N0.getOperand(0), N1);
4195 // copysign(x, abs(y)) -> abs(x)
4196 if (N1.getOpcode() == ISD::FABS)
4197 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
4199 // copysign(x, copysign(y,z)) -> copysign(x, z)
4200 if (N1.getOpcode() == ISD::FCOPYSIGN)
4201 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
4202 N0, N1.getOperand(1));
4204 // copysign(x, fp_extend(y)) -> copysign(x, y)
4205 // copysign(x, fp_round(y)) -> copysign(x, y)
4206 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
4207 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
4208 N0, N1.getOperand(0));
4213 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
4214 SDValue N0 = N->getOperand(0);
4215 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4216 EVT VT = N->getValueType(0);
4217 EVT OpVT = N0.getValueType();
4219 // fold (sint_to_fp c1) -> c1fp
4220 if (N0C && OpVT != MVT::ppcf128)
4221 return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
4223 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
4224 // but UINT_TO_FP is legal on this target, try to convert.
4225 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
4226 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
4227 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
4228 if (DAG.SignBitIsZero(N0))
4229 return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
4235 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
4236 SDValue N0 = N->getOperand(0);
4237 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4238 EVT VT = N->getValueType(0);
4239 EVT OpVT = N0.getValueType();
4241 // fold (uint_to_fp c1) -> c1fp
4242 if (N0C && OpVT != MVT::ppcf128)
4243 return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
4245 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
4246 // but SINT_TO_FP is legal on this target, try to convert.
4247 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
4248 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
4249 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
4250 if (DAG.SignBitIsZero(N0))
4251 return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
4257 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
4258 SDValue N0 = N->getOperand(0);
4259 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4260 EVT VT = N->getValueType(0);
4262 // fold (fp_to_sint c1fp) -> c1
4264 return DAG.getNode(ISD::FP_TO_SINT, N->getDebugLoc(), VT, N0);
4269 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
4270 SDValue N0 = N->getOperand(0);
4271 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4272 EVT VT = N->getValueType(0);
4274 // fold (fp_to_uint c1fp) -> c1
4275 if (N0CFP && VT != MVT::ppcf128)
4276 return DAG.getNode(ISD::FP_TO_UINT, N->getDebugLoc(), VT, N0);
4281 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
4282 SDValue N0 = N->getOperand(0);
4283 SDValue N1 = N->getOperand(1);
4284 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4285 EVT VT = N->getValueType(0);
4287 // fold (fp_round c1fp) -> c1fp
4288 if (N0CFP && N0.getValueType() != MVT::ppcf128)
4289 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0, N1);
4291 // fold (fp_round (fp_extend x)) -> x
4292 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
4293 return N0.getOperand(0);
4295 // fold (fp_round (fp_round x)) -> (fp_round x)
4296 if (N0.getOpcode() == ISD::FP_ROUND) {
4297 // This is a value preserving truncation if both round's are.
4298 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
4299 N0.getNode()->getConstantOperandVal(1) == 1;
4300 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0.getOperand(0),
4301 DAG.getIntPtrConstant(IsTrunc));
4304 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
4305 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
4306 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(), VT,
4307 N0.getOperand(0), N1);
4308 AddToWorkList(Tmp.getNode());
4309 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
4310 Tmp, N0.getOperand(1));
4316 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
4317 SDValue N0 = N->getOperand(0);
4318 EVT VT = N->getValueType(0);
4319 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
4320 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4322 // fold (fp_round_inreg c1fp) -> c1fp
4323 if (N0CFP && (TLI.isTypeLegal(EVT) || !LegalTypes)) {
4324 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
4325 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, Round);
4331 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
4332 SDValue N0 = N->getOperand(0);
4333 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4334 EVT VT = N->getValueType(0);
4336 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
4337 if (N->hasOneUse() &&
4338 N->use_begin()->getOpcode() == ISD::FP_ROUND)
4341 // fold (fp_extend c1fp) -> c1fp
4342 if (N0CFP && VT != MVT::ppcf128)
4343 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, N0);
4345 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
4347 if (N0.getOpcode() == ISD::FP_ROUND
4348 && N0.getNode()->getConstantOperandVal(1) == 1) {
4349 SDValue In = N0.getOperand(0);
4350 if (In.getValueType() == VT) return In;
4351 if (VT.bitsLT(In.getValueType()))
4352 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT,
4353 In, N0.getOperand(1));
4354 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, In);
4357 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
4358 if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
4359 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4360 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
4361 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4362 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
4364 LN0->getBasePtr(), LN0->getSrcValue(),
4365 LN0->getSrcValueOffset(),
4367 LN0->isVolatile(), LN0->getAlignment());
4368 CombineTo(N, ExtLoad);
4369 CombineTo(N0.getNode(),
4370 DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(),
4371 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
4372 ExtLoad.getValue(1));
4373 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4379 SDValue DAGCombiner::visitFNEG(SDNode *N) {
4380 SDValue N0 = N->getOperand(0);
4382 if (isNegatibleForFree(N0, LegalOperations))
4383 return GetNegatedExpression(N0, DAG, LegalOperations);
4385 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
4386 // constant pool values.
4387 if (N0.getOpcode() == ISD::BIT_CONVERT && N0.getNode()->hasOneUse() &&
4388 N0.getOperand(0).getValueType().isInteger() &&
4389 !N0.getOperand(0).getValueType().isVector()) {
4390 SDValue Int = N0.getOperand(0);
4391 EVT IntVT = Int.getValueType();
4392 if (IntVT.isInteger() && !IntVT.isVector()) {
4393 Int = DAG.getNode(ISD::XOR, N0.getDebugLoc(), IntVT, Int,
4394 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
4395 AddToWorkList(Int.getNode());
4396 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(),
4397 N->getValueType(0), Int);
4404 SDValue DAGCombiner::visitFABS(SDNode *N) {
4405 SDValue N0 = N->getOperand(0);
4406 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4407 EVT VT = N->getValueType(0);
4409 // fold (fabs c1) -> fabs(c1)
4410 if (N0CFP && VT != MVT::ppcf128)
4411 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
4412 // fold (fabs (fabs x)) -> (fabs x)
4413 if (N0.getOpcode() == ISD::FABS)
4414 return N->getOperand(0);
4415 // fold (fabs (fneg x)) -> (fabs x)
4416 // fold (fabs (fcopysign x, y)) -> (fabs x)
4417 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
4418 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0.getOperand(0));
4420 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
4421 // constant pool values.
4422 if (N0.getOpcode() == ISD::BIT_CONVERT && N0.getNode()->hasOneUse() &&
4423 N0.getOperand(0).getValueType().isInteger() &&
4424 !N0.getOperand(0).getValueType().isVector()) {
4425 SDValue Int = N0.getOperand(0);
4426 EVT IntVT = Int.getValueType();
4427 if (IntVT.isInteger() && !IntVT.isVector()) {
4428 Int = DAG.getNode(ISD::AND, N0.getDebugLoc(), IntVT, Int,
4429 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
4430 AddToWorkList(Int.getNode());
4431 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(),
4432 N->getValueType(0), Int);
4439 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
4440 SDValue Chain = N->getOperand(0);
4441 SDValue N1 = N->getOperand(1);
4442 SDValue N2 = N->getOperand(2);
4443 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4445 // never taken branch, fold to chain
4446 if (N1C && N1C->isNullValue())
4448 // unconditional branch
4449 if (N1C && N1C->getAPIntValue() == 1)
4450 return DAG.getNode(ISD::BR, N->getDebugLoc(), MVT::Other, Chain, N2);
4451 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
4453 if (N1.getOpcode() == ISD::SETCC &&
4454 TLI.isOperationLegalOrCustom(ISD::BR_CC, MVT::Other)) {
4455 return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
4456 Chain, N1.getOperand(2),
4457 N1.getOperand(0), N1.getOperand(1), N2);
4460 if (N1.hasOneUse() && N1.getOpcode() == ISD::SRL) {
4461 // Match this pattern so that we can generate simpler code:
4464 // %b = and i32 %a, 2
4465 // %c = srl i32 %b, 1
4466 // brcond i32 %c ...
4472 // %c = setcc eq %b, 0
4475 // This applies only when the AND constant value has one bit set and the
4476 // SRL constant is equal to the log2 of the AND constant. The back-end is
4477 // smart enough to convert the result into a TEST/JMP sequence.
4478 SDValue Op0 = N1.getOperand(0);
4479 SDValue Op1 = N1.getOperand(1);
4481 if (Op0.getOpcode() == ISD::AND &&
4483 Op1.getOpcode() == ISD::Constant) {
4484 SDValue AndOp0 = Op0.getOperand(0);
4485 SDValue AndOp1 = Op0.getOperand(1);
4487 if (AndOp1.getOpcode() == ISD::Constant) {
4488 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
4490 if (AndConst.isPowerOf2() &&
4491 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
4493 DAG.getSetCC(N->getDebugLoc(),
4494 TLI.getSetCCResultType(Op0.getValueType()),
4495 Op0, DAG.getConstant(0, Op0.getValueType()),
4498 // Replace the uses of SRL with SETCC
4499 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
4500 removeFromWorkList(N1.getNode());
4501 DAG.DeleteNode(N1.getNode());
4502 return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
4503 MVT::Other, Chain, SetCC, N2);
4512 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
4514 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
4515 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
4516 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
4518 // Use SimplifySetCC to simplify SETCC's.
4519 SDValue Simp = SimplifySetCC(TLI.getSetCCResultType(CondLHS.getValueType()),
4520 CondLHS, CondRHS, CC->get(), N->getDebugLoc(),
4522 if (Simp.getNode()) AddToWorkList(Simp.getNode());
4524 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(Simp.getNode());
4526 // fold br_cc true, dest -> br dest (unconditional branch)
4527 if (SCCC && !SCCC->isNullValue())
4528 return DAG.getNode(ISD::BR, N->getDebugLoc(), MVT::Other,
4529 N->getOperand(0), N->getOperand(4));
4530 // fold br_cc false, dest -> unconditional fall through
4531 if (SCCC && SCCC->isNullValue())
4532 return N->getOperand(0);
4534 // fold to a simpler setcc
4535 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
4536 return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
4537 N->getOperand(0), Simp.getOperand(2),
4538 Simp.getOperand(0), Simp.getOperand(1),
4544 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
4545 /// pre-indexed load / store when the base pointer is an add or subtract
4546 /// and it has other uses besides the load / store. After the
4547 /// transformation, the new indexed load / store has effectively folded
4548 /// the add / subtract in and all of its other uses are redirected to the
4549 /// new load / store.
4550 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
4551 if (!LegalOperations)
4557 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
4558 if (LD->isIndexed())
4560 VT = LD->getMemoryVT();
4561 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
4562 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
4564 Ptr = LD->getBasePtr();
4565 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
4566 if (ST->isIndexed())
4568 VT = ST->getMemoryVT();
4569 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
4570 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
4572 Ptr = ST->getBasePtr();
4578 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
4579 // out. There is no reason to make this a preinc/predec.
4580 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
4581 Ptr.getNode()->hasOneUse())
4584 // Ask the target to do addressing mode selection.
4587 ISD::MemIndexedMode AM = ISD::UNINDEXED;
4588 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
4590 // Don't create a indexed load / store with zero offset.
4591 if (isa<ConstantSDNode>(Offset) &&
4592 cast<ConstantSDNode>(Offset)->isNullValue())
4595 // Try turning it into a pre-indexed load / store except when:
4596 // 1) The new base ptr is a frame index.
4597 // 2) If N is a store and the new base ptr is either the same as or is a
4598 // predecessor of the value being stored.
4599 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
4600 // that would create a cycle.
4601 // 4) All uses are load / store ops that use it as old base ptr.
4603 // Check #1. Preinc'ing a frame index would require copying the stack pointer
4604 // (plus the implicit offset) to a register to preinc anyway.
4605 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
4610 SDValue Val = cast<StoreSDNode>(N)->getValue();
4611 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
4615 // Now check for #3 and #4.
4616 bool RealUse = false;
4617 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
4618 E = Ptr.getNode()->use_end(); I != E; ++I) {
4622 if (Use->isPredecessorOf(N))
4625 if (!((Use->getOpcode() == ISD::LOAD &&
4626 cast<LoadSDNode>(Use)->getBasePtr() == Ptr) ||
4627 (Use->getOpcode() == ISD::STORE &&
4628 cast<StoreSDNode>(Use)->getBasePtr() == Ptr)))
4637 Result = DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
4638 BasePtr, Offset, AM);
4640 Result = DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
4641 BasePtr, Offset, AM);
4644 DEBUG(errs() << "\nReplacing.4 ";
4646 errs() << "\nWith: ";
4647 Result.getNode()->dump(&DAG);
4649 WorkListRemover DeadNodes(*this);
4651 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
4653 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
4656 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
4660 // Finally, since the node is now dead, remove it from the graph.
4663 // Replace the uses of Ptr with uses of the updated base value.
4664 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
4666 removeFromWorkList(Ptr.getNode());
4667 DAG.DeleteNode(Ptr.getNode());
4672 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
4673 /// add / sub of the base pointer node into a post-indexed load / store.
4674 /// The transformation folded the add / subtract into the new indexed
4675 /// load / store effectively and all of its uses are redirected to the
4676 /// new load / store.
4677 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
4678 if (!LegalOperations)
4684 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
4685 if (LD->isIndexed())
4687 VT = LD->getMemoryVT();
4688 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
4689 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
4691 Ptr = LD->getBasePtr();
4692 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
4693 if (ST->isIndexed())
4695 VT = ST->getMemoryVT();
4696 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
4697 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
4699 Ptr = ST->getBasePtr();
4705 if (Ptr.getNode()->hasOneUse())
4708 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
4709 E = Ptr.getNode()->use_end(); I != E; ++I) {
4712 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
4717 ISD::MemIndexedMode AM = ISD::UNINDEXED;
4718 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
4720 std::swap(BasePtr, Offset);
4723 // Don't create a indexed load / store with zero offset.
4724 if (isa<ConstantSDNode>(Offset) &&
4725 cast<ConstantSDNode>(Offset)->isNullValue())
4728 // Try turning it into a post-indexed load / store except when
4729 // 1) All uses are load / store ops that use it as base ptr.
4730 // 2) Op must be independent of N, i.e. Op is neither a predecessor
4731 // nor a successor of N. Otherwise, if Op is folded that would
4734 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
4738 bool TryNext = false;
4739 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
4740 EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
4742 if (Use == Ptr.getNode())
4745 // If all the uses are load / store addresses, then don't do the
4747 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
4748 bool RealUse = false;
4749 for (SDNode::use_iterator III = Use->use_begin(),
4750 EEE = Use->use_end(); III != EEE; ++III) {
4751 SDNode *UseUse = *III;
4752 if (!((UseUse->getOpcode() == ISD::LOAD &&
4753 cast<LoadSDNode>(UseUse)->getBasePtr().getNode() == Use) ||
4754 (UseUse->getOpcode() == ISD::STORE &&
4755 cast<StoreSDNode>(UseUse)->getBasePtr().getNode() == Use)))
4770 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
4771 SDValue Result = isLoad
4772 ? DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
4773 BasePtr, Offset, AM)
4774 : DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
4775 BasePtr, Offset, AM);
4778 DEBUG(errs() << "\nReplacing.5 ";
4780 errs() << "\nWith: ";
4781 Result.getNode()->dump(&DAG);
4783 WorkListRemover DeadNodes(*this);
4785 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
4787 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
4790 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
4794 // Finally, since the node is now dead, remove it from the graph.
4797 // Replace the uses of Use with uses of the updated base value.
4798 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
4799 Result.getValue(isLoad ? 1 : 0),
4801 removeFromWorkList(Op);
4811 /// InferAlignment - If we can infer some alignment information from this
4812 /// pointer, return it.
4813 static unsigned InferAlignment(SDValue Ptr, SelectionDAG &DAG) {
4814 // If this is a direct reference to a stack slot, use information about the
4815 // stack slot's alignment.
4816 int FrameIdx = 1 << 31;
4817 int64_t FrameOffset = 0;
4818 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
4819 FrameIdx = FI->getIndex();
4820 } else if (Ptr.getOpcode() == ISD::ADD &&
4821 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
4822 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4823 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4824 FrameOffset = Ptr.getConstantOperandVal(1);
4827 if (FrameIdx != (1 << 31)) {
4828 // FIXME: Handle FI+CST.
4829 const MachineFrameInfo &MFI = *DAG.getMachineFunction().getFrameInfo();
4830 if (MFI.isFixedObjectIndex(FrameIdx)) {
4831 int64_t ObjectOffset = MFI.getObjectOffset(FrameIdx) + FrameOffset;
4833 // The alignment of the frame index can be determined from its offset from
4834 // the incoming frame position. If the frame object is at offset 32 and
4835 // the stack is guaranteed to be 16-byte aligned, then we know that the
4836 // object is 16-byte aligned.
4837 unsigned StackAlign = DAG.getTarget().getFrameInfo()->getStackAlignment();
4838 unsigned Align = MinAlign(ObjectOffset, StackAlign);
4840 // Finally, the frame object itself may have a known alignment. Factor
4841 // the alignment + offset into a new alignment. For example, if we know
4842 // the FI is 8 byte aligned, but the pointer is 4 off, we really have a
4843 // 4-byte alignment of the resultant pointer. Likewise align 4 + 4-byte
4844 // offset = 4-byte alignment, align 4 + 1-byte offset = align 1, etc.
4845 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
4847 return std::max(Align, FIInfoAlign);
4854 SDValue DAGCombiner::visitLOAD(SDNode *N) {
4855 LoadSDNode *LD = cast<LoadSDNode>(N);
4856 SDValue Chain = LD->getChain();
4857 SDValue Ptr = LD->getBasePtr();
4859 // Try to infer better alignment information than the load already has.
4860 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
4861 if (unsigned Align = InferAlignment(Ptr, DAG)) {
4862 if (Align > LD->getAlignment())
4863 return DAG.getExtLoad(LD->getExtensionType(), N->getDebugLoc(),
4864 LD->getValueType(0),
4865 Chain, Ptr, LD->getSrcValue(),
4866 LD->getSrcValueOffset(), LD->getMemoryVT(),
4867 LD->isVolatile(), Align);
4871 // If load is not volatile and there are no uses of the loaded value (and
4872 // the updated indexed value in case of indexed loads), change uses of the
4873 // chain value into uses of the chain input (i.e. delete the dead load).
4874 if (!LD->isVolatile()) {
4875 if (N->getValueType(1) == MVT::Other) {
4877 if (N->hasNUsesOfValue(0, 0)) {
4878 // It's not safe to use the two value CombineTo variant here. e.g.
4879 // v1, chain2 = load chain1, loc
4880 // v2, chain3 = load chain2, loc
4882 // Now we replace use of chain2 with chain1. This makes the second load
4883 // isomorphic to the one we are deleting, and thus makes this load live.
4884 DEBUG(errs() << "\nReplacing.6 ";
4886 errs() << "\nWith chain: ";
4887 Chain.getNode()->dump(&DAG);
4889 WorkListRemover DeadNodes(*this);
4890 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain, &DeadNodes);
4892 if (N->use_empty()) {
4893 removeFromWorkList(N);
4897 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4901 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
4902 if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) {
4903 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
4904 DEBUG(errs() << "\nReplacing.6 ";
4906 errs() << "\nWith: ";
4907 Undef.getNode()->dump(&DAG);
4908 errs() << " and 2 other values\n");
4909 WorkListRemover DeadNodes(*this);
4910 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef, &DeadNodes);
4911 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
4912 DAG.getUNDEF(N->getValueType(1)),
4914 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain, &DeadNodes);
4915 removeFromWorkList(N);
4917 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4922 // If this load is directly stored, replace the load value with the stored
4924 // TODO: Handle store large -> read small portion.
4925 // TODO: Handle TRUNCSTORE/LOADEXT
4926 if (LD->getExtensionType() == ISD::NON_EXTLOAD &&
4927 !LD->isVolatile()) {
4928 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
4929 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
4930 if (PrevST->getBasePtr() == Ptr &&
4931 PrevST->getValue().getValueType() == N->getValueType(0))
4932 return CombineTo(N, Chain.getOperand(1), Chain);
4937 // Walk up chain skipping non-aliasing memory nodes.
4938 SDValue BetterChain = FindBetterChain(N, Chain);
4940 // If there is a better chain.
4941 if (Chain != BetterChain) {
4944 // Replace the chain to void dependency.
4945 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
4946 ReplLoad = DAG.getLoad(N->getValueType(0), LD->getDebugLoc(),
4948 LD->getSrcValue(), LD->getSrcValueOffset(),
4949 LD->isVolatile(), LD->getAlignment());
4951 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), LD->getDebugLoc(),
4952 LD->getValueType(0),
4953 BetterChain, Ptr, LD->getSrcValue(),
4954 LD->getSrcValueOffset(),
4957 LD->getAlignment());
4960 // Create token factor to keep old chain connected.
4961 SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
4962 MVT::Other, Chain, ReplLoad.getValue(1));
4964 // Replace uses with load result and token factor. Don't add users
4966 return CombineTo(N, ReplLoad.getValue(0), Token, false);
4970 // Try transforming N to an indexed load.
4971 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
4972 return SDValue(N, 0);
4978 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
4979 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
4980 /// of the loaded bits, try narrowing the load and store if it would end up
4981 /// being a win for performance or code size.
4982 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
4983 StoreSDNode *ST = cast<StoreSDNode>(N);
4984 if (ST->isVolatile())
4987 SDValue Chain = ST->getChain();
4988 SDValue Value = ST->getValue();
4989 SDValue Ptr = ST->getBasePtr();
4990 EVT VT = Value.getValueType();
4992 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
4995 unsigned Opc = Value.getOpcode();
4996 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
4997 Value.getOperand(1).getOpcode() != ISD::Constant)
5000 SDValue N0 = Value.getOperand(0);
5001 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse()) {
5002 LoadSDNode *LD = cast<LoadSDNode>(N0);
5003 if (LD->getBasePtr() != Ptr)
5006 // Find the type to narrow it the load / op / store to.
5007 SDValue N1 = Value.getOperand(1);
5008 unsigned BitWidth = N1.getValueSizeInBits();
5009 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
5010 if (Opc == ISD::AND)
5011 Imm ^= APInt::getAllOnesValue(BitWidth);
5012 if (Imm == 0 || Imm.isAllOnesValue())
5014 unsigned ShAmt = Imm.countTrailingZeros();
5015 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
5016 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
5017 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
5018 while (NewBW < BitWidth &&
5019 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
5020 TLI.isNarrowingProfitable(VT, NewVT))) {
5021 NewBW = NextPowerOf2(NewBW);
5022 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
5024 if (NewBW >= BitWidth)
5027 // If the lsb changed does not start at the type bitwidth boundary,
5028 // start at the previous one.
5030 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
5031 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, ShAmt + NewBW);
5032 if ((Imm & Mask) == Imm) {
5033 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
5034 if (Opc == ISD::AND)
5035 NewImm ^= APInt::getAllOnesValue(NewBW);
5036 uint64_t PtrOff = ShAmt / 8;
5037 // For big endian targets, we need to adjust the offset to the pointer to
5038 // load the correct bytes.
5039 if (TLI.isBigEndian())
5040 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
5042 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
5044 TLI.getTargetData()->getABITypeAlignment(NewVT.getTypeForEVT(*DAG.getContext())))
5047 SDValue NewPtr = DAG.getNode(ISD::ADD, LD->getDebugLoc(),
5048 Ptr.getValueType(), Ptr,
5049 DAG.getConstant(PtrOff, Ptr.getValueType()));
5050 SDValue NewLD = DAG.getLoad(NewVT, N0.getDebugLoc(),
5051 LD->getChain(), NewPtr,
5052 LD->getSrcValue(), LD->getSrcValueOffset(),
5053 LD->isVolatile(), NewAlign);
5054 SDValue NewVal = DAG.getNode(Opc, Value.getDebugLoc(), NewVT, NewLD,
5055 DAG.getConstant(NewImm, NewVT));
5056 SDValue NewST = DAG.getStore(Chain, N->getDebugLoc(),
5058 ST->getSrcValue(), ST->getSrcValueOffset(),
5061 AddToWorkList(NewPtr.getNode());
5062 AddToWorkList(NewLD.getNode());
5063 AddToWorkList(NewVal.getNode());
5064 WorkListRemover DeadNodes(*this);
5065 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1),
5075 SDValue DAGCombiner::visitSTORE(SDNode *N) {
5076 StoreSDNode *ST = cast<StoreSDNode>(N);
5077 SDValue Chain = ST->getChain();
5078 SDValue Value = ST->getValue();
5079 SDValue Ptr = ST->getBasePtr();
5081 // Try to infer better alignment information than the store already has.
5082 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
5083 if (unsigned Align = InferAlignment(Ptr, DAG)) {
5084 if (Align > ST->getAlignment())
5085 return DAG.getTruncStore(Chain, N->getDebugLoc(), Value,
5086 Ptr, ST->getSrcValue(),
5087 ST->getSrcValueOffset(), ST->getMemoryVT(),
5088 ST->isVolatile(), Align);
5092 // If this is a store of a bit convert, store the input value if the
5093 // resultant store does not need a higher alignment than the original.
5094 if (Value.getOpcode() == ISD::BIT_CONVERT && !ST->isTruncatingStore() &&
5095 ST->isUnindexed()) {
5096 unsigned OrigAlign = ST->getAlignment();
5097 EVT SVT = Value.getOperand(0).getValueType();
5098 unsigned Align = TLI.getTargetData()->
5099 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
5100 if (Align <= OrigAlign &&
5101 ((!LegalOperations && !ST->isVolatile()) ||
5102 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
5103 return DAG.getStore(Chain, N->getDebugLoc(), Value.getOperand(0),
5104 Ptr, ST->getSrcValue(),
5105 ST->getSrcValueOffset(), ST->isVolatile(), OrigAlign);
5108 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
5109 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
5110 // NOTE: If the original store is volatile, this transform must not increase
5111 // the number of stores. For example, on x86-32 an f64 can be stored in one
5112 // processor operation but an i64 (which is not legal) requires two. So the
5113 // transform should not be done in this case.
5114 if (Value.getOpcode() != ISD::TargetConstantFP) {
5116 switch (CFP->getValueType(0).getSimpleVT().SimpleTy) {
5117 default: llvm_unreachable("Unknown FP type");
5118 case MVT::f80: // We don't do this for these yet.
5123 if (((TLI.isTypeLegal(MVT::i32) || !LegalTypes) && !LegalOperations &&
5124 !ST->isVolatile()) ||
5125 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
5126 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
5127 bitcastToAPInt().getZExtValue(), MVT::i32);
5128 return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
5129 Ptr, ST->getSrcValue(),
5130 ST->getSrcValueOffset(), ST->isVolatile(),
5131 ST->getAlignment());
5135 if (((TLI.isTypeLegal(MVT::i64) || !LegalTypes) && !LegalOperations &&
5136 !ST->isVolatile()) ||
5137 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
5138 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
5139 getZExtValue(), MVT::i64);
5140 return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
5141 Ptr, ST->getSrcValue(),
5142 ST->getSrcValueOffset(), ST->isVolatile(),
5143 ST->getAlignment());
5144 } else if (!ST->isVolatile() &&
5145 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
5146 // Many FP stores are not made apparent until after legalize, e.g. for
5147 // argument passing. Since this is so common, custom legalize the
5148 // 64-bit integer store into two 32-bit stores.
5149 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
5150 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
5151 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
5152 if (TLI.isBigEndian()) std::swap(Lo, Hi);
5154 int SVOffset = ST->getSrcValueOffset();
5155 unsigned Alignment = ST->getAlignment();
5156 bool isVolatile = ST->isVolatile();
5158 SDValue St0 = DAG.getStore(Chain, ST->getDebugLoc(), Lo,
5159 Ptr, ST->getSrcValue(),
5160 ST->getSrcValueOffset(),
5161 isVolatile, ST->getAlignment());
5162 Ptr = DAG.getNode(ISD::ADD, N->getDebugLoc(), Ptr.getValueType(), Ptr,
5163 DAG.getConstant(4, Ptr.getValueType()));
5165 Alignment = MinAlign(Alignment, 4U);
5166 SDValue St1 = DAG.getStore(Chain, ST->getDebugLoc(), Hi,
5167 Ptr, ST->getSrcValue(),
5168 SVOffset, isVolatile, Alignment);
5169 return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
5179 // Walk up chain skipping non-aliasing memory nodes.
5180 SDValue BetterChain = FindBetterChain(N, Chain);
5182 // If there is a better chain.
5183 if (Chain != BetterChain) {
5184 // Replace the chain to avoid dependency.
5186 if (ST->isTruncatingStore()) {
5187 ReplStore = DAG.getTruncStore(BetterChain, N->getDebugLoc(), Value, Ptr,
5188 ST->getSrcValue(),ST->getSrcValueOffset(),
5190 ST->isVolatile(), ST->getAlignment());
5192 ReplStore = DAG.getStore(BetterChain, N->getDebugLoc(), Value, Ptr,
5193 ST->getSrcValue(), ST->getSrcValueOffset(),
5194 ST->isVolatile(), ST->getAlignment());
5197 // Create token to keep both nodes around.
5198 SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
5199 MVT::Other, Chain, ReplStore);
5201 // Don't add users to work list.
5202 return CombineTo(N, Token, false);
5206 // Try transforming N to an indexed store.
5207 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
5208 return SDValue(N, 0);
5210 // FIXME: is there such a thing as a truncating indexed store?
5211 if (ST->isTruncatingStore() && ST->isUnindexed() &&
5212 Value.getValueType().isInteger()) {
5213 // See if we can simplify the input to this truncstore with knowledge that
5214 // only the low bits are being used. For example:
5215 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
5217 GetDemandedBits(Value,
5218 APInt::getLowBitsSet(Value.getValueSizeInBits(),
5219 ST->getMemoryVT().getSizeInBits()));
5220 AddToWorkList(Value.getNode());
5221 if (Shorter.getNode())
5222 return DAG.getTruncStore(Chain, N->getDebugLoc(), Shorter,
5223 Ptr, ST->getSrcValue(),
5224 ST->getSrcValueOffset(), ST->getMemoryVT(),
5225 ST->isVolatile(), ST->getAlignment());
5227 // Otherwise, see if we can simplify the operation with
5228 // SimplifyDemandedBits, which only works if the value has a single use.
5229 if (SimplifyDemandedBits(Value,
5230 APInt::getLowBitsSet(
5231 Value.getValueSizeInBits(),
5232 ST->getMemoryVT().getSizeInBits())))
5233 return SDValue(N, 0);
5236 // If this is a load followed by a store to the same location, then the store
5238 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
5239 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
5240 ST->isUnindexed() && !ST->isVolatile() &&
5241 // There can't be any side effects between the load and store, such as
5243 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
5244 // The store is dead, remove it.
5249 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
5250 // truncating store. We can do this even if this is already a truncstore.
5251 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
5252 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
5253 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
5254 ST->getMemoryVT())) {
5255 return DAG.getTruncStore(Chain, N->getDebugLoc(), Value.getOperand(0),
5256 Ptr, ST->getSrcValue(),
5257 ST->getSrcValueOffset(), ST->getMemoryVT(),
5258 ST->isVolatile(), ST->getAlignment());
5261 return ReduceLoadOpStoreWidth(N);
5264 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
5265 SDValue InVec = N->getOperand(0);
5266 SDValue InVal = N->getOperand(1);
5267 SDValue EltNo = N->getOperand(2);
5269 // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
5270 // vector with the inserted element.
5271 if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
5272 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5273 SmallVector<SDValue, 8> Ops(InVec.getNode()->op_begin(),
5274 InVec.getNode()->op_end());
5275 if (Elt < Ops.size())
5277 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
5278 InVec.getValueType(), &Ops[0], Ops.size());
5280 // If the invec is an UNDEF and if EltNo is a constant, create a new
5281 // BUILD_VECTOR with undef elements and the inserted element.
5282 if (!LegalOperations && InVec.getOpcode() == ISD::UNDEF &&
5283 isa<ConstantSDNode>(EltNo)) {
5284 EVT VT = InVec.getValueType();
5285 EVT EVT = VT.getVectorElementType();
5286 unsigned NElts = VT.getVectorNumElements();
5287 SmallVector<SDValue, 8> Ops(NElts, DAG.getUNDEF(EVT));
5289 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5290 if (Elt < Ops.size())
5292 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
5293 InVec.getValueType(), &Ops[0], Ops.size());
5298 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
5299 // (vextract (scalar_to_vector val, 0) -> val
5300 SDValue InVec = N->getOperand(0);
5302 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5303 // If the operand is wider than the vector element type then it is implicitly
5304 // truncated. Make that explicit here.
5305 EVT EltVT = InVec.getValueType().getVectorElementType();
5306 SDValue InOp = InVec.getOperand(0);
5307 if (InOp.getValueType() != EltVT)
5308 return DAG.getNode(ISD::TRUNCATE, InVec.getDebugLoc(), EltVT, InOp);
5312 // Perform only after legalization to ensure build_vector / vector_shuffle
5313 // optimizations have already been done.
5314 if (!LegalOperations) return SDValue();
5316 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
5317 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
5318 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
5319 SDValue EltNo = N->getOperand(1);
5321 if (isa<ConstantSDNode>(EltNo)) {
5322 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5323 bool NewLoad = false;
5324 bool BCNumEltsChanged = false;
5325 EVT VT = InVec.getValueType();
5326 EVT ExtVT = VT.getVectorElementType();
5329 if (InVec.getOpcode() == ISD::BIT_CONVERT) {
5330 EVT BCVT = InVec.getOperand(0).getValueType();
5331 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
5333 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
5334 BCNumEltsChanged = true;
5335 InVec = InVec.getOperand(0);
5336 ExtVT = BCVT.getVectorElementType();
5340 LoadSDNode *LN0 = NULL;
5341 const ShuffleVectorSDNode *SVN = NULL;
5342 if (ISD::isNormalLoad(InVec.getNode())) {
5343 LN0 = cast<LoadSDNode>(InVec);
5344 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5345 InVec.getOperand(0).getValueType() == ExtVT &&
5346 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
5347 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
5348 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
5349 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
5351 // (load $addr+1*size)
5353 // If the bit convert changed the number of elements, it is unsafe
5354 // to examine the mask.
5355 if (BCNumEltsChanged)
5358 // Select the input vector, guarding against out of range extract vector.
5359 unsigned NumElems = VT.getVectorNumElements();
5360 int Idx = (Elt > NumElems) ? -1 : SVN->getMaskElt(Elt);
5361 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
5363 if (InVec.getOpcode() == ISD::BIT_CONVERT)
5364 InVec = InVec.getOperand(0);
5365 if (ISD::isNormalLoad(InVec.getNode())) {
5366 LN0 = cast<LoadSDNode>(InVec);
5367 Elt = (Idx < (int)NumElems) ? Idx : Idx - NumElems;
5371 if (!LN0 || !LN0->hasOneUse() || LN0->isVolatile())
5374 unsigned Align = LN0->getAlignment();
5376 // Check the resultant load doesn't need a higher alignment than the
5379 TLI.getTargetData()->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
5381 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
5387 SDValue NewPtr = LN0->getBasePtr();
5389 unsigned PtrOff = LVT.getSizeInBits() * Elt / 8;
5390 EVT PtrType = NewPtr.getValueType();
5391 if (TLI.isBigEndian())
5392 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
5393 NewPtr = DAG.getNode(ISD::ADD, N->getDebugLoc(), PtrType, NewPtr,
5394 DAG.getConstant(PtrOff, PtrType));
5397 return DAG.getLoad(LVT, N->getDebugLoc(), LN0->getChain(), NewPtr,
5398 LN0->getSrcValue(), LN0->getSrcValueOffset(),
5399 LN0->isVolatile(), Align);
5405 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
5406 unsigned NumInScalars = N->getNumOperands();
5407 EVT VT = N->getValueType(0);
5408 EVT EltType = VT.getVectorElementType();
5410 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
5411 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
5412 // at most two distinct vectors, turn this into a shuffle node.
5413 SDValue VecIn1, VecIn2;
5414 for (unsigned i = 0; i != NumInScalars; ++i) {
5415 // Ignore undef inputs.
5416 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
5418 // If this input is something other than a EXTRACT_VECTOR_ELT with a
5419 // constant index, bail out.
5420 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5421 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
5422 VecIn1 = VecIn2 = SDValue(0, 0);
5426 // If the input vector type disagrees with the result of the build_vector,
5427 // we can't make a shuffle.
5428 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
5429 if (ExtractedFromVec.getValueType() != VT) {
5430 VecIn1 = VecIn2 = SDValue(0, 0);
5434 // Otherwise, remember this. We allow up to two distinct input vectors.
5435 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
5438 if (VecIn1.getNode() == 0) {
5439 VecIn1 = ExtractedFromVec;
5440 } else if (VecIn2.getNode() == 0) {
5441 VecIn2 = ExtractedFromVec;
5444 VecIn1 = VecIn2 = SDValue(0, 0);
5449 // If everything is good, we can make a shuffle operation.
5450 if (VecIn1.getNode()) {
5451 SmallVector<int, 8> Mask;
5452 for (unsigned i = 0; i != NumInScalars; ++i) {
5453 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
5458 // If extracting from the first vector, just use the index directly.
5459 SDValue Extract = N->getOperand(i);
5460 SDValue ExtVal = Extract.getOperand(1);
5461 if (Extract.getOperand(0) == VecIn1) {
5462 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
5463 if (ExtIndex > VT.getVectorNumElements())
5466 Mask.push_back(ExtIndex);
5470 // Otherwise, use InIdx + VecSize
5471 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
5472 Mask.push_back(Idx+NumInScalars);
5475 // Add count and size info.
5476 if (!TLI.isTypeLegal(VT) && LegalTypes)
5479 // Return the new VECTOR_SHUFFLE node.
5482 Ops[1] = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5483 return DAG.getVectorShuffle(VT, N->getDebugLoc(), Ops[0], Ops[1], &Mask[0]);
5489 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
5490 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
5491 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
5492 // inputs come from at most two distinct vectors, turn this into a shuffle
5495 // If we only have one input vector, we don't need to do any concatenation.
5496 if (N->getNumOperands() == 1)
5497 return N->getOperand(0);
5502 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
5505 EVT VT = N->getValueType(0);
5506 unsigned NumElts = VT.getVectorNumElements();
5508 SDValue N0 = N->getOperand(0);
5509 SDValue N1 = N->getOperand(1);
5511 assert(N0.getValueType().getVectorNumElements() == NumElts &&
5512 "Vector shuffle must be normalized in DAG");
5514 // FIXME: implement canonicalizations from DAG.getVectorShuffle()
5516 // If it is a splat, check if the argument vector is a build_vector with
5517 // all scalar elements the same.
5518 if (cast<ShuffleVectorSDNode>(N)->isSplat()) {
5519 SDNode *V = N0.getNode();
5522 // If this is a bit convert that changes the element type of the vector but
5523 // not the number of vector elements, look through it. Be careful not to
5524 // look though conversions that change things like v4f32 to v2f64.
5525 if (V->getOpcode() == ISD::BIT_CONVERT) {
5526 SDValue ConvInput = V->getOperand(0);
5527 if (ConvInput.getValueType().isVector() &&
5528 ConvInput.getValueType().getVectorNumElements() == NumElts)
5529 V = ConvInput.getNode();
5532 if (V->getOpcode() == ISD::BUILD_VECTOR) {
5533 unsigned NumElems = V->getNumOperands();
5534 unsigned BaseIdx = cast<ShuffleVectorSDNode>(N)->getSplatIndex();
5535 if (NumElems > BaseIdx) {
5537 bool AllSame = true;
5538 for (unsigned i = 0; i != NumElems; ++i) {
5539 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
5540 Base = V->getOperand(i);
5544 // Splat of <u, u, u, u>, return <u, u, u, u>
5545 if (!Base.getNode())
5547 for (unsigned i = 0; i != NumElems; ++i) {
5548 if (V->getOperand(i) != Base) {
5553 // Splat of <x, x, x, x>, return <x, x, x, x>
5562 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
5563 /// an AND to a vector_shuffle with the destination vector and a zero vector.
5564 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
5565 /// vector_shuffle V, Zero, <0, 4, 2, 4>
5566 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
5567 EVT VT = N->getValueType(0);
5568 DebugLoc dl = N->getDebugLoc();
5569 SDValue LHS = N->getOperand(0);
5570 SDValue RHS = N->getOperand(1);
5571 if (N->getOpcode() == ISD::AND) {
5572 if (RHS.getOpcode() == ISD::BIT_CONVERT)
5573 RHS = RHS.getOperand(0);
5574 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
5575 SmallVector<int, 8> Indices;
5576 unsigned NumElts = RHS.getNumOperands();
5577 for (unsigned i = 0; i != NumElts; ++i) {
5578 SDValue Elt = RHS.getOperand(i);
5579 if (!isa<ConstantSDNode>(Elt))
5581 else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
5582 Indices.push_back(i);
5583 else if (cast<ConstantSDNode>(Elt)->isNullValue())
5584 Indices.push_back(NumElts);
5589 // Let's see if the target supports this vector_shuffle.
5590 EVT RVT = RHS.getValueType();
5591 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
5594 // Return the new VECTOR_SHUFFLE node.
5595 EVT EVT = RVT.getVectorElementType();
5596 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
5597 DAG.getConstant(0, EVT));
5598 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
5599 RVT, &ZeroOps[0], ZeroOps.size());
5600 LHS = DAG.getNode(ISD::BIT_CONVERT, dl, RVT, LHS);
5601 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
5602 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Shuf);
5609 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
5610 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
5611 // After legalize, the target may be depending on adds and other
5612 // binary ops to provide legal ways to construct constants or other
5613 // things. Simplifying them may result in a loss of legality.
5614 if (LegalOperations) return SDValue();
5616 EVT VT = N->getValueType(0);
5617 assert(VT.isVector() && "SimplifyVBinOp only works on vectors!");
5619 EVT EltType = VT.getVectorElementType();
5620 SDValue LHS = N->getOperand(0);
5621 SDValue RHS = N->getOperand(1);
5622 SDValue Shuffle = XformToShuffleWithZero(N);
5623 if (Shuffle.getNode()) return Shuffle;
5625 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
5627 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
5628 RHS.getOpcode() == ISD::BUILD_VECTOR) {
5629 SmallVector<SDValue, 8> Ops;
5630 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
5631 SDValue LHSOp = LHS.getOperand(i);
5632 SDValue RHSOp = RHS.getOperand(i);
5633 // If these two elements can't be folded, bail out.
5634 if ((LHSOp.getOpcode() != ISD::UNDEF &&
5635 LHSOp.getOpcode() != ISD::Constant &&
5636 LHSOp.getOpcode() != ISD::ConstantFP) ||
5637 (RHSOp.getOpcode() != ISD::UNDEF &&
5638 RHSOp.getOpcode() != ISD::Constant &&
5639 RHSOp.getOpcode() != ISD::ConstantFP))
5642 // Can't fold divide by zero.
5643 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
5644 N->getOpcode() == ISD::FDIV) {
5645 if ((RHSOp.getOpcode() == ISD::Constant &&
5646 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
5647 (RHSOp.getOpcode() == ISD::ConstantFP &&
5648 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
5652 Ops.push_back(DAG.getNode(N->getOpcode(), LHS.getDebugLoc(),
5653 EltType, LHSOp, RHSOp));
5654 AddToWorkList(Ops.back().getNode());
5655 assert((Ops.back().getOpcode() == ISD::UNDEF ||
5656 Ops.back().getOpcode() == ISD::Constant ||
5657 Ops.back().getOpcode() == ISD::ConstantFP) &&
5658 "Scalar binop didn't fold!");
5661 if (Ops.size() == LHS.getNumOperands()) {
5662 EVT VT = LHS.getValueType();
5663 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
5664 &Ops[0], Ops.size());
5671 SDValue DAGCombiner::SimplifySelect(DebugLoc DL, SDValue N0,
5672 SDValue N1, SDValue N2){
5673 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
5675 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
5676 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5678 // If we got a simplified select_cc node back from SimplifySelectCC, then
5679 // break it down into a new SETCC node, and a new SELECT node, and then return
5680 // the SELECT node, since we were called with a SELECT node.
5681 if (SCC.getNode()) {
5682 // Check to see if we got a select_cc back (to turn into setcc/select).
5683 // Otherwise, just return whatever node we got back, like fabs.
5684 if (SCC.getOpcode() == ISD::SELECT_CC) {
5685 SDValue SETCC = DAG.getNode(ISD::SETCC, N0.getDebugLoc(),
5687 SCC.getOperand(0), SCC.getOperand(1),
5689 AddToWorkList(SETCC.getNode());
5690 return DAG.getNode(ISD::SELECT, SCC.getDebugLoc(), SCC.getValueType(),
5691 SCC.getOperand(2), SCC.getOperand(3), SETCC);
5699 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
5700 /// are the two values being selected between, see if we can simplify the
5701 /// select. Callers of this should assume that TheSelect is deleted if this
5702 /// returns true. As such, they should return the appropriate thing (e.g. the
5703 /// node) back to the top-level of the DAG combiner loop to avoid it being
5705 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
5708 // If this is a select from two identical things, try to pull the operation
5709 // through the select.
5710 if (LHS.getOpcode() == RHS.getOpcode() && LHS.hasOneUse() && RHS.hasOneUse()){
5711 // If this is a load and the token chain is identical, replace the select
5712 // of two loads with a load through a select of the address to load from.
5713 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
5714 // constants have been dropped into the constant pool.
5715 if (LHS.getOpcode() == ISD::LOAD &&
5716 // Do not let this transformation reduce the number of volatile loads.
5717 !cast<LoadSDNode>(LHS)->isVolatile() &&
5718 !cast<LoadSDNode>(RHS)->isVolatile() &&
5719 // Token chains must be identical.
5720 LHS.getOperand(0) == RHS.getOperand(0)) {
5721 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
5722 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
5724 // If this is an EXTLOAD, the VT's must match.
5725 if (LLD->getMemoryVT() == RLD->getMemoryVT()) {
5726 // FIXME: this conflates two src values, discarding one. This is not
5727 // the right thing to do, but nothing uses srcvalues now. When they do,
5728 // turn SrcValue into a list of locations.
5730 if (TheSelect->getOpcode() == ISD::SELECT) {
5731 // Check that the condition doesn't reach either load. If so, folding
5732 // this will induce a cycle into the DAG.
5733 if (!LLD->isPredecessorOf(TheSelect->getOperand(0).getNode()) &&
5734 !RLD->isPredecessorOf(TheSelect->getOperand(0).getNode())) {
5735 Addr = DAG.getNode(ISD::SELECT, TheSelect->getDebugLoc(),
5736 LLD->getBasePtr().getValueType(),
5737 TheSelect->getOperand(0), LLD->getBasePtr(),
5741 // Check that the condition doesn't reach either load. If so, folding
5742 // this will induce a cycle into the DAG.
5743 if (!LLD->isPredecessorOf(TheSelect->getOperand(0).getNode()) &&
5744 !RLD->isPredecessorOf(TheSelect->getOperand(0).getNode()) &&
5745 !LLD->isPredecessorOf(TheSelect->getOperand(1).getNode()) &&
5746 !RLD->isPredecessorOf(TheSelect->getOperand(1).getNode())) {
5747 Addr = DAG.getNode(ISD::SELECT_CC, TheSelect->getDebugLoc(),
5748 LLD->getBasePtr().getValueType(),
5749 TheSelect->getOperand(0),
5750 TheSelect->getOperand(1),
5751 LLD->getBasePtr(), RLD->getBasePtr(),
5752 TheSelect->getOperand(4));
5756 if (Addr.getNode()) {
5758 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
5759 Load = DAG.getLoad(TheSelect->getValueType(0),
5760 TheSelect->getDebugLoc(),
5762 Addr,LLD->getSrcValue(),
5763 LLD->getSrcValueOffset(),
5765 LLD->getAlignment());
5767 Load = DAG.getExtLoad(LLD->getExtensionType(),
5768 TheSelect->getDebugLoc(),
5769 TheSelect->getValueType(0),
5770 LLD->getChain(), Addr, LLD->getSrcValue(),
5771 LLD->getSrcValueOffset(),
5774 LLD->getAlignment());
5777 // Users of the select now use the result of the load.
5778 CombineTo(TheSelect, Load);
5780 // Users of the old loads now use the new load's chain. We know the
5781 // old-load value is dead now.
5782 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
5783 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
5793 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
5794 /// where 'cond' is the comparison specified by CC.
5795 SDValue DAGCombiner::SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1,
5796 SDValue N2, SDValue N3,
5797 ISD::CondCode CC, bool NotExtCompare) {
5798 // (x ? y : y) -> y.
5799 if (N2 == N3) return N2;
5801 EVT VT = N2.getValueType();
5802 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
5803 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
5804 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
5806 // Determine if the condition we're dealing with is constant
5807 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
5808 N0, N1, CC, DL, false);
5809 if (SCC.getNode()) AddToWorkList(SCC.getNode());
5810 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
5812 // fold select_cc true, x, y -> x
5813 if (SCCC && !SCCC->isNullValue())
5815 // fold select_cc false, x, y -> y
5816 if (SCCC && SCCC->isNullValue())
5819 // Check to see if we can simplify the select into an fabs node
5820 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
5821 // Allow either -0.0 or 0.0
5822 if (CFP->getValueAPF().isZero()) {
5823 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
5824 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
5825 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
5826 N2 == N3.getOperand(0))
5827 return DAG.getNode(ISD::FABS, DL, VT, N0);
5829 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
5830 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
5831 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
5832 N2.getOperand(0) == N3)
5833 return DAG.getNode(ISD::FABS, DL, VT, N3);
5837 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
5838 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
5839 // in it. This is a win when the constant is not otherwise available because
5840 // it replaces two constant pool loads with one. We only do this if the FP
5841 // type is known to be legal, because if it isn't, then we are before legalize
5842 // types an we want the other legalization to happen first (e.g. to avoid
5843 // messing with soft float) and if the ConstantFP is not legal, because if
5844 // it is legal, we may not need to store the FP constant in a constant pool.
5845 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
5846 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
5847 if (TLI.isTypeLegal(N2.getValueType()) &&
5848 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
5849 TargetLowering::Legal) &&
5850 // If both constants have multiple uses, then we won't need to do an
5851 // extra load, they are likely around in registers for other users.
5852 (TV->hasOneUse() || FV->hasOneUse())) {
5853 Constant *Elts[] = {
5854 const_cast<ConstantFP*>(FV->getConstantFPValue()),
5855 const_cast<ConstantFP*>(TV->getConstantFPValue())
5857 const Type *FPTy = Elts[0]->getType();
5858 const TargetData &TD = *TLI.getTargetData();
5860 // Create a ConstantArray of the two constants.
5861 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts, 2);
5862 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
5863 TD.getPrefTypeAlignment(FPTy));
5864 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
5866 // Get the offsets to the 0 and 1 element of the array so that we can
5867 // select between them.
5868 SDValue Zero = DAG.getIntPtrConstant(0);
5869 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
5870 SDValue One = DAG.getIntPtrConstant(EltSize);
5872 SDValue Cond = DAG.getSetCC(DL,
5873 TLI.getSetCCResultType(N0.getValueType()),
5875 SDValue CstOffset = DAG.getNode(ISD::SELECT, DL, Zero.getValueType(),
5877 CPIdx = DAG.getNode(ISD::ADD, DL, TLI.getPointerTy(), CPIdx,
5879 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
5880 PseudoSourceValue::getConstantPool(), 0, false,
5886 // Check to see if we can perform the "gzip trick", transforming
5887 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
5888 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
5889 N0.getValueType().isInteger() &&
5890 N2.getValueType().isInteger() &&
5891 (N1C->isNullValue() || // (a < 0) ? b : 0
5892 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
5893 EVT XType = N0.getValueType();
5894 EVT AType = N2.getValueType();
5895 if (XType.bitsGE(AType)) {
5896 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
5897 // single-bit constant.
5898 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
5899 unsigned ShCtV = N2C->getAPIntValue().logBase2();
5900 ShCtV = XType.getSizeInBits()-ShCtV-1;
5901 SDValue ShCt = DAG.getConstant(ShCtV, getShiftAmountTy());
5902 SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(),
5904 AddToWorkList(Shift.getNode());
5906 if (XType.bitsGT(AType)) {
5907 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
5908 AddToWorkList(Shift.getNode());
5911 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
5914 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(),
5916 DAG.getConstant(XType.getSizeInBits()-1,
5917 getShiftAmountTy()));
5918 AddToWorkList(Shift.getNode());
5920 if (XType.bitsGT(AType)) {
5921 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
5922 AddToWorkList(Shift.getNode());
5925 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
5929 // fold select C, 16, 0 -> shl C, 4
5930 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
5931 TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent) {
5933 // If the caller doesn't want us to simplify this into a zext of a compare,
5935 if (NotExtCompare && N2C->getAPIntValue() == 1)
5938 // Get a SetCC of the condition
5939 // FIXME: Should probably make sure that setcc is legal if we ever have a
5940 // target where it isn't.
5942 // cast from setcc result type to select result type
5944 SCC = DAG.getSetCC(DL, TLI.getSetCCResultType(N0.getValueType()),
5946 if (N2.getValueType().bitsLT(SCC.getValueType()))
5947 Temp = DAG.getZeroExtendInReg(SCC, N2.getDebugLoc(), N2.getValueType());
5949 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
5950 N2.getValueType(), SCC);
5952 SCC = DAG.getSetCC(N0.getDebugLoc(), MVT::i1, N0, N1, CC);
5953 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
5954 N2.getValueType(), SCC);
5957 AddToWorkList(SCC.getNode());
5958 AddToWorkList(Temp.getNode());
5960 if (N2C->getAPIntValue() == 1)
5963 // shl setcc result by log2 n2c
5964 return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
5965 DAG.getConstant(N2C->getAPIntValue().logBase2(),
5966 getShiftAmountTy()));
5969 // Check to see if this is the equivalent of setcc
5970 // FIXME: Turn all of these into setcc if setcc if setcc is legal
5971 // otherwise, go ahead with the folds.
5972 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
5973 EVT XType = N0.getValueType();
5974 if (!LegalOperations ||
5975 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(XType))) {
5976 SDValue Res = DAG.getSetCC(DL, TLI.getSetCCResultType(XType), N0, N1, CC);
5977 if (Res.getValueType() != VT)
5978 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
5982 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
5983 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
5984 (!LegalOperations ||
5985 TLI.isOperationLegal(ISD::CTLZ, XType))) {
5986 SDValue Ctlz = DAG.getNode(ISD::CTLZ, N0.getDebugLoc(), XType, N0);
5987 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
5988 DAG.getConstant(Log2_32(XType.getSizeInBits()),
5989 getShiftAmountTy()));
5991 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
5992 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
5993 SDValue NegN0 = DAG.getNode(ISD::SUB, N0.getDebugLoc(),
5994 XType, DAG.getConstant(0, XType), N0);
5995 SDValue NotN0 = DAG.getNOT(N0.getDebugLoc(), N0, XType);
5996 return DAG.getNode(ISD::SRL, DL, XType,
5997 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
5998 DAG.getConstant(XType.getSizeInBits()-1,
5999 getShiftAmountTy()));
6001 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
6002 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
6003 SDValue Sign = DAG.getNode(ISD::SRL, N0.getDebugLoc(), XType, N0,
6004 DAG.getConstant(XType.getSizeInBits()-1,
6005 getShiftAmountTy()));
6006 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
6010 // Check to see if this is an integer abs. select_cc setl[te] X, 0, -X, X ->
6011 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
6012 if (N1C && N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE) &&
6013 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1) &&
6014 N2.getOperand(0) == N1 && N0.getValueType().isInteger()) {
6015 EVT XType = N0.getValueType();
6016 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType, N0,
6017 DAG.getConstant(XType.getSizeInBits()-1,
6018 getShiftAmountTy()));
6019 SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(), XType,
6021 AddToWorkList(Shift.getNode());
6022 AddToWorkList(Add.getNode());
6023 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
6025 // Check to see if this is an integer abs. select_cc setgt X, -1, X, -X ->
6026 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
6027 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT &&
6028 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) {
6029 if (ConstantSDNode *SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0))) {
6030 EVT XType = N0.getValueType();
6031 if (SubC->isNullValue() && XType.isInteger()) {
6032 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType,
6034 DAG.getConstant(XType.getSizeInBits()-1,
6035 getShiftAmountTy()));
6036 SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(),
6038 AddToWorkList(Shift.getNode());
6039 AddToWorkList(Add.getNode());
6040 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
6048 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
6049 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
6050 SDValue N1, ISD::CondCode Cond,
6051 DebugLoc DL, bool foldBooleans) {
6052 TargetLowering::DAGCombinerInfo
6053 DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
6054 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
6057 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
6058 /// return a DAG expression to select that will generate the same value by
6059 /// multiplying by a magic number. See:
6060 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
6061 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
6062 std::vector<SDNode*> Built;
6063 SDValue S = TLI.BuildSDIV(N, DAG, &Built);
6065 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
6071 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
6072 /// return a DAG expression to select that will generate the same value by
6073 /// multiplying by a magic number. See:
6074 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
6075 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
6076 std::vector<SDNode*> Built;
6077 SDValue S = TLI.BuildUDIV(N, DAG, &Built);
6079 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
6085 /// FindBaseOffset - Return true if base is known not to alias with anything
6086 /// but itself. Provides base object and offset as results.
6087 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset) {
6088 // Assume it is a primitive operation.
6089 Base = Ptr; Offset = 0;
6091 // If it's an adding a simple constant then integrate the offset.
6092 if (Base.getOpcode() == ISD::ADD) {
6093 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
6094 Base = Base.getOperand(0);
6095 Offset += C->getZExtValue();
6099 // If it's any of the following then it can't alias with anything but itself.
6100 return isa<FrameIndexSDNode>(Base) ||
6101 isa<ConstantPoolSDNode>(Base) ||
6102 isa<GlobalAddressSDNode>(Base);
6105 /// isAlias - Return true if there is any possibility that the two addresses
6107 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
6108 const Value *SrcValue1, int SrcValueOffset1,
6109 SDValue Ptr2, int64_t Size2,
6110 const Value *SrcValue2, int SrcValueOffset2) const {
6111 // If they are the same then they must be aliases.
6112 if (Ptr1 == Ptr2) return true;
6114 // Gather base node and offset information.
6115 SDValue Base1, Base2;
6116 int64_t Offset1, Offset2;
6117 bool KnownBase1 = FindBaseOffset(Ptr1, Base1, Offset1);
6118 bool KnownBase2 = FindBaseOffset(Ptr2, Base2, Offset2);
6120 // If they have a same base address then...
6122 // Check to see if the addresses overlap.
6123 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
6125 // If we know both bases then they can't alias.
6126 if (KnownBase1 && KnownBase2) return false;
6128 if (CombinerGlobalAA) {
6129 // Use alias analysis information.
6130 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
6131 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
6132 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
6133 AliasAnalysis::AliasResult AAResult =
6134 AA.alias(SrcValue1, Overlap1, SrcValue2, Overlap2);
6135 if (AAResult == AliasAnalysis::NoAlias)
6139 // Otherwise we have to assume they alias.
6143 /// FindAliasInfo - Extracts the relevant alias information from the memory
6144 /// node. Returns true if the operand was a load.
6145 bool DAGCombiner::FindAliasInfo(SDNode *N,
6146 SDValue &Ptr, int64_t &Size,
6147 const Value *&SrcValue, int &SrcValueOffset) const {
6148 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
6149 Ptr = LD->getBasePtr();
6150 Size = LD->getMemoryVT().getSizeInBits() >> 3;
6151 SrcValue = LD->getSrcValue();
6152 SrcValueOffset = LD->getSrcValueOffset();
6154 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
6155 Ptr = ST->getBasePtr();
6156 Size = ST->getMemoryVT().getSizeInBits() >> 3;
6157 SrcValue = ST->getSrcValue();
6158 SrcValueOffset = ST->getSrcValueOffset();
6160 llvm_unreachable("FindAliasInfo expected a memory operand");
6166 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
6167 /// looking for aliasing nodes and adding them to the Aliases vector.
6168 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
6169 SmallVector<SDValue, 8> &Aliases) {
6170 SmallVector<SDValue, 8> Chains; // List of chains to visit.
6171 std::set<SDNode *> Visited; // Visited node set.
6173 // Get alias information for node.
6176 const Value *SrcValue = 0;
6177 int SrcValueOffset = 0;
6178 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset);
6181 Chains.push_back(OriginalChain);
6183 // Look at each chain and determine if it is an alias. If so, add it to the
6184 // aliases list. If not, then continue up the chain looking for the next
6186 while (!Chains.empty()) {
6187 SDValue Chain = Chains.back();
6190 // Don't bother if we've been before.
6191 if (Visited.find(Chain.getNode()) != Visited.end()) continue;
6192 Visited.insert(Chain.getNode());
6194 switch (Chain.getOpcode()) {
6195 case ISD::EntryToken:
6196 // Entry token is ideal chain operand, but handled in FindBetterChain.
6201 // Get alias information for Chain.
6204 const Value *OpSrcValue = 0;
6205 int OpSrcValueOffset = 0;
6206 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
6207 OpSrcValue, OpSrcValueOffset);
6209 // If chain is alias then stop here.
6210 if (!(IsLoad && IsOpLoad) &&
6211 isAlias(Ptr, Size, SrcValue, SrcValueOffset,
6212 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset)) {
6213 Aliases.push_back(Chain);
6215 // Look further up the chain.
6216 Chains.push_back(Chain.getOperand(0));
6217 // Clean up old chain.
6218 AddToWorkList(Chain.getNode());
6223 case ISD::TokenFactor:
6224 // We have to check each of the operands of the token factor, so we queue
6225 // then up. Adding the operands to the queue (stack) in reverse order
6226 // maintains the original order and increases the likelihood that getNode
6227 // will find a matching token factor (CSE.)
6228 for (unsigned n = Chain.getNumOperands(); n;)
6229 Chains.push_back(Chain.getOperand(--n));
6230 // Eliminate the token factor if we can.
6231 AddToWorkList(Chain.getNode());
6235 // For all other instructions we will just have to take what we can get.
6236 Aliases.push_back(Chain);
6242 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
6243 /// for a better chain (aliasing node.)
6244 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
6245 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
6247 // Accumulate all the aliases to this node.
6248 GatherAllAliases(N, OldChain, Aliases);
6250 if (Aliases.size() == 0) {
6251 // If no operands then chain to entry token.
6252 return DAG.getEntryNode();
6253 } else if (Aliases.size() == 1) {
6254 // If a single operand then chain to it. We don't need to revisit it.
6258 // Construct a custom tailored token factor.
6259 SDValue NewChain = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
6260 &Aliases[0], Aliases.size());
6262 // Make sure the old chain gets cleaned up.
6263 if (NewChain != OldChain) AddToWorkList(OldChain.getNode());
6268 // SelectionDAG::Combine - This is the entry point for the file.
6270 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
6271 CodeGenOpt::Level OptLevel) {
6272 /// run - This is the main entry point to this class.
6274 DAGCombiner(*this, AA, OptLevel).Run(Level);