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/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetLowering.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetSubtargetInfo.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");
46 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
50 CombinerAA("combiner-alias-analysis", cl::Hidden,
51 cl::desc("Turn on alias analysis during testing"));
54 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
55 cl::desc("Include global information in alias analysis"));
57 //------------------------------ DAGCombiner ---------------------------------//
61 const TargetLowering &TLI;
63 CodeGenOpt::Level OptLevel;
67 // Worklist of all of the nodes that need to be simplified.
69 // This has the semantics that when adding to the worklist,
70 // the item added must be next to be processed. It should
71 // also only appear once. The naive approach to this takes
74 // To reduce the insert/remove time to logarithmic, we use
75 // a set and a vector to maintain our worklist.
77 // The set contains the items on the worklist, but does not
78 // maintain the order they should be visited.
80 // The vector maintains the order nodes should be visited, but may
81 // contain duplicate or removed nodes. When choosing a node to
82 // visit, we pop off the order stack until we find an item that is
83 // also in the contents set. All operations are O(log N).
84 SmallPtrSet<SDNode*, 64> WorkListContents;
85 SmallVector<SDNode*, 64> WorkListOrder;
87 // AA - Used for DAG load/store alias analysis.
90 /// AddUsersToWorkList - When an instruction is simplified, add all users of
91 /// the instruction to the work lists because they might get more simplified
94 void AddUsersToWorkList(SDNode *N) {
95 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
100 /// visit - call the node-specific routine that knows how to fold each
101 /// particular type of node.
102 SDValue visit(SDNode *N);
105 /// AddToWorkList - Add to the work list making sure its instance is at the
106 /// back (next to be processed.)
107 void AddToWorkList(SDNode *N) {
108 WorkListContents.insert(N);
109 WorkListOrder.push_back(N);
112 /// removeFromWorkList - remove all instances of N from the worklist.
114 void removeFromWorkList(SDNode *N) {
115 WorkListContents.erase(N);
118 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
121 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
122 return CombineTo(N, &Res, 1, AddTo);
125 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
127 SDValue To[] = { Res0, Res1 };
128 return CombineTo(N, To, 2, AddTo);
131 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
135 /// SimplifyDemandedBits - Check the specified integer node value to see if
136 /// it can be simplified or if things it uses can be simplified by bit
137 /// propagation. If so, return true.
138 bool SimplifyDemandedBits(SDValue Op) {
139 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
140 APInt Demanded = APInt::getAllOnesValue(BitWidth);
141 return SimplifyDemandedBits(Op, Demanded);
144 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
146 bool CombineToPreIndexedLoadStore(SDNode *N);
147 bool CombineToPostIndexedLoadStore(SDNode *N);
149 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
150 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
151 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
152 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
153 SDValue PromoteIntBinOp(SDValue Op);
154 SDValue PromoteIntShiftOp(SDValue Op);
155 SDValue PromoteExtend(SDValue Op);
156 bool PromoteLoad(SDValue Op);
158 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
159 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
160 ISD::NodeType ExtType);
162 /// combine - call the node-specific routine that knows how to fold each
163 /// particular type of node. If that doesn't do anything, try the
164 /// target-specific DAG combines.
165 SDValue combine(SDNode *N);
167 // Visitation implementation - Implement dag node combining for different
168 // node types. The semantics are as follows:
170 // SDValue.getNode() == 0 - No change was made
171 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
172 // otherwise - N should be replaced by the returned Operand.
174 SDValue visitTokenFactor(SDNode *N);
175 SDValue visitMERGE_VALUES(SDNode *N);
176 SDValue visitADD(SDNode *N);
177 SDValue visitSUB(SDNode *N);
178 SDValue visitADDC(SDNode *N);
179 SDValue visitSUBC(SDNode *N);
180 SDValue visitADDE(SDNode *N);
181 SDValue visitSUBE(SDNode *N);
182 SDValue visitMUL(SDNode *N);
183 SDValue visitSDIV(SDNode *N);
184 SDValue visitUDIV(SDNode *N);
185 SDValue visitSREM(SDNode *N);
186 SDValue visitUREM(SDNode *N);
187 SDValue visitMULHU(SDNode *N);
188 SDValue visitMULHS(SDNode *N);
189 SDValue visitSMUL_LOHI(SDNode *N);
190 SDValue visitUMUL_LOHI(SDNode *N);
191 SDValue visitSMULO(SDNode *N);
192 SDValue visitUMULO(SDNode *N);
193 SDValue visitSDIVREM(SDNode *N);
194 SDValue visitUDIVREM(SDNode *N);
195 SDValue visitAND(SDNode *N);
196 SDValue visitOR(SDNode *N);
197 SDValue visitXOR(SDNode *N);
198 SDValue SimplifyVBinOp(SDNode *N);
199 SDValue SimplifyVUnaryOp(SDNode *N);
200 SDValue visitSHL(SDNode *N);
201 SDValue visitSRA(SDNode *N);
202 SDValue visitSRL(SDNode *N);
203 SDValue visitCTLZ(SDNode *N);
204 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
205 SDValue visitCTTZ(SDNode *N);
206 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
207 SDValue visitCTPOP(SDNode *N);
208 SDValue visitSELECT(SDNode *N);
209 SDValue visitVSELECT(SDNode *N);
210 SDValue visitSELECT_CC(SDNode *N);
211 SDValue visitSETCC(SDNode *N);
212 SDValue visitSIGN_EXTEND(SDNode *N);
213 SDValue visitZERO_EXTEND(SDNode *N);
214 SDValue visitANY_EXTEND(SDNode *N);
215 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
216 SDValue visitTRUNCATE(SDNode *N);
217 SDValue visitBITCAST(SDNode *N);
218 SDValue visitBUILD_PAIR(SDNode *N);
219 SDValue visitFADD(SDNode *N);
220 SDValue visitFSUB(SDNode *N);
221 SDValue visitFMUL(SDNode *N);
222 SDValue visitFMA(SDNode *N);
223 SDValue visitFDIV(SDNode *N);
224 SDValue visitFREM(SDNode *N);
225 SDValue visitFCOPYSIGN(SDNode *N);
226 SDValue visitSINT_TO_FP(SDNode *N);
227 SDValue visitUINT_TO_FP(SDNode *N);
228 SDValue visitFP_TO_SINT(SDNode *N);
229 SDValue visitFP_TO_UINT(SDNode *N);
230 SDValue visitFP_ROUND(SDNode *N);
231 SDValue visitFP_ROUND_INREG(SDNode *N);
232 SDValue visitFP_EXTEND(SDNode *N);
233 SDValue visitFNEG(SDNode *N);
234 SDValue visitFABS(SDNode *N);
235 SDValue visitFCEIL(SDNode *N);
236 SDValue visitFTRUNC(SDNode *N);
237 SDValue visitFFLOOR(SDNode *N);
238 SDValue visitBRCOND(SDNode *N);
239 SDValue visitBR_CC(SDNode *N);
240 SDValue visitLOAD(SDNode *N);
241 SDValue visitSTORE(SDNode *N);
242 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
243 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
244 SDValue visitBUILD_VECTOR(SDNode *N);
245 SDValue visitCONCAT_VECTORS(SDNode *N);
246 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
247 SDValue visitVECTOR_SHUFFLE(SDNode *N);
249 SDValue XformToShuffleWithZero(SDNode *N);
250 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
252 SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
254 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
255 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
256 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
257 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
258 SDValue N3, ISD::CondCode CC,
259 bool NotExtCompare = false);
260 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
261 SDLoc DL, bool foldBooleans = true);
262 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
264 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
265 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
266 SDValue BuildSDIV(SDNode *N);
267 SDValue BuildUDIV(SDNode *N);
268 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
269 bool DemandHighBits = true);
270 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
271 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
272 SDValue ReduceLoadWidth(SDNode *N);
273 SDValue ReduceLoadOpStoreWidth(SDNode *N);
274 SDValue TransformFPLoadStorePair(SDNode *N);
275 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
276 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
278 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
280 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
281 /// looking for aliasing nodes and adding them to the Aliases vector.
282 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
283 SmallVectorImpl<SDValue> &Aliases);
285 /// isAlias - Return true if there is any possibility that the two addresses
287 bool isAlias(SDValue Ptr1, int64_t Size1,
288 const Value *SrcValue1, int SrcValueOffset1,
289 unsigned SrcValueAlign1,
290 const MDNode *TBAAInfo1,
291 SDValue Ptr2, int64_t Size2,
292 const Value *SrcValue2, int SrcValueOffset2,
293 unsigned SrcValueAlign2,
294 const MDNode *TBAAInfo2) const;
296 /// isAlias - Return true if there is any possibility that the two addresses
298 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1);
300 /// FindAliasInfo - Extracts the relevant alias information from the memory
301 /// node. Returns true if the operand was a load.
302 bool FindAliasInfo(SDNode *N,
303 SDValue &Ptr, int64_t &Size,
304 const Value *&SrcValue, int &SrcValueOffset,
305 unsigned &SrcValueAlignment,
306 const MDNode *&TBAAInfo) const;
308 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
309 /// looking for a better chain (aliasing node.)
310 SDValue FindBetterChain(SDNode *N, SDValue Chain);
312 /// Merge consecutive store operations into a wide store.
313 /// This optimization uses wide integers or vectors when possible.
314 /// \return True if some memory operations were changed.
315 bool MergeConsecutiveStores(StoreSDNode *N);
318 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
319 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
320 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {}
322 /// Run - runs the dag combiner on all nodes in the work list
323 void Run(CombineLevel AtLevel);
325 SelectionDAG &getDAG() const { return DAG; }
327 /// getShiftAmountTy - Returns a type large enough to hold any valid
328 /// shift amount - before type legalization these can be huge.
329 EVT getShiftAmountTy(EVT LHSTy) {
330 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
331 if (LHSTy.isVector())
333 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy) : TLI.getPointerTy();
336 /// isTypeLegal - This method returns true if we are running before type
337 /// legalization or if the specified VT is legal.
338 bool isTypeLegal(const EVT &VT) {
339 if (!LegalTypes) return true;
340 return TLI.isTypeLegal(VT);
343 /// getSetCCResultType - Convenience wrapper around
344 /// TargetLowering::getSetCCResultType
345 EVT getSetCCResultType(EVT VT) const {
346 return TLI.getSetCCResultType(*DAG.getContext(), VT);
353 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
354 /// nodes from the worklist.
355 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
358 explicit WorkListRemover(DAGCombiner &dc)
359 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
361 virtual void NodeDeleted(SDNode *N, SDNode *E) {
362 DC.removeFromWorkList(N);
367 //===----------------------------------------------------------------------===//
368 // TargetLowering::DAGCombinerInfo implementation
369 //===----------------------------------------------------------------------===//
371 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
372 ((DAGCombiner*)DC)->AddToWorkList(N);
375 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
376 ((DAGCombiner*)DC)->removeFromWorkList(N);
379 SDValue TargetLowering::DAGCombinerInfo::
380 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
381 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
384 SDValue TargetLowering::DAGCombinerInfo::
385 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
386 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
390 SDValue TargetLowering::DAGCombinerInfo::
391 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
392 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
395 void TargetLowering::DAGCombinerInfo::
396 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
397 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
400 //===----------------------------------------------------------------------===//
402 //===----------------------------------------------------------------------===//
404 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
405 /// specified expression for the same cost as the expression itself, or 2 if we
406 /// can compute the negated form more cheaply than the expression itself.
407 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
408 const TargetLowering &TLI,
409 const TargetOptions *Options,
410 unsigned Depth = 0) {
411 // fneg is removable even if it has multiple uses.
412 if (Op.getOpcode() == ISD::FNEG) return 2;
414 // Don't allow anything with multiple uses.
415 if (!Op.hasOneUse()) return 0;
417 // Don't recurse exponentially.
418 if (Depth > 6) return 0;
420 switch (Op.getOpcode()) {
421 default: return false;
422 case ISD::ConstantFP:
423 // Don't invert constant FP values after legalize. The negated constant
424 // isn't necessarily legal.
425 return LegalOperations ? 0 : 1;
427 // FIXME: determine better conditions for this xform.
428 if (!Options->UnsafeFPMath) return 0;
430 // After operation legalization, it might not be legal to create new FSUBs.
431 if (LegalOperations &&
432 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
435 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
436 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
439 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
440 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
443 // We can't turn -(A-B) into B-A when we honor signed zeros.
444 if (!Options->UnsafeFPMath) return 0;
446 // fold (fneg (fsub A, B)) -> (fsub B, A)
451 if (Options->HonorSignDependentRoundingFPMath()) return 0;
453 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
454 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
458 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
464 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
469 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
470 /// returns the newly negated expression.
471 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
472 bool LegalOperations, unsigned Depth = 0) {
473 // fneg is removable even if it has multiple uses.
474 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
476 // Don't allow anything with multiple uses.
477 assert(Op.hasOneUse() && "Unknown reuse!");
479 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
480 switch (Op.getOpcode()) {
481 default: llvm_unreachable("Unknown code");
482 case ISD::ConstantFP: {
483 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
485 return DAG.getConstantFP(V, Op.getValueType());
488 // FIXME: determine better conditions for this xform.
489 assert(DAG.getTarget().Options.UnsafeFPMath);
491 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
492 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
493 DAG.getTargetLoweringInfo(),
494 &DAG.getTarget().Options, Depth+1))
495 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
496 GetNegatedExpression(Op.getOperand(0), DAG,
497 LegalOperations, Depth+1),
499 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
500 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
501 GetNegatedExpression(Op.getOperand(1), DAG,
502 LegalOperations, Depth+1),
505 // We can't turn -(A-B) into B-A when we honor signed zeros.
506 assert(DAG.getTarget().Options.UnsafeFPMath);
508 // fold (fneg (fsub 0, B)) -> B
509 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
510 if (N0CFP->getValueAPF().isZero())
511 return Op.getOperand(1);
513 // fold (fneg (fsub A, B)) -> (fsub B, A)
514 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
515 Op.getOperand(1), Op.getOperand(0));
519 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
521 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
522 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
523 DAG.getTargetLoweringInfo(),
524 &DAG.getTarget().Options, Depth+1))
525 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
526 GetNegatedExpression(Op.getOperand(0), DAG,
527 LegalOperations, Depth+1),
530 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
531 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
533 GetNegatedExpression(Op.getOperand(1), DAG,
534 LegalOperations, Depth+1));
538 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
539 GetNegatedExpression(Op.getOperand(0), DAG,
540 LegalOperations, Depth+1));
542 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
543 GetNegatedExpression(Op.getOperand(0), DAG,
544 LegalOperations, Depth+1),
550 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
551 // that selects between the values 1 and 0, making it equivalent to a setcc.
552 // Also, set the incoming LHS, RHS, and CC references to the appropriate
553 // nodes based on the type of node we are checking. This simplifies life a
554 // bit for the callers.
555 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
557 if (N.getOpcode() == ISD::SETCC) {
558 LHS = N.getOperand(0);
559 RHS = N.getOperand(1);
560 CC = N.getOperand(2);
563 if (N.getOpcode() == ISD::SELECT_CC &&
564 N.getOperand(2).getOpcode() == ISD::Constant &&
565 N.getOperand(3).getOpcode() == ISD::Constant &&
566 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
567 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
568 LHS = N.getOperand(0);
569 RHS = N.getOperand(1);
570 CC = N.getOperand(4);
576 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
577 // one use. If this is true, it allows the users to invert the operation for
578 // free when it is profitable to do so.
579 static bool isOneUseSetCC(SDValue N) {
581 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
586 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
587 SDValue N0, SDValue N1) {
588 EVT VT = N0.getValueType();
589 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
590 if (isa<ConstantSDNode>(N1)) {
591 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
593 DAG.FoldConstantArithmetic(Opc, VT,
594 cast<ConstantSDNode>(N0.getOperand(1)),
595 cast<ConstantSDNode>(N1));
596 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
598 if (N0.hasOneUse()) {
599 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
600 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT,
601 N0.getOperand(0), N1);
602 AddToWorkList(OpNode.getNode());
603 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
607 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
608 if (isa<ConstantSDNode>(N0)) {
609 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
611 DAG.FoldConstantArithmetic(Opc, VT,
612 cast<ConstantSDNode>(N1.getOperand(1)),
613 cast<ConstantSDNode>(N0));
614 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
616 if (N1.hasOneUse()) {
617 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
618 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT,
619 N1.getOperand(0), N0);
620 AddToWorkList(OpNode.getNode());
621 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
628 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
630 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
632 DEBUG(dbgs() << "\nReplacing.1 ";
634 dbgs() << "\nWith: ";
635 To[0].getNode()->dump(&DAG);
636 dbgs() << " and " << NumTo-1 << " other values\n";
637 for (unsigned i = 0, e = NumTo; i != e; ++i)
638 assert((!To[i].getNode() ||
639 N->getValueType(i) == To[i].getValueType()) &&
640 "Cannot combine value to value of different type!"));
641 WorkListRemover DeadNodes(*this);
642 DAG.ReplaceAllUsesWith(N, To);
644 // Push the new nodes and any users onto the worklist
645 for (unsigned i = 0, e = NumTo; i != e; ++i) {
646 if (To[i].getNode()) {
647 AddToWorkList(To[i].getNode());
648 AddUsersToWorkList(To[i].getNode());
653 // Finally, if the node is now dead, remove it from the graph. The node
654 // may not be dead if the replacement process recursively simplified to
655 // something else needing this node.
656 if (N->use_empty()) {
657 // Nodes can be reintroduced into the worklist. Make sure we do not
658 // process a node that has been replaced.
659 removeFromWorkList(N);
661 // Finally, since the node is now dead, remove it from the graph.
664 return SDValue(N, 0);
668 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
669 // Replace all uses. If any nodes become isomorphic to other nodes and
670 // are deleted, make sure to remove them from our worklist.
671 WorkListRemover DeadNodes(*this);
672 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
674 // Push the new node and any (possibly new) users onto the worklist.
675 AddToWorkList(TLO.New.getNode());
676 AddUsersToWorkList(TLO.New.getNode());
678 // Finally, if the node is now dead, remove it from the graph. The node
679 // may not be dead if the replacement process recursively simplified to
680 // something else needing this node.
681 if (TLO.Old.getNode()->use_empty()) {
682 removeFromWorkList(TLO.Old.getNode());
684 // If the operands of this node are only used by the node, they will now
685 // be dead. Make sure to visit them first to delete dead nodes early.
686 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
687 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
688 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
690 DAG.DeleteNode(TLO.Old.getNode());
694 /// SimplifyDemandedBits - Check the specified integer node value to see if
695 /// it can be simplified or if things it uses can be simplified by bit
696 /// propagation. If so, return true.
697 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
698 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
699 APInt KnownZero, KnownOne;
700 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
704 AddToWorkList(Op.getNode());
706 // Replace the old value with the new one.
708 DEBUG(dbgs() << "\nReplacing.2 ";
709 TLO.Old.getNode()->dump(&DAG);
710 dbgs() << "\nWith: ";
711 TLO.New.getNode()->dump(&DAG);
714 CommitTargetLoweringOpt(TLO);
718 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
720 EVT VT = Load->getValueType(0);
721 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
723 DEBUG(dbgs() << "\nReplacing.9 ";
725 dbgs() << "\nWith: ";
726 Trunc.getNode()->dump(&DAG);
728 WorkListRemover DeadNodes(*this);
729 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
730 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
731 removeFromWorkList(Load);
732 DAG.DeleteNode(Load);
733 AddToWorkList(Trunc.getNode());
736 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
739 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
740 EVT MemVT = LD->getMemoryVT();
741 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
742 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
744 : LD->getExtensionType();
746 return DAG.getExtLoad(ExtType, dl, PVT,
747 LD->getChain(), LD->getBasePtr(),
748 LD->getPointerInfo(),
749 MemVT, LD->isVolatile(),
750 LD->isNonTemporal(), LD->getAlignment());
753 unsigned Opc = Op.getOpcode();
756 case ISD::AssertSext:
757 return DAG.getNode(ISD::AssertSext, dl, PVT,
758 SExtPromoteOperand(Op.getOperand(0), PVT),
760 case ISD::AssertZext:
761 return DAG.getNode(ISD::AssertZext, dl, PVT,
762 ZExtPromoteOperand(Op.getOperand(0), PVT),
764 case ISD::Constant: {
766 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
767 return DAG.getNode(ExtOpc, dl, PVT, Op);
771 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
773 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
776 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
777 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
779 EVT OldVT = Op.getValueType();
781 bool Replace = false;
782 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
783 if (NewOp.getNode() == 0)
785 AddToWorkList(NewOp.getNode());
788 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
789 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
790 DAG.getValueType(OldVT));
793 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
794 EVT OldVT = Op.getValueType();
796 bool Replace = false;
797 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
798 if (NewOp.getNode() == 0)
800 AddToWorkList(NewOp.getNode());
803 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
804 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
807 /// PromoteIntBinOp - Promote the specified integer binary operation if the
808 /// target indicates it is beneficial. e.g. On x86, it's usually better to
809 /// promote i16 operations to i32 since i16 instructions are longer.
810 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
811 if (!LegalOperations)
814 EVT VT = Op.getValueType();
815 if (VT.isVector() || !VT.isInteger())
818 // If operation type is 'undesirable', e.g. i16 on x86, consider
820 unsigned Opc = Op.getOpcode();
821 if (TLI.isTypeDesirableForOp(Opc, VT))
825 // Consult target whether it is a good idea to promote this operation and
826 // what's the right type to promote it to.
827 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
828 assert(PVT != VT && "Don't know what type to promote to!");
830 bool Replace0 = false;
831 SDValue N0 = Op.getOperand(0);
832 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
833 if (NN0.getNode() == 0)
836 bool Replace1 = false;
837 SDValue N1 = Op.getOperand(1);
842 NN1 = PromoteOperand(N1, PVT, Replace1);
843 if (NN1.getNode() == 0)
847 AddToWorkList(NN0.getNode());
849 AddToWorkList(NN1.getNode());
852 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
854 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
856 DEBUG(dbgs() << "\nPromoting ";
857 Op.getNode()->dump(&DAG));
859 return DAG.getNode(ISD::TRUNCATE, dl, VT,
860 DAG.getNode(Opc, dl, PVT, NN0, NN1));
865 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
866 /// target indicates it is beneficial. e.g. On x86, it's usually better to
867 /// promote i16 operations to i32 since i16 instructions are longer.
868 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
869 if (!LegalOperations)
872 EVT VT = Op.getValueType();
873 if (VT.isVector() || !VT.isInteger())
876 // If operation type is 'undesirable', e.g. i16 on x86, consider
878 unsigned Opc = Op.getOpcode();
879 if (TLI.isTypeDesirableForOp(Opc, VT))
883 // Consult target whether it is a good idea to promote this operation and
884 // what's the right type to promote it to.
885 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
886 assert(PVT != VT && "Don't know what type to promote to!");
888 bool Replace = false;
889 SDValue N0 = Op.getOperand(0);
891 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
892 else if (Opc == ISD::SRL)
893 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
895 N0 = PromoteOperand(N0, PVT, Replace);
896 if (N0.getNode() == 0)
899 AddToWorkList(N0.getNode());
901 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
903 DEBUG(dbgs() << "\nPromoting ";
904 Op.getNode()->dump(&DAG));
906 return DAG.getNode(ISD::TRUNCATE, dl, VT,
907 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
912 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
913 if (!LegalOperations)
916 EVT VT = Op.getValueType();
917 if (VT.isVector() || !VT.isInteger())
920 // If operation type is 'undesirable', e.g. i16 on x86, consider
922 unsigned Opc = Op.getOpcode();
923 if (TLI.isTypeDesirableForOp(Opc, VT))
927 // Consult target whether it is a good idea to promote this operation and
928 // what's the right type to promote it to.
929 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
930 assert(PVT != VT && "Don't know what type to promote to!");
931 // fold (aext (aext x)) -> (aext x)
932 // fold (aext (zext x)) -> (zext x)
933 // fold (aext (sext x)) -> (sext x)
934 DEBUG(dbgs() << "\nPromoting ";
935 Op.getNode()->dump(&DAG));
936 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
941 bool DAGCombiner::PromoteLoad(SDValue Op) {
942 if (!LegalOperations)
945 EVT VT = Op.getValueType();
946 if (VT.isVector() || !VT.isInteger())
949 // If operation type is 'undesirable', e.g. i16 on x86, consider
951 unsigned Opc = Op.getOpcode();
952 if (TLI.isTypeDesirableForOp(Opc, VT))
956 // Consult target whether it is a good idea to promote this operation and
957 // what's the right type to promote it to.
958 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
959 assert(PVT != VT && "Don't know what type to promote to!");
962 SDNode *N = Op.getNode();
963 LoadSDNode *LD = cast<LoadSDNode>(N);
964 EVT MemVT = LD->getMemoryVT();
965 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
966 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
968 : LD->getExtensionType();
969 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
970 LD->getChain(), LD->getBasePtr(),
971 LD->getPointerInfo(),
972 MemVT, LD->isVolatile(),
973 LD->isNonTemporal(), LD->getAlignment());
974 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
976 DEBUG(dbgs() << "\nPromoting ";
979 Result.getNode()->dump(&DAG);
981 WorkListRemover DeadNodes(*this);
982 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
983 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
984 removeFromWorkList(N);
986 AddToWorkList(Result.getNode());
993 //===----------------------------------------------------------------------===//
994 // Main DAG Combiner implementation
995 //===----------------------------------------------------------------------===//
997 void DAGCombiner::Run(CombineLevel AtLevel) {
998 // set the instance variables, so that the various visit routines may use it.
1000 LegalOperations = Level >= AfterLegalizeVectorOps;
1001 LegalTypes = Level >= AfterLegalizeTypes;
1003 // Add all the dag nodes to the worklist.
1004 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1005 E = DAG.allnodes_end(); I != E; ++I)
1008 // Create a dummy node (which is not added to allnodes), that adds a reference
1009 // to the root node, preventing it from being deleted, and tracking any
1010 // changes of the root.
1011 HandleSDNode Dummy(DAG.getRoot());
1013 // The root of the dag may dangle to deleted nodes until the dag combiner is
1014 // done. Set it to null to avoid confusion.
1015 DAG.setRoot(SDValue());
1017 // while the worklist isn't empty, find a node and
1018 // try and combine it.
1019 while (!WorkListContents.empty()) {
1021 // The WorkListOrder holds the SDNodes in order, but it may contain duplicates.
1022 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1023 // worklist *should* contain, and check the node we want to visit is should
1024 // actually be visited.
1026 N = WorkListOrder.pop_back_val();
1027 } while (!WorkListContents.erase(N));
1029 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1030 // N is deleted from the DAG, since they too may now be dead or may have a
1031 // reduced number of uses, allowing other xforms.
1032 if (N->use_empty() && N != &Dummy) {
1033 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1034 AddToWorkList(N->getOperand(i).getNode());
1040 SDValue RV = combine(N);
1042 if (RV.getNode() == 0)
1047 // If we get back the same node we passed in, rather than a new node or
1048 // zero, we know that the node must have defined multiple values and
1049 // CombineTo was used. Since CombineTo takes care of the worklist
1050 // mechanics for us, we have no work to do in this case.
1051 if (RV.getNode() == N)
1054 assert(N->getOpcode() != ISD::DELETED_NODE &&
1055 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1056 "Node was deleted but visit returned new node!");
1058 DEBUG(dbgs() << "\nReplacing.3 ";
1060 dbgs() << "\nWith: ";
1061 RV.getNode()->dump(&DAG);
1064 // Transfer debug value.
1065 DAG.TransferDbgValues(SDValue(N, 0), RV);
1066 WorkListRemover DeadNodes(*this);
1067 if (N->getNumValues() == RV.getNode()->getNumValues())
1068 DAG.ReplaceAllUsesWith(N, RV.getNode());
1070 assert(N->getValueType(0) == RV.getValueType() &&
1071 N->getNumValues() == 1 && "Type mismatch");
1073 DAG.ReplaceAllUsesWith(N, &OpV);
1076 // Push the new node and any users onto the worklist
1077 AddToWorkList(RV.getNode());
1078 AddUsersToWorkList(RV.getNode());
1080 // Add any uses of the old node to the worklist in case this node is the
1081 // last one that uses them. They may become dead after this node is
1083 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1084 AddToWorkList(N->getOperand(i).getNode());
1086 // Finally, if the node is now dead, remove it from the graph. The node
1087 // may not be dead if the replacement process recursively simplified to
1088 // something else needing this node.
1089 if (N->use_empty()) {
1090 // Nodes can be reintroduced into the worklist. Make sure we do not
1091 // process a node that has been replaced.
1092 removeFromWorkList(N);
1094 // Finally, since the node is now dead, remove it from the graph.
1099 // If the root changed (e.g. it was a dead load, update the root).
1100 DAG.setRoot(Dummy.getValue());
1101 DAG.RemoveDeadNodes();
1104 SDValue DAGCombiner::visit(SDNode *N) {
1105 switch (N->getOpcode()) {
1107 case ISD::TokenFactor: return visitTokenFactor(N);
1108 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1109 case ISD::ADD: return visitADD(N);
1110 case ISD::SUB: return visitSUB(N);
1111 case ISD::ADDC: return visitADDC(N);
1112 case ISD::SUBC: return visitSUBC(N);
1113 case ISD::ADDE: return visitADDE(N);
1114 case ISD::SUBE: return visitSUBE(N);
1115 case ISD::MUL: return visitMUL(N);
1116 case ISD::SDIV: return visitSDIV(N);
1117 case ISD::UDIV: return visitUDIV(N);
1118 case ISD::SREM: return visitSREM(N);
1119 case ISD::UREM: return visitUREM(N);
1120 case ISD::MULHU: return visitMULHU(N);
1121 case ISD::MULHS: return visitMULHS(N);
1122 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1123 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1124 case ISD::SMULO: return visitSMULO(N);
1125 case ISD::UMULO: return visitUMULO(N);
1126 case ISD::SDIVREM: return visitSDIVREM(N);
1127 case ISD::UDIVREM: return visitUDIVREM(N);
1128 case ISD::AND: return visitAND(N);
1129 case ISD::OR: return visitOR(N);
1130 case ISD::XOR: return visitXOR(N);
1131 case ISD::SHL: return visitSHL(N);
1132 case ISD::SRA: return visitSRA(N);
1133 case ISD::SRL: return visitSRL(N);
1134 case ISD::CTLZ: return visitCTLZ(N);
1135 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1136 case ISD::CTTZ: return visitCTTZ(N);
1137 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1138 case ISD::CTPOP: return visitCTPOP(N);
1139 case ISD::SELECT: return visitSELECT(N);
1140 case ISD::VSELECT: return visitVSELECT(N);
1141 case ISD::SELECT_CC: return visitSELECT_CC(N);
1142 case ISD::SETCC: return visitSETCC(N);
1143 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1144 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1145 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1146 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1147 case ISD::TRUNCATE: return visitTRUNCATE(N);
1148 case ISD::BITCAST: return visitBITCAST(N);
1149 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1150 case ISD::FADD: return visitFADD(N);
1151 case ISD::FSUB: return visitFSUB(N);
1152 case ISD::FMUL: return visitFMUL(N);
1153 case ISD::FMA: return visitFMA(N);
1154 case ISD::FDIV: return visitFDIV(N);
1155 case ISD::FREM: return visitFREM(N);
1156 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1157 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1158 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1159 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1160 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1161 case ISD::FP_ROUND: return visitFP_ROUND(N);
1162 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1163 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1164 case ISD::FNEG: return visitFNEG(N);
1165 case ISD::FABS: return visitFABS(N);
1166 case ISD::FFLOOR: return visitFFLOOR(N);
1167 case ISD::FCEIL: return visitFCEIL(N);
1168 case ISD::FTRUNC: return visitFTRUNC(N);
1169 case ISD::BRCOND: return visitBRCOND(N);
1170 case ISD::BR_CC: return visitBR_CC(N);
1171 case ISD::LOAD: return visitLOAD(N);
1172 case ISD::STORE: return visitSTORE(N);
1173 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1174 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1175 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1176 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1177 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1178 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1183 SDValue DAGCombiner::combine(SDNode *N) {
1184 SDValue RV = visit(N);
1186 // If nothing happened, try a target-specific DAG combine.
1187 if (RV.getNode() == 0) {
1188 assert(N->getOpcode() != ISD::DELETED_NODE &&
1189 "Node was deleted but visit returned NULL!");
1191 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1192 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1194 // Expose the DAG combiner to the target combiner impls.
1195 TargetLowering::DAGCombinerInfo
1196 DagCombineInfo(DAG, Level, false, this);
1198 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1202 // If nothing happened still, try promoting the operation.
1203 if (RV.getNode() == 0) {
1204 switch (N->getOpcode()) {
1212 RV = PromoteIntBinOp(SDValue(N, 0));
1217 RV = PromoteIntShiftOp(SDValue(N, 0));
1219 case ISD::SIGN_EXTEND:
1220 case ISD::ZERO_EXTEND:
1221 case ISD::ANY_EXTEND:
1222 RV = PromoteExtend(SDValue(N, 0));
1225 if (PromoteLoad(SDValue(N, 0)))
1231 // If N is a commutative binary node, try commuting it to enable more
1233 if (RV.getNode() == 0 &&
1234 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1235 N->getNumValues() == 1) {
1236 SDValue N0 = N->getOperand(0);
1237 SDValue N1 = N->getOperand(1);
1239 // Constant operands are canonicalized to RHS.
1240 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1241 SDValue Ops[] = { N1, N0 };
1242 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1245 return SDValue(CSENode, 0);
1252 /// getInputChainForNode - Given a node, return its input chain if it has one,
1253 /// otherwise return a null sd operand.
1254 static SDValue getInputChainForNode(SDNode *N) {
1255 if (unsigned NumOps = N->getNumOperands()) {
1256 if (N->getOperand(0).getValueType() == MVT::Other)
1257 return N->getOperand(0);
1258 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1259 return N->getOperand(NumOps-1);
1260 for (unsigned i = 1; i < NumOps-1; ++i)
1261 if (N->getOperand(i).getValueType() == MVT::Other)
1262 return N->getOperand(i);
1267 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1268 // If N has two operands, where one has an input chain equal to the other,
1269 // the 'other' chain is redundant.
1270 if (N->getNumOperands() == 2) {
1271 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1272 return N->getOperand(0);
1273 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1274 return N->getOperand(1);
1277 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1278 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1279 SmallPtrSet<SDNode*, 16> SeenOps;
1280 bool Changed = false; // If we should replace this token factor.
1282 // Start out with this token factor.
1285 // Iterate through token factors. The TFs grows when new token factors are
1287 for (unsigned i = 0; i < TFs.size(); ++i) {
1288 SDNode *TF = TFs[i];
1290 // Check each of the operands.
1291 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1292 SDValue Op = TF->getOperand(i);
1294 switch (Op.getOpcode()) {
1295 case ISD::EntryToken:
1296 // Entry tokens don't need to be added to the list. They are
1301 case ISD::TokenFactor:
1302 if (Op.hasOneUse() &&
1303 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1304 // Queue up for processing.
1305 TFs.push_back(Op.getNode());
1306 // Clean up in case the token factor is removed.
1307 AddToWorkList(Op.getNode());
1314 // Only add if it isn't already in the list.
1315 if (SeenOps.insert(Op.getNode()))
1326 // If we've change things around then replace token factor.
1329 // The entry token is the only possible outcome.
1330 Result = DAG.getEntryNode();
1332 // New and improved token factor.
1333 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
1334 MVT::Other, &Ops[0], Ops.size());
1337 // Don't add users to work list.
1338 return CombineTo(N, Result, false);
1344 /// MERGE_VALUES can always be eliminated.
1345 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1346 WorkListRemover DeadNodes(*this);
1347 // Replacing results may cause a different MERGE_VALUES to suddenly
1348 // be CSE'd with N, and carry its uses with it. Iterate until no
1349 // uses remain, to ensure that the node can be safely deleted.
1350 // First add the users of this node to the work list so that they
1351 // can be tried again once they have new operands.
1352 AddUsersToWorkList(N);
1354 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1355 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1356 } while (!N->use_empty());
1357 removeFromWorkList(N);
1359 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1363 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1364 SelectionDAG &DAG) {
1365 EVT VT = N0.getValueType();
1366 SDValue N00 = N0.getOperand(0);
1367 SDValue N01 = N0.getOperand(1);
1368 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1370 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1371 isa<ConstantSDNode>(N00.getOperand(1))) {
1372 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1373 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1374 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1375 N00.getOperand(0), N01),
1376 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1377 N00.getOperand(1), N01));
1378 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1384 SDValue DAGCombiner::visitADD(SDNode *N) {
1385 SDValue N0 = N->getOperand(0);
1386 SDValue N1 = N->getOperand(1);
1387 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1388 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1389 EVT VT = N0.getValueType();
1392 if (VT.isVector()) {
1393 SDValue FoldedVOp = SimplifyVBinOp(N);
1394 if (FoldedVOp.getNode()) return FoldedVOp;
1396 // fold (add x, 0) -> x, vector edition
1397 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1399 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1403 // fold (add x, undef) -> undef
1404 if (N0.getOpcode() == ISD::UNDEF)
1406 if (N1.getOpcode() == ISD::UNDEF)
1408 // fold (add c1, c2) -> c1+c2
1410 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1411 // canonicalize constant to RHS
1413 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1414 // fold (add x, 0) -> x
1415 if (N1C && N1C->isNullValue())
1417 // fold (add Sym, c) -> Sym+c
1418 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1419 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1420 GA->getOpcode() == ISD::GlobalAddress)
1421 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1423 (uint64_t)N1C->getSExtValue());
1424 // fold ((c1-A)+c2) -> (c1+c2)-A
1425 if (N1C && N0.getOpcode() == ISD::SUB)
1426 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1427 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1428 DAG.getConstant(N1C->getAPIntValue()+
1429 N0C->getAPIntValue(), VT),
1432 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1433 if (RADD.getNode() != 0)
1435 // fold ((0-A) + B) -> B-A
1436 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1437 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1438 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1439 // fold (A + (0-B)) -> A-B
1440 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1441 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1442 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1443 // fold (A+(B-A)) -> B
1444 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1445 return N1.getOperand(0);
1446 // fold ((B-A)+A) -> B
1447 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1448 return N0.getOperand(0);
1449 // fold (A+(B-(A+C))) to (B-C)
1450 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1451 N0 == N1.getOperand(1).getOperand(0))
1452 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1453 N1.getOperand(1).getOperand(1));
1454 // fold (A+(B-(C+A))) to (B-C)
1455 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1456 N0 == N1.getOperand(1).getOperand(1))
1457 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1458 N1.getOperand(1).getOperand(0));
1459 // fold (A+((B-A)+or-C)) to (B+or-C)
1460 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1461 N1.getOperand(0).getOpcode() == ISD::SUB &&
1462 N0 == N1.getOperand(0).getOperand(1))
1463 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1464 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1466 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1467 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1468 SDValue N00 = N0.getOperand(0);
1469 SDValue N01 = N0.getOperand(1);
1470 SDValue N10 = N1.getOperand(0);
1471 SDValue N11 = N1.getOperand(1);
1473 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1474 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1475 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1476 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1479 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1480 return SDValue(N, 0);
1482 // fold (a+b) -> (a|b) iff a and b share no bits.
1483 if (VT.isInteger() && !VT.isVector()) {
1484 APInt LHSZero, LHSOne;
1485 APInt RHSZero, RHSOne;
1486 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1488 if (LHSZero.getBoolValue()) {
1489 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1491 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1492 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1493 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1494 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1498 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1499 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1500 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1501 if (Result.getNode()) return Result;
1503 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1504 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1505 if (Result.getNode()) return Result;
1508 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1509 if (N1.getOpcode() == ISD::SHL &&
1510 N1.getOperand(0).getOpcode() == ISD::SUB)
1511 if (ConstantSDNode *C =
1512 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1513 if (C->getAPIntValue() == 0)
1514 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1515 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1516 N1.getOperand(0).getOperand(1),
1518 if (N0.getOpcode() == ISD::SHL &&
1519 N0.getOperand(0).getOpcode() == ISD::SUB)
1520 if (ConstantSDNode *C =
1521 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1522 if (C->getAPIntValue() == 0)
1523 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1524 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1525 N0.getOperand(0).getOperand(1),
1528 if (N1.getOpcode() == ISD::AND) {
1529 SDValue AndOp0 = N1.getOperand(0);
1530 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1531 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1532 unsigned DestBits = VT.getScalarType().getSizeInBits();
1534 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1535 // and similar xforms where the inner op is either ~0 or 0.
1536 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1538 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1542 // add (sext i1), X -> sub X, (zext i1)
1543 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1544 N0.getOperand(0).getValueType() == MVT::i1 &&
1545 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1547 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1548 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1554 SDValue DAGCombiner::visitADDC(SDNode *N) {
1555 SDValue N0 = N->getOperand(0);
1556 SDValue N1 = N->getOperand(1);
1557 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1558 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1559 EVT VT = N0.getValueType();
1561 // If the flag result is dead, turn this into an ADD.
1562 if (!N->hasAnyUseOfValue(1))
1563 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1564 DAG.getNode(ISD::CARRY_FALSE,
1565 SDLoc(N), MVT::Glue));
1567 // canonicalize constant to RHS.
1569 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1571 // fold (addc x, 0) -> x + no carry out
1572 if (N1C && N1C->isNullValue())
1573 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1574 SDLoc(N), MVT::Glue));
1576 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1577 APInt LHSZero, LHSOne;
1578 APInt RHSZero, RHSOne;
1579 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1581 if (LHSZero.getBoolValue()) {
1582 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1584 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1585 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1586 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1587 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1588 DAG.getNode(ISD::CARRY_FALSE,
1589 SDLoc(N), MVT::Glue));
1595 SDValue DAGCombiner::visitADDE(SDNode *N) {
1596 SDValue N0 = N->getOperand(0);
1597 SDValue N1 = N->getOperand(1);
1598 SDValue CarryIn = N->getOperand(2);
1599 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1600 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1602 // canonicalize constant to RHS
1604 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1607 // fold (adde x, y, false) -> (addc x, y)
1608 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1609 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1614 // Since it may not be valid to emit a fold to zero for vector initializers
1615 // check if we can before folding.
1616 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1618 bool LegalOperations, bool LegalTypes) {
1620 return DAG.getConstant(0, VT);
1621 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
1622 // Produce a vector of zeros.
1623 EVT ElemTy = VT.getVectorElementType();
1624 if (LegalTypes && TLI.getTypeAction(*DAG.getContext(), ElemTy) ==
1625 TargetLowering::TypePromoteInteger)
1626 ElemTy = TLI.getTypeToTransformTo(*DAG.getContext(), ElemTy);
1627 assert((!LegalTypes || TLI.isTypeLegal(ElemTy)) &&
1628 "Type for zero vector elements is not legal");
1629 SDValue El = DAG.getConstant(0, ElemTy);
1630 std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
1631 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
1632 &Ops[0], Ops.size());
1637 SDValue DAGCombiner::visitSUB(SDNode *N) {
1638 SDValue N0 = N->getOperand(0);
1639 SDValue N1 = N->getOperand(1);
1640 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1641 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1642 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1643 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1644 EVT VT = N0.getValueType();
1647 if (VT.isVector()) {
1648 SDValue FoldedVOp = SimplifyVBinOp(N);
1649 if (FoldedVOp.getNode()) return FoldedVOp;
1651 // fold (sub x, 0) -> x, vector edition
1652 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1656 // fold (sub x, x) -> 0
1657 // FIXME: Refactor this and xor and other similar operations together.
1659 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1660 // fold (sub c1, c2) -> c1-c2
1662 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1663 // fold (sub x, c) -> (add x, -c)
1665 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1666 DAG.getConstant(-N1C->getAPIntValue(), VT));
1667 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1668 if (N0C && N0C->isAllOnesValue())
1669 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1670 // fold A-(A-B) -> B
1671 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1672 return N1.getOperand(1);
1673 // fold (A+B)-A -> B
1674 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1675 return N0.getOperand(1);
1676 // fold (A+B)-B -> A
1677 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1678 return N0.getOperand(0);
1679 // fold C2-(A+C1) -> (C2-C1)-A
1680 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1681 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1683 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1686 // fold ((A+(B+or-C))-B) -> A+or-C
1687 if (N0.getOpcode() == ISD::ADD &&
1688 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1689 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1690 N0.getOperand(1).getOperand(0) == N1)
1691 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1692 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1693 // fold ((A+(C+B))-B) -> A+C
1694 if (N0.getOpcode() == ISD::ADD &&
1695 N0.getOperand(1).getOpcode() == ISD::ADD &&
1696 N0.getOperand(1).getOperand(1) == N1)
1697 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1698 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1699 // fold ((A-(B-C))-C) -> A-B
1700 if (N0.getOpcode() == ISD::SUB &&
1701 N0.getOperand(1).getOpcode() == ISD::SUB &&
1702 N0.getOperand(1).getOperand(1) == N1)
1703 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1704 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1706 // If either operand of a sub is undef, the result is undef
1707 if (N0.getOpcode() == ISD::UNDEF)
1709 if (N1.getOpcode() == ISD::UNDEF)
1712 // If the relocation model supports it, consider symbol offsets.
1713 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1714 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1715 // fold (sub Sym, c) -> Sym-c
1716 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1717 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1719 (uint64_t)N1C->getSExtValue());
1720 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1721 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1722 if (GA->getGlobal() == GB->getGlobal())
1723 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1730 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1731 SDValue N0 = N->getOperand(0);
1732 SDValue N1 = N->getOperand(1);
1733 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1734 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1735 EVT VT = N0.getValueType();
1737 // If the flag result is dead, turn this into an SUB.
1738 if (!N->hasAnyUseOfValue(1))
1739 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1740 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1743 // fold (subc x, x) -> 0 + no borrow
1745 return CombineTo(N, DAG.getConstant(0, VT),
1746 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1749 // fold (subc x, 0) -> x + no borrow
1750 if (N1C && N1C->isNullValue())
1751 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1754 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1755 if (N0C && N0C->isAllOnesValue())
1756 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1757 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1763 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1764 SDValue N0 = N->getOperand(0);
1765 SDValue N1 = N->getOperand(1);
1766 SDValue CarryIn = N->getOperand(2);
1768 // fold (sube x, y, false) -> (subc x, y)
1769 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1770 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1775 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
1776 /// all the same constant or undefined.
1777 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
1778 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
1783 unsigned SplatBitSize;
1785 EVT EltVT = N->getValueType(0).getVectorElementType();
1786 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
1788 EltVT.getSizeInBits() >= SplatBitSize);
1791 SDValue DAGCombiner::visitMUL(SDNode *N) {
1792 SDValue N0 = N->getOperand(0);
1793 SDValue N1 = N->getOperand(1);
1794 EVT VT = N0.getValueType();
1796 // fold (mul x, undef) -> 0
1797 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1798 return DAG.getConstant(0, VT);
1800 bool N0IsConst = false;
1801 bool N1IsConst = false;
1802 APInt ConstValue0, ConstValue1;
1804 if (VT.isVector()) {
1805 SDValue FoldedVOp = SimplifyVBinOp(N);
1806 if (FoldedVOp.getNode()) return FoldedVOp;
1808 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1809 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1811 N0IsConst = dyn_cast<ConstantSDNode>(N0) != 0;
1812 ConstValue0 = N0IsConst? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue() : APInt();
1813 N1IsConst = dyn_cast<ConstantSDNode>(N1) != 0;
1814 ConstValue1 = N1IsConst? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue() : APInt();
1817 // fold (mul c1, c2) -> c1*c2
1818 if (N0IsConst && N1IsConst)
1819 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1821 // canonicalize constant to RHS
1822 if (N0IsConst && !N1IsConst)
1823 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1824 // fold (mul x, 0) -> 0
1825 if (N1IsConst && ConstValue1 == 0)
1827 // We require a splat of the entire scalar bit width for non-contiguous
1830 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1831 // fold (mul x, 1) -> x
1832 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1834 // fold (mul x, -1) -> 0-x
1835 if (N1IsConst && ConstValue1.isAllOnesValue())
1836 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1837 DAG.getConstant(0, VT), N0);
1838 // fold (mul x, (1 << c)) -> x << c
1839 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1840 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1841 DAG.getConstant(ConstValue1.logBase2(),
1842 getShiftAmountTy(N0.getValueType())));
1843 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1844 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1845 unsigned Log2Val = (-ConstValue1).logBase2();
1846 // FIXME: If the input is something that is easily negated (e.g. a
1847 // single-use add), we should put the negate there.
1848 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1849 DAG.getConstant(0, VT),
1850 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1851 DAG.getConstant(Log2Val,
1852 getShiftAmountTy(N0.getValueType()))));
1856 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1857 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1858 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1859 isa<ConstantSDNode>(N0.getOperand(1)))) {
1860 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1861 N1, N0.getOperand(1));
1862 AddToWorkList(C3.getNode());
1863 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1864 N0.getOperand(0), C3);
1867 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1870 SDValue Sh(0,0), Y(0,0);
1871 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1872 if (N0.getOpcode() == ISD::SHL &&
1873 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1874 isa<ConstantSDNode>(N0.getOperand(1))) &&
1875 N0.getNode()->hasOneUse()) {
1877 } else if (N1.getOpcode() == ISD::SHL &&
1878 isa<ConstantSDNode>(N1.getOperand(1)) &&
1879 N1.getNode()->hasOneUse()) {
1884 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1885 Sh.getOperand(0), Y);
1886 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1887 Mul, Sh.getOperand(1));
1891 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1892 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1893 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1894 isa<ConstantSDNode>(N0.getOperand(1))))
1895 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1896 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1897 N0.getOperand(0), N1),
1898 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1899 N0.getOperand(1), N1));
1902 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1903 if (RMUL.getNode() != 0)
1909 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1910 SDValue N0 = N->getOperand(0);
1911 SDValue N1 = N->getOperand(1);
1912 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1913 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1914 EVT VT = N->getValueType(0);
1917 if (VT.isVector()) {
1918 SDValue FoldedVOp = SimplifyVBinOp(N);
1919 if (FoldedVOp.getNode()) return FoldedVOp;
1922 // fold (sdiv c1, c2) -> c1/c2
1923 if (N0C && N1C && !N1C->isNullValue())
1924 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1925 // fold (sdiv X, 1) -> X
1926 if (N1C && N1C->getAPIntValue() == 1LL)
1928 // fold (sdiv X, -1) -> 0-X
1929 if (N1C && N1C->isAllOnesValue())
1930 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1931 DAG.getConstant(0, VT), N0);
1932 // If we know the sign bits of both operands are zero, strength reduce to a
1933 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1934 if (!VT.isVector()) {
1935 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1936 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
1939 // fold (sdiv X, pow2) -> simple ops after legalize
1940 if (N1C && !N1C->isNullValue() &&
1941 (N1C->getAPIntValue().isPowerOf2() ||
1942 (-N1C->getAPIntValue()).isPowerOf2())) {
1943 // If dividing by powers of two is cheap, then don't perform the following
1945 if (TLI.isPow2DivCheap())
1948 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
1950 // Splat the sign bit into the register
1951 SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
1952 DAG.getConstant(VT.getSizeInBits()-1,
1953 getShiftAmountTy(N0.getValueType())));
1954 AddToWorkList(SGN.getNode());
1956 // Add (N0 < 0) ? abs2 - 1 : 0;
1957 SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
1958 DAG.getConstant(VT.getSizeInBits() - lg2,
1959 getShiftAmountTy(SGN.getValueType())));
1960 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
1961 AddToWorkList(SRL.getNode());
1962 AddToWorkList(ADD.getNode()); // Divide by pow2
1963 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
1964 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
1966 // If we're dividing by a positive value, we're done. Otherwise, we must
1967 // negate the result.
1968 if (N1C->getAPIntValue().isNonNegative())
1971 AddToWorkList(SRA.getNode());
1972 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1973 DAG.getConstant(0, VT), SRA);
1976 // if integer divide is expensive and we satisfy the requirements, emit an
1977 // alternate sequence.
1978 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1979 SDValue Op = BuildSDIV(N);
1980 if (Op.getNode()) return Op;
1984 if (N0.getOpcode() == ISD::UNDEF)
1985 return DAG.getConstant(0, VT);
1986 // X / undef -> undef
1987 if (N1.getOpcode() == ISD::UNDEF)
1993 SDValue DAGCombiner::visitUDIV(SDNode *N) {
1994 SDValue N0 = N->getOperand(0);
1995 SDValue N1 = N->getOperand(1);
1996 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1997 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1998 EVT VT = N->getValueType(0);
2001 if (VT.isVector()) {
2002 SDValue FoldedVOp = SimplifyVBinOp(N);
2003 if (FoldedVOp.getNode()) return FoldedVOp;
2006 // fold (udiv c1, c2) -> c1/c2
2007 if (N0C && N1C && !N1C->isNullValue())
2008 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2009 // fold (udiv x, (1 << c)) -> x >>u c
2010 if (N1C && N1C->getAPIntValue().isPowerOf2())
2011 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2012 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2013 getShiftAmountTy(N0.getValueType())));
2014 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2015 if (N1.getOpcode() == ISD::SHL) {
2016 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2017 if (SHC->getAPIntValue().isPowerOf2()) {
2018 EVT ADDVT = N1.getOperand(1).getValueType();
2019 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2021 DAG.getConstant(SHC->getAPIntValue()
2024 AddToWorkList(Add.getNode());
2025 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2029 // fold (udiv x, c) -> alternate
2030 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2031 SDValue Op = BuildUDIV(N);
2032 if (Op.getNode()) return Op;
2036 if (N0.getOpcode() == ISD::UNDEF)
2037 return DAG.getConstant(0, VT);
2038 // X / undef -> undef
2039 if (N1.getOpcode() == ISD::UNDEF)
2045 SDValue DAGCombiner::visitSREM(SDNode *N) {
2046 SDValue N0 = N->getOperand(0);
2047 SDValue N1 = N->getOperand(1);
2048 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2049 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2050 EVT VT = N->getValueType(0);
2052 // fold (srem c1, c2) -> c1%c2
2053 if (N0C && N1C && !N1C->isNullValue())
2054 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2055 // If we know the sign bits of both operands are zero, strength reduce to a
2056 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2057 if (!VT.isVector()) {
2058 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2059 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2062 // If X/C can be simplified by the division-by-constant logic, lower
2063 // X%C to the equivalent of X-X/C*C.
2064 if (N1C && !N1C->isNullValue()) {
2065 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2066 AddToWorkList(Div.getNode());
2067 SDValue OptimizedDiv = combine(Div.getNode());
2068 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2069 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2071 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2072 AddToWorkList(Mul.getNode());
2078 if (N0.getOpcode() == ISD::UNDEF)
2079 return DAG.getConstant(0, VT);
2080 // X % undef -> undef
2081 if (N1.getOpcode() == ISD::UNDEF)
2087 SDValue DAGCombiner::visitUREM(SDNode *N) {
2088 SDValue N0 = N->getOperand(0);
2089 SDValue N1 = N->getOperand(1);
2090 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2091 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2092 EVT VT = N->getValueType(0);
2094 // fold (urem c1, c2) -> c1%c2
2095 if (N0C && N1C && !N1C->isNullValue())
2096 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2097 // fold (urem x, pow2) -> (and x, pow2-1)
2098 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2099 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2100 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2101 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2102 if (N1.getOpcode() == ISD::SHL) {
2103 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2104 if (SHC->getAPIntValue().isPowerOf2()) {
2106 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2107 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2109 AddToWorkList(Add.getNode());
2110 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2115 // If X/C can be simplified by the division-by-constant logic, lower
2116 // X%C to the equivalent of X-X/C*C.
2117 if (N1C && !N1C->isNullValue()) {
2118 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2119 AddToWorkList(Div.getNode());
2120 SDValue OptimizedDiv = combine(Div.getNode());
2121 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2122 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2124 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2125 AddToWorkList(Mul.getNode());
2131 if (N0.getOpcode() == ISD::UNDEF)
2132 return DAG.getConstant(0, VT);
2133 // X % undef -> undef
2134 if (N1.getOpcode() == ISD::UNDEF)
2140 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2141 SDValue N0 = N->getOperand(0);
2142 SDValue N1 = N->getOperand(1);
2143 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2144 EVT VT = N->getValueType(0);
2147 // fold (mulhs x, 0) -> 0
2148 if (N1C && N1C->isNullValue())
2150 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2151 if (N1C && N1C->getAPIntValue() == 1)
2152 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2153 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2154 getShiftAmountTy(N0.getValueType())));
2155 // fold (mulhs x, undef) -> 0
2156 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2157 return DAG.getConstant(0, VT);
2159 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2161 if (VT.isSimple() && !VT.isVector()) {
2162 MVT Simple = VT.getSimpleVT();
2163 unsigned SimpleSize = Simple.getSizeInBits();
2164 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2165 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2166 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2167 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2168 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2169 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2170 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2171 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2178 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2179 SDValue N0 = N->getOperand(0);
2180 SDValue N1 = N->getOperand(1);
2181 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2182 EVT VT = N->getValueType(0);
2185 // fold (mulhu x, 0) -> 0
2186 if (N1C && N1C->isNullValue())
2188 // fold (mulhu x, 1) -> 0
2189 if (N1C && N1C->getAPIntValue() == 1)
2190 return DAG.getConstant(0, N0.getValueType());
2191 // fold (mulhu x, undef) -> 0
2192 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2193 return DAG.getConstant(0, VT);
2195 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2197 if (VT.isSimple() && !VT.isVector()) {
2198 MVT Simple = VT.getSimpleVT();
2199 unsigned SimpleSize = Simple.getSizeInBits();
2200 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2201 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2202 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2203 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2204 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2205 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2206 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2207 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2214 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2215 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2216 /// that are being performed. Return true if a simplification was made.
2218 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2220 // If the high half is not needed, just compute the low half.
2221 bool HiExists = N->hasAnyUseOfValue(1);
2223 (!LegalOperations ||
2224 TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
2225 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2226 N->op_begin(), N->getNumOperands());
2227 return CombineTo(N, Res, Res);
2230 // If the low half is not needed, just compute the high half.
2231 bool LoExists = N->hasAnyUseOfValue(0);
2233 (!LegalOperations ||
2234 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2235 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2236 N->op_begin(), N->getNumOperands());
2237 return CombineTo(N, Res, Res);
2240 // If both halves are used, return as it is.
2241 if (LoExists && HiExists)
2244 // If the two computed results can be simplified separately, separate them.
2246 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2247 N->op_begin(), N->getNumOperands());
2248 AddToWorkList(Lo.getNode());
2249 SDValue LoOpt = combine(Lo.getNode());
2250 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2251 (!LegalOperations ||
2252 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2253 return CombineTo(N, LoOpt, LoOpt);
2257 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2258 N->op_begin(), N->getNumOperands());
2259 AddToWorkList(Hi.getNode());
2260 SDValue HiOpt = combine(Hi.getNode());
2261 if (HiOpt.getNode() && HiOpt != Hi &&
2262 (!LegalOperations ||
2263 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2264 return CombineTo(N, HiOpt, HiOpt);
2270 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2271 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2272 if (Res.getNode()) return Res;
2274 EVT VT = N->getValueType(0);
2277 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2279 if (VT.isSimple() && !VT.isVector()) {
2280 MVT Simple = VT.getSimpleVT();
2281 unsigned SimpleSize = Simple.getSizeInBits();
2282 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2283 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2284 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2285 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2286 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2287 // Compute the high part as N1.
2288 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2289 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2290 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2291 // Compute the low part as N0.
2292 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2293 return CombineTo(N, Lo, Hi);
2300 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2301 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2302 if (Res.getNode()) return Res;
2304 EVT VT = N->getValueType(0);
2307 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2309 if (VT.isSimple() && !VT.isVector()) {
2310 MVT Simple = VT.getSimpleVT();
2311 unsigned SimpleSize = Simple.getSizeInBits();
2312 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2313 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2314 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2315 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2316 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2317 // Compute the high part as N1.
2318 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2319 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2320 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2321 // Compute the low part as N0.
2322 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2323 return CombineTo(N, Lo, Hi);
2330 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2331 // (smulo x, 2) -> (saddo x, x)
2332 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2333 if (C2->getAPIntValue() == 2)
2334 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2335 N->getOperand(0), N->getOperand(0));
2340 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2341 // (umulo x, 2) -> (uaddo x, x)
2342 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2343 if (C2->getAPIntValue() == 2)
2344 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2345 N->getOperand(0), N->getOperand(0));
2350 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2351 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2352 if (Res.getNode()) return Res;
2357 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2358 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2359 if (Res.getNode()) return Res;
2364 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2365 /// two operands of the same opcode, try to simplify it.
2366 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2367 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2368 EVT VT = N0.getValueType();
2369 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2371 // Bail early if none of these transforms apply.
2372 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2374 // For each of OP in AND/OR/XOR:
2375 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2376 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2377 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2378 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2380 // do not sink logical op inside of a vector extend, since it may combine
2382 EVT Op0VT = N0.getOperand(0).getValueType();
2383 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2384 N0.getOpcode() == ISD::SIGN_EXTEND ||
2385 // Avoid infinite looping with PromoteIntBinOp.
2386 (N0.getOpcode() == ISD::ANY_EXTEND &&
2387 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2388 (N0.getOpcode() == ISD::TRUNCATE &&
2389 (!TLI.isZExtFree(VT, Op0VT) ||
2390 !TLI.isTruncateFree(Op0VT, VT)) &&
2391 TLI.isTypeLegal(Op0VT))) &&
2393 Op0VT == N1.getOperand(0).getValueType() &&
2394 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2395 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2396 N0.getOperand(0).getValueType(),
2397 N0.getOperand(0), N1.getOperand(0));
2398 AddToWorkList(ORNode.getNode());
2399 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2402 // For each of OP in SHL/SRL/SRA/AND...
2403 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2404 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2405 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2406 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2407 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2408 N0.getOperand(1) == N1.getOperand(1)) {
2409 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2410 N0.getOperand(0).getValueType(),
2411 N0.getOperand(0), N1.getOperand(0));
2412 AddToWorkList(ORNode.getNode());
2413 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2414 ORNode, N0.getOperand(1));
2417 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2418 // Only perform this optimization after type legalization and before
2419 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2420 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2421 // we don't want to undo this promotion.
2422 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2424 if ((N0.getOpcode() == ISD::BITCAST ||
2425 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2426 Level == AfterLegalizeTypes) {
2427 SDValue In0 = N0.getOperand(0);
2428 SDValue In1 = N1.getOperand(0);
2429 EVT In0Ty = In0.getValueType();
2430 EVT In1Ty = In1.getValueType();
2432 // If both incoming values are integers, and the original types are the
2434 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2435 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2436 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2437 AddToWorkList(Op.getNode());
2442 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2443 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2444 // If both shuffles use the same mask, and both shuffle within a single
2445 // vector, then it is worthwhile to move the swizzle after the operation.
2446 // The type-legalizer generates this pattern when loading illegal
2447 // vector types from memory. In many cases this allows additional shuffle
2449 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
2450 N0.getOperand(1).getOpcode() == ISD::UNDEF &&
2451 N1.getOperand(1).getOpcode() == ISD::UNDEF) {
2452 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2453 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2455 assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
2456 "Inputs to shuffles are not the same type");
2458 unsigned NumElts = VT.getVectorNumElements();
2460 // Check that both shuffles use the same mask. The masks are known to be of
2461 // the same length because the result vector type is the same.
2462 bool SameMask = true;
2463 for (unsigned i = 0; i != NumElts; ++i) {
2464 int Idx0 = SVN0->getMaskElt(i);
2465 int Idx1 = SVN1->getMaskElt(i);
2473 SDValue Op = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2474 N0.getOperand(0), N1.getOperand(0));
2475 AddToWorkList(Op.getNode());
2476 return DAG.getVectorShuffle(VT, SDLoc(N), Op,
2477 DAG.getUNDEF(VT), &SVN0->getMask()[0]);
2484 SDValue DAGCombiner::visitAND(SDNode *N) {
2485 SDValue N0 = N->getOperand(0);
2486 SDValue N1 = N->getOperand(1);
2487 SDValue LL, LR, RL, RR, CC0, CC1;
2488 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2489 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2490 EVT VT = N1.getValueType();
2491 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2494 if (VT.isVector()) {
2495 SDValue FoldedVOp = SimplifyVBinOp(N);
2496 if (FoldedVOp.getNode()) return FoldedVOp;
2498 // fold (and x, 0) -> 0, vector edition
2499 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2501 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2504 // fold (and x, -1) -> x, vector edition
2505 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2507 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2511 // fold (and x, undef) -> 0
2512 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2513 return DAG.getConstant(0, VT);
2514 // fold (and c1, c2) -> c1&c2
2516 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2517 // canonicalize constant to RHS
2519 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2520 // fold (and x, -1) -> x
2521 if (N1C && N1C->isAllOnesValue())
2523 // if (and x, c) is known to be zero, return 0
2524 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2525 APInt::getAllOnesValue(BitWidth)))
2526 return DAG.getConstant(0, VT);
2528 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2529 if (RAND.getNode() != 0)
2531 // fold (and (or x, C), D) -> D if (C & D) == D
2532 if (N1C && N0.getOpcode() == ISD::OR)
2533 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2534 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2536 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2537 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2538 SDValue N0Op0 = N0.getOperand(0);
2539 APInt Mask = ~N1C->getAPIntValue();
2540 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2541 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2542 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2543 N0.getValueType(), N0Op0);
2545 // Replace uses of the AND with uses of the Zero extend node.
2548 // We actually want to replace all uses of the any_extend with the
2549 // zero_extend, to avoid duplicating things. This will later cause this
2550 // AND to be folded.
2551 CombineTo(N0.getNode(), Zext);
2552 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2555 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2556 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2557 // already be zero by virtue of the width of the base type of the load.
2559 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2561 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2562 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2563 N0.getOpcode() == ISD::LOAD) {
2564 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2565 N0 : N0.getOperand(0) );
2567 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2568 // This can be a pure constant or a vector splat, in which case we treat the
2569 // vector as a scalar and use the splat value.
2570 APInt Constant = APInt::getNullValue(1);
2571 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2572 Constant = C->getAPIntValue();
2573 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2574 APInt SplatValue, SplatUndef;
2575 unsigned SplatBitSize;
2577 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2578 SplatBitSize, HasAnyUndefs);
2580 // Undef bits can contribute to a possible optimisation if set, so
2582 SplatValue |= SplatUndef;
2584 // The splat value may be something like "0x00FFFFFF", which means 0 for
2585 // the first vector value and FF for the rest, repeating. We need a mask
2586 // that will apply equally to all members of the vector, so AND all the
2587 // lanes of the constant together.
2588 EVT VT = Vector->getValueType(0);
2589 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2591 // If the splat value has been compressed to a bitlength lower
2592 // than the size of the vector lane, we need to re-expand it to
2594 if (BitWidth > SplatBitSize)
2595 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2596 SplatBitSize < BitWidth;
2597 SplatBitSize = SplatBitSize * 2)
2598 SplatValue |= SplatValue.shl(SplatBitSize);
2600 Constant = APInt::getAllOnesValue(BitWidth);
2601 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2602 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2606 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2607 // actually legal and isn't going to get expanded, else this is a false
2609 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2610 Load->getMemoryVT());
2612 // Resize the constant to the same size as the original memory access before
2613 // extension. If it is still the AllOnesValue then this AND is completely
2616 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2619 switch (Load->getExtensionType()) {
2620 default: B = false; break;
2621 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2623 case ISD::NON_EXTLOAD: B = true; break;
2626 if (B && Constant.isAllOnesValue()) {
2627 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2628 // preserve semantics once we get rid of the AND.
2629 SDValue NewLoad(Load, 0);
2630 if (Load->getExtensionType() == ISD::EXTLOAD) {
2631 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2632 Load->getValueType(0), SDLoc(Load),
2633 Load->getChain(), Load->getBasePtr(),
2634 Load->getOffset(), Load->getMemoryVT(),
2635 Load->getMemOperand());
2636 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2637 if (Load->getNumValues() == 3) {
2638 // PRE/POST_INC loads have 3 values.
2639 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2640 NewLoad.getValue(2) };
2641 CombineTo(Load, To, 3, true);
2643 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2647 // Fold the AND away, taking care not to fold to the old load node if we
2649 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2651 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2654 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2655 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2656 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2657 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2659 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2660 LL.getValueType().isInteger()) {
2661 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2662 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2663 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2664 LR.getValueType(), LL, RL);
2665 AddToWorkList(ORNode.getNode());
2666 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2668 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2669 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2670 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2671 LR.getValueType(), LL, RL);
2672 AddToWorkList(ANDNode.getNode());
2673 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2675 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2676 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2677 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2678 LR.getValueType(), LL, RL);
2679 AddToWorkList(ORNode.getNode());
2680 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2683 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2684 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2685 Op0 == Op1 && LL.getValueType().isInteger() &&
2686 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2687 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2688 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2689 cast<ConstantSDNode>(RR)->isNullValue()))) {
2690 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2691 LL, DAG.getConstant(1, LL.getValueType()));
2692 AddToWorkList(ADDNode.getNode());
2693 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2694 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2696 // canonicalize equivalent to ll == rl
2697 if (LL == RR && LR == RL) {
2698 Op1 = ISD::getSetCCSwappedOperands(Op1);
2701 if (LL == RL && LR == RR) {
2702 bool isInteger = LL.getValueType().isInteger();
2703 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2704 if (Result != ISD::SETCC_INVALID &&
2705 (!LegalOperations ||
2706 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2707 TLI.isOperationLegal(ISD::SETCC,
2708 getSetCCResultType(N0.getSimpleValueType())))))
2709 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2714 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2715 if (N0.getOpcode() == N1.getOpcode()) {
2716 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2717 if (Tmp.getNode()) return Tmp;
2720 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2721 // fold (and (sra)) -> (and (srl)) when possible.
2722 if (!VT.isVector() &&
2723 SimplifyDemandedBits(SDValue(N, 0)))
2724 return SDValue(N, 0);
2726 // fold (zext_inreg (extload x)) -> (zextload x)
2727 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2728 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2729 EVT MemVT = LN0->getMemoryVT();
2730 // If we zero all the possible extended bits, then we can turn this into
2731 // a zextload if we are running before legalize or the operation is legal.
2732 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2733 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2734 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2735 ((!LegalOperations && !LN0->isVolatile()) ||
2736 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2737 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2738 LN0->getChain(), LN0->getBasePtr(),
2739 LN0->getPointerInfo(), MemVT,
2740 LN0->isVolatile(), LN0->isNonTemporal(),
2741 LN0->getAlignment());
2743 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2744 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2747 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2748 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2750 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2751 EVT MemVT = LN0->getMemoryVT();
2752 // If we zero all the possible extended bits, then we can turn this into
2753 // a zextload if we are running before legalize or the operation is legal.
2754 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2755 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2756 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2757 ((!LegalOperations && !LN0->isVolatile()) ||
2758 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2759 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2761 LN0->getBasePtr(), LN0->getPointerInfo(),
2763 LN0->isVolatile(), LN0->isNonTemporal(),
2764 LN0->getAlignment());
2766 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2767 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2771 // fold (and (load x), 255) -> (zextload x, i8)
2772 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2773 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2774 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2775 (N0.getOpcode() == ISD::ANY_EXTEND &&
2776 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2777 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2778 LoadSDNode *LN0 = HasAnyExt
2779 ? cast<LoadSDNode>(N0.getOperand(0))
2780 : cast<LoadSDNode>(N0);
2781 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2782 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2783 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2784 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2785 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2786 EVT LoadedVT = LN0->getMemoryVT();
2788 if (ExtVT == LoadedVT &&
2789 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2790 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2793 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2794 LN0->getChain(), LN0->getBasePtr(),
2795 LN0->getPointerInfo(),
2796 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2797 LN0->getAlignment());
2799 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2800 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2803 // Do not change the width of a volatile load.
2804 // Do not generate loads of non-round integer types since these can
2805 // be expensive (and would be wrong if the type is not byte sized).
2806 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2807 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2808 EVT PtrType = LN0->getOperand(1).getValueType();
2810 unsigned Alignment = LN0->getAlignment();
2811 SDValue NewPtr = LN0->getBasePtr();
2813 // For big endian targets, we need to add an offset to the pointer
2814 // to load the correct bytes. For little endian systems, we merely
2815 // need to read fewer bytes from the same pointer.
2816 if (TLI.isBigEndian()) {
2817 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2818 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2819 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2820 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2821 NewPtr, DAG.getConstant(PtrOff, PtrType));
2822 Alignment = MinAlign(Alignment, PtrOff);
2825 AddToWorkList(NewPtr.getNode());
2827 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2829 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2830 LN0->getChain(), NewPtr,
2831 LN0->getPointerInfo(),
2832 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2835 CombineTo(LN0, Load, Load.getValue(1));
2836 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2842 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2843 VT.getSizeInBits() <= 64) {
2844 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2845 APInt ADDC = ADDI->getAPIntValue();
2846 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2847 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2848 // immediate for an add, but it is legal if its top c2 bits are set,
2849 // transform the ADD so the immediate doesn't need to be materialized
2851 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2852 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2853 SRLI->getZExtValue());
2854 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2856 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2858 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2859 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2860 CombineTo(N0.getNode(), NewAdd);
2861 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2869 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2870 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2871 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2872 N0.getOperand(1), false);
2873 if (BSwap.getNode())
2880 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2882 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2883 bool DemandHighBits) {
2884 if (!LegalOperations)
2887 EVT VT = N->getValueType(0);
2888 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2890 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2893 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2894 bool LookPassAnd0 = false;
2895 bool LookPassAnd1 = false;
2896 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2898 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2900 if (N0.getOpcode() == ISD::AND) {
2901 if (!N0.getNode()->hasOneUse())
2903 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2904 if (!N01C || N01C->getZExtValue() != 0xFF00)
2906 N0 = N0.getOperand(0);
2907 LookPassAnd0 = true;
2910 if (N1.getOpcode() == ISD::AND) {
2911 if (!N1.getNode()->hasOneUse())
2913 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2914 if (!N11C || N11C->getZExtValue() != 0xFF)
2916 N1 = N1.getOperand(0);
2917 LookPassAnd1 = true;
2920 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2922 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2924 if (!N0.getNode()->hasOneUse() ||
2925 !N1.getNode()->hasOneUse())
2928 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2929 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2932 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2935 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
2936 SDValue N00 = N0->getOperand(0);
2937 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
2938 if (!N00.getNode()->hasOneUse())
2940 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
2941 if (!N001C || N001C->getZExtValue() != 0xFF)
2943 N00 = N00.getOperand(0);
2944 LookPassAnd0 = true;
2947 SDValue N10 = N1->getOperand(0);
2948 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
2949 if (!N10.getNode()->hasOneUse())
2951 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
2952 if (!N101C || N101C->getZExtValue() != 0xFF00)
2954 N10 = N10.getOperand(0);
2955 LookPassAnd1 = true;
2961 // Make sure everything beyond the low halfword gets set to zero since the SRL
2962 // 16 will clear the top bits.
2963 unsigned OpSizeInBits = VT.getSizeInBits();
2964 if (DemandHighBits && OpSizeInBits > 16) {
2965 // If the left-shift isn't masked out then the only way this is a bswap is
2966 // if all bits beyond the low 8 are 0. In that case the entire pattern
2967 // reduces to a left shift anyway: leave it for other parts of the combiner.
2971 // However, if the right shift isn't masked out then it might be because
2972 // it's not needed. See if we can spot that too.
2973 if (!LookPassAnd1 &&
2974 !DAG.MaskedValueIsZero(
2975 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
2979 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
2980 if (OpSizeInBits > 16)
2981 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
2982 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
2986 /// isBSwapHWordElement - Return true if the specified node is an element
2987 /// that makes up a 32-bit packed halfword byteswap. i.e.
2988 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
2989 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
2990 if (!N.getNode()->hasOneUse())
2993 unsigned Opc = N.getOpcode();
2994 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
2997 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3002 switch (N1C->getZExtValue()) {
3005 case 0xFF: Num = 0; break;
3006 case 0xFF00: Num = 1; break;
3007 case 0xFF0000: Num = 2; break;
3008 case 0xFF000000: Num = 3; break;
3011 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3012 SDValue N0 = N.getOperand(0);
3013 if (Opc == ISD::AND) {
3014 if (Num == 0 || Num == 2) {
3016 // (x >> 8) & 0xff0000
3017 if (N0.getOpcode() != ISD::SRL)
3019 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3020 if (!C || C->getZExtValue() != 8)
3023 // (x << 8) & 0xff00
3024 // (x << 8) & 0xff000000
3025 if (N0.getOpcode() != ISD::SHL)
3027 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3028 if (!C || C->getZExtValue() != 8)
3031 } else if (Opc == ISD::SHL) {
3033 // (x & 0xff0000) << 8
3034 if (Num != 0 && Num != 2)
3036 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3037 if (!C || C->getZExtValue() != 8)
3039 } else { // Opc == ISD::SRL
3040 // (x & 0xff00) >> 8
3041 // (x & 0xff000000) >> 8
3042 if (Num != 1 && Num != 3)
3044 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3045 if (!C || C->getZExtValue() != 8)
3052 Parts[Num] = N0.getOperand(0).getNode();
3056 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3057 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3058 /// => (rotl (bswap x), 16)
3059 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3060 if (!LegalOperations)
3063 EVT VT = N->getValueType(0);
3066 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3069 SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
3071 // (or (or (and), (and)), (or (and), (and)))
3072 // (or (or (or (and), (and)), (and)), (and))
3073 if (N0.getOpcode() != ISD::OR)
3075 SDValue N00 = N0.getOperand(0);
3076 SDValue N01 = N0.getOperand(1);
3078 if (N1.getOpcode() == ISD::OR &&
3079 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3080 // (or (or (and), (and)), (or (and), (and)))
3081 SDValue N000 = N00.getOperand(0);
3082 if (!isBSwapHWordElement(N000, Parts))
3085 SDValue N001 = N00.getOperand(1);
3086 if (!isBSwapHWordElement(N001, Parts))
3088 SDValue N010 = N01.getOperand(0);
3089 if (!isBSwapHWordElement(N010, Parts))
3091 SDValue N011 = N01.getOperand(1);
3092 if (!isBSwapHWordElement(N011, Parts))
3095 // (or (or (or (and), (and)), (and)), (and))
3096 if (!isBSwapHWordElement(N1, Parts))
3098 if (!isBSwapHWordElement(N01, Parts))
3100 if (N00.getOpcode() != ISD::OR)
3102 SDValue N000 = N00.getOperand(0);
3103 if (!isBSwapHWordElement(N000, Parts))
3105 SDValue N001 = N00.getOperand(1);
3106 if (!isBSwapHWordElement(N001, Parts))
3110 // Make sure the parts are all coming from the same node.
3111 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3114 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3115 SDValue(Parts[0],0));
3117 // Result of the bswap should be rotated by 16. If it's not legal, than
3118 // do (x << 16) | (x >> 16).
3119 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3120 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3121 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3122 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3123 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3124 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3125 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3126 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3129 SDValue DAGCombiner::visitOR(SDNode *N) {
3130 SDValue N0 = N->getOperand(0);
3131 SDValue N1 = N->getOperand(1);
3132 SDValue LL, LR, RL, RR, CC0, CC1;
3133 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3134 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3135 EVT VT = N1.getValueType();
3138 if (VT.isVector()) {
3139 SDValue FoldedVOp = SimplifyVBinOp(N);
3140 if (FoldedVOp.getNode()) return FoldedVOp;
3142 // fold (or x, 0) -> x, vector edition
3143 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3145 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3148 // fold (or x, -1) -> -1, vector edition
3149 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3151 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3155 // fold (or x, undef) -> -1
3156 if (!LegalOperations &&
3157 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3158 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3159 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3161 // fold (or c1, c2) -> c1|c2
3163 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3164 // canonicalize constant to RHS
3166 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3167 // fold (or x, 0) -> x
3168 if (N1C && N1C->isNullValue())
3170 // fold (or x, -1) -> -1
3171 if (N1C && N1C->isAllOnesValue())
3173 // fold (or x, c) -> c iff (x & ~c) == 0
3174 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3177 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3178 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3179 if (BSwap.getNode() != 0)
3181 BSwap = MatchBSwapHWordLow(N, N0, N1);
3182 if (BSwap.getNode() != 0)
3186 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3187 if (ROR.getNode() != 0)
3189 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3190 // iff (c1 & c2) == 0.
3191 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3192 isa<ConstantSDNode>(N0.getOperand(1))) {
3193 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3194 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
3195 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3196 DAG.getNode(ISD::OR, SDLoc(N0), VT,
3197 N0.getOperand(0), N1),
3198 DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
3200 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3201 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3202 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3203 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3205 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3206 LL.getValueType().isInteger()) {
3207 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3208 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3209 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3210 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3211 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3212 LR.getValueType(), LL, RL);
3213 AddToWorkList(ORNode.getNode());
3214 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3216 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3217 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3218 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3219 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3220 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3221 LR.getValueType(), LL, RL);
3222 AddToWorkList(ANDNode.getNode());
3223 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3226 // canonicalize equivalent to ll == rl
3227 if (LL == RR && LR == RL) {
3228 Op1 = ISD::getSetCCSwappedOperands(Op1);
3231 if (LL == RL && LR == RR) {
3232 bool isInteger = LL.getValueType().isInteger();
3233 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3234 if (Result != ISD::SETCC_INVALID &&
3235 (!LegalOperations ||
3236 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3237 TLI.isOperationLegal(ISD::SETCC,
3238 getSetCCResultType(N0.getValueType())))))
3239 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3244 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3245 if (N0.getOpcode() == N1.getOpcode()) {
3246 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3247 if (Tmp.getNode()) return Tmp;
3250 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3251 if (N0.getOpcode() == ISD::AND &&
3252 N1.getOpcode() == ISD::AND &&
3253 N0.getOperand(1).getOpcode() == ISD::Constant &&
3254 N1.getOperand(1).getOpcode() == ISD::Constant &&
3255 // Don't increase # computations.
3256 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3257 // We can only do this xform if we know that bits from X that are set in C2
3258 // but not in C1 are already zero. Likewise for Y.
3259 const APInt &LHSMask =
3260 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3261 const APInt &RHSMask =
3262 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3264 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3265 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3266 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3267 N0.getOperand(0), N1.getOperand(0));
3268 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3269 DAG.getConstant(LHSMask | RHSMask, VT));
3273 // See if this is some rotate idiom.
3274 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3275 return SDValue(Rot, 0);
3277 // Simplify the operands using demanded-bits information.
3278 if (!VT.isVector() &&
3279 SimplifyDemandedBits(SDValue(N, 0)))
3280 return SDValue(N, 0);
3285 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3286 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3287 if (Op.getOpcode() == ISD::AND) {
3288 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3289 Mask = Op.getOperand(1);
3290 Op = Op.getOperand(0);
3296 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3304 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3305 // idioms for rotate, and if the target supports rotation instructions, generate
3307 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3308 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3309 EVT VT = LHS.getValueType();
3310 if (!TLI.isTypeLegal(VT)) return 0;
3312 // The target must have at least one rotate flavor.
3313 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3314 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3315 if (!HasROTL && !HasROTR) return 0;
3317 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3318 SDValue LHSShift; // The shift.
3319 SDValue LHSMask; // AND value if any.
3320 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3321 return 0; // Not part of a rotate.
3323 SDValue RHSShift; // The shift.
3324 SDValue RHSMask; // AND value if any.
3325 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3326 return 0; // Not part of a rotate.
3328 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3329 return 0; // Not shifting the same value.
3331 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3332 return 0; // Shifts must disagree.
3334 // Canonicalize shl to left side in a shl/srl pair.
3335 if (RHSShift.getOpcode() == ISD::SHL) {
3336 std::swap(LHS, RHS);
3337 std::swap(LHSShift, RHSShift);
3338 std::swap(LHSMask , RHSMask );
3341 unsigned OpSizeInBits = VT.getSizeInBits();
3342 SDValue LHSShiftArg = LHSShift.getOperand(0);
3343 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3344 SDValue RHSShiftArg = RHSShift.getOperand(0);
3345 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3347 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3348 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3349 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3350 RHSShiftAmt.getOpcode() == ISD::Constant) {
3351 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3352 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3353 if ((LShVal + RShVal) != OpSizeInBits)
3356 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3357 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3359 // If there is an AND of either shifted operand, apply it to the result.
3360 if (LHSMask.getNode() || RHSMask.getNode()) {
3361 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3363 if (LHSMask.getNode()) {
3364 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3365 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3367 if (RHSMask.getNode()) {
3368 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3369 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3372 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3375 return Rot.getNode();
3378 // If there is a mask here, and we have a variable shift, we can't be sure
3379 // that we're masking out the right stuff.
3380 if (LHSMask.getNode() || RHSMask.getNode())
3383 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
3384 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
3385 if (RHSShiftAmt.getOpcode() == ISD::SUB &&
3386 LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
3387 if (ConstantSDNode *SUBC =
3388 dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
3389 if (SUBC->getAPIntValue() == OpSizeInBits)
3390 return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, LHSShiftArg,
3391 HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
3395 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
3396 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
3397 if (LHSShiftAmt.getOpcode() == ISD::SUB &&
3398 RHSShiftAmt == LHSShiftAmt.getOperand(1))
3399 if (ConstantSDNode *SUBC =
3400 dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0)))
3401 if (SUBC->getAPIntValue() == OpSizeInBits)
3402 return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT, LHSShiftArg,
3403 HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
3405 // Look for sign/zext/any-extended or truncate cases:
3406 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3407 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3408 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3409 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3410 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3411 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3412 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3413 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3414 SDValue LExtOp0 = LHSShiftAmt.getOperand(0);
3415 SDValue RExtOp0 = RHSShiftAmt.getOperand(0);
3416 if (RExtOp0.getOpcode() == ISD::SUB &&
3417 RExtOp0.getOperand(1) == LExtOp0) {
3418 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3420 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3421 // (rotr x, (sub 32, y))
3422 if (ConstantSDNode *SUBC =
3423 dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
3424 if (SUBC->getAPIntValue() == OpSizeInBits) {
3425 return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3427 HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
3428 } else if (LHSShiftArg.getOpcode() == ISD::ZERO_EXTEND ||
3429 LHSShiftArg.getOpcode() == ISD::ANY_EXTEND) {
3430 // fold (or (shl (*ext x), (*ext y)),
3431 // (srl (*ext x), (*ext (sub 32, y)))) ->
3432 // (*ext (rotl x, y))
3433 // fold (or (shl (*ext x), (*ext y)),
3434 // (srl (*ext x), (*ext (sub 32, y)))) ->
3435 // (*ext (rotr x, (sub 32, y)))
3436 SDValue LArgExtOp0 = LHSShiftArg.getOperand(0);
3437 EVT LArgVT = LArgExtOp0.getValueType();
3438 if (LArgVT.getSizeInBits() == SUBC->getAPIntValue()) {
3439 SDValue V = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, LArgVT,
3441 HasROTL ? LHSShiftAmt : RHSShiftAmt);
3442 return DAG.getNode(LHSShiftArg.getOpcode(), DL, VT, V).getNode();
3446 } else if (LExtOp0.getOpcode() == ISD::SUB &&
3447 RExtOp0 == LExtOp0.getOperand(1)) {
3448 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3450 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3451 // (rotl x, (sub 32, y))
3452 if (ConstantSDNode *SUBC =
3453 dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
3454 if (SUBC->getAPIntValue() == OpSizeInBits) {
3455 return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT,
3457 HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
3458 } else if (RHSShiftArg.getOpcode() == ISD::ZERO_EXTEND ||
3459 RHSShiftArg.getOpcode() == ISD::ANY_EXTEND) {
3460 // fold (or (shl (*ext x), (*ext (sub 32, y))),
3461 // (srl (*ext x), (*ext y))) ->
3462 // (*ext (rotl x, y))
3463 // fold (or (shl (*ext x), (*ext (sub 32, y))),
3464 // (srl (*ext x), (*ext y))) ->
3465 // (*ext (rotr x, (sub 32, y)))
3466 SDValue RArgExtOp0 = RHSShiftArg.getOperand(0);
3467 EVT RArgVT = RArgExtOp0.getValueType();
3468 if (RArgVT.getSizeInBits() == SUBC->getAPIntValue()) {
3469 SDValue V = DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, RArgVT,
3471 HasROTR ? RHSShiftAmt : LHSShiftAmt);
3472 return DAG.getNode(RHSShiftArg.getOpcode(), DL, VT, V).getNode();
3482 SDValue DAGCombiner::visitXOR(SDNode *N) {
3483 SDValue N0 = N->getOperand(0);
3484 SDValue N1 = N->getOperand(1);
3485 SDValue LHS, RHS, CC;
3486 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3487 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3488 EVT VT = N0.getValueType();
3491 if (VT.isVector()) {
3492 SDValue FoldedVOp = SimplifyVBinOp(N);
3493 if (FoldedVOp.getNode()) return FoldedVOp;
3495 // fold (xor x, 0) -> x, vector edition
3496 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3498 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3502 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3503 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3504 return DAG.getConstant(0, VT);
3505 // fold (xor x, undef) -> undef
3506 if (N0.getOpcode() == ISD::UNDEF)
3508 if (N1.getOpcode() == ISD::UNDEF)
3510 // fold (xor c1, c2) -> c1^c2
3512 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3513 // canonicalize constant to RHS
3515 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3516 // fold (xor x, 0) -> x
3517 if (N1C && N1C->isNullValue())
3520 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3521 if (RXOR.getNode() != 0)
3524 // fold !(x cc y) -> (x !cc y)
3525 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3526 bool isInt = LHS.getValueType().isInteger();
3527 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3530 if (!LegalOperations ||
3531 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3532 switch (N0.getOpcode()) {
3534 llvm_unreachable("Unhandled SetCC Equivalent!");
3536 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3537 case ISD::SELECT_CC:
3538 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3539 N0.getOperand(3), NotCC);
3544 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3545 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3546 N0.getNode()->hasOneUse() &&
3547 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3548 SDValue V = N0.getOperand(0);
3549 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3550 DAG.getConstant(1, V.getValueType()));
3551 AddToWorkList(V.getNode());
3552 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3555 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3556 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3557 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3558 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3559 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3560 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3561 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3562 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3563 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3564 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3567 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3568 if (N1C && N1C->isAllOnesValue() &&
3569 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3570 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3571 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3572 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3573 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3574 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3575 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3576 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3579 // fold (xor (and x, y), y) -> (and (not x), y)
3580 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3581 N0->getOperand(1) == N1) {
3582 SDValue X = N0->getOperand(0);
3583 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3584 AddToWorkList(NotX.getNode());
3585 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3587 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3588 if (N1C && N0.getOpcode() == ISD::XOR) {
3589 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3590 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3592 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3593 DAG.getConstant(N1C->getAPIntValue() ^
3594 N00C->getAPIntValue(), VT));
3596 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3597 DAG.getConstant(N1C->getAPIntValue() ^
3598 N01C->getAPIntValue(), VT));
3600 // fold (xor x, x) -> 0
3602 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3604 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3605 if (N0.getOpcode() == N1.getOpcode()) {
3606 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3607 if (Tmp.getNode()) return Tmp;
3610 // Simplify the expression using non-local knowledge.
3611 if (!VT.isVector() &&
3612 SimplifyDemandedBits(SDValue(N, 0)))
3613 return SDValue(N, 0);
3618 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3619 /// the shift amount is a constant.
3620 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
3621 SDNode *LHS = N->getOperand(0).getNode();
3622 if (!LHS->hasOneUse()) return SDValue();
3624 // We want to pull some binops through shifts, so that we have (and (shift))
3625 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3626 // thing happens with address calculations, so it's important to canonicalize
3628 bool HighBitSet = false; // Can we transform this if the high bit is set?
3630 switch (LHS->getOpcode()) {
3631 default: return SDValue();
3634 HighBitSet = false; // We can only transform sra if the high bit is clear.
3637 HighBitSet = true; // We can only transform sra if the high bit is set.
3640 if (N->getOpcode() != ISD::SHL)
3641 return SDValue(); // only shl(add) not sr[al](add).
3642 HighBitSet = false; // We can only transform sra if the high bit is clear.
3646 // We require the RHS of the binop to be a constant as well.
3647 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3648 if (!BinOpCst) return SDValue();
3650 // FIXME: disable this unless the input to the binop is a shift by a constant.
3651 // If it is not a shift, it pessimizes some common cases like:
3653 // void foo(int *X, int i) { X[i & 1235] = 1; }
3654 // int bar(int *X, int i) { return X[i & 255]; }
3655 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3656 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3657 BinOpLHSVal->getOpcode() != ISD::SRA &&
3658 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3659 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3662 EVT VT = N->getValueType(0);
3664 // If this is a signed shift right, and the high bit is modified by the
3665 // logical operation, do not perform the transformation. The highBitSet
3666 // boolean indicates the value of the high bit of the constant which would
3667 // cause it to be modified for this operation.
3668 if (N->getOpcode() == ISD::SRA) {
3669 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3670 if (BinOpRHSSignSet != HighBitSet)
3674 // Fold the constants, shifting the binop RHS by the shift amount.
3675 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3677 LHS->getOperand(1), N->getOperand(1));
3679 // Create the new shift.
3680 SDValue NewShift = DAG.getNode(N->getOpcode(),
3681 SDLoc(LHS->getOperand(0)),
3682 VT, LHS->getOperand(0), N->getOperand(1));
3684 // Create the new binop.
3685 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3688 SDValue DAGCombiner::visitSHL(SDNode *N) {
3689 SDValue N0 = N->getOperand(0);
3690 SDValue N1 = N->getOperand(1);
3691 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3692 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3693 EVT VT = N0.getValueType();
3694 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3696 // fold (shl c1, c2) -> c1<<c2
3698 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3699 // fold (shl 0, x) -> 0
3700 if (N0C && N0C->isNullValue())
3702 // fold (shl x, c >= size(x)) -> undef
3703 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3704 return DAG.getUNDEF(VT);
3705 // fold (shl x, 0) -> x
3706 if (N1C && N1C->isNullValue())
3708 // fold (shl undef, x) -> 0
3709 if (N0.getOpcode() == ISD::UNDEF)
3710 return DAG.getConstant(0, VT);
3711 // if (shl x, c) is known to be zero, return 0
3712 if (DAG.MaskedValueIsZero(SDValue(N, 0),
3713 APInt::getAllOnesValue(OpSizeInBits)))
3714 return DAG.getConstant(0, VT);
3715 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3716 if (N1.getOpcode() == ISD::TRUNCATE &&
3717 N1.getOperand(0).getOpcode() == ISD::AND &&
3718 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3719 SDValue N101 = N1.getOperand(0).getOperand(1);
3720 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3721 EVT TruncVT = N1.getValueType();
3722 SDValue N100 = N1.getOperand(0).getOperand(0);
3723 APInt TruncC = N101C->getAPIntValue();
3724 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3725 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
3726 DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3727 DAG.getNode(ISD::TRUNCATE,
3730 DAG.getConstant(TruncC, TruncVT)));
3734 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3735 return SDValue(N, 0);
3737 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3738 if (N1C && N0.getOpcode() == ISD::SHL &&
3739 N0.getOperand(1).getOpcode() == ISD::Constant) {
3740 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3741 uint64_t c2 = N1C->getZExtValue();
3742 if (c1 + c2 >= OpSizeInBits)
3743 return DAG.getConstant(0, VT);
3744 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3745 DAG.getConstant(c1 + c2, N1.getValueType()));
3748 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3749 // For this to be valid, the second form must not preserve any of the bits
3750 // that are shifted out by the inner shift in the first form. This means
3751 // the outer shift size must be >= the number of bits added by the ext.
3752 // As a corollary, we don't care what kind of ext it is.
3753 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3754 N0.getOpcode() == ISD::ANY_EXTEND ||
3755 N0.getOpcode() == ISD::SIGN_EXTEND) &&
3756 N0.getOperand(0).getOpcode() == ISD::SHL &&
3757 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3759 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3760 uint64_t c2 = N1C->getZExtValue();
3761 EVT InnerShiftVT = N0.getOperand(0).getValueType();
3762 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3763 if (c2 >= OpSizeInBits - InnerShiftSize) {
3764 if (c1 + c2 >= OpSizeInBits)
3765 return DAG.getConstant(0, VT);
3766 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
3767 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
3768 N0.getOperand(0)->getOperand(0)),
3769 DAG.getConstant(c1 + c2, N1.getValueType()));
3773 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
3774 // (and (srl x, (sub c1, c2), MASK)
3775 // Only fold this if the inner shift has no other uses -- if it does, folding
3776 // this will increase the total number of instructions.
3777 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
3778 N0.getOperand(1).getOpcode() == ISD::Constant) {
3779 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3780 if (c1 < VT.getSizeInBits()) {
3781 uint64_t c2 = N1C->getZExtValue();
3782 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3783 VT.getSizeInBits() - c1);
3786 Mask = Mask.shl(c2-c1);
3787 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3788 DAG.getConstant(c2-c1, N1.getValueType()));
3790 Mask = Mask.lshr(c1-c2);
3791 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
3792 DAG.getConstant(c1-c2, N1.getValueType()));
3794 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
3795 DAG.getConstant(Mask, VT));
3798 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
3799 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3800 SDValue HiBitsMask =
3801 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3802 VT.getSizeInBits() -
3803 N1C->getZExtValue()),
3805 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
3810 SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3811 if (NewSHL.getNode())
3818 SDValue DAGCombiner::visitSRA(SDNode *N) {
3819 SDValue N0 = N->getOperand(0);
3820 SDValue N1 = N->getOperand(1);
3821 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3822 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3823 EVT VT = N0.getValueType();
3824 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3826 // fold (sra c1, c2) -> (sra c1, c2)
3828 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
3829 // fold (sra 0, x) -> 0
3830 if (N0C && N0C->isNullValue())
3832 // fold (sra -1, x) -> -1
3833 if (N0C && N0C->isAllOnesValue())
3835 // fold (sra x, (setge c, size(x))) -> undef
3836 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3837 return DAG.getUNDEF(VT);
3838 // fold (sra x, 0) -> x
3839 if (N1C && N1C->isNullValue())
3841 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3843 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
3844 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
3845 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
3847 ExtVT = EVT::getVectorVT(*DAG.getContext(),
3848 ExtVT, VT.getVectorNumElements());
3849 if ((!LegalOperations ||
3850 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
3851 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
3852 N0.getOperand(0), DAG.getValueType(ExtVT));
3855 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
3856 if (N1C && N0.getOpcode() == ISD::SRA) {
3857 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3858 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
3859 if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
3860 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
3861 DAG.getConstant(Sum, N1C->getValueType(0)));
3865 // fold (sra (shl X, m), (sub result_size, n))
3866 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
3867 // result_size - n != m.
3868 // If truncate is free for the target sext(shl) is likely to result in better
3870 if (N0.getOpcode() == ISD::SHL) {
3871 // Get the two constanst of the shifts, CN0 = m, CN = n.
3872 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3874 // Determine what the truncate's result bitsize and type would be.
3876 EVT::getIntegerVT(*DAG.getContext(),
3877 OpSizeInBits - N1C->getZExtValue());
3878 // Determine the residual right-shift amount.
3879 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
3881 // If the shift is not a no-op (in which case this should be just a sign
3882 // extend already), the truncated to type is legal, sign_extend is legal
3883 // on that type, and the truncate to that type is both legal and free,
3884 // perform the transform.
3885 if ((ShiftAmt > 0) &&
3886 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
3887 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
3888 TLI.isTruncateFree(VT, TruncVT)) {
3890 SDValue Amt = DAG.getConstant(ShiftAmt,
3891 getShiftAmountTy(N0.getOperand(0).getValueType()));
3892 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
3893 N0.getOperand(0), Amt);
3894 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
3896 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
3897 N->getValueType(0), Trunc);
3902 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
3903 if (N1.getOpcode() == ISD::TRUNCATE &&
3904 N1.getOperand(0).getOpcode() == ISD::AND &&
3905 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3906 SDValue N101 = N1.getOperand(0).getOperand(1);
3907 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3908 EVT TruncVT = N1.getValueType();
3909 SDValue N100 = N1.getOperand(0).getOperand(0);
3910 APInt TruncC = N101C->getAPIntValue();
3911 TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
3912 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
3913 DAG.getNode(ISD::AND, SDLoc(N),
3915 DAG.getNode(ISD::TRUNCATE,
3918 DAG.getConstant(TruncC, TruncVT)));
3922 // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
3923 // if c1 is equal to the number of bits the trunc removes
3924 if (N0.getOpcode() == ISD::TRUNCATE &&
3925 (N0.getOperand(0).getOpcode() == ISD::SRL ||
3926 N0.getOperand(0).getOpcode() == ISD::SRA) &&
3927 N0.getOperand(0).hasOneUse() &&
3928 N0.getOperand(0).getOperand(1).hasOneUse() &&
3929 N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
3930 EVT LargeVT = N0.getOperand(0).getValueType();
3931 ConstantSDNode *LargeShiftAmt =
3932 cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
3934 if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
3935 LargeShiftAmt->getZExtValue()) {
3937 DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
3938 getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
3939 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
3940 N0.getOperand(0).getOperand(0), Amt);
3941 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
3945 // Simplify, based on bits shifted out of the LHS.
3946 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3947 return SDValue(N, 0);
3950 // If the sign bit is known to be zero, switch this to a SRL.
3951 if (DAG.SignBitIsZero(N0))
3952 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
3955 SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
3956 if (NewSRA.getNode())
3963 SDValue DAGCombiner::visitSRL(SDNode *N) {
3964 SDValue N0 = N->getOperand(0);
3965 SDValue N1 = N->getOperand(1);
3966 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3967 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3968 EVT VT = N0.getValueType();
3969 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3971 // fold (srl c1, c2) -> c1 >>u c2
3973 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
3974 // fold (srl 0, x) -> 0
3975 if (N0C && N0C->isNullValue())
3977 // fold (srl x, c >= size(x)) -> undef
3978 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3979 return DAG.getUNDEF(VT);
3980 // fold (srl x, 0) -> x
3981 if (N1C && N1C->isNullValue())
3983 // if (srl x, c) is known to be zero, return 0
3984 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3985 APInt::getAllOnesValue(OpSizeInBits)))
3986 return DAG.getConstant(0, VT);
3988 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
3989 if (N1C && N0.getOpcode() == ISD::SRL &&
3990 N0.getOperand(1).getOpcode() == ISD::Constant) {
3991 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3992 uint64_t c2 = N1C->getZExtValue();
3993 if (c1 + c2 >= OpSizeInBits)
3994 return DAG.getConstant(0, VT);
3995 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
3996 DAG.getConstant(c1 + c2, N1.getValueType()));
3999 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4000 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4001 N0.getOperand(0).getOpcode() == ISD::SRL &&
4002 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4004 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4005 uint64_t c2 = N1C->getZExtValue();
4006 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4007 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4008 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4009 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4010 if (c1 + OpSizeInBits == InnerShiftSize) {
4011 if (c1 + c2 >= InnerShiftSize)
4012 return DAG.getConstant(0, VT);
4013 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4014 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4015 N0.getOperand(0)->getOperand(0),
4016 DAG.getConstant(c1 + c2, ShiftCountVT)));
4020 // fold (srl (shl x, c), c) -> (and x, cst2)
4021 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
4022 N0.getValueSizeInBits() <= 64) {
4023 uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
4024 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4025 DAG.getConstant(~0ULL >> ShAmt, VT));
4028 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4029 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4030 // Shifting in all undef bits?
4031 EVT SmallVT = N0.getOperand(0).getValueType();
4032 if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
4033 return DAG.getUNDEF(VT);
4035 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4036 uint64_t ShiftAmt = N1C->getZExtValue();
4037 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4039 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4040 AddToWorkList(SmallShift.getNode());
4041 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits()).lshr(ShiftAmt);
4042 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4043 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4044 DAG.getConstant(Mask, VT));
4048 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4049 // bit, which is unmodified by sra.
4050 if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
4051 if (N0.getOpcode() == ISD::SRA)
4052 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4055 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4056 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4057 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
4058 APInt KnownZero, KnownOne;
4059 DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
4061 // If any of the input bits are KnownOne, then the input couldn't be all
4062 // zeros, thus the result of the srl will always be zero.
4063 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4065 // If all of the bits input the to ctlz node are known to be zero, then
4066 // the result of the ctlz is "32" and the result of the shift is one.
4067 APInt UnknownBits = ~KnownZero;
4068 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4070 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4071 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4072 // Okay, we know that only that the single bit specified by UnknownBits
4073 // could be set on input to the CTLZ node. If this bit is set, the SRL
4074 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4075 // to an SRL/XOR pair, which is likely to simplify more.
4076 unsigned ShAmt = UnknownBits.countTrailingZeros();
4077 SDValue Op = N0.getOperand(0);
4080 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4081 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4082 AddToWorkList(Op.getNode());
4085 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4086 Op, DAG.getConstant(1, VT));
4090 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4091 if (N1.getOpcode() == ISD::TRUNCATE &&
4092 N1.getOperand(0).getOpcode() == ISD::AND &&
4093 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
4094 SDValue N101 = N1.getOperand(0).getOperand(1);
4095 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
4096 EVT TruncVT = N1.getValueType();
4097 SDValue N100 = N1.getOperand(0).getOperand(0);
4098 APInt TruncC = N101C->getAPIntValue();
4099 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
4100 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
4101 DAG.getNode(ISD::AND, SDLoc(N),
4103 DAG.getNode(ISD::TRUNCATE,
4106 DAG.getConstant(TruncC, TruncVT)));
4110 // fold operands of srl based on knowledge that the low bits are not
4112 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4113 return SDValue(N, 0);
4116 SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
4117 if (NewSRL.getNode())
4121 // Attempt to convert a srl of a load into a narrower zero-extending load.
4122 SDValue NarrowLoad = ReduceLoadWidth(N);
4123 if (NarrowLoad.getNode())
4126 // Here is a common situation. We want to optimize:
4129 // %b = and i32 %a, 2
4130 // %c = srl i32 %b, 1
4131 // brcond i32 %c ...
4137 // %c = setcc eq %b, 0
4140 // However when after the source operand of SRL is optimized into AND, the SRL
4141 // itself may not be optimized further. Look for it and add the BRCOND into
4143 if (N->hasOneUse()) {
4144 SDNode *Use = *N->use_begin();
4145 if (Use->getOpcode() == ISD::BRCOND)
4147 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4148 // Also look pass the truncate.
4149 Use = *Use->use_begin();
4150 if (Use->getOpcode() == ISD::BRCOND)
4158 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4159 SDValue N0 = N->getOperand(0);
4160 EVT VT = N->getValueType(0);
4162 // fold (ctlz c1) -> c2
4163 if (isa<ConstantSDNode>(N0))
4164 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4168 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4169 SDValue N0 = N->getOperand(0);
4170 EVT VT = N->getValueType(0);
4172 // fold (ctlz_zero_undef c1) -> c2
4173 if (isa<ConstantSDNode>(N0))
4174 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4178 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4179 SDValue N0 = N->getOperand(0);
4180 EVT VT = N->getValueType(0);
4182 // fold (cttz c1) -> c2
4183 if (isa<ConstantSDNode>(N0))
4184 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4188 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4189 SDValue N0 = N->getOperand(0);
4190 EVT VT = N->getValueType(0);
4192 // fold (cttz_zero_undef c1) -> c2
4193 if (isa<ConstantSDNode>(N0))
4194 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4198 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4199 SDValue N0 = N->getOperand(0);
4200 EVT VT = N->getValueType(0);
4202 // fold (ctpop c1) -> c2
4203 if (isa<ConstantSDNode>(N0))
4204 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4208 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4209 SDValue N0 = N->getOperand(0);
4210 SDValue N1 = N->getOperand(1);
4211 SDValue N2 = N->getOperand(2);
4212 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4213 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4214 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4215 EVT VT = N->getValueType(0);
4216 EVT VT0 = N0.getValueType();
4218 // fold (select C, X, X) -> X
4221 // fold (select true, X, Y) -> X
4222 if (N0C && !N0C->isNullValue())
4224 // fold (select false, X, Y) -> Y
4225 if (N0C && N0C->isNullValue())
4227 // fold (select C, 1, X) -> (or C, X)
4228 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4229 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4230 // fold (select C, 0, 1) -> (xor C, 1)
4231 if (VT.isInteger() &&
4234 TLI.getBooleanContents(false) ==
4235 TargetLowering::ZeroOrOneBooleanContent)) &&
4236 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4239 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4240 N0, DAG.getConstant(1, VT0));
4241 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4242 N0, DAG.getConstant(1, VT0));
4243 AddToWorkList(XORNode.getNode());
4245 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4246 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4248 // fold (select C, 0, X) -> (and (not C), X)
4249 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4250 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4251 AddToWorkList(NOTNode.getNode());
4252 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4254 // fold (select C, X, 1) -> (or (not C), X)
4255 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4256 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4257 AddToWorkList(NOTNode.getNode());
4258 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4260 // fold (select C, X, 0) -> (and C, X)
4261 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4262 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4263 // fold (select X, X, Y) -> (or X, Y)
4264 // fold (select X, 1, Y) -> (or X, Y)
4265 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4266 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4267 // fold (select X, Y, X) -> (and X, Y)
4268 // fold (select X, Y, 0) -> (and X, Y)
4269 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4270 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4272 // If we can fold this based on the true/false value, do so.
4273 if (SimplifySelectOps(N, N1, N2))
4274 return SDValue(N, 0); // Don't revisit N.
4276 // fold selects based on a setcc into other things, such as min/max/abs
4277 if (N0.getOpcode() == ISD::SETCC) {
4279 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4280 // having to say they don't support SELECT_CC on every type the DAG knows
4281 // about, since there is no way to mark an opcode illegal at all value types
4282 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4283 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4284 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4285 N0.getOperand(0), N0.getOperand(1),
4286 N1, N2, N0.getOperand(2));
4287 return SimplifySelect(SDLoc(N), N0, N1, N2);
4293 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4294 SDValue N0 = N->getOperand(0);
4295 SDValue N1 = N->getOperand(1);
4296 SDValue N2 = N->getOperand(2);
4299 // Canonicalize integer abs.
4300 // vselect (setg[te] X, 0), X, -X ->
4301 // vselect (setgt X, -1), X, -X ->
4302 // vselect (setl[te] X, 0), -X, X ->
4303 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4304 if (N0.getOpcode() == ISD::SETCC) {
4305 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4306 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4308 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4310 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4311 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4312 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4313 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4314 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4315 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4316 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4319 EVT VT = LHS.getValueType();
4320 SDValue Shift = DAG.getNode(
4321 ISD::SRA, DL, VT, LHS,
4322 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4323 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4324 AddToWorkList(Shift.getNode());
4325 AddToWorkList(Add.getNode());
4326 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4330 // Treat SETCC as a mask and promote the result type based on the targets
4331 // expected SETCC result type. This will ensure that SETCC and VSELECT are
4332 // both split by the type legalizer. This is done to prevent the type
4333 // legalizer from unrolling SETCC into scalar comparions.
4334 EVT SelectVT = N->getValueType(0);
4335 if (N0.getOpcode() == ISD::SETCC &&
4336 N0.getValueType() != getSetCCResultType(SelectVT)) {
4338 EVT MaskVT = getSetCCResultType(SelectVT);
4340 SDValue Mask = DAG.getNode(ISD::SETCC, MaskDL, MaskVT, N0->getOperand(0),
4341 N0->getOperand(1), N0->getOperand(2));
4343 AddToWorkList(Mask.getNode());
4345 SDValue LHS = N->getOperand(1);
4346 SDValue RHS = N->getOperand(2);
4348 return DAG.getNode(ISD::VSELECT, DL, SelectVT, Mask, LHS, RHS);
4354 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4355 SDValue N0 = N->getOperand(0);
4356 SDValue N1 = N->getOperand(1);
4357 SDValue N2 = N->getOperand(2);
4358 SDValue N3 = N->getOperand(3);
4359 SDValue N4 = N->getOperand(4);
4360 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4362 // fold select_cc lhs, rhs, x, x, cc -> x
4366 // Determine if the condition we're dealing with is constant
4367 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4368 N0, N1, CC, SDLoc(N), false);
4369 if (SCC.getNode()) {
4370 AddToWorkList(SCC.getNode());
4372 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4373 if (!SCCC->isNullValue())
4374 return N2; // cond always true -> true val
4376 return N3; // cond always false -> false val
4379 // Fold to a simpler select_cc
4380 if (SCC.getOpcode() == ISD::SETCC)
4381 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4382 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4386 // If we can fold this based on the true/false value, do so.
4387 if (SimplifySelectOps(N, N2, N3))
4388 return SDValue(N, 0); // Don't revisit N.
4390 // fold select_cc into other things, such as min/max/abs
4391 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4394 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4395 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4396 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4400 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4401 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4402 // transformation. Returns true if extension are possible and the above
4403 // mentioned transformation is profitable.
4404 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4406 SmallVectorImpl<SDNode *> &ExtendNodes,
4407 const TargetLowering &TLI) {
4408 bool HasCopyToRegUses = false;
4409 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4410 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4411 UE = N0.getNode()->use_end();
4416 if (UI.getUse().getResNo() != N0.getResNo())
4418 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4419 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4420 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4421 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4422 // Sign bits will be lost after a zext.
4425 for (unsigned i = 0; i != 2; ++i) {
4426 SDValue UseOp = User->getOperand(i);
4429 if (!isa<ConstantSDNode>(UseOp))
4434 ExtendNodes.push_back(User);
4437 // If truncates aren't free and there are users we can't
4438 // extend, it isn't worthwhile.
4441 // Remember if this value is live-out.
4442 if (User->getOpcode() == ISD::CopyToReg)
4443 HasCopyToRegUses = true;
4446 if (HasCopyToRegUses) {
4447 bool BothLiveOut = false;
4448 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4450 SDUse &Use = UI.getUse();
4451 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4457 // Both unextended and extended values are live out. There had better be
4458 // a good reason for the transformation.
4459 return ExtendNodes.size();
4464 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4465 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4466 ISD::NodeType ExtType) {
4467 // Extend SetCC uses if necessary.
4468 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4469 SDNode *SetCC = SetCCs[i];
4470 SmallVector<SDValue, 4> Ops;
4472 for (unsigned j = 0; j != 2; ++j) {
4473 SDValue SOp = SetCC->getOperand(j);
4475 Ops.push_back(ExtLoad);
4477 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4480 Ops.push_back(SetCC->getOperand(2));
4481 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4482 &Ops[0], Ops.size()));
4486 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4487 SDValue N0 = N->getOperand(0);
4488 EVT VT = N->getValueType(0);
4490 // fold (sext c1) -> c1
4491 if (isa<ConstantSDNode>(N0))
4492 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N0);
4494 // fold (sext (sext x)) -> (sext x)
4495 // fold (sext (aext x)) -> (sext x)
4496 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4497 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4500 if (N0.getOpcode() == ISD::TRUNCATE) {
4501 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4502 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4503 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4504 if (NarrowLoad.getNode()) {
4505 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4506 if (NarrowLoad.getNode() != N0.getNode()) {
4507 CombineTo(N0.getNode(), NarrowLoad);
4508 // CombineTo deleted the truncate, if needed, but not what's under it.
4511 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4514 // See if the value being truncated is already sign extended. If so, just
4515 // eliminate the trunc/sext pair.
4516 SDValue Op = N0.getOperand(0);
4517 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4518 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4519 unsigned DestBits = VT.getScalarType().getSizeInBits();
4520 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4522 if (OpBits == DestBits) {
4523 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4524 // bits, it is already ready.
4525 if (NumSignBits > DestBits-MidBits)
4527 } else if (OpBits < DestBits) {
4528 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4529 // bits, just sext from i32.
4530 if (NumSignBits > OpBits-MidBits)
4531 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4533 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4534 // bits, just truncate to i32.
4535 if (NumSignBits > OpBits-MidBits)
4536 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4539 // fold (sext (truncate x)) -> (sextinreg x).
4540 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4541 N0.getValueType())) {
4542 if (OpBits < DestBits)
4543 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4544 else if (OpBits > DestBits)
4545 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4546 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4547 DAG.getValueType(N0.getValueType()));
4551 // fold (sext (load x)) -> (sext (truncate (sextload x)))
4552 // None of the supported targets knows how to perform load and sign extend
4553 // on vectors in one instruction. We only perform this transformation on
4555 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4556 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4557 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4558 bool DoXform = true;
4559 SmallVector<SDNode*, 4> SetCCs;
4560 if (!N0.hasOneUse())
4561 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4563 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4564 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4566 LN0->getBasePtr(), LN0->getPointerInfo(),
4568 LN0->isVolatile(), LN0->isNonTemporal(),
4569 LN0->getAlignment());
4570 CombineTo(N, ExtLoad);
4571 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4572 N0.getValueType(), ExtLoad);
4573 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4574 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4576 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4580 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4581 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4582 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4583 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4584 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4585 EVT MemVT = LN0->getMemoryVT();
4586 if ((!LegalOperations && !LN0->isVolatile()) ||
4587 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4588 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4590 LN0->getBasePtr(), LN0->getPointerInfo(),
4592 LN0->isVolatile(), LN0->isNonTemporal(),
4593 LN0->getAlignment());
4594 CombineTo(N, ExtLoad);
4595 CombineTo(N0.getNode(),
4596 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4597 N0.getValueType(), ExtLoad),
4598 ExtLoad.getValue(1));
4599 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4603 // fold (sext (and/or/xor (load x), cst)) ->
4604 // (and/or/xor (sextload x), (sext cst))
4605 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4606 N0.getOpcode() == ISD::XOR) &&
4607 isa<LoadSDNode>(N0.getOperand(0)) &&
4608 N0.getOperand(1).getOpcode() == ISD::Constant &&
4609 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4610 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4611 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4612 if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4613 bool DoXform = true;
4614 SmallVector<SDNode*, 4> SetCCs;
4615 if (!N0.hasOneUse())
4616 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4619 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
4620 LN0->getChain(), LN0->getBasePtr(),
4621 LN0->getPointerInfo(),
4624 LN0->isNonTemporal(),
4625 LN0->getAlignment());
4626 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4627 Mask = Mask.sext(VT.getSizeInBits());
4628 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4629 ExtLoad, DAG.getConstant(Mask, VT));
4630 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4631 SDLoc(N0.getOperand(0)),
4632 N0.getOperand(0).getValueType(), ExtLoad);
4634 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4635 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4637 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4642 if (N0.getOpcode() == ISD::SETCC) {
4643 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
4644 // Only do this before legalize for now.
4645 if (VT.isVector() && !LegalOperations &&
4646 TLI.getBooleanContents(true) ==
4647 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4648 EVT N0VT = N0.getOperand(0).getValueType();
4649 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
4650 // of the same size as the compared operands. Only optimize sext(setcc())
4651 // if this is the case.
4652 EVT SVT = getSetCCResultType(N0VT);
4654 // We know that the # elements of the results is the same as the
4655 // # elements of the compare (and the # elements of the compare result
4656 // for that matter). Check to see that they are the same size. If so,
4657 // we know that the element size of the sext'd result matches the
4658 // element size of the compare operands.
4659 if (VT.getSizeInBits() == SVT.getSizeInBits())
4660 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4662 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4664 // If the desired elements are smaller or larger than the source
4665 // elements we can use a matching integer vector type and then
4666 // truncate/sign extend
4667 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
4668 if (SVT == MatchingVectorType) {
4669 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
4670 N0.getOperand(0), N0.getOperand(1),
4671 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4672 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
4676 // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
4677 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
4679 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
4681 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
4682 NegOne, DAG.getConstant(0, VT),
4683 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4684 if (SCC.getNode()) return SCC;
4685 if (!VT.isVector() &&
4686 (!LegalOperations ||
4687 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(VT)))) {
4688 return DAG.getSelect(SDLoc(N), VT,
4689 DAG.getSetCC(SDLoc(N),
4690 getSetCCResultType(VT),
4691 N0.getOperand(0), N0.getOperand(1),
4692 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4693 NegOne, DAG.getConstant(0, VT));
4697 // fold (sext x) -> (zext x) if the sign bit is known zero.
4698 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
4699 DAG.SignBitIsZero(N0))
4700 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4705 // isTruncateOf - If N is a truncate of some other value, return true, record
4706 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
4707 // This function computes KnownZero to avoid a duplicated call to
4708 // ComputeMaskedBits in the caller.
4709 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
4712 if (N->getOpcode() == ISD::TRUNCATE) {
4713 Op = N->getOperand(0);
4714 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4718 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
4719 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
4722 SDValue Op0 = N->getOperand(0);
4723 SDValue Op1 = N->getOperand(1);
4724 assert(Op0.getValueType() == Op1.getValueType());
4726 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
4727 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
4728 if (COp0 && COp0->isNullValue())
4730 else if (COp1 && COp1->isNullValue())
4735 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4737 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
4743 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
4744 SDValue N0 = N->getOperand(0);
4745 EVT VT = N->getValueType(0);
4747 // fold (zext c1) -> c1
4748 if (isa<ConstantSDNode>(N0))
4749 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4750 // fold (zext (zext x)) -> (zext x)
4751 // fold (zext (aext x)) -> (zext x)
4752 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4753 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
4756 // fold (zext (truncate x)) -> (zext x) or
4757 // (zext (truncate x)) -> (truncate x)
4758 // This is valid when the truncated bits of x are already zero.
4759 // FIXME: We should extend this to work for vectors too.
4762 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
4763 APInt TruncatedBits =
4764 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
4765 APInt(Op.getValueSizeInBits(), 0) :
4766 APInt::getBitsSet(Op.getValueSizeInBits(),
4767 N0.getValueSizeInBits(),
4768 std::min(Op.getValueSizeInBits(),
4769 VT.getSizeInBits()));
4770 if (TruncatedBits == (KnownZero & TruncatedBits)) {
4771 if (VT.bitsGT(Op.getValueType()))
4772 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
4773 if (VT.bitsLT(Op.getValueType()))
4774 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4780 // fold (zext (truncate (load x))) -> (zext (smaller load x))
4781 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
4782 if (N0.getOpcode() == ISD::TRUNCATE) {
4783 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4784 if (NarrowLoad.getNode()) {
4785 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4786 if (NarrowLoad.getNode() != N0.getNode()) {
4787 CombineTo(N0.getNode(), NarrowLoad);
4788 // CombineTo deleted the truncate, if needed, but not what's under it.
4791 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4795 // fold (zext (truncate x)) -> (and x, mask)
4796 if (N0.getOpcode() == ISD::TRUNCATE &&
4797 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
4799 // fold (zext (truncate (load x))) -> (zext (smaller load x))
4800 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
4801 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4802 if (NarrowLoad.getNode()) {
4803 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4804 if (NarrowLoad.getNode() != N0.getNode()) {
4805 CombineTo(N0.getNode(), NarrowLoad);
4806 // CombineTo deleted the truncate, if needed, but not what's under it.
4809 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4812 SDValue Op = N0.getOperand(0);
4813 if (Op.getValueType().bitsLT(VT)) {
4814 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
4815 AddToWorkList(Op.getNode());
4816 } else if (Op.getValueType().bitsGT(VT)) {
4817 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4818 AddToWorkList(Op.getNode());
4820 return DAG.getZeroExtendInReg(Op, SDLoc(N),
4821 N0.getValueType().getScalarType());
4824 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
4825 // if either of the casts is not free.
4826 if (N0.getOpcode() == ISD::AND &&
4827 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4828 N0.getOperand(1).getOpcode() == ISD::Constant &&
4829 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4830 N0.getValueType()) ||
4831 !TLI.isZExtFree(N0.getValueType(), VT))) {
4832 SDValue X = N0.getOperand(0).getOperand(0);
4833 if (X.getValueType().bitsLT(VT)) {
4834 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
4835 } else if (X.getValueType().bitsGT(VT)) {
4836 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
4838 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4839 Mask = Mask.zext(VT.getSizeInBits());
4840 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4841 X, DAG.getConstant(Mask, VT));
4844 // fold (zext (load x)) -> (zext (truncate (zextload x)))
4845 // None of the supported targets knows how to perform load and vector_zext
4846 // on vectors in one instruction. We only perform this transformation on
4848 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4849 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4850 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
4851 bool DoXform = true;
4852 SmallVector<SDNode*, 4> SetCCs;
4853 if (!N0.hasOneUse())
4854 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
4856 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4857 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
4859 LN0->getBasePtr(), LN0->getPointerInfo(),
4861 LN0->isVolatile(), LN0->isNonTemporal(),
4862 LN0->getAlignment());
4863 CombineTo(N, ExtLoad);
4864 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4865 N0.getValueType(), ExtLoad);
4866 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4868 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4870 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4874 // fold (zext (and/or/xor (load x), cst)) ->
4875 // (and/or/xor (zextload x), (zext cst))
4876 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4877 N0.getOpcode() == ISD::XOR) &&
4878 isa<LoadSDNode>(N0.getOperand(0)) &&
4879 N0.getOperand(1).getOpcode() == ISD::Constant &&
4880 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
4881 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4882 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4883 if (LN0->getExtensionType() != ISD::SEXTLOAD) {
4884 bool DoXform = true;
4885 SmallVector<SDNode*, 4> SetCCs;
4886 if (!N0.hasOneUse())
4887 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
4890 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
4891 LN0->getChain(), LN0->getBasePtr(),
4892 LN0->getPointerInfo(),
4895 LN0->isNonTemporal(),
4896 LN0->getAlignment());
4897 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4898 Mask = Mask.zext(VT.getSizeInBits());
4899 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4900 ExtLoad, DAG.getConstant(Mask, VT));
4901 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4902 SDLoc(N0.getOperand(0)),
4903 N0.getOperand(0).getValueType(), ExtLoad);
4905 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4906 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4908 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4913 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
4914 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
4915 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4916 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4917 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4918 EVT MemVT = LN0->getMemoryVT();
4919 if ((!LegalOperations && !LN0->isVolatile()) ||
4920 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
4921 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
4923 LN0->getBasePtr(), LN0->getPointerInfo(),
4925 LN0->isVolatile(), LN0->isNonTemporal(),
4926 LN0->getAlignment());
4927 CombineTo(N, ExtLoad);
4928 CombineTo(N0.getNode(),
4929 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
4931 ExtLoad.getValue(1));
4932 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4936 if (N0.getOpcode() == ISD::SETCC) {
4937 if (!LegalOperations && VT.isVector()) {
4938 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
4939 // Only do this before legalize for now.
4940 EVT N0VT = N0.getOperand(0).getValueType();
4941 EVT EltVT = VT.getVectorElementType();
4942 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
4943 DAG.getConstant(1, EltVT));
4944 if (VT.getSizeInBits() == N0VT.getSizeInBits())
4945 // We know that the # elements of the results is the same as the
4946 // # elements of the compare (and the # elements of the compare result
4947 // for that matter). Check to see that they are the same size. If so,
4948 // we know that the element size of the sext'd result matches the
4949 // element size of the compare operands.
4950 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4951 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4953 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4954 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
4955 &OneOps[0], OneOps.size()));
4957 // If the desired elements are smaller or larger than the source
4958 // elements we can use a matching integer vector type and then
4959 // truncate/sign extend
4960 EVT MatchingElementType =
4961 EVT::getIntegerVT(*DAG.getContext(),
4962 N0VT.getScalarType().getSizeInBits());
4963 EVT MatchingVectorType =
4964 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4965 N0VT.getVectorNumElements());
4967 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
4969 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4970 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4971 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
4972 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
4973 &OneOps[0], OneOps.size()));
4976 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4978 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
4979 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4980 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4981 if (SCC.getNode()) return SCC;
4984 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
4985 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
4986 isa<ConstantSDNode>(N0.getOperand(1)) &&
4987 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
4989 SDValue ShAmt = N0.getOperand(1);
4990 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
4991 if (N0.getOpcode() == ISD::SHL) {
4992 SDValue InnerZExt = N0.getOperand(0);
4993 // If the original shl may be shifting out bits, do not perform this
4995 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
4996 InnerZExt.getOperand(0).getValueType().getSizeInBits();
4997 if (ShAmtVal > KnownZeroBits)
5003 // Ensure that the shift amount is wide enough for the shifted value.
5004 if (VT.getSizeInBits() >= 256)
5005 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5007 return DAG.getNode(N0.getOpcode(), DL, VT,
5008 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5015 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5016 SDValue N0 = N->getOperand(0);
5017 EVT VT = N->getValueType(0);
5019 // fold (aext c1) -> c1
5020 if (isa<ConstantSDNode>(N0))
5021 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, N0);
5022 // fold (aext (aext x)) -> (aext x)
5023 // fold (aext (zext x)) -> (zext x)
5024 // fold (aext (sext x)) -> (sext x)
5025 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5026 N0.getOpcode() == ISD::ZERO_EXTEND ||
5027 N0.getOpcode() == ISD::SIGN_EXTEND)
5028 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5030 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5031 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5032 if (N0.getOpcode() == ISD::TRUNCATE) {
5033 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5034 if (NarrowLoad.getNode()) {
5035 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5036 if (NarrowLoad.getNode() != N0.getNode()) {
5037 CombineTo(N0.getNode(), NarrowLoad);
5038 // CombineTo deleted the truncate, if needed, but not what's under it.
5041 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5045 // fold (aext (truncate x))
5046 if (N0.getOpcode() == ISD::TRUNCATE) {
5047 SDValue TruncOp = N0.getOperand(0);
5048 if (TruncOp.getValueType() == VT)
5049 return TruncOp; // x iff x size == zext size.
5050 if (TruncOp.getValueType().bitsGT(VT))
5051 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5052 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5055 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5056 // if the trunc is not free.
5057 if (N0.getOpcode() == ISD::AND &&
5058 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5059 N0.getOperand(1).getOpcode() == ISD::Constant &&
5060 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5061 N0.getValueType())) {
5062 SDValue X = N0.getOperand(0).getOperand(0);
5063 if (X.getValueType().bitsLT(VT)) {
5064 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5065 } else if (X.getValueType().bitsGT(VT)) {
5066 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5068 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5069 Mask = Mask.zext(VT.getSizeInBits());
5070 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5071 X, DAG.getConstant(Mask, VT));
5074 // fold (aext (load x)) -> (aext (truncate (extload x)))
5075 // None of the supported targets knows how to perform load and any_ext
5076 // on vectors in one instruction. We only perform this transformation on
5078 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5079 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5080 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5081 bool DoXform = true;
5082 SmallVector<SDNode*, 4> SetCCs;
5083 if (!N0.hasOneUse())
5084 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5086 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5087 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5089 LN0->getBasePtr(), LN0->getPointerInfo(),
5091 LN0->isVolatile(), LN0->isNonTemporal(),
5092 LN0->getAlignment());
5093 CombineTo(N, ExtLoad);
5094 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5095 N0.getValueType(), ExtLoad);
5096 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5097 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5099 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5103 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5104 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5105 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5106 if (N0.getOpcode() == ISD::LOAD &&
5107 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5109 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5110 EVT MemVT = LN0->getMemoryVT();
5111 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N),
5112 VT, LN0->getChain(), LN0->getBasePtr(),
5113 LN0->getPointerInfo(), MemVT,
5114 LN0->isVolatile(), LN0->isNonTemporal(),
5115 LN0->getAlignment());
5116 CombineTo(N, ExtLoad);
5117 CombineTo(N0.getNode(),
5118 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5119 N0.getValueType(), ExtLoad),
5120 ExtLoad.getValue(1));
5121 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5124 if (N0.getOpcode() == ISD::SETCC) {
5125 // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5126 // Only do this before legalize for now.
5127 if (VT.isVector() && !LegalOperations) {
5128 EVT N0VT = N0.getOperand(0).getValueType();
5129 // We know that the # elements of the results is the same as the
5130 // # elements of the compare (and the # elements of the compare result
5131 // for that matter). Check to see that they are the same size. If so,
5132 // we know that the element size of the sext'd result matches the
5133 // element size of the compare operands.
5134 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5135 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5137 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5138 // If the desired elements are smaller or larger than the source
5139 // elements we can use a matching integer vector type and then
5140 // truncate/sign extend
5142 EVT MatchingElementType =
5143 EVT::getIntegerVT(*DAG.getContext(),
5144 N0VT.getScalarType().getSizeInBits());
5145 EVT MatchingVectorType =
5146 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5147 N0VT.getVectorNumElements());
5149 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5151 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5152 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5156 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5158 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5159 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5160 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5168 /// GetDemandedBits - See if the specified operand can be simplified with the
5169 /// knowledge that only the bits specified by Mask are used. If so, return the
5170 /// simpler operand, otherwise return a null SDValue.
5171 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5172 switch (V.getOpcode()) {
5174 case ISD::Constant: {
5175 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5176 assert(CV != 0 && "Const value should be ConstSDNode.");
5177 const APInt &CVal = CV->getAPIntValue();
5178 APInt NewVal = CVal & Mask;
5180 return DAG.getConstant(NewVal, V.getValueType());
5185 // If the LHS or RHS don't contribute bits to the or, drop them.
5186 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5187 return V.getOperand(1);
5188 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5189 return V.getOperand(0);
5192 // Only look at single-use SRLs.
5193 if (!V.getNode()->hasOneUse())
5195 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5196 // See if we can recursively simplify the LHS.
5197 unsigned Amt = RHSC->getZExtValue();
5199 // Watch out for shift count overflow though.
5200 if (Amt >= Mask.getBitWidth()) break;
5201 APInt NewMask = Mask << Amt;
5202 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5203 if (SimplifyLHS.getNode())
5204 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5205 SimplifyLHS, V.getOperand(1));
5211 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5212 /// bits and then truncated to a narrower type and where N is a multiple
5213 /// of number of bits of the narrower type, transform it to a narrower load
5214 /// from address + N / num of bits of new type. If the result is to be
5215 /// extended, also fold the extension to form a extending load.
5216 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5217 unsigned Opc = N->getOpcode();
5219 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5220 SDValue N0 = N->getOperand(0);
5221 EVT VT = N->getValueType(0);
5224 // This transformation isn't valid for vector loads.
5228 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5230 if (Opc == ISD::SIGN_EXTEND_INREG) {
5231 ExtType = ISD::SEXTLOAD;
5232 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5233 } else if (Opc == ISD::SRL) {
5234 // Another special-case: SRL is basically zero-extending a narrower value.
5235 ExtType = ISD::ZEXTLOAD;
5237 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5238 if (!N01) return SDValue();
5239 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5240 VT.getSizeInBits() - N01->getZExtValue());
5242 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5245 unsigned EVTBits = ExtVT.getSizeInBits();
5247 // Do not generate loads of non-round integer types since these can
5248 // be expensive (and would be wrong if the type is not byte sized).
5249 if (!ExtVT.isRound())
5253 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5254 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5255 ShAmt = N01->getZExtValue();
5256 // Is the shift amount a multiple of size of VT?
5257 if ((ShAmt & (EVTBits-1)) == 0) {
5258 N0 = N0.getOperand(0);
5259 // Is the load width a multiple of size of VT?
5260 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5264 // At this point, we must have a load or else we can't do the transform.
5265 if (!isa<LoadSDNode>(N0)) return SDValue();
5267 // Because a SRL must be assumed to *need* to zero-extend the high bits
5268 // (as opposed to anyext the high bits), we can't combine the zextload
5269 // lowering of SRL and an sextload.
5270 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5273 // If the shift amount is larger than the input type then we're not
5274 // accessing any of the loaded bytes. If the load was a zextload/extload
5275 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5276 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5281 // If the load is shifted left (and the result isn't shifted back right),
5282 // we can fold the truncate through the shift.
5283 unsigned ShLeftAmt = 0;
5284 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5285 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5286 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5287 ShLeftAmt = N01->getZExtValue();
5288 N0 = N0.getOperand(0);
5292 // If we haven't found a load, we can't narrow it. Don't transform one with
5293 // multiple uses, this would require adding a new load.
5294 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5297 // Don't change the width of a volatile load.
5298 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5299 if (LN0->isVolatile())
5302 // Verify that we are actually reducing a load width here.
5303 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5306 // For the transform to be legal, the load must produce only two values
5307 // (the value loaded and the chain). Don't transform a pre-increment
5308 // load, for example, which produces an extra value. Otherwise the
5309 // transformation is not equivalent, and the downstream logic to replace
5310 // uses gets things wrong.
5311 if (LN0->getNumValues() > 2)
5314 // If the load that we're shrinking is an extload and we're not just
5315 // discarding the extension we can't simply shrink the load. Bail.
5316 // TODO: It would be possible to merge the extensions in some cases.
5317 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5318 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5321 EVT PtrType = N0.getOperand(1).getValueType();
5323 if (PtrType == MVT::Untyped || PtrType.isExtended())
5324 // It's not possible to generate a constant of extended or untyped type.
5327 // For big endian targets, we need to adjust the offset to the pointer to
5328 // load the correct bytes.
5329 if (TLI.isBigEndian()) {
5330 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5331 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5332 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5335 uint64_t PtrOff = ShAmt / 8;
5336 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5337 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5338 PtrType, LN0->getBasePtr(),
5339 DAG.getConstant(PtrOff, PtrType));
5340 AddToWorkList(NewPtr.getNode());
5343 if (ExtType == ISD::NON_EXTLOAD)
5344 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5345 LN0->getPointerInfo().getWithOffset(PtrOff),
5346 LN0->isVolatile(), LN0->isNonTemporal(),
5347 LN0->isInvariant(), NewAlign);
5349 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5350 LN0->getPointerInfo().getWithOffset(PtrOff),
5351 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5354 // Replace the old load's chain with the new load's chain.
5355 WorkListRemover DeadNodes(*this);
5356 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5358 // Shift the result left, if we've swallowed a left shift.
5359 SDValue Result = Load;
5360 if (ShLeftAmt != 0) {
5361 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5362 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5364 // If the shift amount is as large as the result size (but, presumably,
5365 // no larger than the source) then the useful bits of the result are
5366 // zero; we can't simply return the shortened shift, because the result
5367 // of that operation is undefined.
5368 if (ShLeftAmt >= VT.getSizeInBits())
5369 Result = DAG.getConstant(0, VT);
5371 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5372 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5375 // Return the new loaded value.
5379 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5380 SDValue N0 = N->getOperand(0);
5381 SDValue N1 = N->getOperand(1);
5382 EVT VT = N->getValueType(0);
5383 EVT EVT = cast<VTSDNode>(N1)->getVT();
5384 unsigned VTBits = VT.getScalarType().getSizeInBits();
5385 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5387 // fold (sext_in_reg c1) -> c1
5388 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5389 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5391 // If the input is already sign extended, just drop the extension.
5392 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5395 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5396 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5397 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5398 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5399 N0.getOperand(0), N1);
5401 // fold (sext_in_reg (sext x)) -> (sext x)
5402 // fold (sext_in_reg (aext x)) -> (sext x)
5403 // if x is small enough.
5404 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5405 SDValue N00 = N0.getOperand(0);
5406 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5407 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5408 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5411 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5412 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5413 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5415 // fold operands of sext_in_reg based on knowledge that the top bits are not
5417 if (SimplifyDemandedBits(SDValue(N, 0)))
5418 return SDValue(N, 0);
5420 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5421 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5422 SDValue NarrowLoad = ReduceLoadWidth(N);
5423 if (NarrowLoad.getNode())
5426 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5427 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5428 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5429 if (N0.getOpcode() == ISD::SRL) {
5430 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5431 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5432 // We can turn this into an SRA iff the input to the SRL is already sign
5434 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5435 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5436 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5437 N0.getOperand(0), N0.getOperand(1));
5441 // fold (sext_inreg (extload x)) -> (sextload x)
5442 if (ISD::isEXTLoad(N0.getNode()) &&
5443 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5444 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5445 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5446 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5447 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5448 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5450 LN0->getBasePtr(), LN0->getPointerInfo(),
5452 LN0->isVolatile(), LN0->isNonTemporal(),
5453 LN0->getAlignment());
5454 CombineTo(N, ExtLoad);
5455 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5456 AddToWorkList(ExtLoad.getNode());
5457 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5459 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5460 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5462 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5463 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5464 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5465 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5466 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5468 LN0->getBasePtr(), LN0->getPointerInfo(),
5470 LN0->isVolatile(), LN0->isNonTemporal(),
5471 LN0->getAlignment());
5472 CombineTo(N, ExtLoad);
5473 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5474 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5477 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5478 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5479 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5480 N0.getOperand(1), false);
5481 if (BSwap.getNode() != 0)
5482 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5489 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5490 SDValue N0 = N->getOperand(0);
5491 EVT VT = N->getValueType(0);
5492 bool isLE = TLI.isLittleEndian();
5495 if (N0.getValueType() == N->getValueType(0))
5497 // fold (truncate c1) -> c1
5498 if (isa<ConstantSDNode>(N0))
5499 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5500 // fold (truncate (truncate x)) -> (truncate x)
5501 if (N0.getOpcode() == ISD::TRUNCATE)
5502 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5503 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5504 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5505 N0.getOpcode() == ISD::SIGN_EXTEND ||
5506 N0.getOpcode() == ISD::ANY_EXTEND) {
5507 if (N0.getOperand(0).getValueType().bitsLT(VT))
5508 // if the source is smaller than the dest, we still need an extend
5509 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5511 if (N0.getOperand(0).getValueType().bitsGT(VT))
5512 // if the source is larger than the dest, than we just need the truncate
5513 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5514 // if the source and dest are the same type, we can drop both the extend
5515 // and the truncate.
5516 return N0.getOperand(0);
5519 // Fold extract-and-trunc into a narrow extract. For example:
5520 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5521 // i32 y = TRUNCATE(i64 x)
5523 // v16i8 b = BITCAST (v2i64 val)
5524 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5526 // Note: We only run this optimization after type legalization (which often
5527 // creates this pattern) and before operation legalization after which
5528 // we need to be more careful about the vector instructions that we generate.
5529 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5530 LegalTypes && !LegalOperations && N0->hasOneUse()) {
5532 EVT VecTy = N0.getOperand(0).getValueType();
5533 EVT ExTy = N0.getValueType();
5534 EVT TrTy = N->getValueType(0);
5536 unsigned NumElem = VecTy.getVectorNumElements();
5537 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5539 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5540 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5542 SDValue EltNo = N0->getOperand(1);
5543 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5544 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5545 EVT IndexTy = TLI.getVectorIdxTy();
5546 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5548 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5549 NVT, N0.getOperand(0));
5551 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5553 DAG.getConstant(Index, IndexTy));
5557 // Fold a series of buildvector, bitcast, and truncate if possible.
5559 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5560 // (2xi32 (buildvector x, y)).
5561 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5562 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5563 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5564 N0.getOperand(0).hasOneUse()) {
5566 SDValue BuildVect = N0.getOperand(0);
5567 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5568 EVT TruncVecEltTy = VT.getVectorElementType();
5570 // Check that the element types match.
5571 if (BuildVectEltTy == TruncVecEltTy) {
5572 // Now we only need to compute the offset of the truncated elements.
5573 unsigned BuildVecNumElts = BuildVect.getNumOperands();
5574 unsigned TruncVecNumElts = VT.getVectorNumElements();
5575 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5577 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5578 "Invalid number of elements");
5580 SmallVector<SDValue, 8> Opnds;
5581 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5582 Opnds.push_back(BuildVect.getOperand(i));
5584 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
5589 // See if we can simplify the input to this truncate through knowledge that
5590 // only the low bits are being used.
5591 // For example "trunc (or (shl x, 8), y)" // -> trunc y
5592 // Currently we only perform this optimization on scalars because vectors
5593 // may have different active low bits.
5594 if (!VT.isVector()) {
5596 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5597 VT.getSizeInBits()));
5598 if (Shorter.getNode())
5599 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
5601 // fold (truncate (load x)) -> (smaller load x)
5602 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5603 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5604 SDValue Reduced = ReduceLoadWidth(N);
5605 if (Reduced.getNode())
5608 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
5609 // where ... are all 'undef'.
5610 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
5611 SmallVector<EVT, 8> VTs;
5614 unsigned NumDefs = 0;
5616 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
5617 SDValue X = N0.getOperand(i);
5618 if (X.getOpcode() != ISD::UNDEF) {
5623 // Stop if more than one members are non-undef.
5626 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
5627 VT.getVectorElementType(),
5628 X.getValueType().getVectorNumElements()));
5632 return DAG.getUNDEF(VT);
5635 assert(V.getNode() && "The single defined operand is empty!");
5636 SmallVector<SDValue, 8> Opnds;
5637 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
5639 Opnds.push_back(DAG.getUNDEF(VTs[i]));
5642 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
5643 AddToWorkList(NV.getNode());
5644 Opnds.push_back(NV);
5646 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
5647 &Opnds[0], Opnds.size());
5651 // Simplify the operands using demanded-bits information.
5652 if (!VT.isVector() &&
5653 SimplifyDemandedBits(SDValue(N, 0)))
5654 return SDValue(N, 0);
5659 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
5660 SDValue Elt = N->getOperand(i);
5661 if (Elt.getOpcode() != ISD::MERGE_VALUES)
5662 return Elt.getNode();
5663 return Elt.getOperand(Elt.getResNo()).getNode();
5666 /// CombineConsecutiveLoads - build_pair (load, load) -> load
5667 /// if load locations are consecutive.
5668 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
5669 assert(N->getOpcode() == ISD::BUILD_PAIR);
5671 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
5672 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
5673 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
5674 LD1->getPointerInfo().getAddrSpace() !=
5675 LD2->getPointerInfo().getAddrSpace())
5677 EVT LD1VT = LD1->getValueType(0);
5679 if (ISD::isNON_EXTLoad(LD2) &&
5681 // If both are volatile this would reduce the number of volatile loads.
5682 // If one is volatile it might be ok, but play conservative and bail out.
5683 !LD1->isVolatile() &&
5684 !LD2->isVolatile() &&
5685 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
5686 unsigned Align = LD1->getAlignment();
5687 unsigned NewAlign = TLI.getDataLayout()->
5688 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5690 if (NewAlign <= Align &&
5691 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
5692 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
5693 LD1->getBasePtr(), LD1->getPointerInfo(),
5694 false, false, false, Align);
5700 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
5701 SDValue N0 = N->getOperand(0);
5702 EVT VT = N->getValueType(0);
5704 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
5705 // Only do this before legalize, since afterward the target may be depending
5706 // on the bitconvert.
5707 // First check to see if this is all constant.
5709 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
5711 bool isSimple = true;
5712 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
5713 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
5714 N0.getOperand(i).getOpcode() != ISD::Constant &&
5715 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
5720 EVT DestEltVT = N->getValueType(0).getVectorElementType();
5721 assert(!DestEltVT.isVector() &&
5722 "Element type of vector ValueType must not be vector!");
5724 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
5727 // If the input is a constant, let getNode fold it.
5728 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
5729 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
5730 if (Res.getNode() != N) {
5731 if (!LegalOperations ||
5732 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
5735 // Folding it resulted in an illegal node, and it's too late to
5736 // do that. Clean up the old node and forego the transformation.
5737 // Ideally this won't happen very often, because instcombine
5738 // and the earlier dagcombine runs (where illegal nodes are
5739 // permitted) should have folded most of them already.
5740 DAG.DeleteNode(Res.getNode());
5744 // (conv (conv x, t1), t2) -> (conv x, t2)
5745 if (N0.getOpcode() == ISD::BITCAST)
5746 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
5749 // fold (conv (load x)) -> (load (conv*)x)
5750 // If the resultant load doesn't need a higher alignment than the original!
5751 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
5752 // Do not change the width of a volatile load.
5753 !cast<LoadSDNode>(N0)->isVolatile() &&
5754 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
5755 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5756 unsigned Align = TLI.getDataLayout()->
5757 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5758 unsigned OrigAlign = LN0->getAlignment();
5760 if (Align <= OrigAlign) {
5761 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
5762 LN0->getBasePtr(), LN0->getPointerInfo(),
5763 LN0->isVolatile(), LN0->isNonTemporal(),
5764 LN0->isInvariant(), OrigAlign);
5766 CombineTo(N0.getNode(),
5767 DAG.getNode(ISD::BITCAST, SDLoc(N0),
5768 N0.getValueType(), Load),
5774 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
5775 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
5776 // This often reduces constant pool loads.
5777 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
5778 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
5779 N0.getNode()->hasOneUse() && VT.isInteger() &&
5780 !VT.isVector() && !N0.getValueType().isVector()) {
5781 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
5783 AddToWorkList(NewConv.getNode());
5785 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5786 if (N0.getOpcode() == ISD::FNEG)
5787 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
5788 NewConv, DAG.getConstant(SignBit, VT));
5789 assert(N0.getOpcode() == ISD::FABS);
5790 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5791 NewConv, DAG.getConstant(~SignBit, VT));
5794 // fold (bitconvert (fcopysign cst, x)) ->
5795 // (or (and (bitconvert x), sign), (and cst, (not sign)))
5796 // Note that we don't handle (copysign x, cst) because this can always be
5797 // folded to an fneg or fabs.
5798 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
5799 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
5800 VT.isInteger() && !VT.isVector()) {
5801 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
5802 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
5803 if (isTypeLegal(IntXVT)) {
5804 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5805 IntXVT, N0.getOperand(1));
5806 AddToWorkList(X.getNode());
5808 // If X has a different width than the result/lhs, sext it or truncate it.
5809 unsigned VTWidth = VT.getSizeInBits();
5810 if (OrigXWidth < VTWidth) {
5811 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
5812 AddToWorkList(X.getNode());
5813 } else if (OrigXWidth > VTWidth) {
5814 // To get the sign bit in the right place, we have to shift it right
5815 // before truncating.
5816 X = DAG.getNode(ISD::SRL, SDLoc(X),
5817 X.getValueType(), X,
5818 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
5819 AddToWorkList(X.getNode());
5820 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5821 AddToWorkList(X.getNode());
5824 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5825 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
5826 X, DAG.getConstant(SignBit, VT));
5827 AddToWorkList(X.getNode());
5829 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5830 VT, N0.getOperand(0));
5831 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
5832 Cst, DAG.getConstant(~SignBit, VT));
5833 AddToWorkList(Cst.getNode());
5835 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
5839 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
5840 if (N0.getOpcode() == ISD::BUILD_PAIR) {
5841 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
5842 if (CombineLD.getNode())
5849 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
5850 EVT VT = N->getValueType(0);
5851 return CombineConsecutiveLoads(N, VT);
5854 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
5855 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
5856 /// destination element value type.
5857 SDValue DAGCombiner::
5858 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
5859 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
5861 // If this is already the right type, we're done.
5862 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
5864 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
5865 unsigned DstBitSize = DstEltVT.getSizeInBits();
5867 // If this is a conversion of N elements of one type to N elements of another
5868 // type, convert each element. This handles FP<->INT cases.
5869 if (SrcBitSize == DstBitSize) {
5870 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5871 BV->getValueType(0).getVectorNumElements());
5873 // Due to the FP element handling below calling this routine recursively,
5874 // we can end up with a scalar-to-vector node here.
5875 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
5876 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
5877 DAG.getNode(ISD::BITCAST, SDLoc(BV),
5878 DstEltVT, BV->getOperand(0)));
5880 SmallVector<SDValue, 8> Ops;
5881 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5882 SDValue Op = BV->getOperand(i);
5883 // If the vector element type is not legal, the BUILD_VECTOR operands
5884 // are promoted and implicitly truncated. Make that explicit here.
5885 if (Op.getValueType() != SrcEltVT)
5886 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
5887 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
5889 AddToWorkList(Ops.back().getNode());
5891 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5892 &Ops[0], Ops.size());
5895 // Otherwise, we're growing or shrinking the elements. To avoid having to
5896 // handle annoying details of growing/shrinking FP values, we convert them to
5898 if (SrcEltVT.isFloatingPoint()) {
5899 // Convert the input float vector to a int vector where the elements are the
5901 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
5902 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
5903 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
5907 // Now we know the input is an integer vector. If the output is a FP type,
5908 // convert to integer first, then to FP of the right size.
5909 if (DstEltVT.isFloatingPoint()) {
5910 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
5911 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
5912 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
5914 // Next, convert to FP elements of the same size.
5915 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
5918 // Okay, we know the src/dst types are both integers of differing types.
5919 // Handling growing first.
5920 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
5921 if (SrcBitSize < DstBitSize) {
5922 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
5924 SmallVector<SDValue, 8> Ops;
5925 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
5926 i += NumInputsPerOutput) {
5927 bool isLE = TLI.isLittleEndian();
5928 APInt NewBits = APInt(DstBitSize, 0);
5929 bool EltIsUndef = true;
5930 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
5931 // Shift the previously computed bits over.
5932 NewBits <<= SrcBitSize;
5933 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
5934 if (Op.getOpcode() == ISD::UNDEF) continue;
5937 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
5938 zextOrTrunc(SrcBitSize).zext(DstBitSize);
5942 Ops.push_back(DAG.getUNDEF(DstEltVT));
5944 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
5947 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
5948 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5949 &Ops[0], Ops.size());
5952 // Finally, this must be the case where we are shrinking elements: each input
5953 // turns into multiple outputs.
5954 bool isS2V = ISD::isScalarToVector(BV);
5955 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
5956 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5957 NumOutputsPerInput*BV->getNumOperands());
5958 SmallVector<SDValue, 8> Ops;
5960 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5961 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
5962 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
5963 Ops.push_back(DAG.getUNDEF(DstEltVT));
5967 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
5968 getAPIntValue().zextOrTrunc(SrcBitSize);
5970 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
5971 APInt ThisVal = OpVal.trunc(DstBitSize);
5972 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
5973 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
5974 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
5975 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
5977 OpVal = OpVal.lshr(DstBitSize);
5980 // For big endian targets, swap the order of the pieces of each element.
5981 if (TLI.isBigEndian())
5982 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
5985 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5986 &Ops[0], Ops.size());
5989 SDValue DAGCombiner::visitFADD(SDNode *N) {
5990 SDValue N0 = N->getOperand(0);
5991 SDValue N1 = N->getOperand(1);
5992 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5993 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5994 EVT VT = N->getValueType(0);
5997 if (VT.isVector()) {
5998 SDValue FoldedVOp = SimplifyVBinOp(N);
5999 if (FoldedVOp.getNode()) return FoldedVOp;
6002 // fold (fadd c1, c2) -> c1 + c2
6004 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6005 // canonicalize constant to RHS
6006 if (N0CFP && !N1CFP)
6007 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6008 // fold (fadd A, 0) -> A
6009 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6010 N1CFP->getValueAPF().isZero())
6012 // fold (fadd A, (fneg B)) -> (fsub A, B)
6013 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6014 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6015 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6016 GetNegatedExpression(N1, DAG, LegalOperations));
6017 // fold (fadd (fneg A), B) -> (fsub B, A)
6018 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6019 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6020 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6021 GetNegatedExpression(N0, DAG, LegalOperations));
6023 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6024 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6025 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6026 isa<ConstantFPSDNode>(N0.getOperand(1)))
6027 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6028 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6029 N0.getOperand(1), N1));
6031 // No FP constant should be created after legalization as Instruction
6032 // Selection pass has hard time in dealing with FP constant.
6034 // We don't need test this condition for transformation like following, as
6035 // the DAG being transformed implies it is legal to take FP constant as
6038 // (fadd (fmul c, x), x) -> (fmul c+1, x)
6040 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6042 // If allow, fold (fadd (fneg x), x) -> 0.0
6043 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6044 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6045 return DAG.getConstantFP(0.0, VT);
6047 // If allow, fold (fadd x, (fneg x)) -> 0.0
6048 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6049 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6050 return DAG.getConstantFP(0.0, VT);
6052 // In unsafe math mode, we can fold chains of FADD's of the same value
6053 // into multiplications. This transform is not safe in general because
6054 // we are reducing the number of rounding steps.
6055 if (DAG.getTarget().Options.UnsafeFPMath &&
6056 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6058 if (N0.getOpcode() == ISD::FMUL) {
6059 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6060 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6062 // (fadd (fmul c, x), x) -> (fmul x, c+1)
6063 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6064 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6066 DAG.getConstantFP(1.0, VT));
6067 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6071 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6072 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6073 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6075 DAG.getConstantFP(1.0, VT));
6076 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6080 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6081 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6082 N1.getOperand(0) == N1.getOperand(1) &&
6083 N0.getOperand(1) == N1.getOperand(0)) {
6084 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6086 DAG.getConstantFP(2.0, VT));
6087 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6088 N0.getOperand(1), NewCFP);
6091 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6092 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6093 N1.getOperand(0) == N1.getOperand(1) &&
6094 N0.getOperand(0) == N1.getOperand(0)) {
6095 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6097 DAG.getConstantFP(2.0, VT));
6098 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6099 N0.getOperand(0), NewCFP);
6103 if (N1.getOpcode() == ISD::FMUL) {
6104 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6105 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6107 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6108 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6109 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6111 DAG.getConstantFP(1.0, VT));
6112 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6116 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6117 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6118 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6120 DAG.getConstantFP(1.0, VT));
6121 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6126 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6127 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6128 N0.getOperand(0) == N0.getOperand(1) &&
6129 N1.getOperand(1) == N0.getOperand(0)) {
6130 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6132 DAG.getConstantFP(2.0, VT));
6133 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6134 N1.getOperand(1), NewCFP);
6137 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6138 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6139 N0.getOperand(0) == N0.getOperand(1) &&
6140 N1.getOperand(0) == N0.getOperand(0)) {
6141 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6143 DAG.getConstantFP(2.0, VT));
6144 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6145 N1.getOperand(0), NewCFP);
6149 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6150 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6151 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6152 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6153 (N0.getOperand(0) == N1))
6154 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6155 N1, DAG.getConstantFP(3.0, VT));
6158 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6159 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6160 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6161 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6162 N1.getOperand(0) == N0)
6163 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6164 N0, DAG.getConstantFP(3.0, VT));
6167 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6168 if (AllowNewFpConst &&
6169 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6170 N0.getOperand(0) == N0.getOperand(1) &&
6171 N1.getOperand(0) == N1.getOperand(1) &&
6172 N0.getOperand(0) == N1.getOperand(0))
6173 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6175 DAG.getConstantFP(4.0, VT));
6178 // FADD -> FMA combines:
6179 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6180 DAG.getTarget().Options.UnsafeFPMath) &&
6181 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6182 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6184 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6185 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6186 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6187 N0.getOperand(0), N0.getOperand(1), N1);
6189 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6190 // Note: Commutes FADD operands.
6191 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6192 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6193 N1.getOperand(0), N1.getOperand(1), N0);
6199 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6200 SDValue N0 = N->getOperand(0);
6201 SDValue N1 = N->getOperand(1);
6202 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6203 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6204 EVT VT = N->getValueType(0);
6208 if (VT.isVector()) {
6209 SDValue FoldedVOp = SimplifyVBinOp(N);
6210 if (FoldedVOp.getNode()) return FoldedVOp;
6213 // fold (fsub c1, c2) -> c1-c2
6215 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6216 // fold (fsub A, 0) -> A
6217 if (DAG.getTarget().Options.UnsafeFPMath &&
6218 N1CFP && N1CFP->getValueAPF().isZero())
6220 // fold (fsub 0, B) -> -B
6221 if (DAG.getTarget().Options.UnsafeFPMath &&
6222 N0CFP && N0CFP->getValueAPF().isZero()) {
6223 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6224 return GetNegatedExpression(N1, DAG, LegalOperations);
6225 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6226 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6228 // fold (fsub A, (fneg B)) -> (fadd A, B)
6229 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6230 return DAG.getNode(ISD::FADD, dl, VT, N0,
6231 GetNegatedExpression(N1, DAG, LegalOperations));
6233 // If 'unsafe math' is enabled, fold
6234 // (fsub x, x) -> 0.0 &
6235 // (fsub x, (fadd x, y)) -> (fneg y) &
6236 // (fsub x, (fadd y, x)) -> (fneg y)
6237 if (DAG.getTarget().Options.UnsafeFPMath) {
6239 return DAG.getConstantFP(0.0f, VT);
6241 if (N1.getOpcode() == ISD::FADD) {
6242 SDValue N10 = N1->getOperand(0);
6243 SDValue N11 = N1->getOperand(1);
6245 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6246 &DAG.getTarget().Options))
6247 return GetNegatedExpression(N11, DAG, LegalOperations);
6249 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6250 &DAG.getTarget().Options))
6251 return GetNegatedExpression(N10, DAG, LegalOperations);
6255 // FSUB -> FMA combines:
6256 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6257 DAG.getTarget().Options.UnsafeFPMath) &&
6258 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6259 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6261 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6262 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6263 return DAG.getNode(ISD::FMA, dl, VT,
6264 N0.getOperand(0), N0.getOperand(1),
6265 DAG.getNode(ISD::FNEG, dl, VT, N1));
6267 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6268 // Note: Commutes FSUB operands.
6269 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6270 return DAG.getNode(ISD::FMA, dl, VT,
6271 DAG.getNode(ISD::FNEG, dl, VT,
6273 N1.getOperand(1), N0);
6275 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6276 if (N0.getOpcode() == ISD::FNEG &&
6277 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6278 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6279 SDValue N00 = N0.getOperand(0).getOperand(0);
6280 SDValue N01 = N0.getOperand(0).getOperand(1);
6281 return DAG.getNode(ISD::FMA, dl, VT,
6282 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6283 DAG.getNode(ISD::FNEG, dl, VT, N1));
6290 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6291 SDValue N0 = N->getOperand(0);
6292 SDValue N1 = N->getOperand(1);
6293 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6294 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6295 EVT VT = N->getValueType(0);
6296 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6299 if (VT.isVector()) {
6300 SDValue FoldedVOp = SimplifyVBinOp(N);
6301 if (FoldedVOp.getNode()) return FoldedVOp;
6304 // fold (fmul c1, c2) -> c1*c2
6306 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6307 // canonicalize constant to RHS
6308 if (N0CFP && !N1CFP)
6309 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6310 // fold (fmul A, 0) -> 0
6311 if (DAG.getTarget().Options.UnsafeFPMath &&
6312 N1CFP && N1CFP->getValueAPF().isZero())
6314 // fold (fmul A, 0) -> 0, vector edition.
6315 if (DAG.getTarget().Options.UnsafeFPMath &&
6316 ISD::isBuildVectorAllZeros(N1.getNode()))
6318 // fold (fmul A, 1.0) -> A
6319 if (N1CFP && N1CFP->isExactlyValue(1.0))
6321 // fold (fmul X, 2.0) -> (fadd X, X)
6322 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6323 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6324 // fold (fmul X, -1.0) -> (fneg X)
6325 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6326 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6327 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6329 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6330 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6331 &DAG.getTarget().Options)) {
6332 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6333 &DAG.getTarget().Options)) {
6334 // Both can be negated for free, check to see if at least one is cheaper
6336 if (LHSNeg == 2 || RHSNeg == 2)
6337 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6338 GetNegatedExpression(N0, DAG, LegalOperations),
6339 GetNegatedExpression(N1, DAG, LegalOperations));
6343 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6344 if (DAG.getTarget().Options.UnsafeFPMath &&
6345 N1CFP && N0.getOpcode() == ISD::FMUL &&
6346 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6347 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6348 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6349 N0.getOperand(1), N1));
6354 SDValue DAGCombiner::visitFMA(SDNode *N) {
6355 SDValue N0 = N->getOperand(0);
6356 SDValue N1 = N->getOperand(1);
6357 SDValue N2 = N->getOperand(2);
6358 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6359 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6360 EVT VT = N->getValueType(0);
6363 if (DAG.getTarget().Options.UnsafeFPMath) {
6364 if (N0CFP && N0CFP->isZero())
6366 if (N1CFP && N1CFP->isZero())
6369 if (N0CFP && N0CFP->isExactlyValue(1.0))
6370 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6371 if (N1CFP && N1CFP->isExactlyValue(1.0))
6372 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6374 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6375 if (N0CFP && !N1CFP)
6376 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6378 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6379 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6380 N2.getOpcode() == ISD::FMUL &&
6381 N0 == N2.getOperand(0) &&
6382 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6383 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6384 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6388 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6389 if (DAG.getTarget().Options.UnsafeFPMath &&
6390 N0.getOpcode() == ISD::FMUL && N1CFP &&
6391 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6392 return DAG.getNode(ISD::FMA, dl, VT,
6394 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6398 // (fma x, 1, y) -> (fadd x, y)
6399 // (fma x, -1, y) -> (fadd (fneg x), y)
6401 if (N1CFP->isExactlyValue(1.0))
6402 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6404 if (N1CFP->isExactlyValue(-1.0) &&
6405 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6406 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6407 AddToWorkList(RHSNeg.getNode());
6408 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6412 // (fma x, c, x) -> (fmul x, (c+1))
6413 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6414 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6415 DAG.getNode(ISD::FADD, dl, VT,
6416 N1, DAG.getConstantFP(1.0, VT)));
6418 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6419 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6420 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6421 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6422 DAG.getNode(ISD::FADD, dl, VT,
6423 N1, DAG.getConstantFP(-1.0, VT)));
6429 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6430 SDValue N0 = N->getOperand(0);
6431 SDValue N1 = N->getOperand(1);
6432 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6433 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6434 EVT VT = N->getValueType(0);
6435 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6438 if (VT.isVector()) {
6439 SDValue FoldedVOp = SimplifyVBinOp(N);
6440 if (FoldedVOp.getNode()) return FoldedVOp;
6443 // fold (fdiv c1, c2) -> c1/c2
6445 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6447 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6448 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6449 // Compute the reciprocal 1.0 / c2.
6450 APFloat N1APF = N1CFP->getValueAPF();
6451 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6452 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6453 // Only do the transform if the reciprocal is a legal fp immediate that
6454 // isn't too nasty (eg NaN, denormal, ...).
6455 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6456 (!LegalOperations ||
6457 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6458 // backend)... we should handle this gracefully after Legalize.
6459 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6460 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6461 TLI.isFPImmLegal(Recip, VT)))
6462 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6463 DAG.getConstantFP(Recip, VT));
6466 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6467 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6468 &DAG.getTarget().Options)) {
6469 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6470 &DAG.getTarget().Options)) {
6471 // Both can be negated for free, check to see if at least one is cheaper
6473 if (LHSNeg == 2 || RHSNeg == 2)
6474 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6475 GetNegatedExpression(N0, DAG, LegalOperations),
6476 GetNegatedExpression(N1, DAG, LegalOperations));
6483 SDValue DAGCombiner::visitFREM(SDNode *N) {
6484 SDValue N0 = N->getOperand(0);
6485 SDValue N1 = N->getOperand(1);
6486 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6487 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6488 EVT VT = N->getValueType(0);
6490 // fold (frem c1, c2) -> fmod(c1,c2)
6492 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6497 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6498 SDValue N0 = N->getOperand(0);
6499 SDValue N1 = N->getOperand(1);
6500 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6501 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6502 EVT VT = N->getValueType(0);
6504 if (N0CFP && N1CFP) // Constant fold
6505 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6508 const APFloat& V = N1CFP->getValueAPF();
6509 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6510 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6511 if (!V.isNegative()) {
6512 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6513 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6515 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6516 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6517 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6521 // copysign(fabs(x), y) -> copysign(x, y)
6522 // copysign(fneg(x), y) -> copysign(x, y)
6523 // copysign(copysign(x,z), y) -> copysign(x, y)
6524 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6525 N0.getOpcode() == ISD::FCOPYSIGN)
6526 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6527 N0.getOperand(0), N1);
6529 // copysign(x, abs(y)) -> abs(x)
6530 if (N1.getOpcode() == ISD::FABS)
6531 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6533 // copysign(x, copysign(y,z)) -> copysign(x, z)
6534 if (N1.getOpcode() == ISD::FCOPYSIGN)
6535 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6536 N0, N1.getOperand(1));
6538 // copysign(x, fp_extend(y)) -> copysign(x, y)
6539 // copysign(x, fp_round(y)) -> copysign(x, y)
6540 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6541 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6542 N0, N1.getOperand(0));
6547 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6548 SDValue N0 = N->getOperand(0);
6549 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6550 EVT VT = N->getValueType(0);
6551 EVT OpVT = N0.getValueType();
6553 // fold (sint_to_fp c1) -> c1fp
6555 // ...but only if the target supports immediate floating-point values
6556 (!LegalOperations ||
6557 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6558 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6560 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6561 // but UINT_TO_FP is legal on this target, try to convert.
6562 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6563 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6564 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6565 if (DAG.SignBitIsZero(N0))
6566 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6569 // The next optimizations are desireable only if SELECT_CC can be lowered.
6570 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6571 // having to say they don't support SELECT_CC on every type the DAG knows
6572 // about, since there is no way to mark an opcode illegal at all value types
6573 // (See also visitSELECT)
6574 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6575 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6576 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6578 (!LegalOperations ||
6579 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6581 { N0.getOperand(0), N0.getOperand(1),
6582 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6584 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6587 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6588 // (select_cc x, y, 1.0, 0.0,, cc)
6589 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6590 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6591 (!LegalOperations ||
6592 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6594 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6595 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6596 N0.getOperand(0).getOperand(2) };
6597 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6604 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6605 SDValue N0 = N->getOperand(0);
6606 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6607 EVT VT = N->getValueType(0);
6608 EVT OpVT = N0.getValueType();
6610 // fold (uint_to_fp c1) -> c1fp
6612 // ...but only if the target supports immediate floating-point values
6613 (!LegalOperations ||
6614 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6615 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6617 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6618 // but SINT_TO_FP is legal on this target, try to convert.
6619 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
6620 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
6621 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
6622 if (DAG.SignBitIsZero(N0))
6623 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6626 // The next optimizations are desireable only if SELECT_CC can be lowered.
6627 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6628 // having to say they don't support SELECT_CC on every type the DAG knows
6629 // about, since there is no way to mark an opcode illegal at all value types
6630 // (See also visitSELECT)
6631 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6632 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6634 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
6635 (!LegalOperations ||
6636 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6638 { N0.getOperand(0), N0.getOperand(1),
6639 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
6641 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6648 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
6649 SDValue N0 = N->getOperand(0);
6650 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6651 EVT VT = N->getValueType(0);
6653 // fold (fp_to_sint c1fp) -> c1
6655 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
6660 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
6661 SDValue N0 = N->getOperand(0);
6662 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6663 EVT VT = N->getValueType(0);
6665 // fold (fp_to_uint c1fp) -> c1
6667 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
6672 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
6673 SDValue N0 = N->getOperand(0);
6674 SDValue N1 = N->getOperand(1);
6675 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6676 EVT VT = N->getValueType(0);
6678 // fold (fp_round c1fp) -> c1fp
6680 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
6682 // fold (fp_round (fp_extend x)) -> x
6683 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
6684 return N0.getOperand(0);
6686 // fold (fp_round (fp_round x)) -> (fp_round x)
6687 if (N0.getOpcode() == ISD::FP_ROUND) {
6688 // This is a value preserving truncation if both round's are.
6689 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
6690 N0.getNode()->getConstantOperandVal(1) == 1;
6691 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
6692 DAG.getIntPtrConstant(IsTrunc));
6695 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
6696 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
6697 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
6698 N0.getOperand(0), N1);
6699 AddToWorkList(Tmp.getNode());
6700 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6701 Tmp, N0.getOperand(1));
6707 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
6708 SDValue N0 = N->getOperand(0);
6709 EVT VT = N->getValueType(0);
6710 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6711 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6713 // fold (fp_round_inreg c1fp) -> c1fp
6714 if (N0CFP && isTypeLegal(EVT)) {
6715 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
6716 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
6722 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
6723 SDValue N0 = N->getOperand(0);
6724 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6725 EVT VT = N->getValueType(0);
6727 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
6728 if (N->hasOneUse() &&
6729 N->use_begin()->getOpcode() == ISD::FP_ROUND)
6732 // fold (fp_extend c1fp) -> c1fp
6734 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
6736 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
6738 if (N0.getOpcode() == ISD::FP_ROUND
6739 && N0.getNode()->getConstantOperandVal(1) == 1) {
6740 SDValue In = N0.getOperand(0);
6741 if (In.getValueType() == VT) return In;
6742 if (VT.bitsLT(In.getValueType()))
6743 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
6744 In, N0.getOperand(1));
6745 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
6748 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
6749 if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
6750 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6751 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
6752 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6753 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6755 LN0->getBasePtr(), LN0->getPointerInfo(),
6757 LN0->isVolatile(), LN0->isNonTemporal(),
6758 LN0->getAlignment());
6759 CombineTo(N, ExtLoad);
6760 CombineTo(N0.getNode(),
6761 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
6762 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
6763 ExtLoad.getValue(1));
6764 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6770 SDValue DAGCombiner::visitFNEG(SDNode *N) {
6771 SDValue N0 = N->getOperand(0);
6772 EVT VT = N->getValueType(0);
6774 if (VT.isVector()) {
6775 SDValue FoldedVOp = SimplifyVUnaryOp(N);
6776 if (FoldedVOp.getNode()) return FoldedVOp;
6779 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
6780 &DAG.getTarget().Options))
6781 return GetNegatedExpression(N0, DAG, LegalOperations);
6783 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
6784 // constant pool values.
6785 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
6787 N0.getNode()->hasOneUse() &&
6788 N0.getOperand(0).getValueType().isInteger()) {
6789 SDValue Int = N0.getOperand(0);
6790 EVT IntVT = Int.getValueType();
6791 if (IntVT.isInteger() && !IntVT.isVector()) {
6792 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
6793 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6794 AddToWorkList(Int.getNode());
6795 return DAG.getNode(ISD::BITCAST, SDLoc(N),
6800 // (fneg (fmul c, x)) -> (fmul -c, x)
6801 if (N0.getOpcode() == ISD::FMUL) {
6802 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6804 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6806 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6813 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
6814 SDValue N0 = N->getOperand(0);
6815 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6816 EVT VT = N->getValueType(0);
6818 // fold (fceil c1) -> fceil(c1)
6820 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
6825 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
6826 SDValue N0 = N->getOperand(0);
6827 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6828 EVT VT = N->getValueType(0);
6830 // fold (ftrunc c1) -> ftrunc(c1)
6832 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
6837 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
6838 SDValue N0 = N->getOperand(0);
6839 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6840 EVT VT = N->getValueType(0);
6842 // fold (ffloor c1) -> ffloor(c1)
6844 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
6849 SDValue DAGCombiner::visitFABS(SDNode *N) {
6850 SDValue N0 = N->getOperand(0);
6851 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6852 EVT VT = N->getValueType(0);
6854 if (VT.isVector()) {
6855 SDValue FoldedVOp = SimplifyVUnaryOp(N);
6856 if (FoldedVOp.getNode()) return FoldedVOp;
6859 // fold (fabs c1) -> fabs(c1)
6861 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6862 // fold (fabs (fabs x)) -> (fabs x)
6863 if (N0.getOpcode() == ISD::FABS)
6864 return N->getOperand(0);
6865 // fold (fabs (fneg x)) -> (fabs x)
6866 // fold (fabs (fcopysign x, y)) -> (fabs x)
6867 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
6868 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
6870 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
6871 // constant pool values.
6872 if (!TLI.isFAbsFree(VT) &&
6873 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
6874 N0.getOperand(0).getValueType().isInteger() &&
6875 !N0.getOperand(0).getValueType().isVector()) {
6876 SDValue Int = N0.getOperand(0);
6877 EVT IntVT = Int.getValueType();
6878 if (IntVT.isInteger() && !IntVT.isVector()) {
6879 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
6880 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6881 AddToWorkList(Int.getNode());
6882 return DAG.getNode(ISD::BITCAST, SDLoc(N),
6883 N->getValueType(0), Int);
6890 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
6891 SDValue Chain = N->getOperand(0);
6892 SDValue N1 = N->getOperand(1);
6893 SDValue N2 = N->getOperand(2);
6895 // If N is a constant we could fold this into a fallthrough or unconditional
6896 // branch. However that doesn't happen very often in normal code, because
6897 // Instcombine/SimplifyCFG should have handled the available opportunities.
6898 // If we did this folding here, it would be necessary to update the
6899 // MachineBasicBlock CFG, which is awkward.
6901 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
6903 if (N1.getOpcode() == ISD::SETCC &&
6904 TLI.isOperationLegalOrCustom(ISD::BR_CC,
6905 N1.getOperand(0).getValueType())) {
6906 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
6907 Chain, N1.getOperand(2),
6908 N1.getOperand(0), N1.getOperand(1), N2);
6911 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
6912 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
6913 (N1.getOperand(0).hasOneUse() &&
6914 N1.getOperand(0).getOpcode() == ISD::SRL))) {
6916 if (N1.getOpcode() == ISD::TRUNCATE) {
6917 // Look pass the truncate.
6918 Trunc = N1.getNode();
6919 N1 = N1.getOperand(0);
6922 // Match this pattern so that we can generate simpler code:
6925 // %b = and i32 %a, 2
6926 // %c = srl i32 %b, 1
6927 // brcond i32 %c ...
6932 // %b = and i32 %a, 2
6933 // %c = setcc eq %b, 0
6936 // This applies only when the AND constant value has one bit set and the
6937 // SRL constant is equal to the log2 of the AND constant. The back-end is
6938 // smart enough to convert the result into a TEST/JMP sequence.
6939 SDValue Op0 = N1.getOperand(0);
6940 SDValue Op1 = N1.getOperand(1);
6942 if (Op0.getOpcode() == ISD::AND &&
6943 Op1.getOpcode() == ISD::Constant) {
6944 SDValue AndOp1 = Op0.getOperand(1);
6946 if (AndOp1.getOpcode() == ISD::Constant) {
6947 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
6949 if (AndConst.isPowerOf2() &&
6950 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
6952 DAG.getSetCC(SDLoc(N),
6953 getSetCCResultType(Op0.getValueType()),
6954 Op0, DAG.getConstant(0, Op0.getValueType()),
6957 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
6958 MVT::Other, Chain, SetCC, N2);
6959 // Don't add the new BRCond into the worklist or else SimplifySelectCC
6960 // will convert it back to (X & C1) >> C2.
6961 CombineTo(N, NewBRCond, false);
6962 // Truncate is dead.
6964 removeFromWorkList(Trunc);
6965 DAG.DeleteNode(Trunc);
6967 // Replace the uses of SRL with SETCC
6968 WorkListRemover DeadNodes(*this);
6969 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
6970 removeFromWorkList(N1.getNode());
6971 DAG.DeleteNode(N1.getNode());
6972 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6978 // Restore N1 if the above transformation doesn't match.
6979 N1 = N->getOperand(1);
6982 // Transform br(xor(x, y)) -> br(x != y)
6983 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
6984 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
6985 SDNode *TheXor = N1.getNode();
6986 SDValue Op0 = TheXor->getOperand(0);
6987 SDValue Op1 = TheXor->getOperand(1);
6988 if (Op0.getOpcode() == Op1.getOpcode()) {
6989 // Avoid missing important xor optimizations.
6990 SDValue Tmp = visitXOR(TheXor);
6991 if (Tmp.getNode()) {
6992 if (Tmp.getNode() != TheXor) {
6993 DEBUG(dbgs() << "\nReplacing.8 ";
6995 dbgs() << "\nWith: ";
6996 Tmp.getNode()->dump(&DAG);
6998 WorkListRemover DeadNodes(*this);
6999 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7000 removeFromWorkList(TheXor);
7001 DAG.DeleteNode(TheXor);
7002 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7003 MVT::Other, Chain, Tmp, N2);
7006 // visitXOR has changed XOR's operands or replaced the XOR completely,
7008 return SDValue(N, 0);
7012 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7014 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7015 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7016 Op0.getOpcode() == ISD::XOR) {
7017 TheXor = Op0.getNode();
7021 EVT SetCCVT = N1.getValueType();
7023 SetCCVT = getSetCCResultType(SetCCVT);
7024 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7027 Equal ? ISD::SETEQ : ISD::SETNE);
7028 // Replace the uses of XOR with SETCC
7029 WorkListRemover DeadNodes(*this);
7030 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7031 removeFromWorkList(N1.getNode());
7032 DAG.DeleteNode(N1.getNode());
7033 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7034 MVT::Other, Chain, SetCC, N2);
7041 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7043 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7044 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7045 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7047 // If N is a constant we could fold this into a fallthrough or unconditional
7048 // branch. However that doesn't happen very often in normal code, because
7049 // Instcombine/SimplifyCFG should have handled the available opportunities.
7050 // If we did this folding here, it would be necessary to update the
7051 // MachineBasicBlock CFG, which is awkward.
7053 // Use SimplifySetCC to simplify SETCC's.
7054 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7055 CondLHS, CondRHS, CC->get(), SDLoc(N),
7057 if (Simp.getNode()) AddToWorkList(Simp.getNode());
7059 // fold to a simpler setcc
7060 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7061 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7062 N->getOperand(0), Simp.getOperand(2),
7063 Simp.getOperand(0), Simp.getOperand(1),
7069 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7070 /// uses N as its base pointer and that N may be folded in the load / store
7071 /// addressing mode.
7072 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7074 const TargetLowering &TLI) {
7076 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7077 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7079 VT = Use->getValueType(0);
7080 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7081 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7083 VT = ST->getValue().getValueType();
7087 TargetLowering::AddrMode AM;
7088 if (N->getOpcode() == ISD::ADD) {
7089 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7092 AM.BaseOffs = Offset->getSExtValue();
7096 } else if (N->getOpcode() == ISD::SUB) {
7097 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7100 AM.BaseOffs = -Offset->getSExtValue();
7107 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7110 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7111 /// pre-indexed load / store when the base pointer is an add or subtract
7112 /// and it has other uses besides the load / store. After the
7113 /// transformation, the new indexed load / store has effectively folded
7114 /// the add / subtract in and all of its other uses are redirected to the
7115 /// new load / store.
7116 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7117 if (Level < AfterLegalizeDAG)
7123 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7124 if (LD->isIndexed())
7126 VT = LD->getMemoryVT();
7127 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7128 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7130 Ptr = LD->getBasePtr();
7131 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7132 if (ST->isIndexed())
7134 VT = ST->getMemoryVT();
7135 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7136 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7138 Ptr = ST->getBasePtr();
7144 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7145 // out. There is no reason to make this a preinc/predec.
7146 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7147 Ptr.getNode()->hasOneUse())
7150 // Ask the target to do addressing mode selection.
7153 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7154 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7157 // Backends without true r+i pre-indexed forms may need to pass a
7158 // constant base with a variable offset so that constant coercion
7159 // will work with the patterns in canonical form.
7160 bool Swapped = false;
7161 if (isa<ConstantSDNode>(BasePtr)) {
7162 std::swap(BasePtr, Offset);
7166 // Don't create a indexed load / store with zero offset.
7167 if (isa<ConstantSDNode>(Offset) &&
7168 cast<ConstantSDNode>(Offset)->isNullValue())
7171 // Try turning it into a pre-indexed load / store except when:
7172 // 1) The new base ptr is a frame index.
7173 // 2) If N is a store and the new base ptr is either the same as or is a
7174 // predecessor of the value being stored.
7175 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7176 // that would create a cycle.
7177 // 4) All uses are load / store ops that use it as old base ptr.
7179 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7180 // (plus the implicit offset) to a register to preinc anyway.
7181 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7186 SDValue Val = cast<StoreSDNode>(N)->getValue();
7187 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7191 // If the offset is a constant, there may be other adds of constants that
7192 // can be folded with this one. We should do this to avoid having to keep
7193 // a copy of the original base pointer.
7194 SmallVector<SDNode *, 16> OtherUses;
7195 if (isa<ConstantSDNode>(Offset))
7196 for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7197 E = BasePtr.getNode()->use_end(); I != E; ++I) {
7199 if (Use == Ptr.getNode())
7202 if (Use->isPredecessorOf(N))
7205 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7210 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7211 if (Op1.getNode() == BasePtr.getNode())
7212 std::swap(Op0, Op1);
7213 assert(Op0.getNode() == BasePtr.getNode() &&
7214 "Use of ADD/SUB but not an operand");
7216 if (!isa<ConstantSDNode>(Op1)) {
7221 // FIXME: In some cases, we can be smarter about this.
7222 if (Op1.getValueType() != Offset.getValueType()) {
7227 OtherUses.push_back(Use);
7231 std::swap(BasePtr, Offset);
7233 // Now check for #3 and #4.
7234 bool RealUse = false;
7236 // Caches for hasPredecessorHelper
7237 SmallPtrSet<const SDNode *, 32> Visited;
7238 SmallVector<const SDNode *, 16> Worklist;
7240 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7241 E = Ptr.getNode()->use_end(); I != E; ++I) {
7245 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7248 // If Ptr may be folded in addressing mode of other use, then it's
7249 // not profitable to do this transformation.
7250 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7259 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7260 BasePtr, Offset, AM);
7262 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7263 BasePtr, Offset, AM);
7266 DEBUG(dbgs() << "\nReplacing.4 ";
7268 dbgs() << "\nWith: ";
7269 Result.getNode()->dump(&DAG);
7271 WorkListRemover DeadNodes(*this);
7273 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7274 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7276 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7279 // Finally, since the node is now dead, remove it from the graph.
7283 std::swap(BasePtr, Offset);
7285 // Replace other uses of BasePtr that can be updated to use Ptr
7286 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7287 unsigned OffsetIdx = 1;
7288 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7290 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7291 BasePtr.getNode() && "Expected BasePtr operand");
7293 // We need to replace ptr0 in the following expression:
7294 // x0 * offset0 + y0 * ptr0 = t0
7296 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7298 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7299 // indexed load/store and the expresion that needs to be re-written.
7301 // Therefore, we have:
7302 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7304 ConstantSDNode *CN =
7305 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7307 APInt Offset0 = CN->getAPIntValue();
7308 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7310 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7311 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7312 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7313 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7315 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7317 APInt CNV = Offset0;
7318 if (X0 < 0) CNV = -CNV;
7319 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7320 else CNV = CNV - Offset1;
7322 // We can now generate the new expression.
7323 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7324 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7326 SDValue NewUse = DAG.getNode(Opcode,
7327 SDLoc(OtherUses[i]),
7328 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7329 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7330 removeFromWorkList(OtherUses[i]);
7331 DAG.DeleteNode(OtherUses[i]);
7334 // Replace the uses of Ptr with uses of the updated base value.
7335 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7336 removeFromWorkList(Ptr.getNode());
7337 DAG.DeleteNode(Ptr.getNode());
7342 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7343 /// add / sub of the base pointer node into a post-indexed load / store.
7344 /// The transformation folded the add / subtract into the new indexed
7345 /// load / store effectively and all of its uses are redirected to the
7346 /// new load / store.
7347 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7348 if (Level < AfterLegalizeDAG)
7354 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7355 if (LD->isIndexed())
7357 VT = LD->getMemoryVT();
7358 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7359 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7361 Ptr = LD->getBasePtr();
7362 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7363 if (ST->isIndexed())
7365 VT = ST->getMemoryVT();
7366 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7367 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7369 Ptr = ST->getBasePtr();
7375 if (Ptr.getNode()->hasOneUse())
7378 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7379 E = Ptr.getNode()->use_end(); I != E; ++I) {
7382 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7387 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7388 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7389 // Don't create a indexed load / store with zero offset.
7390 if (isa<ConstantSDNode>(Offset) &&
7391 cast<ConstantSDNode>(Offset)->isNullValue())
7394 // Try turning it into a post-indexed load / store except when
7395 // 1) All uses are load / store ops that use it as base ptr (and
7396 // it may be folded as addressing mmode).
7397 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7398 // nor a successor of N. Otherwise, if Op is folded that would
7401 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7405 bool TryNext = false;
7406 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7407 EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
7409 if (Use == Ptr.getNode())
7412 // If all the uses are load / store addresses, then don't do the
7414 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7415 bool RealUse = false;
7416 for (SDNode::use_iterator III = Use->use_begin(),
7417 EEE = Use->use_end(); III != EEE; ++III) {
7418 SDNode *UseUse = *III;
7419 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7434 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7435 SDValue Result = isLoad
7436 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7437 BasePtr, Offset, AM)
7438 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7439 BasePtr, Offset, AM);
7442 DEBUG(dbgs() << "\nReplacing.5 ";
7444 dbgs() << "\nWith: ";
7445 Result.getNode()->dump(&DAG);
7447 WorkListRemover DeadNodes(*this);
7449 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7450 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7452 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7455 // Finally, since the node is now dead, remove it from the graph.
7458 // Replace the uses of Use with uses of the updated base value.
7459 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7460 Result.getValue(isLoad ? 1 : 0));
7461 removeFromWorkList(Op);
7471 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7472 LoadSDNode *LD = cast<LoadSDNode>(N);
7473 SDValue Chain = LD->getChain();
7474 SDValue Ptr = LD->getBasePtr();
7476 // If load is not volatile and there are no uses of the loaded value (and
7477 // the updated indexed value in case of indexed loads), change uses of the
7478 // chain value into uses of the chain input (i.e. delete the dead load).
7479 if (!LD->isVolatile()) {
7480 if (N->getValueType(1) == MVT::Other) {
7482 if (!N->hasAnyUseOfValue(0)) {
7483 // It's not safe to use the two value CombineTo variant here. e.g.
7484 // v1, chain2 = load chain1, loc
7485 // v2, chain3 = load chain2, loc
7487 // Now we replace use of chain2 with chain1. This makes the second load
7488 // isomorphic to the one we are deleting, and thus makes this load live.
7489 DEBUG(dbgs() << "\nReplacing.6 ";
7491 dbgs() << "\nWith chain: ";
7492 Chain.getNode()->dump(&DAG);
7494 WorkListRemover DeadNodes(*this);
7495 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7497 if (N->use_empty()) {
7498 removeFromWorkList(N);
7502 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7506 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7507 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7508 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7509 DEBUG(dbgs() << "\nReplacing.7 ";
7511 dbgs() << "\nWith: ";
7512 Undef.getNode()->dump(&DAG);
7513 dbgs() << " and 2 other values\n");
7514 WorkListRemover DeadNodes(*this);
7515 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7516 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7517 DAG.getUNDEF(N->getValueType(1)));
7518 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7519 removeFromWorkList(N);
7521 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7526 // If this load is directly stored, replace the load value with the stored
7528 // TODO: Handle store large -> read small portion.
7529 // TODO: Handle TRUNCSTORE/LOADEXT
7530 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7531 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7532 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7533 if (PrevST->getBasePtr() == Ptr &&
7534 PrevST->getValue().getValueType() == N->getValueType(0))
7535 return CombineTo(N, Chain.getOperand(1), Chain);
7539 // Try to infer better alignment information than the load already has.
7540 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7541 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7542 if (Align > LD->getMemOperand()->getBaseAlignment()) {
7544 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7545 LD->getValueType(0),
7546 Chain, Ptr, LD->getPointerInfo(),
7548 LD->isVolatile(), LD->isNonTemporal(), Align);
7549 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7554 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7555 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7557 // Walk up chain skipping non-aliasing memory nodes.
7558 SDValue BetterChain = FindBetterChain(N, Chain);
7560 // If there is a better chain.
7561 if (Chain != BetterChain) {
7564 // Replace the chain to void dependency.
7565 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7566 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7567 BetterChain, Ptr, LD->getPointerInfo(),
7568 LD->isVolatile(), LD->isNonTemporal(),
7569 LD->isInvariant(), LD->getAlignment());
7571 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7572 LD->getValueType(0),
7573 BetterChain, Ptr, LD->getPointerInfo(),
7576 LD->isNonTemporal(),
7577 LD->getAlignment());
7580 // Create token factor to keep old chain connected.
7581 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7582 MVT::Other, Chain, ReplLoad.getValue(1));
7584 // Make sure the new and old chains are cleaned up.
7585 AddToWorkList(Token.getNode());
7587 // Replace uses with load result and token factor. Don't add users
7589 return CombineTo(N, ReplLoad.getValue(0), Token, false);
7593 // Try transforming N to an indexed load.
7594 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7595 return SDValue(N, 0);
7600 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
7601 /// load is having specific bytes cleared out. If so, return the byte size
7602 /// being masked out and the shift amount.
7603 static std::pair<unsigned, unsigned>
7604 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
7605 std::pair<unsigned, unsigned> Result(0, 0);
7607 // Check for the structure we're looking for.
7608 if (V->getOpcode() != ISD::AND ||
7609 !isa<ConstantSDNode>(V->getOperand(1)) ||
7610 !ISD::isNormalLoad(V->getOperand(0).getNode()))
7613 // Check the chain and pointer.
7614 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
7615 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
7617 // The store should be chained directly to the load or be an operand of a
7619 if (LD == Chain.getNode())
7621 else if (Chain->getOpcode() != ISD::TokenFactor)
7622 return Result; // Fail.
7625 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
7626 if (Chain->getOperand(i).getNode() == LD) {
7630 if (!isOk) return Result;
7633 // This only handles simple types.
7634 if (V.getValueType() != MVT::i16 &&
7635 V.getValueType() != MVT::i32 &&
7636 V.getValueType() != MVT::i64)
7639 // Check the constant mask. Invert it so that the bits being masked out are
7640 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
7641 // follow the sign bit for uniformity.
7642 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
7643 unsigned NotMaskLZ = countLeadingZeros(NotMask);
7644 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
7645 unsigned NotMaskTZ = countTrailingZeros(NotMask);
7646 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
7647 if (NotMaskLZ == 64) return Result; // All zero mask.
7649 // See if we have a continuous run of bits. If so, we have 0*1+0*
7650 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
7653 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
7654 if (V.getValueType() != MVT::i64 && NotMaskLZ)
7655 NotMaskLZ -= 64-V.getValueSizeInBits();
7657 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
7658 switch (MaskedBytes) {
7662 default: return Result; // All one mask, or 5-byte mask.
7665 // Verify that the first bit starts at a multiple of mask so that the access
7666 // is aligned the same as the access width.
7667 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
7669 Result.first = MaskedBytes;
7670 Result.second = NotMaskTZ/8;
7675 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
7676 /// provides a value as specified by MaskInfo. If so, replace the specified
7677 /// store with a narrower store of truncated IVal.
7679 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
7680 SDValue IVal, StoreSDNode *St,
7682 unsigned NumBytes = MaskInfo.first;
7683 unsigned ByteShift = MaskInfo.second;
7684 SelectionDAG &DAG = DC->getDAG();
7686 // Check to see if IVal is all zeros in the part being masked in by the 'or'
7687 // that uses this. If not, this is not a replacement.
7688 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
7689 ByteShift*8, (ByteShift+NumBytes)*8);
7690 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
7692 // Check that it is legal on the target to do this. It is legal if the new
7693 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
7695 MVT VT = MVT::getIntegerVT(NumBytes*8);
7696 if (!DC->isTypeLegal(VT))
7699 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
7700 // shifted by ByteShift and truncated down to NumBytes.
7702 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
7703 DAG.getConstant(ByteShift*8,
7704 DC->getShiftAmountTy(IVal.getValueType())));
7706 // Figure out the offset for the store and the alignment of the access.
7708 unsigned NewAlign = St->getAlignment();
7710 if (DAG.getTargetLoweringInfo().isLittleEndian())
7711 StOffset = ByteShift;
7713 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
7715 SDValue Ptr = St->getBasePtr();
7717 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
7718 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
7719 NewAlign = MinAlign(NewAlign, StOffset);
7722 // Truncate down to the new size.
7723 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
7726 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
7727 St->getPointerInfo().getWithOffset(StOffset),
7728 false, false, NewAlign).getNode();
7732 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
7733 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
7734 /// of the loaded bits, try narrowing the load and store if it would end up
7735 /// being a win for performance or code size.
7736 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
7737 StoreSDNode *ST = cast<StoreSDNode>(N);
7738 if (ST->isVolatile())
7741 SDValue Chain = ST->getChain();
7742 SDValue Value = ST->getValue();
7743 SDValue Ptr = ST->getBasePtr();
7744 EVT VT = Value.getValueType();
7746 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
7749 unsigned Opc = Value.getOpcode();
7751 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
7752 // is a byte mask indicating a consecutive number of bytes, check to see if
7753 // Y is known to provide just those bytes. If so, we try to replace the
7754 // load + replace + store sequence with a single (narrower) store, which makes
7756 if (Opc == ISD::OR) {
7757 std::pair<unsigned, unsigned> MaskedLoad;
7758 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
7759 if (MaskedLoad.first)
7760 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
7761 Value.getOperand(1), ST,this))
7762 return SDValue(NewST, 0);
7764 // Or is commutative, so try swapping X and Y.
7765 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
7766 if (MaskedLoad.first)
7767 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
7768 Value.getOperand(0), ST,this))
7769 return SDValue(NewST, 0);
7772 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
7773 Value.getOperand(1).getOpcode() != ISD::Constant)
7776 SDValue N0 = Value.getOperand(0);
7777 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7778 Chain == SDValue(N0.getNode(), 1)) {
7779 LoadSDNode *LD = cast<LoadSDNode>(N0);
7780 if (LD->getBasePtr() != Ptr ||
7781 LD->getPointerInfo().getAddrSpace() !=
7782 ST->getPointerInfo().getAddrSpace())
7785 // Find the type to narrow it the load / op / store to.
7786 SDValue N1 = Value.getOperand(1);
7787 unsigned BitWidth = N1.getValueSizeInBits();
7788 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
7789 if (Opc == ISD::AND)
7790 Imm ^= APInt::getAllOnesValue(BitWidth);
7791 if (Imm == 0 || Imm.isAllOnesValue())
7793 unsigned ShAmt = Imm.countTrailingZeros();
7794 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
7795 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
7796 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
7797 while (NewBW < BitWidth &&
7798 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
7799 TLI.isNarrowingProfitable(VT, NewVT))) {
7800 NewBW = NextPowerOf2(NewBW);
7801 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
7803 if (NewBW >= BitWidth)
7806 // If the lsb changed does not start at the type bitwidth boundary,
7807 // start at the previous one.
7809 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
7810 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
7811 std::min(BitWidth, ShAmt + NewBW));
7812 if ((Imm & Mask) == Imm) {
7813 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
7814 if (Opc == ISD::AND)
7815 NewImm ^= APInt::getAllOnesValue(NewBW);
7816 uint64_t PtrOff = ShAmt / 8;
7817 // For big endian targets, we need to adjust the offset to the pointer to
7818 // load the correct bytes.
7819 if (TLI.isBigEndian())
7820 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
7822 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
7823 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
7824 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
7827 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
7828 Ptr.getValueType(), Ptr,
7829 DAG.getConstant(PtrOff, Ptr.getValueType()));
7830 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
7831 LD->getChain(), NewPtr,
7832 LD->getPointerInfo().getWithOffset(PtrOff),
7833 LD->isVolatile(), LD->isNonTemporal(),
7834 LD->isInvariant(), NewAlign);
7835 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
7836 DAG.getConstant(NewImm, NewVT));
7837 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
7839 ST->getPointerInfo().getWithOffset(PtrOff),
7840 false, false, NewAlign);
7842 AddToWorkList(NewPtr.getNode());
7843 AddToWorkList(NewLD.getNode());
7844 AddToWorkList(NewVal.getNode());
7845 WorkListRemover DeadNodes(*this);
7846 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
7855 /// TransformFPLoadStorePair - For a given floating point load / store pair,
7856 /// if the load value isn't used by any other operations, then consider
7857 /// transforming the pair to integer load / store operations if the target
7858 /// deems the transformation profitable.
7859 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
7860 StoreSDNode *ST = cast<StoreSDNode>(N);
7861 SDValue Chain = ST->getChain();
7862 SDValue Value = ST->getValue();
7863 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
7864 Value.hasOneUse() &&
7865 Chain == SDValue(Value.getNode(), 1)) {
7866 LoadSDNode *LD = cast<LoadSDNode>(Value);
7867 EVT VT = LD->getMemoryVT();
7868 if (!VT.isFloatingPoint() ||
7869 VT != ST->getMemoryVT() ||
7870 LD->isNonTemporal() ||
7871 ST->isNonTemporal() ||
7872 LD->getPointerInfo().getAddrSpace() != 0 ||
7873 ST->getPointerInfo().getAddrSpace() != 0)
7876 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7877 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
7878 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
7879 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
7880 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
7883 unsigned LDAlign = LD->getAlignment();
7884 unsigned STAlign = ST->getAlignment();
7885 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
7886 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
7887 if (LDAlign < ABIAlign || STAlign < ABIAlign)
7890 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
7891 LD->getChain(), LD->getBasePtr(),
7892 LD->getPointerInfo(),
7893 false, false, false, LDAlign);
7895 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
7896 NewLD, ST->getBasePtr(),
7897 ST->getPointerInfo(),
7898 false, false, STAlign);
7900 AddToWorkList(NewLD.getNode());
7901 AddToWorkList(NewST.getNode());
7902 WorkListRemover DeadNodes(*this);
7903 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
7911 /// Helper struct to parse and store a memory address as base + index + offset.
7912 /// We ignore sign extensions when it is safe to do so.
7913 /// The following two expressions are not equivalent. To differentiate we need
7914 /// to store whether there was a sign extension involved in the index
7916 /// (load (i64 add (i64 copyfromreg %c)
7917 /// (i64 signextend (add (i8 load %index)
7921 /// (load (i64 add (i64 copyfromreg %c)
7922 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
7924 struct BaseIndexOffset {
7928 bool IsIndexSignExt;
7930 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
7932 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
7933 bool IsIndexSignExt) :
7934 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
7936 bool equalBaseIndex(const BaseIndexOffset &Other) {
7937 return Other.Base == Base && Other.Index == Index &&
7938 Other.IsIndexSignExt == IsIndexSignExt;
7941 /// Parses tree in Ptr for base, index, offset addresses.
7942 static BaseIndexOffset match(SDValue Ptr) {
7943 bool IsIndexSignExt = false;
7945 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
7946 // instruction, then it could be just the BASE or everything else we don't
7947 // know how to handle. Just use Ptr as BASE and give up.
7948 if (Ptr->getOpcode() != ISD::ADD)
7949 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
7951 // We know that we have at least an ADD instruction. Try to pattern match
7952 // the simple case of BASE + OFFSET.
7953 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
7954 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
7955 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
7959 // Inside a loop the current BASE pointer is calculated using an ADD and a
7960 // MUL instruction. In this case Ptr is the actual BASE pointer.
7961 // (i64 add (i64 %array_ptr)
7962 // (i64 mul (i64 %induction_var)
7963 // (i64 %element_size)))
7964 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
7965 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
7967 // Look at Base + Index + Offset cases.
7968 SDValue Base = Ptr->getOperand(0);
7969 SDValue IndexOffset = Ptr->getOperand(1);
7971 // Skip signextends.
7972 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
7973 IndexOffset = IndexOffset->getOperand(0);
7974 IsIndexSignExt = true;
7977 // Either the case of Base + Index (no offset) or something else.
7978 if (IndexOffset->getOpcode() != ISD::ADD)
7979 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
7981 // Now we have the case of Base + Index + offset.
7982 SDValue Index = IndexOffset->getOperand(0);
7983 SDValue Offset = IndexOffset->getOperand(1);
7985 if (!isa<ConstantSDNode>(Offset))
7986 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
7988 // Ignore signextends.
7989 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
7990 Index = Index->getOperand(0);
7991 IsIndexSignExt = true;
7992 } else IsIndexSignExt = false;
7994 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
7995 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
7999 /// Holds a pointer to an LSBaseSDNode as well as information on where it
8000 /// is located in a sequence of memory operations connected by a chain.
8002 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8003 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8004 // Ptr to the mem node.
8005 LSBaseSDNode *MemNode;
8006 // Offset from the base ptr.
8007 int64_t OffsetFromBase;
8008 // What is the sequence number of this mem node.
8009 // Lowest mem operand in the DAG starts at zero.
8010 unsigned SequenceNum;
8013 /// Sorts store nodes in a link according to their offset from a shared
8015 struct ConsecutiveMemoryChainSorter {
8016 bool operator()(MemOpLink LHS, MemOpLink RHS) {
8017 return LHS.OffsetFromBase < RHS.OffsetFromBase;
8021 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8022 EVT MemVT = St->getMemoryVT();
8023 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
8024 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8025 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
8027 // Don't merge vectors into wider inputs.
8028 if (MemVT.isVector() || !MemVT.isSimple())
8031 // Perform an early exit check. Do not bother looking at stored values that
8032 // are not constants or loads.
8033 SDValue StoredVal = St->getValue();
8034 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8035 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8039 // Only look at ends of store sequences.
8040 SDValue Chain = SDValue(St, 1);
8041 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8044 // This holds the base pointer, index, and the offset in bytes from the base
8046 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
8048 // We must have a base and an offset.
8049 if (!BasePtr.Base.getNode())
8052 // Do not handle stores to undef base pointers.
8053 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
8056 // Save the LoadSDNodes that we find in the chain.
8057 // We need to make sure that these nodes do not interfere with
8058 // any of the store nodes.
8059 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8061 // Save the StoreSDNodes that we find in the chain.
8062 SmallVector<MemOpLink, 8> StoreNodes;
8064 // Walk up the chain and look for nodes with offsets from the same
8065 // base pointer. Stop when reaching an instruction with a different kind
8066 // or instruction which has a different base pointer.
8068 StoreSDNode *Index = St;
8070 // If the chain has more than one use, then we can't reorder the mem ops.
8071 if (Index != St && !SDValue(Index, 1)->hasOneUse())
8074 // Find the base pointer and offset for this memory node.
8075 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
8077 // Check that the base pointer is the same as the original one.
8078 if (!Ptr.equalBaseIndex(BasePtr))
8081 // Check that the alignment is the same.
8082 if (Index->getAlignment() != St->getAlignment())
8085 // The memory operands must not be volatile.
8086 if (Index->isVolatile() || Index->isIndexed())
8090 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
8091 if (St->isTruncatingStore())
8094 // The stored memory type must be the same.
8095 if (Index->getMemoryVT() != MemVT)
8098 // We do not allow unaligned stores because we want to prevent overriding
8100 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
8103 // We found a potential memory operand to merge.
8104 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
8106 // Find the next memory operand in the chain. If the next operand in the
8107 // chain is a store then move up and continue the scan with the next
8108 // memory operand. If the next operand is a load save it and use alias
8109 // information to check if it interferes with anything.
8110 SDNode *NextInChain = Index->getChain().getNode();
8112 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
8113 // We found a store node. Use it for the next iteration.
8116 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
8117 // Save the load node for later. Continue the scan.
8118 AliasLoadNodes.push_back(Ldn);
8119 NextInChain = Ldn->getChain().getNode();
8128 // Check if there is anything to merge.
8129 if (StoreNodes.size() < 2)
8132 // Sort the memory operands according to their distance from the base pointer.
8133 std::sort(StoreNodes.begin(), StoreNodes.end(),
8134 ConsecutiveMemoryChainSorter());
8136 // Scan the memory operations on the chain and find the first non-consecutive
8137 // store memory address.
8138 unsigned LastConsecutiveStore = 0;
8139 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
8140 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
8142 // Check that the addresses are consecutive starting from the second
8143 // element in the list of stores.
8145 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
8146 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8151 // Check if this store interferes with any of the loads that we found.
8152 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
8153 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
8157 // We found a load that alias with this store. Stop the sequence.
8161 // Mark this node as useful.
8162 LastConsecutiveStore = i;
8165 // The node with the lowest store address.
8166 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
8168 // Store the constants into memory as one consecutive store.
8170 unsigned LastLegalType = 0;
8171 unsigned LastLegalVectorType = 0;
8172 bool NonZero = false;
8173 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8174 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8175 SDValue StoredVal = St->getValue();
8177 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
8178 NonZero |= !C->isNullValue();
8179 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
8180 NonZero |= !C->getConstantFPValue()->isNullValue();
8186 // Find a legal type for the constant store.
8187 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8188 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8189 if (TLI.isTypeLegal(StoreTy))
8190 LastLegalType = i+1;
8191 // Or check whether a truncstore is legal.
8192 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8193 TargetLowering::TypePromoteInteger) {
8194 EVT LegalizedStoredValueTy =
8195 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
8196 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
8197 LastLegalType = i+1;
8200 // Find a legal type for the vector store.
8201 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8202 if (TLI.isTypeLegal(Ty))
8203 LastLegalVectorType = i + 1;
8206 // We only use vectors if the constant is known to be zero and the
8207 // function is not marked with the noimplicitfloat attribute.
8208 if (NonZero || NoVectors)
8209 LastLegalVectorType = 0;
8211 // Check if we found a legal integer type to store.
8212 if (LastLegalType == 0 && LastLegalVectorType == 0)
8215 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
8216 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
8218 // Make sure we have something to merge.
8222 unsigned EarliestNodeUsed = 0;
8223 for (unsigned i=0; i < NumElem; ++i) {
8224 // Find a chain for the new wide-store operand. Notice that some
8225 // of the store nodes that we found may not be selected for inclusion
8226 // in the wide store. The chain we use needs to be the chain of the
8227 // earliest store node which is *used* and replaced by the wide store.
8228 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8229 EarliestNodeUsed = i;
8232 // The earliest Node in the DAG.
8233 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8234 SDLoc DL(StoreNodes[0].MemNode);
8238 // Find a legal type for the vector store.
8239 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8240 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
8241 StoredVal = DAG.getConstant(0, Ty);
8243 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8244 APInt StoreInt(StoreBW, 0);
8246 // Construct a single integer constant which is made of the smaller
8248 bool IsLE = TLI.isLittleEndian();
8249 for (unsigned i = 0; i < NumElem ; ++i) {
8250 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
8251 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
8252 SDValue Val = St->getValue();
8253 StoreInt<<=ElementSizeBytes*8;
8254 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
8255 StoreInt|=C->getAPIntValue().zext(StoreBW);
8256 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
8257 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
8259 assert(false && "Invalid constant element type");
8263 // Create the new Load and Store operations.
8264 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8265 StoredVal = DAG.getConstant(StoreInt, StoreTy);
8268 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
8269 FirstInChain->getBasePtr(),
8270 FirstInChain->getPointerInfo(),
8272 FirstInChain->getAlignment());
8274 // Replace the first store with the new store
8275 CombineTo(EarliestOp, NewStore);
8276 // Erase all other stores.
8277 for (unsigned i = 0; i < NumElem ; ++i) {
8278 if (StoreNodes[i].MemNode == EarliestOp)
8280 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8281 // ReplaceAllUsesWith will replace all uses that existed when it was
8282 // called, but graph optimizations may cause new ones to appear. For
8283 // example, the case in pr14333 looks like
8285 // St's chain -> St -> another store -> X
8287 // And the only difference from St to the other store is the chain.
8288 // When we change it's chain to be St's chain they become identical,
8289 // get CSEed and the net result is that X is now a use of St.
8290 // Since we know that St is redundant, just iterate.
8291 while (!St->use_empty())
8292 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
8293 removeFromWorkList(St);
8300 // Below we handle the case of multiple consecutive stores that
8301 // come from multiple consecutive loads. We merge them into a single
8302 // wide load and a single wide store.
8304 // Look for load nodes which are used by the stored values.
8305 SmallVector<MemOpLink, 8> LoadNodes;
8307 // Find acceptable loads. Loads need to have the same chain (token factor),
8308 // must not be zext, volatile, indexed, and they must be consecutive.
8309 BaseIndexOffset LdBasePtr;
8310 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8311 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8312 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
8315 // Loads must only have one use.
8316 if (!Ld->hasNUsesOfValue(1, 0))
8319 // Check that the alignment is the same as the stores.
8320 if (Ld->getAlignment() != St->getAlignment())
8323 // The memory operands must not be volatile.
8324 if (Ld->isVolatile() || Ld->isIndexed())
8327 // We do not accept ext loads.
8328 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
8331 // The stored memory type must be the same.
8332 if (Ld->getMemoryVT() != MemVT)
8335 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
8336 // If this is not the first ptr that we check.
8337 if (LdBasePtr.Base.getNode()) {
8338 // The base ptr must be the same.
8339 if (!LdPtr.equalBaseIndex(LdBasePtr))
8342 // Check that all other base pointers are the same as this one.
8346 // We found a potential memory operand to merge.
8347 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
8350 if (LoadNodes.size() < 2)
8353 // Scan the memory operations on the chain and find the first non-consecutive
8354 // load memory address. These variables hold the index in the store node
8356 unsigned LastConsecutiveLoad = 0;
8357 // This variable refers to the size and not index in the array.
8358 unsigned LastLegalVectorType = 0;
8359 unsigned LastLegalIntegerType = 0;
8360 StartAddress = LoadNodes[0].OffsetFromBase;
8361 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
8362 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
8363 // All loads much share the same chain.
8364 if (LoadNodes[i].MemNode->getChain() != FirstChain)
8367 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
8368 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8370 LastConsecutiveLoad = i;
8372 // Find a legal type for the vector store.
8373 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8374 if (TLI.isTypeLegal(StoreTy))
8375 LastLegalVectorType = i + 1;
8377 // Find a legal type for the integer store.
8378 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8379 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8380 if (TLI.isTypeLegal(StoreTy))
8381 LastLegalIntegerType = i + 1;
8382 // Or check whether a truncstore and extload is legal.
8383 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8384 TargetLowering::TypePromoteInteger) {
8385 EVT LegalizedStoredValueTy =
8386 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
8387 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
8388 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
8389 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
8390 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
8391 LastLegalIntegerType = i+1;
8395 // Only use vector types if the vector type is larger than the integer type.
8396 // If they are the same, use integers.
8397 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
8398 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
8400 // We add +1 here because the LastXXX variables refer to location while
8401 // the NumElem refers to array/index size.
8402 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
8403 NumElem = std::min(LastLegalType, NumElem);
8408 // The earliest Node in the DAG.
8409 unsigned EarliestNodeUsed = 0;
8410 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8411 for (unsigned i=1; i<NumElem; ++i) {
8412 // Find a chain for the new wide-store operand. Notice that some
8413 // of the store nodes that we found may not be selected for inclusion
8414 // in the wide store. The chain we use needs to be the chain of the
8415 // earliest store node which is *used* and replaced by the wide store.
8416 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8417 EarliestNodeUsed = i;
8420 // Find if it is better to use vectors or integers to load and store
8424 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8426 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8427 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8430 SDLoc LoadDL(LoadNodes[0].MemNode);
8431 SDLoc StoreDL(StoreNodes[0].MemNode);
8433 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
8434 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
8435 FirstLoad->getChain(),
8436 FirstLoad->getBasePtr(),
8437 FirstLoad->getPointerInfo(),
8438 false, false, false,
8439 FirstLoad->getAlignment());
8441 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
8442 FirstInChain->getBasePtr(),
8443 FirstInChain->getPointerInfo(), false, false,
8444 FirstInChain->getAlignment());
8446 // Replace one of the loads with the new load.
8447 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
8448 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
8449 SDValue(NewLoad.getNode(), 1));
8451 // Remove the rest of the load chains.
8452 for (unsigned i = 1; i < NumElem ; ++i) {
8453 // Replace all chain users of the old load nodes with the chain of the new
8455 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
8456 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
8459 // Replace the first store with the new store.
8460 CombineTo(EarliestOp, NewStore);
8461 // Erase all other stores.
8462 for (unsigned i = 0; i < NumElem ; ++i) {
8463 // Remove all Store nodes.
8464 if (StoreNodes[i].MemNode == EarliestOp)
8466 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8467 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
8468 removeFromWorkList(St);
8475 SDValue DAGCombiner::visitSTORE(SDNode *N) {
8476 StoreSDNode *ST = cast<StoreSDNode>(N);
8477 SDValue Chain = ST->getChain();
8478 SDValue Value = ST->getValue();
8479 SDValue Ptr = ST->getBasePtr();
8481 // If this is a store of a bit convert, store the input value if the
8482 // resultant store does not need a higher alignment than the original.
8483 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
8484 ST->isUnindexed()) {
8485 unsigned OrigAlign = ST->getAlignment();
8486 EVT SVT = Value.getOperand(0).getValueType();
8487 unsigned Align = TLI.getDataLayout()->
8488 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
8489 if (Align <= OrigAlign &&
8490 ((!LegalOperations && !ST->isVolatile()) ||
8491 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
8492 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
8493 Ptr, ST->getPointerInfo(), ST->isVolatile(),
8494 ST->isNonTemporal(), OrigAlign);
8497 // Turn 'store undef, Ptr' -> nothing.
8498 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
8501 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
8502 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
8503 // NOTE: If the original store is volatile, this transform must not increase
8504 // the number of stores. For example, on x86-32 an f64 can be stored in one
8505 // processor operation but an i64 (which is not legal) requires two. So the
8506 // transform should not be done in this case.
8507 if (Value.getOpcode() != ISD::TargetConstantFP) {
8509 switch (CFP->getSimpleValueType(0).SimpleTy) {
8510 default: llvm_unreachable("Unknown FP type");
8511 case MVT::f16: // We don't do this for these yet.
8517 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
8518 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
8519 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
8520 bitcastToAPInt().getZExtValue(), MVT::i32);
8521 return DAG.getStore(Chain, SDLoc(N), Tmp,
8522 Ptr, ST->getPointerInfo(), ST->isVolatile(),
8523 ST->isNonTemporal(), ST->getAlignment());
8527 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
8528 !ST->isVolatile()) ||
8529 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
8530 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
8531 getZExtValue(), MVT::i64);
8532 return DAG.getStore(Chain, SDLoc(N), Tmp,
8533 Ptr, ST->getPointerInfo(), ST->isVolatile(),
8534 ST->isNonTemporal(), ST->getAlignment());
8537 if (!ST->isVolatile() &&
8538 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
8539 // Many FP stores are not made apparent until after legalize, e.g. for
8540 // argument passing. Since this is so common, custom legalize the
8541 // 64-bit integer store into two 32-bit stores.
8542 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
8543 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
8544 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
8545 if (TLI.isBigEndian()) std::swap(Lo, Hi);
8547 unsigned Alignment = ST->getAlignment();
8548 bool isVolatile = ST->isVolatile();
8549 bool isNonTemporal = ST->isNonTemporal();
8551 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
8552 Ptr, ST->getPointerInfo(),
8553 isVolatile, isNonTemporal,
8554 ST->getAlignment());
8555 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
8556 DAG.getConstant(4, Ptr.getValueType()));
8557 Alignment = MinAlign(Alignment, 4U);
8558 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
8559 Ptr, ST->getPointerInfo().getWithOffset(4),
8560 isVolatile, isNonTemporal,
8562 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
8571 // Try to infer better alignment information than the store already has.
8572 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
8573 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8574 if (Align > ST->getAlignment())
8575 return DAG.getTruncStore(Chain, SDLoc(N), Value,
8576 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
8577 ST->isVolatile(), ST->isNonTemporal(), Align);
8581 // Try transforming a pair floating point load / store ops to integer
8582 // load / store ops.
8583 SDValue NewST = TransformFPLoadStorePair(N);
8584 if (NewST.getNode())
8587 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8588 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
8590 // Walk up chain skipping non-aliasing memory nodes.
8591 SDValue BetterChain = FindBetterChain(N, Chain);
8593 // If there is a better chain.
8594 if (Chain != BetterChain) {
8597 // Replace the chain to avoid dependency.
8598 if (ST->isTruncatingStore()) {
8599 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
8600 ST->getPointerInfo(),
8601 ST->getMemoryVT(), ST->isVolatile(),
8602 ST->isNonTemporal(), ST->getAlignment());
8604 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
8605 ST->getPointerInfo(),
8606 ST->isVolatile(), ST->isNonTemporal(),
8607 ST->getAlignment());
8610 // Create token to keep both nodes around.
8611 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8612 MVT::Other, Chain, ReplStore);
8614 // Make sure the new and old chains are cleaned up.
8615 AddToWorkList(Token.getNode());
8617 // Don't add users to work list.
8618 return CombineTo(N, Token, false);
8622 // Try transforming N to an indexed store.
8623 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8624 return SDValue(N, 0);
8626 // FIXME: is there such a thing as a truncating indexed store?
8627 if (ST->isTruncatingStore() && ST->isUnindexed() &&
8628 Value.getValueType().isInteger()) {
8629 // See if we can simplify the input to this truncstore with knowledge that
8630 // only the low bits are being used. For example:
8631 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
8633 GetDemandedBits(Value,
8634 APInt::getLowBitsSet(
8635 Value.getValueType().getScalarType().getSizeInBits(),
8636 ST->getMemoryVT().getScalarType().getSizeInBits()));
8637 AddToWorkList(Value.getNode());
8638 if (Shorter.getNode())
8639 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
8640 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
8641 ST->isVolatile(), ST->isNonTemporal(),
8642 ST->getAlignment());
8644 // Otherwise, see if we can simplify the operation with
8645 // SimplifyDemandedBits, which only works if the value has a single use.
8646 if (SimplifyDemandedBits(Value,
8647 APInt::getLowBitsSet(
8648 Value.getValueType().getScalarType().getSizeInBits(),
8649 ST->getMemoryVT().getScalarType().getSizeInBits())))
8650 return SDValue(N, 0);
8653 // If this is a load followed by a store to the same location, then the store
8655 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
8656 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
8657 ST->isUnindexed() && !ST->isVolatile() &&
8658 // There can't be any side effects between the load and store, such as
8660 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
8661 // The store is dead, remove it.
8666 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
8667 // truncating store. We can do this even if this is already a truncstore.
8668 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
8669 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
8670 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
8671 ST->getMemoryVT())) {
8672 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
8673 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
8674 ST->isVolatile(), ST->isNonTemporal(),
8675 ST->getAlignment());
8678 // Only perform this optimization before the types are legal, because we
8679 // don't want to perform this optimization on every DAGCombine invocation.
8681 bool EverChanged = false;
8684 // There can be multiple store sequences on the same chain.
8685 // Keep trying to merge store sequences until we are unable to do so
8686 // or until we merge the last store on the chain.
8687 bool Changed = MergeConsecutiveStores(ST);
8688 EverChanged |= Changed;
8689 if (!Changed) break;
8690 } while (ST->getOpcode() != ISD::DELETED_NODE);
8693 return SDValue(N, 0);
8696 return ReduceLoadOpStoreWidth(N);
8699 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
8700 SDValue InVec = N->getOperand(0);
8701 SDValue InVal = N->getOperand(1);
8702 SDValue EltNo = N->getOperand(2);
8705 // If the inserted element is an UNDEF, just use the input vector.
8706 if (InVal.getOpcode() == ISD::UNDEF)
8709 EVT VT = InVec.getValueType();
8711 // If we can't generate a legal BUILD_VECTOR, exit
8712 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
8715 // Check that we know which element is being inserted
8716 if (!isa<ConstantSDNode>(EltNo))
8718 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8720 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
8721 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
8723 SmallVector<SDValue, 8> Ops;
8724 // Do not combine these two vectors if the output vector will not replace
8725 // the input vector.
8726 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
8727 Ops.append(InVec.getNode()->op_begin(),
8728 InVec.getNode()->op_end());
8729 } else if (InVec.getOpcode() == ISD::UNDEF) {
8730 unsigned NElts = VT.getVectorNumElements();
8731 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
8736 // Insert the element
8737 if (Elt < Ops.size()) {
8738 // All the operands of BUILD_VECTOR must have the same type;
8739 // we enforce that here.
8740 EVT OpVT = Ops[0].getValueType();
8741 if (InVal.getValueType() != OpVT)
8742 InVal = OpVT.bitsGT(InVal.getValueType()) ?
8743 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
8744 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
8748 // Return the new vector
8749 return DAG.getNode(ISD::BUILD_VECTOR, dl,
8750 VT, &Ops[0], Ops.size());
8753 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
8754 // (vextract (scalar_to_vector val, 0) -> val
8755 SDValue InVec = N->getOperand(0);
8756 EVT VT = InVec.getValueType();
8757 EVT NVT = N->getValueType(0);
8759 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
8760 // Check if the result type doesn't match the inserted element type. A
8761 // SCALAR_TO_VECTOR may truncate the inserted element and the
8762 // EXTRACT_VECTOR_ELT may widen the extracted vector.
8763 SDValue InOp = InVec.getOperand(0);
8764 if (InOp.getValueType() != NVT) {
8765 assert(InOp.getValueType().isInteger() && NVT.isInteger());
8766 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
8771 SDValue EltNo = N->getOperand(1);
8772 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
8774 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
8775 // We only perform this optimization before the op legalization phase because
8776 // we may introduce new vector instructions which are not backed by TD
8777 // patterns. For example on AVX, extracting elements from a wide vector
8778 // without using extract_subvector.
8779 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
8780 && ConstEltNo && !LegalOperations) {
8781 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8782 int NumElem = VT.getVectorNumElements();
8783 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
8784 // Find the new index to extract from.
8785 int OrigElt = SVOp->getMaskElt(Elt);
8787 // Extracting an undef index is undef.
8789 return DAG.getUNDEF(NVT);
8791 // Select the right vector half to extract from.
8792 if (OrigElt < NumElem) {
8793 InVec = InVec->getOperand(0);
8795 InVec = InVec->getOperand(1);
8799 EVT IndexTy = TLI.getVectorIdxTy();
8800 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
8801 InVec, DAG.getConstant(OrigElt, IndexTy));
8804 // Perform only after legalization to ensure build_vector / vector_shuffle
8805 // optimizations have already been done.
8806 if (!LegalOperations) return SDValue();
8808 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
8809 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
8810 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
8813 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8814 bool NewLoad = false;
8815 bool BCNumEltsChanged = false;
8816 EVT ExtVT = VT.getVectorElementType();
8819 // If the result of load has to be truncated, then it's not necessarily
8821 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
8824 if (InVec.getOpcode() == ISD::BITCAST) {
8825 // Don't duplicate a load with other uses.
8826 if (!InVec.hasOneUse())
8829 EVT BCVT = InVec.getOperand(0).getValueType();
8830 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
8832 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
8833 BCNumEltsChanged = true;
8834 InVec = InVec.getOperand(0);
8835 ExtVT = BCVT.getVectorElementType();
8839 LoadSDNode *LN0 = NULL;
8840 const ShuffleVectorSDNode *SVN = NULL;
8841 if (ISD::isNormalLoad(InVec.getNode())) {
8842 LN0 = cast<LoadSDNode>(InVec);
8843 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8844 InVec.getOperand(0).getValueType() == ExtVT &&
8845 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
8846 // Don't duplicate a load with other uses.
8847 if (!InVec.hasOneUse())
8850 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
8851 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
8852 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
8854 // (load $addr+1*size)
8856 // Don't duplicate a load with other uses.
8857 if (!InVec.hasOneUse())
8860 // If the bit convert changed the number of elements, it is unsafe
8861 // to examine the mask.
8862 if (BCNumEltsChanged)
8865 // Select the input vector, guarding against out of range extract vector.
8866 unsigned NumElems = VT.getVectorNumElements();
8867 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
8868 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
8870 if (InVec.getOpcode() == ISD::BITCAST) {
8871 // Don't duplicate a load with other uses.
8872 if (!InVec.hasOneUse())
8875 InVec = InVec.getOperand(0);
8877 if (ISD::isNormalLoad(InVec.getNode())) {
8878 LN0 = cast<LoadSDNode>(InVec);
8879 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
8883 // Make sure we found a non-volatile load and the extractelement is
8885 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
8888 // If Idx was -1 above, Elt is going to be -1, so just return undef.
8890 return DAG.getUNDEF(LVT);
8892 unsigned Align = LN0->getAlignment();
8894 // Check the resultant load doesn't need a higher alignment than the
8898 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
8900 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
8906 SDValue NewPtr = LN0->getBasePtr();
8907 unsigned PtrOff = 0;
8910 PtrOff = LVT.getSizeInBits() * Elt / 8;
8911 EVT PtrType = NewPtr.getValueType();
8912 if (TLI.isBigEndian())
8913 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
8914 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
8915 DAG.getConstant(PtrOff, PtrType));
8918 // The replacement we need to do here is a little tricky: we need to
8919 // replace an extractelement of a load with a load.
8920 // Use ReplaceAllUsesOfValuesWith to do the replacement.
8921 // Note that this replacement assumes that the extractvalue is the only
8922 // use of the load; that's okay because we don't want to perform this
8923 // transformation in other cases anyway.
8926 if (NVT.bitsGT(LVT)) {
8927 // If the result type of vextract is wider than the load, then issue an
8928 // extending load instead.
8929 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
8930 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
8931 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
8932 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
8933 LVT, LN0->isVolatile(), LN0->isNonTemporal(),Align);
8934 Chain = Load.getValue(1);
8936 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
8937 LN0->getPointerInfo().getWithOffset(PtrOff),
8938 LN0->isVolatile(), LN0->isNonTemporal(),
8939 LN0->isInvariant(), Align);
8940 Chain = Load.getValue(1);
8941 if (NVT.bitsLT(LVT))
8942 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
8944 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
8946 WorkListRemover DeadNodes(*this);
8947 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
8948 SDValue To[] = { Load, Chain };
8949 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8950 // Since we're explcitly calling ReplaceAllUses, add the new node to the
8951 // worklist explicitly as well.
8952 AddToWorkList(Load.getNode());
8953 AddUsersToWorkList(Load.getNode()); // Add users too
8954 // Make sure to revisit this node to clean it up; it will usually be dead.
8956 return SDValue(N, 0);
8962 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
8963 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
8964 // We perform this optimization post type-legalization because
8965 // the type-legalizer often scalarizes integer-promoted vectors.
8966 // Performing this optimization before may create bit-casts which
8967 // will be type-legalized to complex code sequences.
8968 // We perform this optimization only before the operation legalizer because we
8969 // may introduce illegal operations.
8970 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
8973 unsigned NumInScalars = N->getNumOperands();
8975 EVT VT = N->getValueType(0);
8977 // Check to see if this is a BUILD_VECTOR of a bunch of values
8978 // which come from any_extend or zero_extend nodes. If so, we can create
8979 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
8980 // optimizations. We do not handle sign-extend because we can't fill the sign
8982 EVT SourceType = MVT::Other;
8983 bool AllAnyExt = true;
8985 for (unsigned i = 0; i != NumInScalars; ++i) {
8986 SDValue In = N->getOperand(i);
8987 // Ignore undef inputs.
8988 if (In.getOpcode() == ISD::UNDEF) continue;
8990 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
8991 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
8993 // Abort if the element is not an extension.
8994 if (!ZeroExt && !AnyExt) {
8995 SourceType = MVT::Other;
8999 // The input is a ZeroExt or AnyExt. Check the original type.
9000 EVT InTy = In.getOperand(0).getValueType();
9002 // Check that all of the widened source types are the same.
9003 if (SourceType == MVT::Other)
9006 else if (InTy != SourceType) {
9007 // Multiple income types. Abort.
9008 SourceType = MVT::Other;
9012 // Check if all of the extends are ANY_EXTENDs.
9013 AllAnyExt &= AnyExt;
9016 // In order to have valid types, all of the inputs must be extended from the
9017 // same source type and all of the inputs must be any or zero extend.
9018 // Scalar sizes must be a power of two.
9019 EVT OutScalarTy = VT.getScalarType();
9020 bool ValidTypes = SourceType != MVT::Other &&
9021 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9022 isPowerOf2_32(SourceType.getSizeInBits());
9024 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9025 // turn into a single shuffle instruction.
9029 bool isLE = TLI.isLittleEndian();
9030 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
9031 assert(ElemRatio > 1 && "Invalid element size ratio");
9032 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
9033 DAG.getConstant(0, SourceType);
9035 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
9036 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
9038 // Populate the new build_vector
9039 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9040 SDValue Cast = N->getOperand(i);
9041 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
9042 Cast.getOpcode() == ISD::ZERO_EXTEND ||
9043 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
9045 if (Cast.getOpcode() == ISD::UNDEF)
9046 In = DAG.getUNDEF(SourceType);
9048 In = Cast->getOperand(0);
9049 unsigned Index = isLE ? (i * ElemRatio) :
9050 (i * ElemRatio + (ElemRatio - 1));
9052 assert(Index < Ops.size() && "Invalid index");
9056 // The type of the new BUILD_VECTOR node.
9057 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
9058 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
9059 "Invalid vector size");
9060 // Check if the new vector type is legal.
9061 if (!isTypeLegal(VecVT)) return SDValue();
9063 // Make the new BUILD_VECTOR.
9064 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
9066 // The new BUILD_VECTOR node has the potential to be further optimized.
9067 AddToWorkList(BV.getNode());
9068 // Bitcast to the desired type.
9069 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9072 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
9073 EVT VT = N->getValueType(0);
9075 unsigned NumInScalars = N->getNumOperands();
9078 EVT SrcVT = MVT::Other;
9079 unsigned Opcode = ISD::DELETED_NODE;
9080 unsigned NumDefs = 0;
9082 for (unsigned i = 0; i != NumInScalars; ++i) {
9083 SDValue In = N->getOperand(i);
9084 unsigned Opc = In.getOpcode();
9086 if (Opc == ISD::UNDEF)
9089 // If all scalar values are floats and converted from integers.
9090 if (Opcode == ISD::DELETED_NODE &&
9091 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
9098 EVT InVT = In.getOperand(0).getValueType();
9100 // If all scalar values are typed differently, bail out. It's chosen to
9101 // simplify BUILD_VECTOR of integer types.
9102 if (SrcVT == MVT::Other)
9109 // If the vector has just one element defined, it's not worth to fold it into
9110 // a vectorized one.
9114 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
9115 && "Should only handle conversion from integer to float.");
9116 assert(SrcVT != MVT::Other && "Cannot determine source type!");
9118 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
9120 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
9123 SmallVector<SDValue, 8> Opnds;
9124 for (unsigned i = 0; i != NumInScalars; ++i) {
9125 SDValue In = N->getOperand(i);
9127 if (In.getOpcode() == ISD::UNDEF)
9128 Opnds.push_back(DAG.getUNDEF(SrcVT));
9130 Opnds.push_back(In.getOperand(0));
9132 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
9133 &Opnds[0], Opnds.size());
9134 AddToWorkList(BV.getNode());
9136 return DAG.getNode(Opcode, dl, VT, BV);
9139 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
9140 unsigned NumInScalars = N->getNumOperands();
9142 EVT VT = N->getValueType(0);
9144 // A vector built entirely of undefs is undef.
9145 if (ISD::allOperandsUndef(N))
9146 return DAG.getUNDEF(VT);
9148 SDValue V = reduceBuildVecExtToExtBuildVec(N);
9152 V = reduceBuildVecConvertToConvertBuildVec(N);
9156 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
9157 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
9158 // at most two distinct vectors, turn this into a shuffle node.
9160 // May only combine to shuffle after legalize if shuffle is legal.
9161 if (LegalOperations &&
9162 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
9165 SDValue VecIn1, VecIn2;
9166 for (unsigned i = 0; i != NumInScalars; ++i) {
9167 // Ignore undef inputs.
9168 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
9170 // If this input is something other than a EXTRACT_VECTOR_ELT with a
9171 // constant index, bail out.
9172 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9173 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
9174 VecIn1 = VecIn2 = SDValue(0, 0);
9178 // We allow up to two distinct input vectors.
9179 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
9180 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
9183 if (VecIn1.getNode() == 0) {
9184 VecIn1 = ExtractedFromVec;
9185 } else if (VecIn2.getNode() == 0) {
9186 VecIn2 = ExtractedFromVec;
9189 VecIn1 = VecIn2 = SDValue(0, 0);
9194 // If everything is good, we can make a shuffle operation.
9195 if (VecIn1.getNode()) {
9196 SmallVector<int, 8> Mask;
9197 for (unsigned i = 0; i != NumInScalars; ++i) {
9198 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
9203 // If extracting from the first vector, just use the index directly.
9204 SDValue Extract = N->getOperand(i);
9205 SDValue ExtVal = Extract.getOperand(1);
9206 if (Extract.getOperand(0) == VecIn1) {
9207 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9208 if (ExtIndex > VT.getVectorNumElements())
9211 Mask.push_back(ExtIndex);
9215 // Otherwise, use InIdx + VecSize
9216 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9217 Mask.push_back(Idx+NumInScalars);
9220 // We can't generate a shuffle node with mismatched input and output types.
9221 // Attempt to transform a single input vector to the correct type.
9222 if ((VT != VecIn1.getValueType())) {
9223 // We don't support shuffeling between TWO values of different types.
9224 if (VecIn2.getNode() != 0)
9227 // We only support widening of vectors which are half the size of the
9228 // output registers. For example XMM->YMM widening on X86 with AVX.
9229 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
9232 // If the input vector type has a different base type to the output
9233 // vector type, bail out.
9234 if (VecIn1.getValueType().getVectorElementType() !=
9235 VT.getVectorElementType())
9238 // Widen the input vector by adding undef values.
9239 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9240 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
9243 // If VecIn2 is unused then change it to undef.
9244 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
9246 // Check that we were able to transform all incoming values to the same
9248 if (VecIn2.getValueType() != VecIn1.getValueType() ||
9249 VecIn1.getValueType() != VT)
9252 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
9253 if (!isTypeLegal(VT))
9256 // Return the new VECTOR_SHUFFLE node.
9260 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
9266 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
9267 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
9268 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
9269 // inputs come from at most two distinct vectors, turn this into a shuffle
9272 // If we only have one input vector, we don't need to do any concatenation.
9273 if (N->getNumOperands() == 1)
9274 return N->getOperand(0);
9276 // Check if all of the operands are undefs.
9277 if (ISD::allOperandsUndef(N))
9278 return DAG.getUNDEF(N->getValueType(0));
9280 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
9281 // nodes often generate nop CONCAT_VECTOR nodes.
9282 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
9283 // place the incoming vectors at the exact same location.
9284 SDValue SingleSource = SDValue();
9285 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
9287 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9288 SDValue Op = N->getOperand(i);
9290 if (Op.getOpcode() == ISD::UNDEF)
9293 // Check if this is the identity extract:
9294 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
9297 // Find the single incoming vector for the extract_subvector.
9298 if (SingleSource.getNode()) {
9299 if (Op.getOperand(0) != SingleSource)
9302 SingleSource = Op.getOperand(0);
9304 // Check the source type is the same as the type of the result.
9305 // If not, this concat may extend the vector, so we can not
9306 // optimize it away.
9307 if (SingleSource.getValueType() != N->getValueType(0))
9311 unsigned IdentityIndex = i * PartNumElem;
9312 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9313 // The extract index must be constant.
9317 // Check that we are reading from the identity index.
9318 if (CS->getZExtValue() != IdentityIndex)
9322 if (SingleSource.getNode())
9323 return SingleSource;
9328 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
9329 EVT NVT = N->getValueType(0);
9330 SDValue V = N->getOperand(0);
9332 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
9334 // (extract_subvec (concat V1, V2, ...), i)
9337 // Only operand 0 is checked as 'concat' assumes all inputs of the same type.
9338 if (V->getOperand(0).getValueType() != NVT)
9340 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9341 unsigned NumElems = NVT.getVectorNumElements();
9342 assert((Idx % NumElems) == 0 &&
9343 "IDX in concat is not a multiple of the result vector length.");
9344 return V->getOperand(Idx / NumElems);
9348 if (V->getOpcode() == ISD::BITCAST)
9349 V = V.getOperand(0);
9351 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
9353 // Handle only simple case where vector being inserted and vector
9354 // being extracted are of same type, and are half size of larger vectors.
9355 EVT BigVT = V->getOperand(0).getValueType();
9356 EVT SmallVT = V->getOperand(1).getValueType();
9357 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
9360 // Only handle cases where both indexes are constants with the same type.
9361 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
9362 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
9364 if (InsIdx && ExtIdx &&
9365 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
9366 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
9368 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
9370 // indices are equal or bit offsets are equal => V1
9371 // otherwise => (extract_subvec V1, ExtIdx)
9372 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
9373 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
9374 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
9375 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
9376 DAG.getNode(ISD::BITCAST, dl,
9377 N->getOperand(0).getValueType(),
9378 V->getOperand(0)), N->getOperand(1));
9385 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
9386 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
9387 EVT VT = N->getValueType(0);
9388 unsigned NumElts = VT.getVectorNumElements();
9390 SDValue N0 = N->getOperand(0);
9391 SDValue N1 = N->getOperand(1);
9392 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9394 SmallVector<SDValue, 4> Ops;
9395 EVT ConcatVT = N0.getOperand(0).getValueType();
9396 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
9397 unsigned NumConcats = NumElts / NumElemsPerConcat;
9399 // Look at every vector that's inserted. We're looking for exact
9400 // subvector-sized copies from a concatenated vector
9401 for (unsigned I = 0; I != NumConcats; ++I) {
9402 // Make sure we're dealing with a copy.
9403 unsigned Begin = I * NumElemsPerConcat;
9404 bool AllUndef = true, NoUndef = true;
9405 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
9406 if (SVN->getMaskElt(J) >= 0)
9413 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
9416 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
9417 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
9420 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
9421 if (FirstElt < N0.getNumOperands())
9422 Ops.push_back(N0.getOperand(FirstElt));
9424 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
9426 } else if (AllUndef) {
9427 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
9428 } else { // Mixed with general masks and undefs, can't do optimization.
9433 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
9437 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
9438 EVT VT = N->getValueType(0);
9439 unsigned NumElts = VT.getVectorNumElements();
9441 SDValue N0 = N->getOperand(0);
9442 SDValue N1 = N->getOperand(1);
9444 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
9446 // Canonicalize shuffle undef, undef -> undef
9447 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
9448 return DAG.getUNDEF(VT);
9450 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9452 // Canonicalize shuffle v, v -> v, undef
9454 SmallVector<int, 8> NewMask;
9455 for (unsigned i = 0; i != NumElts; ++i) {
9456 int Idx = SVN->getMaskElt(i);
9457 if (Idx >= (int)NumElts) Idx -= NumElts;
9458 NewMask.push_back(Idx);
9460 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
9464 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
9465 if (N0.getOpcode() == ISD::UNDEF) {
9466 SmallVector<int, 8> NewMask;
9467 for (unsigned i = 0; i != NumElts; ++i) {
9468 int Idx = SVN->getMaskElt(i);
9470 if (Idx >= (int)NumElts)
9473 Idx = -1; // remove reference to lhs
9475 NewMask.push_back(Idx);
9477 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
9481 // Remove references to rhs if it is undef
9482 if (N1.getOpcode() == ISD::UNDEF) {
9483 bool Changed = false;
9484 SmallVector<int, 8> NewMask;
9485 for (unsigned i = 0; i != NumElts; ++i) {
9486 int Idx = SVN->getMaskElt(i);
9487 if (Idx >= (int)NumElts) {
9491 NewMask.push_back(Idx);
9494 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
9497 // If it is a splat, check if the argument vector is another splat or a
9498 // build_vector with all scalar elements the same.
9499 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
9500 SDNode *V = N0.getNode();
9502 // If this is a bit convert that changes the element type of the vector but
9503 // not the number of vector elements, look through it. Be careful not to
9504 // look though conversions that change things like v4f32 to v2f64.
9505 if (V->getOpcode() == ISD::BITCAST) {
9506 SDValue ConvInput = V->getOperand(0);
9507 if (ConvInput.getValueType().isVector() &&
9508 ConvInput.getValueType().getVectorNumElements() == NumElts)
9509 V = ConvInput.getNode();
9512 if (V->getOpcode() == ISD::BUILD_VECTOR) {
9513 assert(V->getNumOperands() == NumElts &&
9514 "BUILD_VECTOR has wrong number of operands");
9516 bool AllSame = true;
9517 for (unsigned i = 0; i != NumElts; ++i) {
9518 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
9519 Base = V->getOperand(i);
9523 // Splat of <u, u, u, u>, return <u, u, u, u>
9524 if (!Base.getNode())
9526 for (unsigned i = 0; i != NumElts; ++i) {
9527 if (V->getOperand(i) != Base) {
9532 // Splat of <x, x, x, x>, return <x, x, x, x>
9538 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
9539 Level < AfterLegalizeVectorOps &&
9540 (N1.getOpcode() == ISD::UNDEF ||
9541 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
9542 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
9543 SDValue V = partitionShuffleOfConcats(N, DAG);
9549 // If this shuffle node is simply a swizzle of another shuffle node,
9550 // and it reverses the swizzle of the previous shuffle then we can
9551 // optimize shuffle(shuffle(x, undef), undef) -> x.
9552 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
9553 N1.getOpcode() == ISD::UNDEF) {
9555 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
9557 // Shuffle nodes can only reverse shuffles with a single non-undef value.
9558 if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
9561 // The incoming shuffle must be of the same type as the result of the
9563 assert(OtherSV->getOperand(0).getValueType() == VT &&
9564 "Shuffle types don't match");
9566 for (unsigned i = 0; i != NumElts; ++i) {
9567 int Idx = SVN->getMaskElt(i);
9568 assert(Idx < (int)NumElts && "Index references undef operand");
9569 // Next, this index comes from the first value, which is the incoming
9570 // shuffle. Adopt the incoming index.
9572 Idx = OtherSV->getMaskElt(Idx);
9574 // The combined shuffle must map each index to itself.
9575 if (Idx >= 0 && (unsigned)Idx != i)
9579 return OtherSV->getOperand(0);
9585 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
9586 /// an AND to a vector_shuffle with the destination vector and a zero vector.
9587 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
9588 /// vector_shuffle V, Zero, <0, 4, 2, 4>
9589 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
9590 EVT VT = N->getValueType(0);
9592 SDValue LHS = N->getOperand(0);
9593 SDValue RHS = N->getOperand(1);
9594 if (N->getOpcode() == ISD::AND) {
9595 if (RHS.getOpcode() == ISD::BITCAST)
9596 RHS = RHS.getOperand(0);
9597 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
9598 SmallVector<int, 8> Indices;
9599 unsigned NumElts = RHS.getNumOperands();
9600 for (unsigned i = 0; i != NumElts; ++i) {
9601 SDValue Elt = RHS.getOperand(i);
9602 if (!isa<ConstantSDNode>(Elt))
9605 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
9606 Indices.push_back(i);
9607 else if (cast<ConstantSDNode>(Elt)->isNullValue())
9608 Indices.push_back(NumElts);
9613 // Let's see if the target supports this vector_shuffle.
9614 EVT RVT = RHS.getValueType();
9615 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
9618 // Return the new VECTOR_SHUFFLE node.
9619 EVT EltVT = RVT.getVectorElementType();
9620 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
9621 DAG.getConstant(0, EltVT));
9622 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
9623 RVT, &ZeroOps[0], ZeroOps.size());
9624 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
9625 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
9626 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
9633 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
9634 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
9635 assert(N->getValueType(0).isVector() &&
9636 "SimplifyVBinOp only works on vectors!");
9638 SDValue LHS = N->getOperand(0);
9639 SDValue RHS = N->getOperand(1);
9640 SDValue Shuffle = XformToShuffleWithZero(N);
9641 if (Shuffle.getNode()) return Shuffle;
9643 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
9645 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
9646 RHS.getOpcode() == ISD::BUILD_VECTOR) {
9647 SmallVector<SDValue, 8> Ops;
9648 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
9649 SDValue LHSOp = LHS.getOperand(i);
9650 SDValue RHSOp = RHS.getOperand(i);
9651 // If these two elements can't be folded, bail out.
9652 if ((LHSOp.getOpcode() != ISD::UNDEF &&
9653 LHSOp.getOpcode() != ISD::Constant &&
9654 LHSOp.getOpcode() != ISD::ConstantFP) ||
9655 (RHSOp.getOpcode() != ISD::UNDEF &&
9656 RHSOp.getOpcode() != ISD::Constant &&
9657 RHSOp.getOpcode() != ISD::ConstantFP))
9660 // Can't fold divide by zero.
9661 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
9662 N->getOpcode() == ISD::FDIV) {
9663 if ((RHSOp.getOpcode() == ISD::Constant &&
9664 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
9665 (RHSOp.getOpcode() == ISD::ConstantFP &&
9666 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
9670 EVT VT = LHSOp.getValueType();
9671 EVT RVT = RHSOp.getValueType();
9673 // Integer BUILD_VECTOR operands may have types larger than the element
9674 // size (e.g., when the element type is not legal). Prior to type
9675 // legalization, the types may not match between the two BUILD_VECTORS.
9676 // Truncate one of the operands to make them match.
9677 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
9678 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
9680 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
9684 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
9686 if (FoldOp.getOpcode() != ISD::UNDEF &&
9687 FoldOp.getOpcode() != ISD::Constant &&
9688 FoldOp.getOpcode() != ISD::ConstantFP)
9690 Ops.push_back(FoldOp);
9691 AddToWorkList(FoldOp.getNode());
9694 if (Ops.size() == LHS.getNumOperands())
9695 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
9696 LHS.getValueType(), &Ops[0], Ops.size());
9702 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
9703 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
9704 assert(N->getValueType(0).isVector() &&
9705 "SimplifyVUnaryOp only works on vectors!");
9707 SDValue N0 = N->getOperand(0);
9709 if (N0.getOpcode() != ISD::BUILD_VECTOR)
9712 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
9713 SmallVector<SDValue, 8> Ops;
9714 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
9715 SDValue Op = N0.getOperand(i);
9716 if (Op.getOpcode() != ISD::UNDEF &&
9717 Op.getOpcode() != ISD::ConstantFP)
9719 EVT EltVT = Op.getValueType();
9720 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
9721 if (FoldOp.getOpcode() != ISD::UNDEF &&
9722 FoldOp.getOpcode() != ISD::ConstantFP)
9724 Ops.push_back(FoldOp);
9725 AddToWorkList(FoldOp.getNode());
9728 if (Ops.size() != N0.getNumOperands())
9731 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
9732 N0.getValueType(), &Ops[0], Ops.size());
9735 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
9736 SDValue N1, SDValue N2){
9737 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
9739 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
9740 cast<CondCodeSDNode>(N0.getOperand(2))->get());
9742 // If we got a simplified select_cc node back from SimplifySelectCC, then
9743 // break it down into a new SETCC node, and a new SELECT node, and then return
9744 // the SELECT node, since we were called with a SELECT node.
9745 if (SCC.getNode()) {
9746 // Check to see if we got a select_cc back (to turn into setcc/select).
9747 // Otherwise, just return whatever node we got back, like fabs.
9748 if (SCC.getOpcode() == ISD::SELECT_CC) {
9749 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
9751 SCC.getOperand(0), SCC.getOperand(1),
9753 AddToWorkList(SETCC.getNode());
9754 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
9755 SCC.getOperand(2), SCC.getOperand(3), SETCC);
9763 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
9764 /// are the two values being selected between, see if we can simplify the
9765 /// select. Callers of this should assume that TheSelect is deleted if this
9766 /// returns true. As such, they should return the appropriate thing (e.g. the
9767 /// node) back to the top-level of the DAG combiner loop to avoid it being
9769 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
9772 // Cannot simplify select with vector condition
9773 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
9775 // If this is a select from two identical things, try to pull the operation
9776 // through the select.
9777 if (LHS.getOpcode() != RHS.getOpcode() ||
9778 !LHS.hasOneUse() || !RHS.hasOneUse())
9781 // If this is a load and the token chain is identical, replace the select
9782 // of two loads with a load through a select of the address to load from.
9783 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
9784 // constants have been dropped into the constant pool.
9785 if (LHS.getOpcode() == ISD::LOAD) {
9786 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
9787 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
9789 // Token chains must be identical.
9790 if (LHS.getOperand(0) != RHS.getOperand(0) ||
9791 // Do not let this transformation reduce the number of volatile loads.
9792 LLD->isVolatile() || RLD->isVolatile() ||
9793 // If this is an EXTLOAD, the VT's must match.
9794 LLD->getMemoryVT() != RLD->getMemoryVT() ||
9795 // If this is an EXTLOAD, the kind of extension must match.
9796 (LLD->getExtensionType() != RLD->getExtensionType() &&
9797 // The only exception is if one of the extensions is anyext.
9798 LLD->getExtensionType() != ISD::EXTLOAD &&
9799 RLD->getExtensionType() != ISD::EXTLOAD) ||
9800 // FIXME: this discards src value information. This is
9801 // over-conservative. It would be beneficial to be able to remember
9802 // both potential memory locations. Since we are discarding
9803 // src value info, don't do the transformation if the memory
9804 // locations are not in the default address space.
9805 LLD->getPointerInfo().getAddrSpace() != 0 ||
9806 RLD->getPointerInfo().getAddrSpace() != 0 ||
9807 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
9808 LLD->getBasePtr().getValueType()))
9811 // Check that the select condition doesn't reach either load. If so,
9812 // folding this will induce a cycle into the DAG. If not, this is safe to
9813 // xform, so create a select of the addresses.
9815 if (TheSelect->getOpcode() == ISD::SELECT) {
9816 SDNode *CondNode = TheSelect->getOperand(0).getNode();
9817 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
9818 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
9820 // The loads must not depend on one another.
9821 if (LLD->isPredecessorOf(RLD) ||
9822 RLD->isPredecessorOf(LLD))
9824 Addr = DAG.getSelect(SDLoc(TheSelect),
9825 LLD->getBasePtr().getValueType(),
9826 TheSelect->getOperand(0), LLD->getBasePtr(),
9828 } else { // Otherwise SELECT_CC
9829 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
9830 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
9832 if ((LLD->hasAnyUseOfValue(1) &&
9833 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
9834 (RLD->hasAnyUseOfValue(1) &&
9835 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
9838 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
9839 LLD->getBasePtr().getValueType(),
9840 TheSelect->getOperand(0),
9841 TheSelect->getOperand(1),
9842 LLD->getBasePtr(), RLD->getBasePtr(),
9843 TheSelect->getOperand(4));
9847 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
9848 Load = DAG.getLoad(TheSelect->getValueType(0),
9850 // FIXME: Discards pointer info.
9851 LLD->getChain(), Addr, MachinePointerInfo(),
9852 LLD->isVolatile(), LLD->isNonTemporal(),
9853 LLD->isInvariant(), LLD->getAlignment());
9855 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
9856 RLD->getExtensionType() : LLD->getExtensionType(),
9858 TheSelect->getValueType(0),
9859 // FIXME: Discards pointer info.
9860 LLD->getChain(), Addr, MachinePointerInfo(),
9861 LLD->getMemoryVT(), LLD->isVolatile(),
9862 LLD->isNonTemporal(), LLD->getAlignment());
9865 // Users of the select now use the result of the load.
9866 CombineTo(TheSelect, Load);
9868 // Users of the old loads now use the new load's chain. We know the
9869 // old-load value is dead now.
9870 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
9871 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
9878 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
9879 /// where 'cond' is the comparison specified by CC.
9880 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
9881 SDValue N2, SDValue N3,
9882 ISD::CondCode CC, bool NotExtCompare) {
9883 // (x ? y : y) -> y.
9884 if (N2 == N3) return N2;
9886 EVT VT = N2.getValueType();
9887 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
9888 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
9889 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
9891 // Determine if the condition we're dealing with is constant
9892 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
9893 N0, N1, CC, DL, false);
9894 if (SCC.getNode()) AddToWorkList(SCC.getNode());
9895 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
9897 // fold select_cc true, x, y -> x
9898 if (SCCC && !SCCC->isNullValue())
9900 // fold select_cc false, x, y -> y
9901 if (SCCC && SCCC->isNullValue())
9904 // Check to see if we can simplify the select into an fabs node
9905 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
9906 // Allow either -0.0 or 0.0
9907 if (CFP->getValueAPF().isZero()) {
9908 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
9909 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
9910 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
9911 N2 == N3.getOperand(0))
9912 return DAG.getNode(ISD::FABS, DL, VT, N0);
9914 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
9915 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
9916 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
9917 N2.getOperand(0) == N3)
9918 return DAG.getNode(ISD::FABS, DL, VT, N3);
9922 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
9923 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
9924 // in it. This is a win when the constant is not otherwise available because
9925 // it replaces two constant pool loads with one. We only do this if the FP
9926 // type is known to be legal, because if it isn't, then we are before legalize
9927 // types an we want the other legalization to happen first (e.g. to avoid
9928 // messing with soft float) and if the ConstantFP is not legal, because if
9929 // it is legal, we may not need to store the FP constant in a constant pool.
9930 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
9931 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
9932 if (TLI.isTypeLegal(N2.getValueType()) &&
9933 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
9934 TargetLowering::Legal) &&
9935 // If both constants have multiple uses, then we won't need to do an
9936 // extra load, they are likely around in registers for other users.
9937 (TV->hasOneUse() || FV->hasOneUse())) {
9938 Constant *Elts[] = {
9939 const_cast<ConstantFP*>(FV->getConstantFPValue()),
9940 const_cast<ConstantFP*>(TV->getConstantFPValue())
9942 Type *FPTy = Elts[0]->getType();
9943 const DataLayout &TD = *TLI.getDataLayout();
9945 // Create a ConstantArray of the two constants.
9946 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
9947 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
9948 TD.getPrefTypeAlignment(FPTy));
9949 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9951 // Get the offsets to the 0 and 1 element of the array so that we can
9952 // select between them.
9953 SDValue Zero = DAG.getIntPtrConstant(0);
9954 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
9955 SDValue One = DAG.getIntPtrConstant(EltSize);
9957 SDValue Cond = DAG.getSetCC(DL,
9958 getSetCCResultType(N0.getValueType()),
9960 AddToWorkList(Cond.getNode());
9961 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
9963 AddToWorkList(CstOffset.getNode());
9964 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
9966 AddToWorkList(CPIdx.getNode());
9967 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
9968 MachinePointerInfo::getConstantPool(), false,
9969 false, false, Alignment);
9974 // Check to see if we can perform the "gzip trick", transforming
9975 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
9976 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
9977 (N1C->isNullValue() || // (a < 0) ? b : 0
9978 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
9979 EVT XType = N0.getValueType();
9980 EVT AType = N2.getValueType();
9981 if (XType.bitsGE(AType)) {
9982 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
9983 // single-bit constant.
9984 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
9985 unsigned ShCtV = N2C->getAPIntValue().logBase2();
9986 ShCtV = XType.getSizeInBits()-ShCtV-1;
9987 SDValue ShCt = DAG.getConstant(ShCtV,
9988 getShiftAmountTy(N0.getValueType()));
9989 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
9991 AddToWorkList(Shift.getNode());
9993 if (XType.bitsGT(AType)) {
9994 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
9995 AddToWorkList(Shift.getNode());
9998 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
10001 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
10003 DAG.getConstant(XType.getSizeInBits()-1,
10004 getShiftAmountTy(N0.getValueType())));
10005 AddToWorkList(Shift.getNode());
10007 if (XType.bitsGT(AType)) {
10008 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
10009 AddToWorkList(Shift.getNode());
10012 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
10016 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
10017 // where y is has a single bit set.
10018 // A plaintext description would be, we can turn the SELECT_CC into an AND
10019 // when the condition can be materialized as an all-ones register. Any
10020 // single bit-test can be materialized as an all-ones register with
10021 // shift-left and shift-right-arith.
10022 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
10023 N0->getValueType(0) == VT &&
10024 N1C && N1C->isNullValue() &&
10025 N2C && N2C->isNullValue()) {
10026 SDValue AndLHS = N0->getOperand(0);
10027 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
10028 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
10029 // Shift the tested bit over the sign bit.
10030 APInt AndMask = ConstAndRHS->getAPIntValue();
10032 DAG.getConstant(AndMask.countLeadingZeros(),
10033 getShiftAmountTy(AndLHS.getValueType()));
10034 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
10036 // Now arithmetic right shift it all the way over, so the result is either
10037 // all-ones, or zero.
10039 DAG.getConstant(AndMask.getBitWidth()-1,
10040 getShiftAmountTy(Shl.getValueType()));
10041 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
10043 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
10047 // fold select C, 16, 0 -> shl C, 4
10048 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
10049 TLI.getBooleanContents(N0.getValueType().isVector()) ==
10050 TargetLowering::ZeroOrOneBooleanContent) {
10052 // If the caller doesn't want us to simplify this into a zext of a compare,
10054 if (NotExtCompare && N2C->getAPIntValue() == 1)
10057 // Get a SetCC of the condition
10058 // NOTE: Don't create a SETCC if it's not legal on this target.
10059 if (!LegalOperations ||
10060 TLI.isOperationLegal(ISD::SETCC,
10061 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
10063 // cast from setcc result type to select result type
10065 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
10067 if (N2.getValueType().bitsLT(SCC.getValueType()))
10068 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
10069 N2.getValueType());
10071 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10072 N2.getValueType(), SCC);
10074 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
10075 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10076 N2.getValueType(), SCC);
10079 AddToWorkList(SCC.getNode());
10080 AddToWorkList(Temp.getNode());
10082 if (N2C->getAPIntValue() == 1)
10085 // shl setcc result by log2 n2c
10086 return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
10087 DAG.getConstant(N2C->getAPIntValue().logBase2(),
10088 getShiftAmountTy(Temp.getValueType())));
10092 // Check to see if this is the equivalent of setcc
10093 // FIXME: Turn all of these into setcc if setcc if setcc is legal
10094 // otherwise, go ahead with the folds.
10095 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
10096 EVT XType = N0.getValueType();
10097 if (!LegalOperations ||
10098 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
10099 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
10100 if (Res.getValueType() != VT)
10101 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
10105 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
10106 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
10107 (!LegalOperations ||
10108 TLI.isOperationLegal(ISD::CTLZ, XType))) {
10109 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
10110 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
10111 DAG.getConstant(Log2_32(XType.getSizeInBits()),
10112 getShiftAmountTy(Ctlz.getValueType())));
10114 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
10115 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
10116 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
10117 XType, DAG.getConstant(0, XType), N0);
10118 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
10119 return DAG.getNode(ISD::SRL, DL, XType,
10120 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
10121 DAG.getConstant(XType.getSizeInBits()-1,
10122 getShiftAmountTy(XType)));
10124 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
10125 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
10126 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
10127 DAG.getConstant(XType.getSizeInBits()-1,
10128 getShiftAmountTy(N0.getValueType())));
10129 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
10133 // Check to see if this is an integer abs.
10134 // select_cc setg[te] X, 0, X, -X ->
10135 // select_cc setgt X, -1, X, -X ->
10136 // select_cc setl[te] X, 0, -X, X ->
10137 // select_cc setlt X, 1, -X, X ->
10138 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
10140 ConstantSDNode *SubC = NULL;
10141 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
10142 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
10143 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
10144 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
10145 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
10146 (N1C->isOne() && CC == ISD::SETLT)) &&
10147 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
10148 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
10150 EVT XType = N0.getValueType();
10151 if (SubC && SubC->isNullValue() && XType.isInteger()) {
10152 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
10154 DAG.getConstant(XType.getSizeInBits()-1,
10155 getShiftAmountTy(N0.getValueType())));
10156 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
10158 AddToWorkList(Shift.getNode());
10159 AddToWorkList(Add.getNode());
10160 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
10167 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
10168 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
10169 SDValue N1, ISD::CondCode Cond,
10170 SDLoc DL, bool foldBooleans) {
10171 TargetLowering::DAGCombinerInfo
10172 DagCombineInfo(DAG, Level, false, this);
10173 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
10176 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
10177 /// return a DAG expression to select that will generate the same value by
10178 /// multiplying by a magic number. See:
10179 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10180 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
10181 std::vector<SDNode*> Built;
10182 SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
10184 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10186 AddToWorkList(*ii);
10190 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
10191 /// return a DAG expression to select that will generate the same value by
10192 /// multiplying by a magic number. See:
10193 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10194 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
10195 std::vector<SDNode*> Built;
10196 SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
10198 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10200 AddToWorkList(*ii);
10204 /// FindBaseOffset - Return true if base is a frame index, which is known not
10205 // to alias with anything but itself. Provides base object and offset as
10207 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
10208 const GlobalValue *&GV, const void *&CV) {
10209 // Assume it is a primitive operation.
10210 Base = Ptr; Offset = 0; GV = 0; CV = 0;
10212 // If it's an adding a simple constant then integrate the offset.
10213 if (Base.getOpcode() == ISD::ADD) {
10214 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
10215 Base = Base.getOperand(0);
10216 Offset += C->getZExtValue();
10220 // Return the underlying GlobalValue, and update the Offset. Return false
10221 // for GlobalAddressSDNode since the same GlobalAddress may be represented
10222 // by multiple nodes with different offsets.
10223 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
10224 GV = G->getGlobal();
10225 Offset += G->getOffset();
10229 // Return the underlying Constant value, and update the Offset. Return false
10230 // for ConstantSDNodes since the same constant pool entry may be represented
10231 // by multiple nodes with different offsets.
10232 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
10233 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
10234 : (const void *)C->getConstVal();
10235 Offset += C->getOffset();
10238 // If it's any of the following then it can't alias with anything but itself.
10239 return isa<FrameIndexSDNode>(Base);
10242 /// isAlias - Return true if there is any possibility that the two addresses
10244 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
10245 const Value *SrcValue1, int SrcValueOffset1,
10246 unsigned SrcValueAlign1,
10247 const MDNode *TBAAInfo1,
10248 SDValue Ptr2, int64_t Size2,
10249 const Value *SrcValue2, int SrcValueOffset2,
10250 unsigned SrcValueAlign2,
10251 const MDNode *TBAAInfo2) const {
10252 // If they are the same then they must be aliases.
10253 if (Ptr1 == Ptr2) return true;
10255 // Gather base node and offset information.
10256 SDValue Base1, Base2;
10257 int64_t Offset1, Offset2;
10258 const GlobalValue *GV1, *GV2;
10259 const void *CV1, *CV2;
10260 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
10261 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
10263 // If they have a same base address then check to see if they overlap.
10264 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
10265 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
10267 // It is possible for different frame indices to alias each other, mostly
10268 // when tail call optimization reuses return address slots for arguments.
10269 // To catch this case, look up the actual index of frame indices to compute
10270 // the real alias relationship.
10271 if (isFrameIndex1 && isFrameIndex2) {
10272 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10273 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
10274 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
10275 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
10278 // Otherwise, if we know what the bases are, and they aren't identical, then
10279 // we know they cannot alias.
10280 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
10283 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
10284 // compared to the size and offset of the access, we may be able to prove they
10285 // do not alias. This check is conservative for now to catch cases created by
10286 // splitting vector types.
10287 if ((SrcValueAlign1 == SrcValueAlign2) &&
10288 (SrcValueOffset1 != SrcValueOffset2) &&
10289 (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
10290 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
10291 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
10293 // There is no overlap between these relatively aligned accesses of similar
10294 // size, return no alias.
10295 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
10299 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
10300 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
10301 if (UseAA && SrcValue1 && SrcValue2) {
10302 // Use alias analysis information.
10303 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
10304 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
10305 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
10306 AliasAnalysis::AliasResult AAResult =
10307 AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
10308 AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
10309 if (AAResult == AliasAnalysis::NoAlias)
10313 // Otherwise we have to assume they alias.
10317 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
10318 SDValue Ptr0, Ptr1;
10319 int64_t Size0, Size1;
10320 const Value *SrcValue0, *SrcValue1;
10321 int SrcValueOffset0, SrcValueOffset1;
10322 unsigned SrcValueAlign0, SrcValueAlign1;
10323 const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
10324 FindAliasInfo(Op0, Ptr0, Size0, SrcValue0, SrcValueOffset0,
10325 SrcValueAlign0, SrcTBAAInfo0);
10326 FindAliasInfo(Op1, Ptr1, Size1, SrcValue1, SrcValueOffset1,
10327 SrcValueAlign1, SrcTBAAInfo1);
10328 return isAlias(Ptr0, Size0, SrcValue0, SrcValueOffset0,
10329 SrcValueAlign0, SrcTBAAInfo0,
10330 Ptr1, Size1, SrcValue1, SrcValueOffset1,
10331 SrcValueAlign1, SrcTBAAInfo1);
10334 /// FindAliasInfo - Extracts the relevant alias information from the memory
10335 /// node. Returns true if the operand was a load.
10336 bool DAGCombiner::FindAliasInfo(SDNode *N,
10337 SDValue &Ptr, int64_t &Size,
10338 const Value *&SrcValue,
10339 int &SrcValueOffset,
10340 unsigned &SrcValueAlign,
10341 const MDNode *&TBAAInfo) const {
10342 LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
10344 Ptr = LS->getBasePtr();
10345 Size = LS->getMemoryVT().getSizeInBits() >> 3;
10346 SrcValue = LS->getSrcValue();
10347 SrcValueOffset = LS->getSrcValueOffset();
10348 SrcValueAlign = LS->getOriginalAlignment();
10349 TBAAInfo = LS->getTBAAInfo();
10350 return isa<LoadSDNode>(LS);
10353 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
10354 /// looking for aliasing nodes and adding them to the Aliases vector.
10355 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
10356 SmallVectorImpl<SDValue> &Aliases) {
10357 SmallVector<SDValue, 8> Chains; // List of chains to visit.
10358 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
10360 // Get alias information for node.
10363 const Value *SrcValue;
10364 int SrcValueOffset;
10365 unsigned SrcValueAlign;
10366 const MDNode *SrcTBAAInfo;
10367 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset,
10368 SrcValueAlign, SrcTBAAInfo);
10371 Chains.push_back(OriginalChain);
10372 unsigned Depth = 0;
10374 // Look at each chain and determine if it is an alias. If so, add it to the
10375 // aliases list. If not, then continue up the chain looking for the next
10377 while (!Chains.empty()) {
10378 SDValue Chain = Chains.back();
10381 // For TokenFactor nodes, look at each operand and only continue up the
10382 // chain until we find two aliases. If we've seen two aliases, assume we'll
10383 // find more and revert to original chain since the xform is unlikely to be
10386 // FIXME: The depth check could be made to return the last non-aliasing
10387 // chain we found before we hit a tokenfactor rather than the original
10389 if (Depth > 6 || Aliases.size() == 2) {
10391 Aliases.push_back(OriginalChain);
10395 // Don't bother if we've been before.
10396 if (!Visited.insert(Chain.getNode()))
10399 switch (Chain.getOpcode()) {
10400 case ISD::EntryToken:
10401 // Entry token is ideal chain operand, but handled in FindBetterChain.
10406 // Get alias information for Chain.
10409 const Value *OpSrcValue;
10410 int OpSrcValueOffset;
10411 unsigned OpSrcValueAlign;
10412 const MDNode *OpSrcTBAAInfo;
10413 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
10414 OpSrcValue, OpSrcValueOffset,
10418 // If chain is alias then stop here.
10419 if (!(IsLoad && IsOpLoad) &&
10420 isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign,
10422 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset,
10423 OpSrcValueAlign, OpSrcTBAAInfo)) {
10424 Aliases.push_back(Chain);
10426 // Look further up the chain.
10427 Chains.push_back(Chain.getOperand(0));
10433 case ISD::TokenFactor:
10434 // We have to check each of the operands of the token factor for "small"
10435 // token factors, so we queue them up. Adding the operands to the queue
10436 // (stack) in reverse order maintains the original order and increases the
10437 // likelihood that getNode will find a matching token factor (CSE.)
10438 if (Chain.getNumOperands() > 16) {
10439 Aliases.push_back(Chain);
10442 for (unsigned n = Chain.getNumOperands(); n;)
10443 Chains.push_back(Chain.getOperand(--n));
10448 // For all other instructions we will just have to take what we can get.
10449 Aliases.push_back(Chain);
10455 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
10456 /// for a better chain (aliasing node.)
10457 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
10458 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
10460 // Accumulate all the aliases to this node.
10461 GatherAllAliases(N, OldChain, Aliases);
10463 // If no operands then chain to entry token.
10464 if (Aliases.size() == 0)
10465 return DAG.getEntryNode();
10467 // If a single operand then chain to it. We don't need to revisit it.
10468 if (Aliases.size() == 1)
10471 // Construct a custom tailored token factor.
10472 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
10473 &Aliases[0], Aliases.size());
10476 // SelectionDAG::Combine - This is the entry point for the file.
10478 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
10479 CodeGenOpt::Level OptLevel) {
10480 /// run - This is the main entry point to this class.
10482 DAGCombiner(*this, AA, OptLevel).Run(Level);