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/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/raw_ostream.h"
42 STATISTIC(NodesCombined , "Number of dag nodes combined");
43 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
44 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
45 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
49 CombinerAA("combiner-alias-analysis", cl::Hidden,
50 cl::desc("Turn on alias analysis during testing"));
53 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
54 cl::desc("Include global information in alias analysis"));
56 //------------------------------ DAGCombiner ---------------------------------//
60 const TargetLowering &TLI;
62 CodeGenOpt::Level OptLevel;
66 // Worklist of all of the nodes that need to be simplified.
67 std::vector<SDNode*> WorkList;
69 // AA - Used for DAG load/store alias analysis.
72 /// AddUsersToWorkList - When an instruction is simplified, add all users of
73 /// the instruction to the work lists because they might get more simplified
76 void AddUsersToWorkList(SDNode *N) {
77 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
82 /// visit - call the node-specific routine that knows how to fold each
83 /// particular type of node.
84 SDValue visit(SDNode *N);
87 /// AddToWorkList - Add to the work list making sure it's instance is at the
88 /// the back (next to be processed.)
89 void AddToWorkList(SDNode *N) {
90 removeFromWorkList(N);
91 WorkList.push_back(N);
94 /// removeFromWorkList - remove all instances of N from the worklist.
96 void removeFromWorkList(SDNode *N) {
97 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N),
101 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
104 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
105 return CombineTo(N, &Res, 1, AddTo);
108 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
110 SDValue To[] = { Res0, Res1 };
111 return CombineTo(N, To, 2, AddTo);
114 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
118 /// SimplifyDemandedBits - Check the specified integer node value to see if
119 /// it can be simplified or if things it uses can be simplified by bit
120 /// propagation. If so, return true.
121 bool SimplifyDemandedBits(SDValue Op) {
122 APInt Demanded = APInt::getAllOnesValue(Op.getValueSizeInBits());
123 return SimplifyDemandedBits(Op, Demanded);
126 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
128 bool CombineToPreIndexedLoadStore(SDNode *N);
129 bool CombineToPostIndexedLoadStore(SDNode *N);
132 /// combine - call the node-specific routine that knows how to fold each
133 /// particular type of node. If that doesn't do anything, try the
134 /// target-specific DAG combines.
135 SDValue combine(SDNode *N);
137 // Visitation implementation - Implement dag node combining for different
138 // node types. The semantics are as follows:
140 // SDValue.getNode() == 0 - No change was made
141 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
142 // otherwise - N should be replaced by the returned Operand.
144 SDValue visitTokenFactor(SDNode *N);
145 SDValue visitMERGE_VALUES(SDNode *N);
146 SDValue visitADD(SDNode *N);
147 SDValue visitSUB(SDNode *N);
148 SDValue visitADDC(SDNode *N);
149 SDValue visitADDE(SDNode *N);
150 SDValue visitMUL(SDNode *N);
151 SDValue visitSDIV(SDNode *N);
152 SDValue visitUDIV(SDNode *N);
153 SDValue visitSREM(SDNode *N);
154 SDValue visitUREM(SDNode *N);
155 SDValue visitMULHU(SDNode *N);
156 SDValue visitMULHS(SDNode *N);
157 SDValue visitSMUL_LOHI(SDNode *N);
158 SDValue visitUMUL_LOHI(SDNode *N);
159 SDValue visitSDIVREM(SDNode *N);
160 SDValue visitUDIVREM(SDNode *N);
161 SDValue visitAND(SDNode *N);
162 SDValue visitOR(SDNode *N);
163 SDValue visitXOR(SDNode *N);
164 SDValue SimplifyVBinOp(SDNode *N);
165 SDValue visitSHL(SDNode *N);
166 SDValue visitSRA(SDNode *N);
167 SDValue visitSRL(SDNode *N);
168 SDValue visitCTLZ(SDNode *N);
169 SDValue visitCTTZ(SDNode *N);
170 SDValue visitCTPOP(SDNode *N);
171 SDValue visitSELECT(SDNode *N);
172 SDValue visitSELECT_CC(SDNode *N);
173 SDValue visitSETCC(SDNode *N);
174 SDValue visitSIGN_EXTEND(SDNode *N);
175 SDValue visitZERO_EXTEND(SDNode *N);
176 SDValue visitANY_EXTEND(SDNode *N);
177 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
178 SDValue visitTRUNCATE(SDNode *N);
179 SDValue visitBIT_CONVERT(SDNode *N);
180 SDValue visitBUILD_PAIR(SDNode *N);
181 SDValue visitFADD(SDNode *N);
182 SDValue visitFSUB(SDNode *N);
183 SDValue visitFMUL(SDNode *N);
184 SDValue visitFDIV(SDNode *N);
185 SDValue visitFREM(SDNode *N);
186 SDValue visitFCOPYSIGN(SDNode *N);
187 SDValue visitSINT_TO_FP(SDNode *N);
188 SDValue visitUINT_TO_FP(SDNode *N);
189 SDValue visitFP_TO_SINT(SDNode *N);
190 SDValue visitFP_TO_UINT(SDNode *N);
191 SDValue visitFP_ROUND(SDNode *N);
192 SDValue visitFP_ROUND_INREG(SDNode *N);
193 SDValue visitFP_EXTEND(SDNode *N);
194 SDValue visitFNEG(SDNode *N);
195 SDValue visitFABS(SDNode *N);
196 SDValue visitBRCOND(SDNode *N);
197 SDValue visitBR_CC(SDNode *N);
198 SDValue visitLOAD(SDNode *N);
199 SDValue visitSTORE(SDNode *N);
200 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
201 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
202 SDValue visitBUILD_VECTOR(SDNode *N);
203 SDValue visitCONCAT_VECTORS(SDNode *N);
204 SDValue visitVECTOR_SHUFFLE(SDNode *N);
206 SDValue XformToShuffleWithZero(SDNode *N);
207 SDValue ReassociateOps(unsigned Opc, DebugLoc DL, SDValue LHS, SDValue RHS);
209 SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
211 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
212 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
213 SDValue SimplifySelect(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2);
214 SDValue SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2,
215 SDValue N3, ISD::CondCode CC,
216 bool NotExtCompare = false);
217 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
218 DebugLoc DL, bool foldBooleans = true);
219 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
221 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
222 SDValue ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *, EVT);
223 SDValue BuildSDIV(SDNode *N);
224 SDValue BuildUDIV(SDNode *N);
225 SDNode *MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL);
226 SDValue ReduceLoadWidth(SDNode *N);
227 SDValue ReduceLoadOpStoreWidth(SDNode *N);
229 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
231 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
232 /// looking for aliasing nodes and adding them to the Aliases vector.
233 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
234 SmallVector<SDValue, 8> &Aliases);
236 /// isAlias - Return true if there is any possibility that the two addresses
238 bool isAlias(SDValue Ptr1, int64_t Size1,
239 const Value *SrcValue1, int SrcValueOffset1,
240 unsigned SrcValueAlign1,
241 SDValue Ptr2, int64_t Size2,
242 const Value *SrcValue2, int SrcValueOffset2,
243 unsigned SrcValueAlign2) 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,
250 unsigned &SrcValueAlignment) const;
252 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
253 /// looking for a better chain (aliasing node.)
254 SDValue FindBetterChain(SDNode *N, SDValue Chain);
256 /// getShiftAmountTy - Returns a type large enough to hold any valid
257 /// shift amount - before type legalization these can be huge.
258 EVT getShiftAmountTy() {
259 return LegalTypes ? TLI.getShiftAmountTy() : TLI.getPointerTy();
263 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
265 TLI(D.getTargetLoweringInfo()),
268 LegalOperations(false),
272 /// Run - runs the dag combiner on all nodes in the work list
273 void Run(CombineLevel AtLevel);
279 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
280 /// nodes from the worklist.
281 class WorkListRemover : 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((!To[i].getNode() ||
550 N->getValueType(i) == To[i].getValueType()) &&
551 "Cannot combine value to value of different type!"));
552 WorkListRemover DeadNodes(*this);
553 DAG.ReplaceAllUsesWith(N, To, &DeadNodes);
556 // Push the new nodes and any users onto the worklist
557 for (unsigned i = 0, e = NumTo; i != e; ++i) {
558 if (To[i].getNode()) {
559 AddToWorkList(To[i].getNode());
560 AddUsersToWorkList(To[i].getNode());
565 // Finally, if the node is now dead, remove it from the graph. The node
566 // may not be dead if the replacement process recursively simplified to
567 // something else needing this node.
568 if (N->use_empty()) {
569 // Nodes can be reintroduced into the worklist. Make sure we do not
570 // process a node that has been replaced.
571 removeFromWorkList(N);
573 // Finally, since the node is now dead, remove it from the graph.
576 return SDValue(N, 0);
580 DAGCombiner::CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &
582 // Replace all uses. If any nodes become isomorphic to other nodes and
583 // are deleted, make sure to remove them from our worklist.
584 WorkListRemover DeadNodes(*this);
585 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, &DeadNodes);
587 // Push the new node and any (possibly new) users onto the worklist.
588 AddToWorkList(TLO.New.getNode());
589 AddUsersToWorkList(TLO.New.getNode());
591 // Finally, if the node is now dead, remove it from the graph. The node
592 // may not be dead if the replacement process recursively simplified to
593 // something else needing this node.
594 if (TLO.Old.getNode()->use_empty()) {
595 removeFromWorkList(TLO.Old.getNode());
597 // If the operands of this node are only used by the node, they will now
598 // be dead. Make sure to visit them first to delete dead nodes early.
599 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
600 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
601 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
603 DAG.DeleteNode(TLO.Old.getNode());
607 /// SimplifyDemandedBits - Check the specified integer node value to see if
608 /// it can be simplified or if things it uses can be simplified by bit
609 /// propagation. If so, return true.
610 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
611 TargetLowering::TargetLoweringOpt TLO(DAG);
612 APInt KnownZero, KnownOne;
613 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
617 AddToWorkList(Op.getNode());
619 // Replace the old value with the new one.
621 DEBUG(errs() << "\nReplacing.2 ";
622 TLO.Old.getNode()->dump(&DAG);
623 errs() << "\nWith: ";
624 TLO.New.getNode()->dump(&DAG);
627 CommitTargetLoweringOpt(TLO);
631 //===----------------------------------------------------------------------===//
632 // Main DAG Combiner implementation
633 //===----------------------------------------------------------------------===//
635 void DAGCombiner::Run(CombineLevel AtLevel) {
636 // set the instance variables, so that the various visit routines may use it.
638 LegalOperations = Level >= NoIllegalOperations;
639 LegalTypes = Level >= NoIllegalTypes;
641 // Add all the dag nodes to the worklist.
642 WorkList.reserve(DAG.allnodes_size());
643 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
644 E = DAG.allnodes_end(); I != E; ++I)
645 WorkList.push_back(I);
647 // Create a dummy node (which is not added to allnodes), that adds a reference
648 // to the root node, preventing it from being deleted, and tracking any
649 // changes of the root.
650 HandleSDNode Dummy(DAG.getRoot());
652 // The root of the dag may dangle to deleted nodes until the dag combiner is
653 // done. Set it to null to avoid confusion.
654 DAG.setRoot(SDValue());
656 // while the worklist isn't empty, inspect the node on the end of it and
657 // try and combine it.
658 while (!WorkList.empty()) {
659 SDNode *N = WorkList.back();
662 // If N has no uses, it is dead. Make sure to revisit all N's operands once
663 // N is deleted from the DAG, since they too may now be dead or may have a
664 // reduced number of uses, allowing other xforms.
665 if (N->use_empty() && N != &Dummy) {
666 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
667 AddToWorkList(N->getOperand(i).getNode());
673 SDValue RV = combine(N);
675 if (RV.getNode() == 0)
680 // If we get back the same node we passed in, rather than a new node or
681 // zero, we know that the node must have defined multiple values and
682 // CombineTo was used. Since CombineTo takes care of the worklist
683 // mechanics for us, we have no work to do in this case.
684 if (RV.getNode() == N)
687 assert(N->getOpcode() != ISD::DELETED_NODE &&
688 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
689 "Node was deleted but visit returned new node!");
691 DEBUG(errs() << "\nReplacing.3 ";
693 errs() << "\nWith: ";
694 RV.getNode()->dump(&DAG);
696 WorkListRemover DeadNodes(*this);
697 if (N->getNumValues() == RV.getNode()->getNumValues())
698 DAG.ReplaceAllUsesWith(N, RV.getNode(), &DeadNodes);
700 assert(N->getValueType(0) == RV.getValueType() &&
701 N->getNumValues() == 1 && "Type mismatch");
703 DAG.ReplaceAllUsesWith(N, &OpV, &DeadNodes);
706 // Push the new node and any users onto the worklist
707 AddToWorkList(RV.getNode());
708 AddUsersToWorkList(RV.getNode());
710 // Add any uses of the old node to the worklist in case this node is the
711 // last one that uses them. They may become dead after this node is
713 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
714 AddToWorkList(N->getOperand(i).getNode());
716 // Finally, if the node is now dead, remove it from the graph. The node
717 // may not be dead if the replacement process recursively simplified to
718 // something else needing this node.
719 if (N->use_empty()) {
720 // Nodes can be reintroduced into the worklist. Make sure we do not
721 // process a node that has been replaced.
722 removeFromWorkList(N);
724 // Finally, since the node is now dead, remove it from the graph.
729 // If the root changed (e.g. it was a dead load, update the root).
730 DAG.setRoot(Dummy.getValue());
733 SDValue DAGCombiner::visit(SDNode *N) {
734 switch(N->getOpcode()) {
736 case ISD::TokenFactor: return visitTokenFactor(N);
737 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
738 case ISD::ADD: return visitADD(N);
739 case ISD::SUB: return visitSUB(N);
740 case ISD::ADDC: return visitADDC(N);
741 case ISD::ADDE: return visitADDE(N);
742 case ISD::MUL: return visitMUL(N);
743 case ISD::SDIV: return visitSDIV(N);
744 case ISD::UDIV: return visitUDIV(N);
745 case ISD::SREM: return visitSREM(N);
746 case ISD::UREM: return visitUREM(N);
747 case ISD::MULHU: return visitMULHU(N);
748 case ISD::MULHS: return visitMULHS(N);
749 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
750 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
751 case ISD::SDIVREM: return visitSDIVREM(N);
752 case ISD::UDIVREM: return visitUDIVREM(N);
753 case ISD::AND: return visitAND(N);
754 case ISD::OR: return visitOR(N);
755 case ISD::XOR: return visitXOR(N);
756 case ISD::SHL: return visitSHL(N);
757 case ISD::SRA: return visitSRA(N);
758 case ISD::SRL: return visitSRL(N);
759 case ISD::CTLZ: return visitCTLZ(N);
760 case ISD::CTTZ: return visitCTTZ(N);
761 case ISD::CTPOP: return visitCTPOP(N);
762 case ISD::SELECT: return visitSELECT(N);
763 case ISD::SELECT_CC: return visitSELECT_CC(N);
764 case ISD::SETCC: return visitSETCC(N);
765 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
766 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
767 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
768 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
769 case ISD::TRUNCATE: return visitTRUNCATE(N);
770 case ISD::BIT_CONVERT: return visitBIT_CONVERT(N);
771 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
772 case ISD::FADD: return visitFADD(N);
773 case ISD::FSUB: return visitFSUB(N);
774 case ISD::FMUL: return visitFMUL(N);
775 case ISD::FDIV: return visitFDIV(N);
776 case ISD::FREM: return visitFREM(N);
777 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
778 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
779 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
780 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
781 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
782 case ISD::FP_ROUND: return visitFP_ROUND(N);
783 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
784 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
785 case ISD::FNEG: return visitFNEG(N);
786 case ISD::FABS: return visitFABS(N);
787 case ISD::BRCOND: return visitBRCOND(N);
788 case ISD::BR_CC: return visitBR_CC(N);
789 case ISD::LOAD: return visitLOAD(N);
790 case ISD::STORE: return visitSTORE(N);
791 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
792 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
793 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
794 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
795 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
800 SDValue DAGCombiner::combine(SDNode *N) {
801 SDValue RV = visit(N);
803 // If nothing happened, try a target-specific DAG combine.
804 if (RV.getNode() == 0) {
805 assert(N->getOpcode() != ISD::DELETED_NODE &&
806 "Node was deleted but visit returned NULL!");
808 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
809 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
811 // Expose the DAG combiner to the target combiner impls.
812 TargetLowering::DAGCombinerInfo
813 DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
815 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
819 // If N is a commutative binary node, try commuting it to enable more
821 if (RV.getNode() == 0 &&
822 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
823 N->getNumValues() == 1) {
824 SDValue N0 = N->getOperand(0);
825 SDValue N1 = N->getOperand(1);
827 // Constant operands are canonicalized to RHS.
828 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
829 SDValue Ops[] = { N1, N0 };
830 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
833 return SDValue(CSENode, 0);
840 /// getInputChainForNode - Given a node, return its input chain if it has one,
841 /// otherwise return a null sd operand.
842 static SDValue getInputChainForNode(SDNode *N) {
843 if (unsigned NumOps = N->getNumOperands()) {
844 if (N->getOperand(0).getValueType() == MVT::Other)
845 return N->getOperand(0);
846 else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
847 return N->getOperand(NumOps-1);
848 for (unsigned i = 1; i < NumOps-1; ++i)
849 if (N->getOperand(i).getValueType() == MVT::Other)
850 return N->getOperand(i);
855 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
856 // If N has two operands, where one has an input chain equal to the other,
857 // the 'other' chain is redundant.
858 if (N->getNumOperands() == 2) {
859 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
860 return N->getOperand(0);
861 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
862 return N->getOperand(1);
865 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
866 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
867 SmallPtrSet<SDNode*, 16> SeenOps;
868 bool Changed = false; // If we should replace this token factor.
870 // Start out with this token factor.
873 // Iterate through token factors. The TFs grows when new token factors are
875 for (unsigned i = 0; i < TFs.size(); ++i) {
878 // Check each of the operands.
879 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
880 SDValue Op = TF->getOperand(i);
882 switch (Op.getOpcode()) {
883 case ISD::EntryToken:
884 // Entry tokens don't need to be added to the list. They are
889 case ISD::TokenFactor:
890 if (Op.hasOneUse() &&
891 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
892 // Queue up for processing.
893 TFs.push_back(Op.getNode());
894 // Clean up in case the token factor is removed.
895 AddToWorkList(Op.getNode());
902 // Only add if it isn't already in the list.
903 if (SeenOps.insert(Op.getNode()))
914 // If we've change things around then replace token factor.
917 // The entry token is the only possible outcome.
918 Result = DAG.getEntryNode();
920 // New and improved token factor.
921 Result = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
922 MVT::Other, &Ops[0], Ops.size());
925 // Don't add users to work list.
926 return CombineTo(N, Result, false);
932 /// MERGE_VALUES can always be eliminated.
933 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
934 WorkListRemover DeadNodes(*this);
935 // Replacing results may cause a different MERGE_VALUES to suddenly
936 // be CSE'd with N, and carry its uses with it. Iterate until no
937 // uses remain, to ensure that the node can be safely deleted.
939 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
940 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i),
942 } while (!N->use_empty());
943 removeFromWorkList(N);
945 return SDValue(N, 0); // Return N so it doesn't get rechecked!
949 SDValue combineShlAddConstant(DebugLoc DL, SDValue N0, SDValue N1,
951 EVT VT = N0.getValueType();
952 SDValue N00 = N0.getOperand(0);
953 SDValue N01 = N0.getOperand(1);
954 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
956 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
957 isa<ConstantSDNode>(N00.getOperand(1))) {
958 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
959 N0 = DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT,
960 DAG.getNode(ISD::SHL, N00.getDebugLoc(), VT,
961 N00.getOperand(0), N01),
962 DAG.getNode(ISD::SHL, N01.getDebugLoc(), VT,
963 N00.getOperand(1), N01));
964 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
970 SDValue DAGCombiner::visitADD(SDNode *N) {
971 SDValue N0 = N->getOperand(0);
972 SDValue N1 = N->getOperand(1);
973 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
974 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
975 EVT VT = N0.getValueType();
979 SDValue FoldedVOp = SimplifyVBinOp(N);
980 if (FoldedVOp.getNode()) return FoldedVOp;
983 // fold (add x, undef) -> undef
984 if (N0.getOpcode() == ISD::UNDEF)
986 if (N1.getOpcode() == ISD::UNDEF)
988 // fold (add c1, c2) -> c1+c2
990 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
991 // canonicalize constant to RHS
993 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0);
994 // fold (add x, 0) -> x
995 if (N1C && N1C->isNullValue())
997 // fold (add Sym, c) -> Sym+c
998 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
999 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1000 GA->getOpcode() == ISD::GlobalAddress)
1001 return DAG.getGlobalAddress(GA->getGlobal(), VT,
1003 (uint64_t)N1C->getSExtValue());
1004 // fold ((c1-A)+c2) -> (c1+c2)-A
1005 if (N1C && N0.getOpcode() == ISD::SUB)
1006 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1007 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1008 DAG.getConstant(N1C->getAPIntValue()+
1009 N0C->getAPIntValue(), VT),
1012 SDValue RADD = ReassociateOps(ISD::ADD, N->getDebugLoc(), N0, N1);
1013 if (RADD.getNode() != 0)
1015 // fold ((0-A) + B) -> B-A
1016 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1017 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1018 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1, N0.getOperand(1));
1019 // fold (A + (0-B)) -> A-B
1020 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1021 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1022 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1.getOperand(1));
1023 // fold (A+(B-A)) -> B
1024 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1025 return N1.getOperand(0);
1026 // fold ((B-A)+A) -> B
1027 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1028 return N0.getOperand(0);
1029 // fold (A+(B-(A+C))) to (B-C)
1030 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1031 N0 == N1.getOperand(1).getOperand(0))
1032 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1033 N1.getOperand(1).getOperand(1));
1034 // fold (A+(B-(C+A))) to (B-C)
1035 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1036 N0 == N1.getOperand(1).getOperand(1))
1037 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1038 N1.getOperand(1).getOperand(0));
1039 // fold (A+((B-A)+or-C)) to (B+or-C)
1040 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1041 N1.getOperand(0).getOpcode() == ISD::SUB &&
1042 N0 == N1.getOperand(0).getOperand(1))
1043 return DAG.getNode(N1.getOpcode(), N->getDebugLoc(), VT,
1044 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1046 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1047 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1048 SDValue N00 = N0.getOperand(0);
1049 SDValue N01 = N0.getOperand(1);
1050 SDValue N10 = N1.getOperand(0);
1051 SDValue N11 = N1.getOperand(1);
1053 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1054 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1055 DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT, N00, N10),
1056 DAG.getNode(ISD::ADD, N1.getDebugLoc(), VT, N01, N11));
1059 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1060 return SDValue(N, 0);
1062 // fold (a+b) -> (a|b) iff a and b share no bits.
1063 if (VT.isInteger() && !VT.isVector()) {
1064 APInt LHSZero, LHSOne;
1065 APInt RHSZero, RHSOne;
1066 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
1067 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1069 if (LHSZero.getBoolValue()) {
1070 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1072 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1073 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1074 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1075 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1076 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1);
1080 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1081 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1082 SDValue Result = combineShlAddConstant(N->getDebugLoc(), N0, N1, DAG);
1083 if (Result.getNode()) return Result;
1085 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1086 SDValue Result = combineShlAddConstant(N->getDebugLoc(), N1, N0, DAG);
1087 if (Result.getNode()) return Result;
1093 SDValue DAGCombiner::visitADDC(SDNode *N) {
1094 SDValue N0 = N->getOperand(0);
1095 SDValue N1 = N->getOperand(1);
1096 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1097 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1098 EVT VT = N0.getValueType();
1100 // If the flag result is dead, turn this into an ADD.
1101 if (N->hasNUsesOfValue(0, 1))
1102 return CombineTo(N, DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0),
1103 DAG.getNode(ISD::CARRY_FALSE,
1104 N->getDebugLoc(), MVT::Flag));
1106 // canonicalize constant to RHS.
1108 return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
1110 // fold (addc x, 0) -> x + no carry out
1111 if (N1C && N1C->isNullValue())
1112 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1113 N->getDebugLoc(), MVT::Flag));
1115 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1116 APInt LHSZero, LHSOne;
1117 APInt RHSZero, RHSOne;
1118 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
1119 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1121 if (LHSZero.getBoolValue()) {
1122 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1124 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1125 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1126 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1127 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1128 return CombineTo(N, DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1),
1129 DAG.getNode(ISD::CARRY_FALSE,
1130 N->getDebugLoc(), MVT::Flag));
1136 SDValue DAGCombiner::visitADDE(SDNode *N) {
1137 SDValue N0 = N->getOperand(0);
1138 SDValue N1 = N->getOperand(1);
1139 SDValue CarryIn = N->getOperand(2);
1140 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1141 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1143 // canonicalize constant to RHS
1145 return DAG.getNode(ISD::ADDE, N->getDebugLoc(), N->getVTList(),
1148 // fold (adde x, y, false) -> (addc x, y)
1149 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1150 return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
1155 SDValue DAGCombiner::visitSUB(SDNode *N) {
1156 SDValue N0 = N->getOperand(0);
1157 SDValue N1 = N->getOperand(1);
1158 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1159 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1160 EVT VT = N0.getValueType();
1163 if (VT.isVector()) {
1164 SDValue FoldedVOp = SimplifyVBinOp(N);
1165 if (FoldedVOp.getNode()) return FoldedVOp;
1168 // fold (sub x, x) -> 0
1170 return DAG.getConstant(0, N->getValueType(0));
1171 // fold (sub c1, c2) -> c1-c2
1173 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1174 // fold (sub x, c) -> (add x, -c)
1176 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0,
1177 DAG.getConstant(-N1C->getAPIntValue(), VT));
1178 // fold (A+B)-A -> B
1179 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1180 return N0.getOperand(1);
1181 // fold (A+B)-B -> A
1182 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1183 return N0.getOperand(0);
1184 // fold ((A+(B+or-C))-B) -> A+or-C
1185 if (N0.getOpcode() == ISD::ADD &&
1186 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1187 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1188 N0.getOperand(1).getOperand(0) == N1)
1189 return DAG.getNode(N0.getOperand(1).getOpcode(), N->getDebugLoc(), VT,
1190 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1191 // fold ((A+(C+B))-B) -> A+C
1192 if (N0.getOpcode() == ISD::ADD &&
1193 N0.getOperand(1).getOpcode() == ISD::ADD &&
1194 N0.getOperand(1).getOperand(1) == N1)
1195 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1196 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1197 // fold ((A-(B-C))-C) -> A-B
1198 if (N0.getOpcode() == ISD::SUB &&
1199 N0.getOperand(1).getOpcode() == ISD::SUB &&
1200 N0.getOperand(1).getOperand(1) == N1)
1201 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1202 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1204 // If either operand of a sub is undef, the result is undef
1205 if (N0.getOpcode() == ISD::UNDEF)
1207 if (N1.getOpcode() == ISD::UNDEF)
1210 // If the relocation model supports it, consider symbol offsets.
1211 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1212 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1213 // fold (sub Sym, c) -> Sym-c
1214 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1215 return DAG.getGlobalAddress(GA->getGlobal(), VT,
1217 (uint64_t)N1C->getSExtValue());
1218 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1219 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1220 if (GA->getGlobal() == GB->getGlobal())
1221 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1228 SDValue DAGCombiner::visitMUL(SDNode *N) {
1229 SDValue N0 = N->getOperand(0);
1230 SDValue N1 = N->getOperand(1);
1231 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1232 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1233 EVT VT = N0.getValueType();
1236 if (VT.isVector()) {
1237 SDValue FoldedVOp = SimplifyVBinOp(N);
1238 if (FoldedVOp.getNode()) return FoldedVOp;
1241 // fold (mul x, undef) -> 0
1242 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1243 return DAG.getConstant(0, VT);
1244 // fold (mul c1, c2) -> c1*c2
1246 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0C, N1C);
1247 // canonicalize constant to RHS
1249 return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, N1, N0);
1250 // fold (mul x, 0) -> 0
1251 if (N1C && N1C->isNullValue())
1253 // fold (mul x, -1) -> 0-x
1254 if (N1C && N1C->isAllOnesValue())
1255 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1256 DAG.getConstant(0, VT), N0);
1257 // fold (mul x, (1 << c)) -> x << c
1258 if (N1C && N1C->getAPIntValue().isPowerOf2())
1259 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1260 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1261 getShiftAmountTy()));
1262 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1263 if (N1C && (-N1C->getAPIntValue()).isPowerOf2()) {
1264 unsigned Log2Val = (-N1C->getAPIntValue()).logBase2();
1265 // FIXME: If the input is something that is easily negated (e.g. a
1266 // single-use add), we should put the negate there.
1267 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1268 DAG.getConstant(0, VT),
1269 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1270 DAG.getConstant(Log2Val, getShiftAmountTy())));
1272 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1273 if (N1C && N0.getOpcode() == ISD::SHL &&
1274 isa<ConstantSDNode>(N0.getOperand(1))) {
1275 SDValue C3 = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1276 N1, N0.getOperand(1));
1277 AddToWorkList(C3.getNode());
1278 return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1279 N0.getOperand(0), C3);
1282 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1285 SDValue Sh(0,0), Y(0,0);
1286 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1287 if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1288 N0.getNode()->hasOneUse()) {
1290 } else if (N1.getOpcode() == ISD::SHL &&
1291 isa<ConstantSDNode>(N1.getOperand(1)) &&
1292 N1.getNode()->hasOneUse()) {
1297 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1298 Sh.getOperand(0), Y);
1299 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1300 Mul, Sh.getOperand(1));
1304 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1305 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1306 isa<ConstantSDNode>(N0.getOperand(1)))
1307 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1308 DAG.getNode(ISD::MUL, N0.getDebugLoc(), VT,
1309 N0.getOperand(0), N1),
1310 DAG.getNode(ISD::MUL, N1.getDebugLoc(), VT,
1311 N0.getOperand(1), N1));
1314 SDValue RMUL = ReassociateOps(ISD::MUL, N->getDebugLoc(), N0, N1);
1315 if (RMUL.getNode() != 0)
1321 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1322 SDValue N0 = N->getOperand(0);
1323 SDValue N1 = N->getOperand(1);
1324 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1325 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1326 EVT VT = N->getValueType(0);
1329 if (VT.isVector()) {
1330 SDValue FoldedVOp = SimplifyVBinOp(N);
1331 if (FoldedVOp.getNode()) return FoldedVOp;
1334 // fold (sdiv c1, c2) -> c1/c2
1335 if (N0C && N1C && !N1C->isNullValue())
1336 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1337 // fold (sdiv X, 1) -> X
1338 if (N1C && N1C->getSExtValue() == 1LL)
1340 // fold (sdiv X, -1) -> 0-X
1341 if (N1C && N1C->isAllOnesValue())
1342 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1343 DAG.getConstant(0, VT), N0);
1344 // If we know the sign bits of both operands are zero, strength reduce to a
1345 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1346 if (!VT.isVector()) {
1347 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1348 return DAG.getNode(ISD::UDIV, N->getDebugLoc(), N1.getValueType(),
1351 // fold (sdiv X, pow2) -> simple ops after legalize
1352 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap() &&
1353 (isPowerOf2_64(N1C->getSExtValue()) ||
1354 isPowerOf2_64(-N1C->getSExtValue()))) {
1355 // If dividing by powers of two is cheap, then don't perform the following
1357 if (TLI.isPow2DivCheap())
1360 int64_t pow2 = N1C->getSExtValue();
1361 int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
1362 unsigned lg2 = Log2_64(abs2);
1364 // Splat the sign bit into the register
1365 SDValue SGN = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
1366 DAG.getConstant(VT.getSizeInBits()-1,
1367 getShiftAmountTy()));
1368 AddToWorkList(SGN.getNode());
1370 // Add (N0 < 0) ? abs2 - 1 : 0;
1371 SDValue SRL = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, SGN,
1372 DAG.getConstant(VT.getSizeInBits() - lg2,
1373 getShiftAmountTy()));
1374 SDValue ADD = DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, SRL);
1375 AddToWorkList(SRL.getNode());
1376 AddToWorkList(ADD.getNode()); // Divide by pow2
1377 SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, ADD,
1378 DAG.getConstant(lg2, getShiftAmountTy()));
1380 // If we're dividing by a positive value, we're done. Otherwise, we must
1381 // negate the result.
1385 AddToWorkList(SRA.getNode());
1386 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1387 DAG.getConstant(0, VT), SRA);
1390 // if integer divide is expensive and we satisfy the requirements, emit an
1391 // alternate sequence.
1392 if (N1C && (N1C->getSExtValue() < -1 || N1C->getSExtValue() > 1) &&
1393 !TLI.isIntDivCheap()) {
1394 SDValue Op = BuildSDIV(N);
1395 if (Op.getNode()) return Op;
1399 if (N0.getOpcode() == ISD::UNDEF)
1400 return DAG.getConstant(0, VT);
1401 // X / undef -> undef
1402 if (N1.getOpcode() == ISD::UNDEF)
1408 SDValue DAGCombiner::visitUDIV(SDNode *N) {
1409 SDValue N0 = N->getOperand(0);
1410 SDValue N1 = N->getOperand(1);
1411 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1412 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1413 EVT VT = N->getValueType(0);
1416 if (VT.isVector()) {
1417 SDValue FoldedVOp = SimplifyVBinOp(N);
1418 if (FoldedVOp.getNode()) return FoldedVOp;
1421 // fold (udiv c1, c2) -> c1/c2
1422 if (N0C && N1C && !N1C->isNullValue())
1423 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
1424 // fold (udiv x, (1 << c)) -> x >>u c
1425 if (N1C && N1C->getAPIntValue().isPowerOf2())
1426 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
1427 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1428 getShiftAmountTy()));
1429 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1430 if (N1.getOpcode() == ISD::SHL) {
1431 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1432 if (SHC->getAPIntValue().isPowerOf2()) {
1433 EVT ADDVT = N1.getOperand(1).getValueType();
1434 SDValue Add = DAG.getNode(ISD::ADD, N->getDebugLoc(), ADDVT,
1436 DAG.getConstant(SHC->getAPIntValue()
1439 AddToWorkList(Add.getNode());
1440 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, Add);
1444 // fold (udiv x, c) -> alternate
1445 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1446 SDValue Op = BuildUDIV(N);
1447 if (Op.getNode()) return Op;
1451 if (N0.getOpcode() == ISD::UNDEF)
1452 return DAG.getConstant(0, VT);
1453 // X / undef -> undef
1454 if (N1.getOpcode() == ISD::UNDEF)
1460 SDValue DAGCombiner::visitSREM(SDNode *N) {
1461 SDValue N0 = N->getOperand(0);
1462 SDValue N1 = N->getOperand(1);
1463 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1464 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1465 EVT VT = N->getValueType(0);
1467 // fold (srem c1, c2) -> c1%c2
1468 if (N0C && N1C && !N1C->isNullValue())
1469 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
1470 // If we know the sign bits of both operands are zero, strength reduce to a
1471 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
1472 if (!VT.isVector()) {
1473 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1474 return DAG.getNode(ISD::UREM, N->getDebugLoc(), VT, N0, N1);
1477 // If X/C can be simplified by the division-by-constant logic, lower
1478 // X%C to the equivalent of X-X/C*C.
1479 if (N1C && !N1C->isNullValue()) {
1480 SDValue Div = DAG.getNode(ISD::SDIV, N->getDebugLoc(), VT, N0, N1);
1481 AddToWorkList(Div.getNode());
1482 SDValue OptimizedDiv = combine(Div.getNode());
1483 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1484 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1486 SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
1487 AddToWorkList(Mul.getNode());
1493 if (N0.getOpcode() == ISD::UNDEF)
1494 return DAG.getConstant(0, VT);
1495 // X % undef -> undef
1496 if (N1.getOpcode() == ISD::UNDEF)
1502 SDValue DAGCombiner::visitUREM(SDNode *N) {
1503 SDValue N0 = N->getOperand(0);
1504 SDValue N1 = N->getOperand(1);
1505 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1506 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1507 EVT VT = N->getValueType(0);
1509 // fold (urem c1, c2) -> c1%c2
1510 if (N0C && N1C && !N1C->isNullValue())
1511 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
1512 // fold (urem x, pow2) -> (and x, pow2-1)
1513 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
1514 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0,
1515 DAG.getConstant(N1C->getAPIntValue()-1,VT));
1516 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
1517 if (N1.getOpcode() == ISD::SHL) {
1518 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1519 if (SHC->getAPIntValue().isPowerOf2()) {
1521 DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1,
1522 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
1524 AddToWorkList(Add.getNode());
1525 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, Add);
1530 // If X/C can be simplified by the division-by-constant logic, lower
1531 // X%C to the equivalent of X-X/C*C.
1532 if (N1C && !N1C->isNullValue()) {
1533 SDValue Div = DAG.getNode(ISD::UDIV, N->getDebugLoc(), VT, N0, N1);
1534 AddToWorkList(Div.getNode());
1535 SDValue OptimizedDiv = combine(Div.getNode());
1536 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1537 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1539 SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
1540 AddToWorkList(Mul.getNode());
1546 if (N0.getOpcode() == ISD::UNDEF)
1547 return DAG.getConstant(0, VT);
1548 // X % undef -> undef
1549 if (N1.getOpcode() == ISD::UNDEF)
1555 SDValue DAGCombiner::visitMULHS(SDNode *N) {
1556 SDValue N0 = N->getOperand(0);
1557 SDValue N1 = N->getOperand(1);
1558 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1559 EVT VT = N->getValueType(0);
1561 // fold (mulhs x, 0) -> 0
1562 if (N1C && N1C->isNullValue())
1564 // fold (mulhs x, 1) -> (sra x, size(x)-1)
1565 if (N1C && N1C->getAPIntValue() == 1)
1566 return DAG.getNode(ISD::SRA, N->getDebugLoc(), N0.getValueType(), N0,
1567 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
1568 getShiftAmountTy()));
1569 // fold (mulhs x, undef) -> 0
1570 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1571 return DAG.getConstant(0, VT);
1576 SDValue DAGCombiner::visitMULHU(SDNode *N) {
1577 SDValue N0 = N->getOperand(0);
1578 SDValue N1 = N->getOperand(1);
1579 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1580 EVT VT = N->getValueType(0);
1582 // fold (mulhu x, 0) -> 0
1583 if (N1C && N1C->isNullValue())
1585 // fold (mulhu x, 1) -> 0
1586 if (N1C && N1C->getAPIntValue() == 1)
1587 return DAG.getConstant(0, N0.getValueType());
1588 // fold (mulhu x, undef) -> 0
1589 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1590 return DAG.getConstant(0, VT);
1595 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
1596 /// compute two values. LoOp and HiOp give the opcodes for the two computations
1597 /// that are being performed. Return true if a simplification was made.
1599 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
1601 // If the high half is not needed, just compute the low half.
1602 bool HiExists = N->hasAnyUseOfValue(1);
1604 (!LegalOperations ||
1605 TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
1606 SDValue Res = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
1607 N->op_begin(), N->getNumOperands());
1608 return CombineTo(N, Res, Res);
1611 // If the low half is not needed, just compute the high half.
1612 bool LoExists = N->hasAnyUseOfValue(0);
1614 (!LegalOperations ||
1615 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
1616 SDValue Res = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
1617 N->op_begin(), N->getNumOperands());
1618 return CombineTo(N, Res, Res);
1621 // If both halves are used, return as it is.
1622 if (LoExists && HiExists)
1625 // If the two computed results can be simplified separately, separate them.
1627 SDValue Lo = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
1628 N->op_begin(), N->getNumOperands());
1629 AddToWorkList(Lo.getNode());
1630 SDValue LoOpt = combine(Lo.getNode());
1631 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
1632 (!LegalOperations ||
1633 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
1634 return CombineTo(N, LoOpt, LoOpt);
1638 SDValue Hi = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
1639 N->op_begin(), N->getNumOperands());
1640 AddToWorkList(Hi.getNode());
1641 SDValue HiOpt = combine(Hi.getNode());
1642 if (HiOpt.getNode() && HiOpt != Hi &&
1643 (!LegalOperations ||
1644 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
1645 return CombineTo(N, HiOpt, HiOpt);
1651 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
1652 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
1653 if (Res.getNode()) return Res;
1658 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
1659 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
1660 if (Res.getNode()) return Res;
1665 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
1666 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
1667 if (Res.getNode()) return Res;
1672 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
1673 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
1674 if (Res.getNode()) return Res;
1679 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
1680 /// two operands of the same opcode, try to simplify it.
1681 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
1682 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
1683 EVT VT = N0.getValueType();
1684 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
1686 // For each of OP in AND/OR/XOR:
1687 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
1688 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
1689 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
1690 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
1692 // do not sink logical op inside of a vector extend, since it may combine
1694 if ((N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND||
1695 N0.getOpcode() == ISD::SIGN_EXTEND ||
1696 (N0.getOpcode() == ISD::TRUNCATE &&
1697 !TLI.isTruncateFree(N0.getOperand(0).getValueType(), VT))) &&
1699 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
1700 (!LegalOperations ||
1701 TLI.isOperationLegal(N->getOpcode(), N0.getOperand(0).getValueType()))) {
1702 SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
1703 N0.getOperand(0).getValueType(),
1704 N0.getOperand(0), N1.getOperand(0));
1705 AddToWorkList(ORNode.getNode());
1706 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, ORNode);
1709 // For each of OP in SHL/SRL/SRA/AND...
1710 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
1711 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
1712 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
1713 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
1714 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
1715 N0.getOperand(1) == N1.getOperand(1)) {
1716 SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
1717 N0.getOperand(0).getValueType(),
1718 N0.getOperand(0), N1.getOperand(0));
1719 AddToWorkList(ORNode.getNode());
1720 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
1721 ORNode, N0.getOperand(1));
1727 SDValue DAGCombiner::visitAND(SDNode *N) {
1728 SDValue N0 = N->getOperand(0);
1729 SDValue N1 = N->getOperand(1);
1730 SDValue LL, LR, RL, RR, CC0, CC1;
1731 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1732 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1733 EVT VT = N1.getValueType();
1734 unsigned BitWidth = VT.getSizeInBits();
1737 if (VT.isVector()) {
1738 SDValue FoldedVOp = SimplifyVBinOp(N);
1739 if (FoldedVOp.getNode()) return FoldedVOp;
1742 // fold (and x, undef) -> 0
1743 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1744 return DAG.getConstant(0, VT);
1745 // fold (and c1, c2) -> c1&c2
1747 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
1748 // canonicalize constant to RHS
1750 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N1, N0);
1751 // fold (and x, -1) -> x
1752 if (N1C && N1C->isAllOnesValue())
1754 // if (and x, c) is known to be zero, return 0
1755 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
1756 APInt::getAllOnesValue(BitWidth)))
1757 return DAG.getConstant(0, VT);
1759 SDValue RAND = ReassociateOps(ISD::AND, N->getDebugLoc(), N0, N1);
1760 if (RAND.getNode() != 0)
1762 // fold (and (or x, 0xFFFF), 0xFF) -> 0xFF
1763 if (N1C && N0.getOpcode() == ISD::OR)
1764 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
1765 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
1767 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
1768 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
1769 SDValue N0Op0 = N0.getOperand(0);
1770 APInt Mask = ~N1C->getAPIntValue();
1771 Mask.trunc(N0Op0.getValueSizeInBits());
1772 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
1773 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(),
1774 N0.getValueType(), N0Op0);
1776 // Replace uses of the AND with uses of the Zero extend node.
1779 // We actually want to replace all uses of the any_extend with the
1780 // zero_extend, to avoid duplicating things. This will later cause this
1781 // AND to be folded.
1782 CombineTo(N0.getNode(), Zext);
1783 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1786 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
1787 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1788 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1789 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1791 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1792 LL.getValueType().isInteger()) {
1793 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
1794 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
1795 SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
1796 LR.getValueType(), LL, RL);
1797 AddToWorkList(ORNode.getNode());
1798 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
1800 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
1801 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
1802 SDValue ANDNode = DAG.getNode(ISD::AND, N0.getDebugLoc(),
1803 LR.getValueType(), LL, RL);
1804 AddToWorkList(ANDNode.getNode());
1805 return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
1807 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
1808 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
1809 SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
1810 LR.getValueType(), LL, RL);
1811 AddToWorkList(ORNode.getNode());
1812 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
1815 // canonicalize equivalent to ll == rl
1816 if (LL == RR && LR == RL) {
1817 Op1 = ISD::getSetCCSwappedOperands(Op1);
1820 if (LL == RL && LR == RR) {
1821 bool isInteger = LL.getValueType().isInteger();
1822 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
1823 if (Result != ISD::SETCC_INVALID &&
1824 (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
1825 return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
1830 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
1831 if (N0.getOpcode() == N1.getOpcode()) {
1832 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1833 if (Tmp.getNode()) return Tmp;
1836 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
1837 // fold (and (sra)) -> (and (srl)) when possible.
1838 if (!VT.isVector() &&
1839 SimplifyDemandedBits(SDValue(N, 0)))
1840 return SDValue(N, 0);
1841 // fold (zext_inreg (extload x)) -> (zextload x)
1842 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
1843 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1844 EVT MemVT = LN0->getMemoryVT();
1845 // If we zero all the possible extended bits, then we can turn this into
1846 // a zextload if we are running before legalize or the operation is legal.
1847 unsigned BitWidth = N1.getValueSizeInBits();
1848 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
1849 BitWidth - MemVT.getSizeInBits())) &&
1850 ((!LegalOperations && !LN0->isVolatile()) ||
1851 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
1852 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
1853 LN0->getChain(), LN0->getBasePtr(),
1855 LN0->getSrcValueOffset(), MemVT,
1856 LN0->isVolatile(), LN0->getAlignment());
1858 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
1859 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1862 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
1863 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
1865 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1866 EVT MemVT = LN0->getMemoryVT();
1867 // If we zero all the possible extended bits, then we can turn this into
1868 // a zextload if we are running before legalize or the operation is legal.
1869 unsigned BitWidth = N1.getValueSizeInBits();
1870 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
1871 BitWidth - MemVT.getSizeInBits())) &&
1872 ((!LegalOperations && !LN0->isVolatile()) ||
1873 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
1874 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
1876 LN0->getBasePtr(), LN0->getSrcValue(),
1877 LN0->getSrcValueOffset(), MemVT,
1878 LN0->isVolatile(), LN0->getAlignment());
1880 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
1881 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1885 // fold (and (load x), 255) -> (zextload x, i8)
1886 // fold (and (extload x, i16), 255) -> (zextload x, i8)
1887 if (N1C && N0.getOpcode() == ISD::LOAD) {
1888 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1889 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
1890 LN0->isUnindexed() && N0.hasOneUse() &&
1891 // Do not change the width of a volatile load.
1892 !LN0->isVolatile()) {
1893 EVT ExtVT = MVT::Other;
1894 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
1895 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue()))
1896 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
1898 EVT LoadedVT = LN0->getMemoryVT();
1900 // Do not generate loads of non-round integer types since these can
1901 // be expensive (and would be wrong if the type is not byte sized).
1902 if (ExtVT != MVT::Other && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
1903 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
1904 EVT PtrType = N0.getOperand(1).getValueType();
1906 // For big endian targets, we need to add an offset to the pointer to
1907 // load the correct bytes. For little endian systems, we merely need to
1908 // read fewer bytes from the same pointer.
1909 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
1910 unsigned EVTStoreBytes = ExtVT.getStoreSize();
1911 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
1912 unsigned Alignment = LN0->getAlignment();
1913 SDValue NewPtr = LN0->getBasePtr();
1915 if (TLI.isBigEndian()) {
1916 NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(), PtrType,
1917 NewPtr, DAG.getConstant(PtrOff, PtrType));
1918 Alignment = MinAlign(Alignment, PtrOff);
1921 AddToWorkList(NewPtr.getNode());
1923 DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), VT, LN0->getChain(),
1924 NewPtr, LN0->getSrcValue(), LN0->getSrcValueOffset(),
1925 ExtVT, LN0->isVolatile(), Alignment);
1927 CombineTo(N0.getNode(), Load, Load.getValue(1));
1928 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1936 SDValue DAGCombiner::visitOR(SDNode *N) {
1937 SDValue N0 = N->getOperand(0);
1938 SDValue N1 = N->getOperand(1);
1939 SDValue LL, LR, RL, RR, CC0, CC1;
1940 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1941 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1942 EVT VT = N1.getValueType();
1945 if (VT.isVector()) {
1946 SDValue FoldedVOp = SimplifyVBinOp(N);
1947 if (FoldedVOp.getNode()) return FoldedVOp;
1950 // fold (or x, undef) -> -1
1951 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) {
1952 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
1953 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
1955 // fold (or c1, c2) -> c1|c2
1957 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
1958 // canonicalize constant to RHS
1960 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N1, N0);
1961 // fold (or x, 0) -> x
1962 if (N1C && N1C->isNullValue())
1964 // fold (or x, -1) -> -1
1965 if (N1C && N1C->isAllOnesValue())
1967 // fold (or x, c) -> c iff (x & ~c) == 0
1968 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
1971 SDValue ROR = ReassociateOps(ISD::OR, N->getDebugLoc(), N0, N1);
1972 if (ROR.getNode() != 0)
1974 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
1975 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
1976 isa<ConstantSDNode>(N0.getOperand(1))) {
1977 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
1978 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
1979 DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
1980 N0.getOperand(0), N1),
1981 DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
1983 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
1984 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1985 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1986 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1988 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1989 LL.getValueType().isInteger()) {
1990 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
1991 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
1992 if (cast<ConstantSDNode>(LR)->isNullValue() &&
1993 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
1994 SDValue ORNode = DAG.getNode(ISD::OR, LR.getDebugLoc(),
1995 LR.getValueType(), LL, RL);
1996 AddToWorkList(ORNode.getNode());
1997 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
1999 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
2000 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
2001 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2002 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
2003 SDValue ANDNode = DAG.getNode(ISD::AND, LR.getDebugLoc(),
2004 LR.getValueType(), LL, RL);
2005 AddToWorkList(ANDNode.getNode());
2006 return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
2009 // canonicalize equivalent to ll == rl
2010 if (LL == RR && LR == RL) {
2011 Op1 = ISD::getSetCCSwappedOperands(Op1);
2014 if (LL == RL && LR == RR) {
2015 bool isInteger = LL.getValueType().isInteger();
2016 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
2017 if (Result != ISD::SETCC_INVALID &&
2018 (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
2019 return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
2024 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
2025 if (N0.getOpcode() == N1.getOpcode()) {
2026 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2027 if (Tmp.getNode()) return Tmp;
2030 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
2031 if (N0.getOpcode() == ISD::AND &&
2032 N1.getOpcode() == ISD::AND &&
2033 N0.getOperand(1).getOpcode() == ISD::Constant &&
2034 N1.getOperand(1).getOpcode() == ISD::Constant &&
2035 // Don't increase # computations.
2036 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
2037 // We can only do this xform if we know that bits from X that are set in C2
2038 // but not in C1 are already zero. Likewise for Y.
2039 const APInt &LHSMask =
2040 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
2041 const APInt &RHSMask =
2042 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
2044 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
2045 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
2046 SDValue X = DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
2047 N0.getOperand(0), N1.getOperand(0));
2048 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, X,
2049 DAG.getConstant(LHSMask | RHSMask, VT));
2053 // See if this is some rotate idiom.
2054 if (SDNode *Rot = MatchRotate(N0, N1, N->getDebugLoc()))
2055 return SDValue(Rot, 0);
2060 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
2061 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
2062 if (Op.getOpcode() == ISD::AND) {
2063 if (isa<ConstantSDNode>(Op.getOperand(1))) {
2064 Mask = Op.getOperand(1);
2065 Op = Op.getOperand(0);
2071 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
2079 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
2080 // idioms for rotate, and if the target supports rotation instructions, generate
2082 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL) {
2083 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
2084 EVT VT = LHS.getValueType();
2085 if (!TLI.isTypeLegal(VT)) return 0;
2087 // The target must have at least one rotate flavor.
2088 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
2089 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
2090 if (!HasROTL && !HasROTR) return 0;
2092 // Match "(X shl/srl V1) & V2" where V2 may not be present.
2093 SDValue LHSShift; // The shift.
2094 SDValue LHSMask; // AND value if any.
2095 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
2096 return 0; // Not part of a rotate.
2098 SDValue RHSShift; // The shift.
2099 SDValue RHSMask; // AND value if any.
2100 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
2101 return 0; // Not part of a rotate.
2103 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
2104 return 0; // Not shifting the same value.
2106 if (LHSShift.getOpcode() == RHSShift.getOpcode())
2107 return 0; // Shifts must disagree.
2109 // Canonicalize shl to left side in a shl/srl pair.
2110 if (RHSShift.getOpcode() == ISD::SHL) {
2111 std::swap(LHS, RHS);
2112 std::swap(LHSShift, RHSShift);
2113 std::swap(LHSMask , RHSMask );
2116 unsigned OpSizeInBits = VT.getSizeInBits();
2117 SDValue LHSShiftArg = LHSShift.getOperand(0);
2118 SDValue LHSShiftAmt = LHSShift.getOperand(1);
2119 SDValue RHSShiftAmt = RHSShift.getOperand(1);
2121 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
2122 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
2123 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
2124 RHSShiftAmt.getOpcode() == ISD::Constant) {
2125 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
2126 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
2127 if ((LShVal + RShVal) != OpSizeInBits)
2132 Rot = DAG.getNode(ISD::ROTL, DL, VT, LHSShiftArg, LHSShiftAmt);
2134 Rot = DAG.getNode(ISD::ROTR, DL, VT, LHSShiftArg, RHSShiftAmt);
2136 // If there is an AND of either shifted operand, apply it to the result.
2137 if (LHSMask.getNode() || RHSMask.getNode()) {
2138 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
2140 if (LHSMask.getNode()) {
2141 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
2142 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
2144 if (RHSMask.getNode()) {
2145 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
2146 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
2149 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
2152 return Rot.getNode();
2155 // If there is a mask here, and we have a variable shift, we can't be sure
2156 // that we're masking out the right stuff.
2157 if (LHSMask.getNode() || RHSMask.getNode())
2160 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
2161 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
2162 if (RHSShiftAmt.getOpcode() == ISD::SUB &&
2163 LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
2164 if (ConstantSDNode *SUBC =
2165 dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
2166 if (SUBC->getAPIntValue() == OpSizeInBits) {
2168 return DAG.getNode(ISD::ROTL, DL, VT,
2169 LHSShiftArg, LHSShiftAmt).getNode();
2171 return DAG.getNode(ISD::ROTR, DL, VT,
2172 LHSShiftArg, RHSShiftAmt).getNode();
2177 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
2178 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
2179 if (LHSShiftAmt.getOpcode() == ISD::SUB &&
2180 RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
2181 if (ConstantSDNode *SUBC =
2182 dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
2183 if (SUBC->getAPIntValue() == OpSizeInBits) {
2185 return DAG.getNode(ISD::ROTR, DL, VT,
2186 LHSShiftArg, RHSShiftAmt).getNode();
2188 return DAG.getNode(ISD::ROTL, DL, VT,
2189 LHSShiftArg, LHSShiftAmt).getNode();
2194 // Look for sign/zext/any-extended or truncate cases:
2195 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2196 || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2197 || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
2198 || LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
2199 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2200 || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2201 || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
2202 || RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
2203 SDValue LExtOp0 = LHSShiftAmt.getOperand(0);
2204 SDValue RExtOp0 = RHSShiftAmt.getOperand(0);
2205 if (RExtOp0.getOpcode() == ISD::SUB &&
2206 RExtOp0.getOperand(1) == LExtOp0) {
2207 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2209 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2210 // (rotr x, (sub 32, y))
2211 if (ConstantSDNode *SUBC =
2212 dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
2213 if (SUBC->getAPIntValue() == OpSizeInBits) {
2214 return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
2216 HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
2219 } else if (LExtOp0.getOpcode() == ISD::SUB &&
2220 RExtOp0 == LExtOp0.getOperand(1)) {
2221 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
2223 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
2224 // (rotl x, (sub 32, y))
2225 if (ConstantSDNode *SUBC =
2226 dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
2227 if (SUBC->getAPIntValue() == OpSizeInBits) {
2228 return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT,
2230 HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
2239 SDValue DAGCombiner::visitXOR(SDNode *N) {
2240 SDValue N0 = N->getOperand(0);
2241 SDValue N1 = N->getOperand(1);
2242 SDValue LHS, RHS, CC;
2243 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2244 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2245 EVT VT = N0.getValueType();
2248 if (VT.isVector()) {
2249 SDValue FoldedVOp = SimplifyVBinOp(N);
2250 if (FoldedVOp.getNode()) return FoldedVOp;
2253 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
2254 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
2255 return DAG.getConstant(0, VT);
2256 // fold (xor x, undef) -> undef
2257 if (N0.getOpcode() == ISD::UNDEF)
2259 if (N1.getOpcode() == ISD::UNDEF)
2261 // fold (xor c1, c2) -> c1^c2
2263 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
2264 // canonicalize constant to RHS
2266 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
2267 // fold (xor x, 0) -> x
2268 if (N1C && N1C->isNullValue())
2271 SDValue RXOR = ReassociateOps(ISD::XOR, N->getDebugLoc(), N0, N1);
2272 if (RXOR.getNode() != 0)
2275 // fold !(x cc y) -> (x !cc y)
2276 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
2277 bool isInt = LHS.getValueType().isInteger();
2278 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
2281 if (!LegalOperations || TLI.isCondCodeLegal(NotCC, LHS.getValueType())) {
2282 switch (N0.getOpcode()) {
2284 llvm_unreachable("Unhandled SetCC Equivalent!");
2286 return DAG.getSetCC(N->getDebugLoc(), VT, LHS, RHS, NotCC);
2287 case ISD::SELECT_CC:
2288 return DAG.getSelectCC(N->getDebugLoc(), LHS, RHS, N0.getOperand(2),
2289 N0.getOperand(3), NotCC);
2294 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
2295 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
2296 N0.getNode()->hasOneUse() &&
2297 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
2298 SDValue V = N0.getOperand(0);
2299 V = DAG.getNode(ISD::XOR, N0.getDebugLoc(), V.getValueType(), V,
2300 DAG.getConstant(1, V.getValueType()));
2301 AddToWorkList(V.getNode());
2302 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, V);
2305 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
2306 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
2307 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2308 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2309 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
2310 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2311 LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
2312 RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
2313 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
2314 return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
2317 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
2318 if (N1C && N1C->isAllOnesValue() &&
2319 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2320 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2321 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
2322 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2323 LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
2324 RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
2325 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
2326 return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
2329 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
2330 if (N1C && N0.getOpcode() == ISD::XOR) {
2331 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
2332 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2334 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(1),
2335 DAG.getConstant(N1C->getAPIntValue() ^
2336 N00C->getAPIntValue(), VT));
2338 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(0),
2339 DAG.getConstant(N1C->getAPIntValue() ^
2340 N01C->getAPIntValue(), VT));
2342 // fold (xor x, x) -> 0
2344 if (!VT.isVector()) {
2345 return DAG.getConstant(0, VT);
2346 } else if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)){
2347 // Produce a vector of zeros.
2348 SDValue El = DAG.getConstant(0, VT.getVectorElementType());
2349 std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
2350 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
2351 &Ops[0], Ops.size());
2355 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
2356 if (N0.getOpcode() == N1.getOpcode()) {
2357 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2358 if (Tmp.getNode()) return Tmp;
2361 // Simplify the expression using non-local knowledge.
2362 if (!VT.isVector() &&
2363 SimplifyDemandedBits(SDValue(N, 0)))
2364 return SDValue(N, 0);
2369 /// visitShiftByConstant - Handle transforms common to the three shifts, when
2370 /// the shift amount is a constant.
2371 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
2372 SDNode *LHS = N->getOperand(0).getNode();
2373 if (!LHS->hasOneUse()) return SDValue();
2375 // We want to pull some binops through shifts, so that we have (and (shift))
2376 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
2377 // thing happens with address calculations, so it's important to canonicalize
2379 bool HighBitSet = false; // Can we transform this if the high bit is set?
2381 switch (LHS->getOpcode()) {
2382 default: return SDValue();
2385 HighBitSet = false; // We can only transform sra if the high bit is clear.
2388 HighBitSet = true; // We can only transform sra if the high bit is set.
2391 if (N->getOpcode() != ISD::SHL)
2392 return SDValue(); // only shl(add) not sr[al](add).
2393 HighBitSet = false; // We can only transform sra if the high bit is clear.
2397 // We require the RHS of the binop to be a constant as well.
2398 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
2399 if (!BinOpCst) return SDValue();
2401 // FIXME: disable this unless the input to the binop is a shift by a constant.
2402 // If it is not a shift, it pessimizes some common cases like:
2404 // void foo(int *X, int i) { X[i & 1235] = 1; }
2405 // int bar(int *X, int i) { return X[i & 255]; }
2406 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
2407 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
2408 BinOpLHSVal->getOpcode() != ISD::SRA &&
2409 BinOpLHSVal->getOpcode() != ISD::SRL) ||
2410 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
2413 EVT VT = N->getValueType(0);
2415 // If this is a signed shift right, and the high bit is modified by the
2416 // logical operation, do not perform the transformation. The highBitSet
2417 // boolean indicates the value of the high bit of the constant which would
2418 // cause it to be modified for this operation.
2419 if (N->getOpcode() == ISD::SRA) {
2420 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
2421 if (BinOpRHSSignSet != HighBitSet)
2425 // Fold the constants, shifting the binop RHS by the shift amount.
2426 SDValue NewRHS = DAG.getNode(N->getOpcode(), LHS->getOperand(1).getDebugLoc(),
2428 LHS->getOperand(1), N->getOperand(1));
2430 // Create the new shift.
2431 SDValue NewShift = DAG.getNode(N->getOpcode(), LHS->getOperand(0).getDebugLoc(),
2432 VT, LHS->getOperand(0), N->getOperand(1));
2434 // Create the new binop.
2435 return DAG.getNode(LHS->getOpcode(), N->getDebugLoc(), VT, NewShift, NewRHS);
2438 SDValue DAGCombiner::visitSHL(SDNode *N) {
2439 SDValue N0 = N->getOperand(0);
2440 SDValue N1 = N->getOperand(1);
2441 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2442 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2443 EVT VT = N0.getValueType();
2444 unsigned OpSizeInBits = VT.getSizeInBits();
2446 // fold (shl c1, c2) -> c1<<c2
2448 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
2449 // fold (shl 0, x) -> 0
2450 if (N0C && N0C->isNullValue())
2452 // fold (shl x, c >= size(x)) -> undef
2453 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
2454 return DAG.getUNDEF(VT);
2455 // fold (shl x, 0) -> x
2456 if (N1C && N1C->isNullValue())
2458 // if (shl x, c) is known to be zero, return 0
2459 if (DAG.MaskedValueIsZero(SDValue(N, 0),
2460 APInt::getAllOnesValue(VT.getSizeInBits())))
2461 return DAG.getConstant(0, VT);
2462 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
2463 if (N1.getOpcode() == ISD::TRUNCATE &&
2464 N1.getOperand(0).getOpcode() == ISD::AND &&
2465 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
2466 SDValue N101 = N1.getOperand(0).getOperand(1);
2467 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
2468 EVT TruncVT = N1.getValueType();
2469 SDValue N100 = N1.getOperand(0).getOperand(0);
2470 APInt TruncC = N101C->getAPIntValue();
2471 TruncC.trunc(TruncVT.getSizeInBits());
2472 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
2473 DAG.getNode(ISD::AND, N->getDebugLoc(), TruncVT,
2474 DAG.getNode(ISD::TRUNCATE,
2477 DAG.getConstant(TruncC, TruncVT)));
2481 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
2482 return SDValue(N, 0);
2484 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
2485 if (N1C && N0.getOpcode() == ISD::SHL &&
2486 N0.getOperand(1).getOpcode() == ISD::Constant) {
2487 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
2488 uint64_t c2 = N1C->getZExtValue();
2489 if (c1 + c2 > OpSizeInBits)
2490 return DAG.getConstant(0, VT);
2491 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
2492 DAG.getConstant(c1 + c2, N1.getValueType()));
2494 // fold (shl (srl x, c1), c2) -> (shl (and x, (shl -1, c1)), (sub c2, c1)) or
2495 // (srl (and x, (shl -1, c1)), (sub c1, c2))
2496 if (N1C && N0.getOpcode() == ISD::SRL &&
2497 N0.getOperand(1).getOpcode() == ISD::Constant) {
2498 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
2499 if (c1 < VT.getSizeInBits()) {
2500 uint64_t c2 = N1C->getZExtValue();
2501 SDValue HiBitsMask =
2502 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
2503 VT.getSizeInBits() - c1),
2505 SDValue Mask = DAG.getNode(ISD::AND, N0.getDebugLoc(), VT,
2509 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, Mask,
2510 DAG.getConstant(c2-c1, N1.getValueType()));
2512 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, Mask,
2513 DAG.getConstant(c1-c2, N1.getValueType()));
2516 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
2517 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
2518 SDValue HiBitsMask =
2519 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
2520 VT.getSizeInBits() -
2521 N1C->getZExtValue()),
2523 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
2527 return N1C ? visitShiftByConstant(N, N1C->getZExtValue()) : SDValue();
2530 SDValue DAGCombiner::visitSRA(SDNode *N) {
2531 SDValue N0 = N->getOperand(0);
2532 SDValue N1 = N->getOperand(1);
2533 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2534 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2535 EVT VT = N0.getValueType();
2537 // fold (sra c1, c2) -> (sra c1, c2)
2539 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
2540 // fold (sra 0, x) -> 0
2541 if (N0C && N0C->isNullValue())
2543 // fold (sra -1, x) -> -1
2544 if (N0C && N0C->isAllOnesValue())
2546 // fold (sra x, (setge c, size(x))) -> undef
2547 if (N1C && N1C->getZExtValue() >= VT.getSizeInBits())
2548 return DAG.getUNDEF(VT);
2549 // fold (sra x, 0) -> x
2550 if (N1C && N1C->isNullValue())
2552 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
2554 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
2555 unsigned LowBits = VT.getSizeInBits() - (unsigned)N1C->getZExtValue();
2556 EVT EVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
2557 if ((!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, EVT)))
2558 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
2559 N0.getOperand(0), DAG.getValueType(EVT));
2562 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
2563 if (N1C && N0.getOpcode() == ISD::SRA) {
2564 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2565 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
2566 if (Sum >= VT.getSizeInBits()) Sum = VT.getSizeInBits()-1;
2567 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0.getOperand(0),
2568 DAG.getConstant(Sum, N1C->getValueType(0)));
2572 // fold (sra (shl X, m), (sub result_size, n))
2573 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
2574 // result_size - n != m.
2575 // If truncate is free for the target sext(shl) is likely to result in better
2577 if (N0.getOpcode() == ISD::SHL) {
2578 // Get the two constanst of the shifts, CN0 = m, CN = n.
2579 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2581 // Determine what the truncate's result bitsize and type would be.
2582 unsigned VTValSize = VT.getSizeInBits();
2584 EVT::getIntegerVT(*DAG.getContext(), VTValSize - N1C->getZExtValue());
2585 // Determine the residual right-shift amount.
2586 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
2588 // If the shift is not a no-op (in which case this should be just a sign
2589 // extend already), the truncated to type is legal, sign_extend is legal
2590 // on that type, and the the truncate to that type is both legal and free,
2591 // perform the transform.
2592 if ((ShiftAmt > 0) &&
2593 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
2594 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
2595 TLI.isTruncateFree(VT, TruncVT)) {
2597 SDValue Amt = DAG.getConstant(ShiftAmt, getShiftAmountTy());
2598 SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT,
2599 N0.getOperand(0), Amt);
2600 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), TruncVT,
2602 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(),
2603 N->getValueType(0), Trunc);
2608 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
2609 if (N1.getOpcode() == ISD::TRUNCATE &&
2610 N1.getOperand(0).getOpcode() == ISD::AND &&
2611 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
2612 SDValue N101 = N1.getOperand(0).getOperand(1);
2613 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
2614 EVT TruncVT = N1.getValueType();
2615 SDValue N100 = N1.getOperand(0).getOperand(0);
2616 APInt TruncC = N101C->getAPIntValue();
2617 TruncC.trunc(TruncVT.getSizeInBits());
2618 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
2619 DAG.getNode(ISD::AND, N->getDebugLoc(),
2621 DAG.getNode(ISD::TRUNCATE,
2624 DAG.getConstant(TruncC, TruncVT)));
2628 // Simplify, based on bits shifted out of the LHS.
2629 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
2630 return SDValue(N, 0);
2633 // If the sign bit is known to be zero, switch this to a SRL.
2634 if (DAG.SignBitIsZero(N0))
2635 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, N1);
2637 return N1C ? visitShiftByConstant(N, N1C->getZExtValue()) : SDValue();
2640 SDValue DAGCombiner::visitSRL(SDNode *N) {
2641 SDValue N0 = N->getOperand(0);
2642 SDValue N1 = N->getOperand(1);
2643 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2644 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2645 EVT VT = N0.getValueType();
2646 unsigned OpSizeInBits = VT.getSizeInBits();
2648 // fold (srl c1, c2) -> c1 >>u c2
2650 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
2651 // fold (srl 0, x) -> 0
2652 if (N0C && N0C->isNullValue())
2654 // fold (srl x, c >= size(x)) -> undef
2655 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
2656 return DAG.getUNDEF(VT);
2657 // fold (srl x, 0) -> x
2658 if (N1C && N1C->isNullValue())
2660 // if (srl x, c) is known to be zero, return 0
2661 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2662 APInt::getAllOnesValue(OpSizeInBits)))
2663 return DAG.getConstant(0, VT);
2665 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
2666 if (N1C && N0.getOpcode() == ISD::SRL &&
2667 N0.getOperand(1).getOpcode() == ISD::Constant) {
2668 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
2669 uint64_t c2 = N1C->getZExtValue();
2670 if (c1 + c2 > OpSizeInBits)
2671 return DAG.getConstant(0, VT);
2672 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
2673 DAG.getConstant(c1 + c2, N1.getValueType()));
2676 // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
2677 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2678 // Shifting in all undef bits?
2679 EVT SmallVT = N0.getOperand(0).getValueType();
2680 if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
2681 return DAG.getUNDEF(VT);
2683 SDValue SmallShift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), SmallVT,
2684 N0.getOperand(0), N1);
2685 AddToWorkList(SmallShift.getNode());
2686 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, SmallShift);
2689 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
2690 // bit, which is unmodified by sra.
2691 if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
2692 if (N0.getOpcode() == ISD::SRA)
2693 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0), N1);
2696 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
2697 if (N1C && N0.getOpcode() == ISD::CTLZ &&
2698 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
2699 APInt KnownZero, KnownOne;
2700 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
2701 DAG.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
2703 // If any of the input bits are KnownOne, then the input couldn't be all
2704 // zeros, thus the result of the srl will always be zero.
2705 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
2707 // If all of the bits input the to ctlz node are known to be zero, then
2708 // the result of the ctlz is "32" and the result of the shift is one.
2709 APInt UnknownBits = ~KnownZero & Mask;
2710 if (UnknownBits == 0) return DAG.getConstant(1, VT);
2712 // Otherwise, check to see if there is exactly one bit input to the ctlz.
2713 if ((UnknownBits & (UnknownBits - 1)) == 0) {
2714 // Okay, we know that only that the single bit specified by UnknownBits
2715 // could be set on input to the CTLZ node. If this bit is set, the SRL
2716 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
2717 // to an SRL/XOR pair, which is likely to simplify more.
2718 unsigned ShAmt = UnknownBits.countTrailingZeros();
2719 SDValue Op = N0.getOperand(0);
2722 Op = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT, Op,
2723 DAG.getConstant(ShAmt, getShiftAmountTy()));
2724 AddToWorkList(Op.getNode());
2727 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
2728 Op, DAG.getConstant(1, VT));
2732 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
2733 if (N1.getOpcode() == ISD::TRUNCATE &&
2734 N1.getOperand(0).getOpcode() == ISD::AND &&
2735 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
2736 SDValue N101 = N1.getOperand(0).getOperand(1);
2737 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
2738 EVT TruncVT = N1.getValueType();
2739 SDValue N100 = N1.getOperand(0).getOperand(0);
2740 APInt TruncC = N101C->getAPIntValue();
2741 TruncC.trunc(TruncVT.getSizeInBits());
2742 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
2743 DAG.getNode(ISD::AND, N->getDebugLoc(),
2745 DAG.getNode(ISD::TRUNCATE,
2748 DAG.getConstant(TruncC, TruncVT)));
2752 // fold operands of srl based on knowledge that the low bits are not
2754 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
2755 return SDValue(N, 0);
2757 return N1C ? visitShiftByConstant(N, N1C->getZExtValue()) : SDValue();
2760 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
2761 SDValue N0 = N->getOperand(0);
2762 EVT VT = N->getValueType(0);
2764 // fold (ctlz c1) -> c2
2765 if (isa<ConstantSDNode>(N0))
2766 return DAG.getNode(ISD::CTLZ, N->getDebugLoc(), VT, N0);
2770 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
2771 SDValue N0 = N->getOperand(0);
2772 EVT VT = N->getValueType(0);
2774 // fold (cttz c1) -> c2
2775 if (isa<ConstantSDNode>(N0))
2776 return DAG.getNode(ISD::CTTZ, N->getDebugLoc(), VT, N0);
2780 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
2781 SDValue N0 = N->getOperand(0);
2782 EVT VT = N->getValueType(0);
2784 // fold (ctpop c1) -> c2
2785 if (isa<ConstantSDNode>(N0))
2786 return DAG.getNode(ISD::CTPOP, N->getDebugLoc(), VT, N0);
2790 SDValue DAGCombiner::visitSELECT(SDNode *N) {
2791 SDValue N0 = N->getOperand(0);
2792 SDValue N1 = N->getOperand(1);
2793 SDValue N2 = N->getOperand(2);
2794 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2795 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2796 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
2797 EVT VT = N->getValueType(0);
2798 EVT VT0 = N0.getValueType();
2800 // fold (select C, X, X) -> X
2803 // fold (select true, X, Y) -> X
2804 if (N0C && !N0C->isNullValue())
2806 // fold (select false, X, Y) -> Y
2807 if (N0C && N0C->isNullValue())
2809 // fold (select C, 1, X) -> (or C, X)
2810 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
2811 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
2812 // fold (select C, 0, 1) -> (xor C, 1)
2813 if (VT.isInteger() &&
2816 TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent)) &&
2817 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
2820 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT0,
2821 N0, DAG.getConstant(1, VT0));
2822 XORNode = DAG.getNode(ISD::XOR, N0.getDebugLoc(), VT0,
2823 N0, DAG.getConstant(1, VT0));
2824 AddToWorkList(XORNode.getNode());
2826 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, XORNode);
2827 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, XORNode);
2829 // fold (select C, 0, X) -> (and (not C), X)
2830 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
2831 SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
2832 AddToWorkList(NOTNode.getNode());
2833 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, NOTNode, N2);
2835 // fold (select C, X, 1) -> (or (not C), X)
2836 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
2837 SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
2838 AddToWorkList(NOTNode.getNode());
2839 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, NOTNode, N1);
2841 // fold (select C, X, 0) -> (and C, X)
2842 if (VT == MVT::i1 && N2C && N2C->isNullValue())
2843 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
2844 // fold (select X, X, Y) -> (or X, Y)
2845 // fold (select X, 1, Y) -> (or X, Y)
2846 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
2847 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
2848 // fold (select X, Y, X) -> (and X, Y)
2849 // fold (select X, Y, 0) -> (and X, Y)
2850 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
2851 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
2853 // If we can fold this based on the true/false value, do so.
2854 if (SimplifySelectOps(N, N1, N2))
2855 return SDValue(N, 0); // Don't revisit N.
2857 // fold selects based on a setcc into other things, such as min/max/abs
2858 if (N0.getOpcode() == ISD::SETCC) {
2860 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
2861 // having to say they don't support SELECT_CC on every type the DAG knows
2862 // about, since there is no way to mark an opcode illegal at all value types
2863 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
2864 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
2865 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT,
2866 N0.getOperand(0), N0.getOperand(1),
2867 N1, N2, N0.getOperand(2));
2868 return SimplifySelect(N->getDebugLoc(), N0, N1, N2);
2874 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
2875 SDValue N0 = N->getOperand(0);
2876 SDValue N1 = N->getOperand(1);
2877 SDValue N2 = N->getOperand(2);
2878 SDValue N3 = N->getOperand(3);
2879 SDValue N4 = N->getOperand(4);
2880 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
2882 // fold select_cc lhs, rhs, x, x, cc -> x
2886 // Determine if the condition we're dealing with is constant
2887 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
2888 N0, N1, CC, N->getDebugLoc(), false);
2889 if (SCC.getNode()) AddToWorkList(SCC.getNode());
2891 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
2892 if (!SCCC->isNullValue())
2893 return N2; // cond always true -> true val
2895 return N3; // cond always false -> false val
2898 // Fold to a simpler select_cc
2899 if (SCC.getNode() && SCC.getOpcode() == ISD::SETCC)
2900 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), N2.getValueType(),
2901 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
2904 // If we can fold this based on the true/false value, do so.
2905 if (SimplifySelectOps(N, N2, N3))
2906 return SDValue(N, 0); // Don't revisit N.
2908 // fold select_cc into other things, such as min/max/abs
2909 return SimplifySelectCC(N->getDebugLoc(), N0, N1, N2, N3, CC);
2912 SDValue DAGCombiner::visitSETCC(SDNode *N) {
2913 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
2914 cast<CondCodeSDNode>(N->getOperand(2))->get(),
2918 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
2919 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
2920 // transformation. Returns true if extension are possible and the above
2921 // mentioned transformation is profitable.
2922 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
2924 SmallVector<SDNode*, 4> &ExtendNodes,
2925 const TargetLowering &TLI) {
2926 bool HasCopyToRegUses = false;
2927 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
2928 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
2929 UE = N0.getNode()->use_end();
2934 if (UI.getUse().getResNo() != N0.getResNo())
2936 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
2937 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
2938 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
2939 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
2940 // Sign bits will be lost after a zext.
2943 for (unsigned i = 0; i != 2; ++i) {
2944 SDValue UseOp = User->getOperand(i);
2947 if (!isa<ConstantSDNode>(UseOp))
2952 ExtendNodes.push_back(User);
2955 // If truncates aren't free and there are users we can't
2956 // extend, it isn't worthwhile.
2959 // Remember if this value is live-out.
2960 if (User->getOpcode() == ISD::CopyToReg)
2961 HasCopyToRegUses = true;
2964 if (HasCopyToRegUses) {
2965 bool BothLiveOut = false;
2966 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
2968 SDUse &Use = UI.getUse();
2969 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
2975 // Both unextended and extended values are live out. There had better be
2976 // good a reason for the transformation.
2977 return ExtendNodes.size();
2982 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
2983 SDValue N0 = N->getOperand(0);
2984 EVT VT = N->getValueType(0);
2986 // fold (sext c1) -> c1
2987 if (isa<ConstantSDNode>(N0))
2988 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N0);
2990 // fold (sext (sext x)) -> (sext x)
2991 // fold (sext (aext x)) -> (sext x)
2992 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2993 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT,
2996 if (N0.getOpcode() == ISD::TRUNCATE) {
2997 // fold (sext (truncate (load x))) -> (sext (smaller load x))
2998 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
2999 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3000 if (NarrowLoad.getNode()) {
3001 if (NarrowLoad.getNode() != N0.getNode())
3002 CombineTo(N0.getNode(), NarrowLoad);
3003 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3006 // See if the value being truncated is already sign extended. If so, just
3007 // eliminate the trunc/sext pair.
3008 SDValue Op = N0.getOperand(0);
3009 unsigned OpBits = Op.getValueType().getSizeInBits();
3010 unsigned MidBits = N0.getValueType().getSizeInBits();
3011 unsigned DestBits = VT.getSizeInBits();
3012 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
3014 if (OpBits == DestBits) {
3015 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
3016 // bits, it is already ready.
3017 if (NumSignBits > DestBits-MidBits)
3019 } else if (OpBits < DestBits) {
3020 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
3021 // bits, just sext from i32.
3022 if (NumSignBits > OpBits-MidBits)
3023 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, Op);
3025 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
3026 // bits, just truncate to i32.
3027 if (NumSignBits > OpBits-MidBits)
3028 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
3031 // fold (sext (truncate x)) -> (sextinreg x).
3032 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
3033 N0.getValueType())) {
3034 if (Op.getValueType().bitsLT(VT))
3035 Op = DAG.getNode(ISD::ANY_EXTEND, N0.getDebugLoc(), VT, Op);
3036 else if (Op.getValueType().bitsGT(VT))
3037 Op = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), VT, Op);
3038 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, Op,
3039 DAG.getValueType(N0.getValueType()));
3043 // fold (sext (load x)) -> (sext (truncate (sextload x)))
3044 if (ISD::isNON_EXTLoad(N0.getNode()) &&
3045 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3046 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
3047 bool DoXform = true;
3048 SmallVector<SDNode*, 4> SetCCs;
3049 if (!N0.hasOneUse())
3050 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
3052 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3053 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
3055 LN0->getBasePtr(), LN0->getSrcValue(),
3056 LN0->getSrcValueOffset(),
3058 LN0->isVolatile(), LN0->getAlignment());
3059 CombineTo(N, ExtLoad);
3060 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3061 N0.getValueType(), ExtLoad);
3062 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
3064 // Extend SetCC uses if necessary.
3065 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
3066 SDNode *SetCC = SetCCs[i];
3067 SmallVector<SDValue, 4> Ops;
3069 for (unsigned j = 0; j != 2; ++j) {
3070 SDValue SOp = SetCC->getOperand(j);
3072 Ops.push_back(ExtLoad);
3074 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND,
3075 N->getDebugLoc(), VT, SOp));
3078 Ops.push_back(SetCC->getOperand(2));
3079 CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
3080 SetCC->getValueType(0),
3081 &Ops[0], Ops.size()));
3084 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3088 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
3089 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
3090 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
3091 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
3092 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3093 EVT MemVT = LN0->getMemoryVT();
3094 if ((!LegalOperations && !LN0->isVolatile()) ||
3095 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
3096 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
3098 LN0->getBasePtr(), LN0->getSrcValue(),
3099 LN0->getSrcValueOffset(), MemVT,
3100 LN0->isVolatile(), LN0->getAlignment());
3101 CombineTo(N, ExtLoad);
3102 CombineTo(N0.getNode(),
3103 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3104 N0.getValueType(), ExtLoad),
3105 ExtLoad.getValue(1));
3106 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3110 if (N0.getOpcode() == ISD::SETCC) {
3111 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
3112 if (VT.isVector() &&
3113 // We know that the # elements of the results is the same as the
3114 // # elements of the compare (and the # elements of the compare result
3115 // for that matter). Check to see that they are the same size. If so,
3116 // we know that the element size of the sext'd result matches the
3117 // element size of the compare operands.
3118 VT.getSizeInBits() == N0.getOperand(0).getValueType().getSizeInBits() &&
3120 // Only do this before legalize for now.
3122 return DAG.getVSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
3124 cast<CondCodeSDNode>(N0.getOperand(2))->get());
3127 // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
3129 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
3131 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
3132 NegOne, DAG.getConstant(0, VT),
3133 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3134 if (SCC.getNode()) return SCC;
3139 // fold (sext x) -> (zext x) if the sign bit is known zero.
3140 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
3141 DAG.SignBitIsZero(N0))
3142 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
3147 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
3148 SDValue N0 = N->getOperand(0);
3149 EVT VT = N->getValueType(0);
3151 // fold (zext c1) -> c1
3152 if (isa<ConstantSDNode>(N0))
3153 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
3154 // fold (zext (zext x)) -> (zext x)
3155 // fold (zext (aext x)) -> (zext x)
3156 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
3157 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT,
3160 // fold (zext (truncate (load x))) -> (zext (smaller load x))
3161 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
3162 if (N0.getOpcode() == ISD::TRUNCATE) {
3163 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3164 if (NarrowLoad.getNode()) {
3165 if (NarrowLoad.getNode() != N0.getNode())
3166 CombineTo(N0.getNode(), NarrowLoad);
3167 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, NarrowLoad);
3171 // fold (zext (truncate x)) -> (and x, mask)
3172 if (N0.getOpcode() == ISD::TRUNCATE &&
3173 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
3174 SDValue Op = N0.getOperand(0);
3175 if (Op.getValueType().bitsLT(VT)) {
3176 Op = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, Op);
3177 } else if (Op.getValueType().bitsGT(VT)) {
3178 Op = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
3180 return DAG.getZeroExtendInReg(Op, N->getDebugLoc(), N0.getValueType());
3183 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
3184 // if either of the casts is not free.
3185 if (N0.getOpcode() == ISD::AND &&
3186 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
3187 N0.getOperand(1).getOpcode() == ISD::Constant &&
3188 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
3189 N0.getValueType()) ||
3190 !TLI.isZExtFree(N0.getValueType(), VT))) {
3191 SDValue X = N0.getOperand(0).getOperand(0);
3192 if (X.getValueType().bitsLT(VT)) {
3193 X = DAG.getNode(ISD::ANY_EXTEND, X.getDebugLoc(), VT, X);
3194 } else if (X.getValueType().bitsGT(VT)) {
3195 X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
3197 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3198 Mask.zext(VT.getSizeInBits());
3199 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3200 X, DAG.getConstant(Mask, VT));
3203 // fold (zext (load x)) -> (zext (truncate (zextload x)))
3204 if (ISD::isNON_EXTLoad(N0.getNode()) &&
3205 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3206 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
3207 bool DoXform = true;
3208 SmallVector<SDNode*, 4> SetCCs;
3209 if (!N0.hasOneUse())
3210 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
3212 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3213 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
3215 LN0->getBasePtr(), LN0->getSrcValue(),
3216 LN0->getSrcValueOffset(),
3218 LN0->isVolatile(), LN0->getAlignment());
3219 CombineTo(N, ExtLoad);
3220 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3221 N0.getValueType(), ExtLoad);
3222 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
3224 // Extend SetCC uses if necessary.
3225 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
3226 SDNode *SetCC = SetCCs[i];
3227 SmallVector<SDValue, 4> Ops;
3229 for (unsigned j = 0; j != 2; ++j) {
3230 SDValue SOp = SetCC->getOperand(j);
3232 Ops.push_back(ExtLoad);
3234 Ops.push_back(DAG.getNode(ISD::ZERO_EXTEND,
3235 N->getDebugLoc(), VT, SOp));
3238 Ops.push_back(SetCC->getOperand(2));
3239 CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
3240 SetCC->getValueType(0),
3241 &Ops[0], Ops.size()));
3244 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3248 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
3249 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
3250 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
3251 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
3252 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3253 EVT MemVT = LN0->getMemoryVT();
3254 if ((!LegalOperations && !LN0->isVolatile()) ||
3255 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
3256 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
3258 LN0->getBasePtr(), LN0->getSrcValue(),
3259 LN0->getSrcValueOffset(), MemVT,
3260 LN0->isVolatile(), LN0->getAlignment());
3261 CombineTo(N, ExtLoad);
3262 CombineTo(N0.getNode(),
3263 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), N0.getValueType(),
3265 ExtLoad.getValue(1));
3266 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3270 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3271 if (N0.getOpcode() == ISD::SETCC) {
3273 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
3274 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3275 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3276 if (SCC.getNode()) return SCC;
3282 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
3283 SDValue N0 = N->getOperand(0);
3284 EVT VT = N->getValueType(0);
3286 // fold (aext c1) -> c1
3287 if (isa<ConstantSDNode>(N0))
3288 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, N0);
3289 // fold (aext (aext x)) -> (aext x)
3290 // fold (aext (zext x)) -> (zext x)
3291 // fold (aext (sext x)) -> (sext x)
3292 if (N0.getOpcode() == ISD::ANY_EXTEND ||
3293 N0.getOpcode() == ISD::ZERO_EXTEND ||
3294 N0.getOpcode() == ISD::SIGN_EXTEND)
3295 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, N0.getOperand(0));
3297 // fold (aext (truncate (load x))) -> (aext (smaller load x))
3298 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
3299 if (N0.getOpcode() == ISD::TRUNCATE) {
3300 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3301 if (NarrowLoad.getNode()) {
3302 if (NarrowLoad.getNode() != N0.getNode())
3303 CombineTo(N0.getNode(), NarrowLoad);
3304 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, NarrowLoad);
3308 // fold (aext (truncate x))
3309 if (N0.getOpcode() == ISD::TRUNCATE) {
3310 SDValue TruncOp = N0.getOperand(0);
3311 if (TruncOp.getValueType() == VT)
3312 return TruncOp; // x iff x size == zext size.
3313 if (TruncOp.getValueType().bitsGT(VT))
3314 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, TruncOp);
3315 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, TruncOp);
3318 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
3319 // if the trunc is not free.
3320 if (N0.getOpcode() == ISD::AND &&
3321 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
3322 N0.getOperand(1).getOpcode() == ISD::Constant &&
3323 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
3324 N0.getValueType())) {
3325 SDValue X = N0.getOperand(0).getOperand(0);
3326 if (X.getValueType().bitsLT(VT)) {
3327 X = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, X);
3328 } else if (X.getValueType().bitsGT(VT)) {
3329 X = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, X);
3331 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3332 Mask.zext(VT.getSizeInBits());
3333 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3334 X, DAG.getConstant(Mask, VT));
3337 // fold (aext (load x)) -> (aext (truncate (extload x)))
3338 if (ISD::isNON_EXTLoad(N0.getNode()) &&
3339 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3340 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
3341 bool DoXform = true;
3342 SmallVector<SDNode*, 4> SetCCs;
3343 if (!N0.hasOneUse())
3344 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
3346 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3347 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
3349 LN0->getBasePtr(), LN0->getSrcValue(),
3350 LN0->getSrcValueOffset(),
3352 LN0->isVolatile(), LN0->getAlignment());
3353 CombineTo(N, ExtLoad);
3354 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3355 N0.getValueType(), ExtLoad);
3356 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
3358 // Extend SetCC uses if necessary.
3359 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
3360 SDNode *SetCC = SetCCs[i];
3361 SmallVector<SDValue, 4> Ops;
3363 for (unsigned j = 0; j != 2; ++j) {
3364 SDValue SOp = SetCC->getOperand(j);
3366 Ops.push_back(ExtLoad);
3368 Ops.push_back(DAG.getNode(ISD::ANY_EXTEND,
3369 N->getDebugLoc(), VT, SOp));
3372 Ops.push_back(SetCC->getOperand(2));
3373 CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
3374 SetCC->getValueType(0),
3375 &Ops[0], Ops.size()));
3378 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3382 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
3383 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
3384 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
3385 if (N0.getOpcode() == ISD::LOAD &&
3386 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3388 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3389 EVT MemVT = LN0->getMemoryVT();
3390 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), N->getDebugLoc(),
3391 VT, LN0->getChain(), LN0->getBasePtr(),
3393 LN0->getSrcValueOffset(), MemVT,
3394 LN0->isVolatile(), LN0->getAlignment());
3395 CombineTo(N, ExtLoad);
3396 CombineTo(N0.getNode(),
3397 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3398 N0.getValueType(), ExtLoad),
3399 ExtLoad.getValue(1));
3400 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3403 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3404 if (N0.getOpcode() == ISD::SETCC) {
3406 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
3407 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3408 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3416 /// GetDemandedBits - See if the specified operand can be simplified with the
3417 /// knowledge that only the bits specified by Mask are used. If so, return the
3418 /// simpler operand, otherwise return a null SDValue.
3419 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
3420 switch (V.getOpcode()) {
3424 // If the LHS or RHS don't contribute bits to the or, drop them.
3425 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
3426 return V.getOperand(1);
3427 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
3428 return V.getOperand(0);
3431 // Only look at single-use SRLs.
3432 if (!V.getNode()->hasOneUse())
3434 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
3435 // See if we can recursively simplify the LHS.
3436 unsigned Amt = RHSC->getZExtValue();
3438 // Watch out for shift count overflow though.
3439 if (Amt >= Mask.getBitWidth()) break;
3440 APInt NewMask = Mask << Amt;
3441 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
3442 if (SimplifyLHS.getNode())
3443 return DAG.getNode(ISD::SRL, V.getDebugLoc(), V.getValueType(),
3444 SimplifyLHS, V.getOperand(1));
3450 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
3451 /// bits and then truncated to a narrower type and where N is a multiple
3452 /// of number of bits of the narrower type, transform it to a narrower load
3453 /// from address + N / num of bits of new type. If the result is to be
3454 /// extended, also fold the extension to form a extending load.
3455 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
3456 unsigned Opc = N->getOpcode();
3457 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
3458 SDValue N0 = N->getOperand(0);
3459 EVT VT = N->getValueType(0);
3462 // This transformation isn't valid for vector loads.
3466 // Special case: SIGN_EXTEND_INREG is basically truncating to EVT then
3468 if (Opc == ISD::SIGN_EXTEND_INREG) {
3469 ExtType = ISD::SEXTLOAD;
3470 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
3471 if (LegalOperations && !TLI.isLoadExtLegal(ISD::SEXTLOAD, ExtVT))
3475 unsigned EVTBits = ExtVT.getSizeInBits();
3477 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse() && ExtVT.isRound()) {
3478 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3479 ShAmt = N01->getZExtValue();
3480 // Is the shift amount a multiple of size of VT?
3481 if ((ShAmt & (EVTBits-1)) == 0) {
3482 N0 = N0.getOperand(0);
3483 // Is the load width a multiple of size of VT?
3484 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
3490 // Do not generate loads of non-round integer types since these can
3491 // be expensive (and would be wrong if the type is not byte sized).
3492 if (isa<LoadSDNode>(N0) && N0.hasOneUse() && ExtVT.isRound() &&
3493 cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits() > EVTBits &&
3494 // Do not change the width of a volatile load.
3495 !cast<LoadSDNode>(N0)->isVolatile()) {
3496 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3497 EVT PtrType = N0.getOperand(1).getValueType();
3499 // For big endian targets, we need to adjust the offset to the pointer to
3500 // load the correct bytes.
3501 if (TLI.isBigEndian()) {
3502 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
3503 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
3504 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
3507 uint64_t PtrOff = ShAmt / 8;
3508 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
3509 SDValue NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(),
3510 PtrType, LN0->getBasePtr(),
3511 DAG.getConstant(PtrOff, PtrType));
3512 AddToWorkList(NewPtr.getNode());
3514 SDValue Load = (ExtType == ISD::NON_EXTLOAD)
3515 ? DAG.getLoad(VT, N0.getDebugLoc(), LN0->getChain(), NewPtr,
3516 LN0->getSrcValue(), LN0->getSrcValueOffset() + PtrOff,
3517 LN0->isVolatile(), NewAlign)
3518 : DAG.getExtLoad(ExtType, N0.getDebugLoc(), VT, LN0->getChain(), NewPtr,
3519 LN0->getSrcValue(), LN0->getSrcValueOffset() + PtrOff,
3520 ExtVT, LN0->isVolatile(), NewAlign);
3522 // Replace the old load's chain with the new load's chain.
3523 WorkListRemover DeadNodes(*this);
3524 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1),
3527 // Return the new loaded value.
3534 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
3535 SDValue N0 = N->getOperand(0);
3536 SDValue N1 = N->getOperand(1);
3537 EVT VT = N->getValueType(0);
3538 EVT EVT = cast<VTSDNode>(N1)->getVT();
3539 unsigned VTBits = VT.getSizeInBits();
3540 unsigned EVTBits = EVT.getSizeInBits();
3542 // fold (sext_in_reg c1) -> c1
3543 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
3544 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, N0, N1);
3546 // If the input is already sign extended, just drop the extension.
3547 if (DAG.ComputeNumSignBits(N0) >= VT.getSizeInBits()-EVTBits+1)
3550 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
3551 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3552 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) {
3553 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
3554 N0.getOperand(0), N1);
3557 // fold (sext_in_reg (sext x)) -> (sext x)
3558 // fold (sext_in_reg (aext x)) -> (sext x)
3559 // if x is small enough.
3560 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
3561 SDValue N00 = N0.getOperand(0);
3562 if (N00.getValueType().getSizeInBits() < EVTBits)
3563 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N00, N1);
3566 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
3567 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
3568 return DAG.getZeroExtendInReg(N0, N->getDebugLoc(), EVT);
3570 // fold operands of sext_in_reg based on knowledge that the top bits are not
3572 if (SimplifyDemandedBits(SDValue(N, 0)))
3573 return SDValue(N, 0);
3575 // fold (sext_in_reg (load x)) -> (smaller sextload x)
3576 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
3577 SDValue NarrowLoad = ReduceLoadWidth(N);
3578 if (NarrowLoad.getNode())
3581 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
3582 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
3583 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
3584 if (N0.getOpcode() == ISD::SRL) {
3585 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
3586 if (ShAmt->getZExtValue()+EVTBits <= VT.getSizeInBits()) {
3587 // We can turn this into an SRA iff the input to the SRL is already sign
3589 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
3590 if (VT.getSizeInBits()-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
3591 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT,
3592 N0.getOperand(0), N0.getOperand(1));
3596 // fold (sext_inreg (extload x)) -> (sextload x)
3597 if (ISD::isEXTLoad(N0.getNode()) &&
3598 ISD::isUNINDEXEDLoad(N0.getNode()) &&
3599 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
3600 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3601 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
3602 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3603 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
3605 LN0->getBasePtr(), LN0->getSrcValue(),
3606 LN0->getSrcValueOffset(), EVT,
3607 LN0->isVolatile(), LN0->getAlignment());
3608 CombineTo(N, ExtLoad);
3609 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3610 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3612 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
3613 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3615 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
3616 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3617 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
3618 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3619 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
3621 LN0->getBasePtr(), LN0->getSrcValue(),
3622 LN0->getSrcValueOffset(), EVT,
3623 LN0->isVolatile(), LN0->getAlignment());
3624 CombineTo(N, ExtLoad);
3625 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3626 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3631 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
3632 SDValue N0 = N->getOperand(0);
3633 EVT VT = N->getValueType(0);
3636 if (N0.getValueType() == N->getValueType(0))
3638 // fold (truncate c1) -> c1
3639 if (isa<ConstantSDNode>(N0))
3640 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0);
3641 // fold (truncate (truncate x)) -> (truncate x)
3642 if (N0.getOpcode() == ISD::TRUNCATE)
3643 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
3644 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
3645 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::SIGN_EXTEND||
3646 N0.getOpcode() == ISD::ANY_EXTEND) {
3647 if (N0.getOperand(0).getValueType().bitsLT(VT))
3648 // if the source is smaller than the dest, we still need an extend
3649 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
3651 else if (N0.getOperand(0).getValueType().bitsGT(VT))
3652 // if the source is larger than the dest, than we just need the truncate
3653 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
3655 // if the source and dest are the same type, we can drop both the extend
3657 return N0.getOperand(0);
3660 // See if we can simplify the input to this truncate through knowledge that
3661 // only the low bits are being used. For example "trunc (or (shl x, 8), y)"
3664 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
3665 VT.getSizeInBits()));
3666 if (Shorter.getNode())
3667 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Shorter);
3669 // fold (truncate (load x)) -> (smaller load x)
3670 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
3671 return ReduceLoadWidth(N);
3674 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
3675 SDValue Elt = N->getOperand(i);
3676 if (Elt.getOpcode() != ISD::MERGE_VALUES)
3677 return Elt.getNode();
3678 return Elt.getOperand(Elt.getResNo()).getNode();
3681 /// CombineConsecutiveLoads - build_pair (load, load) -> load
3682 /// if load locations are consecutive.
3683 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
3684 assert(N->getOpcode() == ISD::BUILD_PAIR);
3686 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
3687 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
3688 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse())
3690 EVT LD1VT = LD1->getValueType(0);
3691 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3693 if (ISD::isNON_EXTLoad(LD2) &&
3695 // If both are volatile this would reduce the number of volatile loads.
3696 // If one is volatile it might be ok, but play conservative and bail out.
3697 !LD1->isVolatile() &&
3698 !LD2->isVolatile() &&
3699 TLI.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1, MFI)) {
3700 unsigned Align = LD1->getAlignment();
3701 unsigned NewAlign = TLI.getTargetData()->
3702 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
3704 if (NewAlign <= Align &&
3705 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
3706 return DAG.getLoad(VT, N->getDebugLoc(), LD1->getChain(),
3707 LD1->getBasePtr(), LD1->getSrcValue(),
3708 LD1->getSrcValueOffset(), false, Align);
3714 SDValue DAGCombiner::visitBIT_CONVERT(SDNode *N) {
3715 SDValue N0 = N->getOperand(0);
3716 EVT VT = N->getValueType(0);
3718 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
3719 // Only do this before legalize, since afterward the target may be depending
3720 // on the bitconvert.
3721 // First check to see if this is all constant.
3723 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
3725 bool isSimple = true;
3726 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
3727 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
3728 N0.getOperand(i).getOpcode() != ISD::Constant &&
3729 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
3734 EVT DestEltVT = N->getValueType(0).getVectorElementType();
3735 assert(!DestEltVT.isVector() &&
3736 "Element type of vector ValueType must not be vector!");
3738 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(N0.getNode(), DestEltVT);
3741 // If the input is a constant, let getNode fold it.
3742 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
3743 SDValue Res = DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, N0);
3744 if (Res.getNode() != N) {
3745 if (!LegalOperations ||
3746 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
3749 // Folding it resulted in an illegal node, and it's too late to
3750 // do that. Clean up the old node and forego the transformation.
3751 // Ideally this won't happen very often, because instcombine
3752 // and the earlier dagcombine runs (where illegal nodes are
3753 // permitted) should have folded most of them already.
3754 DAG.DeleteNode(Res.getNode());
3758 // (conv (conv x, t1), t2) -> (conv x, t2)
3759 if (N0.getOpcode() == ISD::BIT_CONVERT)
3760 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT,
3763 // fold (conv (load x)) -> (load (conv*)x)
3764 // If the resultant load doesn't need a higher alignment than the original!
3765 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
3766 // Do not change the width of a volatile load.
3767 !cast<LoadSDNode>(N0)->isVolatile() &&
3768 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
3769 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3770 unsigned Align = TLI.getTargetData()->
3771 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
3772 unsigned OrigAlign = LN0->getAlignment();
3774 if (Align <= OrigAlign) {
3775 SDValue Load = DAG.getLoad(VT, N->getDebugLoc(), LN0->getChain(),
3777 LN0->getSrcValue(), LN0->getSrcValueOffset(),
3778 LN0->isVolatile(), OrigAlign);
3780 CombineTo(N0.getNode(),
3781 DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(),
3782 N0.getValueType(), Load),
3788 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
3789 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
3790 // This often reduces constant pool loads.
3791 if ((N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FABS) &&
3792 N0.getNode()->hasOneUse() && VT.isInteger() && !VT.isVector()) {
3793 SDValue NewConv = DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(), VT,
3795 AddToWorkList(NewConv.getNode());
3797 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
3798 if (N0.getOpcode() == ISD::FNEG)
3799 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
3800 NewConv, DAG.getConstant(SignBit, VT));
3801 assert(N0.getOpcode() == ISD::FABS);
3802 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3803 NewConv, DAG.getConstant(~SignBit, VT));
3806 // fold (bitconvert (fcopysign cst, x)) ->
3807 // (or (and (bitconvert x), sign), (and cst, (not sign)))
3808 // Note that we don't handle (copysign x, cst) because this can always be
3809 // folded to an fneg or fabs.
3810 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
3811 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
3812 VT.isInteger() && !VT.isVector()) {
3813 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
3814 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
3815 if (TLI.isTypeLegal(IntXVT) || !LegalTypes) {
3816 SDValue X = DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(),
3817 IntXVT, N0.getOperand(1));
3818 AddToWorkList(X.getNode());
3820 // If X has a different width than the result/lhs, sext it or truncate it.
3821 unsigned VTWidth = VT.getSizeInBits();
3822 if (OrigXWidth < VTWidth) {
3823 X = DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, X);
3824 AddToWorkList(X.getNode());
3825 } else if (OrigXWidth > VTWidth) {
3826 // To get the sign bit in the right place, we have to shift it right
3827 // before truncating.
3828 X = DAG.getNode(ISD::SRL, X.getDebugLoc(),
3829 X.getValueType(), X,
3830 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
3831 AddToWorkList(X.getNode());
3832 X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
3833 AddToWorkList(X.getNode());
3836 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
3837 X = DAG.getNode(ISD::AND, X.getDebugLoc(), VT,
3838 X, DAG.getConstant(SignBit, VT));
3839 AddToWorkList(X.getNode());
3841 SDValue Cst = DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(),
3842 VT, N0.getOperand(0));
3843 Cst = DAG.getNode(ISD::AND, Cst.getDebugLoc(), VT,
3844 Cst, DAG.getConstant(~SignBit, VT));
3845 AddToWorkList(Cst.getNode());
3847 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, X, Cst);
3851 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
3852 if (N0.getOpcode() == ISD::BUILD_PAIR) {
3853 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
3854 if (CombineLD.getNode())
3861 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
3862 EVT VT = N->getValueType(0);
3863 return CombineConsecutiveLoads(N, VT);
3866 /// ConstantFoldBIT_CONVERTofBUILD_VECTOR - We know that BV is a build_vector
3867 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
3868 /// destination element value type.
3869 SDValue DAGCombiner::
3870 ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
3871 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
3873 // If this is already the right type, we're done.
3874 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
3876 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
3877 unsigned DstBitSize = DstEltVT.getSizeInBits();
3879 // If this is a conversion of N elements of one type to N elements of another
3880 // type, convert each element. This handles FP<->INT cases.
3881 if (SrcBitSize == DstBitSize) {
3882 SmallVector<SDValue, 8> Ops;
3883 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3884 SDValue Op = BV->getOperand(i);
3885 // If the vector element type is not legal, the BUILD_VECTOR operands
3886 // are promoted and implicitly truncated. Make that explicit here.
3887 if (Op.getValueType() != SrcEltVT)
3888 Op = DAG.getNode(ISD::TRUNCATE, BV->getDebugLoc(), SrcEltVT, Op);
3889 Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, BV->getDebugLoc(),
3891 AddToWorkList(Ops.back().getNode());
3893 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
3894 BV->getValueType(0).getVectorNumElements());
3895 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
3896 &Ops[0], Ops.size());
3899 // Otherwise, we're growing or shrinking the elements. To avoid having to
3900 // handle annoying details of growing/shrinking FP values, we convert them to
3902 if (SrcEltVT.isFloatingPoint()) {
3903 // Convert the input float vector to a int vector where the elements are the
3905 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
3906 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
3907 BV = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, IntVT).getNode();
3911 // Now we know the input is an integer vector. If the output is a FP type,
3912 // convert to integer first, then to FP of the right size.
3913 if (DstEltVT.isFloatingPoint()) {
3914 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
3915 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
3916 SDNode *Tmp = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, TmpVT).getNode();
3918 // Next, convert to FP elements of the same size.
3919 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(Tmp, DstEltVT);
3922 // Okay, we know the src/dst types are both integers of differing types.
3923 // Handling growing first.
3924 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
3925 if (SrcBitSize < DstBitSize) {
3926 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
3928 SmallVector<SDValue, 8> Ops;
3929 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
3930 i += NumInputsPerOutput) {
3931 bool isLE = TLI.isLittleEndian();
3932 APInt NewBits = APInt(DstBitSize, 0);
3933 bool EltIsUndef = true;
3934 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
3935 // Shift the previously computed bits over.
3936 NewBits <<= SrcBitSize;
3937 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
3938 if (Op.getOpcode() == ISD::UNDEF) continue;
3941 NewBits |= (APInt(cast<ConstantSDNode>(Op)->getAPIntValue()).
3942 zextOrTrunc(SrcBitSize).zext(DstBitSize));
3946 Ops.push_back(DAG.getUNDEF(DstEltVT));
3948 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
3951 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
3952 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
3953 &Ops[0], Ops.size());
3956 // Finally, this must be the case where we are shrinking elements: each input
3957 // turns into multiple outputs.
3958 bool isS2V = ISD::isScalarToVector(BV);
3959 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
3960 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
3961 NumOutputsPerInput*BV->getNumOperands());
3962 SmallVector<SDValue, 8> Ops;
3964 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3965 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
3966 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
3967 Ops.push_back(DAG.getUNDEF(DstEltVT));
3971 APInt OpVal = APInt(cast<ConstantSDNode>(BV->getOperand(i))->
3972 getAPIntValue()).zextOrTrunc(SrcBitSize);
3974 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
3975 APInt ThisVal = APInt(OpVal).trunc(DstBitSize);
3976 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
3977 if (isS2V && i == 0 && j == 0 && APInt(ThisVal).zext(SrcBitSize) == OpVal)
3978 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
3979 return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
3981 OpVal = OpVal.lshr(DstBitSize);
3984 // For big endian targets, swap the order of the pieces of each element.
3985 if (TLI.isBigEndian())
3986 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
3989 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
3990 &Ops[0], Ops.size());
3993 SDValue DAGCombiner::visitFADD(SDNode *N) {
3994 SDValue N0 = N->getOperand(0);
3995 SDValue N1 = N->getOperand(1);
3996 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3997 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3998 EVT VT = N->getValueType(0);
4001 if (VT.isVector()) {
4002 SDValue FoldedVOp = SimplifyVBinOp(N);
4003 if (FoldedVOp.getNode()) return FoldedVOp;
4006 // fold (fadd c1, c2) -> (fadd c1, c2)
4007 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4008 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N1);
4009 // canonicalize constant to RHS
4010 if (N0CFP && !N1CFP)
4011 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N0);
4012 // fold (fadd A, 0) -> A
4013 if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
4015 // fold (fadd A, (fneg B)) -> (fsub A, B)
4016 if (isNegatibleForFree(N1, LegalOperations) == 2)
4017 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0,
4018 GetNegatedExpression(N1, DAG, LegalOperations));
4019 // fold (fadd (fneg A), B) -> (fsub B, A)
4020 if (isNegatibleForFree(N0, LegalOperations) == 2)
4021 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N1,
4022 GetNegatedExpression(N0, DAG, LegalOperations));
4024 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
4025 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FADD &&
4026 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
4027 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0.getOperand(0),
4028 DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
4029 N0.getOperand(1), N1));
4034 SDValue DAGCombiner::visitFSUB(SDNode *N) {
4035 SDValue N0 = N->getOperand(0);
4036 SDValue N1 = N->getOperand(1);
4037 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4038 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4039 EVT VT = N->getValueType(0);
4042 if (VT.isVector()) {
4043 SDValue FoldedVOp = SimplifyVBinOp(N);
4044 if (FoldedVOp.getNode()) return FoldedVOp;
4047 // fold (fsub c1, c2) -> c1-c2
4048 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4049 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0, N1);
4050 // fold (fsub A, 0) -> A
4051 if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
4053 // fold (fsub 0, B) -> -B
4054 if (UnsafeFPMath && N0CFP && N0CFP->getValueAPF().isZero()) {
4055 if (isNegatibleForFree(N1, LegalOperations))
4056 return GetNegatedExpression(N1, DAG, LegalOperations);
4057 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
4058 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N1);
4060 // fold (fsub A, (fneg B)) -> (fadd A, B)
4061 if (isNegatibleForFree(N1, LegalOperations))
4062 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0,
4063 GetNegatedExpression(N1, DAG, LegalOperations));
4068 SDValue DAGCombiner::visitFMUL(SDNode *N) {
4069 SDValue N0 = N->getOperand(0);
4070 SDValue N1 = N->getOperand(1);
4071 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4072 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4073 EVT VT = N->getValueType(0);
4076 if (VT.isVector()) {
4077 SDValue FoldedVOp = SimplifyVBinOp(N);
4078 if (FoldedVOp.getNode()) return FoldedVOp;
4081 // fold (fmul c1, c2) -> c1*c2
4082 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4083 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0, N1);
4084 // canonicalize constant to RHS
4085 if (N0CFP && !N1CFP)
4086 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N1, N0);
4087 // fold (fmul A, 0) -> 0
4088 if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
4090 // fold (fmul A, 0) -> 0, vector edition.
4091 if (UnsafeFPMath && ISD::isBuildVectorAllZeros(N1.getNode()))
4093 // fold (fmul X, 2.0) -> (fadd X, X)
4094 if (N1CFP && N1CFP->isExactlyValue(+2.0))
4095 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N0);
4096 // fold (fmul X, -1.0) -> (fneg X)
4097 if (N1CFP && N1CFP->isExactlyValue(-1.0))
4098 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
4099 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N0);
4101 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
4102 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations)) {
4103 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations)) {
4104 // Both can be negated for free, check to see if at least one is cheaper
4106 if (LHSNeg == 2 || RHSNeg == 2)
4107 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
4108 GetNegatedExpression(N0, DAG, LegalOperations),
4109 GetNegatedExpression(N1, DAG, LegalOperations));
4113 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
4114 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
4115 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
4116 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0.getOperand(0),
4117 DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
4118 N0.getOperand(1), N1));
4123 SDValue DAGCombiner::visitFDIV(SDNode *N) {
4124 SDValue N0 = N->getOperand(0);
4125 SDValue N1 = N->getOperand(1);
4126 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4127 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4128 EVT VT = N->getValueType(0);
4131 if (VT.isVector()) {
4132 SDValue FoldedVOp = SimplifyVBinOp(N);
4133 if (FoldedVOp.getNode()) return FoldedVOp;
4136 // fold (fdiv c1, c2) -> c1/c2
4137 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4138 return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT, N0, N1);
4141 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
4142 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations)) {
4143 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations)) {
4144 // Both can be negated for free, check to see if at least one is cheaper
4146 if (LHSNeg == 2 || RHSNeg == 2)
4147 return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT,
4148 GetNegatedExpression(N0, DAG, LegalOperations),
4149 GetNegatedExpression(N1, DAG, LegalOperations));
4156 SDValue DAGCombiner::visitFREM(SDNode *N) {
4157 SDValue N0 = N->getOperand(0);
4158 SDValue N1 = N->getOperand(1);
4159 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4160 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4161 EVT VT = N->getValueType(0);
4163 // fold (frem c1, c2) -> fmod(c1,c2)
4164 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4165 return DAG.getNode(ISD::FREM, N->getDebugLoc(), VT, N0, N1);
4170 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
4171 SDValue N0 = N->getOperand(0);
4172 SDValue N1 = N->getOperand(1);
4173 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4174 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4175 EVT VT = N->getValueType(0);
4177 if (N0CFP && N1CFP && VT != MVT::ppcf128) // Constant fold
4178 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, N0, N1);
4181 const APFloat& V = N1CFP->getValueAPF();
4182 // copysign(x, c1) -> fabs(x) iff ispos(c1)
4183 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
4184 if (!V.isNegative()) {
4185 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
4186 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
4188 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
4189 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT,
4190 DAG.getNode(ISD::FABS, N0.getDebugLoc(), VT, N0));
4194 // copysign(fabs(x), y) -> copysign(x, y)
4195 // copysign(fneg(x), y) -> copysign(x, y)
4196 // copysign(copysign(x,z), y) -> copysign(x, y)
4197 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
4198 N0.getOpcode() == ISD::FCOPYSIGN)
4199 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
4200 N0.getOperand(0), N1);
4202 // copysign(x, abs(y)) -> abs(x)
4203 if (N1.getOpcode() == ISD::FABS)
4204 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
4206 // copysign(x, copysign(y,z)) -> copysign(x, z)
4207 if (N1.getOpcode() == ISD::FCOPYSIGN)
4208 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
4209 N0, N1.getOperand(1));
4211 // copysign(x, fp_extend(y)) -> copysign(x, y)
4212 // copysign(x, fp_round(y)) -> copysign(x, y)
4213 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
4214 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
4215 N0, N1.getOperand(0));
4220 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
4221 SDValue N0 = N->getOperand(0);
4222 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4223 EVT VT = N->getValueType(0);
4224 EVT OpVT = N0.getValueType();
4226 // fold (sint_to_fp c1) -> c1fp
4227 if (N0C && OpVT != MVT::ppcf128)
4228 return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
4230 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
4231 // but UINT_TO_FP is legal on this target, try to convert.
4232 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
4233 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
4234 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
4235 if (DAG.SignBitIsZero(N0))
4236 return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
4242 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
4243 SDValue N0 = N->getOperand(0);
4244 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4245 EVT VT = N->getValueType(0);
4246 EVT OpVT = N0.getValueType();
4248 // fold (uint_to_fp c1) -> c1fp
4249 if (N0C && OpVT != MVT::ppcf128)
4250 return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
4252 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
4253 // but SINT_TO_FP is legal on this target, try to convert.
4254 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
4255 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
4256 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
4257 if (DAG.SignBitIsZero(N0))
4258 return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
4264 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
4265 SDValue N0 = N->getOperand(0);
4266 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4267 EVT VT = N->getValueType(0);
4269 // fold (fp_to_sint c1fp) -> c1
4271 return DAG.getNode(ISD::FP_TO_SINT, N->getDebugLoc(), VT, N0);
4276 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
4277 SDValue N0 = N->getOperand(0);
4278 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4279 EVT VT = N->getValueType(0);
4281 // fold (fp_to_uint c1fp) -> c1
4282 if (N0CFP && VT != MVT::ppcf128)
4283 return DAG.getNode(ISD::FP_TO_UINT, N->getDebugLoc(), VT, N0);
4288 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
4289 SDValue N0 = N->getOperand(0);
4290 SDValue N1 = N->getOperand(1);
4291 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4292 EVT VT = N->getValueType(0);
4294 // fold (fp_round c1fp) -> c1fp
4295 if (N0CFP && N0.getValueType() != MVT::ppcf128)
4296 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0, N1);
4298 // fold (fp_round (fp_extend x)) -> x
4299 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
4300 return N0.getOperand(0);
4302 // fold (fp_round (fp_round x)) -> (fp_round x)
4303 if (N0.getOpcode() == ISD::FP_ROUND) {
4304 // This is a value preserving truncation if both round's are.
4305 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
4306 N0.getNode()->getConstantOperandVal(1) == 1;
4307 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0.getOperand(0),
4308 DAG.getIntPtrConstant(IsTrunc));
4311 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
4312 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
4313 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(), VT,
4314 N0.getOperand(0), N1);
4315 AddToWorkList(Tmp.getNode());
4316 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
4317 Tmp, N0.getOperand(1));
4323 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
4324 SDValue N0 = N->getOperand(0);
4325 EVT VT = N->getValueType(0);
4326 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
4327 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4329 // fold (fp_round_inreg c1fp) -> c1fp
4330 if (N0CFP && (TLI.isTypeLegal(EVT) || !LegalTypes)) {
4331 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
4332 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, Round);
4338 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
4339 SDValue N0 = N->getOperand(0);
4340 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4341 EVT VT = N->getValueType(0);
4343 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
4344 if (N->hasOneUse() &&
4345 N->use_begin()->getOpcode() == ISD::FP_ROUND)
4348 // fold (fp_extend c1fp) -> c1fp
4349 if (N0CFP && VT != MVT::ppcf128)
4350 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, N0);
4352 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
4354 if (N0.getOpcode() == ISD::FP_ROUND
4355 && N0.getNode()->getConstantOperandVal(1) == 1) {
4356 SDValue In = N0.getOperand(0);
4357 if (In.getValueType() == VT) return In;
4358 if (VT.bitsLT(In.getValueType()))
4359 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT,
4360 In, N0.getOperand(1));
4361 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, In);
4364 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
4365 if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
4366 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4367 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
4368 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4369 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
4371 LN0->getBasePtr(), LN0->getSrcValue(),
4372 LN0->getSrcValueOffset(),
4374 LN0->isVolatile(), LN0->getAlignment());
4375 CombineTo(N, ExtLoad);
4376 CombineTo(N0.getNode(),
4377 DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(),
4378 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
4379 ExtLoad.getValue(1));
4380 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4386 SDValue DAGCombiner::visitFNEG(SDNode *N) {
4387 SDValue N0 = N->getOperand(0);
4388 EVT VT = N->getValueType(0);
4390 if (isNegatibleForFree(N0, LegalOperations))
4391 return GetNegatedExpression(N0, DAG, LegalOperations);
4393 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
4394 // constant pool values.
4395 if (N0.getOpcode() == ISD::BIT_CONVERT &&
4397 N0.getNode()->hasOneUse() &&
4398 N0.getOperand(0).getValueType().isInteger()) {
4399 SDValue Int = N0.getOperand(0);
4400 EVT IntVT = Int.getValueType();
4401 if (IntVT.isInteger() && !IntVT.isVector()) {
4402 Int = DAG.getNode(ISD::XOR, N0.getDebugLoc(), IntVT, Int,
4403 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
4404 AddToWorkList(Int.getNode());
4405 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(),
4413 SDValue DAGCombiner::visitFABS(SDNode *N) {
4414 SDValue N0 = N->getOperand(0);
4415 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4416 EVT VT = N->getValueType(0);
4418 // fold (fabs c1) -> fabs(c1)
4419 if (N0CFP && VT != MVT::ppcf128)
4420 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
4421 // fold (fabs (fabs x)) -> (fabs x)
4422 if (N0.getOpcode() == ISD::FABS)
4423 return N->getOperand(0);
4424 // fold (fabs (fneg x)) -> (fabs x)
4425 // fold (fabs (fcopysign x, y)) -> (fabs x)
4426 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
4427 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0.getOperand(0));
4429 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
4430 // constant pool values.
4431 if (N0.getOpcode() == ISD::BIT_CONVERT && N0.getNode()->hasOneUse() &&
4432 N0.getOperand(0).getValueType().isInteger() &&
4433 !N0.getOperand(0).getValueType().isVector()) {
4434 SDValue Int = N0.getOperand(0);
4435 EVT IntVT = Int.getValueType();
4436 if (IntVT.isInteger() && !IntVT.isVector()) {
4437 Int = DAG.getNode(ISD::AND, N0.getDebugLoc(), IntVT, Int,
4438 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
4439 AddToWorkList(Int.getNode());
4440 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(),
4441 N->getValueType(0), Int);
4448 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
4449 SDValue Chain = N->getOperand(0);
4450 SDValue N1 = N->getOperand(1);
4451 SDValue N2 = N->getOperand(2);
4453 // If N is a constant we could fold this into a fallthrough or unconditional
4454 // branch. However that doesn't happen very often in normal code, because
4455 // Instcombine/SimplifyCFG should have handled the available opportunities.
4456 // If we did this folding here, it would be necessary to update the
4457 // MachineBasicBlock CFG, which is awkward.
4459 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
4461 if (N1.getOpcode() == ISD::SETCC &&
4462 TLI.isOperationLegalOrCustom(ISD::BR_CC, MVT::Other)) {
4463 return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
4464 Chain, N1.getOperand(2),
4465 N1.getOperand(0), N1.getOperand(1), N2);
4468 if (N1.hasOneUse() && N1.getOpcode() == ISD::SRL) {
4469 // Match this pattern so that we can generate simpler code:
4472 // %b = and i32 %a, 2
4473 // %c = srl i32 %b, 1
4474 // brcond i32 %c ...
4480 // %c = setcc eq %b, 0
4483 // This applies only when the AND constant value has one bit set and the
4484 // SRL constant is equal to the log2 of the AND constant. The back-end is
4485 // smart enough to convert the result into a TEST/JMP sequence.
4486 SDValue Op0 = N1.getOperand(0);
4487 SDValue Op1 = N1.getOperand(1);
4489 if (Op0.getOpcode() == ISD::AND &&
4491 Op1.getOpcode() == ISD::Constant) {
4492 SDValue AndOp1 = Op0.getOperand(1);
4494 if (AndOp1.getOpcode() == ISD::Constant) {
4495 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
4497 if (AndConst.isPowerOf2() &&
4498 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
4500 DAG.getSetCC(N->getDebugLoc(),
4501 TLI.getSetCCResultType(Op0.getValueType()),
4502 Op0, DAG.getConstant(0, Op0.getValueType()),
4505 // Replace the uses of SRL with SETCC
4506 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
4507 removeFromWorkList(N1.getNode());
4508 DAG.DeleteNode(N1.getNode());
4509 return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
4510 MVT::Other, Chain, SetCC, N2);
4519 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
4521 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
4522 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
4523 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
4525 // If N is a constant we could fold this into a fallthrough or unconditional
4526 // branch. However that doesn't happen very often in normal code, because
4527 // Instcombine/SimplifyCFG should have handled the available opportunities.
4528 // If we did this folding here, it would be necessary to update the
4529 // MachineBasicBlock CFG, which is awkward.
4531 // Use SimplifySetCC to simplify SETCC's.
4532 SDValue Simp = SimplifySetCC(TLI.getSetCCResultType(CondLHS.getValueType()),
4533 CondLHS, CondRHS, CC->get(), N->getDebugLoc(),
4535 if (Simp.getNode()) AddToWorkList(Simp.getNode());
4537 // fold to a simpler setcc
4538 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
4539 return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
4540 N->getOperand(0), Simp.getOperand(2),
4541 Simp.getOperand(0), Simp.getOperand(1),
4547 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
4548 /// pre-indexed load / store when the base pointer is an add or subtract
4549 /// and it has other uses besides the load / store. After the
4550 /// transformation, the new indexed load / store has effectively folded
4551 /// the add / subtract in and all of its other uses are redirected to the
4552 /// new load / store.
4553 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
4554 if (!LegalOperations)
4560 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
4561 if (LD->isIndexed())
4563 VT = LD->getMemoryVT();
4564 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
4565 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
4567 Ptr = LD->getBasePtr();
4568 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
4569 if (ST->isIndexed())
4571 VT = ST->getMemoryVT();
4572 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
4573 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
4575 Ptr = ST->getBasePtr();
4581 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
4582 // out. There is no reason to make this a preinc/predec.
4583 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
4584 Ptr.getNode()->hasOneUse())
4587 // Ask the target to do addressing mode selection.
4590 ISD::MemIndexedMode AM = ISD::UNINDEXED;
4591 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
4593 // Don't create a indexed load / store with zero offset.
4594 if (isa<ConstantSDNode>(Offset) &&
4595 cast<ConstantSDNode>(Offset)->isNullValue())
4598 // Try turning it into a pre-indexed load / store except when:
4599 // 1) The new base ptr is a frame index.
4600 // 2) If N is a store and the new base ptr is either the same as or is a
4601 // predecessor of the value being stored.
4602 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
4603 // that would create a cycle.
4604 // 4) All uses are load / store ops that use it as old base ptr.
4606 // Check #1. Preinc'ing a frame index would require copying the stack pointer
4607 // (plus the implicit offset) to a register to preinc anyway.
4608 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
4613 SDValue Val = cast<StoreSDNode>(N)->getValue();
4614 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
4618 // Now check for #3 and #4.
4619 bool RealUse = false;
4620 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
4621 E = Ptr.getNode()->use_end(); I != E; ++I) {
4625 if (Use->isPredecessorOf(N))
4628 if (!((Use->getOpcode() == ISD::LOAD &&
4629 cast<LoadSDNode>(Use)->getBasePtr() == Ptr) ||
4630 (Use->getOpcode() == ISD::STORE &&
4631 cast<StoreSDNode>(Use)->getBasePtr() == Ptr)))
4640 Result = DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
4641 BasePtr, Offset, AM);
4643 Result = DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
4644 BasePtr, Offset, AM);
4647 DEBUG(errs() << "\nReplacing.4 ";
4649 errs() << "\nWith: ";
4650 Result.getNode()->dump(&DAG);
4652 WorkListRemover DeadNodes(*this);
4654 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
4656 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
4659 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
4663 // Finally, since the node is now dead, remove it from the graph.
4666 // Replace the uses of Ptr with uses of the updated base value.
4667 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
4669 removeFromWorkList(Ptr.getNode());
4670 DAG.DeleteNode(Ptr.getNode());
4675 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
4676 /// add / sub of the base pointer node into a post-indexed load / store.
4677 /// The transformation folded the add / subtract into the new indexed
4678 /// load / store effectively and all of its uses are redirected to the
4679 /// new load / store.
4680 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
4681 if (!LegalOperations)
4687 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
4688 if (LD->isIndexed())
4690 VT = LD->getMemoryVT();
4691 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
4692 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
4694 Ptr = LD->getBasePtr();
4695 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
4696 if (ST->isIndexed())
4698 VT = ST->getMemoryVT();
4699 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
4700 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
4702 Ptr = ST->getBasePtr();
4708 if (Ptr.getNode()->hasOneUse())
4711 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
4712 E = Ptr.getNode()->use_end(); I != E; ++I) {
4715 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
4720 ISD::MemIndexedMode AM = ISD::UNINDEXED;
4721 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
4722 if (Ptr == Offset && Op->getOpcode() == ISD::ADD)
4723 std::swap(BasePtr, Offset);
4726 // Don't create a indexed load / store with zero offset.
4727 if (isa<ConstantSDNode>(Offset) &&
4728 cast<ConstantSDNode>(Offset)->isNullValue())
4731 // Try turning it into a post-indexed load / store except when
4732 // 1) All uses are load / store ops that use it as base ptr.
4733 // 2) Op must be independent of N, i.e. Op is neither a predecessor
4734 // nor a successor of N. Otherwise, if Op is folded that would
4737 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
4741 bool TryNext = false;
4742 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
4743 EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
4745 if (Use == Ptr.getNode())
4748 // If all the uses are load / store addresses, then don't do the
4750 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
4751 bool RealUse = false;
4752 for (SDNode::use_iterator III = Use->use_begin(),
4753 EEE = Use->use_end(); III != EEE; ++III) {
4754 SDNode *UseUse = *III;
4755 if (!((UseUse->getOpcode() == ISD::LOAD &&
4756 cast<LoadSDNode>(UseUse)->getBasePtr().getNode() == Use) ||
4757 (UseUse->getOpcode() == ISD::STORE &&
4758 cast<StoreSDNode>(UseUse)->getBasePtr().getNode() == Use)))
4773 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
4774 SDValue Result = isLoad
4775 ? DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
4776 BasePtr, Offset, AM)
4777 : DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
4778 BasePtr, Offset, AM);
4781 DEBUG(errs() << "\nReplacing.5 ";
4783 errs() << "\nWith: ";
4784 Result.getNode()->dump(&DAG);
4786 WorkListRemover DeadNodes(*this);
4788 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
4790 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
4793 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
4797 // Finally, since the node is now dead, remove it from the graph.
4800 // Replace the uses of Use with uses of the updated base value.
4801 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
4802 Result.getValue(isLoad ? 1 : 0),
4804 removeFromWorkList(Op);
4814 SDValue DAGCombiner::visitLOAD(SDNode *N) {
4815 LoadSDNode *LD = cast<LoadSDNode>(N);
4816 SDValue Chain = LD->getChain();
4817 SDValue Ptr = LD->getBasePtr();
4819 // Try to infer better alignment information than the load already has.
4820 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
4821 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
4822 if (Align > LD->getAlignment())
4823 return DAG.getExtLoad(LD->getExtensionType(), N->getDebugLoc(),
4824 LD->getValueType(0),
4825 Chain, Ptr, LD->getSrcValue(),
4826 LD->getSrcValueOffset(), LD->getMemoryVT(),
4827 LD->isVolatile(), Align);
4831 // If load is not volatile and there are no uses of the loaded value (and
4832 // the updated indexed value in case of indexed loads), change uses of the
4833 // chain value into uses of the chain input (i.e. delete the dead load).
4834 if (!LD->isVolatile()) {
4835 if (N->getValueType(1) == MVT::Other) {
4837 if (N->hasNUsesOfValue(0, 0)) {
4838 // It's not safe to use the two value CombineTo variant here. e.g.
4839 // v1, chain2 = load chain1, loc
4840 // v2, chain3 = load chain2, loc
4842 // Now we replace use of chain2 with chain1. This makes the second load
4843 // isomorphic to the one we are deleting, and thus makes this load live.
4844 DEBUG(errs() << "\nReplacing.6 ";
4846 errs() << "\nWith chain: ";
4847 Chain.getNode()->dump(&DAG);
4849 WorkListRemover DeadNodes(*this);
4850 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain, &DeadNodes);
4852 if (N->use_empty()) {
4853 removeFromWorkList(N);
4857 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4861 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
4862 if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) {
4863 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
4864 DEBUG(errs() << "\nReplacing.6 ";
4866 errs() << "\nWith: ";
4867 Undef.getNode()->dump(&DAG);
4868 errs() << " and 2 other values\n");
4869 WorkListRemover DeadNodes(*this);
4870 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef, &DeadNodes);
4871 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
4872 DAG.getUNDEF(N->getValueType(1)),
4874 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain, &DeadNodes);
4875 removeFromWorkList(N);
4877 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4882 // If this load is directly stored, replace the load value with the stored
4884 // TODO: Handle store large -> read small portion.
4885 // TODO: Handle TRUNCSTORE/LOADEXT
4886 if (LD->getExtensionType() == ISD::NON_EXTLOAD &&
4887 !LD->isVolatile()) {
4888 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
4889 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
4890 if (PrevST->getBasePtr() == Ptr &&
4891 PrevST->getValue().getValueType() == N->getValueType(0))
4892 return CombineTo(N, Chain.getOperand(1), Chain);
4897 // Walk up chain skipping non-aliasing memory nodes.
4898 SDValue BetterChain = FindBetterChain(N, Chain);
4900 // If there is a better chain.
4901 if (Chain != BetterChain) {
4904 // Replace the chain to void dependency.
4905 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
4906 ReplLoad = DAG.getLoad(N->getValueType(0), LD->getDebugLoc(),
4908 LD->getSrcValue(), LD->getSrcValueOffset(),
4909 LD->isVolatile(), LD->getAlignment());
4911 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), LD->getDebugLoc(),
4912 LD->getValueType(0),
4913 BetterChain, Ptr, LD->getSrcValue(),
4914 LD->getSrcValueOffset(),
4917 LD->getAlignment());
4920 // Create token factor to keep old chain connected.
4921 SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
4922 MVT::Other, Chain, ReplLoad.getValue(1));
4924 // Make sure the new and old chains are cleaned up.
4925 AddToWorkList(Token.getNode());
4927 // Replace uses with load result and token factor. Don't add users
4929 return CombineTo(N, ReplLoad.getValue(0), Token, false);
4933 // Try transforming N to an indexed load.
4934 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
4935 return SDValue(N, 0);
4941 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
4942 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
4943 /// of the loaded bits, try narrowing the load and store if it would end up
4944 /// being a win for performance or code size.
4945 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
4946 StoreSDNode *ST = cast<StoreSDNode>(N);
4947 if (ST->isVolatile())
4950 SDValue Chain = ST->getChain();
4951 SDValue Value = ST->getValue();
4952 SDValue Ptr = ST->getBasePtr();
4953 EVT VT = Value.getValueType();
4955 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
4958 unsigned Opc = Value.getOpcode();
4959 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
4960 Value.getOperand(1).getOpcode() != ISD::Constant)
4963 SDValue N0 = Value.getOperand(0);
4964 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse()) {
4965 LoadSDNode *LD = cast<LoadSDNode>(N0);
4966 if (LD->getBasePtr() != Ptr)
4969 // Find the type to narrow it the load / op / store to.
4970 SDValue N1 = Value.getOperand(1);
4971 unsigned BitWidth = N1.getValueSizeInBits();
4972 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
4973 if (Opc == ISD::AND)
4974 Imm ^= APInt::getAllOnesValue(BitWidth);
4975 if (Imm == 0 || Imm.isAllOnesValue())
4977 unsigned ShAmt = Imm.countTrailingZeros();
4978 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
4979 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
4980 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
4981 while (NewBW < BitWidth &&
4982 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
4983 TLI.isNarrowingProfitable(VT, NewVT))) {
4984 NewBW = NextPowerOf2(NewBW);
4985 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
4987 if (NewBW >= BitWidth)
4990 // If the lsb changed does not start at the type bitwidth boundary,
4991 // start at the previous one.
4993 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
4994 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, ShAmt + NewBW);
4995 if ((Imm & Mask) == Imm) {
4996 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
4997 if (Opc == ISD::AND)
4998 NewImm ^= APInt::getAllOnesValue(NewBW);
4999 uint64_t PtrOff = ShAmt / 8;
5000 // For big endian targets, we need to adjust the offset to the pointer to
5001 // load the correct bytes.
5002 if (TLI.isBigEndian())
5003 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
5005 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
5007 TLI.getTargetData()->getABITypeAlignment(NewVT.getTypeForEVT(*DAG.getContext())))
5010 SDValue NewPtr = DAG.getNode(ISD::ADD, LD->getDebugLoc(),
5011 Ptr.getValueType(), Ptr,
5012 DAG.getConstant(PtrOff, Ptr.getValueType()));
5013 SDValue NewLD = DAG.getLoad(NewVT, N0.getDebugLoc(),
5014 LD->getChain(), NewPtr,
5015 LD->getSrcValue(), LD->getSrcValueOffset(),
5016 LD->isVolatile(), NewAlign);
5017 SDValue NewVal = DAG.getNode(Opc, Value.getDebugLoc(), NewVT, NewLD,
5018 DAG.getConstant(NewImm, NewVT));
5019 SDValue NewST = DAG.getStore(Chain, N->getDebugLoc(),
5021 ST->getSrcValue(), ST->getSrcValueOffset(),
5024 AddToWorkList(NewPtr.getNode());
5025 AddToWorkList(NewLD.getNode());
5026 AddToWorkList(NewVal.getNode());
5027 WorkListRemover DeadNodes(*this);
5028 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1),
5038 SDValue DAGCombiner::visitSTORE(SDNode *N) {
5039 StoreSDNode *ST = cast<StoreSDNode>(N);
5040 SDValue Chain = ST->getChain();
5041 SDValue Value = ST->getValue();
5042 SDValue Ptr = ST->getBasePtr();
5044 // Try to infer better alignment information than the store already has.
5045 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
5046 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
5047 if (Align > ST->getAlignment())
5048 return DAG.getTruncStore(Chain, N->getDebugLoc(), Value,
5049 Ptr, ST->getSrcValue(),
5050 ST->getSrcValueOffset(), ST->getMemoryVT(),
5051 ST->isVolatile(), Align);
5055 // If this is a store of a bit convert, store the input value if the
5056 // resultant store does not need a higher alignment than the original.
5057 if (Value.getOpcode() == ISD::BIT_CONVERT && !ST->isTruncatingStore() &&
5058 ST->isUnindexed()) {
5059 unsigned OrigAlign = ST->getAlignment();
5060 EVT SVT = Value.getOperand(0).getValueType();
5061 unsigned Align = TLI.getTargetData()->
5062 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
5063 if (Align <= OrigAlign &&
5064 ((!LegalOperations && !ST->isVolatile()) ||
5065 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
5066 return DAG.getStore(Chain, N->getDebugLoc(), Value.getOperand(0),
5067 Ptr, ST->getSrcValue(),
5068 ST->getSrcValueOffset(), ST->isVolatile(), OrigAlign);
5071 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
5072 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
5073 // NOTE: If the original store is volatile, this transform must not increase
5074 // the number of stores. For example, on x86-32 an f64 can be stored in one
5075 // processor operation but an i64 (which is not legal) requires two. So the
5076 // transform should not be done in this case.
5077 if (Value.getOpcode() != ISD::TargetConstantFP) {
5079 switch (CFP->getValueType(0).getSimpleVT().SimpleTy) {
5080 default: llvm_unreachable("Unknown FP type");
5081 case MVT::f80: // We don't do this for these yet.
5086 if (((TLI.isTypeLegal(MVT::i32) || !LegalTypes) && !LegalOperations &&
5087 !ST->isVolatile()) ||
5088 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
5089 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
5090 bitcastToAPInt().getZExtValue(), MVT::i32);
5091 return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
5092 Ptr, ST->getSrcValue(),
5093 ST->getSrcValueOffset(), ST->isVolatile(),
5094 ST->getAlignment());
5098 if (((TLI.isTypeLegal(MVT::i64) || !LegalTypes) && !LegalOperations &&
5099 !ST->isVolatile()) ||
5100 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
5101 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
5102 getZExtValue(), MVT::i64);
5103 return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
5104 Ptr, ST->getSrcValue(),
5105 ST->getSrcValueOffset(), ST->isVolatile(),
5106 ST->getAlignment());
5107 } else if (!ST->isVolatile() &&
5108 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
5109 // Many FP stores are not made apparent until after legalize, e.g. for
5110 // argument passing. Since this is so common, custom legalize the
5111 // 64-bit integer store into two 32-bit stores.
5112 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
5113 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
5114 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
5115 if (TLI.isBigEndian()) std::swap(Lo, Hi);
5117 int SVOffset = ST->getSrcValueOffset();
5118 unsigned Alignment = ST->getAlignment();
5119 bool isVolatile = ST->isVolatile();
5121 SDValue St0 = DAG.getStore(Chain, ST->getDebugLoc(), Lo,
5122 Ptr, ST->getSrcValue(),
5123 ST->getSrcValueOffset(),
5124 isVolatile, ST->getAlignment());
5125 Ptr = DAG.getNode(ISD::ADD, N->getDebugLoc(), Ptr.getValueType(), Ptr,
5126 DAG.getConstant(4, Ptr.getValueType()));
5128 Alignment = MinAlign(Alignment, 4U);
5129 SDValue St1 = DAG.getStore(Chain, ST->getDebugLoc(), Hi,
5130 Ptr, ST->getSrcValue(),
5131 SVOffset, isVolatile, Alignment);
5132 return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
5142 // Walk up chain skipping non-aliasing memory nodes.
5143 SDValue BetterChain = FindBetterChain(N, Chain);
5145 // If there is a better chain.
5146 if (Chain != BetterChain) {
5149 // Replace the chain to avoid dependency.
5150 if (ST->isTruncatingStore()) {
5151 ReplStore = DAG.getTruncStore(BetterChain, N->getDebugLoc(), Value, Ptr,
5152 ST->getSrcValue(),ST->getSrcValueOffset(),
5154 ST->isVolatile(), ST->getAlignment());
5156 ReplStore = DAG.getStore(BetterChain, N->getDebugLoc(), Value, Ptr,
5157 ST->getSrcValue(), ST->getSrcValueOffset(),
5158 ST->isVolatile(), ST->getAlignment());
5161 // Create token to keep both nodes around.
5162 SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
5163 MVT::Other, Chain, ReplStore);
5165 // Make sure the new and old chains are cleaned up.
5166 AddToWorkList(Token.getNode());
5168 // Don't add users to work list.
5169 return CombineTo(N, Token, false);
5173 // Try transforming N to an indexed store.
5174 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
5175 return SDValue(N, 0);
5177 // FIXME: is there such a thing as a truncating indexed store?
5178 if (ST->isTruncatingStore() && ST->isUnindexed() &&
5179 Value.getValueType().isInteger()) {
5180 // See if we can simplify the input to this truncstore with knowledge that
5181 // only the low bits are being used. For example:
5182 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
5184 GetDemandedBits(Value,
5185 APInt::getLowBitsSet(Value.getValueSizeInBits(),
5186 ST->getMemoryVT().getSizeInBits()));
5187 AddToWorkList(Value.getNode());
5188 if (Shorter.getNode())
5189 return DAG.getTruncStore(Chain, N->getDebugLoc(), Shorter,
5190 Ptr, ST->getSrcValue(),
5191 ST->getSrcValueOffset(), ST->getMemoryVT(),
5192 ST->isVolatile(), ST->getAlignment());
5194 // Otherwise, see if we can simplify the operation with
5195 // SimplifyDemandedBits, which only works if the value has a single use.
5196 if (SimplifyDemandedBits(Value,
5197 APInt::getLowBitsSet(
5198 Value.getValueSizeInBits(),
5199 ST->getMemoryVT().getSizeInBits())))
5200 return SDValue(N, 0);
5203 // If this is a load followed by a store to the same location, then the store
5205 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
5206 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
5207 ST->isUnindexed() && !ST->isVolatile() &&
5208 // There can't be any side effects between the load and store, such as
5210 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
5211 // The store is dead, remove it.
5216 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
5217 // truncating store. We can do this even if this is already a truncstore.
5218 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
5219 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
5220 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
5221 ST->getMemoryVT())) {
5222 return DAG.getTruncStore(Chain, N->getDebugLoc(), Value.getOperand(0),
5223 Ptr, ST->getSrcValue(),
5224 ST->getSrcValueOffset(), ST->getMemoryVT(),
5225 ST->isVolatile(), ST->getAlignment());
5228 return ReduceLoadOpStoreWidth(N);
5231 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
5232 SDValue InVec = N->getOperand(0);
5233 SDValue InVal = N->getOperand(1);
5234 SDValue EltNo = N->getOperand(2);
5236 // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
5237 // vector with the inserted element.
5238 if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
5239 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5240 SmallVector<SDValue, 8> Ops(InVec.getNode()->op_begin(),
5241 InVec.getNode()->op_end());
5242 if (Elt < Ops.size())
5244 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
5245 InVec.getValueType(), &Ops[0], Ops.size());
5247 // If the invec is an UNDEF and if EltNo is a constant, create a new
5248 // BUILD_VECTOR with undef elements and the inserted element.
5249 if (!LegalOperations && InVec.getOpcode() == ISD::UNDEF &&
5250 isa<ConstantSDNode>(EltNo)) {
5251 EVT VT = InVec.getValueType();
5252 EVT EltVT = VT.getVectorElementType();
5253 unsigned NElts = VT.getVectorNumElements();
5254 SmallVector<SDValue, 8> Ops(NElts, DAG.getUNDEF(EltVT));
5256 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5257 if (Elt < Ops.size())
5259 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
5260 InVec.getValueType(), &Ops[0], Ops.size());
5265 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
5266 // (vextract (scalar_to_vector val, 0) -> val
5267 SDValue InVec = N->getOperand(0);
5269 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5270 // If the operand is wider than the vector element type then it is implicitly
5271 // truncated. Make that explicit here.
5272 EVT EltVT = InVec.getValueType().getVectorElementType();
5273 SDValue InOp = InVec.getOperand(0);
5274 if (InOp.getValueType() != EltVT)
5275 return DAG.getNode(ISD::TRUNCATE, InVec.getDebugLoc(), EltVT, InOp);
5279 // Perform only after legalization to ensure build_vector / vector_shuffle
5280 // optimizations have already been done.
5281 if (!LegalOperations) return SDValue();
5283 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
5284 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
5285 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
5286 SDValue EltNo = N->getOperand(1);
5288 if (isa<ConstantSDNode>(EltNo)) {
5289 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5290 bool NewLoad = false;
5291 bool BCNumEltsChanged = false;
5292 EVT VT = InVec.getValueType();
5293 EVT ExtVT = VT.getVectorElementType();
5296 if (InVec.getOpcode() == ISD::BIT_CONVERT) {
5297 EVT BCVT = InVec.getOperand(0).getValueType();
5298 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
5300 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
5301 BCNumEltsChanged = true;
5302 InVec = InVec.getOperand(0);
5303 ExtVT = BCVT.getVectorElementType();
5307 LoadSDNode *LN0 = NULL;
5308 const ShuffleVectorSDNode *SVN = NULL;
5309 if (ISD::isNormalLoad(InVec.getNode())) {
5310 LN0 = cast<LoadSDNode>(InVec);
5311 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5312 InVec.getOperand(0).getValueType() == ExtVT &&
5313 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
5314 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
5315 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
5316 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
5318 // (load $addr+1*size)
5320 // If the bit convert changed the number of elements, it is unsafe
5321 // to examine the mask.
5322 if (BCNumEltsChanged)
5325 // Select the input vector, guarding against out of range extract vector.
5326 unsigned NumElems = VT.getVectorNumElements();
5327 int Idx = (Elt > NumElems) ? -1 : SVN->getMaskElt(Elt);
5328 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
5330 if (InVec.getOpcode() == ISD::BIT_CONVERT)
5331 InVec = InVec.getOperand(0);
5332 if (ISD::isNormalLoad(InVec.getNode())) {
5333 LN0 = cast<LoadSDNode>(InVec);
5334 Elt = (Idx < (int)NumElems) ? Idx : Idx - NumElems;
5338 if (!LN0 || !LN0->hasOneUse() || LN0->isVolatile())
5341 unsigned Align = LN0->getAlignment();
5343 // Check the resultant load doesn't need a higher alignment than the
5346 TLI.getTargetData()->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
5348 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
5354 SDValue NewPtr = LN0->getBasePtr();
5356 unsigned PtrOff = LVT.getSizeInBits() * Elt / 8;
5357 EVT PtrType = NewPtr.getValueType();
5358 if (TLI.isBigEndian())
5359 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
5360 NewPtr = DAG.getNode(ISD::ADD, N->getDebugLoc(), PtrType, NewPtr,
5361 DAG.getConstant(PtrOff, PtrType));
5364 return DAG.getLoad(LVT, N->getDebugLoc(), LN0->getChain(), NewPtr,
5365 LN0->getSrcValue(), LN0->getSrcValueOffset(),
5366 LN0->isVolatile(), Align);
5372 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
5373 unsigned NumInScalars = N->getNumOperands();
5374 EVT VT = N->getValueType(0);
5376 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
5377 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
5378 // at most two distinct vectors, turn this into a shuffle node.
5379 SDValue VecIn1, VecIn2;
5380 for (unsigned i = 0; i != NumInScalars; ++i) {
5381 // Ignore undef inputs.
5382 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
5384 // If this input is something other than a EXTRACT_VECTOR_ELT with a
5385 // constant index, bail out.
5386 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5387 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
5388 VecIn1 = VecIn2 = SDValue(0, 0);
5392 // If the input vector type disagrees with the result of the build_vector,
5393 // we can't make a shuffle.
5394 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
5395 if (ExtractedFromVec.getValueType() != VT) {
5396 VecIn1 = VecIn2 = SDValue(0, 0);
5400 // Otherwise, remember this. We allow up to two distinct input vectors.
5401 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
5404 if (VecIn1.getNode() == 0) {
5405 VecIn1 = ExtractedFromVec;
5406 } else if (VecIn2.getNode() == 0) {
5407 VecIn2 = ExtractedFromVec;
5410 VecIn1 = VecIn2 = SDValue(0, 0);
5415 // If everything is good, we can make a shuffle operation.
5416 if (VecIn1.getNode()) {
5417 SmallVector<int, 8> Mask;
5418 for (unsigned i = 0; i != NumInScalars; ++i) {
5419 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
5424 // If extracting from the first vector, just use the index directly.
5425 SDValue Extract = N->getOperand(i);
5426 SDValue ExtVal = Extract.getOperand(1);
5427 if (Extract.getOperand(0) == VecIn1) {
5428 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
5429 if (ExtIndex > VT.getVectorNumElements())
5432 Mask.push_back(ExtIndex);
5436 // Otherwise, use InIdx + VecSize
5437 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
5438 Mask.push_back(Idx+NumInScalars);
5441 // Add count and size info.
5442 if (!TLI.isTypeLegal(VT) && LegalTypes)
5445 // Return the new VECTOR_SHUFFLE node.
5448 Ops[1] = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5449 return DAG.getVectorShuffle(VT, N->getDebugLoc(), Ops[0], Ops[1], &Mask[0]);
5455 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
5456 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
5457 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
5458 // inputs come from at most two distinct vectors, turn this into a shuffle
5461 // If we only have one input vector, we don't need to do any concatenation.
5462 if (N->getNumOperands() == 1)
5463 return N->getOperand(0);
5468 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
5471 EVT VT = N->getValueType(0);
5472 unsigned NumElts = VT.getVectorNumElements();
5474 SDValue N0 = N->getOperand(0);
5476 assert(N0.getValueType().getVectorNumElements() == NumElts &&
5477 "Vector shuffle must be normalized in DAG");
5479 // FIXME: implement canonicalizations from DAG.getVectorShuffle()
5481 // If it is a splat, check if the argument vector is a build_vector with
5482 // all scalar elements the same.
5483 if (cast<ShuffleVectorSDNode>(N)->isSplat()) {
5484 SDNode *V = N0.getNode();
5487 // If this is a bit convert that changes the element type of the vector but
5488 // not the number of vector elements, look through it. Be careful not to
5489 // look though conversions that change things like v4f32 to v2f64.
5490 if (V->getOpcode() == ISD::BIT_CONVERT) {
5491 SDValue ConvInput = V->getOperand(0);
5492 if (ConvInput.getValueType().isVector() &&
5493 ConvInput.getValueType().getVectorNumElements() == NumElts)
5494 V = ConvInput.getNode();
5497 if (V->getOpcode() == ISD::BUILD_VECTOR) {
5498 unsigned NumElems = V->getNumOperands();
5499 unsigned BaseIdx = cast<ShuffleVectorSDNode>(N)->getSplatIndex();
5500 if (NumElems > BaseIdx) {
5502 bool AllSame = true;
5503 for (unsigned i = 0; i != NumElems; ++i) {
5504 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
5505 Base = V->getOperand(i);
5509 // Splat of <u, u, u, u>, return <u, u, u, u>
5510 if (!Base.getNode())
5512 for (unsigned i = 0; i != NumElems; ++i) {
5513 if (V->getOperand(i) != Base) {
5518 // Splat of <x, x, x, x>, return <x, x, x, x>
5527 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
5528 /// an AND to a vector_shuffle with the destination vector and a zero vector.
5529 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
5530 /// vector_shuffle V, Zero, <0, 4, 2, 4>
5531 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
5532 EVT VT = N->getValueType(0);
5533 DebugLoc dl = N->getDebugLoc();
5534 SDValue LHS = N->getOperand(0);
5535 SDValue RHS = N->getOperand(1);
5536 if (N->getOpcode() == ISD::AND) {
5537 if (RHS.getOpcode() == ISD::BIT_CONVERT)
5538 RHS = RHS.getOperand(0);
5539 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
5540 SmallVector<int, 8> Indices;
5541 unsigned NumElts = RHS.getNumOperands();
5542 for (unsigned i = 0; i != NumElts; ++i) {
5543 SDValue Elt = RHS.getOperand(i);
5544 if (!isa<ConstantSDNode>(Elt))
5546 else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
5547 Indices.push_back(i);
5548 else if (cast<ConstantSDNode>(Elt)->isNullValue())
5549 Indices.push_back(NumElts);
5554 // Let's see if the target supports this vector_shuffle.
5555 EVT RVT = RHS.getValueType();
5556 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
5559 // Return the new VECTOR_SHUFFLE node.
5560 EVT EltVT = RVT.getVectorElementType();
5561 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
5562 DAG.getConstant(0, EltVT));
5563 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
5564 RVT, &ZeroOps[0], ZeroOps.size());
5565 LHS = DAG.getNode(ISD::BIT_CONVERT, dl, RVT, LHS);
5566 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
5567 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Shuf);
5574 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
5575 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
5576 // After legalize, the target may be depending on adds and other
5577 // binary ops to provide legal ways to construct constants or other
5578 // things. Simplifying them may result in a loss of legality.
5579 if (LegalOperations) return SDValue();
5581 EVT VT = N->getValueType(0);
5582 assert(VT.isVector() && "SimplifyVBinOp only works on vectors!");
5584 EVT EltType = VT.getVectorElementType();
5585 SDValue LHS = N->getOperand(0);
5586 SDValue RHS = N->getOperand(1);
5587 SDValue Shuffle = XformToShuffleWithZero(N);
5588 if (Shuffle.getNode()) return Shuffle;
5590 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
5592 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
5593 RHS.getOpcode() == ISD::BUILD_VECTOR) {
5594 SmallVector<SDValue, 8> Ops;
5595 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
5596 SDValue LHSOp = LHS.getOperand(i);
5597 SDValue RHSOp = RHS.getOperand(i);
5598 // If these two elements can't be folded, bail out.
5599 if ((LHSOp.getOpcode() != ISD::UNDEF &&
5600 LHSOp.getOpcode() != ISD::Constant &&
5601 LHSOp.getOpcode() != ISD::ConstantFP) ||
5602 (RHSOp.getOpcode() != ISD::UNDEF &&
5603 RHSOp.getOpcode() != ISD::Constant &&
5604 RHSOp.getOpcode() != ISD::ConstantFP))
5607 // Can't fold divide by zero.
5608 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
5609 N->getOpcode() == ISD::FDIV) {
5610 if ((RHSOp.getOpcode() == ISD::Constant &&
5611 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
5612 (RHSOp.getOpcode() == ISD::ConstantFP &&
5613 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
5617 Ops.push_back(DAG.getNode(N->getOpcode(), LHS.getDebugLoc(),
5618 EltType, LHSOp, RHSOp));
5619 AddToWorkList(Ops.back().getNode());
5620 assert((Ops.back().getOpcode() == ISD::UNDEF ||
5621 Ops.back().getOpcode() == ISD::Constant ||
5622 Ops.back().getOpcode() == ISD::ConstantFP) &&
5623 "Scalar binop didn't fold!");
5626 if (Ops.size() == LHS.getNumOperands()) {
5627 EVT VT = LHS.getValueType();
5628 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
5629 &Ops[0], Ops.size());
5636 SDValue DAGCombiner::SimplifySelect(DebugLoc DL, SDValue N0,
5637 SDValue N1, SDValue N2){
5638 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
5640 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
5641 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5643 // If we got a simplified select_cc node back from SimplifySelectCC, then
5644 // break it down into a new SETCC node, and a new SELECT node, and then return
5645 // the SELECT node, since we were called with a SELECT node.
5646 if (SCC.getNode()) {
5647 // Check to see if we got a select_cc back (to turn into setcc/select).
5648 // Otherwise, just return whatever node we got back, like fabs.
5649 if (SCC.getOpcode() == ISD::SELECT_CC) {
5650 SDValue SETCC = DAG.getNode(ISD::SETCC, N0.getDebugLoc(),
5652 SCC.getOperand(0), SCC.getOperand(1),
5654 AddToWorkList(SETCC.getNode());
5655 return DAG.getNode(ISD::SELECT, SCC.getDebugLoc(), SCC.getValueType(),
5656 SCC.getOperand(2), SCC.getOperand(3), SETCC);
5664 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
5665 /// are the two values being selected between, see if we can simplify the
5666 /// select. Callers of this should assume that TheSelect is deleted if this
5667 /// returns true. As such, they should return the appropriate thing (e.g. the
5668 /// node) back to the top-level of the DAG combiner loop to avoid it being
5670 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
5673 // If this is a select from two identical things, try to pull the operation
5674 // through the select.
5675 if (LHS.getOpcode() == RHS.getOpcode() && LHS.hasOneUse() && RHS.hasOneUse()){
5676 // If this is a load and the token chain is identical, replace the select
5677 // of two loads with a load through a select of the address to load from.
5678 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
5679 // constants have been dropped into the constant pool.
5680 if (LHS.getOpcode() == ISD::LOAD &&
5681 // Do not let this transformation reduce the number of volatile loads.
5682 !cast<LoadSDNode>(LHS)->isVolatile() &&
5683 !cast<LoadSDNode>(RHS)->isVolatile() &&
5684 // Token chains must be identical.
5685 LHS.getOperand(0) == RHS.getOperand(0)) {
5686 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
5687 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
5689 // If this is an EXTLOAD, the VT's must match.
5690 if (LLD->getMemoryVT() == RLD->getMemoryVT()) {
5691 // FIXME: this discards src value information. This is
5692 // over-conservative. It would be beneficial to be able to remember
5693 // both potential memory locations.
5695 if (TheSelect->getOpcode() == ISD::SELECT) {
5696 // Check that the condition doesn't reach either load. If so, folding
5697 // this will induce a cycle into the DAG.
5698 if ((!LLD->hasAnyUseOfValue(1) ||
5699 !LLD->isPredecessorOf(TheSelect->getOperand(0).getNode())) &&
5700 (!RLD->hasAnyUseOfValue(1) ||
5701 !RLD->isPredecessorOf(TheSelect->getOperand(0).getNode()))) {
5702 Addr = DAG.getNode(ISD::SELECT, TheSelect->getDebugLoc(),
5703 LLD->getBasePtr().getValueType(),
5704 TheSelect->getOperand(0), LLD->getBasePtr(),
5708 // Check that the condition doesn't reach either load. If so, folding
5709 // this will induce a cycle into the DAG.
5710 if ((!LLD->hasAnyUseOfValue(1) ||
5711 (!LLD->isPredecessorOf(TheSelect->getOperand(0).getNode()) &&
5712 !LLD->isPredecessorOf(TheSelect->getOperand(1).getNode()))) &&
5713 (!RLD->hasAnyUseOfValue(1) ||
5714 (!RLD->isPredecessorOf(TheSelect->getOperand(0).getNode()) &&
5715 !RLD->isPredecessorOf(TheSelect->getOperand(1).getNode())))) {
5716 Addr = DAG.getNode(ISD::SELECT_CC, TheSelect->getDebugLoc(),
5717 LLD->getBasePtr().getValueType(),
5718 TheSelect->getOperand(0),
5719 TheSelect->getOperand(1),
5720 LLD->getBasePtr(), RLD->getBasePtr(),
5721 TheSelect->getOperand(4));
5725 if (Addr.getNode()) {
5727 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
5728 Load = DAG.getLoad(TheSelect->getValueType(0),
5729 TheSelect->getDebugLoc(),
5733 LLD->getAlignment());
5735 Load = DAG.getExtLoad(LLD->getExtensionType(),
5736 TheSelect->getDebugLoc(),
5737 TheSelect->getValueType(0),
5738 LLD->getChain(), Addr, 0, 0,
5741 LLD->getAlignment());
5744 // Users of the select now use the result of the load.
5745 CombineTo(TheSelect, Load);
5747 // Users of the old loads now use the new load's chain. We know the
5748 // old-load value is dead now.
5749 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
5750 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
5760 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
5761 /// where 'cond' is the comparison specified by CC.
5762 SDValue DAGCombiner::SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1,
5763 SDValue N2, SDValue N3,
5764 ISD::CondCode CC, bool NotExtCompare) {
5765 // (x ? y : y) -> y.
5766 if (N2 == N3) return N2;
5768 EVT VT = N2.getValueType();
5769 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
5770 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
5771 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
5773 // Determine if the condition we're dealing with is constant
5774 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
5775 N0, N1, CC, DL, false);
5776 if (SCC.getNode()) AddToWorkList(SCC.getNode());
5777 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
5779 // fold select_cc true, x, y -> x
5780 if (SCCC && !SCCC->isNullValue())
5782 // fold select_cc false, x, y -> y
5783 if (SCCC && SCCC->isNullValue())
5786 // Check to see if we can simplify the select into an fabs node
5787 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
5788 // Allow either -0.0 or 0.0
5789 if (CFP->getValueAPF().isZero()) {
5790 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
5791 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
5792 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
5793 N2 == N3.getOperand(0))
5794 return DAG.getNode(ISD::FABS, DL, VT, N0);
5796 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
5797 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
5798 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
5799 N2.getOperand(0) == N3)
5800 return DAG.getNode(ISD::FABS, DL, VT, N3);
5804 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
5805 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
5806 // in it. This is a win when the constant is not otherwise available because
5807 // it replaces two constant pool loads with one. We only do this if the FP
5808 // type is known to be legal, because if it isn't, then we are before legalize
5809 // types an we want the other legalization to happen first (e.g. to avoid
5810 // messing with soft float) and if the ConstantFP is not legal, because if
5811 // it is legal, we may not need to store the FP constant in a constant pool.
5812 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
5813 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
5814 if (TLI.isTypeLegal(N2.getValueType()) &&
5815 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
5816 TargetLowering::Legal) &&
5817 // If both constants have multiple uses, then we won't need to do an
5818 // extra load, they are likely around in registers for other users.
5819 (TV->hasOneUse() || FV->hasOneUse())) {
5820 Constant *Elts[] = {
5821 const_cast<ConstantFP*>(FV->getConstantFPValue()),
5822 const_cast<ConstantFP*>(TV->getConstantFPValue())
5824 const Type *FPTy = Elts[0]->getType();
5825 const TargetData &TD = *TLI.getTargetData();
5827 // Create a ConstantArray of the two constants.
5828 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts, 2);
5829 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
5830 TD.getPrefTypeAlignment(FPTy));
5831 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
5833 // Get the offsets to the 0 and 1 element of the array so that we can
5834 // select between them.
5835 SDValue Zero = DAG.getIntPtrConstant(0);
5836 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
5837 SDValue One = DAG.getIntPtrConstant(EltSize);
5839 SDValue Cond = DAG.getSetCC(DL,
5840 TLI.getSetCCResultType(N0.getValueType()),
5842 SDValue CstOffset = DAG.getNode(ISD::SELECT, DL, Zero.getValueType(),
5844 CPIdx = DAG.getNode(ISD::ADD, DL, TLI.getPointerTy(), CPIdx,
5846 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
5847 PseudoSourceValue::getConstantPool(), 0, false,
5853 // Check to see if we can perform the "gzip trick", transforming
5854 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
5855 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
5856 N0.getValueType().isInteger() &&
5857 N2.getValueType().isInteger() &&
5858 (N1C->isNullValue() || // (a < 0) ? b : 0
5859 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
5860 EVT XType = N0.getValueType();
5861 EVT AType = N2.getValueType();
5862 if (XType.bitsGE(AType)) {
5863 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
5864 // single-bit constant.
5865 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
5866 unsigned ShCtV = N2C->getAPIntValue().logBase2();
5867 ShCtV = XType.getSizeInBits()-ShCtV-1;
5868 SDValue ShCt = DAG.getConstant(ShCtV, getShiftAmountTy());
5869 SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(),
5871 AddToWorkList(Shift.getNode());
5873 if (XType.bitsGT(AType)) {
5874 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
5875 AddToWorkList(Shift.getNode());
5878 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
5881 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(),
5883 DAG.getConstant(XType.getSizeInBits()-1,
5884 getShiftAmountTy()));
5885 AddToWorkList(Shift.getNode());
5887 if (XType.bitsGT(AType)) {
5888 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
5889 AddToWorkList(Shift.getNode());
5892 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
5896 // fold select C, 16, 0 -> shl C, 4
5897 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
5898 TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent) {
5900 // If the caller doesn't want us to simplify this into a zext of a compare,
5902 if (NotExtCompare && N2C->getAPIntValue() == 1)
5905 // Get a SetCC of the condition
5906 // FIXME: Should probably make sure that setcc is legal if we ever have a
5907 // target where it isn't.
5909 // cast from setcc result type to select result type
5911 SCC = DAG.getSetCC(DL, TLI.getSetCCResultType(N0.getValueType()),
5913 if (N2.getValueType().bitsLT(SCC.getValueType()))
5914 Temp = DAG.getZeroExtendInReg(SCC, N2.getDebugLoc(), N2.getValueType());
5916 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
5917 N2.getValueType(), SCC);
5919 SCC = DAG.getSetCC(N0.getDebugLoc(), MVT::i1, N0, N1, CC);
5920 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
5921 N2.getValueType(), SCC);
5924 AddToWorkList(SCC.getNode());
5925 AddToWorkList(Temp.getNode());
5927 if (N2C->getAPIntValue() == 1)
5930 // shl setcc result by log2 n2c
5931 return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
5932 DAG.getConstant(N2C->getAPIntValue().logBase2(),
5933 getShiftAmountTy()));
5936 // Check to see if this is the equivalent of setcc
5937 // FIXME: Turn all of these into setcc if setcc if setcc is legal
5938 // otherwise, go ahead with the folds.
5939 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
5940 EVT XType = N0.getValueType();
5941 if (!LegalOperations ||
5942 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(XType))) {
5943 SDValue Res = DAG.getSetCC(DL, TLI.getSetCCResultType(XType), N0, N1, CC);
5944 if (Res.getValueType() != VT)
5945 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
5949 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
5950 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
5951 (!LegalOperations ||
5952 TLI.isOperationLegal(ISD::CTLZ, XType))) {
5953 SDValue Ctlz = DAG.getNode(ISD::CTLZ, N0.getDebugLoc(), XType, N0);
5954 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
5955 DAG.getConstant(Log2_32(XType.getSizeInBits()),
5956 getShiftAmountTy()));
5958 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
5959 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
5960 SDValue NegN0 = DAG.getNode(ISD::SUB, N0.getDebugLoc(),
5961 XType, DAG.getConstant(0, XType), N0);
5962 SDValue NotN0 = DAG.getNOT(N0.getDebugLoc(), N0, XType);
5963 return DAG.getNode(ISD::SRL, DL, XType,
5964 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
5965 DAG.getConstant(XType.getSizeInBits()-1,
5966 getShiftAmountTy()));
5968 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
5969 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
5970 SDValue Sign = DAG.getNode(ISD::SRL, N0.getDebugLoc(), XType, N0,
5971 DAG.getConstant(XType.getSizeInBits()-1,
5972 getShiftAmountTy()));
5973 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
5977 // Check to see if this is an integer abs. select_cc setl[te] X, 0, -X, X ->
5978 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5979 if (N1C && N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE) &&
5980 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1) &&
5981 N2.getOperand(0) == N1 && N0.getValueType().isInteger()) {
5982 EVT XType = N0.getValueType();
5983 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType, N0,
5984 DAG.getConstant(XType.getSizeInBits()-1,
5985 getShiftAmountTy()));
5986 SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(), XType,
5988 AddToWorkList(Shift.getNode());
5989 AddToWorkList(Add.getNode());
5990 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
5992 // Check to see if this is an integer abs. select_cc setgt X, -1, X, -X ->
5993 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5994 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT &&
5995 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) {
5996 if (ConstantSDNode *SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0))) {
5997 EVT XType = N0.getValueType();
5998 if (SubC->isNullValue() && XType.isInteger()) {
5999 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType,
6001 DAG.getConstant(XType.getSizeInBits()-1,
6002 getShiftAmountTy()));
6003 SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(),
6005 AddToWorkList(Shift.getNode());
6006 AddToWorkList(Add.getNode());
6007 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
6015 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
6016 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
6017 SDValue N1, ISD::CondCode Cond,
6018 DebugLoc DL, bool foldBooleans) {
6019 TargetLowering::DAGCombinerInfo
6020 DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
6021 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
6024 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
6025 /// return a DAG expression to select that will generate the same value by
6026 /// multiplying by a magic number. See:
6027 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
6028 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
6029 std::vector<SDNode*> Built;
6030 SDValue S = TLI.BuildSDIV(N, DAG, &Built);
6032 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
6038 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
6039 /// return a DAG expression to select that will generate the same value by
6040 /// multiplying by a magic number. See:
6041 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
6042 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
6043 std::vector<SDNode*> Built;
6044 SDValue S = TLI.BuildUDIV(N, DAG, &Built);
6046 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
6052 /// FindBaseOffset - Return true if base is a frame index, which is known not
6053 // to alias with anything but itself. Provides base object and offset as results.
6054 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
6055 GlobalValue *&GV, void *&CV) {
6056 // Assume it is a primitive operation.
6057 Base = Ptr; Offset = 0; GV = 0; CV = 0;
6059 // If it's an adding a simple constant then integrate the offset.
6060 if (Base.getOpcode() == ISD::ADD) {
6061 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
6062 Base = Base.getOperand(0);
6063 Offset += C->getZExtValue();
6067 // Return the underlying GlobalValue, and update the Offset. Return false
6068 // for GlobalAddressSDNode since the same GlobalAddress may be represented
6069 // by multiple nodes with different offsets.
6070 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
6071 GV = G->getGlobal();
6072 Offset += G->getOffset();
6076 // Return the underlying Constant value, and update the Offset. Return false
6077 // for ConstantSDNodes since the same constant pool entry may be represented
6078 // by multiple nodes with different offsets.
6079 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
6080 CV = C->isMachineConstantPoolEntry() ? (void *)C->getMachineCPVal()
6081 : (void *)C->getConstVal();
6082 Offset += C->getOffset();
6085 // If it's any of the following then it can't alias with anything but itself.
6086 return isa<FrameIndexSDNode>(Base);
6089 /// isAlias - Return true if there is any possibility that the two addresses
6091 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
6092 const Value *SrcValue1, int SrcValueOffset1,
6093 unsigned SrcValueAlign1,
6094 SDValue Ptr2, int64_t Size2,
6095 const Value *SrcValue2, int SrcValueOffset2,
6096 unsigned SrcValueAlign2) const {
6097 // If they are the same then they must be aliases.
6098 if (Ptr1 == Ptr2) return true;
6100 // Gather base node and offset information.
6101 SDValue Base1, Base2;
6102 int64_t Offset1, Offset2;
6103 GlobalValue *GV1, *GV2;
6105 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
6106 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
6108 // If they have a same base address then check to see if they overlap.
6109 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
6110 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
6112 // If we know what the bases are, and they aren't identical, then we know they
6114 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
6117 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
6118 // compared to the size and offset of the access, we may be able to prove they
6119 // do not alias. This check is conservative for now to catch cases created by
6120 // splitting vector types.
6121 if ((SrcValueAlign1 == SrcValueAlign2) &&
6122 (SrcValueOffset1 != SrcValueOffset2) &&
6123 (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
6124 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
6125 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
6127 // There is no overlap between these relatively aligned accesses of similar
6128 // size, return no alias.
6129 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
6133 if (CombinerGlobalAA) {
6134 // Use alias analysis information.
6135 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
6136 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
6137 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
6138 AliasAnalysis::AliasResult AAResult =
6139 AA.alias(SrcValue1, Overlap1, SrcValue2, Overlap2);
6140 if (AAResult == AliasAnalysis::NoAlias)
6144 // Otherwise we have to assume they alias.
6148 /// FindAliasInfo - Extracts the relevant alias information from the memory
6149 /// node. Returns true if the operand was a load.
6150 bool DAGCombiner::FindAliasInfo(SDNode *N,
6151 SDValue &Ptr, int64_t &Size,
6152 const Value *&SrcValue,
6153 int &SrcValueOffset,
6154 unsigned &SrcValueAlign) const {
6155 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
6156 Ptr = LD->getBasePtr();
6157 Size = LD->getMemoryVT().getSizeInBits() >> 3;
6158 SrcValue = LD->getSrcValue();
6159 SrcValueOffset = LD->getSrcValueOffset();
6160 SrcValueAlign = LD->getOriginalAlignment();
6162 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
6163 Ptr = ST->getBasePtr();
6164 Size = ST->getMemoryVT().getSizeInBits() >> 3;
6165 SrcValue = ST->getSrcValue();
6166 SrcValueOffset = ST->getSrcValueOffset();
6167 SrcValueAlign = ST->getOriginalAlignment();
6169 llvm_unreachable("FindAliasInfo expected a memory operand");
6175 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
6176 /// looking for aliasing nodes and adding them to the Aliases vector.
6177 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
6178 SmallVector<SDValue, 8> &Aliases) {
6179 SmallVector<SDValue, 8> Chains; // List of chains to visit.
6180 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
6182 // Get alias information for node.
6185 const Value *SrcValue;
6187 unsigned SrcValueAlign;
6188 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset,
6192 Chains.push_back(OriginalChain);
6195 // Look at each chain and determine if it is an alias. If so, add it to the
6196 // aliases list. If not, then continue up the chain looking for the next
6198 while (!Chains.empty()) {
6199 SDValue Chain = Chains.back();
6202 // For TokenFactor nodes, look at each operand and only continue up the
6203 // chain until we find two aliases. If we've seen two aliases, assume we'll
6204 // find more and revert to original chain since the xform is unlikely to be
6207 // FIXME: The depth check could be made to return the last non-aliasing
6208 // chain we found before we hit a tokenfactor rather than the original
6210 if (Depth > 6 || Aliases.size() == 2) {
6212 Aliases.push_back(OriginalChain);
6216 // Don't bother if we've been before.
6217 if (!Visited.insert(Chain.getNode()))
6220 switch (Chain.getOpcode()) {
6221 case ISD::EntryToken:
6222 // Entry token is ideal chain operand, but handled in FindBetterChain.
6227 // Get alias information for Chain.
6230 const Value *OpSrcValue;
6231 int OpSrcValueOffset;
6232 unsigned OpSrcValueAlign;
6233 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
6234 OpSrcValue, OpSrcValueOffset,
6237 // If chain is alias then stop here.
6238 if (!(IsLoad && IsOpLoad) &&
6239 isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign,
6240 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset,
6242 Aliases.push_back(Chain);
6244 // Look further up the chain.
6245 Chains.push_back(Chain.getOperand(0));
6251 case ISD::TokenFactor:
6252 // We have to check each of the operands of the token factor for "small"
6253 // token factors, so we queue them up. Adding the operands to the queue
6254 // (stack) in reverse order maintains the original order and increases the
6255 // likelihood that getNode will find a matching token factor (CSE.)
6256 if (Chain.getNumOperands() > 16) {
6257 Aliases.push_back(Chain);
6260 for (unsigned n = Chain.getNumOperands(); n;)
6261 Chains.push_back(Chain.getOperand(--n));
6266 // For all other instructions we will just have to take what we can get.
6267 Aliases.push_back(Chain);
6273 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
6274 /// for a better chain (aliasing node.)
6275 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
6276 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
6278 // Accumulate all the aliases to this node.
6279 GatherAllAliases(N, OldChain, Aliases);
6281 if (Aliases.size() == 0) {
6282 // If no operands then chain to entry token.
6283 return DAG.getEntryNode();
6284 } else if (Aliases.size() == 1) {
6285 // If a single operand then chain to it. We don't need to revisit it.
6289 // Construct a custom tailored token factor.
6290 return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
6291 &Aliases[0], Aliases.size());
6294 // SelectionDAG::Combine - This is the entry point for the file.
6296 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
6297 CodeGenOpt::Level OptLevel) {
6298 /// run - This is the main entry point to this class.
6300 DAGCombiner(*this, AA, OptLevel).Run(Level);