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 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
123 APInt Demanded = APInt::getAllOnesValue(BitWidth);
124 return SimplifyDemandedBits(Op, Demanded);
127 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
129 bool CombineToPreIndexedLoadStore(SDNode *N);
130 bool CombineToPostIndexedLoadStore(SDNode *N);
132 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
133 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
134 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
135 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
136 SDValue PromoteIntBinOp(SDValue Op);
137 SDValue PromoteIntShiftOp(SDValue Op);
138 SDValue PromoteExtend(SDValue Op);
139 bool PromoteLoad(SDValue Op);
141 /// combine - call the node-specific routine that knows how to fold each
142 /// particular type of node. If that doesn't do anything, try the
143 /// target-specific DAG combines.
144 SDValue combine(SDNode *N);
146 // Visitation implementation - Implement dag node combining for different
147 // node types. The semantics are as follows:
149 // SDValue.getNode() == 0 - No change was made
150 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
151 // otherwise - N should be replaced by the returned Operand.
153 SDValue visitTokenFactor(SDNode *N);
154 SDValue visitMERGE_VALUES(SDNode *N);
155 SDValue visitADD(SDNode *N);
156 SDValue visitSUB(SDNode *N);
157 SDValue visitADDC(SDNode *N);
158 SDValue visitADDE(SDNode *N);
159 SDValue visitMUL(SDNode *N);
160 SDValue visitSDIV(SDNode *N);
161 SDValue visitUDIV(SDNode *N);
162 SDValue visitSREM(SDNode *N);
163 SDValue visitUREM(SDNode *N);
164 SDValue visitMULHU(SDNode *N);
165 SDValue visitMULHS(SDNode *N);
166 SDValue visitSMUL_LOHI(SDNode *N);
167 SDValue visitUMUL_LOHI(SDNode *N);
168 SDValue visitSDIVREM(SDNode *N);
169 SDValue visitUDIVREM(SDNode *N);
170 SDValue visitAND(SDNode *N);
171 SDValue visitOR(SDNode *N);
172 SDValue visitXOR(SDNode *N);
173 SDValue SimplifyVBinOp(SDNode *N);
174 SDValue visitSHL(SDNode *N);
175 SDValue visitSRA(SDNode *N);
176 SDValue visitSRL(SDNode *N);
177 SDValue visitCTLZ(SDNode *N);
178 SDValue visitCTTZ(SDNode *N);
179 SDValue visitCTPOP(SDNode *N);
180 SDValue visitSELECT(SDNode *N);
181 SDValue visitSELECT_CC(SDNode *N);
182 SDValue visitSETCC(SDNode *N);
183 SDValue visitSIGN_EXTEND(SDNode *N);
184 SDValue visitZERO_EXTEND(SDNode *N);
185 SDValue visitANY_EXTEND(SDNode *N);
186 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
187 SDValue visitTRUNCATE(SDNode *N);
188 SDValue visitBIT_CONVERT(SDNode *N);
189 SDValue visitBUILD_PAIR(SDNode *N);
190 SDValue visitFADD(SDNode *N);
191 SDValue visitFSUB(SDNode *N);
192 SDValue visitFMUL(SDNode *N);
193 SDValue visitFDIV(SDNode *N);
194 SDValue visitFREM(SDNode *N);
195 SDValue visitFCOPYSIGN(SDNode *N);
196 SDValue visitSINT_TO_FP(SDNode *N);
197 SDValue visitUINT_TO_FP(SDNode *N);
198 SDValue visitFP_TO_SINT(SDNode *N);
199 SDValue visitFP_TO_UINT(SDNode *N);
200 SDValue visitFP_ROUND(SDNode *N);
201 SDValue visitFP_ROUND_INREG(SDNode *N);
202 SDValue visitFP_EXTEND(SDNode *N);
203 SDValue visitFNEG(SDNode *N);
204 SDValue visitFABS(SDNode *N);
205 SDValue visitBRCOND(SDNode *N);
206 SDValue visitBR_CC(SDNode *N);
207 SDValue visitLOAD(SDNode *N);
208 SDValue visitSTORE(SDNode *N);
209 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
210 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
211 SDValue visitBUILD_VECTOR(SDNode *N);
212 SDValue visitCONCAT_VECTORS(SDNode *N);
213 SDValue visitVECTOR_SHUFFLE(SDNode *N);
215 SDValue XformToShuffleWithZero(SDNode *N);
216 SDValue ReassociateOps(unsigned Opc, DebugLoc DL, SDValue LHS, SDValue RHS);
218 SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
220 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
221 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
222 SDValue SimplifySelect(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2);
223 SDValue SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2,
224 SDValue N3, ISD::CondCode CC,
225 bool NotExtCompare = false);
226 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
227 DebugLoc DL, bool foldBooleans = true);
228 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
230 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
231 SDValue ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *, EVT);
232 SDValue BuildSDIV(SDNode *N);
233 SDValue BuildUDIV(SDNode *N);
234 SDNode *MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL);
235 SDValue ReduceLoadWidth(SDNode *N);
236 SDValue ReduceLoadOpStoreWidth(SDNode *N);
238 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
240 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
241 /// looking for aliasing nodes and adding them to the Aliases vector.
242 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
243 SmallVector<SDValue, 8> &Aliases);
245 /// isAlias - Return true if there is any possibility that the two addresses
247 bool isAlias(SDValue Ptr1, int64_t Size1,
248 const Value *SrcValue1, int SrcValueOffset1,
249 unsigned SrcValueAlign1,
250 SDValue Ptr2, int64_t Size2,
251 const Value *SrcValue2, int SrcValueOffset2,
252 unsigned SrcValueAlign2) const;
254 /// FindAliasInfo - Extracts the relevant alias information from the memory
255 /// node. Returns true if the operand was a load.
256 bool FindAliasInfo(SDNode *N,
257 SDValue &Ptr, int64_t &Size,
258 const Value *&SrcValue, int &SrcValueOffset,
259 unsigned &SrcValueAlignment) const;
261 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
262 /// looking for a better chain (aliasing node.)
263 SDValue FindBetterChain(SDNode *N, SDValue Chain);
266 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
267 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(Unrestricted),
268 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {}
270 /// Run - runs the dag combiner on all nodes in the work list
271 void Run(CombineLevel AtLevel);
273 SelectionDAG &getDAG() const { return DAG; }
275 /// getShiftAmountTy - Returns a type large enough to hold any valid
276 /// shift amount - before type legalization these can be huge.
277 EVT getShiftAmountTy() {
278 return LegalTypes ? TLI.getShiftAmountTy() : TLI.getPointerTy();
281 /// isTypeLegal - This method returns true if we are running before type
282 /// legalization or if the specified VT is legal.
283 bool isTypeLegal(const EVT &VT) {
284 if (!LegalTypes) return true;
285 return TLI.isTypeLegal(VT);
292 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
293 /// nodes from the worklist.
294 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
297 explicit WorkListRemover(DAGCombiner &dc) : DC(dc) {}
299 virtual void NodeDeleted(SDNode *N, SDNode *E) {
300 DC.removeFromWorkList(N);
303 virtual void NodeUpdated(SDNode *N) {
309 //===----------------------------------------------------------------------===//
310 // TargetLowering::DAGCombinerInfo implementation
311 //===----------------------------------------------------------------------===//
313 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
314 ((DAGCombiner*)DC)->AddToWorkList(N);
317 SDValue TargetLowering::DAGCombinerInfo::
318 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
319 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
322 SDValue TargetLowering::DAGCombinerInfo::
323 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
324 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
328 SDValue TargetLowering::DAGCombinerInfo::
329 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
330 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
333 void TargetLowering::DAGCombinerInfo::
334 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
335 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
338 //===----------------------------------------------------------------------===//
340 //===----------------------------------------------------------------------===//
342 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
343 /// specified expression for the same cost as the expression itself, or 2 if we
344 /// can compute the negated form more cheaply than the expression itself.
345 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
346 unsigned Depth = 0) {
347 // No compile time optimizations on this type.
348 if (Op.getValueType() == MVT::ppcf128)
351 // fneg is removable even if it has multiple uses.
352 if (Op.getOpcode() == ISD::FNEG) return 2;
354 // Don't allow anything with multiple uses.
355 if (!Op.hasOneUse()) return 0;
357 // Don't recurse exponentially.
358 if (Depth > 6) return 0;
360 switch (Op.getOpcode()) {
361 default: return false;
362 case ISD::ConstantFP:
363 // Don't invert constant FP values after legalize. The negated constant
364 // isn't necessarily legal.
365 return LegalOperations ? 0 : 1;
367 // FIXME: determine better conditions for this xform.
368 if (!UnsafeFPMath) return 0;
370 // fold (fsub (fadd A, B)) -> (fsub (fneg A), B)
371 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
373 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
374 return isNegatibleForFree(Op.getOperand(1), LegalOperations, Depth+1);
376 // We can't turn -(A-B) into B-A when we honor signed zeros.
377 if (!UnsafeFPMath) return 0;
379 // fold (fneg (fsub A, B)) -> (fsub B, A)
384 if (HonorSignDependentRoundingFPMath()) return 0;
386 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
387 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
390 return isNegatibleForFree(Op.getOperand(1), LegalOperations, Depth+1);
395 return isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1);
399 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
400 /// returns the newly negated expression.
401 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
402 bool LegalOperations, unsigned Depth = 0) {
403 // fneg is removable even if it has multiple uses.
404 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
406 // Don't allow anything with multiple uses.
407 assert(Op.hasOneUse() && "Unknown reuse!");
409 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
410 switch (Op.getOpcode()) {
411 default: llvm_unreachable("Unknown code");
412 case ISD::ConstantFP: {
413 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
415 return DAG.getConstantFP(V, Op.getValueType());
418 // FIXME: determine better conditions for this xform.
419 assert(UnsafeFPMath);
421 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
422 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
423 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
424 GetNegatedExpression(Op.getOperand(0), DAG,
425 LegalOperations, Depth+1),
427 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
428 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
429 GetNegatedExpression(Op.getOperand(1), DAG,
430 LegalOperations, Depth+1),
433 // We can't turn -(A-B) into B-A when we honor signed zeros.
434 assert(UnsafeFPMath);
436 // fold (fneg (fsub 0, B)) -> B
437 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
438 if (N0CFP->getValueAPF().isZero())
439 return Op.getOperand(1);
441 // fold (fneg (fsub A, B)) -> (fsub B, A)
442 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
443 Op.getOperand(1), Op.getOperand(0));
447 assert(!HonorSignDependentRoundingFPMath());
449 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
450 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
451 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
452 GetNegatedExpression(Op.getOperand(0), DAG,
453 LegalOperations, Depth+1),
456 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
457 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
459 GetNegatedExpression(Op.getOperand(1), DAG,
460 LegalOperations, Depth+1));
464 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
465 GetNegatedExpression(Op.getOperand(0), DAG,
466 LegalOperations, Depth+1));
468 return DAG.getNode(ISD::FP_ROUND, Op.getDebugLoc(), Op.getValueType(),
469 GetNegatedExpression(Op.getOperand(0), DAG,
470 LegalOperations, Depth+1),
476 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
477 // that selects between the values 1 and 0, making it equivalent to a setcc.
478 // Also, set the incoming LHS, RHS, and CC references to the appropriate
479 // nodes based on the type of node we are checking. This simplifies life a
480 // bit for the callers.
481 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
483 if (N.getOpcode() == ISD::SETCC) {
484 LHS = N.getOperand(0);
485 RHS = N.getOperand(1);
486 CC = N.getOperand(2);
489 if (N.getOpcode() == ISD::SELECT_CC &&
490 N.getOperand(2).getOpcode() == ISD::Constant &&
491 N.getOperand(3).getOpcode() == ISD::Constant &&
492 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
493 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
494 LHS = N.getOperand(0);
495 RHS = N.getOperand(1);
496 CC = N.getOperand(4);
502 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
503 // one use. If this is true, it allows the users to invert the operation for
504 // free when it is profitable to do so.
505 static bool isOneUseSetCC(SDValue N) {
507 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
512 SDValue DAGCombiner::ReassociateOps(unsigned Opc, DebugLoc DL,
513 SDValue N0, SDValue N1) {
514 EVT VT = N0.getValueType();
515 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
516 if (isa<ConstantSDNode>(N1)) {
517 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
519 DAG.FoldConstantArithmetic(Opc, VT,
520 cast<ConstantSDNode>(N0.getOperand(1)),
521 cast<ConstantSDNode>(N1));
522 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
523 } else if (N0.hasOneUse()) {
524 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
525 SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
526 N0.getOperand(0), N1);
527 AddToWorkList(OpNode.getNode());
528 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
532 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
533 if (isa<ConstantSDNode>(N0)) {
534 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
536 DAG.FoldConstantArithmetic(Opc, VT,
537 cast<ConstantSDNode>(N1.getOperand(1)),
538 cast<ConstantSDNode>(N0));
539 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
540 } else if (N1.hasOneUse()) {
541 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
542 SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
543 N1.getOperand(0), N0);
544 AddToWorkList(OpNode.getNode());
545 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
552 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
554 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
556 DEBUG(dbgs() << "\nReplacing.1 ";
558 dbgs() << "\nWith: ";
559 To[0].getNode()->dump(&DAG);
560 dbgs() << " and " << NumTo-1 << " other values\n";
561 for (unsigned i = 0, e = NumTo; i != e; ++i)
562 assert((!To[i].getNode() ||
563 N->getValueType(i) == To[i].getValueType()) &&
564 "Cannot combine value to value of different type!"));
565 WorkListRemover DeadNodes(*this);
566 DAG.ReplaceAllUsesWith(N, To, &DeadNodes);
569 // Push the new nodes and any users onto the worklist
570 for (unsigned i = 0, e = NumTo; i != e; ++i) {
571 if (To[i].getNode()) {
572 AddToWorkList(To[i].getNode());
573 AddUsersToWorkList(To[i].getNode());
578 // Finally, if the node is now dead, remove it from the graph. The node
579 // may not be dead if the replacement process recursively simplified to
580 // something else needing this node.
581 if (N->use_empty()) {
582 // Nodes can be reintroduced into the worklist. Make sure we do not
583 // process a node that has been replaced.
584 removeFromWorkList(N);
586 // Finally, since the node is now dead, remove it from the graph.
589 return SDValue(N, 0);
593 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
594 // Replace all uses. If any nodes become isomorphic to other nodes and
595 // are deleted, make sure to remove them from our worklist.
596 WorkListRemover DeadNodes(*this);
597 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, &DeadNodes);
599 // Push the new node and any (possibly new) users onto the worklist.
600 AddToWorkList(TLO.New.getNode());
601 AddUsersToWorkList(TLO.New.getNode());
603 // Finally, if the node is now dead, remove it from the graph. The node
604 // may not be dead if the replacement process recursively simplified to
605 // something else needing this node.
606 if (TLO.Old.getNode()->use_empty()) {
607 removeFromWorkList(TLO.Old.getNode());
609 // If the operands of this node are only used by the node, they will now
610 // be dead. Make sure to visit them first to delete dead nodes early.
611 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
612 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
613 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
615 DAG.DeleteNode(TLO.Old.getNode());
619 /// SimplifyDemandedBits - Check the specified integer node value to see if
620 /// it can be simplified or if things it uses can be simplified by bit
621 /// propagation. If so, return true.
622 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
623 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
624 APInt KnownZero, KnownOne;
625 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
629 AddToWorkList(Op.getNode());
631 // Replace the old value with the new one.
633 DEBUG(dbgs() << "\nReplacing.2 ";
634 TLO.Old.getNode()->dump(&DAG);
635 dbgs() << "\nWith: ";
636 TLO.New.getNode()->dump(&DAG);
639 CommitTargetLoweringOpt(TLO);
643 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
644 DebugLoc dl = Load->getDebugLoc();
645 EVT VT = Load->getValueType(0);
646 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
648 DEBUG(dbgs() << "\nReplacing.9 ";
650 dbgs() << "\nWith: ";
651 Trunc.getNode()->dump(&DAG);
653 WorkListRemover DeadNodes(*this);
654 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc, &DeadNodes);
655 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1),
657 removeFromWorkList(Load);
658 DAG.DeleteNode(Load);
661 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
663 DebugLoc dl = Op.getDebugLoc();
664 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
665 ISD::LoadExtType ExtType =
666 ISD::isNON_EXTLoad(LD) ? ISD::EXTLOAD : LD->getExtensionType();
668 return DAG.getExtLoad(ExtType, dl, PVT,
669 LD->getChain(), LD->getBasePtr(),
670 LD->getSrcValue(), LD->getSrcValueOffset(),
671 LD->getMemoryVT(), LD->isVolatile(),
672 LD->isNonTemporal(), LD->getAlignment());
675 unsigned Opc = Op.getOpcode();
678 case ISD::AssertSext:
679 return DAG.getNode(ISD::AssertSext, dl, PVT,
680 SExtPromoteOperand(Op.getOperand(0), PVT),
682 case ISD::AssertZext:
683 return DAG.getNode(ISD::AssertZext, dl, PVT,
684 ZExtPromoteOperand(Op.getOperand(0), PVT),
686 case ISD::Constant: {
688 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
689 return DAG.getNode(ExtOpc, dl, PVT, Op);
693 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
695 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
698 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
699 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
701 EVT OldVT = Op.getValueType();
702 DebugLoc dl = Op.getDebugLoc();
703 bool Replace = false;
704 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
705 if (NewOp.getNode() == 0)
709 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
710 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
711 DAG.getValueType(OldVT));
714 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
715 EVT OldVT = Op.getValueType();
716 DebugLoc dl = Op.getDebugLoc();
717 bool Replace = false;
718 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
719 if (NewOp.getNode() == 0)
723 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
724 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
727 /// PromoteIntBinOp - Promote the specified integer binary operation if the
728 /// target indicates it is beneficial. e.g. On x86, it's usually better to
729 /// promote i16 operations to i32 since i16 instructions are longer.
730 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
731 if (!LegalOperations)
734 EVT VT = Op.getValueType();
735 if (VT.isVector() || !VT.isInteger())
738 // If operation type is 'undesirable', e.g. i16 on x86, consider
740 unsigned Opc = Op.getOpcode();
741 if (TLI.isTypeDesirableForOp(Opc, VT))
745 // Consult target whether it is a good idea to promote this operation and
746 // what's the right type to promote it to.
747 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
748 assert(PVT != VT && "Don't know what type to promote to!");
750 bool Replace0 = false;
751 SDValue N0 = Op.getOperand(0);
752 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
753 if (NN0.getNode() == 0)
756 bool Replace1 = false;
757 SDValue N1 = Op.getOperand(1);
758 SDValue NN1 = PromoteOperand(N1, PVT, Replace1);
759 if (NN1.getNode() == 0)
762 AddToWorkList(NN0.getNode());
763 AddToWorkList(NN1.getNode());
766 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
768 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
770 DebugLoc dl = Op.getDebugLoc();
771 return DAG.getNode(ISD::TRUNCATE, dl, VT,
772 DAG.getNode(Opc, dl, PVT, NN0, NN1));
777 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
778 /// target indicates it is beneficial. e.g. On x86, it's usually better to
779 /// promote i16 operations to i32 since i16 instructions are longer.
780 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
781 if (!LegalOperations)
784 EVT VT = Op.getValueType();
785 if (VT.isVector() || !VT.isInteger())
788 // If operation type is 'undesirable', e.g. i16 on x86, consider
790 unsigned Opc = Op.getOpcode();
791 if (TLI.isTypeDesirableForOp(Opc, VT))
795 // Consult target whether it is a good idea to promote this operation and
796 // what's the right type to promote it to.
797 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
798 assert(PVT != VT && "Don't know what type to promote to!");
800 bool Replace = false;
801 SDValue N0 = Op.getOperand(0);
803 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
804 else if (Opc == ISD::SRL)
805 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
807 N0 = PromoteOperand(N0, PVT, Replace);
808 if (N0.getNode() == 0)
811 AddToWorkList(N0.getNode());
813 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
815 DebugLoc dl = Op.getDebugLoc();
816 return DAG.getNode(ISD::TRUNCATE, dl, VT,
817 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
822 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
823 if (!LegalOperations)
826 EVT VT = Op.getValueType();
827 if (VT.isVector() || !VT.isInteger())
830 // If operation type is 'undesirable', e.g. i16 on x86, consider
832 unsigned Opc = Op.getOpcode();
833 if (TLI.isTypeDesirableForOp(Opc, VT))
837 // Consult target whether it is a good idea to promote this operation and
838 // what's the right type to promote it to.
839 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
840 assert(PVT != VT && "Don't know what type to promote to!");
841 // fold (aext (aext x)) -> (aext x)
842 // fold (aext (zext x)) -> (zext x)
843 // fold (aext (sext x)) -> (sext x)
844 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), VT, Op.getOperand(0));
849 bool DAGCombiner::PromoteLoad(SDValue Op) {
850 if (!LegalOperations)
853 EVT VT = Op.getValueType();
854 if (VT.isVector() || !VT.isInteger())
857 // If operation type is 'undesirable', e.g. i16 on x86, consider
859 unsigned Opc = Op.getOpcode();
860 if (TLI.isTypeDesirableForOp(Opc, VT))
864 // Consult target whether it is a good idea to promote this operation and
865 // what's the right type to promote it to.
866 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
867 assert(PVT != VT && "Don't know what type to promote to!");
869 DebugLoc dl = Op.getDebugLoc();
870 SDNode *N = Op.getNode();
871 LoadSDNode *LD = cast<LoadSDNode>(N);
872 ISD::LoadExtType ExtType =
873 ISD::isNON_EXTLoad(LD) ? ISD::EXTLOAD : LD->getExtensionType();
874 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
875 LD->getChain(), LD->getBasePtr(),
876 LD->getSrcValue(), LD->getSrcValueOffset(),
877 LD->getMemoryVT(), LD->isVolatile(),
878 LD->isNonTemporal(), LD->getAlignment());
879 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
881 DEBUG(dbgs() << "\nPromoting ";
884 Result.getNode()->dump(&DAG);
886 WorkListRemover DeadNodes(*this);
887 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result, &DeadNodes);
888 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1), &DeadNodes);
889 removeFromWorkList(N);
897 //===----------------------------------------------------------------------===//
898 // Main DAG Combiner implementation
899 //===----------------------------------------------------------------------===//
901 void DAGCombiner::Run(CombineLevel AtLevel) {
902 // set the instance variables, so that the various visit routines may use it.
904 LegalOperations = Level >= NoIllegalOperations;
905 LegalTypes = Level >= NoIllegalTypes;
907 // Add all the dag nodes to the worklist.
908 WorkList.reserve(DAG.allnodes_size());
909 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
910 E = DAG.allnodes_end(); I != E; ++I)
911 WorkList.push_back(I);
913 // Create a dummy node (which is not added to allnodes), that adds a reference
914 // to the root node, preventing it from being deleted, and tracking any
915 // changes of the root.
916 HandleSDNode Dummy(DAG.getRoot());
918 // The root of the dag may dangle to deleted nodes until the dag combiner is
919 // done. Set it to null to avoid confusion.
920 DAG.setRoot(SDValue());
922 // while the worklist isn't empty, inspect the node on the end of it and
923 // try and combine it.
924 while (!WorkList.empty()) {
925 SDNode *N = WorkList.back();
928 // If N has no uses, it is dead. Make sure to revisit all N's operands once
929 // N is deleted from the DAG, since they too may now be dead or may have a
930 // reduced number of uses, allowing other xforms.
931 if (N->use_empty() && N != &Dummy) {
932 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
933 AddToWorkList(N->getOperand(i).getNode());
939 SDValue RV = combine(N);
941 if (RV.getNode() == 0)
946 // If we get back the same node we passed in, rather than a new node or
947 // zero, we know that the node must have defined multiple values and
948 // CombineTo was used. Since CombineTo takes care of the worklist
949 // mechanics for us, we have no work to do in this case.
950 if (RV.getNode() == N)
953 assert(N->getOpcode() != ISD::DELETED_NODE &&
954 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
955 "Node was deleted but visit returned new node!");
957 DEBUG(dbgs() << "\nReplacing.3 ";
959 dbgs() << "\nWith: ";
960 RV.getNode()->dump(&DAG);
962 WorkListRemover DeadNodes(*this);
963 if (N->getNumValues() == RV.getNode()->getNumValues())
964 DAG.ReplaceAllUsesWith(N, RV.getNode(), &DeadNodes);
966 assert(N->getValueType(0) == RV.getValueType() &&
967 N->getNumValues() == 1 && "Type mismatch");
969 DAG.ReplaceAllUsesWith(N, &OpV, &DeadNodes);
972 // Push the new node and any users onto the worklist
973 AddToWorkList(RV.getNode());
974 AddUsersToWorkList(RV.getNode());
976 // Add any uses of the old node to the worklist in case this node is the
977 // last one that uses them. They may become dead after this node is
979 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
980 AddToWorkList(N->getOperand(i).getNode());
982 // Finally, if the node is now dead, remove it from the graph. The node
983 // may not be dead if the replacement process recursively simplified to
984 // something else needing this node.
985 if (N->use_empty()) {
986 // Nodes can be reintroduced into the worklist. Make sure we do not
987 // process a node that has been replaced.
988 removeFromWorkList(N);
990 // Finally, since the node is now dead, remove it from the graph.
995 // If the root changed (e.g. it was a dead load, update the root).
996 DAG.setRoot(Dummy.getValue());
999 SDValue DAGCombiner::visit(SDNode *N) {
1000 switch(N->getOpcode()) {
1002 case ISD::TokenFactor: return visitTokenFactor(N);
1003 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1004 case ISD::ADD: return visitADD(N);
1005 case ISD::SUB: return visitSUB(N);
1006 case ISD::ADDC: return visitADDC(N);
1007 case ISD::ADDE: return visitADDE(N);
1008 case ISD::MUL: return visitMUL(N);
1009 case ISD::SDIV: return visitSDIV(N);
1010 case ISD::UDIV: return visitUDIV(N);
1011 case ISD::SREM: return visitSREM(N);
1012 case ISD::UREM: return visitUREM(N);
1013 case ISD::MULHU: return visitMULHU(N);
1014 case ISD::MULHS: return visitMULHS(N);
1015 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1016 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1017 case ISD::SDIVREM: return visitSDIVREM(N);
1018 case ISD::UDIVREM: return visitUDIVREM(N);
1019 case ISD::AND: return visitAND(N);
1020 case ISD::OR: return visitOR(N);
1021 case ISD::XOR: return visitXOR(N);
1022 case ISD::SHL: return visitSHL(N);
1023 case ISD::SRA: return visitSRA(N);
1024 case ISD::SRL: return visitSRL(N);
1025 case ISD::CTLZ: return visitCTLZ(N);
1026 case ISD::CTTZ: return visitCTTZ(N);
1027 case ISD::CTPOP: return visitCTPOP(N);
1028 case ISD::SELECT: return visitSELECT(N);
1029 case ISD::SELECT_CC: return visitSELECT_CC(N);
1030 case ISD::SETCC: return visitSETCC(N);
1031 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1032 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1033 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1034 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1035 case ISD::TRUNCATE: return visitTRUNCATE(N);
1036 case ISD::BIT_CONVERT: return visitBIT_CONVERT(N);
1037 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1038 case ISD::FADD: return visitFADD(N);
1039 case ISD::FSUB: return visitFSUB(N);
1040 case ISD::FMUL: return visitFMUL(N);
1041 case ISD::FDIV: return visitFDIV(N);
1042 case ISD::FREM: return visitFREM(N);
1043 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1044 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1045 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1046 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1047 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1048 case ISD::FP_ROUND: return visitFP_ROUND(N);
1049 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1050 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1051 case ISD::FNEG: return visitFNEG(N);
1052 case ISD::FABS: return visitFABS(N);
1053 case ISD::BRCOND: return visitBRCOND(N);
1054 case ISD::BR_CC: return visitBR_CC(N);
1055 case ISD::LOAD: return visitLOAD(N);
1056 case ISD::STORE: return visitSTORE(N);
1057 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1058 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1059 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1060 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1061 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1066 SDValue DAGCombiner::combine(SDNode *N) {
1067 SDValue RV = visit(N);
1069 // If nothing happened, try a target-specific DAG combine.
1070 if (RV.getNode() == 0) {
1071 assert(N->getOpcode() != ISD::DELETED_NODE &&
1072 "Node was deleted but visit returned NULL!");
1074 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1075 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1077 // Expose the DAG combiner to the target combiner impls.
1078 TargetLowering::DAGCombinerInfo
1079 DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
1081 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1085 // If N is a commutative binary node, try commuting it to enable more
1087 if (RV.getNode() == 0 &&
1088 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1089 N->getNumValues() == 1) {
1090 SDValue N0 = N->getOperand(0);
1091 SDValue N1 = N->getOperand(1);
1093 // Constant operands are canonicalized to RHS.
1094 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1095 SDValue Ops[] = { N1, N0 };
1096 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1099 return SDValue(CSENode, 0);
1106 /// getInputChainForNode - Given a node, return its input chain if it has one,
1107 /// otherwise return a null sd operand.
1108 static SDValue getInputChainForNode(SDNode *N) {
1109 if (unsigned NumOps = N->getNumOperands()) {
1110 if (N->getOperand(0).getValueType() == MVT::Other)
1111 return N->getOperand(0);
1112 else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1113 return N->getOperand(NumOps-1);
1114 for (unsigned i = 1; i < NumOps-1; ++i)
1115 if (N->getOperand(i).getValueType() == MVT::Other)
1116 return N->getOperand(i);
1121 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1122 // If N has two operands, where one has an input chain equal to the other,
1123 // the 'other' chain is redundant.
1124 if (N->getNumOperands() == 2) {
1125 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1126 return N->getOperand(0);
1127 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1128 return N->getOperand(1);
1131 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1132 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1133 SmallPtrSet<SDNode*, 16> SeenOps;
1134 bool Changed = false; // If we should replace this token factor.
1136 // Start out with this token factor.
1139 // Iterate through token factors. The TFs grows when new token factors are
1141 for (unsigned i = 0; i < TFs.size(); ++i) {
1142 SDNode *TF = TFs[i];
1144 // Check each of the operands.
1145 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1146 SDValue Op = TF->getOperand(i);
1148 switch (Op.getOpcode()) {
1149 case ISD::EntryToken:
1150 // Entry tokens don't need to be added to the list. They are
1155 case ISD::TokenFactor:
1156 if (Op.hasOneUse() &&
1157 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1158 // Queue up for processing.
1159 TFs.push_back(Op.getNode());
1160 // Clean up in case the token factor is removed.
1161 AddToWorkList(Op.getNode());
1168 // Only add if it isn't already in the list.
1169 if (SeenOps.insert(Op.getNode()))
1180 // If we've change things around then replace token factor.
1183 // The entry token is the only possible outcome.
1184 Result = DAG.getEntryNode();
1186 // New and improved token factor.
1187 Result = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
1188 MVT::Other, &Ops[0], Ops.size());
1191 // Don't add users to work list.
1192 return CombineTo(N, Result, false);
1198 /// MERGE_VALUES can always be eliminated.
1199 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1200 WorkListRemover DeadNodes(*this);
1201 // Replacing results may cause a different MERGE_VALUES to suddenly
1202 // be CSE'd with N, and carry its uses with it. Iterate until no
1203 // uses remain, to ensure that the node can be safely deleted.
1205 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1206 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i),
1208 } while (!N->use_empty());
1209 removeFromWorkList(N);
1211 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1215 SDValue combineShlAddConstant(DebugLoc DL, SDValue N0, SDValue N1,
1216 SelectionDAG &DAG) {
1217 EVT VT = N0.getValueType();
1218 SDValue N00 = N0.getOperand(0);
1219 SDValue N01 = N0.getOperand(1);
1220 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1222 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1223 isa<ConstantSDNode>(N00.getOperand(1))) {
1224 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1225 N0 = DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT,
1226 DAG.getNode(ISD::SHL, N00.getDebugLoc(), VT,
1227 N00.getOperand(0), N01),
1228 DAG.getNode(ISD::SHL, N01.getDebugLoc(), VT,
1229 N00.getOperand(1), N01));
1230 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1236 SDValue DAGCombiner::visitADD(SDNode *N) {
1237 SDValue N0 = N->getOperand(0);
1238 SDValue N1 = N->getOperand(1);
1239 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1240 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1241 EVT VT = N0.getValueType();
1244 if (VT.isVector()) {
1245 SDValue FoldedVOp = SimplifyVBinOp(N);
1246 if (FoldedVOp.getNode()) return FoldedVOp;
1249 // fold (add x, undef) -> undef
1250 if (N0.getOpcode() == ISD::UNDEF)
1252 if (N1.getOpcode() == ISD::UNDEF)
1254 // fold (add c1, c2) -> c1+c2
1256 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1257 // canonicalize constant to RHS
1259 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0);
1260 // fold (add x, 0) -> x
1261 if (N1C && N1C->isNullValue())
1263 // fold (add Sym, c) -> Sym+c
1264 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1265 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1266 GA->getOpcode() == ISD::GlobalAddress)
1267 return DAG.getGlobalAddress(GA->getGlobal(), VT,
1269 (uint64_t)N1C->getSExtValue());
1270 // fold ((c1-A)+c2) -> (c1+c2)-A
1271 if (N1C && N0.getOpcode() == ISD::SUB)
1272 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1273 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1274 DAG.getConstant(N1C->getAPIntValue()+
1275 N0C->getAPIntValue(), VT),
1278 SDValue RADD = ReassociateOps(ISD::ADD, N->getDebugLoc(), N0, N1);
1279 if (RADD.getNode() != 0)
1281 // fold ((0-A) + B) -> B-A
1282 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1283 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1284 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1, N0.getOperand(1));
1285 // fold (A + (0-B)) -> A-B
1286 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1287 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1288 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1.getOperand(1));
1289 // fold (A+(B-A)) -> B
1290 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1291 return N1.getOperand(0);
1292 // fold ((B-A)+A) -> B
1293 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1294 return N0.getOperand(0);
1295 // fold (A+(B-(A+C))) to (B-C)
1296 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1297 N0 == N1.getOperand(1).getOperand(0))
1298 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1299 N1.getOperand(1).getOperand(1));
1300 // fold (A+(B-(C+A))) to (B-C)
1301 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1302 N0 == N1.getOperand(1).getOperand(1))
1303 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1304 N1.getOperand(1).getOperand(0));
1305 // fold (A+((B-A)+or-C)) to (B+or-C)
1306 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1307 N1.getOperand(0).getOpcode() == ISD::SUB &&
1308 N0 == N1.getOperand(0).getOperand(1))
1309 return DAG.getNode(N1.getOpcode(), N->getDebugLoc(), VT,
1310 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1312 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1313 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1314 SDValue N00 = N0.getOperand(0);
1315 SDValue N01 = N0.getOperand(1);
1316 SDValue N10 = N1.getOperand(0);
1317 SDValue N11 = N1.getOperand(1);
1319 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1320 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1321 DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT, N00, N10),
1322 DAG.getNode(ISD::ADD, N1.getDebugLoc(), VT, N01, N11));
1325 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1326 return SDValue(N, 0);
1328 // fold (a+b) -> (a|b) iff a and b share no bits.
1329 if (VT.isInteger() && !VT.isVector()) {
1330 APInt LHSZero, LHSOne;
1331 APInt RHSZero, RHSOne;
1332 APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
1333 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1335 if (LHSZero.getBoolValue()) {
1336 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1338 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1339 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1340 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1341 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1342 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1);
1346 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1347 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1348 SDValue Result = combineShlAddConstant(N->getDebugLoc(), N0, N1, DAG);
1349 if (Result.getNode()) return Result;
1351 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1352 SDValue Result = combineShlAddConstant(N->getDebugLoc(), N1, N0, DAG);
1353 if (Result.getNode()) return Result;
1356 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1357 if (N1.getOpcode() == ISD::SHL &&
1358 N1.getOperand(0).getOpcode() == ISD::SUB)
1359 if (ConstantSDNode *C =
1360 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1361 if (C->getAPIntValue() == 0)
1362 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0,
1363 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1364 N1.getOperand(0).getOperand(1),
1366 if (N0.getOpcode() == ISD::SHL &&
1367 N0.getOperand(0).getOpcode() == ISD::SUB)
1368 if (ConstantSDNode *C =
1369 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1370 if (C->getAPIntValue() == 0)
1371 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1,
1372 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1373 N0.getOperand(0).getOperand(1),
1376 return PromoteIntBinOp(SDValue(N, 0));
1379 SDValue DAGCombiner::visitADDC(SDNode *N) {
1380 SDValue N0 = N->getOperand(0);
1381 SDValue N1 = N->getOperand(1);
1382 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1383 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1384 EVT VT = N0.getValueType();
1386 // If the flag result is dead, turn this into an ADD.
1387 if (N->hasNUsesOfValue(0, 1))
1388 return CombineTo(N, DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0),
1389 DAG.getNode(ISD::CARRY_FALSE,
1390 N->getDebugLoc(), MVT::Flag));
1392 // canonicalize constant to RHS.
1394 return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
1396 // fold (addc x, 0) -> x + no carry out
1397 if (N1C && N1C->isNullValue())
1398 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1399 N->getDebugLoc(), MVT::Flag));
1401 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1402 APInt LHSZero, LHSOne;
1403 APInt RHSZero, RHSOne;
1404 APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
1405 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1407 if (LHSZero.getBoolValue()) {
1408 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1410 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1411 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1412 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1413 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1414 return CombineTo(N, DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1),
1415 DAG.getNode(ISD::CARRY_FALSE,
1416 N->getDebugLoc(), MVT::Flag));
1422 SDValue DAGCombiner::visitADDE(SDNode *N) {
1423 SDValue N0 = N->getOperand(0);
1424 SDValue N1 = N->getOperand(1);
1425 SDValue CarryIn = N->getOperand(2);
1426 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1427 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1429 // canonicalize constant to RHS
1431 return DAG.getNode(ISD::ADDE, N->getDebugLoc(), N->getVTList(),
1434 // fold (adde x, y, false) -> (addc x, y)
1435 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1436 return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
1441 SDValue DAGCombiner::visitSUB(SDNode *N) {
1442 SDValue N0 = N->getOperand(0);
1443 SDValue N1 = N->getOperand(1);
1444 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1445 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1446 EVT VT = N0.getValueType();
1449 if (VT.isVector()) {
1450 SDValue FoldedVOp = SimplifyVBinOp(N);
1451 if (FoldedVOp.getNode()) return FoldedVOp;
1454 // fold (sub x, x) -> 0
1456 return DAG.getConstant(0, N->getValueType(0));
1457 // fold (sub c1, c2) -> c1-c2
1459 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1460 // fold (sub x, c) -> (add x, -c)
1462 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0,
1463 DAG.getConstant(-N1C->getAPIntValue(), VT));
1464 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1465 if (N0C && N0C->isAllOnesValue())
1466 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
1467 // fold (A+B)-A -> B
1468 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1469 return N0.getOperand(1);
1470 // fold (A+B)-B -> A
1471 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1472 return N0.getOperand(0);
1473 // fold ((A+(B+or-C))-B) -> A+or-C
1474 if (N0.getOpcode() == ISD::ADD &&
1475 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1476 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1477 N0.getOperand(1).getOperand(0) == N1)
1478 return DAG.getNode(N0.getOperand(1).getOpcode(), N->getDebugLoc(), VT,
1479 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1480 // fold ((A+(C+B))-B) -> A+C
1481 if (N0.getOpcode() == ISD::ADD &&
1482 N0.getOperand(1).getOpcode() == ISD::ADD &&
1483 N0.getOperand(1).getOperand(1) == N1)
1484 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1485 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1486 // fold ((A-(B-C))-C) -> A-B
1487 if (N0.getOpcode() == ISD::SUB &&
1488 N0.getOperand(1).getOpcode() == ISD::SUB &&
1489 N0.getOperand(1).getOperand(1) == N1)
1490 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1491 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1493 // If either operand of a sub is undef, the result is undef
1494 if (N0.getOpcode() == ISD::UNDEF)
1496 if (N1.getOpcode() == ISD::UNDEF)
1499 // If the relocation model supports it, consider symbol offsets.
1500 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1501 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1502 // fold (sub Sym, c) -> Sym-c
1503 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1504 return DAG.getGlobalAddress(GA->getGlobal(), VT,
1506 (uint64_t)N1C->getSExtValue());
1507 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1508 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1509 if (GA->getGlobal() == GB->getGlobal())
1510 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1514 return PromoteIntBinOp(SDValue(N, 0));
1517 SDValue DAGCombiner::visitMUL(SDNode *N) {
1518 SDValue N0 = N->getOperand(0);
1519 SDValue N1 = N->getOperand(1);
1520 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1521 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1522 EVT VT = N0.getValueType();
1525 if (VT.isVector()) {
1526 SDValue FoldedVOp = SimplifyVBinOp(N);
1527 if (FoldedVOp.getNode()) return FoldedVOp;
1530 // fold (mul x, undef) -> 0
1531 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1532 return DAG.getConstant(0, VT);
1533 // fold (mul c1, c2) -> c1*c2
1535 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0C, N1C);
1536 // canonicalize constant to RHS
1538 return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, N1, N0);
1539 // fold (mul x, 0) -> 0
1540 if (N1C && N1C->isNullValue())
1542 // fold (mul x, -1) -> 0-x
1543 if (N1C && N1C->isAllOnesValue())
1544 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1545 DAG.getConstant(0, VT), N0);
1546 // fold (mul x, (1 << c)) -> x << c
1547 if (N1C && N1C->getAPIntValue().isPowerOf2())
1548 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1549 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1550 getShiftAmountTy()));
1551 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1552 if (N1C && (-N1C->getAPIntValue()).isPowerOf2()) {
1553 unsigned Log2Val = (-N1C->getAPIntValue()).logBase2();
1554 // FIXME: If the input is something that is easily negated (e.g. a
1555 // single-use add), we should put the negate there.
1556 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1557 DAG.getConstant(0, VT),
1558 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1559 DAG.getConstant(Log2Val, getShiftAmountTy())));
1561 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1562 if (N1C && N0.getOpcode() == ISD::SHL &&
1563 isa<ConstantSDNode>(N0.getOperand(1))) {
1564 SDValue C3 = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1565 N1, N0.getOperand(1));
1566 AddToWorkList(C3.getNode());
1567 return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1568 N0.getOperand(0), C3);
1571 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1574 SDValue Sh(0,0), Y(0,0);
1575 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1576 if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1577 N0.getNode()->hasOneUse()) {
1579 } else if (N1.getOpcode() == ISD::SHL &&
1580 isa<ConstantSDNode>(N1.getOperand(1)) &&
1581 N1.getNode()->hasOneUse()) {
1586 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1587 Sh.getOperand(0), Y);
1588 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1589 Mul, Sh.getOperand(1));
1593 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1594 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1595 isa<ConstantSDNode>(N0.getOperand(1)))
1596 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1597 DAG.getNode(ISD::MUL, N0.getDebugLoc(), VT,
1598 N0.getOperand(0), N1),
1599 DAG.getNode(ISD::MUL, N1.getDebugLoc(), VT,
1600 N0.getOperand(1), N1));
1603 SDValue RMUL = ReassociateOps(ISD::MUL, N->getDebugLoc(), N0, N1);
1604 if (RMUL.getNode() != 0)
1607 return PromoteIntBinOp(SDValue(N, 0));
1610 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1611 SDValue N0 = N->getOperand(0);
1612 SDValue N1 = N->getOperand(1);
1613 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1614 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1615 EVT VT = N->getValueType(0);
1618 if (VT.isVector()) {
1619 SDValue FoldedVOp = SimplifyVBinOp(N);
1620 if (FoldedVOp.getNode()) return FoldedVOp;
1623 // fold (sdiv c1, c2) -> c1/c2
1624 if (N0C && N1C && !N1C->isNullValue())
1625 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1626 // fold (sdiv X, 1) -> X
1627 if (N1C && N1C->getSExtValue() == 1LL)
1629 // fold (sdiv X, -1) -> 0-X
1630 if (N1C && N1C->isAllOnesValue())
1631 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1632 DAG.getConstant(0, VT), N0);
1633 // If we know the sign bits of both operands are zero, strength reduce to a
1634 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1635 if (!VT.isVector()) {
1636 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1637 return DAG.getNode(ISD::UDIV, N->getDebugLoc(), N1.getValueType(),
1640 // fold (sdiv X, pow2) -> simple ops after legalize
1641 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap() &&
1642 (isPowerOf2_64(N1C->getSExtValue()) ||
1643 isPowerOf2_64(-N1C->getSExtValue()))) {
1644 // If dividing by powers of two is cheap, then don't perform the following
1646 if (TLI.isPow2DivCheap())
1649 int64_t pow2 = N1C->getSExtValue();
1650 int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
1651 unsigned lg2 = Log2_64(abs2);
1653 // Splat the sign bit into the register
1654 SDValue SGN = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
1655 DAG.getConstant(VT.getSizeInBits()-1,
1656 getShiftAmountTy()));
1657 AddToWorkList(SGN.getNode());
1659 // Add (N0 < 0) ? abs2 - 1 : 0;
1660 SDValue SRL = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, SGN,
1661 DAG.getConstant(VT.getSizeInBits() - lg2,
1662 getShiftAmountTy()));
1663 SDValue ADD = DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, SRL);
1664 AddToWorkList(SRL.getNode());
1665 AddToWorkList(ADD.getNode()); // Divide by pow2
1666 SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, ADD,
1667 DAG.getConstant(lg2, getShiftAmountTy()));
1669 // If we're dividing by a positive value, we're done. Otherwise, we must
1670 // negate the result.
1674 AddToWorkList(SRA.getNode());
1675 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1676 DAG.getConstant(0, VT), SRA);
1679 // if integer divide is expensive and we satisfy the requirements, emit an
1680 // alternate sequence.
1681 if (N1C && (N1C->getSExtValue() < -1 || N1C->getSExtValue() > 1) &&
1682 !TLI.isIntDivCheap()) {
1683 SDValue Op = BuildSDIV(N);
1684 if (Op.getNode()) return Op;
1688 if (N0.getOpcode() == ISD::UNDEF)
1689 return DAG.getConstant(0, VT);
1690 // X / undef -> undef
1691 if (N1.getOpcode() == ISD::UNDEF)
1697 SDValue DAGCombiner::visitUDIV(SDNode *N) {
1698 SDValue N0 = N->getOperand(0);
1699 SDValue N1 = N->getOperand(1);
1700 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1701 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1702 EVT VT = N->getValueType(0);
1705 if (VT.isVector()) {
1706 SDValue FoldedVOp = SimplifyVBinOp(N);
1707 if (FoldedVOp.getNode()) return FoldedVOp;
1710 // fold (udiv c1, c2) -> c1/c2
1711 if (N0C && N1C && !N1C->isNullValue())
1712 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
1713 // fold (udiv x, (1 << c)) -> x >>u c
1714 if (N1C && N1C->getAPIntValue().isPowerOf2())
1715 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
1716 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1717 getShiftAmountTy()));
1718 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1719 if (N1.getOpcode() == ISD::SHL) {
1720 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1721 if (SHC->getAPIntValue().isPowerOf2()) {
1722 EVT ADDVT = N1.getOperand(1).getValueType();
1723 SDValue Add = DAG.getNode(ISD::ADD, N->getDebugLoc(), ADDVT,
1725 DAG.getConstant(SHC->getAPIntValue()
1728 AddToWorkList(Add.getNode());
1729 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, Add);
1733 // fold (udiv x, c) -> alternate
1734 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1735 SDValue Op = BuildUDIV(N);
1736 if (Op.getNode()) return Op;
1740 if (N0.getOpcode() == ISD::UNDEF)
1741 return DAG.getConstant(0, VT);
1742 // X / undef -> undef
1743 if (N1.getOpcode() == ISD::UNDEF)
1749 SDValue DAGCombiner::visitSREM(SDNode *N) {
1750 SDValue N0 = N->getOperand(0);
1751 SDValue N1 = N->getOperand(1);
1752 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1753 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1754 EVT VT = N->getValueType(0);
1756 // fold (srem c1, c2) -> c1%c2
1757 if (N0C && N1C && !N1C->isNullValue())
1758 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
1759 // If we know the sign bits of both operands are zero, strength reduce to a
1760 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
1761 if (!VT.isVector()) {
1762 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1763 return DAG.getNode(ISD::UREM, N->getDebugLoc(), VT, N0, N1);
1766 // If X/C can be simplified by the division-by-constant logic, lower
1767 // X%C to the equivalent of X-X/C*C.
1768 if (N1C && !N1C->isNullValue()) {
1769 SDValue Div = DAG.getNode(ISD::SDIV, N->getDebugLoc(), VT, N0, N1);
1770 AddToWorkList(Div.getNode());
1771 SDValue OptimizedDiv = combine(Div.getNode());
1772 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1773 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1775 SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
1776 AddToWorkList(Mul.getNode());
1782 if (N0.getOpcode() == ISD::UNDEF)
1783 return DAG.getConstant(0, VT);
1784 // X % undef -> undef
1785 if (N1.getOpcode() == ISD::UNDEF)
1791 SDValue DAGCombiner::visitUREM(SDNode *N) {
1792 SDValue N0 = N->getOperand(0);
1793 SDValue N1 = N->getOperand(1);
1794 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1795 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1796 EVT VT = N->getValueType(0);
1798 // fold (urem c1, c2) -> c1%c2
1799 if (N0C && N1C && !N1C->isNullValue())
1800 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
1801 // fold (urem x, pow2) -> (and x, pow2-1)
1802 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
1803 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0,
1804 DAG.getConstant(N1C->getAPIntValue()-1,VT));
1805 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
1806 if (N1.getOpcode() == ISD::SHL) {
1807 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1808 if (SHC->getAPIntValue().isPowerOf2()) {
1810 DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1,
1811 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
1813 AddToWorkList(Add.getNode());
1814 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, Add);
1819 // If X/C can be simplified by the division-by-constant logic, lower
1820 // X%C to the equivalent of X-X/C*C.
1821 if (N1C && !N1C->isNullValue()) {
1822 SDValue Div = DAG.getNode(ISD::UDIV, N->getDebugLoc(), VT, N0, N1);
1823 AddToWorkList(Div.getNode());
1824 SDValue OptimizedDiv = combine(Div.getNode());
1825 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1826 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1828 SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
1829 AddToWorkList(Mul.getNode());
1835 if (N0.getOpcode() == ISD::UNDEF)
1836 return DAG.getConstant(0, VT);
1837 // X % undef -> undef
1838 if (N1.getOpcode() == ISD::UNDEF)
1844 SDValue DAGCombiner::visitMULHS(SDNode *N) {
1845 SDValue N0 = N->getOperand(0);
1846 SDValue N1 = N->getOperand(1);
1847 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1848 EVT VT = N->getValueType(0);
1850 // fold (mulhs x, 0) -> 0
1851 if (N1C && N1C->isNullValue())
1853 // fold (mulhs x, 1) -> (sra x, size(x)-1)
1854 if (N1C && N1C->getAPIntValue() == 1)
1855 return DAG.getNode(ISD::SRA, N->getDebugLoc(), N0.getValueType(), N0,
1856 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
1857 getShiftAmountTy()));
1858 // fold (mulhs x, undef) -> 0
1859 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1860 return DAG.getConstant(0, VT);
1865 SDValue DAGCombiner::visitMULHU(SDNode *N) {
1866 SDValue N0 = N->getOperand(0);
1867 SDValue N1 = N->getOperand(1);
1868 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1869 EVT VT = N->getValueType(0);
1871 // fold (mulhu x, 0) -> 0
1872 if (N1C && N1C->isNullValue())
1874 // fold (mulhu x, 1) -> 0
1875 if (N1C && N1C->getAPIntValue() == 1)
1876 return DAG.getConstant(0, N0.getValueType());
1877 // fold (mulhu x, undef) -> 0
1878 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1879 return DAG.getConstant(0, VT);
1884 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
1885 /// compute two values. LoOp and HiOp give the opcodes for the two computations
1886 /// that are being performed. Return true if a simplification was made.
1888 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
1890 // If the high half is not needed, just compute the low half.
1891 bool HiExists = N->hasAnyUseOfValue(1);
1893 (!LegalOperations ||
1894 TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
1895 SDValue Res = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
1896 N->op_begin(), N->getNumOperands());
1897 return CombineTo(N, Res, Res);
1900 // If the low half is not needed, just compute the high half.
1901 bool LoExists = N->hasAnyUseOfValue(0);
1903 (!LegalOperations ||
1904 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
1905 SDValue Res = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
1906 N->op_begin(), N->getNumOperands());
1907 return CombineTo(N, Res, Res);
1910 // If both halves are used, return as it is.
1911 if (LoExists && HiExists)
1914 // If the two computed results can be simplified separately, separate them.
1916 SDValue Lo = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
1917 N->op_begin(), N->getNumOperands());
1918 AddToWorkList(Lo.getNode());
1919 SDValue LoOpt = combine(Lo.getNode());
1920 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
1921 (!LegalOperations ||
1922 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
1923 return CombineTo(N, LoOpt, LoOpt);
1927 SDValue Hi = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
1928 N->op_begin(), N->getNumOperands());
1929 AddToWorkList(Hi.getNode());
1930 SDValue HiOpt = combine(Hi.getNode());
1931 if (HiOpt.getNode() && HiOpt != Hi &&
1932 (!LegalOperations ||
1933 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
1934 return CombineTo(N, HiOpt, HiOpt);
1940 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
1941 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
1942 if (Res.getNode()) return Res;
1947 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
1948 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
1949 if (Res.getNode()) return Res;
1954 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
1955 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
1956 if (Res.getNode()) return Res;
1961 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
1962 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
1963 if (Res.getNode()) return Res;
1968 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
1969 /// two operands of the same opcode, try to simplify it.
1970 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
1971 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
1972 EVT VT = N0.getValueType();
1973 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
1975 // Bail early if none of these transforms apply.
1976 if (N0.getNode()->getNumOperands() == 0) return SDValue();
1978 // For each of OP in AND/OR/XOR:
1979 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
1980 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
1981 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
1982 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y))
1984 // do not sink logical op inside of a vector extend, since it may combine
1986 EVT Op0VT = N0.getOperand(0).getValueType();
1987 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
1988 N0.getOpcode() == ISD::SIGN_EXTEND ||
1989 // Avoid infinite looping with PromoteIntBinOp.
1990 (N0.getOpcode() == ISD::ANY_EXTEND &&
1991 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
1992 (N0.getOpcode() == ISD::TRUNCATE && TLI.isTypeLegal(Op0VT))) &&
1994 Op0VT == N1.getOperand(0).getValueType() &&
1995 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
1996 SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
1997 N0.getOperand(0).getValueType(),
1998 N0.getOperand(0), N1.getOperand(0));
1999 AddToWorkList(ORNode.getNode());
2000 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, ORNode);
2003 // For each of OP in SHL/SRL/SRA/AND...
2004 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2005 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2006 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2007 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2008 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2009 N0.getOperand(1) == N1.getOperand(1)) {
2010 SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
2011 N0.getOperand(0).getValueType(),
2012 N0.getOperand(0), N1.getOperand(0));
2013 AddToWorkList(ORNode.getNode());
2014 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
2015 ORNode, N0.getOperand(1));
2021 SDValue DAGCombiner::visitAND(SDNode *N) {
2022 SDValue N0 = N->getOperand(0);
2023 SDValue N1 = N->getOperand(1);
2024 SDValue LL, LR, RL, RR, CC0, CC1;
2025 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2026 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2027 EVT VT = N1.getValueType();
2028 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2031 if (VT.isVector()) {
2032 SDValue FoldedVOp = SimplifyVBinOp(N);
2033 if (FoldedVOp.getNode()) return FoldedVOp;
2036 // fold (and x, undef) -> 0
2037 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2038 return DAG.getConstant(0, VT);
2039 // fold (and c1, c2) -> c1&c2
2041 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2042 // canonicalize constant to RHS
2044 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N1, N0);
2045 // fold (and x, -1) -> x
2046 if (N1C && N1C->isAllOnesValue())
2048 // if (and x, c) is known to be zero, return 0
2049 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2050 APInt::getAllOnesValue(BitWidth)))
2051 return DAG.getConstant(0, VT);
2053 SDValue RAND = ReassociateOps(ISD::AND, N->getDebugLoc(), N0, N1);
2054 if (RAND.getNode() != 0)
2056 // fold (and (or x, C), D) -> D if (C & D) == D
2057 if (N1C && N0.getOpcode() == ISD::OR)
2058 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2059 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2061 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2062 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2063 SDValue N0Op0 = N0.getOperand(0);
2064 APInt Mask = ~N1C->getAPIntValue();
2065 Mask.trunc(N0Op0.getValueSizeInBits());
2066 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2067 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(),
2068 N0.getValueType(), N0Op0);
2070 // Replace uses of the AND with uses of the Zero extend node.
2073 // We actually want to replace all uses of the any_extend with the
2074 // zero_extend, to avoid duplicating things. This will later cause this
2075 // AND to be folded.
2076 CombineTo(N0.getNode(), Zext);
2077 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2080 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2081 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2082 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2083 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2085 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2086 LL.getValueType().isInteger()) {
2087 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2088 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2089 SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
2090 LR.getValueType(), LL, RL);
2091 AddToWorkList(ORNode.getNode());
2092 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2094 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2095 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2096 SDValue ANDNode = DAG.getNode(ISD::AND, N0.getDebugLoc(),
2097 LR.getValueType(), LL, RL);
2098 AddToWorkList(ANDNode.getNode());
2099 return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
2101 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2102 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2103 SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
2104 LR.getValueType(), LL, RL);
2105 AddToWorkList(ORNode.getNode());
2106 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2109 // canonicalize equivalent to ll == rl
2110 if (LL == RR && LR == RL) {
2111 Op1 = ISD::getSetCCSwappedOperands(Op1);
2114 if (LL == RL && LR == RR) {
2115 bool isInteger = LL.getValueType().isInteger();
2116 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2117 if (Result != ISD::SETCC_INVALID &&
2118 (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
2119 return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
2124 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2125 if (N0.getOpcode() == N1.getOpcode()) {
2126 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2127 if (Tmp.getNode()) return Tmp;
2130 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2131 // fold (and (sra)) -> (and (srl)) when possible.
2132 if (!VT.isVector() &&
2133 SimplifyDemandedBits(SDValue(N, 0)))
2134 return SDValue(N, 0);
2136 // fold (zext_inreg (extload x)) -> (zextload x)
2137 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2138 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2139 EVT MemVT = LN0->getMemoryVT();
2140 // If we zero all the possible extended bits, then we can turn this into
2141 // a zextload if we are running before legalize or the operation is legal.
2142 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2143 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2144 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2145 ((!LegalOperations && !LN0->isVolatile()) ||
2146 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2147 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
2148 LN0->getChain(), LN0->getBasePtr(),
2150 LN0->getSrcValueOffset(), MemVT,
2151 LN0->isVolatile(), LN0->isNonTemporal(),
2152 LN0->getAlignment());
2154 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2155 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2158 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2159 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2161 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2162 EVT MemVT = LN0->getMemoryVT();
2163 // If we zero all the possible extended bits, then we can turn this into
2164 // a zextload if we are running before legalize or the operation is legal.
2165 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2166 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2167 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2168 ((!LegalOperations && !LN0->isVolatile()) ||
2169 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2170 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
2172 LN0->getBasePtr(), LN0->getSrcValue(),
2173 LN0->getSrcValueOffset(), MemVT,
2174 LN0->isVolatile(), LN0->isNonTemporal(),
2175 LN0->getAlignment());
2177 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2178 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2182 // fold (and (load x), 255) -> (zextload x, i8)
2183 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2184 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2185 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2186 (N0.getOpcode() == ISD::ANY_EXTEND &&
2187 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2188 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2189 LoadSDNode *LN0 = HasAnyExt
2190 ? cast<LoadSDNode>(N0.getOperand(0))
2191 : cast<LoadSDNode>(N0);
2192 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2193 LN0->isUnindexed() && N0.hasOneUse() && LN0->hasOneUse()) {
2194 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2195 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2196 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2197 EVT LoadedVT = LN0->getMemoryVT();
2199 if (ExtVT == LoadedVT &&
2200 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2201 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2204 DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy,
2205 LN0->getChain(), LN0->getBasePtr(),
2206 LN0->getSrcValue(), LN0->getSrcValueOffset(),
2207 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2208 LN0->getAlignment());
2210 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2211 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2214 // Do not change the width of a volatile load.
2215 // Do not generate loads of non-round integer types since these can
2216 // be expensive (and would be wrong if the type is not byte sized).
2217 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2218 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2219 EVT PtrType = LN0->getOperand(1).getValueType();
2221 unsigned Alignment = LN0->getAlignment();
2222 SDValue NewPtr = LN0->getBasePtr();
2224 // For big endian targets, we need to add an offset to the pointer
2225 // to load the correct bytes. For little endian systems, we merely
2226 // need to read fewer bytes from the same pointer.
2227 if (TLI.isBigEndian()) {
2228 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2229 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2230 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2231 NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(), PtrType,
2232 NewPtr, DAG.getConstant(PtrOff, PtrType));
2233 Alignment = MinAlign(Alignment, PtrOff);
2236 AddToWorkList(NewPtr.getNode());
2238 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2240 DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy,
2241 LN0->getChain(), NewPtr,
2242 LN0->getSrcValue(), LN0->getSrcValueOffset(),
2243 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2246 CombineTo(LN0, Load, Load.getValue(1));
2247 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2253 return PromoteIntBinOp(SDValue(N, 0));
2256 SDValue DAGCombiner::visitOR(SDNode *N) {
2257 SDValue N0 = N->getOperand(0);
2258 SDValue N1 = N->getOperand(1);
2259 SDValue LL, LR, RL, RR, CC0, CC1;
2260 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2261 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2262 EVT VT = N1.getValueType();
2265 if (VT.isVector()) {
2266 SDValue FoldedVOp = SimplifyVBinOp(N);
2267 if (FoldedVOp.getNode()) return FoldedVOp;
2270 // fold (or x, undef) -> -1
2271 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) {
2272 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
2273 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
2275 // fold (or c1, c2) -> c1|c2
2277 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
2278 // canonicalize constant to RHS
2280 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N1, N0);
2281 // fold (or x, 0) -> x
2282 if (N1C && N1C->isNullValue())
2284 // fold (or x, -1) -> -1
2285 if (N1C && N1C->isAllOnesValue())
2287 // fold (or x, c) -> c iff (x & ~c) == 0
2288 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
2291 SDValue ROR = ReassociateOps(ISD::OR, N->getDebugLoc(), N0, N1);
2292 if (ROR.getNode() != 0)
2294 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
2295 // iff (c1 & c2) == 0.
2296 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
2297 isa<ConstantSDNode>(N0.getOperand(1))) {
2298 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
2299 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
2300 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
2301 DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
2302 N0.getOperand(0), N1),
2303 DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
2305 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
2306 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2307 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2308 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2310 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2311 LL.getValueType().isInteger()) {
2312 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
2313 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
2314 if (cast<ConstantSDNode>(LR)->isNullValue() &&
2315 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
2316 SDValue ORNode = DAG.getNode(ISD::OR, LR.getDebugLoc(),
2317 LR.getValueType(), LL, RL);
2318 AddToWorkList(ORNode.getNode());
2319 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2321 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
2322 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
2323 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2324 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
2325 SDValue ANDNode = DAG.getNode(ISD::AND, LR.getDebugLoc(),
2326 LR.getValueType(), LL, RL);
2327 AddToWorkList(ANDNode.getNode());
2328 return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
2331 // canonicalize equivalent to ll == rl
2332 if (LL == RR && LR == RL) {
2333 Op1 = ISD::getSetCCSwappedOperands(Op1);
2336 if (LL == RL && LR == RR) {
2337 bool isInteger = LL.getValueType().isInteger();
2338 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
2339 if (Result != ISD::SETCC_INVALID &&
2340 (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
2341 return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
2346 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
2347 if (N0.getOpcode() == N1.getOpcode()) {
2348 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2349 if (Tmp.getNode()) return Tmp;
2352 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
2353 if (N0.getOpcode() == ISD::AND &&
2354 N1.getOpcode() == ISD::AND &&
2355 N0.getOperand(1).getOpcode() == ISD::Constant &&
2356 N1.getOperand(1).getOpcode() == ISD::Constant &&
2357 // Don't increase # computations.
2358 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
2359 // We can only do this xform if we know that bits from X that are set in C2
2360 // but not in C1 are already zero. Likewise for Y.
2361 const APInt &LHSMask =
2362 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
2363 const APInt &RHSMask =
2364 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
2366 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
2367 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
2368 SDValue X = DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
2369 N0.getOperand(0), N1.getOperand(0));
2370 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, X,
2371 DAG.getConstant(LHSMask | RHSMask, VT));
2375 // See if this is some rotate idiom.
2376 if (SDNode *Rot = MatchRotate(N0, N1, N->getDebugLoc()))
2377 return SDValue(Rot, 0);
2379 return PromoteIntBinOp(SDValue(N, 0));
2382 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
2383 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
2384 if (Op.getOpcode() == ISD::AND) {
2385 if (isa<ConstantSDNode>(Op.getOperand(1))) {
2386 Mask = Op.getOperand(1);
2387 Op = Op.getOperand(0);
2393 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
2401 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
2402 // idioms for rotate, and if the target supports rotation instructions, generate
2404 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL) {
2405 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
2406 EVT VT = LHS.getValueType();
2407 if (!TLI.isTypeLegal(VT)) return 0;
2409 // The target must have at least one rotate flavor.
2410 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
2411 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
2412 if (!HasROTL && !HasROTR) return 0;
2414 // Match "(X shl/srl V1) & V2" where V2 may not be present.
2415 SDValue LHSShift; // The shift.
2416 SDValue LHSMask; // AND value if any.
2417 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
2418 return 0; // Not part of a rotate.
2420 SDValue RHSShift; // The shift.
2421 SDValue RHSMask; // AND value if any.
2422 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
2423 return 0; // Not part of a rotate.
2425 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
2426 return 0; // Not shifting the same value.
2428 if (LHSShift.getOpcode() == RHSShift.getOpcode())
2429 return 0; // Shifts must disagree.
2431 // Canonicalize shl to left side in a shl/srl pair.
2432 if (RHSShift.getOpcode() == ISD::SHL) {
2433 std::swap(LHS, RHS);
2434 std::swap(LHSShift, RHSShift);
2435 std::swap(LHSMask , RHSMask );
2438 unsigned OpSizeInBits = VT.getSizeInBits();
2439 SDValue LHSShiftArg = LHSShift.getOperand(0);
2440 SDValue LHSShiftAmt = LHSShift.getOperand(1);
2441 SDValue RHSShiftAmt = RHSShift.getOperand(1);
2443 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
2444 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
2445 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
2446 RHSShiftAmt.getOpcode() == ISD::Constant) {
2447 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
2448 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
2449 if ((LShVal + RShVal) != OpSizeInBits)
2454 Rot = DAG.getNode(ISD::ROTL, DL, VT, LHSShiftArg, LHSShiftAmt);
2456 Rot = DAG.getNode(ISD::ROTR, DL, VT, LHSShiftArg, RHSShiftAmt);
2458 // If there is an AND of either shifted operand, apply it to the result.
2459 if (LHSMask.getNode() || RHSMask.getNode()) {
2460 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
2462 if (LHSMask.getNode()) {
2463 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
2464 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
2466 if (RHSMask.getNode()) {
2467 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
2468 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
2471 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
2474 return Rot.getNode();
2477 // If there is a mask here, and we have a variable shift, we can't be sure
2478 // that we're masking out the right stuff.
2479 if (LHSMask.getNode() || RHSMask.getNode())
2482 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
2483 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
2484 if (RHSShiftAmt.getOpcode() == ISD::SUB &&
2485 LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
2486 if (ConstantSDNode *SUBC =
2487 dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
2488 if (SUBC->getAPIntValue() == OpSizeInBits) {
2490 return DAG.getNode(ISD::ROTL, DL, VT,
2491 LHSShiftArg, LHSShiftAmt).getNode();
2493 return DAG.getNode(ISD::ROTR, DL, VT,
2494 LHSShiftArg, RHSShiftAmt).getNode();
2499 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
2500 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
2501 if (LHSShiftAmt.getOpcode() == ISD::SUB &&
2502 RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
2503 if (ConstantSDNode *SUBC =
2504 dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
2505 if (SUBC->getAPIntValue() == OpSizeInBits) {
2507 return DAG.getNode(ISD::ROTR, DL, VT,
2508 LHSShiftArg, RHSShiftAmt).getNode();
2510 return DAG.getNode(ISD::ROTL, DL, VT,
2511 LHSShiftArg, LHSShiftAmt).getNode();
2516 // Look for sign/zext/any-extended or truncate cases:
2517 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2518 || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2519 || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
2520 || LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
2521 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2522 || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2523 || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
2524 || RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
2525 SDValue LExtOp0 = LHSShiftAmt.getOperand(0);
2526 SDValue RExtOp0 = RHSShiftAmt.getOperand(0);
2527 if (RExtOp0.getOpcode() == ISD::SUB &&
2528 RExtOp0.getOperand(1) == LExtOp0) {
2529 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2531 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2532 // (rotr x, (sub 32, y))
2533 if (ConstantSDNode *SUBC =
2534 dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
2535 if (SUBC->getAPIntValue() == OpSizeInBits) {
2536 return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
2538 HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
2541 } else if (LExtOp0.getOpcode() == ISD::SUB &&
2542 RExtOp0 == LExtOp0.getOperand(1)) {
2543 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
2545 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
2546 // (rotl x, (sub 32, y))
2547 if (ConstantSDNode *SUBC =
2548 dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
2549 if (SUBC->getAPIntValue() == OpSizeInBits) {
2550 return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT,
2552 HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
2561 SDValue DAGCombiner::visitXOR(SDNode *N) {
2562 SDValue N0 = N->getOperand(0);
2563 SDValue N1 = N->getOperand(1);
2564 SDValue LHS, RHS, CC;
2565 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2566 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2567 EVT VT = N0.getValueType();
2570 if (VT.isVector()) {
2571 SDValue FoldedVOp = SimplifyVBinOp(N);
2572 if (FoldedVOp.getNode()) return FoldedVOp;
2575 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
2576 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
2577 return DAG.getConstant(0, VT);
2578 // fold (xor x, undef) -> undef
2579 if (N0.getOpcode() == ISD::UNDEF)
2581 if (N1.getOpcode() == ISD::UNDEF)
2583 // fold (xor c1, c2) -> c1^c2
2585 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
2586 // canonicalize constant to RHS
2588 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
2589 // fold (xor x, 0) -> x
2590 if (N1C && N1C->isNullValue())
2593 SDValue RXOR = ReassociateOps(ISD::XOR, N->getDebugLoc(), N0, N1);
2594 if (RXOR.getNode() != 0)
2597 // fold !(x cc y) -> (x !cc y)
2598 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
2599 bool isInt = LHS.getValueType().isInteger();
2600 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
2603 if (!LegalOperations || TLI.isCondCodeLegal(NotCC, LHS.getValueType())) {
2604 switch (N0.getOpcode()) {
2606 llvm_unreachable("Unhandled SetCC Equivalent!");
2608 return DAG.getSetCC(N->getDebugLoc(), VT, LHS, RHS, NotCC);
2609 case ISD::SELECT_CC:
2610 return DAG.getSelectCC(N->getDebugLoc(), LHS, RHS, N0.getOperand(2),
2611 N0.getOperand(3), NotCC);
2616 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
2617 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
2618 N0.getNode()->hasOneUse() &&
2619 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
2620 SDValue V = N0.getOperand(0);
2621 V = DAG.getNode(ISD::XOR, N0.getDebugLoc(), V.getValueType(), V,
2622 DAG.getConstant(1, V.getValueType()));
2623 AddToWorkList(V.getNode());
2624 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, V);
2627 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
2628 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
2629 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2630 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2631 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
2632 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2633 LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
2634 RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
2635 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
2636 return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
2639 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
2640 if (N1C && N1C->isAllOnesValue() &&
2641 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2642 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2643 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
2644 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2645 LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
2646 RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
2647 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
2648 return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
2651 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
2652 if (N1C && N0.getOpcode() == ISD::XOR) {
2653 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
2654 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2656 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(1),
2657 DAG.getConstant(N1C->getAPIntValue() ^
2658 N00C->getAPIntValue(), VT));
2660 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(0),
2661 DAG.getConstant(N1C->getAPIntValue() ^
2662 N01C->getAPIntValue(), VT));
2664 // fold (xor x, x) -> 0
2666 if (!VT.isVector()) {
2667 return DAG.getConstant(0, VT);
2668 } else if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)){
2669 // Produce a vector of zeros.
2670 SDValue El = DAG.getConstant(0, VT.getVectorElementType());
2671 std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
2672 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
2673 &Ops[0], Ops.size());
2677 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
2678 if (N0.getOpcode() == N1.getOpcode()) {
2679 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2680 if (Tmp.getNode()) return Tmp;
2683 // Simplify the expression using non-local knowledge.
2684 if (!VT.isVector() &&
2685 SimplifyDemandedBits(SDValue(N, 0)))
2686 return SDValue(N, 0);
2688 return PromoteIntBinOp(SDValue(N, 0));
2691 /// visitShiftByConstant - Handle transforms common to the three shifts, when
2692 /// the shift amount is a constant.
2693 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
2694 SDNode *LHS = N->getOperand(0).getNode();
2695 if (!LHS->hasOneUse()) return SDValue();
2697 // We want to pull some binops through shifts, so that we have (and (shift))
2698 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
2699 // thing happens with address calculations, so it's important to canonicalize
2701 bool HighBitSet = false; // Can we transform this if the high bit is set?
2703 switch (LHS->getOpcode()) {
2704 default: return SDValue();
2707 HighBitSet = false; // We can only transform sra if the high bit is clear.
2710 HighBitSet = true; // We can only transform sra if the high bit is set.
2713 if (N->getOpcode() != ISD::SHL)
2714 return SDValue(); // only shl(add) not sr[al](add).
2715 HighBitSet = false; // We can only transform sra if the high bit is clear.
2719 // We require the RHS of the binop to be a constant as well.
2720 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
2721 if (!BinOpCst) return SDValue();
2723 // FIXME: disable this unless the input to the binop is a shift by a constant.
2724 // If it is not a shift, it pessimizes some common cases like:
2726 // void foo(int *X, int i) { X[i & 1235] = 1; }
2727 // int bar(int *X, int i) { return X[i & 255]; }
2728 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
2729 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
2730 BinOpLHSVal->getOpcode() != ISD::SRA &&
2731 BinOpLHSVal->getOpcode() != ISD::SRL) ||
2732 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
2735 EVT VT = N->getValueType(0);
2737 // If this is a signed shift right, and the high bit is modified by the
2738 // logical operation, do not perform the transformation. The highBitSet
2739 // boolean indicates the value of the high bit of the constant which would
2740 // cause it to be modified for this operation.
2741 if (N->getOpcode() == ISD::SRA) {
2742 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
2743 if (BinOpRHSSignSet != HighBitSet)
2747 // Fold the constants, shifting the binop RHS by the shift amount.
2748 SDValue NewRHS = DAG.getNode(N->getOpcode(), LHS->getOperand(1).getDebugLoc(),
2750 LHS->getOperand(1), N->getOperand(1));
2752 // Create the new shift.
2753 SDValue NewShift = DAG.getNode(N->getOpcode(), LHS->getOperand(0).getDebugLoc(),
2754 VT, LHS->getOperand(0), N->getOperand(1));
2756 // Create the new binop.
2757 return DAG.getNode(LHS->getOpcode(), N->getDebugLoc(), VT, NewShift, NewRHS);
2760 SDValue DAGCombiner::visitSHL(SDNode *N) {
2761 SDValue N0 = N->getOperand(0);
2762 SDValue N1 = N->getOperand(1);
2763 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2764 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2765 EVT VT = N0.getValueType();
2766 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
2768 // fold (shl c1, c2) -> c1<<c2
2770 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
2771 // fold (shl 0, x) -> 0
2772 if (N0C && N0C->isNullValue())
2774 // fold (shl x, c >= size(x)) -> undef
2775 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
2776 return DAG.getUNDEF(VT);
2777 // fold (shl x, 0) -> x
2778 if (N1C && N1C->isNullValue())
2780 // if (shl x, c) is known to be zero, return 0
2781 if (DAG.MaskedValueIsZero(SDValue(N, 0),
2782 APInt::getAllOnesValue(OpSizeInBits)))
2783 return DAG.getConstant(0, VT);
2784 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
2785 if (N1.getOpcode() == ISD::TRUNCATE &&
2786 N1.getOperand(0).getOpcode() == ISD::AND &&
2787 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
2788 SDValue N101 = N1.getOperand(0).getOperand(1);
2789 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
2790 EVT TruncVT = N1.getValueType();
2791 SDValue N100 = N1.getOperand(0).getOperand(0);
2792 APInt TruncC = N101C->getAPIntValue();
2793 TruncC.trunc(TruncVT.getSizeInBits());
2794 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
2795 DAG.getNode(ISD::AND, N->getDebugLoc(), TruncVT,
2796 DAG.getNode(ISD::TRUNCATE,
2799 DAG.getConstant(TruncC, TruncVT)));
2803 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
2804 return SDValue(N, 0);
2806 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
2807 if (N1C && N0.getOpcode() == ISD::SHL &&
2808 N0.getOperand(1).getOpcode() == ISD::Constant) {
2809 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
2810 uint64_t c2 = N1C->getZExtValue();
2811 if (c1 + c2 > OpSizeInBits)
2812 return DAG.getConstant(0, VT);
2813 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
2814 DAG.getConstant(c1 + c2, N1.getValueType()));
2816 // fold (shl (srl x, c1), c2) -> (shl (and x, (shl -1, c1)), (sub c2, c1)) or
2817 // (srl (and x, (shl -1, c1)), (sub c1, c2))
2818 if (N1C && N0.getOpcode() == ISD::SRL &&
2819 N0.getOperand(1).getOpcode() == ISD::Constant) {
2820 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
2821 if (c1 < VT.getSizeInBits()) {
2822 uint64_t c2 = N1C->getZExtValue();
2823 SDValue HiBitsMask =
2824 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
2825 VT.getSizeInBits() - c1),
2827 SDValue Mask = DAG.getNode(ISD::AND, N0.getDebugLoc(), VT,
2831 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, Mask,
2832 DAG.getConstant(c2-c1, N1.getValueType()));
2834 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, Mask,
2835 DAG.getConstant(c1-c2, N1.getValueType()));
2838 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
2839 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
2840 SDValue HiBitsMask =
2841 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
2842 VT.getSizeInBits() -
2843 N1C->getZExtValue()),
2845 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
2850 SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
2851 if (NewSHL.getNode())
2855 return PromoteIntShiftOp(SDValue(N, 0));
2858 SDValue DAGCombiner::visitSRA(SDNode *N) {
2859 SDValue N0 = N->getOperand(0);
2860 SDValue N1 = N->getOperand(1);
2861 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2862 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2863 EVT VT = N0.getValueType();
2864 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
2866 // fold (sra c1, c2) -> (sra c1, c2)
2868 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
2869 // fold (sra 0, x) -> 0
2870 if (N0C && N0C->isNullValue())
2872 // fold (sra -1, x) -> -1
2873 if (N0C && N0C->isAllOnesValue())
2875 // fold (sra x, (setge c, size(x))) -> undef
2876 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
2877 return DAG.getUNDEF(VT);
2878 // fold (sra x, 0) -> x
2879 if (N1C && N1C->isNullValue())
2881 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
2883 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
2884 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
2885 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
2887 ExtVT = EVT::getVectorVT(*DAG.getContext(),
2888 ExtVT, VT.getVectorNumElements());
2889 if ((!LegalOperations ||
2890 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
2891 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
2892 N0.getOperand(0), DAG.getValueType(ExtVT));
2895 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
2896 if (N1C && N0.getOpcode() == ISD::SRA) {
2897 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2898 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
2899 if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
2900 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0.getOperand(0),
2901 DAG.getConstant(Sum, N1C->getValueType(0)));
2905 // fold (sra (shl X, m), (sub result_size, n))
2906 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
2907 // result_size - n != m.
2908 // If truncate is free for the target sext(shl) is likely to result in better
2910 if (N0.getOpcode() == ISD::SHL) {
2911 // Get the two constanst of the shifts, CN0 = m, CN = n.
2912 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2914 // Determine what the truncate's result bitsize and type would be.
2916 EVT::getIntegerVT(*DAG.getContext(), OpSizeInBits - N1C->getZExtValue());
2917 // Determine the residual right-shift amount.
2918 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
2920 // If the shift is not a no-op (in which case this should be just a sign
2921 // extend already), the truncated to type is legal, sign_extend is legal
2922 // on that type, and the truncate to that type is both legal and free,
2923 // perform the transform.
2924 if ((ShiftAmt > 0) &&
2925 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
2926 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
2927 TLI.isTruncateFree(VT, TruncVT)) {
2929 SDValue Amt = DAG.getConstant(ShiftAmt, getShiftAmountTy());
2930 SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT,
2931 N0.getOperand(0), Amt);
2932 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), TruncVT,
2934 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(),
2935 N->getValueType(0), Trunc);
2940 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
2941 if (N1.getOpcode() == ISD::TRUNCATE &&
2942 N1.getOperand(0).getOpcode() == ISD::AND &&
2943 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
2944 SDValue N101 = N1.getOperand(0).getOperand(1);
2945 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
2946 EVT TruncVT = N1.getValueType();
2947 SDValue N100 = N1.getOperand(0).getOperand(0);
2948 APInt TruncC = N101C->getAPIntValue();
2949 TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
2950 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
2951 DAG.getNode(ISD::AND, N->getDebugLoc(),
2953 DAG.getNode(ISD::TRUNCATE,
2956 DAG.getConstant(TruncC, TruncVT)));
2960 // Simplify, based on bits shifted out of the LHS.
2961 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
2962 return SDValue(N, 0);
2965 // If the sign bit is known to be zero, switch this to a SRL.
2966 if (DAG.SignBitIsZero(N0))
2967 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, N1);
2970 SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
2971 if (NewSRA.getNode())
2975 return PromoteIntShiftOp(SDValue(N, 0));
2978 SDValue DAGCombiner::visitSRL(SDNode *N) {
2979 SDValue N0 = N->getOperand(0);
2980 SDValue N1 = N->getOperand(1);
2981 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2982 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2983 EVT VT = N0.getValueType();
2984 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
2986 // fold (srl c1, c2) -> c1 >>u c2
2988 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
2989 // fold (srl 0, x) -> 0
2990 if (N0C && N0C->isNullValue())
2992 // fold (srl x, c >= size(x)) -> undef
2993 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
2994 return DAG.getUNDEF(VT);
2995 // fold (srl x, 0) -> x
2996 if (N1C && N1C->isNullValue())
2998 // if (srl x, c) is known to be zero, return 0
2999 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3000 APInt::getAllOnesValue(OpSizeInBits)))
3001 return DAG.getConstant(0, VT);
3003 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
3004 if (N1C && N0.getOpcode() == ISD::SRL &&
3005 N0.getOperand(1).getOpcode() == ISD::Constant) {
3006 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3007 uint64_t c2 = N1C->getZExtValue();
3008 if (c1 + c2 > OpSizeInBits)
3009 return DAG.getConstant(0, VT);
3010 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
3011 DAG.getConstant(c1 + c2, N1.getValueType()));
3014 // fold (srl (shl x, c), c) -> (and x, cst2)
3015 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
3016 N0.getValueSizeInBits() <= 64) {
3017 uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
3018 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
3019 DAG.getConstant(~0ULL >> ShAmt, VT));
3023 // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
3024 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3025 // Shifting in all undef bits?
3026 EVT SmallVT = N0.getOperand(0).getValueType();
3027 if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
3028 return DAG.getUNDEF(VT);
3030 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
3031 SDValue SmallShift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), SmallVT,
3032 N0.getOperand(0), N1);
3033 AddToWorkList(SmallShift.getNode());
3034 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, SmallShift);
3038 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
3039 // bit, which is unmodified by sra.
3040 if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
3041 if (N0.getOpcode() == ISD::SRA)
3042 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0), N1);
3045 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
3046 if (N1C && N0.getOpcode() == ISD::CTLZ &&
3047 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
3048 APInt KnownZero, KnownOne;
3049 APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
3050 DAG.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
3052 // If any of the input bits are KnownOne, then the input couldn't be all
3053 // zeros, thus the result of the srl will always be zero.
3054 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
3056 // If all of the bits input the to ctlz node are known to be zero, then
3057 // the result of the ctlz is "32" and the result of the shift is one.
3058 APInt UnknownBits = ~KnownZero & Mask;
3059 if (UnknownBits == 0) return DAG.getConstant(1, VT);
3061 // Otherwise, check to see if there is exactly one bit input to the ctlz.
3062 if ((UnknownBits & (UnknownBits - 1)) == 0) {
3063 // Okay, we know that only that the single bit specified by UnknownBits
3064 // could be set on input to the CTLZ node. If this bit is set, the SRL
3065 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
3066 // to an SRL/XOR pair, which is likely to simplify more.
3067 unsigned ShAmt = UnknownBits.countTrailingZeros();
3068 SDValue Op = N0.getOperand(0);
3071 Op = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT, Op,
3072 DAG.getConstant(ShAmt, getShiftAmountTy()));
3073 AddToWorkList(Op.getNode());
3076 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
3077 Op, DAG.getConstant(1, VT));
3081 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
3082 if (N1.getOpcode() == ISD::TRUNCATE &&
3083 N1.getOperand(0).getOpcode() == ISD::AND &&
3084 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3085 SDValue N101 = N1.getOperand(0).getOperand(1);
3086 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3087 EVT TruncVT = N1.getValueType();
3088 SDValue N100 = N1.getOperand(0).getOperand(0);
3089 APInt TruncC = N101C->getAPIntValue();
3090 TruncC.trunc(TruncVT.getSizeInBits());
3091 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
3092 DAG.getNode(ISD::AND, N->getDebugLoc(),
3094 DAG.getNode(ISD::TRUNCATE,
3097 DAG.getConstant(TruncC, TruncVT)));
3101 // fold operands of srl based on knowledge that the low bits are not
3103 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3104 return SDValue(N, 0);
3107 SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
3108 if (NewSRL.getNode())
3112 // Here is a common situation. We want to optimize:
3115 // %b = and i32 %a, 2
3116 // %c = srl i32 %b, 1
3117 // brcond i32 %c ...
3123 // %c = setcc eq %b, 0
3126 // However when after the source operand of SRL is optimized into AND, the SRL
3127 // itself may not be optimized further. Look for it and add the BRCOND into
3129 if (N->hasOneUse()) {
3130 SDNode *Use = *N->use_begin();
3131 if (Use->getOpcode() == ISD::BRCOND)
3133 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
3134 // Also look pass the truncate.
3135 Use = *Use->use_begin();
3136 if (Use->getOpcode() == ISD::BRCOND)
3141 return PromoteIntShiftOp(SDValue(N, 0));
3144 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
3145 SDValue N0 = N->getOperand(0);
3146 EVT VT = N->getValueType(0);
3148 // fold (ctlz c1) -> c2
3149 if (isa<ConstantSDNode>(N0))
3150 return DAG.getNode(ISD::CTLZ, N->getDebugLoc(), VT, N0);
3154 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
3155 SDValue N0 = N->getOperand(0);
3156 EVT VT = N->getValueType(0);
3158 // fold (cttz c1) -> c2
3159 if (isa<ConstantSDNode>(N0))
3160 return DAG.getNode(ISD::CTTZ, N->getDebugLoc(), VT, N0);
3164 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
3165 SDValue N0 = N->getOperand(0);
3166 EVT VT = N->getValueType(0);
3168 // fold (ctpop c1) -> c2
3169 if (isa<ConstantSDNode>(N0))
3170 return DAG.getNode(ISD::CTPOP, N->getDebugLoc(), VT, N0);
3174 SDValue DAGCombiner::visitSELECT(SDNode *N) {
3175 SDValue N0 = N->getOperand(0);
3176 SDValue N1 = N->getOperand(1);
3177 SDValue N2 = N->getOperand(2);
3178 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3179 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3180 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
3181 EVT VT = N->getValueType(0);
3182 EVT VT0 = N0.getValueType();
3184 // fold (select C, X, X) -> X
3187 // fold (select true, X, Y) -> X
3188 if (N0C && !N0C->isNullValue())
3190 // fold (select false, X, Y) -> Y
3191 if (N0C && N0C->isNullValue())
3193 // fold (select C, 1, X) -> (or C, X)
3194 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
3195 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
3196 // fold (select C, 0, 1) -> (xor C, 1)
3197 if (VT.isInteger() &&
3200 TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent)) &&
3201 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
3204 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT0,
3205 N0, DAG.getConstant(1, VT0));
3206 XORNode = DAG.getNode(ISD::XOR, N0.getDebugLoc(), VT0,
3207 N0, DAG.getConstant(1, VT0));
3208 AddToWorkList(XORNode.getNode());
3210 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, XORNode);
3211 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, XORNode);
3213 // fold (select C, 0, X) -> (and (not C), X)
3214 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
3215 SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
3216 AddToWorkList(NOTNode.getNode());
3217 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, NOTNode, N2);
3219 // fold (select C, X, 1) -> (or (not C), X)
3220 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
3221 SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
3222 AddToWorkList(NOTNode.getNode());
3223 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, NOTNode, N1);
3225 // fold (select C, X, 0) -> (and C, X)
3226 if (VT == MVT::i1 && N2C && N2C->isNullValue())
3227 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
3228 // fold (select X, X, Y) -> (or X, Y)
3229 // fold (select X, 1, Y) -> (or X, Y)
3230 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
3231 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
3232 // fold (select X, Y, X) -> (and X, Y)
3233 // fold (select X, Y, 0) -> (and X, Y)
3234 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
3235 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
3237 // If we can fold this based on the true/false value, do so.
3238 if (SimplifySelectOps(N, N1, N2))
3239 return SDValue(N, 0); // Don't revisit N.
3241 // fold selects based on a setcc into other things, such as min/max/abs
3242 if (N0.getOpcode() == ISD::SETCC) {
3244 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
3245 // having to say they don't support SELECT_CC on every type the DAG knows
3246 // about, since there is no way to mark an opcode illegal at all value types
3247 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
3248 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
3249 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT,
3250 N0.getOperand(0), N0.getOperand(1),
3251 N1, N2, N0.getOperand(2));
3252 return SimplifySelect(N->getDebugLoc(), N0, N1, N2);
3258 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
3259 SDValue N0 = N->getOperand(0);
3260 SDValue N1 = N->getOperand(1);
3261 SDValue N2 = N->getOperand(2);
3262 SDValue N3 = N->getOperand(3);
3263 SDValue N4 = N->getOperand(4);
3264 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
3266 // fold select_cc lhs, rhs, x, x, cc -> x
3270 // Determine if the condition we're dealing with is constant
3271 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
3272 N0, N1, CC, N->getDebugLoc(), false);
3273 if (SCC.getNode()) AddToWorkList(SCC.getNode());
3275 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
3276 if (!SCCC->isNullValue())
3277 return N2; // cond always true -> true val
3279 return N3; // cond always false -> false val
3282 // Fold to a simpler select_cc
3283 if (SCC.getNode() && SCC.getOpcode() == ISD::SETCC)
3284 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), N2.getValueType(),
3285 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
3288 // If we can fold this based on the true/false value, do so.
3289 if (SimplifySelectOps(N, N2, N3))
3290 return SDValue(N, 0); // Don't revisit N.
3292 // fold select_cc into other things, such as min/max/abs
3293 return SimplifySelectCC(N->getDebugLoc(), N0, N1, N2, N3, CC);
3296 SDValue DAGCombiner::visitSETCC(SDNode *N) {
3297 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
3298 cast<CondCodeSDNode>(N->getOperand(2))->get(),
3302 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
3303 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
3304 // transformation. Returns true if extension are possible and the above
3305 // mentioned transformation is profitable.
3306 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
3308 SmallVector<SDNode*, 4> &ExtendNodes,
3309 const TargetLowering &TLI) {
3310 bool HasCopyToRegUses = false;
3311 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
3312 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
3313 UE = N0.getNode()->use_end();
3318 if (UI.getUse().getResNo() != N0.getResNo())
3320 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
3321 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
3322 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
3323 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
3324 // Sign bits will be lost after a zext.
3327 for (unsigned i = 0; i != 2; ++i) {
3328 SDValue UseOp = User->getOperand(i);
3331 if (!isa<ConstantSDNode>(UseOp))
3336 ExtendNodes.push_back(User);
3339 // If truncates aren't free and there are users we can't
3340 // extend, it isn't worthwhile.
3343 // Remember if this value is live-out.
3344 if (User->getOpcode() == ISD::CopyToReg)
3345 HasCopyToRegUses = true;
3348 if (HasCopyToRegUses) {
3349 bool BothLiveOut = false;
3350 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
3352 SDUse &Use = UI.getUse();
3353 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
3359 // Both unextended and extended values are live out. There had better be
3360 // good a reason for the transformation.
3361 return ExtendNodes.size();
3366 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
3367 SDValue N0 = N->getOperand(0);
3368 EVT VT = N->getValueType(0);
3370 // fold (sext c1) -> c1
3371 if (isa<ConstantSDNode>(N0))
3372 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N0);
3374 // fold (sext (sext x)) -> (sext x)
3375 // fold (sext (aext x)) -> (sext x)
3376 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
3377 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT,
3380 if (N0.getOpcode() == ISD::TRUNCATE) {
3381 // fold (sext (truncate (load x))) -> (sext (smaller load x))
3382 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
3383 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3384 if (NarrowLoad.getNode()) {
3385 if (NarrowLoad.getNode() != N0.getNode())
3386 CombineTo(N0.getNode(), NarrowLoad);
3387 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3390 // See if the value being truncated is already sign extended. If so, just
3391 // eliminate the trunc/sext pair.
3392 SDValue Op = N0.getOperand(0);
3393 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
3394 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
3395 unsigned DestBits = VT.getScalarType().getSizeInBits();
3396 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
3398 if (OpBits == DestBits) {
3399 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
3400 // bits, it is already ready.
3401 if (NumSignBits > DestBits-MidBits)
3403 } else if (OpBits < DestBits) {
3404 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
3405 // bits, just sext from i32.
3406 if (NumSignBits > OpBits-MidBits)
3407 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, Op);
3409 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
3410 // bits, just truncate to i32.
3411 if (NumSignBits > OpBits-MidBits)
3412 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
3415 // fold (sext (truncate x)) -> (sextinreg x).
3416 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
3417 N0.getValueType())) {
3418 if (OpBits < DestBits)
3419 Op = DAG.getNode(ISD::ANY_EXTEND, N0.getDebugLoc(), VT, Op);
3420 else if (OpBits > DestBits)
3421 Op = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), VT, Op);
3422 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, Op,
3423 DAG.getValueType(N0.getValueType()));
3427 // fold (sext (load x)) -> (sext (truncate (sextload x)))
3428 if (ISD::isNON_EXTLoad(N0.getNode()) &&
3429 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3430 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
3431 bool DoXform = true;
3432 SmallVector<SDNode*, 4> SetCCs;
3433 if (!N0.hasOneUse())
3434 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
3436 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3437 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
3439 LN0->getBasePtr(), LN0->getSrcValue(),
3440 LN0->getSrcValueOffset(),
3442 LN0->isVolatile(), LN0->isNonTemporal(),
3443 LN0->getAlignment());
3444 CombineTo(N, ExtLoad);
3445 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3446 N0.getValueType(), ExtLoad);
3447 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
3449 // Extend SetCC uses if necessary.
3450 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
3451 SDNode *SetCC = SetCCs[i];
3452 SmallVector<SDValue, 4> Ops;
3454 for (unsigned j = 0; j != 2; ++j) {
3455 SDValue SOp = SetCC->getOperand(j);
3457 Ops.push_back(ExtLoad);
3459 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND,
3460 N->getDebugLoc(), VT, SOp));
3463 Ops.push_back(SetCC->getOperand(2));
3464 CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
3465 SetCC->getValueType(0),
3466 &Ops[0], Ops.size()));
3469 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3473 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
3474 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
3475 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
3476 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
3477 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3478 EVT MemVT = LN0->getMemoryVT();
3479 if ((!LegalOperations && !LN0->isVolatile()) ||
3480 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
3481 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
3483 LN0->getBasePtr(), LN0->getSrcValue(),
3484 LN0->getSrcValueOffset(), MemVT,
3485 LN0->isVolatile(), LN0->isNonTemporal(),
3486 LN0->getAlignment());
3487 CombineTo(N, ExtLoad);
3488 CombineTo(N0.getNode(),
3489 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3490 N0.getValueType(), ExtLoad),
3491 ExtLoad.getValue(1));
3492 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3496 if (N0.getOpcode() == ISD::SETCC) {
3497 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
3498 if (VT.isVector() &&
3499 // We know that the # elements of the results is the same as the
3500 // # elements of the compare (and the # elements of the compare result
3501 // for that matter). Check to see that they are the same size. If so,
3502 // we know that the element size of the sext'd result matches the
3503 // element size of the compare operands.
3504 VT.getSizeInBits() == N0.getOperand(0).getValueType().getSizeInBits() &&
3506 // Only do this before legalize for now.
3508 return DAG.getVSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
3510 cast<CondCodeSDNode>(N0.getOperand(2))->get());
3513 // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
3514 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
3516 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
3518 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
3519 NegOne, DAG.getConstant(0, VT),
3520 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3521 if (SCC.getNode()) return SCC;
3522 if (!LegalOperations ||
3523 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(VT)))
3524 return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
3525 DAG.getSetCC(N->getDebugLoc(),
3526 TLI.getSetCCResultType(VT),
3527 N0.getOperand(0), N0.getOperand(1),
3528 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
3529 NegOne, DAG.getConstant(0, VT));
3534 // fold (sext x) -> (zext x) if the sign bit is known zero.
3535 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
3536 DAG.SignBitIsZero(N0))
3537 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
3539 return PromoteExtend(SDValue(N, 0));
3542 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
3543 SDValue N0 = N->getOperand(0);
3544 EVT VT = N->getValueType(0);
3546 // fold (zext c1) -> c1
3547 if (isa<ConstantSDNode>(N0))
3548 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
3549 // fold (zext (zext x)) -> (zext x)
3550 // fold (zext (aext x)) -> (zext x)
3551 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
3552 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT,
3555 // fold (zext (truncate (load x))) -> (zext (smaller load x))
3556 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
3557 if (N0.getOpcode() == ISD::TRUNCATE) {
3558 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3559 if (NarrowLoad.getNode()) {
3560 if (NarrowLoad.getNode() != N0.getNode())
3561 CombineTo(N0.getNode(), NarrowLoad);
3562 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, NarrowLoad);
3566 // fold (zext (truncate x)) -> (and x, mask)
3567 if (N0.getOpcode() == ISD::TRUNCATE &&
3568 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) &&
3569 (!TLI.isTruncateFree(N0.getOperand(0).getValueType(),
3570 N0.getValueType()) ||
3571 !TLI.isZExtFree(N0.getValueType(), VT))) {
3572 SDValue Op = N0.getOperand(0);
3573 if (Op.getValueType().bitsLT(VT)) {
3574 Op = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, Op);
3575 } else if (Op.getValueType().bitsGT(VT)) {
3576 Op = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
3578 return DAG.getZeroExtendInReg(Op, N->getDebugLoc(),
3579 N0.getValueType().getScalarType());
3582 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
3583 // if either of the casts is not free.
3584 if (N0.getOpcode() == ISD::AND &&
3585 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
3586 N0.getOperand(1).getOpcode() == ISD::Constant &&
3587 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
3588 N0.getValueType()) ||
3589 !TLI.isZExtFree(N0.getValueType(), VT))) {
3590 SDValue X = N0.getOperand(0).getOperand(0);
3591 if (X.getValueType().bitsLT(VT)) {
3592 X = DAG.getNode(ISD::ANY_EXTEND, X.getDebugLoc(), VT, X);
3593 } else if (X.getValueType().bitsGT(VT)) {
3594 X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
3596 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3597 Mask.zext(VT.getSizeInBits());
3598 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3599 X, DAG.getConstant(Mask, VT));
3602 // fold (zext (load x)) -> (zext (truncate (zextload x)))
3603 if (ISD::isNON_EXTLoad(N0.getNode()) &&
3604 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3605 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
3606 bool DoXform = true;
3607 SmallVector<SDNode*, 4> SetCCs;
3608 if (!N0.hasOneUse())
3609 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
3611 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3612 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
3614 LN0->getBasePtr(), LN0->getSrcValue(),
3615 LN0->getSrcValueOffset(),
3617 LN0->isVolatile(), LN0->isNonTemporal(),
3618 LN0->getAlignment());
3619 CombineTo(N, ExtLoad);
3620 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3621 N0.getValueType(), ExtLoad);
3622 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
3624 // Extend SetCC uses if necessary.
3625 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
3626 SDNode *SetCC = SetCCs[i];
3627 SmallVector<SDValue, 4> Ops;
3629 for (unsigned j = 0; j != 2; ++j) {
3630 SDValue SOp = SetCC->getOperand(j);
3632 Ops.push_back(ExtLoad);
3634 Ops.push_back(DAG.getNode(ISD::ZERO_EXTEND,
3635 N->getDebugLoc(), VT, SOp));
3638 Ops.push_back(SetCC->getOperand(2));
3639 CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
3640 SetCC->getValueType(0),
3641 &Ops[0], Ops.size()));
3644 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3648 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
3649 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
3650 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
3651 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
3652 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3653 EVT MemVT = LN0->getMemoryVT();
3654 if ((!LegalOperations && !LN0->isVolatile()) ||
3655 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
3656 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
3658 LN0->getBasePtr(), LN0->getSrcValue(),
3659 LN0->getSrcValueOffset(), MemVT,
3660 LN0->isVolatile(), LN0->isNonTemporal(),
3661 LN0->getAlignment());
3662 CombineTo(N, ExtLoad);
3663 CombineTo(N0.getNode(),
3664 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), N0.getValueType(),
3666 ExtLoad.getValue(1));
3667 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3671 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3672 if (N0.getOpcode() == ISD::SETCC) {
3674 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
3675 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3676 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3677 if (SCC.getNode()) return SCC;
3680 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
3681 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
3682 isa<ConstantSDNode>(N0.getOperand(1)) &&
3683 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
3685 if (N0.getOpcode() == ISD::SHL) {
3686 // If the original shl may be shifting out bits, do not perform this
3688 unsigned ShAmt = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3689 unsigned KnownZeroBits = N0.getOperand(0).getValueType().getSizeInBits() -
3690 N0.getOperand(0).getOperand(0).getValueType().getSizeInBits();
3691 if (ShAmt > KnownZeroBits)
3694 DebugLoc dl = N->getDebugLoc();
3695 return DAG.getNode(N0.getOpcode(), dl, VT,
3696 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, N0.getOperand(0)),
3697 DAG.getNode(ISD::ZERO_EXTEND, dl,
3698 N0.getOperand(1).getValueType(),
3702 return PromoteExtend(SDValue(N, 0));
3705 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
3706 SDValue N0 = N->getOperand(0);
3707 EVT VT = N->getValueType(0);
3709 // fold (aext c1) -> c1
3710 if (isa<ConstantSDNode>(N0))
3711 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, N0);
3712 // fold (aext (aext x)) -> (aext x)
3713 // fold (aext (zext x)) -> (zext x)
3714 // fold (aext (sext x)) -> (sext x)
3715 if (N0.getOpcode() == ISD::ANY_EXTEND ||
3716 N0.getOpcode() == ISD::ZERO_EXTEND ||
3717 N0.getOpcode() == ISD::SIGN_EXTEND)
3718 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, N0.getOperand(0));
3720 // fold (aext (truncate (load x))) -> (aext (smaller load x))
3721 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
3722 if (N0.getOpcode() == ISD::TRUNCATE) {
3723 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3724 if (NarrowLoad.getNode()) {
3725 if (NarrowLoad.getNode() != N0.getNode())
3726 CombineTo(N0.getNode(), NarrowLoad);
3727 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, NarrowLoad);
3731 // fold (aext (truncate x))
3732 if (N0.getOpcode() == ISD::TRUNCATE) {
3733 SDValue TruncOp = N0.getOperand(0);
3734 if (TruncOp.getValueType() == VT)
3735 return TruncOp; // x iff x size == zext size.
3736 if (TruncOp.getValueType().bitsGT(VT))
3737 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, TruncOp);
3738 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, TruncOp);
3741 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
3742 // if the trunc is not free.
3743 if (N0.getOpcode() == ISD::AND &&
3744 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
3745 N0.getOperand(1).getOpcode() == ISD::Constant &&
3746 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
3747 N0.getValueType())) {
3748 SDValue X = N0.getOperand(0).getOperand(0);
3749 if (X.getValueType().bitsLT(VT)) {
3750 X = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, X);
3751 } else if (X.getValueType().bitsGT(VT)) {
3752 X = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, X);
3754 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3755 Mask.zext(VT.getSizeInBits());
3756 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3757 X, DAG.getConstant(Mask, VT));
3760 // fold (aext (load x)) -> (aext (truncate (extload x)))
3761 if (ISD::isNON_EXTLoad(N0.getNode()) &&
3762 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3763 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
3764 bool DoXform = true;
3765 SmallVector<SDNode*, 4> SetCCs;
3766 if (!N0.hasOneUse())
3767 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
3769 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3770 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
3772 LN0->getBasePtr(), LN0->getSrcValue(),
3773 LN0->getSrcValueOffset(),
3775 LN0->isVolatile(), LN0->isNonTemporal(),
3776 LN0->getAlignment());
3777 CombineTo(N, ExtLoad);
3778 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3779 N0.getValueType(), ExtLoad);
3780 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
3782 // Extend SetCC uses if necessary.
3783 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
3784 SDNode *SetCC = SetCCs[i];
3785 SmallVector<SDValue, 4> Ops;
3787 for (unsigned j = 0; j != 2; ++j) {
3788 SDValue SOp = SetCC->getOperand(j);
3790 Ops.push_back(ExtLoad);
3792 Ops.push_back(DAG.getNode(ISD::ANY_EXTEND,
3793 N->getDebugLoc(), VT, SOp));
3796 Ops.push_back(SetCC->getOperand(2));
3797 CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
3798 SetCC->getValueType(0),
3799 &Ops[0], Ops.size()));
3802 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3806 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
3807 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
3808 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
3809 if (N0.getOpcode() == ISD::LOAD &&
3810 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3812 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3813 EVT MemVT = LN0->getMemoryVT();
3814 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), N->getDebugLoc(),
3815 VT, LN0->getChain(), LN0->getBasePtr(),
3817 LN0->getSrcValueOffset(), MemVT,
3818 LN0->isVolatile(), LN0->isNonTemporal(),
3819 LN0->getAlignment());
3820 CombineTo(N, ExtLoad);
3821 CombineTo(N0.getNode(),
3822 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3823 N0.getValueType(), ExtLoad),
3824 ExtLoad.getValue(1));
3825 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3828 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3829 if (N0.getOpcode() == ISD::SETCC) {
3831 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
3832 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3833 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3838 return PromoteExtend(SDValue(N, 0));
3841 /// GetDemandedBits - See if the specified operand can be simplified with the
3842 /// knowledge that only the bits specified by Mask are used. If so, return the
3843 /// simpler operand, otherwise return a null SDValue.
3844 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
3845 switch (V.getOpcode()) {
3849 // If the LHS or RHS don't contribute bits to the or, drop them.
3850 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
3851 return V.getOperand(1);
3852 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
3853 return V.getOperand(0);
3856 // Only look at single-use SRLs.
3857 if (!V.getNode()->hasOneUse())
3859 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
3860 // See if we can recursively simplify the LHS.
3861 unsigned Amt = RHSC->getZExtValue();
3863 // Watch out for shift count overflow though.
3864 if (Amt >= Mask.getBitWidth()) break;
3865 APInt NewMask = Mask << Amt;
3866 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
3867 if (SimplifyLHS.getNode())
3868 return DAG.getNode(ISD::SRL, V.getDebugLoc(), V.getValueType(),
3869 SimplifyLHS, V.getOperand(1));
3875 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
3876 /// bits and then truncated to a narrower type and where N is a multiple
3877 /// of number of bits of the narrower type, transform it to a narrower load
3878 /// from address + N / num of bits of new type. If the result is to be
3879 /// extended, also fold the extension to form a extending load.
3880 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
3881 unsigned Opc = N->getOpcode();
3882 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
3883 SDValue N0 = N->getOperand(0);
3884 EVT VT = N->getValueType(0);
3887 // This transformation isn't valid for vector loads.
3891 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
3893 if (Opc == ISD::SIGN_EXTEND_INREG) {
3894 ExtType = ISD::SEXTLOAD;
3895 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
3896 if (LegalOperations && !TLI.isLoadExtLegal(ISD::SEXTLOAD, ExtVT))
3900 unsigned EVTBits = ExtVT.getSizeInBits();
3902 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse() && ExtVT.isRound()) {
3903 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3904 ShAmt = N01->getZExtValue();
3905 // Is the shift amount a multiple of size of VT?
3906 if ((ShAmt & (EVTBits-1)) == 0) {
3907 N0 = N0.getOperand(0);
3908 // Is the load width a multiple of size of VT?
3909 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
3915 // Do not generate loads of non-round integer types since these can
3916 // be expensive (and would be wrong if the type is not byte sized).
3917 if (isa<LoadSDNode>(N0) && N0.hasOneUse() && ExtVT.isRound() &&
3918 cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits() >= EVTBits &&
3919 // Do not change the width of a volatile load.
3920 !cast<LoadSDNode>(N0)->isVolatile()) {
3921 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3922 EVT PtrType = N0.getOperand(1).getValueType();
3924 // For big endian targets, we need to adjust the offset to the pointer to
3925 // load the correct bytes.
3926 if (TLI.isBigEndian()) {
3927 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
3928 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
3929 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
3932 uint64_t PtrOff = ShAmt / 8;
3933 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
3934 SDValue NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(),
3935 PtrType, LN0->getBasePtr(),
3936 DAG.getConstant(PtrOff, PtrType));
3937 AddToWorkList(NewPtr.getNode());
3939 SDValue Load = (ExtType == ISD::NON_EXTLOAD)
3940 ? DAG.getLoad(VT, N0.getDebugLoc(), LN0->getChain(), NewPtr,
3941 LN0->getSrcValue(), LN0->getSrcValueOffset() + PtrOff,
3942 LN0->isVolatile(), LN0->isNonTemporal(), NewAlign)
3943 : DAG.getExtLoad(ExtType, N0.getDebugLoc(), VT, LN0->getChain(), NewPtr,
3944 LN0->getSrcValue(), LN0->getSrcValueOffset() + PtrOff,
3945 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3948 // Replace the old load's chain with the new load's chain.
3949 WorkListRemover DeadNodes(*this);
3950 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1),
3953 // Return the new loaded value.
3960 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
3961 SDValue N0 = N->getOperand(0);
3962 SDValue N1 = N->getOperand(1);
3963 EVT VT = N->getValueType(0);
3964 EVT EVT = cast<VTSDNode>(N1)->getVT();
3965 unsigned VTBits = VT.getScalarType().getSizeInBits();
3966 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
3968 // fold (sext_in_reg c1) -> c1
3969 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
3970 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, N0, N1);
3972 // If the input is already sign extended, just drop the extension.
3973 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
3976 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
3977 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3978 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) {
3979 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
3980 N0.getOperand(0), N1);
3983 // fold (sext_in_reg (sext x)) -> (sext x)
3984 // fold (sext_in_reg (aext x)) -> (sext x)
3985 // if x is small enough.
3986 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
3987 SDValue N00 = N0.getOperand(0);
3988 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
3989 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
3990 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N00, N1);
3993 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
3994 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
3995 return DAG.getZeroExtendInReg(N0, N->getDebugLoc(), EVT);
3997 // fold operands of sext_in_reg based on knowledge that the top bits are not
3999 if (SimplifyDemandedBits(SDValue(N, 0)))
4000 return SDValue(N, 0);
4002 // fold (sext_in_reg (load x)) -> (smaller sextload x)
4003 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
4004 SDValue NarrowLoad = ReduceLoadWidth(N);
4005 if (NarrowLoad.getNode())
4008 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
4009 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
4010 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
4011 if (N0.getOpcode() == ISD::SRL) {
4012 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
4013 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
4014 // We can turn this into an SRA iff the input to the SRL is already sign
4016 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
4017 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
4018 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT,
4019 N0.getOperand(0), N0.getOperand(1));
4023 // fold (sext_inreg (extload x)) -> (sextload x)
4024 if (ISD::isEXTLoad(N0.getNode()) &&
4025 ISD::isUNINDEXEDLoad(N0.getNode()) &&
4026 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
4027 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4028 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
4029 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4030 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
4032 LN0->getBasePtr(), LN0->getSrcValue(),
4033 LN0->getSrcValueOffset(), EVT,
4034 LN0->isVolatile(), LN0->isNonTemporal(),
4035 LN0->getAlignment());
4036 CombineTo(N, ExtLoad);
4037 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
4038 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4040 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
4041 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
4043 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
4044 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4045 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
4046 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4047 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
4049 LN0->getBasePtr(), LN0->getSrcValue(),
4050 LN0->getSrcValueOffset(), EVT,
4051 LN0->isVolatile(), LN0->isNonTemporal(),
4052 LN0->getAlignment());
4053 CombineTo(N, ExtLoad);
4054 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
4055 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4060 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
4061 SDValue N0 = N->getOperand(0);
4062 EVT VT = N->getValueType(0);
4065 if (N0.getValueType() == N->getValueType(0))
4067 // fold (truncate c1) -> c1
4068 if (isa<ConstantSDNode>(N0))
4069 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0);
4070 // fold (truncate (truncate x)) -> (truncate x)
4071 if (N0.getOpcode() == ISD::TRUNCATE)
4072 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
4073 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
4074 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
4075 N0.getOpcode() == ISD::SIGN_EXTEND ||
4076 N0.getOpcode() == ISD::ANY_EXTEND) {
4077 if (N0.getOperand(0).getValueType().bitsLT(VT))
4078 // if the source is smaller than the dest, we still need an extend
4079 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
4081 else if (N0.getOperand(0).getValueType().bitsGT(VT))
4082 // if the source is larger than the dest, than we just need the truncate
4083 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
4085 // if the source and dest are the same type, we can drop both the extend
4086 // and the truncate.
4087 return N0.getOperand(0);
4090 // See if we can simplify the input to this truncate through knowledge that
4091 // only the low bits are being used. For example "trunc (or (shl x, 8), y)"
4094 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
4095 VT.getSizeInBits()));
4096 if (Shorter.getNode())
4097 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Shorter);
4099 // fold (truncate (load x)) -> (smaller load x)
4100 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
4101 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT))
4102 return ReduceLoadWidth(N);
4106 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
4107 SDValue Elt = N->getOperand(i);
4108 if (Elt.getOpcode() != ISD::MERGE_VALUES)
4109 return Elt.getNode();
4110 return Elt.getOperand(Elt.getResNo()).getNode();
4113 /// CombineConsecutiveLoads - build_pair (load, load) -> load
4114 /// if load locations are consecutive.
4115 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
4116 assert(N->getOpcode() == ISD::BUILD_PAIR);
4118 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
4119 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
4120 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse())
4122 EVT LD1VT = LD1->getValueType(0);
4124 if (ISD::isNON_EXTLoad(LD2) &&
4126 // If both are volatile this would reduce the number of volatile loads.
4127 // If one is volatile it might be ok, but play conservative and bail out.
4128 !LD1->isVolatile() &&
4129 !LD2->isVolatile() &&
4130 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
4131 unsigned Align = LD1->getAlignment();
4132 unsigned NewAlign = TLI.getTargetData()->
4133 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
4135 if (NewAlign <= Align &&
4136 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
4137 return DAG.getLoad(VT, N->getDebugLoc(), LD1->getChain(),
4138 LD1->getBasePtr(), LD1->getSrcValue(),
4139 LD1->getSrcValueOffset(), false, false, Align);
4145 SDValue DAGCombiner::visitBIT_CONVERT(SDNode *N) {
4146 SDValue N0 = N->getOperand(0);
4147 EVT VT = N->getValueType(0);
4149 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
4150 // Only do this before legalize, since afterward the target may be depending
4151 // on the bitconvert.
4152 // First check to see if this is all constant.
4154 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
4156 bool isSimple = true;
4157 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
4158 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
4159 N0.getOperand(i).getOpcode() != ISD::Constant &&
4160 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
4165 EVT DestEltVT = N->getValueType(0).getVectorElementType();
4166 assert(!DestEltVT.isVector() &&
4167 "Element type of vector ValueType must not be vector!");
4169 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(N0.getNode(), DestEltVT);
4172 // If the input is a constant, let getNode fold it.
4173 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
4174 SDValue Res = DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, N0);
4175 if (Res.getNode() != N) {
4176 if (!LegalOperations ||
4177 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
4180 // Folding it resulted in an illegal node, and it's too late to
4181 // do that. Clean up the old node and forego the transformation.
4182 // Ideally this won't happen very often, because instcombine
4183 // and the earlier dagcombine runs (where illegal nodes are
4184 // permitted) should have folded most of them already.
4185 DAG.DeleteNode(Res.getNode());
4189 // (conv (conv x, t1), t2) -> (conv x, t2)
4190 if (N0.getOpcode() == ISD::BIT_CONVERT)
4191 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT,
4194 // fold (conv (load x)) -> (load (conv*)x)
4195 // If the resultant load doesn't need a higher alignment than the original!
4196 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
4197 // Do not change the width of a volatile load.
4198 !cast<LoadSDNode>(N0)->isVolatile() &&
4199 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
4200 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4201 unsigned Align = TLI.getTargetData()->
4202 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
4203 unsigned OrigAlign = LN0->getAlignment();
4205 if (Align <= OrigAlign) {
4206 SDValue Load = DAG.getLoad(VT, N->getDebugLoc(), LN0->getChain(),
4208 LN0->getSrcValue(), LN0->getSrcValueOffset(),
4209 LN0->isVolatile(), LN0->isNonTemporal(),
4212 CombineTo(N0.getNode(),
4213 DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(),
4214 N0.getValueType(), Load),
4220 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
4221 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
4222 // This often reduces constant pool loads.
4223 if ((N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FABS) &&
4224 N0.getNode()->hasOneUse() && VT.isInteger() && !VT.isVector()) {
4225 SDValue NewConv = DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(), VT,
4227 AddToWorkList(NewConv.getNode());
4229 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
4230 if (N0.getOpcode() == ISD::FNEG)
4231 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
4232 NewConv, DAG.getConstant(SignBit, VT));
4233 assert(N0.getOpcode() == ISD::FABS);
4234 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4235 NewConv, DAG.getConstant(~SignBit, VT));
4238 // fold (bitconvert (fcopysign cst, x)) ->
4239 // (or (and (bitconvert x), sign), (and cst, (not sign)))
4240 // Note that we don't handle (copysign x, cst) because this can always be
4241 // folded to an fneg or fabs.
4242 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
4243 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
4244 VT.isInteger() && !VT.isVector()) {
4245 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
4246 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
4247 if (isTypeLegal(IntXVT)) {
4248 SDValue X = DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(),
4249 IntXVT, N0.getOperand(1));
4250 AddToWorkList(X.getNode());
4252 // If X has a different width than the result/lhs, sext it or truncate it.
4253 unsigned VTWidth = VT.getSizeInBits();
4254 if (OrigXWidth < VTWidth) {
4255 X = DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, X);
4256 AddToWorkList(X.getNode());
4257 } else if (OrigXWidth > VTWidth) {
4258 // To get the sign bit in the right place, we have to shift it right
4259 // before truncating.
4260 X = DAG.getNode(ISD::SRL, X.getDebugLoc(),
4261 X.getValueType(), X,
4262 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
4263 AddToWorkList(X.getNode());
4264 X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
4265 AddToWorkList(X.getNode());
4268 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
4269 X = DAG.getNode(ISD::AND, X.getDebugLoc(), VT,
4270 X, DAG.getConstant(SignBit, VT));
4271 AddToWorkList(X.getNode());
4273 SDValue Cst = DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(),
4274 VT, N0.getOperand(0));
4275 Cst = DAG.getNode(ISD::AND, Cst.getDebugLoc(), VT,
4276 Cst, DAG.getConstant(~SignBit, VT));
4277 AddToWorkList(Cst.getNode());
4279 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, X, Cst);
4283 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
4284 if (N0.getOpcode() == ISD::BUILD_PAIR) {
4285 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
4286 if (CombineLD.getNode())
4293 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
4294 EVT VT = N->getValueType(0);
4295 return CombineConsecutiveLoads(N, VT);
4298 /// ConstantFoldBIT_CONVERTofBUILD_VECTOR - We know that BV is a build_vector
4299 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
4300 /// destination element value type.
4301 SDValue DAGCombiner::
4302 ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
4303 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
4305 // If this is already the right type, we're done.
4306 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
4308 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
4309 unsigned DstBitSize = DstEltVT.getSizeInBits();
4311 // If this is a conversion of N elements of one type to N elements of another
4312 // type, convert each element. This handles FP<->INT cases.
4313 if (SrcBitSize == DstBitSize) {
4314 SmallVector<SDValue, 8> Ops;
4315 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
4316 SDValue Op = BV->getOperand(i);
4317 // If the vector element type is not legal, the BUILD_VECTOR operands
4318 // are promoted and implicitly truncated. Make that explicit here.
4319 if (Op.getValueType() != SrcEltVT)
4320 Op = DAG.getNode(ISD::TRUNCATE, BV->getDebugLoc(), SrcEltVT, Op);
4321 Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, BV->getDebugLoc(),
4323 AddToWorkList(Ops.back().getNode());
4325 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
4326 BV->getValueType(0).getVectorNumElements());
4327 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
4328 &Ops[0], Ops.size());
4331 // Otherwise, we're growing or shrinking the elements. To avoid having to
4332 // handle annoying details of growing/shrinking FP values, we convert them to
4334 if (SrcEltVT.isFloatingPoint()) {
4335 // Convert the input float vector to a int vector where the elements are the
4337 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
4338 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
4339 BV = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, IntVT).getNode();
4343 // Now we know the input is an integer vector. If the output is a FP type,
4344 // convert to integer first, then to FP of the right size.
4345 if (DstEltVT.isFloatingPoint()) {
4346 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
4347 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
4348 SDNode *Tmp = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, TmpVT).getNode();
4350 // Next, convert to FP elements of the same size.
4351 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(Tmp, DstEltVT);
4354 // Okay, we know the src/dst types are both integers of differing types.
4355 // Handling growing first.
4356 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
4357 if (SrcBitSize < DstBitSize) {
4358 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
4360 SmallVector<SDValue, 8> Ops;
4361 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
4362 i += NumInputsPerOutput) {
4363 bool isLE = TLI.isLittleEndian();
4364 APInt NewBits = APInt(DstBitSize, 0);
4365 bool EltIsUndef = true;
4366 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
4367 // Shift the previously computed bits over.
4368 NewBits <<= SrcBitSize;
4369 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
4370 if (Op.getOpcode() == ISD::UNDEF) continue;
4373 NewBits |= APInt(cast<ConstantSDNode>(Op)->getAPIntValue()).
4374 zextOrTrunc(SrcBitSize).zext(DstBitSize);
4378 Ops.push_back(DAG.getUNDEF(DstEltVT));
4380 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
4383 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
4384 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
4385 &Ops[0], Ops.size());
4388 // Finally, this must be the case where we are shrinking elements: each input
4389 // turns into multiple outputs.
4390 bool isS2V = ISD::isScalarToVector(BV);
4391 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
4392 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
4393 NumOutputsPerInput*BV->getNumOperands());
4394 SmallVector<SDValue, 8> Ops;
4396 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
4397 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
4398 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
4399 Ops.push_back(DAG.getUNDEF(DstEltVT));
4403 APInt OpVal = APInt(cast<ConstantSDNode>(BV->getOperand(i))->
4404 getAPIntValue()).zextOrTrunc(SrcBitSize);
4406 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
4407 APInt ThisVal = APInt(OpVal).trunc(DstBitSize);
4408 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
4409 if (isS2V && i == 0 && j == 0 && APInt(ThisVal).zext(SrcBitSize) == OpVal)
4410 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
4411 return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
4413 OpVal = OpVal.lshr(DstBitSize);
4416 // For big endian targets, swap the order of the pieces of each element.
4417 if (TLI.isBigEndian())
4418 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
4421 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
4422 &Ops[0], Ops.size());
4425 SDValue DAGCombiner::visitFADD(SDNode *N) {
4426 SDValue N0 = N->getOperand(0);
4427 SDValue N1 = N->getOperand(1);
4428 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4429 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4430 EVT VT = N->getValueType(0);
4433 if (VT.isVector()) {
4434 SDValue FoldedVOp = SimplifyVBinOp(N);
4435 if (FoldedVOp.getNode()) return FoldedVOp;
4438 // fold (fadd c1, c2) -> (fadd c1, c2)
4439 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4440 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N1);
4441 // canonicalize constant to RHS
4442 if (N0CFP && !N1CFP)
4443 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N0);
4444 // fold (fadd A, 0) -> A
4445 if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
4447 // fold (fadd A, (fneg B)) -> (fsub A, B)
4448 if (isNegatibleForFree(N1, LegalOperations) == 2)
4449 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0,
4450 GetNegatedExpression(N1, DAG, LegalOperations));
4451 // fold (fadd (fneg A), B) -> (fsub B, A)
4452 if (isNegatibleForFree(N0, LegalOperations) == 2)
4453 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N1,
4454 GetNegatedExpression(N0, DAG, LegalOperations));
4456 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
4457 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FADD &&
4458 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
4459 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0.getOperand(0),
4460 DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
4461 N0.getOperand(1), N1));
4466 SDValue DAGCombiner::visitFSUB(SDNode *N) {
4467 SDValue N0 = N->getOperand(0);
4468 SDValue N1 = N->getOperand(1);
4469 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4470 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4471 EVT VT = N->getValueType(0);
4474 if (VT.isVector()) {
4475 SDValue FoldedVOp = SimplifyVBinOp(N);
4476 if (FoldedVOp.getNode()) return FoldedVOp;
4479 // fold (fsub c1, c2) -> c1-c2
4480 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4481 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0, N1);
4482 // fold (fsub A, 0) -> A
4483 if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
4485 // fold (fsub 0, B) -> -B
4486 if (UnsafeFPMath && N0CFP && N0CFP->getValueAPF().isZero()) {
4487 if (isNegatibleForFree(N1, LegalOperations))
4488 return GetNegatedExpression(N1, DAG, LegalOperations);
4489 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
4490 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N1);
4492 // fold (fsub A, (fneg B)) -> (fadd A, B)
4493 if (isNegatibleForFree(N1, LegalOperations))
4494 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0,
4495 GetNegatedExpression(N1, DAG, LegalOperations));
4500 SDValue DAGCombiner::visitFMUL(SDNode *N) {
4501 SDValue N0 = N->getOperand(0);
4502 SDValue N1 = N->getOperand(1);
4503 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4504 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4505 EVT VT = N->getValueType(0);
4508 if (VT.isVector()) {
4509 SDValue FoldedVOp = SimplifyVBinOp(N);
4510 if (FoldedVOp.getNode()) return FoldedVOp;
4513 // fold (fmul c1, c2) -> c1*c2
4514 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4515 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0, N1);
4516 // canonicalize constant to RHS
4517 if (N0CFP && !N1CFP)
4518 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N1, N0);
4519 // fold (fmul A, 0) -> 0
4520 if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
4522 // fold (fmul A, 0) -> 0, vector edition.
4523 if (UnsafeFPMath && ISD::isBuildVectorAllZeros(N1.getNode()))
4525 // fold (fmul X, 2.0) -> (fadd X, X)
4526 if (N1CFP && N1CFP->isExactlyValue(+2.0))
4527 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N0);
4528 // fold (fmul X, -1.0) -> (fneg X)
4529 if (N1CFP && N1CFP->isExactlyValue(-1.0))
4530 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
4531 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N0);
4533 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
4534 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations)) {
4535 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations)) {
4536 // Both can be negated for free, check to see if at least one is cheaper
4538 if (LHSNeg == 2 || RHSNeg == 2)
4539 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
4540 GetNegatedExpression(N0, DAG, LegalOperations),
4541 GetNegatedExpression(N1, DAG, LegalOperations));
4545 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
4546 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
4547 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
4548 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0.getOperand(0),
4549 DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
4550 N0.getOperand(1), N1));
4555 SDValue DAGCombiner::visitFDIV(SDNode *N) {
4556 SDValue N0 = N->getOperand(0);
4557 SDValue N1 = N->getOperand(1);
4558 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4559 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4560 EVT VT = N->getValueType(0);
4563 if (VT.isVector()) {
4564 SDValue FoldedVOp = SimplifyVBinOp(N);
4565 if (FoldedVOp.getNode()) return FoldedVOp;
4568 // fold (fdiv c1, c2) -> c1/c2
4569 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4570 return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT, N0, N1);
4573 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
4574 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations)) {
4575 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations)) {
4576 // Both can be negated for free, check to see if at least one is cheaper
4578 if (LHSNeg == 2 || RHSNeg == 2)
4579 return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT,
4580 GetNegatedExpression(N0, DAG, LegalOperations),
4581 GetNegatedExpression(N1, DAG, LegalOperations));
4588 SDValue DAGCombiner::visitFREM(SDNode *N) {
4589 SDValue N0 = N->getOperand(0);
4590 SDValue N1 = N->getOperand(1);
4591 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4592 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4593 EVT VT = N->getValueType(0);
4595 // fold (frem c1, c2) -> fmod(c1,c2)
4596 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4597 return DAG.getNode(ISD::FREM, N->getDebugLoc(), VT, N0, N1);
4602 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
4603 SDValue N0 = N->getOperand(0);
4604 SDValue N1 = N->getOperand(1);
4605 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4606 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4607 EVT VT = N->getValueType(0);
4609 if (N0CFP && N1CFP && VT != MVT::ppcf128) // Constant fold
4610 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, N0, N1);
4613 const APFloat& V = N1CFP->getValueAPF();
4614 // copysign(x, c1) -> fabs(x) iff ispos(c1)
4615 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
4616 if (!V.isNegative()) {
4617 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
4618 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
4620 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
4621 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT,
4622 DAG.getNode(ISD::FABS, N0.getDebugLoc(), VT, N0));
4626 // copysign(fabs(x), y) -> copysign(x, y)
4627 // copysign(fneg(x), y) -> copysign(x, y)
4628 // copysign(copysign(x,z), y) -> copysign(x, y)
4629 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
4630 N0.getOpcode() == ISD::FCOPYSIGN)
4631 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
4632 N0.getOperand(0), N1);
4634 // copysign(x, abs(y)) -> abs(x)
4635 if (N1.getOpcode() == ISD::FABS)
4636 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
4638 // copysign(x, copysign(y,z)) -> copysign(x, z)
4639 if (N1.getOpcode() == ISD::FCOPYSIGN)
4640 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
4641 N0, N1.getOperand(1));
4643 // copysign(x, fp_extend(y)) -> copysign(x, y)
4644 // copysign(x, fp_round(y)) -> copysign(x, y)
4645 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
4646 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
4647 N0, N1.getOperand(0));
4652 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
4653 SDValue N0 = N->getOperand(0);
4654 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4655 EVT VT = N->getValueType(0);
4656 EVT OpVT = N0.getValueType();
4658 // fold (sint_to_fp c1) -> c1fp
4659 if (N0C && OpVT != MVT::ppcf128)
4660 return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
4662 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
4663 // but UINT_TO_FP is legal on this target, try to convert.
4664 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
4665 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
4666 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
4667 if (DAG.SignBitIsZero(N0))
4668 return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
4674 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
4675 SDValue N0 = N->getOperand(0);
4676 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4677 EVT VT = N->getValueType(0);
4678 EVT OpVT = N0.getValueType();
4680 // fold (uint_to_fp c1) -> c1fp
4681 if (N0C && OpVT != MVT::ppcf128)
4682 return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
4684 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
4685 // but SINT_TO_FP is legal on this target, try to convert.
4686 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
4687 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
4688 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
4689 if (DAG.SignBitIsZero(N0))
4690 return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
4696 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
4697 SDValue N0 = N->getOperand(0);
4698 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4699 EVT VT = N->getValueType(0);
4701 // fold (fp_to_sint c1fp) -> c1
4703 return DAG.getNode(ISD::FP_TO_SINT, N->getDebugLoc(), VT, N0);
4708 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
4709 SDValue N0 = N->getOperand(0);
4710 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4711 EVT VT = N->getValueType(0);
4713 // fold (fp_to_uint c1fp) -> c1
4714 if (N0CFP && VT != MVT::ppcf128)
4715 return DAG.getNode(ISD::FP_TO_UINT, N->getDebugLoc(), VT, N0);
4720 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
4721 SDValue N0 = N->getOperand(0);
4722 SDValue N1 = N->getOperand(1);
4723 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4724 EVT VT = N->getValueType(0);
4726 // fold (fp_round c1fp) -> c1fp
4727 if (N0CFP && N0.getValueType() != MVT::ppcf128)
4728 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0, N1);
4730 // fold (fp_round (fp_extend x)) -> x
4731 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
4732 return N0.getOperand(0);
4734 // fold (fp_round (fp_round x)) -> (fp_round x)
4735 if (N0.getOpcode() == ISD::FP_ROUND) {
4736 // This is a value preserving truncation if both round's are.
4737 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
4738 N0.getNode()->getConstantOperandVal(1) == 1;
4739 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0.getOperand(0),
4740 DAG.getIntPtrConstant(IsTrunc));
4743 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
4744 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
4745 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(), VT,
4746 N0.getOperand(0), N1);
4747 AddToWorkList(Tmp.getNode());
4748 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
4749 Tmp, N0.getOperand(1));
4755 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
4756 SDValue N0 = N->getOperand(0);
4757 EVT VT = N->getValueType(0);
4758 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
4759 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4761 // fold (fp_round_inreg c1fp) -> c1fp
4762 if (N0CFP && isTypeLegal(EVT)) {
4763 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
4764 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, Round);
4770 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
4771 SDValue N0 = N->getOperand(0);
4772 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4773 EVT VT = N->getValueType(0);
4775 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
4776 if (N->hasOneUse() &&
4777 N->use_begin()->getOpcode() == ISD::FP_ROUND)
4780 // fold (fp_extend c1fp) -> c1fp
4781 if (N0CFP && VT != MVT::ppcf128)
4782 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, N0);
4784 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
4786 if (N0.getOpcode() == ISD::FP_ROUND
4787 && N0.getNode()->getConstantOperandVal(1) == 1) {
4788 SDValue In = N0.getOperand(0);
4789 if (In.getValueType() == VT) return In;
4790 if (VT.bitsLT(In.getValueType()))
4791 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT,
4792 In, N0.getOperand(1));
4793 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, In);
4796 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
4797 if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
4798 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4799 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
4800 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4801 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
4803 LN0->getBasePtr(), LN0->getSrcValue(),
4804 LN0->getSrcValueOffset(),
4806 LN0->isVolatile(), LN0->isNonTemporal(),
4807 LN0->getAlignment());
4808 CombineTo(N, ExtLoad);
4809 CombineTo(N0.getNode(),
4810 DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(),
4811 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
4812 ExtLoad.getValue(1));
4813 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4819 SDValue DAGCombiner::visitFNEG(SDNode *N) {
4820 SDValue N0 = N->getOperand(0);
4821 EVT VT = N->getValueType(0);
4823 if (isNegatibleForFree(N0, LegalOperations))
4824 return GetNegatedExpression(N0, DAG, LegalOperations);
4826 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
4827 // constant pool values.
4828 if (N0.getOpcode() == ISD::BIT_CONVERT &&
4830 N0.getNode()->hasOneUse() &&
4831 N0.getOperand(0).getValueType().isInteger()) {
4832 SDValue Int = N0.getOperand(0);
4833 EVT IntVT = Int.getValueType();
4834 if (IntVT.isInteger() && !IntVT.isVector()) {
4835 Int = DAG.getNode(ISD::XOR, N0.getDebugLoc(), IntVT, Int,
4836 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
4837 AddToWorkList(Int.getNode());
4838 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(),
4846 SDValue DAGCombiner::visitFABS(SDNode *N) {
4847 SDValue N0 = N->getOperand(0);
4848 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4849 EVT VT = N->getValueType(0);
4851 // fold (fabs c1) -> fabs(c1)
4852 if (N0CFP && VT != MVT::ppcf128)
4853 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
4854 // fold (fabs (fabs x)) -> (fabs x)
4855 if (N0.getOpcode() == ISD::FABS)
4856 return N->getOperand(0);
4857 // fold (fabs (fneg x)) -> (fabs x)
4858 // fold (fabs (fcopysign x, y)) -> (fabs x)
4859 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
4860 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0.getOperand(0));
4862 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
4863 // constant pool values.
4864 if (N0.getOpcode() == ISD::BIT_CONVERT && N0.getNode()->hasOneUse() &&
4865 N0.getOperand(0).getValueType().isInteger() &&
4866 !N0.getOperand(0).getValueType().isVector()) {
4867 SDValue Int = N0.getOperand(0);
4868 EVT IntVT = Int.getValueType();
4869 if (IntVT.isInteger() && !IntVT.isVector()) {
4870 Int = DAG.getNode(ISD::AND, N0.getDebugLoc(), IntVT, Int,
4871 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
4872 AddToWorkList(Int.getNode());
4873 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(),
4874 N->getValueType(0), Int);
4881 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
4882 SDValue Chain = N->getOperand(0);
4883 SDValue N1 = N->getOperand(1);
4884 SDValue N2 = N->getOperand(2);
4886 // If N is a constant we could fold this into a fallthrough or unconditional
4887 // branch. However that doesn't happen very often in normal code, because
4888 // Instcombine/SimplifyCFG should have handled the available opportunities.
4889 // If we did this folding here, it would be necessary to update the
4890 // MachineBasicBlock CFG, which is awkward.
4892 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
4894 if (N1.getOpcode() == ISD::SETCC &&
4895 TLI.isOperationLegalOrCustom(ISD::BR_CC, MVT::Other)) {
4896 return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
4897 Chain, N1.getOperand(2),
4898 N1.getOperand(0), N1.getOperand(1), N2);
4902 if (N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) {
4903 // Look past truncate.
4904 Trunc = N1.getNode();
4905 N1 = N1.getOperand(0);
4908 if (N1.hasOneUse() && N1.getOpcode() == ISD::SRL) {
4909 // Match this pattern so that we can generate simpler code:
4912 // %b = and i32 %a, 2
4913 // %c = srl i32 %b, 1
4914 // brcond i32 %c ...
4919 // %b = and i32 %a, 2
4920 // %c = setcc eq %b, 0
4923 // This applies only when the AND constant value has one bit set and the
4924 // SRL constant is equal to the log2 of the AND constant. The back-end is
4925 // smart enough to convert the result into a TEST/JMP sequence.
4926 SDValue Op0 = N1.getOperand(0);
4927 SDValue Op1 = N1.getOperand(1);
4929 if (Op0.getOpcode() == ISD::AND &&
4930 Op1.getOpcode() == ISD::Constant) {
4931 SDValue AndOp1 = Op0.getOperand(1);
4933 if (AndOp1.getOpcode() == ISD::Constant) {
4934 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
4936 if (AndConst.isPowerOf2() &&
4937 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
4939 DAG.getSetCC(N->getDebugLoc(),
4940 TLI.getSetCCResultType(Op0.getValueType()),
4941 Op0, DAG.getConstant(0, Op0.getValueType()),
4944 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
4945 MVT::Other, Chain, SetCC, N2);
4946 // Don't add the new BRCond into the worklist or else SimplifySelectCC
4947 // will convert it back to (X & C1) >> C2.
4948 CombineTo(N, NewBRCond, false);
4949 // Truncate is dead.
4951 removeFromWorkList(Trunc);
4952 DAG.DeleteNode(Trunc);
4954 // Replace the uses of SRL with SETCC
4955 WorkListRemover DeadNodes(*this);
4956 DAG.ReplaceAllUsesOfValueWith(N1, SetCC, &DeadNodes);
4957 removeFromWorkList(N1.getNode());
4958 DAG.DeleteNode(N1.getNode());
4959 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4965 // Transform br(xor(x, y)) -> br(x != y)
4966 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
4967 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
4968 SDNode *TheXor = N1.getNode();
4969 SDValue Op0 = TheXor->getOperand(0);
4970 SDValue Op1 = TheXor->getOperand(1);
4971 if (Op0.getOpcode() == Op1.getOpcode()) {
4972 // Avoid missing important xor optimizations.
4973 SDValue Tmp = visitXOR(TheXor);
4974 if (Tmp.getNode() && Tmp.getNode() != TheXor) {
4975 DEBUG(dbgs() << "\nReplacing.8 ";
4977 dbgs() << "\nWith: ";
4978 Tmp.getNode()->dump(&DAG);
4980 WorkListRemover DeadNodes(*this);
4981 DAG.ReplaceAllUsesOfValueWith(N1, Tmp, &DeadNodes);
4982 removeFromWorkList(TheXor);
4983 DAG.DeleteNode(TheXor);
4984 return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
4985 MVT::Other, Chain, Tmp, N2);
4989 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
4991 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
4992 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
4993 Op0.getOpcode() == ISD::XOR) {
4994 TheXor = Op0.getNode();
4998 SDValue NodeToReplace = Trunc ? SDValue(Trunc, 0) : N1;
5000 EVT SetCCVT = NodeToReplace.getValueType();
5002 SetCCVT = TLI.getSetCCResultType(SetCCVT);
5003 SDValue SetCC = DAG.getSetCC(TheXor->getDebugLoc(),
5006 Equal ? ISD::SETEQ : ISD::SETNE);
5007 // Replace the uses of XOR with SETCC
5008 WorkListRemover DeadNodes(*this);
5009 DAG.ReplaceAllUsesOfValueWith(NodeToReplace, SetCC, &DeadNodes);
5010 removeFromWorkList(NodeToReplace.getNode());
5011 DAG.DeleteNode(NodeToReplace.getNode());
5012 return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
5013 MVT::Other, Chain, SetCC, N2);
5020 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
5022 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
5023 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
5024 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
5026 // If N is a constant we could fold this into a fallthrough or unconditional
5027 // branch. However that doesn't happen very often in normal code, because
5028 // Instcombine/SimplifyCFG should have handled the available opportunities.
5029 // If we did this folding here, it would be necessary to update the
5030 // MachineBasicBlock CFG, which is awkward.
5032 // Use SimplifySetCC to simplify SETCC's.
5033 SDValue Simp = SimplifySetCC(TLI.getSetCCResultType(CondLHS.getValueType()),
5034 CondLHS, CondRHS, CC->get(), N->getDebugLoc(),
5036 if (Simp.getNode()) AddToWorkList(Simp.getNode());
5038 // fold to a simpler setcc
5039 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
5040 return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
5041 N->getOperand(0), Simp.getOperand(2),
5042 Simp.getOperand(0), Simp.getOperand(1),
5048 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
5049 /// pre-indexed load / store when the base pointer is an add or subtract
5050 /// and it has other uses besides the load / store. After the
5051 /// transformation, the new indexed load / store has effectively folded
5052 /// the add / subtract in and all of its other uses are redirected to the
5053 /// new load / store.
5054 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
5055 if (!LegalOperations)
5061 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
5062 if (LD->isIndexed())
5064 VT = LD->getMemoryVT();
5065 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
5066 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
5068 Ptr = LD->getBasePtr();
5069 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
5070 if (ST->isIndexed())
5072 VT = ST->getMemoryVT();
5073 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
5074 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
5076 Ptr = ST->getBasePtr();
5082 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
5083 // out. There is no reason to make this a preinc/predec.
5084 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
5085 Ptr.getNode()->hasOneUse())
5088 // Ask the target to do addressing mode selection.
5091 ISD::MemIndexedMode AM = ISD::UNINDEXED;
5092 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
5094 // Don't create a indexed load / store with zero offset.
5095 if (isa<ConstantSDNode>(Offset) &&
5096 cast<ConstantSDNode>(Offset)->isNullValue())
5099 // Try turning it into a pre-indexed load / store except when:
5100 // 1) The new base ptr is a frame index.
5101 // 2) If N is a store and the new base ptr is either the same as or is a
5102 // predecessor of the value being stored.
5103 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
5104 // that would create a cycle.
5105 // 4) All uses are load / store ops that use it as old base ptr.
5107 // Check #1. Preinc'ing a frame index would require copying the stack pointer
5108 // (plus the implicit offset) to a register to preinc anyway.
5109 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
5114 SDValue Val = cast<StoreSDNode>(N)->getValue();
5115 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
5119 // Now check for #3 and #4.
5120 bool RealUse = false;
5121 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
5122 E = Ptr.getNode()->use_end(); I != E; ++I) {
5126 if (Use->isPredecessorOf(N))
5129 if (!((Use->getOpcode() == ISD::LOAD &&
5130 cast<LoadSDNode>(Use)->getBasePtr() == Ptr) ||
5131 (Use->getOpcode() == ISD::STORE &&
5132 cast<StoreSDNode>(Use)->getBasePtr() == Ptr)))
5141 Result = DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
5142 BasePtr, Offset, AM);
5144 Result = DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
5145 BasePtr, Offset, AM);
5148 DEBUG(dbgs() << "\nReplacing.4 ";
5150 dbgs() << "\nWith: ";
5151 Result.getNode()->dump(&DAG);
5153 WorkListRemover DeadNodes(*this);
5155 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
5157 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
5160 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
5164 // Finally, since the node is now dead, remove it from the graph.
5167 // Replace the uses of Ptr with uses of the updated base value.
5168 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
5170 removeFromWorkList(Ptr.getNode());
5171 DAG.DeleteNode(Ptr.getNode());
5176 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
5177 /// add / sub of the base pointer node into a post-indexed load / store.
5178 /// The transformation folded the add / subtract into the new indexed
5179 /// load / store effectively and all of its uses are redirected to the
5180 /// new load / store.
5181 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
5182 if (!LegalOperations)
5188 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
5189 if (LD->isIndexed())
5191 VT = LD->getMemoryVT();
5192 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
5193 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
5195 Ptr = LD->getBasePtr();
5196 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
5197 if (ST->isIndexed())
5199 VT = ST->getMemoryVT();
5200 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
5201 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
5203 Ptr = ST->getBasePtr();
5209 if (Ptr.getNode()->hasOneUse())
5212 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
5213 E = Ptr.getNode()->use_end(); I != E; ++I) {
5216 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
5221 ISD::MemIndexedMode AM = ISD::UNINDEXED;
5222 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
5223 if (Ptr == Offset && Op->getOpcode() == ISD::ADD)
5224 std::swap(BasePtr, Offset);
5227 // Don't create a indexed load / store with zero offset.
5228 if (isa<ConstantSDNode>(Offset) &&
5229 cast<ConstantSDNode>(Offset)->isNullValue())
5232 // Try turning it into a post-indexed load / store except when
5233 // 1) All uses are load / store ops that use it as base ptr.
5234 // 2) Op must be independent of N, i.e. Op is neither a predecessor
5235 // nor a successor of N. Otherwise, if Op is folded that would
5238 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
5242 bool TryNext = false;
5243 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
5244 EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
5246 if (Use == Ptr.getNode())
5249 // If all the uses are load / store addresses, then don't do the
5251 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
5252 bool RealUse = false;
5253 for (SDNode::use_iterator III = Use->use_begin(),
5254 EEE = Use->use_end(); III != EEE; ++III) {
5255 SDNode *UseUse = *III;
5256 if (!((UseUse->getOpcode() == ISD::LOAD &&
5257 cast<LoadSDNode>(UseUse)->getBasePtr().getNode() == Use) ||
5258 (UseUse->getOpcode() == ISD::STORE &&
5259 cast<StoreSDNode>(UseUse)->getBasePtr().getNode() == Use)))
5274 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
5275 SDValue Result = isLoad
5276 ? DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
5277 BasePtr, Offset, AM)
5278 : DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
5279 BasePtr, Offset, AM);
5282 DEBUG(dbgs() << "\nReplacing.5 ";
5284 dbgs() << "\nWith: ";
5285 Result.getNode()->dump(&DAG);
5287 WorkListRemover DeadNodes(*this);
5289 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
5291 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
5294 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
5298 // Finally, since the node is now dead, remove it from the graph.
5301 // Replace the uses of Use with uses of the updated base value.
5302 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
5303 Result.getValue(isLoad ? 1 : 0),
5305 removeFromWorkList(Op);
5315 SDValue DAGCombiner::visitLOAD(SDNode *N) {
5316 LoadSDNode *LD = cast<LoadSDNode>(N);
5317 SDValue Chain = LD->getChain();
5318 SDValue Ptr = LD->getBasePtr();
5320 // If load is not volatile and there are no uses of the loaded value (and
5321 // the updated indexed value in case of indexed loads), change uses of the
5322 // chain value into uses of the chain input (i.e. delete the dead load).
5323 if (!LD->isVolatile()) {
5324 if (N->getValueType(1) == MVT::Other) {
5326 if (N->hasNUsesOfValue(0, 0)) {
5327 // It's not safe to use the two value CombineTo variant here. e.g.
5328 // v1, chain2 = load chain1, loc
5329 // v2, chain3 = load chain2, loc
5331 // Now we replace use of chain2 with chain1. This makes the second load
5332 // isomorphic to the one we are deleting, and thus makes this load live.
5333 DEBUG(dbgs() << "\nReplacing.6 ";
5335 dbgs() << "\nWith chain: ";
5336 Chain.getNode()->dump(&DAG);
5338 WorkListRemover DeadNodes(*this);
5339 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain, &DeadNodes);
5341 if (N->use_empty()) {
5342 removeFromWorkList(N);
5346 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5350 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
5351 if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) {
5352 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
5353 DEBUG(dbgs() << "\nReplacing.7 ";
5355 dbgs() << "\nWith: ";
5356 Undef.getNode()->dump(&DAG);
5357 dbgs() << " and 2 other values\n");
5358 WorkListRemover DeadNodes(*this);
5359 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef, &DeadNodes);
5360 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
5361 DAG.getUNDEF(N->getValueType(1)),
5363 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain, &DeadNodes);
5364 removeFromWorkList(N);
5366 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5371 // If this load is directly stored, replace the load value with the stored
5373 // TODO: Handle store large -> read small portion.
5374 // TODO: Handle TRUNCSTORE/LOADEXT
5375 if (LD->getExtensionType() == ISD::NON_EXTLOAD &&
5376 !LD->isVolatile()) {
5377 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
5378 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
5379 if (PrevST->getBasePtr() == Ptr &&
5380 PrevST->getValue().getValueType() == N->getValueType(0))
5381 return CombineTo(N, Chain.getOperand(1), Chain);
5385 // Try to infer better alignment information than the load already has.
5386 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
5387 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
5388 if (Align > LD->getAlignment())
5389 return DAG.getExtLoad(LD->getExtensionType(), N->getDebugLoc(),
5390 LD->getValueType(0),
5391 Chain, Ptr, LD->getSrcValue(),
5392 LD->getSrcValueOffset(), LD->getMemoryVT(),
5393 LD->isVolatile(), LD->isNonTemporal(), Align);
5398 // Walk up chain skipping non-aliasing memory nodes.
5399 SDValue BetterChain = FindBetterChain(N, Chain);
5401 // If there is a better chain.
5402 if (Chain != BetterChain) {
5405 // Replace the chain to void dependency.
5406 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
5407 ReplLoad = DAG.getLoad(N->getValueType(0), LD->getDebugLoc(),
5409 LD->getSrcValue(), LD->getSrcValueOffset(),
5410 LD->isVolatile(), LD->isNonTemporal(),
5411 LD->getAlignment());
5413 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), LD->getDebugLoc(),
5414 LD->getValueType(0),
5415 BetterChain, Ptr, LD->getSrcValue(),
5416 LD->getSrcValueOffset(),
5419 LD->isNonTemporal(),
5420 LD->getAlignment());
5423 // Create token factor to keep old chain connected.
5424 SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
5425 MVT::Other, Chain, ReplLoad.getValue(1));
5427 // Make sure the new and old chains are cleaned up.
5428 AddToWorkList(Token.getNode());
5430 // Replace uses with load result and token factor. Don't add users
5432 return CombineTo(N, ReplLoad.getValue(0), Token, false);
5436 // Try transforming N to an indexed load.
5437 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
5438 return SDValue(N, 0);
5440 if (PromoteLoad(SDValue(N, 0)))
5441 return SDValue(N, 0);
5445 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
5446 /// load is having specific bytes cleared out. If so, return the byte size
5447 /// being masked out and the shift amount.
5448 static std::pair<unsigned, unsigned>
5449 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
5450 std::pair<unsigned, unsigned> Result(0, 0);
5452 // Check for the structure we're looking for.
5453 if (V->getOpcode() != ISD::AND ||
5454 !isa<ConstantSDNode>(V->getOperand(1)) ||
5455 !ISD::isNormalLoad(V->getOperand(0).getNode()))
5458 // Check the chain and pointer.
5459 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
5460 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
5462 // The store should be chained directly to the load or be an operand of a
5464 if (LD == Chain.getNode())
5466 else if (Chain->getOpcode() != ISD::TokenFactor)
5467 return Result; // Fail.
5470 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
5471 if (Chain->getOperand(i).getNode() == LD) {
5475 if (!isOk) return Result;
5478 // This only handles simple types.
5479 if (V.getValueType() != MVT::i16 &&
5480 V.getValueType() != MVT::i32 &&
5481 V.getValueType() != MVT::i64)
5484 // Check the constant mask. Invert it so that the bits being masked out are
5485 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
5486 // follow the sign bit for uniformity.
5487 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
5488 unsigned NotMaskLZ = CountLeadingZeros_64(NotMask);
5489 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
5490 unsigned NotMaskTZ = CountTrailingZeros_64(NotMask);
5491 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
5492 if (NotMaskLZ == 64) return Result; // All zero mask.
5494 // See if we have a continuous run of bits. If so, we have 0*1+0*
5495 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
5498 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
5499 if (V.getValueType() != MVT::i64 && NotMaskLZ)
5500 NotMaskLZ -= 64-V.getValueSizeInBits();
5502 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
5503 switch (MaskedBytes) {
5507 default: return Result; // All one mask, or 5-byte mask.
5510 // Verify that the first bit starts at a multiple of mask so that the access
5511 // is aligned the same as the access width.
5512 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
5514 Result.first = MaskedBytes;
5515 Result.second = NotMaskTZ/8;
5520 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
5521 /// provides a value as specified by MaskInfo. If so, replace the specified
5522 /// store with a narrower store of truncated IVal.
5524 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
5525 SDValue IVal, StoreSDNode *St,
5527 unsigned NumBytes = MaskInfo.first;
5528 unsigned ByteShift = MaskInfo.second;
5529 SelectionDAG &DAG = DC->getDAG();
5531 // Check to see if IVal is all zeros in the part being masked in by the 'or'
5532 // that uses this. If not, this is not a replacement.
5533 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
5534 ByteShift*8, (ByteShift+NumBytes)*8);
5535 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
5537 // Check that it is legal on the target to do this. It is legal if the new
5538 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
5540 MVT VT = MVT::getIntegerVT(NumBytes*8);
5541 if (!DC->isTypeLegal(VT))
5544 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
5545 // shifted by ByteShift and truncated down to NumBytes.
5547 IVal = DAG.getNode(ISD::SRL, IVal->getDebugLoc(), IVal.getValueType(), IVal,
5548 DAG.getConstant(ByteShift*8, DC->getShiftAmountTy()));
5550 // Figure out the offset for the store and the alignment of the access.
5552 unsigned NewAlign = St->getAlignment();
5554 if (DAG.getTargetLoweringInfo().isLittleEndian())
5555 StOffset = ByteShift;
5557 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
5559 SDValue Ptr = St->getBasePtr();
5561 Ptr = DAG.getNode(ISD::ADD, IVal->getDebugLoc(), Ptr.getValueType(),
5562 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
5563 NewAlign = MinAlign(NewAlign, StOffset);
5566 // Truncate down to the new size.
5567 IVal = DAG.getNode(ISD::TRUNCATE, IVal->getDebugLoc(), VT, IVal);
5570 return DAG.getStore(St->getChain(), St->getDebugLoc(), IVal, Ptr,
5571 St->getSrcValue(), St->getSrcValueOffset()+StOffset,
5572 false, false, NewAlign).getNode();
5576 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
5577 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
5578 /// of the loaded bits, try narrowing the load and store if it would end up
5579 /// being a win for performance or code size.
5580 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
5581 StoreSDNode *ST = cast<StoreSDNode>(N);
5582 if (ST->isVolatile())
5585 SDValue Chain = ST->getChain();
5586 SDValue Value = ST->getValue();
5587 SDValue Ptr = ST->getBasePtr();
5588 EVT VT = Value.getValueType();
5590 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
5593 unsigned Opc = Value.getOpcode();
5595 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
5596 // is a byte mask indicating a consecutive number of bytes, check to see if
5597 // Y is known to provide just those bytes. If so, we try to replace the
5598 // load + replace + store sequence with a single (narrower) store, which makes
5600 if (Opc == ISD::OR) {
5601 std::pair<unsigned, unsigned> MaskedLoad;
5602 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
5603 if (MaskedLoad.first)
5604 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
5605 Value.getOperand(1), ST,this))
5606 return SDValue(NewST, 0);
5608 // Or is commutative, so try swapping X and Y.
5609 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
5610 if (MaskedLoad.first)
5611 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
5612 Value.getOperand(0), ST,this))
5613 return SDValue(NewST, 0);
5616 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
5617 Value.getOperand(1).getOpcode() != ISD::Constant)
5620 SDValue N0 = Value.getOperand(0);
5621 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse()) {
5622 LoadSDNode *LD = cast<LoadSDNode>(N0);
5623 if (LD->getBasePtr() != Ptr)
5626 // Find the type to narrow it the load / op / store to.
5627 SDValue N1 = Value.getOperand(1);
5628 unsigned BitWidth = N1.getValueSizeInBits();
5629 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
5630 if (Opc == ISD::AND)
5631 Imm ^= APInt::getAllOnesValue(BitWidth);
5632 if (Imm == 0 || Imm.isAllOnesValue())
5634 unsigned ShAmt = Imm.countTrailingZeros();
5635 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
5636 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
5637 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
5638 while (NewBW < BitWidth &&
5639 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
5640 TLI.isNarrowingProfitable(VT, NewVT))) {
5641 NewBW = NextPowerOf2(NewBW);
5642 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
5644 if (NewBW >= BitWidth)
5647 // If the lsb changed does not start at the type bitwidth boundary,
5648 // start at the previous one.
5650 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
5651 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, ShAmt + NewBW);
5652 if ((Imm & Mask) == Imm) {
5653 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
5654 if (Opc == ISD::AND)
5655 NewImm ^= APInt::getAllOnesValue(NewBW);
5656 uint64_t PtrOff = ShAmt / 8;
5657 // For big endian targets, we need to adjust the offset to the pointer to
5658 // load the correct bytes.
5659 if (TLI.isBigEndian())
5660 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
5662 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
5663 const Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
5664 if (NewAlign < TLI.getTargetData()->getABITypeAlignment(NewVTTy))
5667 SDValue NewPtr = DAG.getNode(ISD::ADD, LD->getDebugLoc(),
5668 Ptr.getValueType(), Ptr,
5669 DAG.getConstant(PtrOff, Ptr.getValueType()));
5670 SDValue NewLD = DAG.getLoad(NewVT, N0.getDebugLoc(),
5671 LD->getChain(), NewPtr,
5672 LD->getSrcValue(), LD->getSrcValueOffset(),
5673 LD->isVolatile(), LD->isNonTemporal(),
5675 SDValue NewVal = DAG.getNode(Opc, Value.getDebugLoc(), NewVT, NewLD,
5676 DAG.getConstant(NewImm, NewVT));
5677 SDValue NewST = DAG.getStore(Chain, N->getDebugLoc(),
5679 ST->getSrcValue(), ST->getSrcValueOffset(),
5680 false, false, NewAlign);
5682 AddToWorkList(NewPtr.getNode());
5683 AddToWorkList(NewLD.getNode());
5684 AddToWorkList(NewVal.getNode());
5685 WorkListRemover DeadNodes(*this);
5686 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1),
5696 SDValue DAGCombiner::visitSTORE(SDNode *N) {
5697 StoreSDNode *ST = cast<StoreSDNode>(N);
5698 SDValue Chain = ST->getChain();
5699 SDValue Value = ST->getValue();
5700 SDValue Ptr = ST->getBasePtr();
5702 // If this is a store of a bit convert, store the input value if the
5703 // resultant store does not need a higher alignment than the original.
5704 if (Value.getOpcode() == ISD::BIT_CONVERT && !ST->isTruncatingStore() &&
5705 ST->isUnindexed()) {
5706 unsigned OrigAlign = ST->getAlignment();
5707 EVT SVT = Value.getOperand(0).getValueType();
5708 unsigned Align = TLI.getTargetData()->
5709 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
5710 if (Align <= OrigAlign &&
5711 ((!LegalOperations && !ST->isVolatile()) ||
5712 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
5713 return DAG.getStore(Chain, N->getDebugLoc(), Value.getOperand(0),
5714 Ptr, ST->getSrcValue(),
5715 ST->getSrcValueOffset(), ST->isVolatile(),
5716 ST->isNonTemporal(), OrigAlign);
5719 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
5720 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
5721 // NOTE: If the original store is volatile, this transform must not increase
5722 // the number of stores. For example, on x86-32 an f64 can be stored in one
5723 // processor operation but an i64 (which is not legal) requires two. So the
5724 // transform should not be done in this case.
5725 if (Value.getOpcode() != ISD::TargetConstantFP) {
5727 switch (CFP->getValueType(0).getSimpleVT().SimpleTy) {
5728 default: llvm_unreachable("Unknown FP type");
5729 case MVT::f80: // We don't do this for these yet.
5734 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
5735 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
5736 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
5737 bitcastToAPInt().getZExtValue(), MVT::i32);
5738 return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
5739 Ptr, ST->getSrcValue(),
5740 ST->getSrcValueOffset(), ST->isVolatile(),
5741 ST->isNonTemporal(), ST->getAlignment());
5745 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
5746 !ST->isVolatile()) ||
5747 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
5748 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
5749 getZExtValue(), MVT::i64);
5750 return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
5751 Ptr, ST->getSrcValue(),
5752 ST->getSrcValueOffset(), ST->isVolatile(),
5753 ST->isNonTemporal(), ST->getAlignment());
5754 } else if (!ST->isVolatile() &&
5755 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
5756 // Many FP stores are not made apparent until after legalize, e.g. for
5757 // argument passing. Since this is so common, custom legalize the
5758 // 64-bit integer store into two 32-bit stores.
5759 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
5760 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
5761 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
5762 if (TLI.isBigEndian()) std::swap(Lo, Hi);
5764 int SVOffset = ST->getSrcValueOffset();
5765 unsigned Alignment = ST->getAlignment();
5766 bool isVolatile = ST->isVolatile();
5767 bool isNonTemporal = ST->isNonTemporal();
5769 SDValue St0 = DAG.getStore(Chain, ST->getDebugLoc(), Lo,
5770 Ptr, ST->getSrcValue(),
5771 ST->getSrcValueOffset(),
5772 isVolatile, isNonTemporal,
5773 ST->getAlignment());
5774 Ptr = DAG.getNode(ISD::ADD, N->getDebugLoc(), Ptr.getValueType(), Ptr,
5775 DAG.getConstant(4, Ptr.getValueType()));
5777 Alignment = MinAlign(Alignment, 4U);
5778 SDValue St1 = DAG.getStore(Chain, ST->getDebugLoc(), Hi,
5779 Ptr, ST->getSrcValue(),
5780 SVOffset, isVolatile, isNonTemporal,
5782 return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
5791 // Try to infer better alignment information than the store already has.
5792 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
5793 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
5794 if (Align > ST->getAlignment())
5795 return DAG.getTruncStore(Chain, N->getDebugLoc(), Value,
5796 Ptr, ST->getSrcValue(),
5797 ST->getSrcValueOffset(), ST->getMemoryVT(),
5798 ST->isVolatile(), ST->isNonTemporal(), Align);
5803 // Walk up chain skipping non-aliasing memory nodes.
5804 SDValue BetterChain = FindBetterChain(N, Chain);
5806 // If there is a better chain.
5807 if (Chain != BetterChain) {
5810 // Replace the chain to avoid dependency.
5811 if (ST->isTruncatingStore()) {
5812 ReplStore = DAG.getTruncStore(BetterChain, N->getDebugLoc(), Value, Ptr,
5813 ST->getSrcValue(),ST->getSrcValueOffset(),
5814 ST->getMemoryVT(), ST->isVolatile(),
5815 ST->isNonTemporal(), ST->getAlignment());
5817 ReplStore = DAG.getStore(BetterChain, N->getDebugLoc(), Value, Ptr,
5818 ST->getSrcValue(), ST->getSrcValueOffset(),
5819 ST->isVolatile(), ST->isNonTemporal(),
5820 ST->getAlignment());
5823 // Create token to keep both nodes around.
5824 SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
5825 MVT::Other, Chain, ReplStore);
5827 // Make sure the new and old chains are cleaned up.
5828 AddToWorkList(Token.getNode());
5830 // Don't add users to work list.
5831 return CombineTo(N, Token, false);
5835 // Try transforming N to an indexed store.
5836 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
5837 return SDValue(N, 0);
5839 // FIXME: is there such a thing as a truncating indexed store?
5840 if (ST->isTruncatingStore() && ST->isUnindexed() &&
5841 Value.getValueType().isInteger()) {
5842 // See if we can simplify the input to this truncstore with knowledge that
5843 // only the low bits are being used. For example:
5844 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
5846 GetDemandedBits(Value,
5847 APInt::getLowBitsSet(Value.getValueSizeInBits(),
5848 ST->getMemoryVT().getSizeInBits()));
5849 AddToWorkList(Value.getNode());
5850 if (Shorter.getNode())
5851 return DAG.getTruncStore(Chain, N->getDebugLoc(), Shorter,
5852 Ptr, ST->getSrcValue(),
5853 ST->getSrcValueOffset(), ST->getMemoryVT(),
5854 ST->isVolatile(), ST->isNonTemporal(),
5855 ST->getAlignment());
5857 // Otherwise, see if we can simplify the operation with
5858 // SimplifyDemandedBits, which only works if the value has a single use.
5859 if (SimplifyDemandedBits(Value,
5860 APInt::getLowBitsSet(
5861 Value.getValueType().getScalarType().getSizeInBits(),
5862 ST->getMemoryVT().getScalarType().getSizeInBits())))
5863 return SDValue(N, 0);
5866 // If this is a load followed by a store to the same location, then the store
5868 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
5869 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
5870 ST->isUnindexed() && !ST->isVolatile() &&
5871 // There can't be any side effects between the load and store, such as
5873 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
5874 // The store is dead, remove it.
5879 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
5880 // truncating store. We can do this even if this is already a truncstore.
5881 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
5882 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
5883 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
5884 ST->getMemoryVT())) {
5885 return DAG.getTruncStore(Chain, N->getDebugLoc(), Value.getOperand(0),
5886 Ptr, ST->getSrcValue(),
5887 ST->getSrcValueOffset(), ST->getMemoryVT(),
5888 ST->isVolatile(), ST->isNonTemporal(),
5889 ST->getAlignment());
5892 return ReduceLoadOpStoreWidth(N);
5895 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
5896 SDValue InVec = N->getOperand(0);
5897 SDValue InVal = N->getOperand(1);
5898 SDValue EltNo = N->getOperand(2);
5900 // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
5901 // vector with the inserted element.
5902 if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
5903 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5904 SmallVector<SDValue, 8> Ops(InVec.getNode()->op_begin(),
5905 InVec.getNode()->op_end());
5906 if (Elt < Ops.size())
5908 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
5909 InVec.getValueType(), &Ops[0], Ops.size());
5911 // If the invec is an UNDEF and if EltNo is a constant, create a new
5912 // BUILD_VECTOR with undef elements and the inserted element.
5913 if (!LegalOperations && InVec.getOpcode() == ISD::UNDEF &&
5914 isa<ConstantSDNode>(EltNo)) {
5915 EVT VT = InVec.getValueType();
5916 EVT EltVT = VT.getVectorElementType();
5917 unsigned NElts = VT.getVectorNumElements();
5918 SmallVector<SDValue, 8> Ops(NElts, DAG.getUNDEF(EltVT));
5920 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5921 if (Elt < Ops.size())
5923 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
5924 InVec.getValueType(), &Ops[0], Ops.size());
5929 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
5930 // (vextract (scalar_to_vector val, 0) -> val
5931 SDValue InVec = N->getOperand(0);
5933 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5934 // Check if the result type doesn't match the inserted element type. A
5935 // SCALAR_TO_VECTOR may truncate the inserted element and the
5936 // EXTRACT_VECTOR_ELT may widen the extracted vector.
5937 EVT EltVT = InVec.getValueType().getVectorElementType();
5938 SDValue InOp = InVec.getOperand(0);
5939 EVT NVT = N->getValueType(0);
5940 if (InOp.getValueType() != NVT) {
5941 assert(InOp.getValueType().isInteger() && NVT.isInteger());
5942 return DAG.getSExtOrTrunc(InOp, InVec.getDebugLoc(), NVT);
5947 // Perform only after legalization to ensure build_vector / vector_shuffle
5948 // optimizations have already been done.
5949 if (!LegalOperations) return SDValue();
5951 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
5952 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
5953 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
5954 SDValue EltNo = N->getOperand(1);
5956 if (isa<ConstantSDNode>(EltNo)) {
5957 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5958 bool NewLoad = false;
5959 bool BCNumEltsChanged = false;
5960 EVT VT = InVec.getValueType();
5961 EVT ExtVT = VT.getVectorElementType();
5964 if (InVec.getOpcode() == ISD::BIT_CONVERT) {
5965 EVT BCVT = InVec.getOperand(0).getValueType();
5966 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
5968 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
5969 BCNumEltsChanged = true;
5970 InVec = InVec.getOperand(0);
5971 ExtVT = BCVT.getVectorElementType();
5975 LoadSDNode *LN0 = NULL;
5976 const ShuffleVectorSDNode *SVN = NULL;
5977 if (ISD::isNormalLoad(InVec.getNode())) {
5978 LN0 = cast<LoadSDNode>(InVec);
5979 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5980 InVec.getOperand(0).getValueType() == ExtVT &&
5981 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
5982 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
5983 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
5984 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
5986 // (load $addr+1*size)
5988 // If the bit convert changed the number of elements, it is unsafe
5989 // to examine the mask.
5990 if (BCNumEltsChanged)
5993 // Select the input vector, guarding against out of range extract vector.
5994 unsigned NumElems = VT.getVectorNumElements();
5995 int Idx = (Elt > NumElems) ? -1 : SVN->getMaskElt(Elt);
5996 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
5998 if (InVec.getOpcode() == ISD::BIT_CONVERT)
5999 InVec = InVec.getOperand(0);
6000 if (ISD::isNormalLoad(InVec.getNode())) {
6001 LN0 = cast<LoadSDNode>(InVec);
6002 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
6006 if (!LN0 || !LN0->hasOneUse() || LN0->isVolatile())
6009 unsigned Align = LN0->getAlignment();
6011 // Check the resultant load doesn't need a higher alignment than the
6014 TLI.getTargetData()->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
6016 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
6022 SDValue NewPtr = LN0->getBasePtr();
6024 unsigned PtrOff = LVT.getSizeInBits() * Elt / 8;
6025 EVT PtrType = NewPtr.getValueType();
6026 if (TLI.isBigEndian())
6027 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
6028 NewPtr = DAG.getNode(ISD::ADD, N->getDebugLoc(), PtrType, NewPtr,
6029 DAG.getConstant(PtrOff, PtrType));
6032 return DAG.getLoad(LVT, N->getDebugLoc(), LN0->getChain(), NewPtr,
6033 LN0->getSrcValue(), LN0->getSrcValueOffset(),
6034 LN0->isVolatile(), LN0->isNonTemporal(), Align);
6040 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
6041 unsigned NumInScalars = N->getNumOperands();
6042 EVT VT = N->getValueType(0);
6044 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
6045 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
6046 // at most two distinct vectors, turn this into a shuffle node.
6047 SDValue VecIn1, VecIn2;
6048 for (unsigned i = 0; i != NumInScalars; ++i) {
6049 // Ignore undef inputs.
6050 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6052 // If this input is something other than a EXTRACT_VECTOR_ELT with a
6053 // constant index, bail out.
6054 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6055 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
6056 VecIn1 = VecIn2 = SDValue(0, 0);
6060 // If the input vector type disagrees with the result of the build_vector,
6061 // we can't make a shuffle.
6062 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
6063 if (ExtractedFromVec.getValueType() != VT) {
6064 VecIn1 = VecIn2 = SDValue(0, 0);
6068 // Otherwise, remember this. We allow up to two distinct input vectors.
6069 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
6072 if (VecIn1.getNode() == 0) {
6073 VecIn1 = ExtractedFromVec;
6074 } else if (VecIn2.getNode() == 0) {
6075 VecIn2 = ExtractedFromVec;
6078 VecIn1 = VecIn2 = SDValue(0, 0);
6083 // If everything is good, we can make a shuffle operation.
6084 if (VecIn1.getNode()) {
6085 SmallVector<int, 8> Mask;
6086 for (unsigned i = 0; i != NumInScalars; ++i) {
6087 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
6092 // If extracting from the first vector, just use the index directly.
6093 SDValue Extract = N->getOperand(i);
6094 SDValue ExtVal = Extract.getOperand(1);
6095 if (Extract.getOperand(0) == VecIn1) {
6096 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
6097 if (ExtIndex > VT.getVectorNumElements())
6100 Mask.push_back(ExtIndex);
6104 // Otherwise, use InIdx + VecSize
6105 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
6106 Mask.push_back(Idx+NumInScalars);
6109 // Add count and size info.
6110 if (!isTypeLegal(VT))
6113 // Return the new VECTOR_SHUFFLE node.
6116 Ops[1] = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6117 return DAG.getVectorShuffle(VT, N->getDebugLoc(), Ops[0], Ops[1], &Mask[0]);
6123 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
6124 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
6125 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
6126 // inputs come from at most two distinct vectors, turn this into a shuffle
6129 // If we only have one input vector, we don't need to do any concatenation.
6130 if (N->getNumOperands() == 1)
6131 return N->getOperand(0);
6136 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
6139 EVT VT = N->getValueType(0);
6140 unsigned NumElts = VT.getVectorNumElements();
6142 SDValue N0 = N->getOperand(0);
6144 assert(N0.getValueType().getVectorNumElements() == NumElts &&
6145 "Vector shuffle must be normalized in DAG");
6147 // FIXME: implement canonicalizations from DAG.getVectorShuffle()
6149 // If it is a splat, check if the argument vector is a build_vector with
6150 // all scalar elements the same.
6151 if (cast<ShuffleVectorSDNode>(N)->isSplat()) {
6152 SDNode *V = N0.getNode();
6155 // If this is a bit convert that changes the element type of the vector but
6156 // not the number of vector elements, look through it. Be careful not to
6157 // look though conversions that change things like v4f32 to v2f64.
6158 if (V->getOpcode() == ISD::BIT_CONVERT) {
6159 SDValue ConvInput = V->getOperand(0);
6160 if (ConvInput.getValueType().isVector() &&
6161 ConvInput.getValueType().getVectorNumElements() == NumElts)
6162 V = ConvInput.getNode();
6165 if (V->getOpcode() == ISD::BUILD_VECTOR) {
6166 unsigned NumElems = V->getNumOperands();
6167 unsigned BaseIdx = cast<ShuffleVectorSDNode>(N)->getSplatIndex();
6168 if (NumElems > BaseIdx) {
6170 bool AllSame = true;
6171 for (unsigned i = 0; i != NumElems; ++i) {
6172 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
6173 Base = V->getOperand(i);
6177 // Splat of <u, u, u, u>, return <u, u, u, u>
6178 if (!Base.getNode())
6180 for (unsigned i = 0; i != NumElems; ++i) {
6181 if (V->getOperand(i) != Base) {
6186 // Splat of <x, x, x, x>, return <x, x, x, x>
6195 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
6196 /// an AND to a vector_shuffle with the destination vector and a zero vector.
6197 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
6198 /// vector_shuffle V, Zero, <0, 4, 2, 4>
6199 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
6200 EVT VT = N->getValueType(0);
6201 DebugLoc dl = N->getDebugLoc();
6202 SDValue LHS = N->getOperand(0);
6203 SDValue RHS = N->getOperand(1);
6204 if (N->getOpcode() == ISD::AND) {
6205 if (RHS.getOpcode() == ISD::BIT_CONVERT)
6206 RHS = RHS.getOperand(0);
6207 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
6208 SmallVector<int, 8> Indices;
6209 unsigned NumElts = RHS.getNumOperands();
6210 for (unsigned i = 0; i != NumElts; ++i) {
6211 SDValue Elt = RHS.getOperand(i);
6212 if (!isa<ConstantSDNode>(Elt))
6214 else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
6215 Indices.push_back(i);
6216 else if (cast<ConstantSDNode>(Elt)->isNullValue())
6217 Indices.push_back(NumElts);
6222 // Let's see if the target supports this vector_shuffle.
6223 EVT RVT = RHS.getValueType();
6224 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
6227 // Return the new VECTOR_SHUFFLE node.
6228 EVT EltVT = RVT.getVectorElementType();
6229 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
6230 DAG.getConstant(0, EltVT));
6231 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
6232 RVT, &ZeroOps[0], ZeroOps.size());
6233 LHS = DAG.getNode(ISD::BIT_CONVERT, dl, RVT, LHS);
6234 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
6235 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Shuf);
6242 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
6243 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
6244 // After legalize, the target may be depending on adds and other
6245 // binary ops to provide legal ways to construct constants or other
6246 // things. Simplifying them may result in a loss of legality.
6247 if (LegalOperations) return SDValue();
6249 EVT VT = N->getValueType(0);
6250 assert(VT.isVector() && "SimplifyVBinOp only works on vectors!");
6252 EVT EltType = VT.getVectorElementType();
6253 SDValue LHS = N->getOperand(0);
6254 SDValue RHS = N->getOperand(1);
6255 SDValue Shuffle = XformToShuffleWithZero(N);
6256 if (Shuffle.getNode()) return Shuffle;
6258 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
6260 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
6261 RHS.getOpcode() == ISD::BUILD_VECTOR) {
6262 SmallVector<SDValue, 8> Ops;
6263 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
6264 SDValue LHSOp = LHS.getOperand(i);
6265 SDValue RHSOp = RHS.getOperand(i);
6266 // If these two elements can't be folded, bail out.
6267 if ((LHSOp.getOpcode() != ISD::UNDEF &&
6268 LHSOp.getOpcode() != ISD::Constant &&
6269 LHSOp.getOpcode() != ISD::ConstantFP) ||
6270 (RHSOp.getOpcode() != ISD::UNDEF &&
6271 RHSOp.getOpcode() != ISD::Constant &&
6272 RHSOp.getOpcode() != ISD::ConstantFP))
6275 // Can't fold divide by zero.
6276 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
6277 N->getOpcode() == ISD::FDIV) {
6278 if ((RHSOp.getOpcode() == ISD::Constant &&
6279 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
6280 (RHSOp.getOpcode() == ISD::ConstantFP &&
6281 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
6285 Ops.push_back(DAG.getNode(N->getOpcode(), LHS.getDebugLoc(),
6286 EltType, LHSOp, RHSOp));
6287 AddToWorkList(Ops.back().getNode());
6288 assert((Ops.back().getOpcode() == ISD::UNDEF ||
6289 Ops.back().getOpcode() == ISD::Constant ||
6290 Ops.back().getOpcode() == ISD::ConstantFP) &&
6291 "Scalar binop didn't fold!");
6294 if (Ops.size() == LHS.getNumOperands()) {
6295 EVT VT = LHS.getValueType();
6296 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
6297 &Ops[0], Ops.size());
6304 SDValue DAGCombiner::SimplifySelect(DebugLoc DL, SDValue N0,
6305 SDValue N1, SDValue N2){
6306 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
6308 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
6309 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6311 // If we got a simplified select_cc node back from SimplifySelectCC, then
6312 // break it down into a new SETCC node, and a new SELECT node, and then return
6313 // the SELECT node, since we were called with a SELECT node.
6314 if (SCC.getNode()) {
6315 // Check to see if we got a select_cc back (to turn into setcc/select).
6316 // Otherwise, just return whatever node we got back, like fabs.
6317 if (SCC.getOpcode() == ISD::SELECT_CC) {
6318 SDValue SETCC = DAG.getNode(ISD::SETCC, N0.getDebugLoc(),
6320 SCC.getOperand(0), SCC.getOperand(1),
6322 AddToWorkList(SETCC.getNode());
6323 return DAG.getNode(ISD::SELECT, SCC.getDebugLoc(), SCC.getValueType(),
6324 SCC.getOperand(2), SCC.getOperand(3), SETCC);
6332 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
6333 /// are the two values being selected between, see if we can simplify the
6334 /// select. Callers of this should assume that TheSelect is deleted if this
6335 /// returns true. As such, they should return the appropriate thing (e.g. the
6336 /// node) back to the top-level of the DAG combiner loop to avoid it being
6338 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
6341 // If this is a select from two identical things, try to pull the operation
6342 // through the select.
6343 if (LHS.getOpcode() == RHS.getOpcode() && LHS.hasOneUse() && RHS.hasOneUse()){
6344 // If this is a load and the token chain is identical, replace the select
6345 // of two loads with a load through a select of the address to load from.
6346 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
6347 // constants have been dropped into the constant pool.
6348 if (LHS.getOpcode() == ISD::LOAD &&
6349 // Do not let this transformation reduce the number of volatile loads.
6350 !cast<LoadSDNode>(LHS)->isVolatile() &&
6351 !cast<LoadSDNode>(RHS)->isVolatile() &&
6352 // Token chains must be identical.
6353 LHS.getOperand(0) == RHS.getOperand(0)) {
6354 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
6355 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
6357 // If this is an EXTLOAD, the VT's must match.
6358 if (LLD->getMemoryVT() == RLD->getMemoryVT()) {
6359 // FIXME: this discards src value information. This is
6360 // over-conservative. It would be beneficial to be able to remember
6361 // both potential memory locations. Since we are discarding
6362 // src value info, don't do the transformation if the memory
6363 // locations are not in the default address space.
6364 unsigned LLDAddrSpace = 0, RLDAddrSpace = 0;
6365 if (const Value *LLDVal = LLD->getMemOperand()->getValue()) {
6366 if (const PointerType *PT = dyn_cast<PointerType>(LLDVal->getType()))
6367 LLDAddrSpace = PT->getAddressSpace();
6369 if (const Value *RLDVal = RLD->getMemOperand()->getValue()) {
6370 if (const PointerType *PT = dyn_cast<PointerType>(RLDVal->getType()))
6371 RLDAddrSpace = PT->getAddressSpace();
6374 if (LLDAddrSpace == 0 && RLDAddrSpace == 0) {
6375 if (TheSelect->getOpcode() == ISD::SELECT) {
6376 // Check that the condition doesn't reach either load. If so, folding
6377 // this will induce a cycle into the DAG.
6378 if ((!LLD->hasAnyUseOfValue(1) ||
6379 !LLD->isPredecessorOf(TheSelect->getOperand(0).getNode())) &&
6380 (!RLD->hasAnyUseOfValue(1) ||
6381 !RLD->isPredecessorOf(TheSelect->getOperand(0).getNode()))) {
6382 Addr = DAG.getNode(ISD::SELECT, TheSelect->getDebugLoc(),
6383 LLD->getBasePtr().getValueType(),
6384 TheSelect->getOperand(0), LLD->getBasePtr(),
6388 // Check that the condition doesn't reach either load. If so, folding
6389 // this will induce a cycle into the DAG.
6390 if ((!LLD->hasAnyUseOfValue(1) ||
6391 (!LLD->isPredecessorOf(TheSelect->getOperand(0).getNode()) &&
6392 !LLD->isPredecessorOf(TheSelect->getOperand(1).getNode()))) &&
6393 (!RLD->hasAnyUseOfValue(1) ||
6394 (!RLD->isPredecessorOf(TheSelect->getOperand(0).getNode()) &&
6395 !RLD->isPredecessorOf(TheSelect->getOperand(1).getNode())))) {
6396 Addr = DAG.getNode(ISD::SELECT_CC, TheSelect->getDebugLoc(),
6397 LLD->getBasePtr().getValueType(),
6398 TheSelect->getOperand(0),
6399 TheSelect->getOperand(1),
6400 LLD->getBasePtr(), RLD->getBasePtr(),
6401 TheSelect->getOperand(4));
6406 if (Addr.getNode()) {
6408 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
6409 Load = DAG.getLoad(TheSelect->getValueType(0),
6410 TheSelect->getDebugLoc(),
6414 LLD->isNonTemporal(),
6415 LLD->getAlignment());
6417 Load = DAG.getExtLoad(LLD->getExtensionType(),
6418 TheSelect->getDebugLoc(),
6419 TheSelect->getValueType(0),
6420 LLD->getChain(), Addr, 0, 0,
6423 LLD->isNonTemporal(),
6424 LLD->getAlignment());
6427 // Users of the select now use the result of the load.
6428 CombineTo(TheSelect, Load);
6430 // Users of the old loads now use the new load's chain. We know the
6431 // old-load value is dead now.
6432 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
6433 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
6443 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
6444 /// where 'cond' is the comparison specified by CC.
6445 SDValue DAGCombiner::SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1,
6446 SDValue N2, SDValue N3,
6447 ISD::CondCode CC, bool NotExtCompare) {
6448 // (x ? y : y) -> y.
6449 if (N2 == N3) return N2;
6451 EVT VT = N2.getValueType();
6452 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
6453 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
6454 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
6456 // Determine if the condition we're dealing with is constant
6457 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
6458 N0, N1, CC, DL, false);
6459 if (SCC.getNode()) AddToWorkList(SCC.getNode());
6460 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
6462 // fold select_cc true, x, y -> x
6463 if (SCCC && !SCCC->isNullValue())
6465 // fold select_cc false, x, y -> y
6466 if (SCCC && SCCC->isNullValue())
6469 // Check to see if we can simplify the select into an fabs node
6470 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
6471 // Allow either -0.0 or 0.0
6472 if (CFP->getValueAPF().isZero()) {
6473 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
6474 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
6475 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
6476 N2 == N3.getOperand(0))
6477 return DAG.getNode(ISD::FABS, DL, VT, N0);
6479 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
6480 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
6481 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
6482 N2.getOperand(0) == N3)
6483 return DAG.getNode(ISD::FABS, DL, VT, N3);
6487 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
6488 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
6489 // in it. This is a win when the constant is not otherwise available because
6490 // it replaces two constant pool loads with one. We only do this if the FP
6491 // type is known to be legal, because if it isn't, then we are before legalize
6492 // types an we want the other legalization to happen first (e.g. to avoid
6493 // messing with soft float) and if the ConstantFP is not legal, because if
6494 // it is legal, we may not need to store the FP constant in a constant pool.
6495 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
6496 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
6497 if (TLI.isTypeLegal(N2.getValueType()) &&
6498 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
6499 TargetLowering::Legal) &&
6500 // If both constants have multiple uses, then we won't need to do an
6501 // extra load, they are likely around in registers for other users.
6502 (TV->hasOneUse() || FV->hasOneUse())) {
6503 Constant *Elts[] = {
6504 const_cast<ConstantFP*>(FV->getConstantFPValue()),
6505 const_cast<ConstantFP*>(TV->getConstantFPValue())
6507 const Type *FPTy = Elts[0]->getType();
6508 const TargetData &TD = *TLI.getTargetData();
6510 // Create a ConstantArray of the two constants.
6511 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts, 2);
6512 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
6513 TD.getPrefTypeAlignment(FPTy));
6514 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
6516 // Get the offsets to the 0 and 1 element of the array so that we can
6517 // select between them.
6518 SDValue Zero = DAG.getIntPtrConstant(0);
6519 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
6520 SDValue One = DAG.getIntPtrConstant(EltSize);
6522 SDValue Cond = DAG.getSetCC(DL,
6523 TLI.getSetCCResultType(N0.getValueType()),
6525 SDValue CstOffset = DAG.getNode(ISD::SELECT, DL, Zero.getValueType(),
6527 CPIdx = DAG.getNode(ISD::ADD, DL, TLI.getPointerTy(), CPIdx,
6529 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
6530 PseudoSourceValue::getConstantPool(), 0, false,
6536 // Check to see if we can perform the "gzip trick", transforming
6537 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
6538 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
6539 N0.getValueType().isInteger() &&
6540 N2.getValueType().isInteger() &&
6541 (N1C->isNullValue() || // (a < 0) ? b : 0
6542 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
6543 EVT XType = N0.getValueType();
6544 EVT AType = N2.getValueType();
6545 if (XType.bitsGE(AType)) {
6546 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
6547 // single-bit constant.
6548 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
6549 unsigned ShCtV = N2C->getAPIntValue().logBase2();
6550 ShCtV = XType.getSizeInBits()-ShCtV-1;
6551 SDValue ShCt = DAG.getConstant(ShCtV, getShiftAmountTy());
6552 SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(),
6554 AddToWorkList(Shift.getNode());
6556 if (XType.bitsGT(AType)) {
6557 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
6558 AddToWorkList(Shift.getNode());
6561 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
6564 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(),
6566 DAG.getConstant(XType.getSizeInBits()-1,
6567 getShiftAmountTy()));
6568 AddToWorkList(Shift.getNode());
6570 if (XType.bitsGT(AType)) {
6571 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
6572 AddToWorkList(Shift.getNode());
6575 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
6579 // fold select C, 16, 0 -> shl C, 4
6580 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
6581 TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent) {
6583 // If the caller doesn't want us to simplify this into a zext of a compare,
6585 if (NotExtCompare && N2C->getAPIntValue() == 1)
6588 // Get a SetCC of the condition
6589 // FIXME: Should probably make sure that setcc is legal if we ever have a
6590 // target where it isn't.
6592 // cast from setcc result type to select result type
6594 SCC = DAG.getSetCC(DL, TLI.getSetCCResultType(N0.getValueType()),
6596 if (N2.getValueType().bitsLT(SCC.getValueType()))
6597 Temp = DAG.getZeroExtendInReg(SCC, N2.getDebugLoc(), N2.getValueType());
6599 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
6600 N2.getValueType(), SCC);
6602 SCC = DAG.getSetCC(N0.getDebugLoc(), MVT::i1, N0, N1, CC);
6603 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
6604 N2.getValueType(), SCC);
6607 AddToWorkList(SCC.getNode());
6608 AddToWorkList(Temp.getNode());
6610 if (N2C->getAPIntValue() == 1)
6613 // shl setcc result by log2 n2c
6614 return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
6615 DAG.getConstant(N2C->getAPIntValue().logBase2(),
6616 getShiftAmountTy()));
6619 // Check to see if this is the equivalent of setcc
6620 // FIXME: Turn all of these into setcc if setcc if setcc is legal
6621 // otherwise, go ahead with the folds.
6622 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
6623 EVT XType = N0.getValueType();
6624 if (!LegalOperations ||
6625 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(XType))) {
6626 SDValue Res = DAG.getSetCC(DL, TLI.getSetCCResultType(XType), N0, N1, CC);
6627 if (Res.getValueType() != VT)
6628 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
6632 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
6633 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
6634 (!LegalOperations ||
6635 TLI.isOperationLegal(ISD::CTLZ, XType))) {
6636 SDValue Ctlz = DAG.getNode(ISD::CTLZ, N0.getDebugLoc(), XType, N0);
6637 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
6638 DAG.getConstant(Log2_32(XType.getSizeInBits()),
6639 getShiftAmountTy()));
6641 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
6642 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
6643 SDValue NegN0 = DAG.getNode(ISD::SUB, N0.getDebugLoc(),
6644 XType, DAG.getConstant(0, XType), N0);
6645 SDValue NotN0 = DAG.getNOT(N0.getDebugLoc(), N0, XType);
6646 return DAG.getNode(ISD::SRL, DL, XType,
6647 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
6648 DAG.getConstant(XType.getSizeInBits()-1,
6649 getShiftAmountTy()));
6651 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
6652 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
6653 SDValue Sign = DAG.getNode(ISD::SRL, N0.getDebugLoc(), XType, N0,
6654 DAG.getConstant(XType.getSizeInBits()-1,
6655 getShiftAmountTy()));
6656 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
6660 // Check to see if this is an integer abs. select_cc setl[te] X, 0, -X, X ->
6661 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
6662 if (N1C && N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE) &&
6663 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1) &&
6664 N2.getOperand(0) == N1 && N0.getValueType().isInteger()) {
6665 EVT XType = N0.getValueType();
6666 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType, N0,
6667 DAG.getConstant(XType.getSizeInBits()-1,
6668 getShiftAmountTy()));
6669 SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(), XType,
6671 AddToWorkList(Shift.getNode());
6672 AddToWorkList(Add.getNode());
6673 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
6675 // Check to see if this is an integer abs. select_cc setgt X, -1, X, -X ->
6676 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
6677 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT &&
6678 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) {
6679 if (ConstantSDNode *SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0))) {
6680 EVT XType = N0.getValueType();
6681 if (SubC->isNullValue() && XType.isInteger()) {
6682 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType,
6684 DAG.getConstant(XType.getSizeInBits()-1,
6685 getShiftAmountTy()));
6686 SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(),
6688 AddToWorkList(Shift.getNode());
6689 AddToWorkList(Add.getNode());
6690 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
6698 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
6699 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
6700 SDValue N1, ISD::CondCode Cond,
6701 DebugLoc DL, bool foldBooleans) {
6702 TargetLowering::DAGCombinerInfo
6703 DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
6704 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
6707 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
6708 /// return a DAG expression to select that will generate the same value by
6709 /// multiplying by a magic number. See:
6710 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
6711 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
6712 std::vector<SDNode*> Built;
6713 SDValue S = TLI.BuildSDIV(N, DAG, &Built);
6715 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
6721 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
6722 /// return a DAG expression to select that will generate the same value by
6723 /// multiplying by a magic number. See:
6724 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
6725 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
6726 std::vector<SDNode*> Built;
6727 SDValue S = TLI.BuildUDIV(N, DAG, &Built);
6729 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
6735 /// FindBaseOffset - Return true if base is a frame index, which is known not
6736 // to alias with anything but itself. Provides base object and offset as results.
6737 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
6738 const GlobalValue *&GV, void *&CV) {
6739 // Assume it is a primitive operation.
6740 Base = Ptr; Offset = 0; GV = 0; CV = 0;
6742 // If it's an adding a simple constant then integrate the offset.
6743 if (Base.getOpcode() == ISD::ADD) {
6744 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
6745 Base = Base.getOperand(0);
6746 Offset += C->getZExtValue();
6750 // Return the underlying GlobalValue, and update the Offset. Return false
6751 // for GlobalAddressSDNode since the same GlobalAddress may be represented
6752 // by multiple nodes with different offsets.
6753 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
6754 GV = G->getGlobal();
6755 Offset += G->getOffset();
6759 // Return the underlying Constant value, and update the Offset. Return false
6760 // for ConstantSDNodes since the same constant pool entry may be represented
6761 // by multiple nodes with different offsets.
6762 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
6763 CV = C->isMachineConstantPoolEntry() ? (void *)C->getMachineCPVal()
6764 : (void *)C->getConstVal();
6765 Offset += C->getOffset();
6768 // If it's any of the following then it can't alias with anything but itself.
6769 return isa<FrameIndexSDNode>(Base);
6772 /// isAlias - Return true if there is any possibility that the two addresses
6774 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
6775 const Value *SrcValue1, int SrcValueOffset1,
6776 unsigned SrcValueAlign1,
6777 SDValue Ptr2, int64_t Size2,
6778 const Value *SrcValue2, int SrcValueOffset2,
6779 unsigned SrcValueAlign2) const {
6780 // If they are the same then they must be aliases.
6781 if (Ptr1 == Ptr2) return true;
6783 // Gather base node and offset information.
6784 SDValue Base1, Base2;
6785 int64_t Offset1, Offset2;
6786 const GlobalValue *GV1, *GV2;
6788 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
6789 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
6791 // If they have a same base address then check to see if they overlap.
6792 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
6793 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
6795 // If we know what the bases are, and they aren't identical, then we know they
6797 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
6800 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
6801 // compared to the size and offset of the access, we may be able to prove they
6802 // do not alias. This check is conservative for now to catch cases created by
6803 // splitting vector types.
6804 if ((SrcValueAlign1 == SrcValueAlign2) &&
6805 (SrcValueOffset1 != SrcValueOffset2) &&
6806 (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
6807 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
6808 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
6810 // There is no overlap between these relatively aligned accesses of similar
6811 // size, return no alias.
6812 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
6816 if (CombinerGlobalAA) {
6817 // Use alias analysis information.
6818 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
6819 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
6820 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
6821 AliasAnalysis::AliasResult AAResult =
6822 AA.alias(SrcValue1, Overlap1, SrcValue2, Overlap2);
6823 if (AAResult == AliasAnalysis::NoAlias)
6827 // Otherwise we have to assume they alias.
6831 /// FindAliasInfo - Extracts the relevant alias information from the memory
6832 /// node. Returns true if the operand was a load.
6833 bool DAGCombiner::FindAliasInfo(SDNode *N,
6834 SDValue &Ptr, int64_t &Size,
6835 const Value *&SrcValue,
6836 int &SrcValueOffset,
6837 unsigned &SrcValueAlign) const {
6838 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
6839 Ptr = LD->getBasePtr();
6840 Size = LD->getMemoryVT().getSizeInBits() >> 3;
6841 SrcValue = LD->getSrcValue();
6842 SrcValueOffset = LD->getSrcValueOffset();
6843 SrcValueAlign = LD->getOriginalAlignment();
6845 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
6846 Ptr = ST->getBasePtr();
6847 Size = ST->getMemoryVT().getSizeInBits() >> 3;
6848 SrcValue = ST->getSrcValue();
6849 SrcValueOffset = ST->getSrcValueOffset();
6850 SrcValueAlign = ST->getOriginalAlignment();
6852 llvm_unreachable("FindAliasInfo expected a memory operand");
6858 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
6859 /// looking for aliasing nodes and adding them to the Aliases vector.
6860 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
6861 SmallVector<SDValue, 8> &Aliases) {
6862 SmallVector<SDValue, 8> Chains; // List of chains to visit.
6863 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
6865 // Get alias information for node.
6868 const Value *SrcValue;
6870 unsigned SrcValueAlign;
6871 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset,
6875 Chains.push_back(OriginalChain);
6878 // Look at each chain and determine if it is an alias. If so, add it to the
6879 // aliases list. If not, then continue up the chain looking for the next
6881 while (!Chains.empty()) {
6882 SDValue Chain = Chains.back();
6885 // For TokenFactor nodes, look at each operand and only continue up the
6886 // chain until we find two aliases. If we've seen two aliases, assume we'll
6887 // find more and revert to original chain since the xform is unlikely to be
6890 // FIXME: The depth check could be made to return the last non-aliasing
6891 // chain we found before we hit a tokenfactor rather than the original
6893 if (Depth > 6 || Aliases.size() == 2) {
6895 Aliases.push_back(OriginalChain);
6899 // Don't bother if we've been before.
6900 if (!Visited.insert(Chain.getNode()))
6903 switch (Chain.getOpcode()) {
6904 case ISD::EntryToken:
6905 // Entry token is ideal chain operand, but handled in FindBetterChain.
6910 // Get alias information for Chain.
6913 const Value *OpSrcValue;
6914 int OpSrcValueOffset;
6915 unsigned OpSrcValueAlign;
6916 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
6917 OpSrcValue, OpSrcValueOffset,
6920 // If chain is alias then stop here.
6921 if (!(IsLoad && IsOpLoad) &&
6922 isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign,
6923 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset,
6925 Aliases.push_back(Chain);
6927 // Look further up the chain.
6928 Chains.push_back(Chain.getOperand(0));
6934 case ISD::TokenFactor:
6935 // We have to check each of the operands of the token factor for "small"
6936 // token factors, so we queue them up. Adding the operands to the queue
6937 // (stack) in reverse order maintains the original order and increases the
6938 // likelihood that getNode will find a matching token factor (CSE.)
6939 if (Chain.getNumOperands() > 16) {
6940 Aliases.push_back(Chain);
6943 for (unsigned n = Chain.getNumOperands(); n;)
6944 Chains.push_back(Chain.getOperand(--n));
6949 // For all other instructions we will just have to take what we can get.
6950 Aliases.push_back(Chain);
6956 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
6957 /// for a better chain (aliasing node.)
6958 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
6959 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
6961 // Accumulate all the aliases to this node.
6962 GatherAllAliases(N, OldChain, Aliases);
6964 if (Aliases.size() == 0) {
6965 // If no operands then chain to entry token.
6966 return DAG.getEntryNode();
6967 } else if (Aliases.size() == 1) {
6968 // If a single operand then chain to it. We don't need to revisit it.
6972 // Construct a custom tailored token factor.
6973 return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
6974 &Aliases[0], Aliases.size());
6977 // SelectionDAG::Combine - This is the entry point for the file.
6979 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
6980 CodeGenOpt::Level OptLevel) {
6981 /// run - This is the main entry point to this class.
6983 DAGCombiner(*this, AA, OptLevel).Run(Level);