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/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
43 STATISTIC(NodesCombined , "Number of dag nodes combined");
44 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
45 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
46 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
47 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
48 STATISTIC(SlicedLoads, "Number of load sliced");
52 CombinerAA("combiner-alias-analysis", cl::Hidden,
53 cl::desc("Enable DAG combiner alias-analysis heuristics"));
56 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
57 cl::desc("Enable DAG combiner's use of IR alias analysis"));
59 // FIXME: Enable the use of TBAA. There are two known issues preventing this:
60 // 1. Stack coloring does not update TBAA when merging allocas
61 // 2. CGP inserts ptrtoint/inttoptr pairs when sinking address computations.
62 // Because BasicAA does not handle inttoptr, we'll often miss basic type
63 // punning idioms that we need to catch so we don't miscompile real-world
66 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(false),
67 cl::desc("Enable DAG combiner's use of TBAA"));
70 static cl::opt<std::string>
71 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
72 cl::desc("Only use DAG-combiner alias analysis in this"
76 /// Hidden option to stress test load slicing, i.e., when this option
77 /// is enabled, load slicing bypasses most of its profitability guards.
79 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
80 cl::desc("Bypass the profitability model of load "
84 //------------------------------ DAGCombiner ---------------------------------//
88 const TargetLowering &TLI;
90 CodeGenOpt::Level OptLevel;
95 // Worklist of all of the nodes that need to be simplified.
97 // This has the semantics that when adding to the worklist,
98 // the item added must be next to be processed. It should
99 // also only appear once. The naive approach to this takes
102 // To reduce the insert/remove time to logarithmic, we use
103 // a set and a vector to maintain our worklist.
105 // The set contains the items on the worklist, but does not
106 // maintain the order they should be visited.
108 // The vector maintains the order nodes should be visited, but may
109 // contain duplicate or removed nodes. When choosing a node to
110 // visit, we pop off the order stack until we find an item that is
111 // also in the contents set. All operations are O(log N).
112 SmallPtrSet<SDNode*, 64> WorkListContents;
113 SmallVector<SDNode*, 64> WorkListOrder;
115 // AA - Used for DAG load/store alias analysis.
118 /// AddUsersToWorkList - When an instruction is simplified, add all users of
119 /// the instruction to the work lists because they might get more simplified
122 void AddUsersToWorkList(SDNode *N) {
123 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
128 /// visit - call the node-specific routine that knows how to fold each
129 /// particular type of node.
130 SDValue visit(SDNode *N);
133 /// AddToWorkList - Add to the work list making sure its instance is at the
134 /// back (next to be processed.)
135 void AddToWorkList(SDNode *N) {
136 WorkListContents.insert(N);
137 WorkListOrder.push_back(N);
140 /// removeFromWorkList - remove all instances of N from the worklist.
142 void removeFromWorkList(SDNode *N) {
143 WorkListContents.erase(N);
146 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
149 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
150 return CombineTo(N, &Res, 1, AddTo);
153 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
155 SDValue To[] = { Res0, Res1 };
156 return CombineTo(N, To, 2, AddTo);
159 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
163 /// SimplifyDemandedBits - Check the specified integer node value to see if
164 /// it can be simplified or if things it uses can be simplified by bit
165 /// propagation. If so, return true.
166 bool SimplifyDemandedBits(SDValue Op) {
167 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
168 APInt Demanded = APInt::getAllOnesValue(BitWidth);
169 return SimplifyDemandedBits(Op, Demanded);
172 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
174 bool CombineToPreIndexedLoadStore(SDNode *N);
175 bool CombineToPostIndexedLoadStore(SDNode *N);
176 bool SliceUpLoad(SDNode *N);
178 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
179 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
180 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
181 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
182 SDValue PromoteIntBinOp(SDValue Op);
183 SDValue PromoteIntShiftOp(SDValue Op);
184 SDValue PromoteExtend(SDValue Op);
185 bool PromoteLoad(SDValue Op);
187 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
188 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
189 ISD::NodeType ExtType);
191 /// combine - call the node-specific routine that knows how to fold each
192 /// particular type of node. If that doesn't do anything, try the
193 /// target-specific DAG combines.
194 SDValue combine(SDNode *N);
196 // Visitation implementation - Implement dag node combining for different
197 // node types. The semantics are as follows:
199 // SDValue.getNode() == 0 - No change was made
200 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
201 // otherwise - N should be replaced by the returned Operand.
203 SDValue visitTokenFactor(SDNode *N);
204 SDValue visitMERGE_VALUES(SDNode *N);
205 SDValue visitADD(SDNode *N);
206 SDValue visitSUB(SDNode *N);
207 SDValue visitADDC(SDNode *N);
208 SDValue visitSUBC(SDNode *N);
209 SDValue visitADDE(SDNode *N);
210 SDValue visitSUBE(SDNode *N);
211 SDValue visitMUL(SDNode *N);
212 SDValue visitSDIV(SDNode *N);
213 SDValue visitUDIV(SDNode *N);
214 SDValue visitSREM(SDNode *N);
215 SDValue visitUREM(SDNode *N);
216 SDValue visitMULHU(SDNode *N);
217 SDValue visitMULHS(SDNode *N);
218 SDValue visitSMUL_LOHI(SDNode *N);
219 SDValue visitUMUL_LOHI(SDNode *N);
220 SDValue visitSMULO(SDNode *N);
221 SDValue visitUMULO(SDNode *N);
222 SDValue visitSDIVREM(SDNode *N);
223 SDValue visitUDIVREM(SDNode *N);
224 SDValue visitAND(SDNode *N);
225 SDValue visitOR(SDNode *N);
226 SDValue visitXOR(SDNode *N);
227 SDValue SimplifyVBinOp(SDNode *N);
228 SDValue SimplifyVUnaryOp(SDNode *N);
229 SDValue visitSHL(SDNode *N);
230 SDValue visitSRA(SDNode *N);
231 SDValue visitSRL(SDNode *N);
232 SDValue visitCTLZ(SDNode *N);
233 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
234 SDValue visitCTTZ(SDNode *N);
235 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
236 SDValue visitCTPOP(SDNode *N);
237 SDValue visitSELECT(SDNode *N);
238 SDValue visitVSELECT(SDNode *N);
239 SDValue visitSELECT_CC(SDNode *N);
240 SDValue visitSETCC(SDNode *N);
241 SDValue visitSIGN_EXTEND(SDNode *N);
242 SDValue visitZERO_EXTEND(SDNode *N);
243 SDValue visitANY_EXTEND(SDNode *N);
244 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
245 SDValue visitTRUNCATE(SDNode *N);
246 SDValue visitBITCAST(SDNode *N);
247 SDValue visitBUILD_PAIR(SDNode *N);
248 SDValue visitFADD(SDNode *N);
249 SDValue visitFSUB(SDNode *N);
250 SDValue visitFMUL(SDNode *N);
251 SDValue visitFMA(SDNode *N);
252 SDValue visitFDIV(SDNode *N);
253 SDValue visitFREM(SDNode *N);
254 SDValue visitFCOPYSIGN(SDNode *N);
255 SDValue visitSINT_TO_FP(SDNode *N);
256 SDValue visitUINT_TO_FP(SDNode *N);
257 SDValue visitFP_TO_SINT(SDNode *N);
258 SDValue visitFP_TO_UINT(SDNode *N);
259 SDValue visitFP_ROUND(SDNode *N);
260 SDValue visitFP_ROUND_INREG(SDNode *N);
261 SDValue visitFP_EXTEND(SDNode *N);
262 SDValue visitFNEG(SDNode *N);
263 SDValue visitFABS(SDNode *N);
264 SDValue visitFCEIL(SDNode *N);
265 SDValue visitFTRUNC(SDNode *N);
266 SDValue visitFFLOOR(SDNode *N);
267 SDValue visitBRCOND(SDNode *N);
268 SDValue visitBR_CC(SDNode *N);
269 SDValue visitLOAD(SDNode *N);
270 SDValue visitSTORE(SDNode *N);
271 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
272 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
273 SDValue visitBUILD_VECTOR(SDNode *N);
274 SDValue visitCONCAT_VECTORS(SDNode *N);
275 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
276 SDValue visitVECTOR_SHUFFLE(SDNode *N);
277 SDValue visitINSERT_SUBVECTOR(SDNode *N);
279 SDValue XformToShuffleWithZero(SDNode *N);
280 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
282 SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
284 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
285 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
286 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
287 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
288 SDValue N3, ISD::CondCode CC,
289 bool NotExtCompare = false);
290 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
291 SDLoc DL, bool foldBooleans = true);
292 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
294 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
295 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
296 SDValue BuildSDIV(SDNode *N);
297 SDValue BuildUDIV(SDNode *N);
298 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
299 bool DemandHighBits = true);
300 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
301 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
302 SDValue InnerPos, SDValue InnerNeg,
303 unsigned PosOpcode, unsigned NegOpcode,
305 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
306 SDValue ReduceLoadWidth(SDNode *N);
307 SDValue ReduceLoadOpStoreWidth(SDNode *N);
308 SDValue TransformFPLoadStorePair(SDNode *N);
309 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
310 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
312 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
314 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
315 /// looking for aliasing nodes and adding them to the Aliases vector.
316 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
317 SmallVectorImpl<SDValue> &Aliases);
319 /// isAlias - Return true if there is any possibility that the two addresses
321 bool isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
322 const Value *SrcValue1, int SrcValueOffset1,
323 unsigned SrcValueAlign1,
324 const MDNode *TBAAInfo1,
325 SDValue Ptr2, int64_t Size2, bool IsVolatile2,
326 const Value *SrcValue2, int SrcValueOffset2,
327 unsigned SrcValueAlign2,
328 const MDNode *TBAAInfo2) const;
330 /// isAlias - Return true if there is any possibility that the two addresses
332 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1);
334 /// FindAliasInfo - Extracts the relevant alias information from the memory
335 /// node. Returns true if the operand was a load.
336 bool FindAliasInfo(SDNode *N,
337 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
338 const Value *&SrcValue, int &SrcValueOffset,
339 unsigned &SrcValueAlignment,
340 const MDNode *&TBAAInfo) const;
342 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
343 /// looking for a better chain (aliasing node.)
344 SDValue FindBetterChain(SDNode *N, SDValue Chain);
346 /// Merge consecutive store operations into a wide store.
347 /// This optimization uses wide integers or vectors when possible.
348 /// \return True if some memory operations were changed.
349 bool MergeConsecutiveStores(StoreSDNode *N);
351 /// \brief Try to transform a truncation where C is a constant:
352 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
354 /// \p N needs to be a truncation and its first operand an AND. Other
355 /// requirements are checked by the function (e.g. that trunc is
356 /// single-use) and if missed an empty SDValue is returned.
357 SDValue distributeTruncateThroughAnd(SDNode *N);
360 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
361 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
362 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
363 AttributeSet FnAttrs =
364 DAG.getMachineFunction().getFunction()->getAttributes();
366 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
367 Attribute::OptimizeForSize) ||
368 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
371 /// Run - runs the dag combiner on all nodes in the work list
372 void Run(CombineLevel AtLevel);
374 SelectionDAG &getDAG() const { return DAG; }
376 /// getShiftAmountTy - Returns a type large enough to hold any valid
377 /// shift amount - before type legalization these can be huge.
378 EVT getShiftAmountTy(EVT LHSTy) {
379 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
380 if (LHSTy.isVector())
382 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
383 : TLI.getPointerTy();
386 /// isTypeLegal - This method returns true if we are running before type
387 /// legalization or if the specified VT is legal.
388 bool isTypeLegal(const EVT &VT) {
389 if (!LegalTypes) return true;
390 return TLI.isTypeLegal(VT);
393 /// getSetCCResultType - Convenience wrapper around
394 /// TargetLowering::getSetCCResultType
395 EVT getSetCCResultType(EVT VT) const {
396 return TLI.getSetCCResultType(*DAG.getContext(), VT);
403 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
404 /// nodes from the worklist.
405 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
408 explicit WorkListRemover(DAGCombiner &dc)
409 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
411 virtual void NodeDeleted(SDNode *N, SDNode *E) {
412 DC.removeFromWorkList(N);
417 //===----------------------------------------------------------------------===//
418 // TargetLowering::DAGCombinerInfo implementation
419 //===----------------------------------------------------------------------===//
421 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
422 ((DAGCombiner*)DC)->AddToWorkList(N);
425 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
426 ((DAGCombiner*)DC)->removeFromWorkList(N);
429 SDValue TargetLowering::DAGCombinerInfo::
430 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
431 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
434 SDValue TargetLowering::DAGCombinerInfo::
435 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
436 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
440 SDValue TargetLowering::DAGCombinerInfo::
441 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
442 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
445 void TargetLowering::DAGCombinerInfo::
446 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
447 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
450 //===----------------------------------------------------------------------===//
452 //===----------------------------------------------------------------------===//
454 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
455 /// specified expression for the same cost as the expression itself, or 2 if we
456 /// can compute the negated form more cheaply than the expression itself.
457 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
458 const TargetLowering &TLI,
459 const TargetOptions *Options,
460 unsigned Depth = 0) {
461 // fneg is removable even if it has multiple uses.
462 if (Op.getOpcode() == ISD::FNEG) return 2;
464 // Don't allow anything with multiple uses.
465 if (!Op.hasOneUse()) return 0;
467 // Don't recurse exponentially.
468 if (Depth > 6) return 0;
470 switch (Op.getOpcode()) {
471 default: return false;
472 case ISD::ConstantFP:
473 // Don't invert constant FP values after legalize. The negated constant
474 // isn't necessarily legal.
475 return LegalOperations ? 0 : 1;
477 // FIXME: determine better conditions for this xform.
478 if (!Options->UnsafeFPMath) return 0;
480 // After operation legalization, it might not be legal to create new FSUBs.
481 if (LegalOperations &&
482 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
485 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
486 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
489 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
490 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
493 // We can't turn -(A-B) into B-A when we honor signed zeros.
494 if (!Options->UnsafeFPMath) return 0;
496 // fold (fneg (fsub A, B)) -> (fsub B, A)
501 if (Options->HonorSignDependentRoundingFPMath()) return 0;
503 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
504 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
508 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
514 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
519 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
520 /// returns the newly negated expression.
521 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
522 bool LegalOperations, unsigned Depth = 0) {
523 // fneg is removable even if it has multiple uses.
524 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
526 // Don't allow anything with multiple uses.
527 assert(Op.hasOneUse() && "Unknown reuse!");
529 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
530 switch (Op.getOpcode()) {
531 default: llvm_unreachable("Unknown code");
532 case ISD::ConstantFP: {
533 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
535 return DAG.getConstantFP(V, Op.getValueType());
538 // FIXME: determine better conditions for this xform.
539 assert(DAG.getTarget().Options.UnsafeFPMath);
541 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
542 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
543 DAG.getTargetLoweringInfo(),
544 &DAG.getTarget().Options, Depth+1))
545 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
546 GetNegatedExpression(Op.getOperand(0), DAG,
547 LegalOperations, Depth+1),
549 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
550 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
551 GetNegatedExpression(Op.getOperand(1), DAG,
552 LegalOperations, Depth+1),
555 // We can't turn -(A-B) into B-A when we honor signed zeros.
556 assert(DAG.getTarget().Options.UnsafeFPMath);
558 // fold (fneg (fsub 0, B)) -> B
559 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
560 if (N0CFP->getValueAPF().isZero())
561 return Op.getOperand(1);
563 // fold (fneg (fsub A, B)) -> (fsub B, A)
564 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
565 Op.getOperand(1), Op.getOperand(0));
569 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
571 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
572 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
573 DAG.getTargetLoweringInfo(),
574 &DAG.getTarget().Options, Depth+1))
575 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
576 GetNegatedExpression(Op.getOperand(0), DAG,
577 LegalOperations, Depth+1),
580 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
581 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
583 GetNegatedExpression(Op.getOperand(1), DAG,
584 LegalOperations, Depth+1));
588 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
589 GetNegatedExpression(Op.getOperand(0), DAG,
590 LegalOperations, Depth+1));
592 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
593 GetNegatedExpression(Op.getOperand(0), DAG,
594 LegalOperations, Depth+1),
600 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
601 // that selects between the values 1 and 0, making it equivalent to a setcc.
602 // Also, set the incoming LHS, RHS, and CC references to the appropriate
603 // nodes based on the type of node we are checking. This simplifies life a
604 // bit for the callers.
605 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
607 if (N.getOpcode() == ISD::SETCC) {
608 LHS = N.getOperand(0);
609 RHS = N.getOperand(1);
610 CC = N.getOperand(2);
613 if (N.getOpcode() == ISD::SELECT_CC &&
614 N.getOperand(2).getOpcode() == ISD::Constant &&
615 N.getOperand(3).getOpcode() == ISD::Constant &&
616 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
617 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
618 LHS = N.getOperand(0);
619 RHS = N.getOperand(1);
620 CC = N.getOperand(4);
626 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
627 // one use. If this is true, it allows the users to invert the operation for
628 // free when it is profitable to do so.
629 static bool isOneUseSetCC(SDValue N) {
631 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
636 // \brief Returns the SDNode if it is a constant BuildVector or constant int.
637 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
638 if (isa<ConstantSDNode>(N))
640 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
641 if(BV && BV->isConstant())
646 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
647 SDValue N0, SDValue N1) {
648 EVT VT = N0.getValueType();
649 if (N0.getOpcode() == Opc) {
650 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
651 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
652 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
653 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
654 if (!OpNode.getNode())
656 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
658 if (N0.hasOneUse()) {
659 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
661 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
662 if (!OpNode.getNode())
664 AddToWorkList(OpNode.getNode());
665 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
670 if (N1.getOpcode() == Opc) {
671 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
672 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
673 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
674 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
675 if (!OpNode.getNode())
677 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
679 if (N1.hasOneUse()) {
680 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
682 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
683 if (!OpNode.getNode())
685 AddToWorkList(OpNode.getNode());
686 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
694 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
696 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
698 DEBUG(dbgs() << "\nReplacing.1 ";
700 dbgs() << "\nWith: ";
701 To[0].getNode()->dump(&DAG);
702 dbgs() << " and " << NumTo-1 << " other values\n";
703 for (unsigned i = 0, e = NumTo; i != e; ++i)
704 assert((!To[i].getNode() ||
705 N->getValueType(i) == To[i].getValueType()) &&
706 "Cannot combine value to value of different type!"));
707 WorkListRemover DeadNodes(*this);
708 DAG.ReplaceAllUsesWith(N, To);
710 // Push the new nodes and any users onto the worklist
711 for (unsigned i = 0, e = NumTo; i != e; ++i) {
712 if (To[i].getNode()) {
713 AddToWorkList(To[i].getNode());
714 AddUsersToWorkList(To[i].getNode());
719 // Finally, if the node is now dead, remove it from the graph. The node
720 // may not be dead if the replacement process recursively simplified to
721 // something else needing this node.
722 if (N->use_empty()) {
723 // Nodes can be reintroduced into the worklist. Make sure we do not
724 // process a node that has been replaced.
725 removeFromWorkList(N);
727 // Finally, since the node is now dead, remove it from the graph.
730 return SDValue(N, 0);
734 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
735 // Replace all uses. If any nodes become isomorphic to other nodes and
736 // are deleted, make sure to remove them from our worklist.
737 WorkListRemover DeadNodes(*this);
738 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
740 // Push the new node and any (possibly new) users onto the worklist.
741 AddToWorkList(TLO.New.getNode());
742 AddUsersToWorkList(TLO.New.getNode());
744 // Finally, if the node is now dead, remove it from the graph. The node
745 // may not be dead if the replacement process recursively simplified to
746 // something else needing this node.
747 if (TLO.Old.getNode()->use_empty()) {
748 removeFromWorkList(TLO.Old.getNode());
750 // If the operands of this node are only used by the node, they will now
751 // be dead. Make sure to visit them first to delete dead nodes early.
752 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
753 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
754 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
756 DAG.DeleteNode(TLO.Old.getNode());
760 /// SimplifyDemandedBits - Check the specified integer node value to see if
761 /// it can be simplified or if things it uses can be simplified by bit
762 /// propagation. If so, return true.
763 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
764 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
765 APInt KnownZero, KnownOne;
766 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
770 AddToWorkList(Op.getNode());
772 // Replace the old value with the new one.
774 DEBUG(dbgs() << "\nReplacing.2 ";
775 TLO.Old.getNode()->dump(&DAG);
776 dbgs() << "\nWith: ";
777 TLO.New.getNode()->dump(&DAG);
780 CommitTargetLoweringOpt(TLO);
784 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
786 EVT VT = Load->getValueType(0);
787 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
789 DEBUG(dbgs() << "\nReplacing.9 ";
791 dbgs() << "\nWith: ";
792 Trunc.getNode()->dump(&DAG);
794 WorkListRemover DeadNodes(*this);
795 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
796 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
797 removeFromWorkList(Load);
798 DAG.DeleteNode(Load);
799 AddToWorkList(Trunc.getNode());
802 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
805 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
806 EVT MemVT = LD->getMemoryVT();
807 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
808 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
810 : LD->getExtensionType();
812 return DAG.getExtLoad(ExtType, dl, PVT,
813 LD->getChain(), LD->getBasePtr(),
814 MemVT, LD->getMemOperand());
817 unsigned Opc = Op.getOpcode();
820 case ISD::AssertSext:
821 return DAG.getNode(ISD::AssertSext, dl, PVT,
822 SExtPromoteOperand(Op.getOperand(0), PVT),
824 case ISD::AssertZext:
825 return DAG.getNode(ISD::AssertZext, dl, PVT,
826 ZExtPromoteOperand(Op.getOperand(0), PVT),
828 case ISD::Constant: {
830 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
831 return DAG.getNode(ExtOpc, dl, PVT, Op);
835 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
837 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
840 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
841 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
843 EVT OldVT = Op.getValueType();
845 bool Replace = false;
846 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
847 if (NewOp.getNode() == 0)
849 AddToWorkList(NewOp.getNode());
852 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
853 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
854 DAG.getValueType(OldVT));
857 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
858 EVT OldVT = Op.getValueType();
860 bool Replace = false;
861 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
862 if (NewOp.getNode() == 0)
864 AddToWorkList(NewOp.getNode());
867 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
868 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
871 /// PromoteIntBinOp - Promote the specified integer binary operation if the
872 /// target indicates it is beneficial. e.g. On x86, it's usually better to
873 /// promote i16 operations to i32 since i16 instructions are longer.
874 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
875 if (!LegalOperations)
878 EVT VT = Op.getValueType();
879 if (VT.isVector() || !VT.isInteger())
882 // If operation type is 'undesirable', e.g. i16 on x86, consider
884 unsigned Opc = Op.getOpcode();
885 if (TLI.isTypeDesirableForOp(Opc, VT))
889 // Consult target whether it is a good idea to promote this operation and
890 // what's the right type to promote it to.
891 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
892 assert(PVT != VT && "Don't know what type to promote to!");
894 bool Replace0 = false;
895 SDValue N0 = Op.getOperand(0);
896 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
897 if (NN0.getNode() == 0)
900 bool Replace1 = false;
901 SDValue N1 = Op.getOperand(1);
906 NN1 = PromoteOperand(N1, PVT, Replace1);
907 if (NN1.getNode() == 0)
911 AddToWorkList(NN0.getNode());
913 AddToWorkList(NN1.getNode());
916 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
918 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
920 DEBUG(dbgs() << "\nPromoting ";
921 Op.getNode()->dump(&DAG));
923 return DAG.getNode(ISD::TRUNCATE, dl, VT,
924 DAG.getNode(Opc, dl, PVT, NN0, NN1));
929 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
930 /// target indicates it is beneficial. e.g. On x86, it's usually better to
931 /// promote i16 operations to i32 since i16 instructions are longer.
932 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
933 if (!LegalOperations)
936 EVT VT = Op.getValueType();
937 if (VT.isVector() || !VT.isInteger())
940 // If operation type is 'undesirable', e.g. i16 on x86, consider
942 unsigned Opc = Op.getOpcode();
943 if (TLI.isTypeDesirableForOp(Opc, VT))
947 // Consult target whether it is a good idea to promote this operation and
948 // what's the right type to promote it to.
949 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
950 assert(PVT != VT && "Don't know what type to promote to!");
952 bool Replace = false;
953 SDValue N0 = Op.getOperand(0);
955 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
956 else if (Opc == ISD::SRL)
957 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
959 N0 = PromoteOperand(N0, PVT, Replace);
960 if (N0.getNode() == 0)
963 AddToWorkList(N0.getNode());
965 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
967 DEBUG(dbgs() << "\nPromoting ";
968 Op.getNode()->dump(&DAG));
970 return DAG.getNode(ISD::TRUNCATE, dl, VT,
971 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
976 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
977 if (!LegalOperations)
980 EVT VT = Op.getValueType();
981 if (VT.isVector() || !VT.isInteger())
984 // If operation type is 'undesirable', e.g. i16 on x86, consider
986 unsigned Opc = Op.getOpcode();
987 if (TLI.isTypeDesirableForOp(Opc, VT))
991 // Consult target whether it is a good idea to promote this operation and
992 // what's the right type to promote it to.
993 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
994 assert(PVT != VT && "Don't know what type to promote to!");
995 // fold (aext (aext x)) -> (aext x)
996 // fold (aext (zext x)) -> (zext x)
997 // fold (aext (sext x)) -> (sext x)
998 DEBUG(dbgs() << "\nPromoting ";
999 Op.getNode()->dump(&DAG));
1000 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1005 bool DAGCombiner::PromoteLoad(SDValue Op) {
1006 if (!LegalOperations)
1009 EVT VT = Op.getValueType();
1010 if (VT.isVector() || !VT.isInteger())
1013 // If operation type is 'undesirable', e.g. i16 on x86, consider
1015 unsigned Opc = Op.getOpcode();
1016 if (TLI.isTypeDesirableForOp(Opc, VT))
1020 // Consult target whether it is a good idea to promote this operation and
1021 // what's the right type to promote it to.
1022 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1023 assert(PVT != VT && "Don't know what type to promote to!");
1026 SDNode *N = Op.getNode();
1027 LoadSDNode *LD = cast<LoadSDNode>(N);
1028 EVT MemVT = LD->getMemoryVT();
1029 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1030 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1032 : LD->getExtensionType();
1033 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1034 LD->getChain(), LD->getBasePtr(),
1035 MemVT, LD->getMemOperand());
1036 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1038 DEBUG(dbgs() << "\nPromoting ";
1041 Result.getNode()->dump(&DAG);
1043 WorkListRemover DeadNodes(*this);
1044 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1045 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1046 removeFromWorkList(N);
1048 AddToWorkList(Result.getNode());
1055 //===----------------------------------------------------------------------===//
1056 // Main DAG Combiner implementation
1057 //===----------------------------------------------------------------------===//
1059 void DAGCombiner::Run(CombineLevel AtLevel) {
1060 // set the instance variables, so that the various visit routines may use it.
1062 LegalOperations = Level >= AfterLegalizeVectorOps;
1063 LegalTypes = Level >= AfterLegalizeTypes;
1065 // Add all the dag nodes to the worklist.
1066 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1067 E = DAG.allnodes_end(); I != E; ++I)
1070 // Create a dummy node (which is not added to allnodes), that adds a reference
1071 // to the root node, preventing it from being deleted, and tracking any
1072 // changes of the root.
1073 HandleSDNode Dummy(DAG.getRoot());
1075 // The root of the dag may dangle to deleted nodes until the dag combiner is
1076 // done. Set it to null to avoid confusion.
1077 DAG.setRoot(SDValue());
1079 // while the worklist isn't empty, find a node and
1080 // try and combine it.
1081 while (!WorkListContents.empty()) {
1083 // The WorkListOrder holds the SDNodes in order, but it may contain
1085 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1086 // worklist *should* contain, and check the node we want to visit is should
1087 // actually be visited.
1089 N = WorkListOrder.pop_back_val();
1090 } while (!WorkListContents.erase(N));
1092 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1093 // N is deleted from the DAG, since they too may now be dead or may have a
1094 // reduced number of uses, allowing other xforms.
1095 if (N->use_empty() && N != &Dummy) {
1096 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1097 AddToWorkList(N->getOperand(i).getNode());
1103 SDValue RV = combine(N);
1105 if (RV.getNode() == 0)
1110 // If we get back the same node we passed in, rather than a new node or
1111 // zero, we know that the node must have defined multiple values and
1112 // CombineTo was used. Since CombineTo takes care of the worklist
1113 // mechanics for us, we have no work to do in this case.
1114 if (RV.getNode() == N)
1117 assert(N->getOpcode() != ISD::DELETED_NODE &&
1118 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1119 "Node was deleted but visit returned new node!");
1121 DEBUG(dbgs() << "\nReplacing.3 ";
1123 dbgs() << "\nWith: ";
1124 RV.getNode()->dump(&DAG);
1127 // Transfer debug value.
1128 DAG.TransferDbgValues(SDValue(N, 0), RV);
1129 WorkListRemover DeadNodes(*this);
1130 if (N->getNumValues() == RV.getNode()->getNumValues())
1131 DAG.ReplaceAllUsesWith(N, RV.getNode());
1133 assert(N->getValueType(0) == RV.getValueType() &&
1134 N->getNumValues() == 1 && "Type mismatch");
1136 DAG.ReplaceAllUsesWith(N, &OpV);
1139 // Push the new node and any users onto the worklist
1140 AddToWorkList(RV.getNode());
1141 AddUsersToWorkList(RV.getNode());
1143 // Add any uses of the old node to the worklist in case this node is the
1144 // last one that uses them. They may become dead after this node is
1146 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1147 AddToWorkList(N->getOperand(i).getNode());
1149 // Finally, if the node is now dead, remove it from the graph. The node
1150 // may not be dead if the replacement process recursively simplified to
1151 // something else needing this node.
1152 if (N->use_empty()) {
1153 // Nodes can be reintroduced into the worklist. Make sure we do not
1154 // process a node that has been replaced.
1155 removeFromWorkList(N);
1157 // Finally, since the node is now dead, remove it from the graph.
1162 // If the root changed (e.g. it was a dead load, update the root).
1163 DAG.setRoot(Dummy.getValue());
1164 DAG.RemoveDeadNodes();
1167 SDValue DAGCombiner::visit(SDNode *N) {
1168 switch (N->getOpcode()) {
1170 case ISD::TokenFactor: return visitTokenFactor(N);
1171 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1172 case ISD::ADD: return visitADD(N);
1173 case ISD::SUB: return visitSUB(N);
1174 case ISD::ADDC: return visitADDC(N);
1175 case ISD::SUBC: return visitSUBC(N);
1176 case ISD::ADDE: return visitADDE(N);
1177 case ISD::SUBE: return visitSUBE(N);
1178 case ISD::MUL: return visitMUL(N);
1179 case ISD::SDIV: return visitSDIV(N);
1180 case ISD::UDIV: return visitUDIV(N);
1181 case ISD::SREM: return visitSREM(N);
1182 case ISD::UREM: return visitUREM(N);
1183 case ISD::MULHU: return visitMULHU(N);
1184 case ISD::MULHS: return visitMULHS(N);
1185 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1186 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1187 case ISD::SMULO: return visitSMULO(N);
1188 case ISD::UMULO: return visitUMULO(N);
1189 case ISD::SDIVREM: return visitSDIVREM(N);
1190 case ISD::UDIVREM: return visitUDIVREM(N);
1191 case ISD::AND: return visitAND(N);
1192 case ISD::OR: return visitOR(N);
1193 case ISD::XOR: return visitXOR(N);
1194 case ISD::SHL: return visitSHL(N);
1195 case ISD::SRA: return visitSRA(N);
1196 case ISD::SRL: return visitSRL(N);
1197 case ISD::CTLZ: return visitCTLZ(N);
1198 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1199 case ISD::CTTZ: return visitCTTZ(N);
1200 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1201 case ISD::CTPOP: return visitCTPOP(N);
1202 case ISD::SELECT: return visitSELECT(N);
1203 case ISD::VSELECT: return visitVSELECT(N);
1204 case ISD::SELECT_CC: return visitSELECT_CC(N);
1205 case ISD::SETCC: return visitSETCC(N);
1206 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1207 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1208 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1209 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1210 case ISD::TRUNCATE: return visitTRUNCATE(N);
1211 case ISD::BITCAST: return visitBITCAST(N);
1212 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1213 case ISD::FADD: return visitFADD(N);
1214 case ISD::FSUB: return visitFSUB(N);
1215 case ISD::FMUL: return visitFMUL(N);
1216 case ISD::FMA: return visitFMA(N);
1217 case ISD::FDIV: return visitFDIV(N);
1218 case ISD::FREM: return visitFREM(N);
1219 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1220 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1221 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1222 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1223 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1224 case ISD::FP_ROUND: return visitFP_ROUND(N);
1225 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1226 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1227 case ISD::FNEG: return visitFNEG(N);
1228 case ISD::FABS: return visitFABS(N);
1229 case ISD::FFLOOR: return visitFFLOOR(N);
1230 case ISD::FCEIL: return visitFCEIL(N);
1231 case ISD::FTRUNC: return visitFTRUNC(N);
1232 case ISD::BRCOND: return visitBRCOND(N);
1233 case ISD::BR_CC: return visitBR_CC(N);
1234 case ISD::LOAD: return visitLOAD(N);
1235 case ISD::STORE: return visitSTORE(N);
1236 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1237 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1238 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1239 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1240 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1241 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1242 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1247 SDValue DAGCombiner::combine(SDNode *N) {
1248 SDValue RV = visit(N);
1250 // If nothing happened, try a target-specific DAG combine.
1251 if (RV.getNode() == 0) {
1252 assert(N->getOpcode() != ISD::DELETED_NODE &&
1253 "Node was deleted but visit returned NULL!");
1255 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1256 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1258 // Expose the DAG combiner to the target combiner impls.
1259 TargetLowering::DAGCombinerInfo
1260 DagCombineInfo(DAG, Level, false, this);
1262 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1266 // If nothing happened still, try promoting the operation.
1267 if (RV.getNode() == 0) {
1268 switch (N->getOpcode()) {
1276 RV = PromoteIntBinOp(SDValue(N, 0));
1281 RV = PromoteIntShiftOp(SDValue(N, 0));
1283 case ISD::SIGN_EXTEND:
1284 case ISD::ZERO_EXTEND:
1285 case ISD::ANY_EXTEND:
1286 RV = PromoteExtend(SDValue(N, 0));
1289 if (PromoteLoad(SDValue(N, 0)))
1295 // If N is a commutative binary node, try commuting it to enable more
1297 if (RV.getNode() == 0 &&
1298 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1299 N->getNumValues() == 1) {
1300 SDValue N0 = N->getOperand(0);
1301 SDValue N1 = N->getOperand(1);
1303 // Constant operands are canonicalized to RHS.
1304 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1305 SDValue Ops[] = { N1, N0 };
1306 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1309 return SDValue(CSENode, 0);
1316 /// getInputChainForNode - Given a node, return its input chain if it has one,
1317 /// otherwise return a null sd operand.
1318 static SDValue getInputChainForNode(SDNode *N) {
1319 if (unsigned NumOps = N->getNumOperands()) {
1320 if (N->getOperand(0).getValueType() == MVT::Other)
1321 return N->getOperand(0);
1322 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1323 return N->getOperand(NumOps-1);
1324 for (unsigned i = 1; i < NumOps-1; ++i)
1325 if (N->getOperand(i).getValueType() == MVT::Other)
1326 return N->getOperand(i);
1331 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1332 // If N has two operands, where one has an input chain equal to the other,
1333 // the 'other' chain is redundant.
1334 if (N->getNumOperands() == 2) {
1335 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1336 return N->getOperand(0);
1337 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1338 return N->getOperand(1);
1341 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1342 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1343 SmallPtrSet<SDNode*, 16> SeenOps;
1344 bool Changed = false; // If we should replace this token factor.
1346 // Start out with this token factor.
1349 // Iterate through token factors. The TFs grows when new token factors are
1351 for (unsigned i = 0; i < TFs.size(); ++i) {
1352 SDNode *TF = TFs[i];
1354 // Check each of the operands.
1355 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1356 SDValue Op = TF->getOperand(i);
1358 switch (Op.getOpcode()) {
1359 case ISD::EntryToken:
1360 // Entry tokens don't need to be added to the list. They are
1365 case ISD::TokenFactor:
1366 if (Op.hasOneUse() &&
1367 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1368 // Queue up for processing.
1369 TFs.push_back(Op.getNode());
1370 // Clean up in case the token factor is removed.
1371 AddToWorkList(Op.getNode());
1378 // Only add if it isn't already in the list.
1379 if (SeenOps.insert(Op.getNode()))
1390 // If we've change things around then replace token factor.
1393 // The entry token is the only possible outcome.
1394 Result = DAG.getEntryNode();
1396 // New and improved token factor.
1397 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
1398 MVT::Other, &Ops[0], Ops.size());
1401 // Don't add users to work list.
1402 return CombineTo(N, Result, false);
1408 /// MERGE_VALUES can always be eliminated.
1409 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1410 WorkListRemover DeadNodes(*this);
1411 // Replacing results may cause a different MERGE_VALUES to suddenly
1412 // be CSE'd with N, and carry its uses with it. Iterate until no
1413 // uses remain, to ensure that the node can be safely deleted.
1414 // First add the users of this node to the work list so that they
1415 // can be tried again once they have new operands.
1416 AddUsersToWorkList(N);
1418 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1419 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1420 } while (!N->use_empty());
1421 removeFromWorkList(N);
1423 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1427 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1428 SelectionDAG &DAG) {
1429 EVT VT = N0.getValueType();
1430 SDValue N00 = N0.getOperand(0);
1431 SDValue N01 = N0.getOperand(1);
1432 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1434 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1435 isa<ConstantSDNode>(N00.getOperand(1))) {
1436 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1437 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1438 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1439 N00.getOperand(0), N01),
1440 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1441 N00.getOperand(1), N01));
1442 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1448 SDValue DAGCombiner::visitADD(SDNode *N) {
1449 SDValue N0 = N->getOperand(0);
1450 SDValue N1 = N->getOperand(1);
1451 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1452 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1453 EVT VT = N0.getValueType();
1456 if (VT.isVector()) {
1457 SDValue FoldedVOp = SimplifyVBinOp(N);
1458 if (FoldedVOp.getNode()) return FoldedVOp;
1460 // fold (add x, 0) -> x, vector edition
1461 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1463 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1467 // fold (add x, undef) -> undef
1468 if (N0.getOpcode() == ISD::UNDEF)
1470 if (N1.getOpcode() == ISD::UNDEF)
1472 // fold (add c1, c2) -> c1+c2
1474 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1475 // canonicalize constant to RHS
1477 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1478 // fold (add x, 0) -> x
1479 if (N1C && N1C->isNullValue())
1481 // fold (add Sym, c) -> Sym+c
1482 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1483 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1484 GA->getOpcode() == ISD::GlobalAddress)
1485 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1487 (uint64_t)N1C->getSExtValue());
1488 // fold ((c1-A)+c2) -> (c1+c2)-A
1489 if (N1C && N0.getOpcode() == ISD::SUB)
1490 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1491 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1492 DAG.getConstant(N1C->getAPIntValue()+
1493 N0C->getAPIntValue(), VT),
1496 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1497 if (RADD.getNode() != 0)
1499 // fold ((0-A) + B) -> B-A
1500 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1501 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1502 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1503 // fold (A + (0-B)) -> A-B
1504 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1505 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1506 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1507 // fold (A+(B-A)) -> B
1508 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1509 return N1.getOperand(0);
1510 // fold ((B-A)+A) -> B
1511 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1512 return N0.getOperand(0);
1513 // fold (A+(B-(A+C))) to (B-C)
1514 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1515 N0 == N1.getOperand(1).getOperand(0))
1516 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1517 N1.getOperand(1).getOperand(1));
1518 // fold (A+(B-(C+A))) to (B-C)
1519 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1520 N0 == N1.getOperand(1).getOperand(1))
1521 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1522 N1.getOperand(1).getOperand(0));
1523 // fold (A+((B-A)+or-C)) to (B+or-C)
1524 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1525 N1.getOperand(0).getOpcode() == ISD::SUB &&
1526 N0 == N1.getOperand(0).getOperand(1))
1527 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1528 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1530 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1531 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1532 SDValue N00 = N0.getOperand(0);
1533 SDValue N01 = N0.getOperand(1);
1534 SDValue N10 = N1.getOperand(0);
1535 SDValue N11 = N1.getOperand(1);
1537 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1538 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1539 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1540 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1543 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1544 return SDValue(N, 0);
1546 // fold (a+b) -> (a|b) iff a and b share no bits.
1547 if (VT.isInteger() && !VT.isVector()) {
1548 APInt LHSZero, LHSOne;
1549 APInt RHSZero, RHSOne;
1550 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1552 if (LHSZero.getBoolValue()) {
1553 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1555 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1556 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1557 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1558 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1559 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1564 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1565 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1566 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1567 if (Result.getNode()) return Result;
1569 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1570 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1571 if (Result.getNode()) return Result;
1574 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1575 if (N1.getOpcode() == ISD::SHL &&
1576 N1.getOperand(0).getOpcode() == ISD::SUB)
1577 if (ConstantSDNode *C =
1578 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1579 if (C->getAPIntValue() == 0)
1580 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1581 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1582 N1.getOperand(0).getOperand(1),
1584 if (N0.getOpcode() == ISD::SHL &&
1585 N0.getOperand(0).getOpcode() == ISD::SUB)
1586 if (ConstantSDNode *C =
1587 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1588 if (C->getAPIntValue() == 0)
1589 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1590 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1591 N0.getOperand(0).getOperand(1),
1594 if (N1.getOpcode() == ISD::AND) {
1595 SDValue AndOp0 = N1.getOperand(0);
1596 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1597 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1598 unsigned DestBits = VT.getScalarType().getSizeInBits();
1600 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1601 // and similar xforms where the inner op is either ~0 or 0.
1602 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1604 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1608 // add (sext i1), X -> sub X, (zext i1)
1609 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1610 N0.getOperand(0).getValueType() == MVT::i1 &&
1611 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1613 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1614 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1620 SDValue DAGCombiner::visitADDC(SDNode *N) {
1621 SDValue N0 = N->getOperand(0);
1622 SDValue N1 = N->getOperand(1);
1623 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1624 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1625 EVT VT = N0.getValueType();
1627 // If the flag result is dead, turn this into an ADD.
1628 if (!N->hasAnyUseOfValue(1))
1629 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1630 DAG.getNode(ISD::CARRY_FALSE,
1631 SDLoc(N), MVT::Glue));
1633 // canonicalize constant to RHS.
1635 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1637 // fold (addc x, 0) -> x + no carry out
1638 if (N1C && N1C->isNullValue())
1639 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1640 SDLoc(N), MVT::Glue));
1642 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1643 APInt LHSZero, LHSOne;
1644 APInt RHSZero, RHSOne;
1645 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1647 if (LHSZero.getBoolValue()) {
1648 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1650 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1651 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1652 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1653 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1654 DAG.getNode(ISD::CARRY_FALSE,
1655 SDLoc(N), MVT::Glue));
1661 SDValue DAGCombiner::visitADDE(SDNode *N) {
1662 SDValue N0 = N->getOperand(0);
1663 SDValue N1 = N->getOperand(1);
1664 SDValue CarryIn = N->getOperand(2);
1665 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1666 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1668 // canonicalize constant to RHS
1670 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1673 // fold (adde x, y, false) -> (addc x, y)
1674 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1675 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1680 // Since it may not be valid to emit a fold to zero for vector initializers
1681 // check if we can before folding.
1682 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1684 bool LegalOperations, bool LegalTypes) {
1686 return DAG.getConstant(0, VT);
1687 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1688 return DAG.getConstant(0, VT);
1692 SDValue DAGCombiner::visitSUB(SDNode *N) {
1693 SDValue N0 = N->getOperand(0);
1694 SDValue N1 = N->getOperand(1);
1695 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1696 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1697 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1698 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1699 EVT VT = N0.getValueType();
1702 if (VT.isVector()) {
1703 SDValue FoldedVOp = SimplifyVBinOp(N);
1704 if (FoldedVOp.getNode()) return FoldedVOp;
1706 // fold (sub x, 0) -> x, vector edition
1707 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1711 // fold (sub x, x) -> 0
1712 // FIXME: Refactor this and xor and other similar operations together.
1714 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1715 // fold (sub c1, c2) -> c1-c2
1717 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1718 // fold (sub x, c) -> (add x, -c)
1720 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1721 DAG.getConstant(-N1C->getAPIntValue(), VT));
1722 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1723 if (N0C && N0C->isAllOnesValue())
1724 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1725 // fold A-(A-B) -> B
1726 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1727 return N1.getOperand(1);
1728 // fold (A+B)-A -> B
1729 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1730 return N0.getOperand(1);
1731 // fold (A+B)-B -> A
1732 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1733 return N0.getOperand(0);
1734 // fold C2-(A+C1) -> (C2-C1)-A
1735 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1736 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1738 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1741 // fold ((A+(B+or-C))-B) -> A+or-C
1742 if (N0.getOpcode() == ISD::ADD &&
1743 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1744 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1745 N0.getOperand(1).getOperand(0) == N1)
1746 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1747 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1748 // fold ((A+(C+B))-B) -> A+C
1749 if (N0.getOpcode() == ISD::ADD &&
1750 N0.getOperand(1).getOpcode() == ISD::ADD &&
1751 N0.getOperand(1).getOperand(1) == N1)
1752 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1753 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1754 // fold ((A-(B-C))-C) -> A-B
1755 if (N0.getOpcode() == ISD::SUB &&
1756 N0.getOperand(1).getOpcode() == ISD::SUB &&
1757 N0.getOperand(1).getOperand(1) == N1)
1758 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1759 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1761 // If either operand of a sub is undef, the result is undef
1762 if (N0.getOpcode() == ISD::UNDEF)
1764 if (N1.getOpcode() == ISD::UNDEF)
1767 // If the relocation model supports it, consider symbol offsets.
1768 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1769 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1770 // fold (sub Sym, c) -> Sym-c
1771 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1772 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1774 (uint64_t)N1C->getSExtValue());
1775 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1776 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1777 if (GA->getGlobal() == GB->getGlobal())
1778 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1785 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1786 SDValue N0 = N->getOperand(0);
1787 SDValue N1 = N->getOperand(1);
1788 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1789 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1790 EVT VT = N0.getValueType();
1792 // If the flag result is dead, turn this into an SUB.
1793 if (!N->hasAnyUseOfValue(1))
1794 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1795 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1798 // fold (subc x, x) -> 0 + no borrow
1800 return CombineTo(N, DAG.getConstant(0, VT),
1801 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1804 // fold (subc x, 0) -> x + no borrow
1805 if (N1C && N1C->isNullValue())
1806 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1809 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1810 if (N0C && N0C->isAllOnesValue())
1811 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1812 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1818 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1819 SDValue N0 = N->getOperand(0);
1820 SDValue N1 = N->getOperand(1);
1821 SDValue CarryIn = N->getOperand(2);
1823 // fold (sube x, y, false) -> (subc x, y)
1824 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1825 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1830 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
1831 /// elements are all the same constant or undefined.
1832 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
1833 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
1838 unsigned SplatBitSize;
1840 EVT EltVT = N->getValueType(0).getVectorElementType();
1841 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
1843 EltVT.getSizeInBits() >= SplatBitSize);
1846 SDValue DAGCombiner::visitMUL(SDNode *N) {
1847 SDValue N0 = N->getOperand(0);
1848 SDValue N1 = N->getOperand(1);
1849 EVT VT = N0.getValueType();
1851 // fold (mul x, undef) -> 0
1852 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1853 return DAG.getConstant(0, VT);
1855 bool N0IsConst = false;
1856 bool N1IsConst = false;
1857 APInt ConstValue0, ConstValue1;
1859 if (VT.isVector()) {
1860 SDValue FoldedVOp = SimplifyVBinOp(N);
1861 if (FoldedVOp.getNode()) return FoldedVOp;
1863 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1864 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1866 N0IsConst = dyn_cast<ConstantSDNode>(N0) != 0;
1867 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1869 N1IsConst = dyn_cast<ConstantSDNode>(N1) != 0;
1870 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1874 // fold (mul c1, c2) -> c1*c2
1875 if (N0IsConst && N1IsConst)
1876 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1878 // canonicalize constant to RHS
1879 if (N0IsConst && !N1IsConst)
1880 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1881 // fold (mul x, 0) -> 0
1882 if (N1IsConst && ConstValue1 == 0)
1884 // We require a splat of the entire scalar bit width for non-contiguous
1887 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1888 // fold (mul x, 1) -> x
1889 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1891 // fold (mul x, -1) -> 0-x
1892 if (N1IsConst && ConstValue1.isAllOnesValue())
1893 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1894 DAG.getConstant(0, VT), N0);
1895 // fold (mul x, (1 << c)) -> x << c
1896 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1897 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1898 DAG.getConstant(ConstValue1.logBase2(),
1899 getShiftAmountTy(N0.getValueType())));
1900 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1901 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1902 unsigned Log2Val = (-ConstValue1).logBase2();
1903 // FIXME: If the input is something that is easily negated (e.g. a
1904 // single-use add), we should put the negate there.
1905 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1906 DAG.getConstant(0, VT),
1907 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1908 DAG.getConstant(Log2Val,
1909 getShiftAmountTy(N0.getValueType()))));
1913 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1914 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1915 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1916 isa<ConstantSDNode>(N0.getOperand(1)))) {
1917 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1918 N1, N0.getOperand(1));
1919 AddToWorkList(C3.getNode());
1920 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1921 N0.getOperand(0), C3);
1924 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1927 SDValue Sh(0,0), Y(0,0);
1928 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1929 if (N0.getOpcode() == ISD::SHL &&
1930 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1931 isa<ConstantSDNode>(N0.getOperand(1))) &&
1932 N0.getNode()->hasOneUse()) {
1934 } else if (N1.getOpcode() == ISD::SHL &&
1935 isa<ConstantSDNode>(N1.getOperand(1)) &&
1936 N1.getNode()->hasOneUse()) {
1941 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1942 Sh.getOperand(0), Y);
1943 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1944 Mul, Sh.getOperand(1));
1948 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1949 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1950 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1951 isa<ConstantSDNode>(N0.getOperand(1))))
1952 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1953 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1954 N0.getOperand(0), N1),
1955 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1956 N0.getOperand(1), N1));
1959 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1960 if (RMUL.getNode() != 0)
1966 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1967 SDValue N0 = N->getOperand(0);
1968 SDValue N1 = N->getOperand(1);
1969 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1970 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1971 EVT VT = N->getValueType(0);
1974 if (VT.isVector()) {
1975 SDValue FoldedVOp = SimplifyVBinOp(N);
1976 if (FoldedVOp.getNode()) return FoldedVOp;
1979 // fold (sdiv c1, c2) -> c1/c2
1980 if (N0C && N1C && !N1C->isNullValue())
1981 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1982 // fold (sdiv X, 1) -> X
1983 if (N1C && N1C->getAPIntValue() == 1LL)
1985 // fold (sdiv X, -1) -> 0-X
1986 if (N1C && N1C->isAllOnesValue())
1987 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1988 DAG.getConstant(0, VT), N0);
1989 // If we know the sign bits of both operands are zero, strength reduce to a
1990 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1991 if (!VT.isVector()) {
1992 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1993 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
1996 // fold (sdiv X, pow2) -> simple ops after legalize
1997 if (N1C && !N1C->isNullValue() &&
1998 (N1C->getAPIntValue().isPowerOf2() ||
1999 (-N1C->getAPIntValue()).isPowerOf2())) {
2000 // If dividing by powers of two is cheap, then don't perform the following
2002 if (TLI.isPow2DivCheap())
2005 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2007 // Splat the sign bit into the register
2008 SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2009 DAG.getConstant(VT.getSizeInBits()-1,
2010 getShiftAmountTy(N0.getValueType())));
2011 AddToWorkList(SGN.getNode());
2013 // Add (N0 < 0) ? abs2 - 1 : 0;
2014 SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2015 DAG.getConstant(VT.getSizeInBits() - lg2,
2016 getShiftAmountTy(SGN.getValueType())));
2017 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2018 AddToWorkList(SRL.getNode());
2019 AddToWorkList(ADD.getNode()); // Divide by pow2
2020 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2021 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2023 // If we're dividing by a positive value, we're done. Otherwise, we must
2024 // negate the result.
2025 if (N1C->getAPIntValue().isNonNegative())
2028 AddToWorkList(SRA.getNode());
2029 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2030 DAG.getConstant(0, VT), SRA);
2033 // if integer divide is expensive and we satisfy the requirements, emit an
2034 // alternate sequence.
2035 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2036 SDValue Op = BuildSDIV(N);
2037 if (Op.getNode()) return Op;
2041 if (N0.getOpcode() == ISD::UNDEF)
2042 return DAG.getConstant(0, VT);
2043 // X / undef -> undef
2044 if (N1.getOpcode() == ISD::UNDEF)
2050 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2051 SDValue N0 = N->getOperand(0);
2052 SDValue N1 = N->getOperand(1);
2053 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
2054 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2055 EVT VT = N->getValueType(0);
2058 if (VT.isVector()) {
2059 SDValue FoldedVOp = SimplifyVBinOp(N);
2060 if (FoldedVOp.getNode()) return FoldedVOp;
2063 // fold (udiv c1, c2) -> c1/c2
2064 if (N0C && N1C && !N1C->isNullValue())
2065 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2066 // fold (udiv x, (1 << c)) -> x >>u c
2067 if (N1C && N1C->getAPIntValue().isPowerOf2())
2068 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2069 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2070 getShiftAmountTy(N0.getValueType())));
2071 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2072 if (N1.getOpcode() == ISD::SHL) {
2073 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2074 if (SHC->getAPIntValue().isPowerOf2()) {
2075 EVT ADDVT = N1.getOperand(1).getValueType();
2076 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2078 DAG.getConstant(SHC->getAPIntValue()
2081 AddToWorkList(Add.getNode());
2082 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2086 // fold (udiv x, c) -> alternate
2087 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2088 SDValue Op = BuildUDIV(N);
2089 if (Op.getNode()) return Op;
2093 if (N0.getOpcode() == ISD::UNDEF)
2094 return DAG.getConstant(0, VT);
2095 // X / undef -> undef
2096 if (N1.getOpcode() == ISD::UNDEF)
2102 SDValue DAGCombiner::visitSREM(SDNode *N) {
2103 SDValue N0 = N->getOperand(0);
2104 SDValue N1 = N->getOperand(1);
2105 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2106 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2107 EVT VT = N->getValueType(0);
2109 // fold (srem c1, c2) -> c1%c2
2110 if (N0C && N1C && !N1C->isNullValue())
2111 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2112 // If we know the sign bits of both operands are zero, strength reduce to a
2113 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2114 if (!VT.isVector()) {
2115 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2116 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2119 // If X/C can be simplified by the division-by-constant logic, lower
2120 // X%C to the equivalent of X-X/C*C.
2121 if (N1C && !N1C->isNullValue()) {
2122 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2123 AddToWorkList(Div.getNode());
2124 SDValue OptimizedDiv = combine(Div.getNode());
2125 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2126 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2128 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2129 AddToWorkList(Mul.getNode());
2135 if (N0.getOpcode() == ISD::UNDEF)
2136 return DAG.getConstant(0, VT);
2137 // X % undef -> undef
2138 if (N1.getOpcode() == ISD::UNDEF)
2144 SDValue DAGCombiner::visitUREM(SDNode *N) {
2145 SDValue N0 = N->getOperand(0);
2146 SDValue N1 = N->getOperand(1);
2147 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2148 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2149 EVT VT = N->getValueType(0);
2151 // fold (urem c1, c2) -> c1%c2
2152 if (N0C && N1C && !N1C->isNullValue())
2153 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2154 // fold (urem x, pow2) -> (and x, pow2-1)
2155 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2156 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2157 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2158 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2159 if (N1.getOpcode() == ISD::SHL) {
2160 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2161 if (SHC->getAPIntValue().isPowerOf2()) {
2163 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2164 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2166 AddToWorkList(Add.getNode());
2167 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2172 // If X/C can be simplified by the division-by-constant logic, lower
2173 // X%C to the equivalent of X-X/C*C.
2174 if (N1C && !N1C->isNullValue()) {
2175 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2176 AddToWorkList(Div.getNode());
2177 SDValue OptimizedDiv = combine(Div.getNode());
2178 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2179 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2181 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2182 AddToWorkList(Mul.getNode());
2188 if (N0.getOpcode() == ISD::UNDEF)
2189 return DAG.getConstant(0, VT);
2190 // X % undef -> undef
2191 if (N1.getOpcode() == ISD::UNDEF)
2197 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2198 SDValue N0 = N->getOperand(0);
2199 SDValue N1 = N->getOperand(1);
2200 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2201 EVT VT = N->getValueType(0);
2204 // fold (mulhs x, 0) -> 0
2205 if (N1C && N1C->isNullValue())
2207 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2208 if (N1C && N1C->getAPIntValue() == 1)
2209 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2210 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2211 getShiftAmountTy(N0.getValueType())));
2212 // fold (mulhs x, undef) -> 0
2213 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2214 return DAG.getConstant(0, VT);
2216 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2218 if (VT.isSimple() && !VT.isVector()) {
2219 MVT Simple = VT.getSimpleVT();
2220 unsigned SimpleSize = Simple.getSizeInBits();
2221 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2222 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2223 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2224 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2225 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2226 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2227 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2228 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2235 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2236 SDValue N0 = N->getOperand(0);
2237 SDValue N1 = N->getOperand(1);
2238 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2239 EVT VT = N->getValueType(0);
2242 // fold (mulhu x, 0) -> 0
2243 if (N1C && N1C->isNullValue())
2245 // fold (mulhu x, 1) -> 0
2246 if (N1C && N1C->getAPIntValue() == 1)
2247 return DAG.getConstant(0, N0.getValueType());
2248 // fold (mulhu x, undef) -> 0
2249 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2250 return DAG.getConstant(0, VT);
2252 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2254 if (VT.isSimple() && !VT.isVector()) {
2255 MVT Simple = VT.getSimpleVT();
2256 unsigned SimpleSize = Simple.getSizeInBits();
2257 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2258 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2259 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2260 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2261 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2262 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2263 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2264 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2271 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2272 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2273 /// that are being performed. Return true if a simplification was made.
2275 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2277 // If the high half is not needed, just compute the low half.
2278 bool HiExists = N->hasAnyUseOfValue(1);
2280 (!LegalOperations ||
2281 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2282 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2283 N->op_begin(), N->getNumOperands());
2284 return CombineTo(N, Res, Res);
2287 // If the low half is not needed, just compute the high half.
2288 bool LoExists = N->hasAnyUseOfValue(0);
2290 (!LegalOperations ||
2291 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2292 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2293 N->op_begin(), N->getNumOperands());
2294 return CombineTo(N, Res, Res);
2297 // If both halves are used, return as it is.
2298 if (LoExists && HiExists)
2301 // If the two computed results can be simplified separately, separate them.
2303 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2304 N->op_begin(), N->getNumOperands());
2305 AddToWorkList(Lo.getNode());
2306 SDValue LoOpt = combine(Lo.getNode());
2307 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2308 (!LegalOperations ||
2309 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2310 return CombineTo(N, LoOpt, LoOpt);
2314 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2315 N->op_begin(), N->getNumOperands());
2316 AddToWorkList(Hi.getNode());
2317 SDValue HiOpt = combine(Hi.getNode());
2318 if (HiOpt.getNode() && HiOpt != Hi &&
2319 (!LegalOperations ||
2320 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2321 return CombineTo(N, HiOpt, HiOpt);
2327 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2328 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2329 if (Res.getNode()) return Res;
2331 EVT VT = N->getValueType(0);
2334 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2336 if (VT.isSimple() && !VT.isVector()) {
2337 MVT Simple = VT.getSimpleVT();
2338 unsigned SimpleSize = Simple.getSizeInBits();
2339 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2340 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2341 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2342 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2343 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2344 // Compute the high part as N1.
2345 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2346 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2347 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2348 // Compute the low part as N0.
2349 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2350 return CombineTo(N, Lo, Hi);
2357 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2358 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2359 if (Res.getNode()) return Res;
2361 EVT VT = N->getValueType(0);
2364 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2366 if (VT.isSimple() && !VT.isVector()) {
2367 MVT Simple = VT.getSimpleVT();
2368 unsigned SimpleSize = Simple.getSizeInBits();
2369 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2370 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2371 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2372 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2373 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2374 // Compute the high part as N1.
2375 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2376 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2377 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2378 // Compute the low part as N0.
2379 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2380 return CombineTo(N, Lo, Hi);
2387 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2388 // (smulo x, 2) -> (saddo x, x)
2389 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2390 if (C2->getAPIntValue() == 2)
2391 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2392 N->getOperand(0), N->getOperand(0));
2397 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2398 // (umulo x, 2) -> (uaddo x, x)
2399 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2400 if (C2->getAPIntValue() == 2)
2401 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2402 N->getOperand(0), N->getOperand(0));
2407 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2408 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2409 if (Res.getNode()) return Res;
2414 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2415 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2416 if (Res.getNode()) return Res;
2421 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2422 /// two operands of the same opcode, try to simplify it.
2423 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2424 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2425 EVT VT = N0.getValueType();
2426 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2428 // Bail early if none of these transforms apply.
2429 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2431 // For each of OP in AND/OR/XOR:
2432 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2433 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2434 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2435 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2437 // do not sink logical op inside of a vector extend, since it may combine
2439 EVT Op0VT = N0.getOperand(0).getValueType();
2440 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2441 N0.getOpcode() == ISD::SIGN_EXTEND ||
2442 // Avoid infinite looping with PromoteIntBinOp.
2443 (N0.getOpcode() == ISD::ANY_EXTEND &&
2444 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2445 (N0.getOpcode() == ISD::TRUNCATE &&
2446 (!TLI.isZExtFree(VT, Op0VT) ||
2447 !TLI.isTruncateFree(Op0VT, VT)) &&
2448 TLI.isTypeLegal(Op0VT))) &&
2450 Op0VT == N1.getOperand(0).getValueType() &&
2451 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2452 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2453 N0.getOperand(0).getValueType(),
2454 N0.getOperand(0), N1.getOperand(0));
2455 AddToWorkList(ORNode.getNode());
2456 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2459 // For each of OP in SHL/SRL/SRA/AND...
2460 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2461 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2462 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2463 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2464 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2465 N0.getOperand(1) == N1.getOperand(1)) {
2466 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2467 N0.getOperand(0).getValueType(),
2468 N0.getOperand(0), N1.getOperand(0));
2469 AddToWorkList(ORNode.getNode());
2470 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2471 ORNode, N0.getOperand(1));
2474 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2475 // Only perform this optimization after type legalization and before
2476 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2477 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2478 // we don't want to undo this promotion.
2479 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2481 if ((N0.getOpcode() == ISD::BITCAST ||
2482 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2483 Level == AfterLegalizeTypes) {
2484 SDValue In0 = N0.getOperand(0);
2485 SDValue In1 = N1.getOperand(0);
2486 EVT In0Ty = In0.getValueType();
2487 EVT In1Ty = In1.getValueType();
2489 // If both incoming values are integers, and the original types are the
2491 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2492 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2493 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2494 AddToWorkList(Op.getNode());
2499 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2500 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2501 // If both shuffles use the same mask, and both shuffle within a single
2502 // vector, then it is worthwhile to move the swizzle after the operation.
2503 // The type-legalizer generates this pattern when loading illegal
2504 // vector types from memory. In many cases this allows additional shuffle
2506 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
2507 N0.getOperand(1).getOpcode() == ISD::UNDEF &&
2508 N1.getOperand(1).getOpcode() == ISD::UNDEF) {
2509 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2510 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2512 assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
2513 "Inputs to shuffles are not the same type");
2515 unsigned NumElts = VT.getVectorNumElements();
2517 // Check that both shuffles use the same mask. The masks are known to be of
2518 // the same length because the result vector type is the same.
2519 bool SameMask = true;
2520 for (unsigned i = 0; i != NumElts; ++i) {
2521 int Idx0 = SVN0->getMaskElt(i);
2522 int Idx1 = SVN1->getMaskElt(i);
2530 SDValue Op = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2531 N0.getOperand(0), N1.getOperand(0));
2532 AddToWorkList(Op.getNode());
2533 return DAG.getVectorShuffle(VT, SDLoc(N), Op,
2534 DAG.getUNDEF(VT), &SVN0->getMask()[0]);
2541 SDValue DAGCombiner::visitAND(SDNode *N) {
2542 SDValue N0 = N->getOperand(0);
2543 SDValue N1 = N->getOperand(1);
2544 SDValue LL, LR, RL, RR, CC0, CC1;
2545 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2546 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2547 EVT VT = N1.getValueType();
2548 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2551 if (VT.isVector()) {
2552 SDValue FoldedVOp = SimplifyVBinOp(N);
2553 if (FoldedVOp.getNode()) return FoldedVOp;
2555 // fold (and x, 0) -> 0, vector edition
2556 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2558 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2561 // fold (and x, -1) -> x, vector edition
2562 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2564 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2568 // fold (and x, undef) -> 0
2569 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2570 return DAG.getConstant(0, VT);
2571 // fold (and c1, c2) -> c1&c2
2573 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2574 // canonicalize constant to RHS
2576 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2577 // fold (and x, -1) -> x
2578 if (N1C && N1C->isAllOnesValue())
2580 // if (and x, c) is known to be zero, return 0
2581 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2582 APInt::getAllOnesValue(BitWidth)))
2583 return DAG.getConstant(0, VT);
2585 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2586 if (RAND.getNode() != 0)
2588 // fold (and (or x, C), D) -> D if (C & D) == D
2589 if (N1C && N0.getOpcode() == ISD::OR)
2590 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2591 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2593 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2594 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2595 SDValue N0Op0 = N0.getOperand(0);
2596 APInt Mask = ~N1C->getAPIntValue();
2597 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2598 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2599 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2600 N0.getValueType(), N0Op0);
2602 // Replace uses of the AND with uses of the Zero extend node.
2605 // We actually want to replace all uses of the any_extend with the
2606 // zero_extend, to avoid duplicating things. This will later cause this
2607 // AND to be folded.
2608 CombineTo(N0.getNode(), Zext);
2609 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2612 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2613 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2614 // already be zero by virtue of the width of the base type of the load.
2616 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2618 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2619 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2620 N0.getOpcode() == ISD::LOAD) {
2621 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2622 N0 : N0.getOperand(0) );
2624 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2625 // This can be a pure constant or a vector splat, in which case we treat the
2626 // vector as a scalar and use the splat value.
2627 APInt Constant = APInt::getNullValue(1);
2628 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2629 Constant = C->getAPIntValue();
2630 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2631 APInt SplatValue, SplatUndef;
2632 unsigned SplatBitSize;
2634 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2635 SplatBitSize, HasAnyUndefs);
2637 // Undef bits can contribute to a possible optimisation if set, so
2639 SplatValue |= SplatUndef;
2641 // The splat value may be something like "0x00FFFFFF", which means 0 for
2642 // the first vector value and FF for the rest, repeating. We need a mask
2643 // that will apply equally to all members of the vector, so AND all the
2644 // lanes of the constant together.
2645 EVT VT = Vector->getValueType(0);
2646 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2648 // If the splat value has been compressed to a bitlength lower
2649 // than the size of the vector lane, we need to re-expand it to
2651 if (BitWidth > SplatBitSize)
2652 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2653 SplatBitSize < BitWidth;
2654 SplatBitSize = SplatBitSize * 2)
2655 SplatValue |= SplatValue.shl(SplatBitSize);
2657 Constant = APInt::getAllOnesValue(BitWidth);
2658 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2659 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2663 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2664 // actually legal and isn't going to get expanded, else this is a false
2666 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2667 Load->getMemoryVT());
2669 // Resize the constant to the same size as the original memory access before
2670 // extension. If it is still the AllOnesValue then this AND is completely
2673 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2676 switch (Load->getExtensionType()) {
2677 default: B = false; break;
2678 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2680 case ISD::NON_EXTLOAD: B = true; break;
2683 if (B && Constant.isAllOnesValue()) {
2684 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2685 // preserve semantics once we get rid of the AND.
2686 SDValue NewLoad(Load, 0);
2687 if (Load->getExtensionType() == ISD::EXTLOAD) {
2688 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2689 Load->getValueType(0), SDLoc(Load),
2690 Load->getChain(), Load->getBasePtr(),
2691 Load->getOffset(), Load->getMemoryVT(),
2692 Load->getMemOperand());
2693 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2694 if (Load->getNumValues() == 3) {
2695 // PRE/POST_INC loads have 3 values.
2696 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2697 NewLoad.getValue(2) };
2698 CombineTo(Load, To, 3, true);
2700 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2704 // Fold the AND away, taking care not to fold to the old load node if we
2706 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2708 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2711 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2712 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2713 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2714 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2716 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2717 LL.getValueType().isInteger()) {
2718 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2719 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2720 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2721 LR.getValueType(), LL, RL);
2722 AddToWorkList(ORNode.getNode());
2723 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2725 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2726 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2727 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2728 LR.getValueType(), LL, RL);
2729 AddToWorkList(ANDNode.getNode());
2730 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2732 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2733 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2734 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2735 LR.getValueType(), LL, RL);
2736 AddToWorkList(ORNode.getNode());
2737 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2740 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2741 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2742 Op0 == Op1 && LL.getValueType().isInteger() &&
2743 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2744 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2745 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2746 cast<ConstantSDNode>(RR)->isNullValue()))) {
2747 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2748 LL, DAG.getConstant(1, LL.getValueType()));
2749 AddToWorkList(ADDNode.getNode());
2750 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2751 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2753 // canonicalize equivalent to ll == rl
2754 if (LL == RR && LR == RL) {
2755 Op1 = ISD::getSetCCSwappedOperands(Op1);
2758 if (LL == RL && LR == RR) {
2759 bool isInteger = LL.getValueType().isInteger();
2760 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2761 if (Result != ISD::SETCC_INVALID &&
2762 (!LegalOperations ||
2763 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2764 TLI.isOperationLegal(ISD::SETCC,
2765 getSetCCResultType(N0.getSimpleValueType())))))
2766 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2771 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2772 if (N0.getOpcode() == N1.getOpcode()) {
2773 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2774 if (Tmp.getNode()) return Tmp;
2777 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2778 // fold (and (sra)) -> (and (srl)) when possible.
2779 if (!VT.isVector() &&
2780 SimplifyDemandedBits(SDValue(N, 0)))
2781 return SDValue(N, 0);
2783 // fold (zext_inreg (extload x)) -> (zextload x)
2784 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2785 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2786 EVT MemVT = LN0->getMemoryVT();
2787 // If we zero all the possible extended bits, then we can turn this into
2788 // a zextload if we are running before legalize or the operation is legal.
2789 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2790 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2791 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2792 ((!LegalOperations && !LN0->isVolatile()) ||
2793 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2794 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2795 LN0->getChain(), LN0->getBasePtr(),
2796 MemVT, LN0->getMemOperand());
2798 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2799 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2802 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2803 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2805 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2806 EVT MemVT = LN0->getMemoryVT();
2807 // If we zero all the possible extended bits, then we can turn this into
2808 // a zextload if we are running before legalize or the operation is legal.
2809 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2810 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2811 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2812 ((!LegalOperations && !LN0->isVolatile()) ||
2813 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2814 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2815 LN0->getChain(), LN0->getBasePtr(),
2816 MemVT, LN0->getMemOperand());
2818 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2819 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2823 // fold (and (load x), 255) -> (zextload x, i8)
2824 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2825 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2826 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2827 (N0.getOpcode() == ISD::ANY_EXTEND &&
2828 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2829 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2830 LoadSDNode *LN0 = HasAnyExt
2831 ? cast<LoadSDNode>(N0.getOperand(0))
2832 : cast<LoadSDNode>(N0);
2833 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2834 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2835 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2836 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2837 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2838 EVT LoadedVT = LN0->getMemoryVT();
2840 if (ExtVT == LoadedVT &&
2841 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2842 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2845 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2846 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2847 LN0->getMemOperand());
2849 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2850 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2853 // Do not change the width of a volatile load.
2854 // Do not generate loads of non-round integer types since these can
2855 // be expensive (and would be wrong if the type is not byte sized).
2856 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2857 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2858 EVT PtrType = LN0->getOperand(1).getValueType();
2860 unsigned Alignment = LN0->getAlignment();
2861 SDValue NewPtr = LN0->getBasePtr();
2863 // For big endian targets, we need to add an offset to the pointer
2864 // to load the correct bytes. For little endian systems, we merely
2865 // need to read fewer bytes from the same pointer.
2866 if (TLI.isBigEndian()) {
2867 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2868 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2869 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2870 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2871 NewPtr, DAG.getConstant(PtrOff, PtrType));
2872 Alignment = MinAlign(Alignment, PtrOff);
2875 AddToWorkList(NewPtr.getNode());
2877 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2879 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2880 LN0->getChain(), NewPtr,
2881 LN0->getPointerInfo(),
2882 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2883 Alignment, LN0->getTBAAInfo());
2885 CombineTo(LN0, Load, Load.getValue(1));
2886 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2892 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2893 VT.getSizeInBits() <= 64) {
2894 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2895 APInt ADDC = ADDI->getAPIntValue();
2896 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2897 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2898 // immediate for an add, but it is legal if its top c2 bits are set,
2899 // transform the ADD so the immediate doesn't need to be materialized
2901 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2902 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2903 SRLI->getZExtValue());
2904 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2906 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2908 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2909 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2910 CombineTo(N0.getNode(), NewAdd);
2911 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2919 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2920 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2921 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2922 N0.getOperand(1), false);
2923 if (BSwap.getNode())
2930 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2932 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2933 bool DemandHighBits) {
2934 if (!LegalOperations)
2937 EVT VT = N->getValueType(0);
2938 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2940 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2943 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2944 bool LookPassAnd0 = false;
2945 bool LookPassAnd1 = false;
2946 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2948 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2950 if (N0.getOpcode() == ISD::AND) {
2951 if (!N0.getNode()->hasOneUse())
2953 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2954 if (!N01C || N01C->getZExtValue() != 0xFF00)
2956 N0 = N0.getOperand(0);
2957 LookPassAnd0 = true;
2960 if (N1.getOpcode() == ISD::AND) {
2961 if (!N1.getNode()->hasOneUse())
2963 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2964 if (!N11C || N11C->getZExtValue() != 0xFF)
2966 N1 = N1.getOperand(0);
2967 LookPassAnd1 = true;
2970 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2972 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2974 if (!N0.getNode()->hasOneUse() ||
2975 !N1.getNode()->hasOneUse())
2978 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2979 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2982 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2985 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
2986 SDValue N00 = N0->getOperand(0);
2987 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
2988 if (!N00.getNode()->hasOneUse())
2990 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
2991 if (!N001C || N001C->getZExtValue() != 0xFF)
2993 N00 = N00.getOperand(0);
2994 LookPassAnd0 = true;
2997 SDValue N10 = N1->getOperand(0);
2998 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
2999 if (!N10.getNode()->hasOneUse())
3001 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3002 if (!N101C || N101C->getZExtValue() != 0xFF00)
3004 N10 = N10.getOperand(0);
3005 LookPassAnd1 = true;
3011 // Make sure everything beyond the low halfword gets set to zero since the SRL
3012 // 16 will clear the top bits.
3013 unsigned OpSizeInBits = VT.getSizeInBits();
3014 if (DemandHighBits && OpSizeInBits > 16) {
3015 // If the left-shift isn't masked out then the only way this is a bswap is
3016 // if all bits beyond the low 8 are 0. In that case the entire pattern
3017 // reduces to a left shift anyway: leave it for other parts of the combiner.
3021 // However, if the right shift isn't masked out then it might be because
3022 // it's not needed. See if we can spot that too.
3023 if (!LookPassAnd1 &&
3024 !DAG.MaskedValueIsZero(
3025 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3029 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3030 if (OpSizeInBits > 16)
3031 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3032 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3036 /// isBSwapHWordElement - Return true if the specified node is an element
3037 /// that makes up a 32-bit packed halfword byteswap. i.e.
3038 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3039 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3040 if (!N.getNode()->hasOneUse())
3043 unsigned Opc = N.getOpcode();
3044 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3047 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3052 switch (N1C->getZExtValue()) {
3055 case 0xFF: Num = 0; break;
3056 case 0xFF00: Num = 1; break;
3057 case 0xFF0000: Num = 2; break;
3058 case 0xFF000000: Num = 3; break;
3061 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3062 SDValue N0 = N.getOperand(0);
3063 if (Opc == ISD::AND) {
3064 if (Num == 0 || Num == 2) {
3066 // (x >> 8) & 0xff0000
3067 if (N0.getOpcode() != ISD::SRL)
3069 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3070 if (!C || C->getZExtValue() != 8)
3073 // (x << 8) & 0xff00
3074 // (x << 8) & 0xff000000
3075 if (N0.getOpcode() != ISD::SHL)
3077 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3078 if (!C || C->getZExtValue() != 8)
3081 } else if (Opc == ISD::SHL) {
3083 // (x & 0xff0000) << 8
3084 if (Num != 0 && Num != 2)
3086 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3087 if (!C || C->getZExtValue() != 8)
3089 } else { // Opc == ISD::SRL
3090 // (x & 0xff00) >> 8
3091 // (x & 0xff000000) >> 8
3092 if (Num != 1 && Num != 3)
3094 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3095 if (!C || C->getZExtValue() != 8)
3102 Parts[Num] = N0.getOperand(0).getNode();
3106 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3107 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3108 /// => (rotl (bswap x), 16)
3109 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3110 if (!LegalOperations)
3113 EVT VT = N->getValueType(0);
3116 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3119 SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
3121 // (or (or (and), (and)), (or (and), (and)))
3122 // (or (or (or (and), (and)), (and)), (and))
3123 if (N0.getOpcode() != ISD::OR)
3125 SDValue N00 = N0.getOperand(0);
3126 SDValue N01 = N0.getOperand(1);
3128 if (N1.getOpcode() == ISD::OR &&
3129 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3130 // (or (or (and), (and)), (or (and), (and)))
3131 SDValue N000 = N00.getOperand(0);
3132 if (!isBSwapHWordElement(N000, Parts))
3135 SDValue N001 = N00.getOperand(1);
3136 if (!isBSwapHWordElement(N001, Parts))
3138 SDValue N010 = N01.getOperand(0);
3139 if (!isBSwapHWordElement(N010, Parts))
3141 SDValue N011 = N01.getOperand(1);
3142 if (!isBSwapHWordElement(N011, Parts))
3145 // (or (or (or (and), (and)), (and)), (and))
3146 if (!isBSwapHWordElement(N1, Parts))
3148 if (!isBSwapHWordElement(N01, Parts))
3150 if (N00.getOpcode() != ISD::OR)
3152 SDValue N000 = N00.getOperand(0);
3153 if (!isBSwapHWordElement(N000, Parts))
3155 SDValue N001 = N00.getOperand(1);
3156 if (!isBSwapHWordElement(N001, Parts))
3160 // Make sure the parts are all coming from the same node.
3161 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3164 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3165 SDValue(Parts[0],0));
3167 // Result of the bswap should be rotated by 16. If it's not legal, then
3168 // do (x << 16) | (x >> 16).
3169 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3170 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3171 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3172 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3173 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3174 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3175 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3176 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3179 SDValue DAGCombiner::visitOR(SDNode *N) {
3180 SDValue N0 = N->getOperand(0);
3181 SDValue N1 = N->getOperand(1);
3182 SDValue LL, LR, RL, RR, CC0, CC1;
3183 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3184 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3185 EVT VT = N1.getValueType();
3188 if (VT.isVector()) {
3189 SDValue FoldedVOp = SimplifyVBinOp(N);
3190 if (FoldedVOp.getNode()) return FoldedVOp;
3192 // fold (or x, 0) -> x, vector edition
3193 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3195 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3198 // fold (or x, -1) -> -1, vector edition
3199 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3201 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3205 // fold (or x, undef) -> -1
3206 if (!LegalOperations &&
3207 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3208 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3209 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3211 // fold (or c1, c2) -> c1|c2
3213 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3214 // canonicalize constant to RHS
3216 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3217 // fold (or x, 0) -> x
3218 if (N1C && N1C->isNullValue())
3220 // fold (or x, -1) -> -1
3221 if (N1C && N1C->isAllOnesValue())
3223 // fold (or x, c) -> c iff (x & ~c) == 0
3224 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3227 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3228 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3229 if (BSwap.getNode() != 0)
3231 BSwap = MatchBSwapHWordLow(N, N0, N1);
3232 if (BSwap.getNode() != 0)
3236 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3237 if (ROR.getNode() != 0)
3239 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3240 // iff (c1 & c2) == 0.
3241 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3242 isa<ConstantSDNode>(N0.getOperand(1))) {
3243 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3244 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3245 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3248 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3249 DAG.getNode(ISD::OR, SDLoc(N0), VT,
3250 N0.getOperand(0), N1), COR);
3253 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3254 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3255 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3256 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3258 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3259 LL.getValueType().isInteger()) {
3260 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3261 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3262 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3263 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3264 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3265 LR.getValueType(), LL, RL);
3266 AddToWorkList(ORNode.getNode());
3267 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3269 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3270 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3271 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3272 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3273 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3274 LR.getValueType(), LL, RL);
3275 AddToWorkList(ANDNode.getNode());
3276 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3279 // canonicalize equivalent to ll == rl
3280 if (LL == RR && LR == RL) {
3281 Op1 = ISD::getSetCCSwappedOperands(Op1);
3284 if (LL == RL && LR == RR) {
3285 bool isInteger = LL.getValueType().isInteger();
3286 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3287 if (Result != ISD::SETCC_INVALID &&
3288 (!LegalOperations ||
3289 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3290 TLI.isOperationLegal(ISD::SETCC,
3291 getSetCCResultType(N0.getValueType())))))
3292 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3297 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3298 if (N0.getOpcode() == N1.getOpcode()) {
3299 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3300 if (Tmp.getNode()) return Tmp;
3303 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3304 if (N0.getOpcode() == ISD::AND &&
3305 N1.getOpcode() == ISD::AND &&
3306 N0.getOperand(1).getOpcode() == ISD::Constant &&
3307 N1.getOperand(1).getOpcode() == ISD::Constant &&
3308 // Don't increase # computations.
3309 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3310 // We can only do this xform if we know that bits from X that are set in C2
3311 // but not in C1 are already zero. Likewise for Y.
3312 const APInt &LHSMask =
3313 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3314 const APInt &RHSMask =
3315 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3317 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3318 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3319 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3320 N0.getOperand(0), N1.getOperand(0));
3321 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3322 DAG.getConstant(LHSMask | RHSMask, VT));
3326 // See if this is some rotate idiom.
3327 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3328 return SDValue(Rot, 0);
3330 // Simplify the operands using demanded-bits information.
3331 if (!VT.isVector() &&
3332 SimplifyDemandedBits(SDValue(N, 0)))
3333 return SDValue(N, 0);
3338 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3339 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3340 if (Op.getOpcode() == ISD::AND) {
3341 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3342 Mask = Op.getOperand(1);
3343 Op = Op.getOperand(0);
3349 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3357 // Return true if we can prove that, whenever Neg and Pos are both in the
3358 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3359 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3361 // (or (shift1 X, Neg), (shift2 X, Pos))
3363 // reduces to a rotate in direction shift2 by Pos and a rotate in direction
3364 // shift1 by Neg. The range [0, OpSize) means that we only need to consider
3365 // shift amounts with defined behavior.
3366 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3367 // If OpSize is a power of 2 then:
3369 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3370 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3372 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3373 // for the stronger condition:
3375 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3377 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3378 // we can just replace Neg with Neg' for the rest of the function.
3380 // In other cases we check for the even stronger condition:
3382 // Neg == OpSize - Pos [B]
3384 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3385 // behavior if Pos == 0 (and consequently Neg == OpSize).
3387 // We could actually use [A] whenever OpSize is a power of 2, but the
3388 // only extra cases that it would match are those uninteresting ones
3389 // where Neg and Pos are never in range at the same time. E.g. for
3390 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3391 // as well as (sub 32, Pos), but:
3393 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3395 // always invokes undefined behavior for 32-bit X.
3397 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3398 unsigned LoBits = 0;
3399 if (Neg.getOpcode() == ISD::AND &&
3400 isPowerOf2_64(OpSize) &&
3401 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3402 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3403 Neg = Neg.getOperand(0);
3404 LoBits = Log2_64(OpSize);
3407 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3408 if (Neg.getOpcode() != ISD::SUB)
3410 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3413 SDValue NegOp1 = Neg.getOperand(1);
3415 // The condition we need is now:
3417 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3419 // If NegOp1 == Pos then we need:
3421 // OpSize & Mask == NegC & Mask
3423 // (because "x & Mask" is a truncation and distributes through subtraction).
3426 Width = NegC->getAPIntValue();
3427 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3428 // Then the condition we want to prove becomes:
3430 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3432 // which, again because "x & Mask" is a truncation, becomes:
3434 // NegC & Mask == (OpSize - PosC) & Mask
3435 // OpSize & Mask == (NegC + PosC) & Mask
3436 else if (Pos.getOpcode() == ISD::ADD &&
3437 Pos.getOperand(0) == NegOp1 &&
3438 Pos.getOperand(1).getOpcode() == ISD::Constant)
3439 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3440 NegC->getAPIntValue());
3444 // Now we just need to check that OpSize & Mask == Width & Mask.
3446 return Width.getLoBits(LoBits) == 0;
3447 return Width == OpSize;
3450 // A subroutine of MatchRotate used once we have found an OR of two opposite
3451 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3452 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3453 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3454 // Neg with outer conversions stripped away.
3455 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3456 SDValue Neg, SDValue InnerPos,
3457 SDValue InnerNeg, unsigned PosOpcode,
3458 unsigned NegOpcode, SDLoc DL) {
3459 // fold (or (shl x, (*ext y)),
3460 // (srl x, (*ext (sub 32, y)))) ->
3461 // (rotl x, y) or (rotr x, (sub 32, y))
3463 // fold (or (shl x, (*ext (sub 32, y))),
3464 // (srl x, (*ext y))) ->
3465 // (rotr x, y) or (rotl x, (sub 32, y))
3466 EVT VT = Shifted.getValueType();
3467 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3468 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3469 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3470 HasPos ? Pos : Neg).getNode();
3473 // fold (or (shl (*ext x), (*ext y)),
3474 // (srl (*ext x), (*ext (sub 32, y)))) ->
3475 // (*ext (rotl x, y)) or (*ext (rotr x, (sub 32, y)))
3477 // fold (or (shl (*ext x), (*ext (sub 32, y))),
3478 // (srl (*ext x), (*ext y))) ->
3479 // (*ext (rotr x, y)) or (*ext (rotl x, (sub 32, y)))
3480 if (Shifted.getOpcode() == ISD::ZERO_EXTEND ||
3481 Shifted.getOpcode() == ISD::ANY_EXTEND) {
3482 SDValue InnerShifted = Shifted.getOperand(0);
3483 EVT InnerVT = InnerShifted.getValueType();
3484 bool HasPosInner = TLI.isOperationLegalOrCustom(PosOpcode, InnerVT);
3485 if (HasPosInner || TLI.isOperationLegalOrCustom(NegOpcode, InnerVT)) {
3486 if (matchRotateSub(InnerPos, InnerNeg, InnerVT.getSizeInBits())) {
3487 SDValue V = DAG.getNode(HasPosInner ? PosOpcode : NegOpcode, DL,
3488 InnerVT, InnerShifted, HasPosInner ? Pos : Neg);
3489 return DAG.getNode(Shifted.getOpcode(), DL, VT, V).getNode();
3497 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3498 // idioms for rotate, and if the target supports rotation instructions, generate
3500 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3501 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3502 EVT VT = LHS.getValueType();
3503 if (!TLI.isTypeLegal(VT)) return 0;
3505 // The target must have at least one rotate flavor.
3506 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3507 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3508 if (!HasROTL && !HasROTR) return 0;
3510 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3511 SDValue LHSShift; // The shift.
3512 SDValue LHSMask; // AND value if any.
3513 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3514 return 0; // Not part of a rotate.
3516 SDValue RHSShift; // The shift.
3517 SDValue RHSMask; // AND value if any.
3518 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3519 return 0; // Not part of a rotate.
3521 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3522 return 0; // Not shifting the same value.
3524 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3525 return 0; // Shifts must disagree.
3527 // Canonicalize shl to left side in a shl/srl pair.
3528 if (RHSShift.getOpcode() == ISD::SHL) {
3529 std::swap(LHS, RHS);
3530 std::swap(LHSShift, RHSShift);
3531 std::swap(LHSMask , RHSMask );
3534 unsigned OpSizeInBits = VT.getSizeInBits();
3535 SDValue LHSShiftArg = LHSShift.getOperand(0);
3536 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3537 SDValue RHSShiftArg = RHSShift.getOperand(0);
3538 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3540 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3541 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3542 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3543 RHSShiftAmt.getOpcode() == ISD::Constant) {
3544 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3545 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3546 if ((LShVal + RShVal) != OpSizeInBits)
3549 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3550 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3552 // If there is an AND of either shifted operand, apply it to the result.
3553 if (LHSMask.getNode() || RHSMask.getNode()) {
3554 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3556 if (LHSMask.getNode()) {
3557 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3558 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3560 if (RHSMask.getNode()) {
3561 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3562 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3565 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3568 return Rot.getNode();
3571 // If there is a mask here, and we have a variable shift, we can't be sure
3572 // that we're masking out the right stuff.
3573 if (LHSMask.getNode() || RHSMask.getNode())
3576 // If the shift amount is sign/zext/any-extended just peel it off.
3577 SDValue LExtOp0 = LHSShiftAmt;
3578 SDValue RExtOp0 = RHSShiftAmt;
3579 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3580 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3581 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3582 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3583 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3584 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3585 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3586 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3587 LExtOp0 = LHSShiftAmt.getOperand(0);
3588 RExtOp0 = RHSShiftAmt.getOperand(0);
3591 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3592 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3596 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3597 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3604 SDValue DAGCombiner::visitXOR(SDNode *N) {
3605 SDValue N0 = N->getOperand(0);
3606 SDValue N1 = N->getOperand(1);
3607 SDValue LHS, RHS, CC;
3608 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3609 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3610 EVT VT = N0.getValueType();
3613 if (VT.isVector()) {
3614 SDValue FoldedVOp = SimplifyVBinOp(N);
3615 if (FoldedVOp.getNode()) return FoldedVOp;
3617 // fold (xor x, 0) -> x, vector edition
3618 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3620 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3624 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3625 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3626 return DAG.getConstant(0, VT);
3627 // fold (xor x, undef) -> undef
3628 if (N0.getOpcode() == ISD::UNDEF)
3630 if (N1.getOpcode() == ISD::UNDEF)
3632 // fold (xor c1, c2) -> c1^c2
3634 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3635 // canonicalize constant to RHS
3637 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3638 // fold (xor x, 0) -> x
3639 if (N1C && N1C->isNullValue())
3642 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3643 if (RXOR.getNode() != 0)
3646 // fold !(x cc y) -> (x !cc y)
3647 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3648 bool isInt = LHS.getValueType().isInteger();
3649 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3652 if (!LegalOperations ||
3653 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3654 switch (N0.getOpcode()) {
3656 llvm_unreachable("Unhandled SetCC Equivalent!");
3658 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3659 case ISD::SELECT_CC:
3660 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3661 N0.getOperand(3), NotCC);
3666 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3667 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3668 N0.getNode()->hasOneUse() &&
3669 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3670 SDValue V = N0.getOperand(0);
3671 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3672 DAG.getConstant(1, V.getValueType()));
3673 AddToWorkList(V.getNode());
3674 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3677 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3678 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3679 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3680 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3681 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3682 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3683 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3684 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3685 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3686 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3689 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3690 if (N1C && N1C->isAllOnesValue() &&
3691 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3692 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3693 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3694 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3695 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3696 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3697 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3698 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3701 // fold (xor (and x, y), y) -> (and (not x), y)
3702 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3703 N0->getOperand(1) == N1) {
3704 SDValue X = N0->getOperand(0);
3705 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3706 AddToWorkList(NotX.getNode());
3707 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3709 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3710 if (N1C && N0.getOpcode() == ISD::XOR) {
3711 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3712 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3714 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3715 DAG.getConstant(N1C->getAPIntValue() ^
3716 N00C->getAPIntValue(), VT));
3718 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3719 DAG.getConstant(N1C->getAPIntValue() ^
3720 N01C->getAPIntValue(), VT));
3722 // fold (xor x, x) -> 0
3724 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3726 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3727 if (N0.getOpcode() == N1.getOpcode()) {
3728 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3729 if (Tmp.getNode()) return Tmp;
3732 // Simplify the expression using non-local knowledge.
3733 if (!VT.isVector() &&
3734 SimplifyDemandedBits(SDValue(N, 0)))
3735 return SDValue(N, 0);
3740 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3741 /// the shift amount is a constant.
3742 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
3743 assert(isa<ConstantSDNode>(N->getOperand(1)) &&
3744 "Expected an ConstantSDNode operand.");
3745 // We can't and shouldn't fold opaque constants.
3746 if (cast<ConstantSDNode>(N->getOperand(1))->isOpaque())
3749 SDNode *LHS = N->getOperand(0).getNode();
3750 if (!LHS->hasOneUse()) return SDValue();
3752 // We want to pull some binops through shifts, so that we have (and (shift))
3753 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3754 // thing happens with address calculations, so it's important to canonicalize
3756 bool HighBitSet = false; // Can we transform this if the high bit is set?
3758 switch (LHS->getOpcode()) {
3759 default: return SDValue();
3762 HighBitSet = false; // We can only transform sra if the high bit is clear.
3765 HighBitSet = true; // We can only transform sra if the high bit is set.
3768 if (N->getOpcode() != ISD::SHL)
3769 return SDValue(); // only shl(add) not sr[al](add).
3770 HighBitSet = false; // We can only transform sra if the high bit is clear.
3774 // We require the RHS of the binop to be a constant and not opaque as well.
3775 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3776 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3778 // FIXME: disable this unless the input to the binop is a shift by a constant.
3779 // If it is not a shift, it pessimizes some common cases like:
3781 // void foo(int *X, int i) { X[i & 1235] = 1; }
3782 // int bar(int *X, int i) { return X[i & 255]; }
3783 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3784 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3785 BinOpLHSVal->getOpcode() != ISD::SRA &&
3786 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3787 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3790 EVT VT = N->getValueType(0);
3792 // If this is a signed shift right, and the high bit is modified by the
3793 // logical operation, do not perform the transformation. The highBitSet
3794 // boolean indicates the value of the high bit of the constant which would
3795 // cause it to be modified for this operation.
3796 if (N->getOpcode() == ISD::SRA) {
3797 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3798 if (BinOpRHSSignSet != HighBitSet)
3802 // Fold the constants, shifting the binop RHS by the shift amount.
3803 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3805 LHS->getOperand(1), N->getOperand(1));
3806 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3808 // Create the new shift.
3809 SDValue NewShift = DAG.getNode(N->getOpcode(),
3810 SDLoc(LHS->getOperand(0)),
3811 VT, LHS->getOperand(0), N->getOperand(1));
3813 // Create the new binop.
3814 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3817 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3818 assert(N->getOpcode() == ISD::TRUNCATE);
3819 assert(N->getOperand(0).getOpcode() == ISD::AND);
3821 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3822 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3823 SDValue N01 = N->getOperand(0).getOperand(1);
3825 if (ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01)) {
3826 EVT TruncVT = N->getValueType(0);
3827 SDValue N00 = N->getOperand(0).getOperand(0);
3828 APInt TruncC = N01C->getAPIntValue();
3829 TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
3831 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3832 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3833 DAG.getConstant(TruncC, TruncVT));
3839 SDValue DAGCombiner::visitSHL(SDNode *N) {
3840 SDValue N0 = N->getOperand(0);
3841 SDValue N1 = N->getOperand(1);
3842 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3843 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3844 EVT VT = N0.getValueType();
3845 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3848 if (VT.isVector()) {
3849 SDValue FoldedVOp = SimplifyVBinOp(N);
3850 if (FoldedVOp.getNode()) return FoldedVOp;
3852 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3853 // If setcc produces all-one true value then:
3854 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
3855 if (N1CV && N1CV->isConstant() &&
3856 TLI.getBooleanContents(true) ==
3857 TargetLowering::ZeroOrNegativeOneBooleanContent &&
3858 N0.getOpcode() == ISD::AND) {
3859 SDValue N00 = N0->getOperand(0);
3860 SDValue N01 = N0->getOperand(1);
3861 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
3863 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC) {
3864 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3866 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3871 // fold (shl c1, c2) -> c1<<c2
3873 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3874 // fold (shl 0, x) -> 0
3875 if (N0C && N0C->isNullValue())
3877 // fold (shl x, c >= size(x)) -> undef
3878 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3879 return DAG.getUNDEF(VT);
3880 // fold (shl x, 0) -> x
3881 if (N1C && N1C->isNullValue())
3883 // fold (shl undef, x) -> 0
3884 if (N0.getOpcode() == ISD::UNDEF)
3885 return DAG.getConstant(0, VT);
3886 // if (shl x, c) is known to be zero, return 0
3887 if (DAG.MaskedValueIsZero(SDValue(N, 0),
3888 APInt::getAllOnesValue(OpSizeInBits)))
3889 return DAG.getConstant(0, VT);
3890 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3891 if (N1.getOpcode() == ISD::TRUNCATE &&
3892 N1.getOperand(0).getOpcode() == ISD::AND) {
3893 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
3894 if (NewOp1.getNode())
3895 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
3898 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3899 return SDValue(N, 0);
3901 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3902 if (N1C && N0.getOpcode() == ISD::SHL &&
3903 N0.getOperand(1).getOpcode() == ISD::Constant) {
3904 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3905 uint64_t c2 = N1C->getZExtValue();
3906 if (c1 + c2 >= OpSizeInBits)
3907 return DAG.getConstant(0, VT);
3908 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3909 DAG.getConstant(c1 + c2, N1.getValueType()));
3912 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3913 // For this to be valid, the second form must not preserve any of the bits
3914 // that are shifted out by the inner shift in the first form. This means
3915 // the outer shift size must be >= the number of bits added by the ext.
3916 // As a corollary, we don't care what kind of ext it is.
3917 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3918 N0.getOpcode() == ISD::ANY_EXTEND ||
3919 N0.getOpcode() == ISD::SIGN_EXTEND) &&
3920 N0.getOperand(0).getOpcode() == ISD::SHL &&
3921 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3923 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3924 uint64_t c2 = N1C->getZExtValue();
3925 EVT InnerShiftVT = N0.getOperand(0).getValueType();
3926 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3927 if (c2 >= OpSizeInBits - InnerShiftSize) {
3928 if (c1 + c2 >= OpSizeInBits)
3929 return DAG.getConstant(0, VT);
3930 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
3931 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
3932 N0.getOperand(0)->getOperand(0)),
3933 DAG.getConstant(c1 + c2, N1.getValueType()));
3937 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
3938 // Only fold this if the inner zext has no other uses to avoid increasing
3939 // the total number of instructions.
3940 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
3941 N0.getOperand(0).getOpcode() == ISD::SRL &&
3942 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3944 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3945 if (c1 < VT.getSizeInBits()) {
3946 uint64_t c2 = N1C->getZExtValue();
3948 SDValue NewOp0 = N0.getOperand(0);
3949 EVT CountVT = NewOp0.getOperand(1).getValueType();
3950 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
3951 NewOp0, DAG.getConstant(c2, CountVT));
3952 AddToWorkList(NewSHL.getNode());
3953 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
3958 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
3959 // (and (srl x, (sub c1, c2), MASK)
3960 // Only fold this if the inner shift has no other uses -- if it does, folding
3961 // this will increase the total number of instructions.
3962 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
3963 N0.getOperand(1).getOpcode() == ISD::Constant) {
3964 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3965 if (c1 < VT.getSizeInBits()) {
3966 uint64_t c2 = N1C->getZExtValue();
3967 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3968 VT.getSizeInBits() - c1);
3971 Mask = Mask.shl(c2-c1);
3972 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3973 DAG.getConstant(c2-c1, N1.getValueType()));
3975 Mask = Mask.lshr(c1-c2);
3976 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
3977 DAG.getConstant(c1-c2, N1.getValueType()));
3979 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
3980 DAG.getConstant(Mask, VT));
3983 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
3984 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3985 SDValue HiBitsMask =
3986 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3987 VT.getSizeInBits() -
3988 N1C->getZExtValue()),
3990 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
3995 SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3996 if (NewSHL.getNode())
4003 SDValue DAGCombiner::visitSRA(SDNode *N) {
4004 SDValue N0 = N->getOperand(0);
4005 SDValue N1 = N->getOperand(1);
4006 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4007 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4008 EVT VT = N0.getValueType();
4009 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4012 if (VT.isVector()) {
4013 SDValue FoldedVOp = SimplifyVBinOp(N);
4014 if (FoldedVOp.getNode()) return FoldedVOp;
4017 // fold (sra c1, c2) -> (sra c1, c2)
4019 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4020 // fold (sra 0, x) -> 0
4021 if (N0C && N0C->isNullValue())
4023 // fold (sra -1, x) -> -1
4024 if (N0C && N0C->isAllOnesValue())
4026 // fold (sra x, (setge c, size(x))) -> undef
4027 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4028 return DAG.getUNDEF(VT);
4029 // fold (sra x, 0) -> x
4030 if (N1C && N1C->isNullValue())
4032 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4034 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4035 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4036 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4038 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4039 ExtVT, VT.getVectorNumElements());
4040 if ((!LegalOperations ||
4041 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4042 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4043 N0.getOperand(0), DAG.getValueType(ExtVT));
4046 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4047 if (N1C && N0.getOpcode() == ISD::SRA) {
4048 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4049 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4050 if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
4051 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4052 DAG.getConstant(Sum, N1C->getValueType(0)));
4056 // fold (sra (shl X, m), (sub result_size, n))
4057 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4058 // result_size - n != m.
4059 // If truncate is free for the target sext(shl) is likely to result in better
4061 if (N0.getOpcode() == ISD::SHL) {
4062 // Get the two constanst of the shifts, CN0 = m, CN = n.
4063 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4065 // Determine what the truncate's result bitsize and type would be.
4067 EVT::getIntegerVT(*DAG.getContext(),
4068 OpSizeInBits - N1C->getZExtValue());
4069 // Determine the residual right-shift amount.
4070 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4072 // If the shift is not a no-op (in which case this should be just a sign
4073 // extend already), the truncated to type is legal, sign_extend is legal
4074 // on that type, and the truncate to that type is both legal and free,
4075 // perform the transform.
4076 if ((ShiftAmt > 0) &&
4077 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4078 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4079 TLI.isTruncateFree(VT, TruncVT)) {
4081 SDValue Amt = DAG.getConstant(ShiftAmt,
4082 getShiftAmountTy(N0.getOperand(0).getValueType()));
4083 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4084 N0.getOperand(0), Amt);
4085 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4087 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4088 N->getValueType(0), Trunc);
4093 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4094 if (N1.getOpcode() == ISD::TRUNCATE &&
4095 N1.getOperand(0).getOpcode() == ISD::AND) {
4096 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4097 if (NewOp1.getNode())
4098 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4101 // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
4102 // if c1 is equal to the number of bits the trunc removes
4103 if (N0.getOpcode() == ISD::TRUNCATE &&
4104 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4105 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4106 N0.getOperand(0).hasOneUse() &&
4107 N0.getOperand(0).getOperand(1).hasOneUse() &&
4108 N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
4109 EVT LargeVT = N0.getOperand(0).getValueType();
4110 ConstantSDNode *LargeShiftAmt =
4111 cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
4113 if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
4114 LargeShiftAmt->getZExtValue()) {
4116 DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
4117 getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
4118 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4119 N0.getOperand(0).getOperand(0), Amt);
4120 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4124 // Simplify, based on bits shifted out of the LHS.
4125 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4126 return SDValue(N, 0);
4129 // If the sign bit is known to be zero, switch this to a SRL.
4130 if (DAG.SignBitIsZero(N0))
4131 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4134 SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
4135 if (NewSRA.getNode())
4142 SDValue DAGCombiner::visitSRL(SDNode *N) {
4143 SDValue N0 = N->getOperand(0);
4144 SDValue N1 = N->getOperand(1);
4145 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4146 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4147 EVT VT = N0.getValueType();
4148 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4151 if (VT.isVector()) {
4152 SDValue FoldedVOp = SimplifyVBinOp(N);
4153 if (FoldedVOp.getNode()) return FoldedVOp;
4156 // fold (srl c1, c2) -> c1 >>u c2
4158 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4159 // fold (srl 0, x) -> 0
4160 if (N0C && N0C->isNullValue())
4162 // fold (srl x, c >= size(x)) -> undef
4163 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4164 return DAG.getUNDEF(VT);
4165 // fold (srl x, 0) -> x
4166 if (N1C && N1C->isNullValue())
4168 // if (srl x, c) is known to be zero, return 0
4169 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4170 APInt::getAllOnesValue(OpSizeInBits)))
4171 return DAG.getConstant(0, VT);
4173 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4174 if (N1C && N0.getOpcode() == ISD::SRL &&
4175 N0.getOperand(1).getOpcode() == ISD::Constant) {
4176 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
4177 uint64_t c2 = N1C->getZExtValue();
4178 if (c1 + c2 >= OpSizeInBits)
4179 return DAG.getConstant(0, VT);
4180 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4181 DAG.getConstant(c1 + c2, N1.getValueType()));
4184 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4185 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4186 N0.getOperand(0).getOpcode() == ISD::SRL &&
4187 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4189 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4190 uint64_t c2 = N1C->getZExtValue();
4191 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4192 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4193 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4194 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4195 if (c1 + OpSizeInBits == InnerShiftSize) {
4196 if (c1 + c2 >= InnerShiftSize)
4197 return DAG.getConstant(0, VT);
4198 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4199 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4200 N0.getOperand(0)->getOperand(0),
4201 DAG.getConstant(c1 + c2, ShiftCountVT)));
4205 // fold (srl (shl x, c), c) -> (and x, cst2)
4206 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
4207 N0.getValueSizeInBits() <= 64) {
4208 uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
4209 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4210 DAG.getConstant(~0ULL >> ShAmt, VT));
4213 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4214 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4215 // Shifting in all undef bits?
4216 EVT SmallVT = N0.getOperand(0).getValueType();
4217 if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
4218 return DAG.getUNDEF(VT);
4220 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4221 uint64_t ShiftAmt = N1C->getZExtValue();
4222 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4224 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4225 AddToWorkList(SmallShift.getNode());
4226 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits()).lshr(ShiftAmt);
4227 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4228 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4229 DAG.getConstant(Mask, VT));
4233 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4234 // bit, which is unmodified by sra.
4235 if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
4236 if (N0.getOpcode() == ISD::SRA)
4237 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4240 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4241 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4242 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
4243 APInt KnownZero, KnownOne;
4244 DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
4246 // If any of the input bits are KnownOne, then the input couldn't be all
4247 // zeros, thus the result of the srl will always be zero.
4248 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4250 // If all of the bits input the to ctlz node are known to be zero, then
4251 // the result of the ctlz is "32" and the result of the shift is one.
4252 APInt UnknownBits = ~KnownZero;
4253 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4255 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4256 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4257 // Okay, we know that only that the single bit specified by UnknownBits
4258 // could be set on input to the CTLZ node. If this bit is set, the SRL
4259 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4260 // to an SRL/XOR pair, which is likely to simplify more.
4261 unsigned ShAmt = UnknownBits.countTrailingZeros();
4262 SDValue Op = N0.getOperand(0);
4265 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4266 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4267 AddToWorkList(Op.getNode());
4270 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4271 Op, DAG.getConstant(1, VT));
4275 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4276 if (N1.getOpcode() == ISD::TRUNCATE &&
4277 N1.getOperand(0).getOpcode() == ISD::AND) {
4278 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4279 if (NewOp1.getNode())
4280 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4283 // fold operands of srl based on knowledge that the low bits are not
4285 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4286 return SDValue(N, 0);
4289 SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
4290 if (NewSRL.getNode())
4294 // Attempt to convert a srl of a load into a narrower zero-extending load.
4295 SDValue NarrowLoad = ReduceLoadWidth(N);
4296 if (NarrowLoad.getNode())
4299 // Here is a common situation. We want to optimize:
4302 // %b = and i32 %a, 2
4303 // %c = srl i32 %b, 1
4304 // brcond i32 %c ...
4310 // %c = setcc eq %b, 0
4313 // However when after the source operand of SRL is optimized into AND, the SRL
4314 // itself may not be optimized further. Look for it and add the BRCOND into
4316 if (N->hasOneUse()) {
4317 SDNode *Use = *N->use_begin();
4318 if (Use->getOpcode() == ISD::BRCOND)
4320 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4321 // Also look pass the truncate.
4322 Use = *Use->use_begin();
4323 if (Use->getOpcode() == ISD::BRCOND)
4331 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4332 SDValue N0 = N->getOperand(0);
4333 EVT VT = N->getValueType(0);
4335 // fold (ctlz c1) -> c2
4336 if (isa<ConstantSDNode>(N0))
4337 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4341 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4342 SDValue N0 = N->getOperand(0);
4343 EVT VT = N->getValueType(0);
4345 // fold (ctlz_zero_undef c1) -> c2
4346 if (isa<ConstantSDNode>(N0))
4347 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4351 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4352 SDValue N0 = N->getOperand(0);
4353 EVT VT = N->getValueType(0);
4355 // fold (cttz c1) -> c2
4356 if (isa<ConstantSDNode>(N0))
4357 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4361 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4362 SDValue N0 = N->getOperand(0);
4363 EVT VT = N->getValueType(0);
4365 // fold (cttz_zero_undef c1) -> c2
4366 if (isa<ConstantSDNode>(N0))
4367 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4371 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4372 SDValue N0 = N->getOperand(0);
4373 EVT VT = N->getValueType(0);
4375 // fold (ctpop c1) -> c2
4376 if (isa<ConstantSDNode>(N0))
4377 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4381 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4382 SDValue N0 = N->getOperand(0);
4383 SDValue N1 = N->getOperand(1);
4384 SDValue N2 = N->getOperand(2);
4385 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4386 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4387 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4388 EVT VT = N->getValueType(0);
4389 EVT VT0 = N0.getValueType();
4391 // fold (select C, X, X) -> X
4394 // fold (select true, X, Y) -> X
4395 if (N0C && !N0C->isNullValue())
4397 // fold (select false, X, Y) -> Y
4398 if (N0C && N0C->isNullValue())
4400 // fold (select C, 1, X) -> (or C, X)
4401 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4402 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4403 // fold (select C, 0, 1) -> (xor C, 1)
4404 if (VT.isInteger() &&
4407 TLI.getBooleanContents(false) ==
4408 TargetLowering::ZeroOrOneBooleanContent)) &&
4409 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4412 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4413 N0, DAG.getConstant(1, VT0));
4414 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4415 N0, DAG.getConstant(1, VT0));
4416 AddToWorkList(XORNode.getNode());
4418 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4419 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4421 // fold (select C, 0, X) -> (and (not C), X)
4422 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4423 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4424 AddToWorkList(NOTNode.getNode());
4425 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4427 // fold (select C, X, 1) -> (or (not C), X)
4428 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4429 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4430 AddToWorkList(NOTNode.getNode());
4431 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4433 // fold (select C, X, 0) -> (and C, X)
4434 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4435 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4436 // fold (select X, X, Y) -> (or X, Y)
4437 // fold (select X, 1, Y) -> (or X, Y)
4438 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4439 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4440 // fold (select X, Y, X) -> (and X, Y)
4441 // fold (select X, Y, 0) -> (and X, Y)
4442 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4443 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4445 // If we can fold this based on the true/false value, do so.
4446 if (SimplifySelectOps(N, N1, N2))
4447 return SDValue(N, 0); // Don't revisit N.
4449 // fold selects based on a setcc into other things, such as min/max/abs
4450 if (N0.getOpcode() == ISD::SETCC) {
4452 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4453 // having to say they don't support SELECT_CC on every type the DAG knows
4454 // about, since there is no way to mark an opcode illegal at all value types
4455 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4456 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4457 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4458 N0.getOperand(0), N0.getOperand(1),
4459 N1, N2, N0.getOperand(2));
4460 return SimplifySelect(SDLoc(N), N0, N1, N2);
4467 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4470 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4472 // Split the inputs.
4473 SDValue Lo, Hi, LL, LH, RL, RH;
4474 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4475 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4477 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4478 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4480 return std::make_pair(Lo, Hi);
4483 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4484 SDValue N0 = N->getOperand(0);
4485 SDValue N1 = N->getOperand(1);
4486 SDValue N2 = N->getOperand(2);
4489 // Canonicalize integer abs.
4490 // vselect (setg[te] X, 0), X, -X ->
4491 // vselect (setgt X, -1), X, -X ->
4492 // vselect (setl[te] X, 0), -X, X ->
4493 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4494 if (N0.getOpcode() == ISD::SETCC) {
4495 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4496 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4498 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4500 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4501 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4502 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4503 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4504 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4505 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4506 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4509 EVT VT = LHS.getValueType();
4510 SDValue Shift = DAG.getNode(
4511 ISD::SRA, DL, VT, LHS,
4512 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4513 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4514 AddToWorkList(Shift.getNode());
4515 AddToWorkList(Add.getNode());
4516 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4520 // If the VSELECT result requires splitting and the mask is provided by a
4521 // SETCC, then split both nodes and its operands before legalization. This
4522 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4523 // and enables future optimizations (e.g. min/max pattern matching on X86).
4524 if (N0.getOpcode() == ISD::SETCC) {
4525 EVT VT = N->getValueType(0);
4527 // Check if any splitting is required.
4528 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4529 TargetLowering::TypeSplitVector)
4532 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4533 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4534 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4535 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4537 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4538 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4540 // Add the new VSELECT nodes to the work list in case they need to be split
4542 AddToWorkList(Lo.getNode());
4543 AddToWorkList(Hi.getNode());
4545 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4548 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4549 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4551 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4552 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4558 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4559 SDValue N0 = N->getOperand(0);
4560 SDValue N1 = N->getOperand(1);
4561 SDValue N2 = N->getOperand(2);
4562 SDValue N3 = N->getOperand(3);
4563 SDValue N4 = N->getOperand(4);
4564 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4566 // fold select_cc lhs, rhs, x, x, cc -> x
4570 // Determine if the condition we're dealing with is constant
4571 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4572 N0, N1, CC, SDLoc(N), false);
4573 if (SCC.getNode()) {
4574 AddToWorkList(SCC.getNode());
4576 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4577 if (!SCCC->isNullValue())
4578 return N2; // cond always true -> true val
4580 return N3; // cond always false -> false val
4583 // Fold to a simpler select_cc
4584 if (SCC.getOpcode() == ISD::SETCC)
4585 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4586 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4590 // If we can fold this based on the true/false value, do so.
4591 if (SimplifySelectOps(N, N2, N3))
4592 return SDValue(N, 0); // Don't revisit N.
4594 // fold select_cc into other things, such as min/max/abs
4595 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4598 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4599 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4600 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4604 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4605 // dag node into a ConstantSDNode or a build_vector of constants.
4606 // This function is called by the DAGCombiner when visiting sext/zext/aext
4607 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4608 // Vector extends are not folded if operations are legal; this is to
4609 // avoid introducing illegal build_vector dag nodes.
4610 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4611 SelectionDAG &DAG, bool LegalTypes,
4612 bool LegalOperations) {
4613 unsigned Opcode = N->getOpcode();
4614 SDValue N0 = N->getOperand(0);
4615 EVT VT = N->getValueType(0);
4617 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4618 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4620 // fold (sext c1) -> c1
4621 // fold (zext c1) -> c1
4622 // fold (aext c1) -> c1
4623 if (isa<ConstantSDNode>(N0))
4624 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4626 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4627 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4628 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4629 EVT SVT = VT.getScalarType();
4630 if (!(VT.isVector() &&
4631 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4632 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4635 // We can fold this node into a build_vector.
4636 unsigned VTBits = SVT.getSizeInBits();
4637 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4638 unsigned ShAmt = VTBits - EVTBits;
4639 SmallVector<SDValue, 8> Elts;
4640 unsigned NumElts = N0->getNumOperands();
4643 for (unsigned i=0; i != NumElts; ++i) {
4644 SDValue Op = N0->getOperand(i);
4645 if (Op->getOpcode() == ISD::UNDEF) {
4646 Elts.push_back(DAG.getUNDEF(SVT));
4650 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4651 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4652 if (Opcode == ISD::SIGN_EXTEND)
4653 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4656 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4660 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], NumElts).getNode();
4663 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4664 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4665 // transformation. Returns true if extension are possible and the above
4666 // mentioned transformation is profitable.
4667 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4669 SmallVectorImpl<SDNode *> &ExtendNodes,
4670 const TargetLowering &TLI) {
4671 bool HasCopyToRegUses = false;
4672 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4673 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4674 UE = N0.getNode()->use_end();
4679 if (UI.getUse().getResNo() != N0.getResNo())
4681 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4682 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4683 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4684 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4685 // Sign bits will be lost after a zext.
4688 for (unsigned i = 0; i != 2; ++i) {
4689 SDValue UseOp = User->getOperand(i);
4692 if (!isa<ConstantSDNode>(UseOp))
4697 ExtendNodes.push_back(User);
4700 // If truncates aren't free and there are users we can't
4701 // extend, it isn't worthwhile.
4704 // Remember if this value is live-out.
4705 if (User->getOpcode() == ISD::CopyToReg)
4706 HasCopyToRegUses = true;
4709 if (HasCopyToRegUses) {
4710 bool BothLiveOut = false;
4711 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4713 SDUse &Use = UI.getUse();
4714 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4720 // Both unextended and extended values are live out. There had better be
4721 // a good reason for the transformation.
4722 return ExtendNodes.size();
4727 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4728 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4729 ISD::NodeType ExtType) {
4730 // Extend SetCC uses if necessary.
4731 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4732 SDNode *SetCC = SetCCs[i];
4733 SmallVector<SDValue, 4> Ops;
4735 for (unsigned j = 0; j != 2; ++j) {
4736 SDValue SOp = SetCC->getOperand(j);
4738 Ops.push_back(ExtLoad);
4740 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4743 Ops.push_back(SetCC->getOperand(2));
4744 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4745 &Ops[0], Ops.size()));
4749 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4750 SDValue N0 = N->getOperand(0);
4751 EVT VT = N->getValueType(0);
4753 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4755 return SDValue(Res, 0);
4757 // fold (sext (sext x)) -> (sext x)
4758 // fold (sext (aext x)) -> (sext x)
4759 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4760 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4763 if (N0.getOpcode() == ISD::TRUNCATE) {
4764 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4765 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4766 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4767 if (NarrowLoad.getNode()) {
4768 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4769 if (NarrowLoad.getNode() != N0.getNode()) {
4770 CombineTo(N0.getNode(), NarrowLoad);
4771 // CombineTo deleted the truncate, if needed, but not what's under it.
4774 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4777 // See if the value being truncated is already sign extended. If so, just
4778 // eliminate the trunc/sext pair.
4779 SDValue Op = N0.getOperand(0);
4780 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4781 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4782 unsigned DestBits = VT.getScalarType().getSizeInBits();
4783 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4785 if (OpBits == DestBits) {
4786 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4787 // bits, it is already ready.
4788 if (NumSignBits > DestBits-MidBits)
4790 } else if (OpBits < DestBits) {
4791 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4792 // bits, just sext from i32.
4793 if (NumSignBits > OpBits-MidBits)
4794 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4796 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4797 // bits, just truncate to i32.
4798 if (NumSignBits > OpBits-MidBits)
4799 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4802 // fold (sext (truncate x)) -> (sextinreg x).
4803 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4804 N0.getValueType())) {
4805 if (OpBits < DestBits)
4806 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4807 else if (OpBits > DestBits)
4808 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4809 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4810 DAG.getValueType(N0.getValueType()));
4814 // fold (sext (load x)) -> (sext (truncate (sextload x)))
4815 // None of the supported targets knows how to perform load and sign extend
4816 // on vectors in one instruction. We only perform this transformation on
4818 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4819 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4820 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4821 bool DoXform = true;
4822 SmallVector<SDNode*, 4> SetCCs;
4823 if (!N0.hasOneUse())
4824 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4826 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4827 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4829 LN0->getBasePtr(), N0.getValueType(),
4830 LN0->getMemOperand());
4831 CombineTo(N, ExtLoad);
4832 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4833 N0.getValueType(), ExtLoad);
4834 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4835 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4837 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4841 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4842 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4843 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4844 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4845 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4846 EVT MemVT = LN0->getMemoryVT();
4847 if ((!LegalOperations && !LN0->isVolatile()) ||
4848 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4849 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4851 LN0->getBasePtr(), MemVT,
4852 LN0->getMemOperand());
4853 CombineTo(N, ExtLoad);
4854 CombineTo(N0.getNode(),
4855 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4856 N0.getValueType(), ExtLoad),
4857 ExtLoad.getValue(1));
4858 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4862 // fold (sext (and/or/xor (load x), cst)) ->
4863 // (and/or/xor (sextload x), (sext cst))
4864 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4865 N0.getOpcode() == ISD::XOR) &&
4866 isa<LoadSDNode>(N0.getOperand(0)) &&
4867 N0.getOperand(1).getOpcode() == ISD::Constant &&
4868 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4869 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4870 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4871 if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4872 bool DoXform = true;
4873 SmallVector<SDNode*, 4> SetCCs;
4874 if (!N0.hasOneUse())
4875 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4878 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
4879 LN0->getChain(), LN0->getBasePtr(),
4881 LN0->getMemOperand());
4882 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4883 Mask = Mask.sext(VT.getSizeInBits());
4884 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4885 ExtLoad, DAG.getConstant(Mask, VT));
4886 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4887 SDLoc(N0.getOperand(0)),
4888 N0.getOperand(0).getValueType(), ExtLoad);
4890 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4891 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4893 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4898 if (N0.getOpcode() == ISD::SETCC) {
4899 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
4900 // Only do this before legalize for now.
4901 if (VT.isVector() && !LegalOperations &&
4902 TLI.getBooleanContents(true) ==
4903 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4904 EVT N0VT = N0.getOperand(0).getValueType();
4905 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
4906 // of the same size as the compared operands. Only optimize sext(setcc())
4907 // if this is the case.
4908 EVT SVT = getSetCCResultType(N0VT);
4910 // We know that the # elements of the results is the same as the
4911 // # elements of the compare (and the # elements of the compare result
4912 // for that matter). Check to see that they are the same size. If so,
4913 // we know that the element size of the sext'd result matches the
4914 // element size of the compare operands.
4915 if (VT.getSizeInBits() == SVT.getSizeInBits())
4916 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4918 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4920 // If the desired elements are smaller or larger than the source
4921 // elements we can use a matching integer vector type and then
4922 // truncate/sign extend
4923 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
4924 if (SVT == MatchingVectorType) {
4925 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
4926 N0.getOperand(0), N0.getOperand(1),
4927 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4928 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
4932 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
4933 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
4935 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
4937 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
4938 NegOne, DAG.getConstant(0, VT),
4939 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4940 if (SCC.getNode()) return SCC;
4942 if (!VT.isVector()) {
4943 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
4944 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
4946 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4947 SDValue SetCC = DAG.getSetCC(DL,
4949 N0.getOperand(0), N0.getOperand(1), CC);
4950 EVT SelectVT = getSetCCResultType(VT);
4951 return DAG.getSelect(DL, VT,
4952 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
4953 NegOne, DAG.getConstant(0, VT));
4959 // fold (sext x) -> (zext x) if the sign bit is known zero.
4960 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
4961 DAG.SignBitIsZero(N0))
4962 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4967 // isTruncateOf - If N is a truncate of some other value, return true, record
4968 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
4969 // This function computes KnownZero to avoid a duplicated call to
4970 // ComputeMaskedBits in the caller.
4971 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
4974 if (N->getOpcode() == ISD::TRUNCATE) {
4975 Op = N->getOperand(0);
4976 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4980 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
4981 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
4984 SDValue Op0 = N->getOperand(0);
4985 SDValue Op1 = N->getOperand(1);
4986 assert(Op0.getValueType() == Op1.getValueType());
4988 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
4989 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
4990 if (COp0 && COp0->isNullValue())
4992 else if (COp1 && COp1->isNullValue())
4997 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4999 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5005 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5006 SDValue N0 = N->getOperand(0);
5007 EVT VT = N->getValueType(0);
5009 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5011 return SDValue(Res, 0);
5013 // fold (zext (zext x)) -> (zext x)
5014 // fold (zext (aext x)) -> (zext x)
5015 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5016 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5019 // fold (zext (truncate x)) -> (zext x) or
5020 // (zext (truncate x)) -> (truncate x)
5021 // This is valid when the truncated bits of x are already zero.
5022 // FIXME: We should extend this to work for vectors too.
5025 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5026 APInt TruncatedBits =
5027 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5028 APInt(Op.getValueSizeInBits(), 0) :
5029 APInt::getBitsSet(Op.getValueSizeInBits(),
5030 N0.getValueSizeInBits(),
5031 std::min(Op.getValueSizeInBits(),
5032 VT.getSizeInBits()));
5033 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5034 if (VT.bitsGT(Op.getValueType()))
5035 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5036 if (VT.bitsLT(Op.getValueType()))
5037 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5043 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5044 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5045 if (N0.getOpcode() == ISD::TRUNCATE) {
5046 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5047 if (NarrowLoad.getNode()) {
5048 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5049 if (NarrowLoad.getNode() != N0.getNode()) {
5050 CombineTo(N0.getNode(), NarrowLoad);
5051 // CombineTo deleted the truncate, if needed, but not what's under it.
5054 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5058 // fold (zext (truncate x)) -> (and x, mask)
5059 if (N0.getOpcode() == ISD::TRUNCATE &&
5060 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5062 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5063 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5064 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5065 if (NarrowLoad.getNode()) {
5066 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5067 if (NarrowLoad.getNode() != N0.getNode()) {
5068 CombineTo(N0.getNode(), NarrowLoad);
5069 // CombineTo deleted the truncate, if needed, but not what's under it.
5072 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5075 SDValue Op = N0.getOperand(0);
5076 if (Op.getValueType().bitsLT(VT)) {
5077 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5078 AddToWorkList(Op.getNode());
5079 } else if (Op.getValueType().bitsGT(VT)) {
5080 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5081 AddToWorkList(Op.getNode());
5083 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5084 N0.getValueType().getScalarType());
5087 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5088 // if either of the casts is not free.
5089 if (N0.getOpcode() == ISD::AND &&
5090 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5091 N0.getOperand(1).getOpcode() == ISD::Constant &&
5092 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5093 N0.getValueType()) ||
5094 !TLI.isZExtFree(N0.getValueType(), VT))) {
5095 SDValue X = N0.getOperand(0).getOperand(0);
5096 if (X.getValueType().bitsLT(VT)) {
5097 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5098 } else if (X.getValueType().bitsGT(VT)) {
5099 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5101 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5102 Mask = Mask.zext(VT.getSizeInBits());
5103 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5104 X, DAG.getConstant(Mask, VT));
5107 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5108 // None of the supported targets knows how to perform load and vector_zext
5109 // on vectors in one instruction. We only perform this transformation on
5111 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5112 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5113 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5114 bool DoXform = true;
5115 SmallVector<SDNode*, 4> SetCCs;
5116 if (!N0.hasOneUse())
5117 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5119 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5120 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5122 LN0->getBasePtr(), N0.getValueType(),
5123 LN0->getMemOperand());
5124 CombineTo(N, ExtLoad);
5125 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5126 N0.getValueType(), ExtLoad);
5127 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5129 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5131 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5135 // fold (zext (and/or/xor (load x), cst)) ->
5136 // (and/or/xor (zextload x), (zext cst))
5137 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5138 N0.getOpcode() == ISD::XOR) &&
5139 isa<LoadSDNode>(N0.getOperand(0)) &&
5140 N0.getOperand(1).getOpcode() == ISD::Constant &&
5141 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5142 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5143 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5144 if (LN0->getExtensionType() != ISD::SEXTLOAD) {
5145 bool DoXform = true;
5146 SmallVector<SDNode*, 4> SetCCs;
5147 if (!N0.hasOneUse())
5148 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5151 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5152 LN0->getChain(), LN0->getBasePtr(),
5154 LN0->getMemOperand());
5155 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5156 Mask = Mask.zext(VT.getSizeInBits());
5157 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5158 ExtLoad, DAG.getConstant(Mask, VT));
5159 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5160 SDLoc(N0.getOperand(0)),
5161 N0.getOperand(0).getValueType(), ExtLoad);
5163 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5164 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5166 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5171 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5172 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5173 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5174 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5175 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5176 EVT MemVT = LN0->getMemoryVT();
5177 if ((!LegalOperations && !LN0->isVolatile()) ||
5178 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5179 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5181 LN0->getBasePtr(), MemVT,
5182 LN0->getMemOperand());
5183 CombineTo(N, ExtLoad);
5184 CombineTo(N0.getNode(),
5185 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5187 ExtLoad.getValue(1));
5188 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5192 if (N0.getOpcode() == ISD::SETCC) {
5193 if (!LegalOperations && VT.isVector() &&
5194 N0.getValueType().getVectorElementType() == MVT::i1) {
5195 EVT N0VT = N0.getOperand(0).getValueType();
5196 if (getSetCCResultType(N0VT) == N0.getValueType())
5199 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5200 // Only do this before legalize for now.
5201 EVT EltVT = VT.getVectorElementType();
5202 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5203 DAG.getConstant(1, EltVT));
5204 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5205 // We know that the # elements of the results is the same as the
5206 // # elements of the compare (and the # elements of the compare result
5207 // for that matter). Check to see that they are the same size. If so,
5208 // we know that the element size of the sext'd result matches the
5209 // element size of the compare operands.
5210 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5211 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5213 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5214 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5215 &OneOps[0], OneOps.size()));
5217 // If the desired elements are smaller or larger than the source
5218 // elements we can use a matching integer vector type and then
5219 // truncate/sign extend
5220 EVT MatchingElementType =
5221 EVT::getIntegerVT(*DAG.getContext(),
5222 N0VT.getScalarType().getSizeInBits());
5223 EVT MatchingVectorType =
5224 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5225 N0VT.getVectorNumElements());
5227 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5229 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5230 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5231 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5232 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5233 &OneOps[0], OneOps.size()));
5236 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5238 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5239 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5240 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5241 if (SCC.getNode()) return SCC;
5244 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5245 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5246 isa<ConstantSDNode>(N0.getOperand(1)) &&
5247 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5249 SDValue ShAmt = N0.getOperand(1);
5250 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5251 if (N0.getOpcode() == ISD::SHL) {
5252 SDValue InnerZExt = N0.getOperand(0);
5253 // If the original shl may be shifting out bits, do not perform this
5255 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5256 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5257 if (ShAmtVal > KnownZeroBits)
5263 // Ensure that the shift amount is wide enough for the shifted value.
5264 if (VT.getSizeInBits() >= 256)
5265 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5267 return DAG.getNode(N0.getOpcode(), DL, VT,
5268 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5275 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5276 SDValue N0 = N->getOperand(0);
5277 EVT VT = N->getValueType(0);
5279 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5281 return SDValue(Res, 0);
5283 // fold (aext (aext x)) -> (aext x)
5284 // fold (aext (zext x)) -> (zext x)
5285 // fold (aext (sext x)) -> (sext x)
5286 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5287 N0.getOpcode() == ISD::ZERO_EXTEND ||
5288 N0.getOpcode() == ISD::SIGN_EXTEND)
5289 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5291 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5292 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5293 if (N0.getOpcode() == ISD::TRUNCATE) {
5294 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5295 if (NarrowLoad.getNode()) {
5296 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5297 if (NarrowLoad.getNode() != N0.getNode()) {
5298 CombineTo(N0.getNode(), NarrowLoad);
5299 // CombineTo deleted the truncate, if needed, but not what's under it.
5302 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5306 // fold (aext (truncate x))
5307 if (N0.getOpcode() == ISD::TRUNCATE) {
5308 SDValue TruncOp = N0.getOperand(0);
5309 if (TruncOp.getValueType() == VT)
5310 return TruncOp; // x iff x size == zext size.
5311 if (TruncOp.getValueType().bitsGT(VT))
5312 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5313 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5316 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5317 // if the trunc is not free.
5318 if (N0.getOpcode() == ISD::AND &&
5319 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5320 N0.getOperand(1).getOpcode() == ISD::Constant &&
5321 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5322 N0.getValueType())) {
5323 SDValue X = N0.getOperand(0).getOperand(0);
5324 if (X.getValueType().bitsLT(VT)) {
5325 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5326 } else if (X.getValueType().bitsGT(VT)) {
5327 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5329 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5330 Mask = Mask.zext(VT.getSizeInBits());
5331 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5332 X, DAG.getConstant(Mask, VT));
5335 // fold (aext (load x)) -> (aext (truncate (extload x)))
5336 // None of the supported targets knows how to perform load and any_ext
5337 // on vectors in one instruction. We only perform this transformation on
5339 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5340 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5341 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5342 bool DoXform = true;
5343 SmallVector<SDNode*, 4> SetCCs;
5344 if (!N0.hasOneUse())
5345 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5347 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5348 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5350 LN0->getBasePtr(), N0.getValueType(),
5351 LN0->getMemOperand());
5352 CombineTo(N, ExtLoad);
5353 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5354 N0.getValueType(), ExtLoad);
5355 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5356 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5358 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5362 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5363 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5364 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5365 if (N0.getOpcode() == ISD::LOAD &&
5366 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5368 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5369 EVT MemVT = LN0->getMemoryVT();
5370 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N),
5371 VT, LN0->getChain(), LN0->getBasePtr(),
5372 MemVT, LN0->getMemOperand());
5373 CombineTo(N, ExtLoad);
5374 CombineTo(N0.getNode(),
5375 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5376 N0.getValueType(), ExtLoad),
5377 ExtLoad.getValue(1));
5378 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5381 if (N0.getOpcode() == ISD::SETCC) {
5382 // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5383 // Only do this before legalize for now.
5384 if (VT.isVector() && !LegalOperations) {
5385 EVT N0VT = N0.getOperand(0).getValueType();
5386 // We know that the # elements of the results is the same as the
5387 // # elements of the compare (and the # elements of the compare result
5388 // for that matter). Check to see that they are the same size. If so,
5389 // we know that the element size of the sext'd result matches the
5390 // element size of the compare operands.
5391 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5392 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5394 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5395 // If the desired elements are smaller or larger than the source
5396 // elements we can use a matching integer vector type and then
5397 // truncate/sign extend
5399 EVT MatchingElementType =
5400 EVT::getIntegerVT(*DAG.getContext(),
5401 N0VT.getScalarType().getSizeInBits());
5402 EVT MatchingVectorType =
5403 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5404 N0VT.getVectorNumElements());
5406 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5408 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5409 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5413 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5415 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5416 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5417 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5425 /// GetDemandedBits - See if the specified operand can be simplified with the
5426 /// knowledge that only the bits specified by Mask are used. If so, return the
5427 /// simpler operand, otherwise return a null SDValue.
5428 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5429 switch (V.getOpcode()) {
5431 case ISD::Constant: {
5432 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5433 assert(CV != 0 && "Const value should be ConstSDNode.");
5434 const APInt &CVal = CV->getAPIntValue();
5435 APInt NewVal = CVal & Mask;
5437 return DAG.getConstant(NewVal, V.getValueType());
5442 // If the LHS or RHS don't contribute bits to the or, drop them.
5443 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5444 return V.getOperand(1);
5445 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5446 return V.getOperand(0);
5449 // Only look at single-use SRLs.
5450 if (!V.getNode()->hasOneUse())
5452 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5453 // See if we can recursively simplify the LHS.
5454 unsigned Amt = RHSC->getZExtValue();
5456 // Watch out for shift count overflow though.
5457 if (Amt >= Mask.getBitWidth()) break;
5458 APInt NewMask = Mask << Amt;
5459 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5460 if (SimplifyLHS.getNode())
5461 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5462 SimplifyLHS, V.getOperand(1));
5468 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5469 /// bits and then truncated to a narrower type and where N is a multiple
5470 /// of number of bits of the narrower type, transform it to a narrower load
5471 /// from address + N / num of bits of new type. If the result is to be
5472 /// extended, also fold the extension to form a extending load.
5473 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5474 unsigned Opc = N->getOpcode();
5476 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5477 SDValue N0 = N->getOperand(0);
5478 EVT VT = N->getValueType(0);
5481 // This transformation isn't valid for vector loads.
5485 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5487 if (Opc == ISD::SIGN_EXTEND_INREG) {
5488 ExtType = ISD::SEXTLOAD;
5489 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5490 } else if (Opc == ISD::SRL) {
5491 // Another special-case: SRL is basically zero-extending a narrower value.
5492 ExtType = ISD::ZEXTLOAD;
5494 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5495 if (!N01) return SDValue();
5496 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5497 VT.getSizeInBits() - N01->getZExtValue());
5499 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5502 unsigned EVTBits = ExtVT.getSizeInBits();
5504 // Do not generate loads of non-round integer types since these can
5505 // be expensive (and would be wrong if the type is not byte sized).
5506 if (!ExtVT.isRound())
5510 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5511 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5512 ShAmt = N01->getZExtValue();
5513 // Is the shift amount a multiple of size of VT?
5514 if ((ShAmt & (EVTBits-1)) == 0) {
5515 N0 = N0.getOperand(0);
5516 // Is the load width a multiple of size of VT?
5517 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5521 // At this point, we must have a load or else we can't do the transform.
5522 if (!isa<LoadSDNode>(N0)) return SDValue();
5524 // Because a SRL must be assumed to *need* to zero-extend the high bits
5525 // (as opposed to anyext the high bits), we can't combine the zextload
5526 // lowering of SRL and an sextload.
5527 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5530 // If the shift amount is larger than the input type then we're not
5531 // accessing any of the loaded bytes. If the load was a zextload/extload
5532 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5533 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5538 // If the load is shifted left (and the result isn't shifted back right),
5539 // we can fold the truncate through the shift.
5540 unsigned ShLeftAmt = 0;
5541 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5542 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5543 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5544 ShLeftAmt = N01->getZExtValue();
5545 N0 = N0.getOperand(0);
5549 // If we haven't found a load, we can't narrow it. Don't transform one with
5550 // multiple uses, this would require adding a new load.
5551 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5554 // Don't change the width of a volatile load.
5555 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5556 if (LN0->isVolatile())
5559 // Verify that we are actually reducing a load width here.
5560 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5563 // For the transform to be legal, the load must produce only two values
5564 // (the value loaded and the chain). Don't transform a pre-increment
5565 // load, for example, which produces an extra value. Otherwise the
5566 // transformation is not equivalent, and the downstream logic to replace
5567 // uses gets things wrong.
5568 if (LN0->getNumValues() > 2)
5571 // If the load that we're shrinking is an extload and we're not just
5572 // discarding the extension we can't simply shrink the load. Bail.
5573 // TODO: It would be possible to merge the extensions in some cases.
5574 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5575 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5578 EVT PtrType = N0.getOperand(1).getValueType();
5580 if (PtrType == MVT::Untyped || PtrType.isExtended())
5581 // It's not possible to generate a constant of extended or untyped type.
5584 // For big endian targets, we need to adjust the offset to the pointer to
5585 // load the correct bytes.
5586 if (TLI.isBigEndian()) {
5587 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5588 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5589 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5592 uint64_t PtrOff = ShAmt / 8;
5593 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5594 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5595 PtrType, LN0->getBasePtr(),
5596 DAG.getConstant(PtrOff, PtrType));
5597 AddToWorkList(NewPtr.getNode());
5600 if (ExtType == ISD::NON_EXTLOAD)
5601 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5602 LN0->getPointerInfo().getWithOffset(PtrOff),
5603 LN0->isVolatile(), LN0->isNonTemporal(),
5604 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5606 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5607 LN0->getPointerInfo().getWithOffset(PtrOff),
5608 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5609 NewAlign, LN0->getTBAAInfo());
5611 // Replace the old load's chain with the new load's chain.
5612 WorkListRemover DeadNodes(*this);
5613 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5615 // Shift the result left, if we've swallowed a left shift.
5616 SDValue Result = Load;
5617 if (ShLeftAmt != 0) {
5618 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5619 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5621 // If the shift amount is as large as the result size (but, presumably,
5622 // no larger than the source) then the useful bits of the result are
5623 // zero; we can't simply return the shortened shift, because the result
5624 // of that operation is undefined.
5625 if (ShLeftAmt >= VT.getSizeInBits())
5626 Result = DAG.getConstant(0, VT);
5628 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5629 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5632 // Return the new loaded value.
5636 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5637 SDValue N0 = N->getOperand(0);
5638 SDValue N1 = N->getOperand(1);
5639 EVT VT = N->getValueType(0);
5640 EVT EVT = cast<VTSDNode>(N1)->getVT();
5641 unsigned VTBits = VT.getScalarType().getSizeInBits();
5642 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5644 // fold (sext_in_reg c1) -> c1
5645 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5646 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5648 // If the input is already sign extended, just drop the extension.
5649 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5652 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5653 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5654 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5655 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5656 N0.getOperand(0), N1);
5658 // fold (sext_in_reg (sext x)) -> (sext x)
5659 // fold (sext_in_reg (aext x)) -> (sext x)
5660 // if x is small enough.
5661 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5662 SDValue N00 = N0.getOperand(0);
5663 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5664 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5665 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5668 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5669 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5670 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5672 // fold operands of sext_in_reg based on knowledge that the top bits are not
5674 if (SimplifyDemandedBits(SDValue(N, 0)))
5675 return SDValue(N, 0);
5677 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5678 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5679 SDValue NarrowLoad = ReduceLoadWidth(N);
5680 if (NarrowLoad.getNode())
5683 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5684 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5685 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5686 if (N0.getOpcode() == ISD::SRL) {
5687 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5688 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5689 // We can turn this into an SRA iff the input to the SRL is already sign
5691 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5692 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5693 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5694 N0.getOperand(0), N0.getOperand(1));
5698 // fold (sext_inreg (extload x)) -> (sextload x)
5699 if (ISD::isEXTLoad(N0.getNode()) &&
5700 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5701 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5702 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5703 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5704 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5705 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5707 LN0->getBasePtr(), EVT,
5708 LN0->getMemOperand());
5709 CombineTo(N, ExtLoad);
5710 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5711 AddToWorkList(ExtLoad.getNode());
5712 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5714 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5715 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5717 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5718 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5719 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5720 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5721 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5723 LN0->getBasePtr(), EVT,
5724 LN0->getMemOperand());
5725 CombineTo(N, ExtLoad);
5726 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5727 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5730 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5731 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5732 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5733 N0.getOperand(1), false);
5734 if (BSwap.getNode() != 0)
5735 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5739 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5740 // into a build_vector.
5741 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5742 SmallVector<SDValue, 8> Elts;
5743 unsigned NumElts = N0->getNumOperands();
5744 unsigned ShAmt = VTBits - EVTBits;
5746 for (unsigned i = 0; i != NumElts; ++i) {
5747 SDValue Op = N0->getOperand(i);
5748 if (Op->getOpcode() == ISD::UNDEF) {
5753 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5754 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5755 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5756 Op.getValueType()));
5759 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Elts[0], NumElts);
5765 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5766 SDValue N0 = N->getOperand(0);
5767 EVT VT = N->getValueType(0);
5768 bool isLE = TLI.isLittleEndian();
5771 if (N0.getValueType() == N->getValueType(0))
5773 // fold (truncate c1) -> c1
5774 if (isa<ConstantSDNode>(N0))
5775 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5776 // fold (truncate (truncate x)) -> (truncate x)
5777 if (N0.getOpcode() == ISD::TRUNCATE)
5778 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5779 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5780 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5781 N0.getOpcode() == ISD::SIGN_EXTEND ||
5782 N0.getOpcode() == ISD::ANY_EXTEND) {
5783 if (N0.getOperand(0).getValueType().bitsLT(VT))
5784 // if the source is smaller than the dest, we still need an extend
5785 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5787 if (N0.getOperand(0).getValueType().bitsGT(VT))
5788 // if the source is larger than the dest, than we just need the truncate
5789 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5790 // if the source and dest are the same type, we can drop both the extend
5791 // and the truncate.
5792 return N0.getOperand(0);
5795 // Fold extract-and-trunc into a narrow extract. For example:
5796 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5797 // i32 y = TRUNCATE(i64 x)
5799 // v16i8 b = BITCAST (v2i64 val)
5800 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5802 // Note: We only run this optimization after type legalization (which often
5803 // creates this pattern) and before operation legalization after which
5804 // we need to be more careful about the vector instructions that we generate.
5805 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5806 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
5808 EVT VecTy = N0.getOperand(0).getValueType();
5809 EVT ExTy = N0.getValueType();
5810 EVT TrTy = N->getValueType(0);
5812 unsigned NumElem = VecTy.getVectorNumElements();
5813 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5815 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5816 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5818 SDValue EltNo = N0->getOperand(1);
5819 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5820 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5821 EVT IndexTy = TLI.getVectorIdxTy();
5822 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5824 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5825 NVT, N0.getOperand(0));
5827 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5829 DAG.getConstant(Index, IndexTy));
5833 // Fold a series of buildvector, bitcast, and truncate if possible.
5835 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5836 // (2xi32 (buildvector x, y)).
5837 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5838 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5839 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5840 N0.getOperand(0).hasOneUse()) {
5842 SDValue BuildVect = N0.getOperand(0);
5843 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5844 EVT TruncVecEltTy = VT.getVectorElementType();
5846 // Check that the element types match.
5847 if (BuildVectEltTy == TruncVecEltTy) {
5848 // Now we only need to compute the offset of the truncated elements.
5849 unsigned BuildVecNumElts = BuildVect.getNumOperands();
5850 unsigned TruncVecNumElts = VT.getVectorNumElements();
5851 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5853 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5854 "Invalid number of elements");
5856 SmallVector<SDValue, 8> Opnds;
5857 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5858 Opnds.push_back(BuildVect.getOperand(i));
5860 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
5865 // See if we can simplify the input to this truncate through knowledge that
5866 // only the low bits are being used.
5867 // For example "trunc (or (shl x, 8), y)" // -> trunc y
5868 // Currently we only perform this optimization on scalars because vectors
5869 // may have different active low bits.
5870 if (!VT.isVector()) {
5872 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5873 VT.getSizeInBits()));
5874 if (Shorter.getNode())
5875 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
5877 // fold (truncate (load x)) -> (smaller load x)
5878 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5879 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5880 SDValue Reduced = ReduceLoadWidth(N);
5881 if (Reduced.getNode())
5883 // Handle the case where the load remains an extending load even
5884 // after truncation.
5885 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
5886 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5887 if (!LN0->isVolatile() &&
5888 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
5889 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
5890 VT, LN0->getChain(), LN0->getBasePtr(),
5892 LN0->getMemOperand());
5893 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
5898 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
5899 // where ... are all 'undef'.
5900 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
5901 SmallVector<EVT, 8> VTs;
5904 unsigned NumDefs = 0;
5906 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
5907 SDValue X = N0.getOperand(i);
5908 if (X.getOpcode() != ISD::UNDEF) {
5913 // Stop if more than one members are non-undef.
5916 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
5917 VT.getVectorElementType(),
5918 X.getValueType().getVectorNumElements()));
5922 return DAG.getUNDEF(VT);
5925 assert(V.getNode() && "The single defined operand is empty!");
5926 SmallVector<SDValue, 8> Opnds;
5927 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
5929 Opnds.push_back(DAG.getUNDEF(VTs[i]));
5932 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
5933 AddToWorkList(NV.getNode());
5934 Opnds.push_back(NV);
5936 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
5937 &Opnds[0], Opnds.size());
5941 // Simplify the operands using demanded-bits information.
5942 if (!VT.isVector() &&
5943 SimplifyDemandedBits(SDValue(N, 0)))
5944 return SDValue(N, 0);
5949 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
5950 SDValue Elt = N->getOperand(i);
5951 if (Elt.getOpcode() != ISD::MERGE_VALUES)
5952 return Elt.getNode();
5953 return Elt.getOperand(Elt.getResNo()).getNode();
5956 /// CombineConsecutiveLoads - build_pair (load, load) -> load
5957 /// if load locations are consecutive.
5958 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
5959 assert(N->getOpcode() == ISD::BUILD_PAIR);
5961 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
5962 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
5963 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
5964 LD1->getAddressSpace() != LD2->getAddressSpace())
5966 EVT LD1VT = LD1->getValueType(0);
5968 if (ISD::isNON_EXTLoad(LD2) &&
5970 // If both are volatile this would reduce the number of volatile loads.
5971 // If one is volatile it might be ok, but play conservative and bail out.
5972 !LD1->isVolatile() &&
5973 !LD2->isVolatile() &&
5974 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
5975 unsigned Align = LD1->getAlignment();
5976 unsigned NewAlign = TLI.getDataLayout()->
5977 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5979 if (NewAlign <= Align &&
5980 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
5981 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
5982 LD1->getBasePtr(), LD1->getPointerInfo(),
5983 false, false, false, Align);
5989 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
5990 SDValue N0 = N->getOperand(0);
5991 EVT VT = N->getValueType(0);
5993 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
5994 // Only do this before legalize, since afterward the target may be depending
5995 // on the bitconvert.
5996 // First check to see if this is all constant.
5998 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6000 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6002 EVT DestEltVT = N->getValueType(0).getVectorElementType();
6003 assert(!DestEltVT.isVector() &&
6004 "Element type of vector ValueType must not be vector!");
6006 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6009 // If the input is a constant, let getNode fold it.
6010 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6011 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6012 if (Res.getNode() != N) {
6013 if (!LegalOperations ||
6014 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6017 // Folding it resulted in an illegal node, and it's too late to
6018 // do that. Clean up the old node and forego the transformation.
6019 // Ideally this won't happen very often, because instcombine
6020 // and the earlier dagcombine runs (where illegal nodes are
6021 // permitted) should have folded most of them already.
6022 DAG.DeleteNode(Res.getNode());
6026 // (conv (conv x, t1), t2) -> (conv x, t2)
6027 if (N0.getOpcode() == ISD::BITCAST)
6028 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6031 // fold (conv (load x)) -> (load (conv*)x)
6032 // If the resultant load doesn't need a higher alignment than the original!
6033 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6034 // Do not change the width of a volatile load.
6035 !cast<LoadSDNode>(N0)->isVolatile() &&
6036 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6037 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6038 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6039 unsigned Align = TLI.getDataLayout()->
6040 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6041 unsigned OrigAlign = LN0->getAlignment();
6043 if (Align <= OrigAlign) {
6044 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6045 LN0->getBasePtr(), LN0->getPointerInfo(),
6046 LN0->isVolatile(), LN0->isNonTemporal(),
6047 LN0->isInvariant(), OrigAlign,
6048 LN0->getTBAAInfo());
6050 CombineTo(N0.getNode(),
6051 DAG.getNode(ISD::BITCAST, SDLoc(N0),
6052 N0.getValueType(), Load),
6058 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6059 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6060 // This often reduces constant pool loads.
6061 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6062 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6063 N0.getNode()->hasOneUse() && VT.isInteger() &&
6064 !VT.isVector() && !N0.getValueType().isVector()) {
6065 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6067 AddToWorkList(NewConv.getNode());
6069 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6070 if (N0.getOpcode() == ISD::FNEG)
6071 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6072 NewConv, DAG.getConstant(SignBit, VT));
6073 assert(N0.getOpcode() == ISD::FABS);
6074 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6075 NewConv, DAG.getConstant(~SignBit, VT));
6078 // fold (bitconvert (fcopysign cst, x)) ->
6079 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6080 // Note that we don't handle (copysign x, cst) because this can always be
6081 // folded to an fneg or fabs.
6082 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6083 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6084 VT.isInteger() && !VT.isVector()) {
6085 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6086 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6087 if (isTypeLegal(IntXVT)) {
6088 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6089 IntXVT, N0.getOperand(1));
6090 AddToWorkList(X.getNode());
6092 // If X has a different width than the result/lhs, sext it or truncate it.
6093 unsigned VTWidth = VT.getSizeInBits();
6094 if (OrigXWidth < VTWidth) {
6095 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6096 AddToWorkList(X.getNode());
6097 } else if (OrigXWidth > VTWidth) {
6098 // To get the sign bit in the right place, we have to shift it right
6099 // before truncating.
6100 X = DAG.getNode(ISD::SRL, SDLoc(X),
6101 X.getValueType(), X,
6102 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6103 AddToWorkList(X.getNode());
6104 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6105 AddToWorkList(X.getNode());
6108 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6109 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6110 X, DAG.getConstant(SignBit, VT));
6111 AddToWorkList(X.getNode());
6113 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6114 VT, N0.getOperand(0));
6115 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6116 Cst, DAG.getConstant(~SignBit, VT));
6117 AddToWorkList(Cst.getNode());
6119 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6123 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6124 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6125 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6126 if (CombineLD.getNode())
6133 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6134 EVT VT = N->getValueType(0);
6135 return CombineConsecutiveLoads(N, VT);
6138 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6139 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
6140 /// destination element value type.
6141 SDValue DAGCombiner::
6142 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6143 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6145 // If this is already the right type, we're done.
6146 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6148 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6149 unsigned DstBitSize = DstEltVT.getSizeInBits();
6151 // If this is a conversion of N elements of one type to N elements of another
6152 // type, convert each element. This handles FP<->INT cases.
6153 if (SrcBitSize == DstBitSize) {
6154 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6155 BV->getValueType(0).getVectorNumElements());
6157 // Due to the FP element handling below calling this routine recursively,
6158 // we can end up with a scalar-to-vector node here.
6159 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6160 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6161 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6162 DstEltVT, BV->getOperand(0)));
6164 SmallVector<SDValue, 8> Ops;
6165 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6166 SDValue Op = BV->getOperand(i);
6167 // If the vector element type is not legal, the BUILD_VECTOR operands
6168 // are promoted and implicitly truncated. Make that explicit here.
6169 if (Op.getValueType() != SrcEltVT)
6170 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6171 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6173 AddToWorkList(Ops.back().getNode());
6175 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6176 &Ops[0], Ops.size());
6179 // Otherwise, we're growing or shrinking the elements. To avoid having to
6180 // handle annoying details of growing/shrinking FP values, we convert them to
6182 if (SrcEltVT.isFloatingPoint()) {
6183 // Convert the input float vector to a int vector where the elements are the
6185 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6186 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6187 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6191 // Now we know the input is an integer vector. If the output is a FP type,
6192 // convert to integer first, then to FP of the right size.
6193 if (DstEltVT.isFloatingPoint()) {
6194 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6195 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6196 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6198 // Next, convert to FP elements of the same size.
6199 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6202 // Okay, we know the src/dst types are both integers of differing types.
6203 // Handling growing first.
6204 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6205 if (SrcBitSize < DstBitSize) {
6206 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6208 SmallVector<SDValue, 8> Ops;
6209 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6210 i += NumInputsPerOutput) {
6211 bool isLE = TLI.isLittleEndian();
6212 APInt NewBits = APInt(DstBitSize, 0);
6213 bool EltIsUndef = true;
6214 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6215 // Shift the previously computed bits over.
6216 NewBits <<= SrcBitSize;
6217 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6218 if (Op.getOpcode() == ISD::UNDEF) continue;
6221 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6222 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6226 Ops.push_back(DAG.getUNDEF(DstEltVT));
6228 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6231 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6232 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6233 &Ops[0], Ops.size());
6236 // Finally, this must be the case where we are shrinking elements: each input
6237 // turns into multiple outputs.
6238 bool isS2V = ISD::isScalarToVector(BV);
6239 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6240 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6241 NumOutputsPerInput*BV->getNumOperands());
6242 SmallVector<SDValue, 8> Ops;
6244 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6245 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6246 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6247 Ops.push_back(DAG.getUNDEF(DstEltVT));
6251 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6252 getAPIntValue().zextOrTrunc(SrcBitSize);
6254 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6255 APInt ThisVal = OpVal.trunc(DstBitSize);
6256 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6257 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6258 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6259 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6261 OpVal = OpVal.lshr(DstBitSize);
6264 // For big endian targets, swap the order of the pieces of each element.
6265 if (TLI.isBigEndian())
6266 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6269 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6270 &Ops[0], Ops.size());
6273 SDValue DAGCombiner::visitFADD(SDNode *N) {
6274 SDValue N0 = N->getOperand(0);
6275 SDValue N1 = N->getOperand(1);
6276 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6277 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6278 EVT VT = N->getValueType(0);
6281 if (VT.isVector()) {
6282 SDValue FoldedVOp = SimplifyVBinOp(N);
6283 if (FoldedVOp.getNode()) return FoldedVOp;
6286 // fold (fadd c1, c2) -> c1 + c2
6288 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6289 // canonicalize constant to RHS
6290 if (N0CFP && !N1CFP)
6291 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6292 // fold (fadd A, 0) -> A
6293 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6294 N1CFP->getValueAPF().isZero())
6296 // fold (fadd A, (fneg B)) -> (fsub A, B)
6297 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6298 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6299 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6300 GetNegatedExpression(N1, DAG, LegalOperations));
6301 // fold (fadd (fneg A), B) -> (fsub B, A)
6302 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6303 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6304 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6305 GetNegatedExpression(N0, DAG, LegalOperations));
6307 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6308 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6309 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6310 isa<ConstantFPSDNode>(N0.getOperand(1)))
6311 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6312 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6313 N0.getOperand(1), N1));
6315 // No FP constant should be created after legalization as Instruction
6316 // Selection pass has hard time in dealing with FP constant.
6318 // We don't need test this condition for transformation like following, as
6319 // the DAG being transformed implies it is legal to take FP constant as
6322 // (fadd (fmul c, x), x) -> (fmul c+1, x)
6324 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6326 // If allow, fold (fadd (fneg x), x) -> 0.0
6327 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6328 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6329 return DAG.getConstantFP(0.0, VT);
6331 // If allow, fold (fadd x, (fneg x)) -> 0.0
6332 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6333 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6334 return DAG.getConstantFP(0.0, VT);
6336 // In unsafe math mode, we can fold chains of FADD's of the same value
6337 // into multiplications. This transform is not safe in general because
6338 // we are reducing the number of rounding steps.
6339 if (DAG.getTarget().Options.UnsafeFPMath &&
6340 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6342 if (N0.getOpcode() == ISD::FMUL) {
6343 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6344 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6346 // (fadd (fmul c, x), x) -> (fmul x, c+1)
6347 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6348 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6350 DAG.getConstantFP(1.0, VT));
6351 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6355 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6356 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6357 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6359 DAG.getConstantFP(1.0, VT));
6360 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6364 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6365 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6366 N1.getOperand(0) == N1.getOperand(1) &&
6367 N0.getOperand(1) == N1.getOperand(0)) {
6368 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6370 DAG.getConstantFP(2.0, VT));
6371 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6372 N0.getOperand(1), NewCFP);
6375 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6376 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6377 N1.getOperand(0) == N1.getOperand(1) &&
6378 N0.getOperand(0) == N1.getOperand(0)) {
6379 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6381 DAG.getConstantFP(2.0, VT));
6382 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6383 N0.getOperand(0), NewCFP);
6387 if (N1.getOpcode() == ISD::FMUL) {
6388 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6389 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6391 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6392 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6393 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6395 DAG.getConstantFP(1.0, VT));
6396 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6400 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6401 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6402 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6404 DAG.getConstantFP(1.0, VT));
6405 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6410 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6411 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6412 N0.getOperand(0) == N0.getOperand(1) &&
6413 N1.getOperand(1) == N0.getOperand(0)) {
6414 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6416 DAG.getConstantFP(2.0, VT));
6417 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6418 N1.getOperand(1), NewCFP);
6421 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6422 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6423 N0.getOperand(0) == N0.getOperand(1) &&
6424 N1.getOperand(0) == N0.getOperand(0)) {
6425 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6427 DAG.getConstantFP(2.0, VT));
6428 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6429 N1.getOperand(0), NewCFP);
6433 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6434 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6435 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6436 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6437 (N0.getOperand(0) == N1))
6438 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6439 N1, DAG.getConstantFP(3.0, VT));
6442 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6443 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6444 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6445 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6446 N1.getOperand(0) == N0)
6447 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6448 N0, DAG.getConstantFP(3.0, VT));
6451 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6452 if (AllowNewFpConst &&
6453 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6454 N0.getOperand(0) == N0.getOperand(1) &&
6455 N1.getOperand(0) == N1.getOperand(1) &&
6456 N0.getOperand(0) == N1.getOperand(0))
6457 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6459 DAG.getConstantFP(4.0, VT));
6462 // FADD -> FMA combines:
6463 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6464 DAG.getTarget().Options.UnsafeFPMath) &&
6465 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6466 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6468 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6469 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6470 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6471 N0.getOperand(0), N0.getOperand(1), N1);
6473 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6474 // Note: Commutes FADD operands.
6475 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6476 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6477 N1.getOperand(0), N1.getOperand(1), N0);
6483 SDValue DAGCombiner::visitFSUB(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);
6492 if (VT.isVector()) {
6493 SDValue FoldedVOp = SimplifyVBinOp(N);
6494 if (FoldedVOp.getNode()) return FoldedVOp;
6497 // fold (fsub c1, c2) -> c1-c2
6499 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6500 // fold (fsub A, 0) -> A
6501 if (DAG.getTarget().Options.UnsafeFPMath &&
6502 N1CFP && N1CFP->getValueAPF().isZero())
6504 // fold (fsub 0, B) -> -B
6505 if (DAG.getTarget().Options.UnsafeFPMath &&
6506 N0CFP && N0CFP->getValueAPF().isZero()) {
6507 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6508 return GetNegatedExpression(N1, DAG, LegalOperations);
6509 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6510 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6512 // fold (fsub A, (fneg B)) -> (fadd A, B)
6513 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6514 return DAG.getNode(ISD::FADD, dl, VT, N0,
6515 GetNegatedExpression(N1, DAG, LegalOperations));
6517 // If 'unsafe math' is enabled, fold
6518 // (fsub x, x) -> 0.0 &
6519 // (fsub x, (fadd x, y)) -> (fneg y) &
6520 // (fsub x, (fadd y, x)) -> (fneg y)
6521 if (DAG.getTarget().Options.UnsafeFPMath) {
6523 return DAG.getConstantFP(0.0f, VT);
6525 if (N1.getOpcode() == ISD::FADD) {
6526 SDValue N10 = N1->getOperand(0);
6527 SDValue N11 = N1->getOperand(1);
6529 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6530 &DAG.getTarget().Options))
6531 return GetNegatedExpression(N11, DAG, LegalOperations);
6533 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6534 &DAG.getTarget().Options))
6535 return GetNegatedExpression(N10, DAG, LegalOperations);
6539 // FSUB -> FMA combines:
6540 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6541 DAG.getTarget().Options.UnsafeFPMath) &&
6542 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6543 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6545 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6546 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6547 return DAG.getNode(ISD::FMA, dl, VT,
6548 N0.getOperand(0), N0.getOperand(1),
6549 DAG.getNode(ISD::FNEG, dl, VT, N1));
6551 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6552 // Note: Commutes FSUB operands.
6553 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6554 return DAG.getNode(ISD::FMA, dl, VT,
6555 DAG.getNode(ISD::FNEG, dl, VT,
6557 N1.getOperand(1), N0);
6559 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6560 if (N0.getOpcode() == ISD::FNEG &&
6561 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6562 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6563 SDValue N00 = N0.getOperand(0).getOperand(0);
6564 SDValue N01 = N0.getOperand(0).getOperand(1);
6565 return DAG.getNode(ISD::FMA, dl, VT,
6566 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6567 DAG.getNode(ISD::FNEG, dl, VT, N1));
6574 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6575 SDValue N0 = N->getOperand(0);
6576 SDValue N1 = N->getOperand(1);
6577 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6578 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6579 EVT VT = N->getValueType(0);
6580 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6583 if (VT.isVector()) {
6584 SDValue FoldedVOp = SimplifyVBinOp(N);
6585 if (FoldedVOp.getNode()) return FoldedVOp;
6588 // fold (fmul c1, c2) -> c1*c2
6590 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6591 // canonicalize constant to RHS
6592 if (N0CFP && !N1CFP)
6593 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6594 // fold (fmul A, 0) -> 0
6595 if (DAG.getTarget().Options.UnsafeFPMath &&
6596 N1CFP && N1CFP->getValueAPF().isZero())
6598 // fold (fmul A, 0) -> 0, vector edition.
6599 if (DAG.getTarget().Options.UnsafeFPMath &&
6600 ISD::isBuildVectorAllZeros(N1.getNode()))
6602 // fold (fmul A, 1.0) -> A
6603 if (N1CFP && N1CFP->isExactlyValue(1.0))
6605 // fold (fmul X, 2.0) -> (fadd X, X)
6606 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6607 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6608 // fold (fmul X, -1.0) -> (fneg X)
6609 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6610 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6611 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6613 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6614 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6615 &DAG.getTarget().Options)) {
6616 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6617 &DAG.getTarget().Options)) {
6618 // Both can be negated for free, check to see if at least one is cheaper
6620 if (LHSNeg == 2 || RHSNeg == 2)
6621 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6622 GetNegatedExpression(N0, DAG, LegalOperations),
6623 GetNegatedExpression(N1, DAG, LegalOperations));
6627 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6628 if (DAG.getTarget().Options.UnsafeFPMath &&
6629 N1CFP && N0.getOpcode() == ISD::FMUL &&
6630 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6631 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6632 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6633 N0.getOperand(1), N1));
6638 SDValue DAGCombiner::visitFMA(SDNode *N) {
6639 SDValue N0 = N->getOperand(0);
6640 SDValue N1 = N->getOperand(1);
6641 SDValue N2 = N->getOperand(2);
6642 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6643 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6644 EVT VT = N->getValueType(0);
6647 if (DAG.getTarget().Options.UnsafeFPMath) {
6648 if (N0CFP && N0CFP->isZero())
6650 if (N1CFP && N1CFP->isZero())
6653 if (N0CFP && N0CFP->isExactlyValue(1.0))
6654 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6655 if (N1CFP && N1CFP->isExactlyValue(1.0))
6656 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6658 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6659 if (N0CFP && !N1CFP)
6660 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6662 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6663 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6664 N2.getOpcode() == ISD::FMUL &&
6665 N0 == N2.getOperand(0) &&
6666 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6667 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6668 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6672 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6673 if (DAG.getTarget().Options.UnsafeFPMath &&
6674 N0.getOpcode() == ISD::FMUL && N1CFP &&
6675 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6676 return DAG.getNode(ISD::FMA, dl, VT,
6678 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6682 // (fma x, 1, y) -> (fadd x, y)
6683 // (fma x, -1, y) -> (fadd (fneg x), y)
6685 if (N1CFP->isExactlyValue(1.0))
6686 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6688 if (N1CFP->isExactlyValue(-1.0) &&
6689 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6690 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6691 AddToWorkList(RHSNeg.getNode());
6692 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6696 // (fma x, c, x) -> (fmul x, (c+1))
6697 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6698 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6699 DAG.getNode(ISD::FADD, dl, VT,
6700 N1, DAG.getConstantFP(1.0, VT)));
6702 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6703 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6704 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6705 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6706 DAG.getNode(ISD::FADD, dl, VT,
6707 N1, DAG.getConstantFP(-1.0, VT)));
6713 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6714 SDValue N0 = N->getOperand(0);
6715 SDValue N1 = N->getOperand(1);
6716 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6717 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6718 EVT VT = N->getValueType(0);
6719 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6722 if (VT.isVector()) {
6723 SDValue FoldedVOp = SimplifyVBinOp(N);
6724 if (FoldedVOp.getNode()) return FoldedVOp;
6727 // fold (fdiv c1, c2) -> c1/c2
6729 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6731 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6732 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6733 // Compute the reciprocal 1.0 / c2.
6734 APFloat N1APF = N1CFP->getValueAPF();
6735 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6736 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6737 // Only do the transform if the reciprocal is a legal fp immediate that
6738 // isn't too nasty (eg NaN, denormal, ...).
6739 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6740 (!LegalOperations ||
6741 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6742 // backend)... we should handle this gracefully after Legalize.
6743 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6744 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6745 TLI.isFPImmLegal(Recip, VT)))
6746 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6747 DAG.getConstantFP(Recip, VT));
6750 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6751 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6752 &DAG.getTarget().Options)) {
6753 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6754 &DAG.getTarget().Options)) {
6755 // Both can be negated for free, check to see if at least one is cheaper
6757 if (LHSNeg == 2 || RHSNeg == 2)
6758 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6759 GetNegatedExpression(N0, DAG, LegalOperations),
6760 GetNegatedExpression(N1, DAG, LegalOperations));
6767 SDValue DAGCombiner::visitFREM(SDNode *N) {
6768 SDValue N0 = N->getOperand(0);
6769 SDValue N1 = N->getOperand(1);
6770 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6771 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6772 EVT VT = N->getValueType(0);
6774 // fold (frem c1, c2) -> fmod(c1,c2)
6776 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6781 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6782 SDValue N0 = N->getOperand(0);
6783 SDValue N1 = N->getOperand(1);
6784 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6785 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6786 EVT VT = N->getValueType(0);
6788 if (N0CFP && N1CFP) // Constant fold
6789 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6792 const APFloat& V = N1CFP->getValueAPF();
6793 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6794 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6795 if (!V.isNegative()) {
6796 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6797 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6799 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6800 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6801 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6805 // copysign(fabs(x), y) -> copysign(x, y)
6806 // copysign(fneg(x), y) -> copysign(x, y)
6807 // copysign(copysign(x,z), y) -> copysign(x, y)
6808 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6809 N0.getOpcode() == ISD::FCOPYSIGN)
6810 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6811 N0.getOperand(0), N1);
6813 // copysign(x, abs(y)) -> abs(x)
6814 if (N1.getOpcode() == ISD::FABS)
6815 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6817 // copysign(x, copysign(y,z)) -> copysign(x, z)
6818 if (N1.getOpcode() == ISD::FCOPYSIGN)
6819 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6820 N0, N1.getOperand(1));
6822 // copysign(x, fp_extend(y)) -> copysign(x, y)
6823 // copysign(x, fp_round(y)) -> copysign(x, y)
6824 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6825 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6826 N0, N1.getOperand(0));
6831 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6832 SDValue N0 = N->getOperand(0);
6833 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6834 EVT VT = N->getValueType(0);
6835 EVT OpVT = N0.getValueType();
6837 // fold (sint_to_fp c1) -> c1fp
6839 // ...but only if the target supports immediate floating-point values
6840 (!LegalOperations ||
6841 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6842 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6844 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6845 // but UINT_TO_FP is legal on this target, try to convert.
6846 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6847 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6848 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6849 if (DAG.SignBitIsZero(N0))
6850 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6853 // The next optimizations are desirable only if SELECT_CC can be lowered.
6854 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6855 // having to say they don't support SELECT_CC on every type the DAG knows
6856 // about, since there is no way to mark an opcode illegal at all value types
6857 // (See also visitSELECT)
6858 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6859 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6860 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6862 (!LegalOperations ||
6863 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6865 { N0.getOperand(0), N0.getOperand(1),
6866 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6868 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6871 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6872 // (select_cc x, y, 1.0, 0.0,, cc)
6873 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6874 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6875 (!LegalOperations ||
6876 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6878 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6879 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6880 N0.getOperand(0).getOperand(2) };
6881 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6888 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6889 SDValue N0 = N->getOperand(0);
6890 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6891 EVT VT = N->getValueType(0);
6892 EVT OpVT = N0.getValueType();
6894 // fold (uint_to_fp c1) -> c1fp
6896 // ...but only if the target supports immediate floating-point values
6897 (!LegalOperations ||
6898 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6899 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6901 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6902 // but SINT_TO_FP is legal on this target, try to convert.
6903 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
6904 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
6905 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
6906 if (DAG.SignBitIsZero(N0))
6907 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6910 // The next optimizations are desirable only if SELECT_CC can be lowered.
6911 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6912 // having to say they don't support SELECT_CC on every type the DAG knows
6913 // about, since there is no way to mark an opcode illegal at all value types
6914 // (See also visitSELECT)
6915 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6916 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6918 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
6919 (!LegalOperations ||
6920 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6922 { N0.getOperand(0), N0.getOperand(1),
6923 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
6925 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6932 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
6933 SDValue N0 = N->getOperand(0);
6934 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6935 EVT VT = N->getValueType(0);
6937 // fold (fp_to_sint c1fp) -> c1
6939 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
6944 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
6945 SDValue N0 = N->getOperand(0);
6946 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6947 EVT VT = N->getValueType(0);
6949 // fold (fp_to_uint c1fp) -> c1
6951 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
6956 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
6957 SDValue N0 = N->getOperand(0);
6958 SDValue N1 = N->getOperand(1);
6959 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6960 EVT VT = N->getValueType(0);
6962 // fold (fp_round c1fp) -> c1fp
6964 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
6966 // fold (fp_round (fp_extend x)) -> x
6967 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
6968 return N0.getOperand(0);
6970 // fold (fp_round (fp_round x)) -> (fp_round x)
6971 if (N0.getOpcode() == ISD::FP_ROUND) {
6972 // This is a value preserving truncation if both round's are.
6973 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
6974 N0.getNode()->getConstantOperandVal(1) == 1;
6975 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
6976 DAG.getIntPtrConstant(IsTrunc));
6979 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
6980 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
6981 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
6982 N0.getOperand(0), N1);
6983 AddToWorkList(Tmp.getNode());
6984 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6985 Tmp, N0.getOperand(1));
6991 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
6992 SDValue N0 = N->getOperand(0);
6993 EVT VT = N->getValueType(0);
6994 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6995 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6997 // fold (fp_round_inreg c1fp) -> c1fp
6998 if (N0CFP && isTypeLegal(EVT)) {
6999 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7000 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7006 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7007 SDValue N0 = N->getOperand(0);
7008 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7009 EVT VT = N->getValueType(0);
7011 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7012 if (N->hasOneUse() &&
7013 N->use_begin()->getOpcode() == ISD::FP_ROUND)
7016 // fold (fp_extend c1fp) -> c1fp
7018 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7020 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7022 if (N0.getOpcode() == ISD::FP_ROUND
7023 && N0.getNode()->getConstantOperandVal(1) == 1) {
7024 SDValue In = N0.getOperand(0);
7025 if (In.getValueType() == VT) return In;
7026 if (VT.bitsLT(In.getValueType()))
7027 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7028 In, N0.getOperand(1));
7029 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7032 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7033 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7034 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7035 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
7036 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7037 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7039 LN0->getBasePtr(), N0.getValueType(),
7040 LN0->getMemOperand());
7041 CombineTo(N, ExtLoad);
7042 CombineTo(N0.getNode(),
7043 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7044 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7045 ExtLoad.getValue(1));
7046 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7052 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7053 SDValue N0 = N->getOperand(0);
7054 EVT VT = N->getValueType(0);
7056 if (VT.isVector()) {
7057 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7058 if (FoldedVOp.getNode()) return FoldedVOp;
7061 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7062 &DAG.getTarget().Options))
7063 return GetNegatedExpression(N0, DAG, LegalOperations);
7065 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7066 // constant pool values.
7067 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7069 N0.getNode()->hasOneUse() &&
7070 N0.getOperand(0).getValueType().isInteger()) {
7071 SDValue Int = N0.getOperand(0);
7072 EVT IntVT = Int.getValueType();
7073 if (IntVT.isInteger() && !IntVT.isVector()) {
7074 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7075 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7076 AddToWorkList(Int.getNode());
7077 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7082 // (fneg (fmul c, x)) -> (fmul -c, x)
7083 if (N0.getOpcode() == ISD::FMUL) {
7084 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7086 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7088 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7095 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7096 SDValue N0 = N->getOperand(0);
7097 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7098 EVT VT = N->getValueType(0);
7100 // fold (fceil c1) -> fceil(c1)
7102 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7107 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7108 SDValue N0 = N->getOperand(0);
7109 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7110 EVT VT = N->getValueType(0);
7112 // fold (ftrunc c1) -> ftrunc(c1)
7114 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7119 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7120 SDValue N0 = N->getOperand(0);
7121 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7122 EVT VT = N->getValueType(0);
7124 // fold (ffloor c1) -> ffloor(c1)
7126 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7131 SDValue DAGCombiner::visitFABS(SDNode *N) {
7132 SDValue N0 = N->getOperand(0);
7133 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7134 EVT VT = N->getValueType(0);
7136 if (VT.isVector()) {
7137 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7138 if (FoldedVOp.getNode()) return FoldedVOp;
7141 // fold (fabs c1) -> fabs(c1)
7143 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7144 // fold (fabs (fabs x)) -> (fabs x)
7145 if (N0.getOpcode() == ISD::FABS)
7146 return N->getOperand(0);
7147 // fold (fabs (fneg x)) -> (fabs x)
7148 // fold (fabs (fcopysign x, y)) -> (fabs x)
7149 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7150 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7152 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7153 // constant pool values.
7154 if (!TLI.isFAbsFree(VT) &&
7155 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7156 N0.getOperand(0).getValueType().isInteger() &&
7157 !N0.getOperand(0).getValueType().isVector()) {
7158 SDValue Int = N0.getOperand(0);
7159 EVT IntVT = Int.getValueType();
7160 if (IntVT.isInteger() && !IntVT.isVector()) {
7161 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7162 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7163 AddToWorkList(Int.getNode());
7164 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7165 N->getValueType(0), Int);
7172 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7173 SDValue Chain = N->getOperand(0);
7174 SDValue N1 = N->getOperand(1);
7175 SDValue N2 = N->getOperand(2);
7177 // If N is a constant we could fold this into a fallthrough or unconditional
7178 // branch. However that doesn't happen very often in normal code, because
7179 // Instcombine/SimplifyCFG should have handled the available opportunities.
7180 // If we did this folding here, it would be necessary to update the
7181 // MachineBasicBlock CFG, which is awkward.
7183 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7185 if (N1.getOpcode() == ISD::SETCC &&
7186 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7187 N1.getOperand(0).getValueType())) {
7188 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7189 Chain, N1.getOperand(2),
7190 N1.getOperand(0), N1.getOperand(1), N2);
7193 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7194 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7195 (N1.getOperand(0).hasOneUse() &&
7196 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7198 if (N1.getOpcode() == ISD::TRUNCATE) {
7199 // Look pass the truncate.
7200 Trunc = N1.getNode();
7201 N1 = N1.getOperand(0);
7204 // Match this pattern so that we can generate simpler code:
7207 // %b = and i32 %a, 2
7208 // %c = srl i32 %b, 1
7209 // brcond i32 %c ...
7214 // %b = and i32 %a, 2
7215 // %c = setcc eq %b, 0
7218 // This applies only when the AND constant value has one bit set and the
7219 // SRL constant is equal to the log2 of the AND constant. The back-end is
7220 // smart enough to convert the result into a TEST/JMP sequence.
7221 SDValue Op0 = N1.getOperand(0);
7222 SDValue Op1 = N1.getOperand(1);
7224 if (Op0.getOpcode() == ISD::AND &&
7225 Op1.getOpcode() == ISD::Constant) {
7226 SDValue AndOp1 = Op0.getOperand(1);
7228 if (AndOp1.getOpcode() == ISD::Constant) {
7229 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7231 if (AndConst.isPowerOf2() &&
7232 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7234 DAG.getSetCC(SDLoc(N),
7235 getSetCCResultType(Op0.getValueType()),
7236 Op0, DAG.getConstant(0, Op0.getValueType()),
7239 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7240 MVT::Other, Chain, SetCC, N2);
7241 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7242 // will convert it back to (X & C1) >> C2.
7243 CombineTo(N, NewBRCond, false);
7244 // Truncate is dead.
7246 removeFromWorkList(Trunc);
7247 DAG.DeleteNode(Trunc);
7249 // Replace the uses of SRL with SETCC
7250 WorkListRemover DeadNodes(*this);
7251 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7252 removeFromWorkList(N1.getNode());
7253 DAG.DeleteNode(N1.getNode());
7254 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7260 // Restore N1 if the above transformation doesn't match.
7261 N1 = N->getOperand(1);
7264 // Transform br(xor(x, y)) -> br(x != y)
7265 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7266 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7267 SDNode *TheXor = N1.getNode();
7268 SDValue Op0 = TheXor->getOperand(0);
7269 SDValue Op1 = TheXor->getOperand(1);
7270 if (Op0.getOpcode() == Op1.getOpcode()) {
7271 // Avoid missing important xor optimizations.
7272 SDValue Tmp = visitXOR(TheXor);
7273 if (Tmp.getNode()) {
7274 if (Tmp.getNode() != TheXor) {
7275 DEBUG(dbgs() << "\nReplacing.8 ";
7277 dbgs() << "\nWith: ";
7278 Tmp.getNode()->dump(&DAG);
7280 WorkListRemover DeadNodes(*this);
7281 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7282 removeFromWorkList(TheXor);
7283 DAG.DeleteNode(TheXor);
7284 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7285 MVT::Other, Chain, Tmp, N2);
7288 // visitXOR has changed XOR's operands or replaced the XOR completely,
7290 return SDValue(N, 0);
7294 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7296 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7297 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7298 Op0.getOpcode() == ISD::XOR) {
7299 TheXor = Op0.getNode();
7303 EVT SetCCVT = N1.getValueType();
7305 SetCCVT = getSetCCResultType(SetCCVT);
7306 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7309 Equal ? ISD::SETEQ : ISD::SETNE);
7310 // Replace the uses of XOR with SETCC
7311 WorkListRemover DeadNodes(*this);
7312 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7313 removeFromWorkList(N1.getNode());
7314 DAG.DeleteNode(N1.getNode());
7315 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7316 MVT::Other, Chain, SetCC, N2);
7323 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7325 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7326 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7327 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7329 // If N is a constant we could fold this into a fallthrough or unconditional
7330 // branch. However that doesn't happen very often in normal code, because
7331 // Instcombine/SimplifyCFG should have handled the available opportunities.
7332 // If we did this folding here, it would be necessary to update the
7333 // MachineBasicBlock CFG, which is awkward.
7335 // Use SimplifySetCC to simplify SETCC's.
7336 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7337 CondLHS, CondRHS, CC->get(), SDLoc(N),
7339 if (Simp.getNode()) AddToWorkList(Simp.getNode());
7341 // fold to a simpler setcc
7342 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7343 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7344 N->getOperand(0), Simp.getOperand(2),
7345 Simp.getOperand(0), Simp.getOperand(1),
7351 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7352 /// uses N as its base pointer and that N may be folded in the load / store
7353 /// addressing mode.
7354 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7356 const TargetLowering &TLI) {
7358 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7359 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7361 VT = Use->getValueType(0);
7362 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7363 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7365 VT = ST->getValue().getValueType();
7369 TargetLowering::AddrMode AM;
7370 if (N->getOpcode() == ISD::ADD) {
7371 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7374 AM.BaseOffs = Offset->getSExtValue();
7378 } else if (N->getOpcode() == ISD::SUB) {
7379 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7382 AM.BaseOffs = -Offset->getSExtValue();
7389 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7392 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7393 /// pre-indexed load / store when the base pointer is an add or subtract
7394 /// and it has other uses besides the load / store. After the
7395 /// transformation, the new indexed load / store has effectively folded
7396 /// the add / subtract in and all of its other uses are redirected to the
7397 /// new load / store.
7398 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7399 if (Level < AfterLegalizeDAG)
7405 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7406 if (LD->isIndexed())
7408 VT = LD->getMemoryVT();
7409 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7410 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7412 Ptr = LD->getBasePtr();
7413 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7414 if (ST->isIndexed())
7416 VT = ST->getMemoryVT();
7417 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7418 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7420 Ptr = ST->getBasePtr();
7426 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7427 // out. There is no reason to make this a preinc/predec.
7428 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7429 Ptr.getNode()->hasOneUse())
7432 // Ask the target to do addressing mode selection.
7435 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7436 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7439 // Backends without true r+i pre-indexed forms may need to pass a
7440 // constant base with a variable offset so that constant coercion
7441 // will work with the patterns in canonical form.
7442 bool Swapped = false;
7443 if (isa<ConstantSDNode>(BasePtr)) {
7444 std::swap(BasePtr, Offset);
7448 // Don't create a indexed load / store with zero offset.
7449 if (isa<ConstantSDNode>(Offset) &&
7450 cast<ConstantSDNode>(Offset)->isNullValue())
7453 // Try turning it into a pre-indexed load / store except when:
7454 // 1) The new base ptr is a frame index.
7455 // 2) If N is a store and the new base ptr is either the same as or is a
7456 // predecessor of the value being stored.
7457 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7458 // that would create a cycle.
7459 // 4) All uses are load / store ops that use it as old base ptr.
7461 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7462 // (plus the implicit offset) to a register to preinc anyway.
7463 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7468 SDValue Val = cast<StoreSDNode>(N)->getValue();
7469 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7473 // If the offset is a constant, there may be other adds of constants that
7474 // can be folded with this one. We should do this to avoid having to keep
7475 // a copy of the original base pointer.
7476 SmallVector<SDNode *, 16> OtherUses;
7477 if (isa<ConstantSDNode>(Offset))
7478 for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7479 E = BasePtr.getNode()->use_end(); I != E; ++I) {
7481 if (Use == Ptr.getNode())
7484 if (Use->isPredecessorOf(N))
7487 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7492 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7493 if (Op1.getNode() == BasePtr.getNode())
7494 std::swap(Op0, Op1);
7495 assert(Op0.getNode() == BasePtr.getNode() &&
7496 "Use of ADD/SUB but not an operand");
7498 if (!isa<ConstantSDNode>(Op1)) {
7503 // FIXME: In some cases, we can be smarter about this.
7504 if (Op1.getValueType() != Offset.getValueType()) {
7509 OtherUses.push_back(Use);
7513 std::swap(BasePtr, Offset);
7515 // Now check for #3 and #4.
7516 bool RealUse = false;
7518 // Caches for hasPredecessorHelper
7519 SmallPtrSet<const SDNode *, 32> Visited;
7520 SmallVector<const SDNode *, 16> Worklist;
7522 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7523 E = Ptr.getNode()->use_end(); I != E; ++I) {
7527 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7530 // If Ptr may be folded in addressing mode of other use, then it's
7531 // not profitable to do this transformation.
7532 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7541 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7542 BasePtr, Offset, AM);
7544 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7545 BasePtr, Offset, AM);
7548 DEBUG(dbgs() << "\nReplacing.4 ";
7550 dbgs() << "\nWith: ";
7551 Result.getNode()->dump(&DAG);
7553 WorkListRemover DeadNodes(*this);
7555 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7556 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7558 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7561 // Finally, since the node is now dead, remove it from the graph.
7565 std::swap(BasePtr, Offset);
7567 // Replace other uses of BasePtr that can be updated to use Ptr
7568 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7569 unsigned OffsetIdx = 1;
7570 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7572 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7573 BasePtr.getNode() && "Expected BasePtr operand");
7575 // We need to replace ptr0 in the following expression:
7576 // x0 * offset0 + y0 * ptr0 = t0
7578 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7580 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7581 // indexed load/store and the expresion that needs to be re-written.
7583 // Therefore, we have:
7584 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7586 ConstantSDNode *CN =
7587 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7589 APInt Offset0 = CN->getAPIntValue();
7590 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7592 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7593 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7594 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7595 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7597 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7599 APInt CNV = Offset0;
7600 if (X0 < 0) CNV = -CNV;
7601 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7602 else CNV = CNV - Offset1;
7604 // We can now generate the new expression.
7605 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7606 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7608 SDValue NewUse = DAG.getNode(Opcode,
7609 SDLoc(OtherUses[i]),
7610 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7611 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7612 removeFromWorkList(OtherUses[i]);
7613 DAG.DeleteNode(OtherUses[i]);
7616 // Replace the uses of Ptr with uses of the updated base value.
7617 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7618 removeFromWorkList(Ptr.getNode());
7619 DAG.DeleteNode(Ptr.getNode());
7624 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7625 /// add / sub of the base pointer node into a post-indexed load / store.
7626 /// The transformation folded the add / subtract into the new indexed
7627 /// load / store effectively and all of its uses are redirected to the
7628 /// new load / store.
7629 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7630 if (Level < AfterLegalizeDAG)
7636 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7637 if (LD->isIndexed())
7639 VT = LD->getMemoryVT();
7640 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7641 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7643 Ptr = LD->getBasePtr();
7644 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7645 if (ST->isIndexed())
7647 VT = ST->getMemoryVT();
7648 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7649 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7651 Ptr = ST->getBasePtr();
7657 if (Ptr.getNode()->hasOneUse())
7660 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7661 E = Ptr.getNode()->use_end(); I != E; ++I) {
7664 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7669 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7670 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7671 // Don't create a indexed load / store with zero offset.
7672 if (isa<ConstantSDNode>(Offset) &&
7673 cast<ConstantSDNode>(Offset)->isNullValue())
7676 // Try turning it into a post-indexed load / store except when
7677 // 1) All uses are load / store ops that use it as base ptr (and
7678 // it may be folded as addressing mmode).
7679 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7680 // nor a successor of N. Otherwise, if Op is folded that would
7683 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7687 bool TryNext = false;
7688 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7689 EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
7691 if (Use == Ptr.getNode())
7694 // If all the uses are load / store addresses, then don't do the
7696 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7697 bool RealUse = false;
7698 for (SDNode::use_iterator III = Use->use_begin(),
7699 EEE = Use->use_end(); III != EEE; ++III) {
7700 SDNode *UseUse = *III;
7701 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7716 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7717 SDValue Result = isLoad
7718 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7719 BasePtr, Offset, AM)
7720 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7721 BasePtr, Offset, AM);
7724 DEBUG(dbgs() << "\nReplacing.5 ";
7726 dbgs() << "\nWith: ";
7727 Result.getNode()->dump(&DAG);
7729 WorkListRemover DeadNodes(*this);
7731 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7732 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7734 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7737 // Finally, since the node is now dead, remove it from the graph.
7740 // Replace the uses of Use with uses of the updated base value.
7741 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7742 Result.getValue(isLoad ? 1 : 0));
7743 removeFromWorkList(Op);
7753 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7754 LoadSDNode *LD = cast<LoadSDNode>(N);
7755 SDValue Chain = LD->getChain();
7756 SDValue Ptr = LD->getBasePtr();
7758 // If load is not volatile and there are no uses of the loaded value (and
7759 // the updated indexed value in case of indexed loads), change uses of the
7760 // chain value into uses of the chain input (i.e. delete the dead load).
7761 if (!LD->isVolatile()) {
7762 if (N->getValueType(1) == MVT::Other) {
7764 if (!N->hasAnyUseOfValue(0)) {
7765 // It's not safe to use the two value CombineTo variant here. e.g.
7766 // v1, chain2 = load chain1, loc
7767 // v2, chain3 = load chain2, loc
7769 // Now we replace use of chain2 with chain1. This makes the second load
7770 // isomorphic to the one we are deleting, and thus makes this load live.
7771 DEBUG(dbgs() << "\nReplacing.6 ";
7773 dbgs() << "\nWith chain: ";
7774 Chain.getNode()->dump(&DAG);
7776 WorkListRemover DeadNodes(*this);
7777 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7779 if (N->use_empty()) {
7780 removeFromWorkList(N);
7784 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7788 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7789 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7790 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7791 DEBUG(dbgs() << "\nReplacing.7 ";
7793 dbgs() << "\nWith: ";
7794 Undef.getNode()->dump(&DAG);
7795 dbgs() << " and 2 other values\n");
7796 WorkListRemover DeadNodes(*this);
7797 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7798 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7799 DAG.getUNDEF(N->getValueType(1)));
7800 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7801 removeFromWorkList(N);
7803 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7808 // If this load is directly stored, replace the load value with the stored
7810 // TODO: Handle store large -> read small portion.
7811 // TODO: Handle TRUNCSTORE/LOADEXT
7812 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7813 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7814 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7815 if (PrevST->getBasePtr() == Ptr &&
7816 PrevST->getValue().getValueType() == N->getValueType(0))
7817 return CombineTo(N, Chain.getOperand(1), Chain);
7821 // Try to infer better alignment information than the load already has.
7822 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7823 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7824 if (Align > LD->getMemOperand()->getBaseAlignment()) {
7826 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7827 LD->getValueType(0),
7828 Chain, Ptr, LD->getPointerInfo(),
7830 LD->isVolatile(), LD->isNonTemporal(), Align,
7832 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7837 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7838 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7840 if (CombinerAAOnlyFunc.getNumOccurrences() &&
7841 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
7844 if (UseAA && LD->isUnindexed()) {
7845 // Walk up chain skipping non-aliasing memory nodes.
7846 SDValue BetterChain = FindBetterChain(N, Chain);
7848 // If there is a better chain.
7849 if (Chain != BetterChain) {
7852 // Replace the chain to void dependency.
7853 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7854 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7855 BetterChain, Ptr, LD->getMemOperand());
7857 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7858 LD->getValueType(0),
7859 BetterChain, Ptr, LD->getMemoryVT(),
7860 LD->getMemOperand());
7863 // Create token factor to keep old chain connected.
7864 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7865 MVT::Other, Chain, ReplLoad.getValue(1));
7867 // Make sure the new and old chains are cleaned up.
7868 AddToWorkList(Token.getNode());
7870 // Replace uses with load result and token factor. Don't add users
7872 return CombineTo(N, ReplLoad.getValue(0), Token, false);
7876 // Try transforming N to an indexed load.
7877 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7878 return SDValue(N, 0);
7880 // Try to slice up N to more direct loads if the slices are mapped to
7881 // different register banks or pairing can take place.
7883 return SDValue(N, 0);
7889 /// \brief Helper structure used to slice a load in smaller loads.
7890 /// Basically a slice is obtained from the following sequence:
7891 /// Origin = load Ty1, Base
7892 /// Shift = srl Ty1 Origin, CstTy Amount
7893 /// Inst = trunc Shift to Ty2
7895 /// Then, it will be rewriten into:
7896 /// Slice = load SliceTy, Base + SliceOffset
7897 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
7899 /// SliceTy is deduced from the number of bits that are actually used to
7901 struct LoadedSlice {
7902 /// \brief Helper structure used to compute the cost of a slice.
7904 /// Are we optimizing for code size.
7909 unsigned CrossRegisterBanksCopies;
7913 Cost(bool ForCodeSize = false)
7914 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
7915 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
7917 /// \brief Get the cost of one isolated slice.
7918 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
7919 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
7920 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
7921 EVT TruncType = LS.Inst->getValueType(0);
7922 EVT LoadedType = LS.getLoadedType();
7923 if (TruncType != LoadedType &&
7924 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
7928 /// \brief Account for slicing gain in the current cost.
7929 /// Slicing provide a few gains like removing a shift or a
7930 /// truncate. This method allows to grow the cost of the original
7931 /// load with the gain from this slice.
7932 void addSliceGain(const LoadedSlice &LS) {
7933 // Each slice saves a truncate.
7934 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
7935 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
7936 LS.Inst->getOperand(0).getValueType()))
7938 // If there is a shift amount, this slice gets rid of it.
7941 // If this slice can merge a cross register bank copy, account for it.
7942 if (LS.canMergeExpensiveCrossRegisterBankCopy())
7943 ++CrossRegisterBanksCopies;
7946 Cost &operator+=(const Cost &RHS) {
7948 Truncates += RHS.Truncates;
7949 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
7955 bool operator==(const Cost &RHS) const {
7956 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
7957 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
7958 ZExts == RHS.ZExts && Shift == RHS.Shift;
7961 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
7963 bool operator<(const Cost &RHS) const {
7964 // Assume cross register banks copies are as expensive as loads.
7965 // FIXME: Do we want some more target hooks?
7966 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
7967 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
7968 // Unless we are optimizing for code size, consider the
7969 // expensive operation first.
7970 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
7971 return ExpensiveOpsLHS < ExpensiveOpsRHS;
7972 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
7973 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
7976 bool operator>(const Cost &RHS) const { return RHS < *this; }
7978 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
7980 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
7982 // The last instruction that represent the slice. This should be a
7983 // truncate instruction.
7985 // The original load instruction.
7987 // The right shift amount in bits from the original load.
7989 // The DAG from which Origin came from.
7990 // This is used to get some contextual information about legal types, etc.
7993 LoadedSlice(SDNode *Inst = NULL, LoadSDNode *Origin = NULL,
7994 unsigned Shift = 0, SelectionDAG *DAG = NULL)
7995 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
7997 LoadedSlice(const LoadedSlice &LS)
7998 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8000 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8001 /// \return Result is \p BitWidth and has used bits set to 1 and
8002 /// not used bits set to 0.
8003 APInt getUsedBits() const {
8004 // Reproduce the trunc(lshr) sequence:
8005 // - Start from the truncated value.
8006 // - Zero extend to the desired bit width.
8008 assert(Origin && "No original load to compare against.");
8009 unsigned BitWidth = Origin->getValueSizeInBits(0);
8010 assert(Inst && "This slice is not bound to an instruction");
8011 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8012 "Extracted slice is bigger than the whole type!");
8013 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8014 UsedBits.setAllBits();
8015 UsedBits = UsedBits.zext(BitWidth);
8020 /// \brief Get the size of the slice to be loaded in bytes.
8021 unsigned getLoadedSize() const {
8022 unsigned SliceSize = getUsedBits().countPopulation();
8023 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8024 return SliceSize / 8;
8027 /// \brief Get the type that will be loaded for this slice.
8028 /// Note: This may not be the final type for the slice.
8029 EVT getLoadedType() const {
8030 assert(DAG && "Missing context");
8031 LLVMContext &Ctxt = *DAG->getContext();
8032 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8035 /// \brief Get the alignment of the load used for this slice.
8036 unsigned getAlignment() const {
8037 unsigned Alignment = Origin->getAlignment();
8038 unsigned Offset = getOffsetFromBase();
8040 Alignment = MinAlign(Alignment, Alignment + Offset);
8044 /// \brief Check if this slice can be rewritten with legal operations.
8045 bool isLegal() const {
8046 // An invalid slice is not legal.
8047 if (!Origin || !Inst || !DAG)
8050 // Offsets are for indexed load only, we do not handle that.
8051 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8054 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8056 // Check that the type is legal.
8057 EVT SliceType = getLoadedType();
8058 if (!TLI.isTypeLegal(SliceType))
8061 // Check that the load is legal for this type.
8062 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8065 // Check that the offset can be computed.
8066 // 1. Check its type.
8067 EVT PtrType = Origin->getBasePtr().getValueType();
8068 if (PtrType == MVT::Untyped || PtrType.isExtended())
8071 // 2. Check that it fits in the immediate.
8072 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8075 // 3. Check that the computation is legal.
8076 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8079 // Check that the zext is legal if it needs one.
8080 EVT TruncateType = Inst->getValueType(0);
8081 if (TruncateType != SliceType &&
8082 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8088 /// \brief Get the offset in bytes of this slice in the original chunk of
8090 /// \pre DAG != NULL.
8091 uint64_t getOffsetFromBase() const {
8092 assert(DAG && "Missing context.");
8094 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8095 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8096 uint64_t Offset = Shift / 8;
8097 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8098 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8099 "The size of the original loaded type is not a multiple of a"
8101 // If Offset is bigger than TySizeInBytes, it means we are loading all
8102 // zeros. This should have been optimized before in the process.
8103 assert(TySizeInBytes > Offset &&
8104 "Invalid shift amount for given loaded size");
8106 Offset = TySizeInBytes - Offset - getLoadedSize();
8110 /// \brief Generate the sequence of instructions to load the slice
8111 /// represented by this object and redirect the uses of this slice to
8112 /// this new sequence of instructions.
8113 /// \pre this->Inst && this->Origin are valid Instructions and this
8114 /// object passed the legal check: LoadedSlice::isLegal returned true.
8115 /// \return The last instruction of the sequence used to load the slice.
8116 SDValue loadSlice() const {
8117 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8118 const SDValue &OldBaseAddr = Origin->getBasePtr();
8119 SDValue BaseAddr = OldBaseAddr;
8120 // Get the offset in that chunk of bytes w.r.t. the endianess.
8121 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8122 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8124 // BaseAddr = BaseAddr + Offset.
8125 EVT ArithType = BaseAddr.getValueType();
8126 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8127 DAG->getConstant(Offset, ArithType));
8130 // Create the type of the loaded slice according to its size.
8131 EVT SliceType = getLoadedType();
8133 // Create the load for the slice.
8134 SDValue LastInst = DAG->getLoad(
8135 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8136 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8137 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8138 // If the final type is not the same as the loaded type, this means that
8139 // we have to pad with zero. Create a zero extend for that.
8140 EVT FinalType = Inst->getValueType(0);
8141 if (SliceType != FinalType)
8143 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8147 /// \brief Check if this slice can be merged with an expensive cross register
8148 /// bank copy. E.g.,
8150 /// f = bitcast i32 i to float
8151 bool canMergeExpensiveCrossRegisterBankCopy() const {
8152 if (!Inst || !Inst->hasOneUse())
8154 SDNode *Use = *Inst->use_begin();
8155 if (Use->getOpcode() != ISD::BITCAST)
8157 assert(DAG && "Missing context");
8158 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8159 EVT ResVT = Use->getValueType(0);
8160 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8161 const TargetRegisterClass *ArgRC =
8162 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8163 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8166 // At this point, we know that we perform a cross-register-bank copy.
8167 // Check if it is expensive.
8168 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8169 // Assume bitcasts are cheap, unless both register classes do not
8170 // explicitly share a common sub class.
8171 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8174 // Check if it will be merged with the load.
8175 // 1. Check the alignment constraint.
8176 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8177 ResVT.getTypeForEVT(*DAG->getContext()));
8179 if (RequiredAlignment > getAlignment())
8182 // 2. Check that the load is a legal operation for that type.
8183 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8186 // 3. Check that we do not have a zext in the way.
8187 if (Inst->getValueType(0) != getLoadedType())
8195 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8196 /// \p UsedBits looks like 0..0 1..1 0..0.
8197 static bool areUsedBitsDense(const APInt &UsedBits) {
8198 // If all the bits are one, this is dense!
8199 if (UsedBits.isAllOnesValue())
8202 // Get rid of the unused bits on the right.
8203 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8204 // Get rid of the unused bits on the left.
8205 if (NarrowedUsedBits.countLeadingZeros())
8206 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8207 // Check that the chunk of bits is completely used.
8208 return NarrowedUsedBits.isAllOnesValue();
8211 /// \brief Check whether or not \p First and \p Second are next to each other
8212 /// in memory. This means that there is no hole between the bits loaded
8213 /// by \p First and the bits loaded by \p Second.
8214 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8215 const LoadedSlice &Second) {
8216 assert(First.Origin == Second.Origin && First.Origin &&
8217 "Unable to match different memory origins.");
8218 APInt UsedBits = First.getUsedBits();
8219 assert((UsedBits & Second.getUsedBits()) == 0 &&
8220 "Slices are not supposed to overlap.");
8221 UsedBits |= Second.getUsedBits();
8222 return areUsedBitsDense(UsedBits);
8225 /// \brief Adjust the \p GlobalLSCost according to the target
8226 /// paring capabilities and the layout of the slices.
8227 /// \pre \p GlobalLSCost should account for at least as many loads as
8228 /// there is in the slices in \p LoadedSlices.
8229 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8230 LoadedSlice::Cost &GlobalLSCost) {
8231 unsigned NumberOfSlices = LoadedSlices.size();
8232 // If there is less than 2 elements, no pairing is possible.
8233 if (NumberOfSlices < 2)
8236 // Sort the slices so that elements that are likely to be next to each
8237 // other in memory are next to each other in the list.
8238 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8239 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8240 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8241 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8243 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8244 // First (resp. Second) is the first (resp. Second) potentially candidate
8245 // to be placed in a paired load.
8246 const LoadedSlice *First = NULL;
8247 const LoadedSlice *Second = NULL;
8248 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8249 // Set the beginning of the pair.
8252 Second = &LoadedSlices[CurrSlice];
8254 // If First is NULL, it means we start a new pair.
8255 // Get to the next slice.
8259 EVT LoadedType = First->getLoadedType();
8261 // If the types of the slices are different, we cannot pair them.
8262 if (LoadedType != Second->getLoadedType())
8265 // Check if the target supplies paired loads for this type.
8266 unsigned RequiredAlignment = 0;
8267 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8268 // move to the next pair, this type is hopeless.
8272 // Check if we meet the alignment requirement.
8273 if (RequiredAlignment > First->getAlignment())
8276 // Check that both loads are next to each other in memory.
8277 if (!areSlicesNextToEachOther(*First, *Second))
8280 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8281 --GlobalLSCost.Loads;
8282 // Move to the next pair.
8287 /// \brief Check the profitability of all involved LoadedSlice.
8288 /// Currently, it is considered profitable if there is exactly two
8289 /// involved slices (1) which are (2) next to each other in memory, and
8290 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8292 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8293 /// the elements themselves.
8295 /// FIXME: When the cost model will be mature enough, we can relax
8296 /// constraints (1) and (2).
8297 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8298 const APInt &UsedBits, bool ForCodeSize) {
8299 unsigned NumberOfSlices = LoadedSlices.size();
8300 if (StressLoadSlicing)
8301 return NumberOfSlices > 1;
8304 if (NumberOfSlices != 2)
8308 if (!areUsedBitsDense(UsedBits))
8312 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8313 // The original code has one big load.
8315 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8316 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8317 // Accumulate the cost of all the slices.
8318 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8319 GlobalSlicingCost += SliceCost;
8321 // Account as cost in the original configuration the gain obtained
8322 // with the current slices.
8323 OrigCost.addSliceGain(LS);
8326 // If the target supports paired load, adjust the cost accordingly.
8327 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8328 return OrigCost > GlobalSlicingCost;
8331 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8332 /// operations, split it in the various pieces being extracted.
8334 /// This sort of thing is introduced by SROA.
8335 /// This slicing takes care not to insert overlapping loads.
8336 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8337 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8338 if (Level < AfterLegalizeDAG)
8341 LoadSDNode *LD = cast<LoadSDNode>(N);
8342 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8343 !LD->getValueType(0).isInteger())
8346 // Keep track of already used bits to detect overlapping values.
8347 // In that case, we will just abort the transformation.
8348 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8350 SmallVector<LoadedSlice, 4> LoadedSlices;
8352 // Check if this load is used as several smaller chunks of bits.
8353 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8354 // of computation for each trunc.
8355 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8356 UI != UIEnd; ++UI) {
8357 // Skip the uses of the chain.
8358 if (UI.getUse().getResNo() != 0)
8364 // Check if this is a trunc(lshr).
8365 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8366 isa<ConstantSDNode>(User->getOperand(1))) {
8367 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8368 User = *User->use_begin();
8371 // At this point, User is a Truncate, iff we encountered, trunc or
8373 if (User->getOpcode() != ISD::TRUNCATE)
8376 // The width of the type must be a power of 2 and greater than 8-bits.
8377 // Otherwise the load cannot be represented in LLVM IR.
8378 // Moreover, if we shifted with a non-8-bits multiple, the slice
8379 // will be across several bytes. We do not support that.
8380 unsigned Width = User->getValueSizeInBits(0);
8381 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8384 // Build the slice for this chain of computations.
8385 LoadedSlice LS(User, LD, Shift, &DAG);
8386 APInt CurrentUsedBits = LS.getUsedBits();
8388 // Check if this slice overlaps with another.
8389 if ((CurrentUsedBits & UsedBits) != 0)
8391 // Update the bits used globally.
8392 UsedBits |= CurrentUsedBits;
8394 // Check if the new slice would be legal.
8398 // Record the slice.
8399 LoadedSlices.push_back(LS);
8402 // Abort slicing if it does not seem to be profitable.
8403 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8408 // Rewrite each chain to use an independent load.
8409 // By construction, each chain can be represented by a unique load.
8411 // Prepare the argument for the new token factor for all the slices.
8412 SmallVector<SDValue, 8> ArgChains;
8413 for (SmallVectorImpl<LoadedSlice>::const_iterator
8414 LSIt = LoadedSlices.begin(),
8415 LSItEnd = LoadedSlices.end();
8416 LSIt != LSItEnd; ++LSIt) {
8417 SDValue SliceInst = LSIt->loadSlice();
8418 CombineTo(LSIt->Inst, SliceInst, true);
8419 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8420 SliceInst = SliceInst.getOperand(0);
8421 assert(SliceInst->getOpcode() == ISD::LOAD &&
8422 "It takes more than a zext to get to the loaded slice!!");
8423 ArgChains.push_back(SliceInst.getValue(1));
8426 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8427 &ArgChains[0], ArgChains.size());
8428 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8432 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8433 /// load is having specific bytes cleared out. If so, return the byte size
8434 /// being masked out and the shift amount.
8435 static std::pair<unsigned, unsigned>
8436 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8437 std::pair<unsigned, unsigned> Result(0, 0);
8439 // Check for the structure we're looking for.
8440 if (V->getOpcode() != ISD::AND ||
8441 !isa<ConstantSDNode>(V->getOperand(1)) ||
8442 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8445 // Check the chain and pointer.
8446 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8447 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
8449 // The store should be chained directly to the load or be an operand of a
8451 if (LD == Chain.getNode())
8453 else if (Chain->getOpcode() != ISD::TokenFactor)
8454 return Result; // Fail.
8457 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8458 if (Chain->getOperand(i).getNode() == LD) {
8462 if (!isOk) return Result;
8465 // This only handles simple types.
8466 if (V.getValueType() != MVT::i16 &&
8467 V.getValueType() != MVT::i32 &&
8468 V.getValueType() != MVT::i64)
8471 // Check the constant mask. Invert it so that the bits being masked out are
8472 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8473 // follow the sign bit for uniformity.
8474 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8475 unsigned NotMaskLZ = countLeadingZeros(NotMask);
8476 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
8477 unsigned NotMaskTZ = countTrailingZeros(NotMask);
8478 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8479 if (NotMaskLZ == 64) return Result; // All zero mask.
8481 // See if we have a continuous run of bits. If so, we have 0*1+0*
8482 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8485 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8486 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8487 NotMaskLZ -= 64-V.getValueSizeInBits();
8489 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8490 switch (MaskedBytes) {
8494 default: return Result; // All one mask, or 5-byte mask.
8497 // Verify that the first bit starts at a multiple of mask so that the access
8498 // is aligned the same as the access width.
8499 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8501 Result.first = MaskedBytes;
8502 Result.second = NotMaskTZ/8;
8507 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8508 /// provides a value as specified by MaskInfo. If so, replace the specified
8509 /// store with a narrower store of truncated IVal.
8511 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8512 SDValue IVal, StoreSDNode *St,
8514 unsigned NumBytes = MaskInfo.first;
8515 unsigned ByteShift = MaskInfo.second;
8516 SelectionDAG &DAG = DC->getDAG();
8518 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8519 // that uses this. If not, this is not a replacement.
8520 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8521 ByteShift*8, (ByteShift+NumBytes)*8);
8522 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
8524 // Check that it is legal on the target to do this. It is legal if the new
8525 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8527 MVT VT = MVT::getIntegerVT(NumBytes*8);
8528 if (!DC->isTypeLegal(VT))
8531 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8532 // shifted by ByteShift and truncated down to NumBytes.
8534 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8535 DAG.getConstant(ByteShift*8,
8536 DC->getShiftAmountTy(IVal.getValueType())));
8538 // Figure out the offset for the store and the alignment of the access.
8540 unsigned NewAlign = St->getAlignment();
8542 if (DAG.getTargetLoweringInfo().isLittleEndian())
8543 StOffset = ByteShift;
8545 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8547 SDValue Ptr = St->getBasePtr();
8549 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8550 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8551 NewAlign = MinAlign(NewAlign, StOffset);
8554 // Truncate down to the new size.
8555 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8558 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8559 St->getPointerInfo().getWithOffset(StOffset),
8560 false, false, NewAlign).getNode();
8564 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8565 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8566 /// of the loaded bits, try narrowing the load and store if it would end up
8567 /// being a win for performance or code size.
8568 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8569 StoreSDNode *ST = cast<StoreSDNode>(N);
8570 if (ST->isVolatile())
8573 SDValue Chain = ST->getChain();
8574 SDValue Value = ST->getValue();
8575 SDValue Ptr = ST->getBasePtr();
8576 EVT VT = Value.getValueType();
8578 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8581 unsigned Opc = Value.getOpcode();
8583 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8584 // is a byte mask indicating a consecutive number of bytes, check to see if
8585 // Y is known to provide just those bytes. If so, we try to replace the
8586 // load + replace + store sequence with a single (narrower) store, which makes
8588 if (Opc == ISD::OR) {
8589 std::pair<unsigned, unsigned> MaskedLoad;
8590 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8591 if (MaskedLoad.first)
8592 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8593 Value.getOperand(1), ST,this))
8594 return SDValue(NewST, 0);
8596 // Or is commutative, so try swapping X and Y.
8597 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8598 if (MaskedLoad.first)
8599 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8600 Value.getOperand(0), ST,this))
8601 return SDValue(NewST, 0);
8604 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8605 Value.getOperand(1).getOpcode() != ISD::Constant)
8608 SDValue N0 = Value.getOperand(0);
8609 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8610 Chain == SDValue(N0.getNode(), 1)) {
8611 LoadSDNode *LD = cast<LoadSDNode>(N0);
8612 if (LD->getBasePtr() != Ptr ||
8613 LD->getPointerInfo().getAddrSpace() !=
8614 ST->getPointerInfo().getAddrSpace())
8617 // Find the type to narrow it the load / op / store to.
8618 SDValue N1 = Value.getOperand(1);
8619 unsigned BitWidth = N1.getValueSizeInBits();
8620 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8621 if (Opc == ISD::AND)
8622 Imm ^= APInt::getAllOnesValue(BitWidth);
8623 if (Imm == 0 || Imm.isAllOnesValue())
8625 unsigned ShAmt = Imm.countTrailingZeros();
8626 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8627 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8628 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8629 while (NewBW < BitWidth &&
8630 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8631 TLI.isNarrowingProfitable(VT, NewVT))) {
8632 NewBW = NextPowerOf2(NewBW);
8633 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8635 if (NewBW >= BitWidth)
8638 // If the lsb changed does not start at the type bitwidth boundary,
8639 // start at the previous one.
8641 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8642 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8643 std::min(BitWidth, ShAmt + NewBW));
8644 if ((Imm & Mask) == Imm) {
8645 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8646 if (Opc == ISD::AND)
8647 NewImm ^= APInt::getAllOnesValue(NewBW);
8648 uint64_t PtrOff = ShAmt / 8;
8649 // For big endian targets, we need to adjust the offset to the pointer to
8650 // load the correct bytes.
8651 if (TLI.isBigEndian())
8652 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8654 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8655 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8656 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8659 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8660 Ptr.getValueType(), Ptr,
8661 DAG.getConstant(PtrOff, Ptr.getValueType()));
8662 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8663 LD->getChain(), NewPtr,
8664 LD->getPointerInfo().getWithOffset(PtrOff),
8665 LD->isVolatile(), LD->isNonTemporal(),
8666 LD->isInvariant(), NewAlign,
8668 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8669 DAG.getConstant(NewImm, NewVT));
8670 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8672 ST->getPointerInfo().getWithOffset(PtrOff),
8673 false, false, NewAlign);
8675 AddToWorkList(NewPtr.getNode());
8676 AddToWorkList(NewLD.getNode());
8677 AddToWorkList(NewVal.getNode());
8678 WorkListRemover DeadNodes(*this);
8679 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8688 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8689 /// if the load value isn't used by any other operations, then consider
8690 /// transforming the pair to integer load / store operations if the target
8691 /// deems the transformation profitable.
8692 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8693 StoreSDNode *ST = cast<StoreSDNode>(N);
8694 SDValue Chain = ST->getChain();
8695 SDValue Value = ST->getValue();
8696 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8697 Value.hasOneUse() &&
8698 Chain == SDValue(Value.getNode(), 1)) {
8699 LoadSDNode *LD = cast<LoadSDNode>(Value);
8700 EVT VT = LD->getMemoryVT();
8701 if (!VT.isFloatingPoint() ||
8702 VT != ST->getMemoryVT() ||
8703 LD->isNonTemporal() ||
8704 ST->isNonTemporal() ||
8705 LD->getPointerInfo().getAddrSpace() != 0 ||
8706 ST->getPointerInfo().getAddrSpace() != 0)
8709 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8710 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8711 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8712 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8713 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8716 unsigned LDAlign = LD->getAlignment();
8717 unsigned STAlign = ST->getAlignment();
8718 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8719 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8720 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8723 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8724 LD->getChain(), LD->getBasePtr(),
8725 LD->getPointerInfo(),
8726 false, false, false, LDAlign);
8728 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8729 NewLD, ST->getBasePtr(),
8730 ST->getPointerInfo(),
8731 false, false, STAlign);
8733 AddToWorkList(NewLD.getNode());
8734 AddToWorkList(NewST.getNode());
8735 WorkListRemover DeadNodes(*this);
8736 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8744 /// Helper struct to parse and store a memory address as base + index + offset.
8745 /// We ignore sign extensions when it is safe to do so.
8746 /// The following two expressions are not equivalent. To differentiate we need
8747 /// to store whether there was a sign extension involved in the index
8749 /// (load (i64 add (i64 copyfromreg %c)
8750 /// (i64 signextend (add (i8 load %index)
8754 /// (load (i64 add (i64 copyfromreg %c)
8755 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8757 struct BaseIndexOffset {
8761 bool IsIndexSignExt;
8763 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8765 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8766 bool IsIndexSignExt) :
8767 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8769 bool equalBaseIndex(const BaseIndexOffset &Other) {
8770 return Other.Base == Base && Other.Index == Index &&
8771 Other.IsIndexSignExt == IsIndexSignExt;
8774 /// Parses tree in Ptr for base, index, offset addresses.
8775 static BaseIndexOffset match(SDValue Ptr) {
8776 bool IsIndexSignExt = false;
8778 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8779 // instruction, then it could be just the BASE or everything else we don't
8780 // know how to handle. Just use Ptr as BASE and give up.
8781 if (Ptr->getOpcode() != ISD::ADD)
8782 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8784 // We know that we have at least an ADD instruction. Try to pattern match
8785 // the simple case of BASE + OFFSET.
8786 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8787 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8788 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8792 // Inside a loop the current BASE pointer is calculated using an ADD and a
8793 // MUL instruction. In this case Ptr is the actual BASE pointer.
8794 // (i64 add (i64 %array_ptr)
8795 // (i64 mul (i64 %induction_var)
8796 // (i64 %element_size)))
8797 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8798 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8800 // Look at Base + Index + Offset cases.
8801 SDValue Base = Ptr->getOperand(0);
8802 SDValue IndexOffset = Ptr->getOperand(1);
8804 // Skip signextends.
8805 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8806 IndexOffset = IndexOffset->getOperand(0);
8807 IsIndexSignExt = true;
8810 // Either the case of Base + Index (no offset) or something else.
8811 if (IndexOffset->getOpcode() != ISD::ADD)
8812 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8814 // Now we have the case of Base + Index + offset.
8815 SDValue Index = IndexOffset->getOperand(0);
8816 SDValue Offset = IndexOffset->getOperand(1);
8818 if (!isa<ConstantSDNode>(Offset))
8819 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8821 // Ignore signextends.
8822 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8823 Index = Index->getOperand(0);
8824 IsIndexSignExt = true;
8825 } else IsIndexSignExt = false;
8827 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8828 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8832 /// Holds a pointer to an LSBaseSDNode as well as information on where it
8833 /// is located in a sequence of memory operations connected by a chain.
8835 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8836 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8837 // Ptr to the mem node.
8838 LSBaseSDNode *MemNode;
8839 // Offset from the base ptr.
8840 int64_t OffsetFromBase;
8841 // What is the sequence number of this mem node.
8842 // Lowest mem operand in the DAG starts at zero.
8843 unsigned SequenceNum;
8846 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8847 EVT MemVT = St->getMemoryVT();
8848 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
8849 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8850 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
8852 // Don't merge vectors into wider inputs.
8853 if (MemVT.isVector() || !MemVT.isSimple())
8856 // Perform an early exit check. Do not bother looking at stored values that
8857 // are not constants or loads.
8858 SDValue StoredVal = St->getValue();
8859 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8860 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8864 // Only look at ends of store sequences.
8865 SDValue Chain = SDValue(St, 1);
8866 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8869 // This holds the base pointer, index, and the offset in bytes from the base
8871 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
8873 // We must have a base and an offset.
8874 if (!BasePtr.Base.getNode())
8877 // Do not handle stores to undef base pointers.
8878 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
8881 // Save the LoadSDNodes that we find in the chain.
8882 // We need to make sure that these nodes do not interfere with
8883 // any of the store nodes.
8884 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8886 // Save the StoreSDNodes that we find in the chain.
8887 SmallVector<MemOpLink, 8> StoreNodes;
8889 // Walk up the chain and look for nodes with offsets from the same
8890 // base pointer. Stop when reaching an instruction with a different kind
8891 // or instruction which has a different base pointer.
8893 StoreSDNode *Index = St;
8895 // If the chain has more than one use, then we can't reorder the mem ops.
8896 if (Index != St && !SDValue(Index, 1)->hasOneUse())
8899 // Find the base pointer and offset for this memory node.
8900 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
8902 // Check that the base pointer is the same as the original one.
8903 if (!Ptr.equalBaseIndex(BasePtr))
8906 // Check that the alignment is the same.
8907 if (Index->getAlignment() != St->getAlignment())
8910 // The memory operands must not be volatile.
8911 if (Index->isVolatile() || Index->isIndexed())
8915 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
8916 if (St->isTruncatingStore())
8919 // The stored memory type must be the same.
8920 if (Index->getMemoryVT() != MemVT)
8923 // We do not allow unaligned stores because we want to prevent overriding
8925 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
8928 // We found a potential memory operand to merge.
8929 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
8931 // Find the next memory operand in the chain. If the next operand in the
8932 // chain is a store then move up and continue the scan with the next
8933 // memory operand. If the next operand is a load save it and use alias
8934 // information to check if it interferes with anything.
8935 SDNode *NextInChain = Index->getChain().getNode();
8937 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
8938 // We found a store node. Use it for the next iteration.
8941 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
8942 if (Ldn->isVolatile()) {
8947 // Save the load node for later. Continue the scan.
8948 AliasLoadNodes.push_back(Ldn);
8949 NextInChain = Ldn->getChain().getNode();
8958 // Check if there is anything to merge.
8959 if (StoreNodes.size() < 2)
8962 // Sort the memory operands according to their distance from the base pointer.
8963 std::sort(StoreNodes.begin(), StoreNodes.end(),
8964 [](MemOpLink LHS, MemOpLink RHS) {
8965 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
8966 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
8967 LHS.SequenceNum > RHS.SequenceNum);
8970 // Scan the memory operations on the chain and find the first non-consecutive
8971 // store memory address.
8972 unsigned LastConsecutiveStore = 0;
8973 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
8974 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
8976 // Check that the addresses are consecutive starting from the second
8977 // element in the list of stores.
8979 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
8980 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8985 // Check if this store interferes with any of the loads that we found.
8986 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
8987 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
8991 // We found a load that alias with this store. Stop the sequence.
8995 // Mark this node as useful.
8996 LastConsecutiveStore = i;
8999 // The node with the lowest store address.
9000 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9002 // Store the constants into memory as one consecutive store.
9004 unsigned LastLegalType = 0;
9005 unsigned LastLegalVectorType = 0;
9006 bool NonZero = false;
9007 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9008 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9009 SDValue StoredVal = St->getValue();
9011 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9012 NonZero |= !C->isNullValue();
9013 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9014 NonZero |= !C->getConstantFPValue()->isNullValue();
9020 // Find a legal type for the constant store.
9021 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9022 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9023 if (TLI.isTypeLegal(StoreTy))
9024 LastLegalType = i+1;
9025 // Or check whether a truncstore is legal.
9026 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9027 TargetLowering::TypePromoteInteger) {
9028 EVT LegalizedStoredValueTy =
9029 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9030 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9031 LastLegalType = i+1;
9034 // Find a legal type for the vector store.
9035 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9036 if (TLI.isTypeLegal(Ty))
9037 LastLegalVectorType = i + 1;
9040 // We only use vectors if the constant is known to be zero and the
9041 // function is not marked with the noimplicitfloat attribute.
9042 if (NonZero || NoVectors)
9043 LastLegalVectorType = 0;
9045 // Check if we found a legal integer type to store.
9046 if (LastLegalType == 0 && LastLegalVectorType == 0)
9049 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9050 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9052 // Make sure we have something to merge.
9056 unsigned EarliestNodeUsed = 0;
9057 for (unsigned i=0; i < NumElem; ++i) {
9058 // Find a chain for the new wide-store operand. Notice that some
9059 // of the store nodes that we found may not be selected for inclusion
9060 // in the wide store. The chain we use needs to be the chain of the
9061 // earliest store node which is *used* and replaced by the wide store.
9062 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9063 EarliestNodeUsed = i;
9066 // The earliest Node in the DAG.
9067 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9068 SDLoc DL(StoreNodes[0].MemNode);
9072 // Find a legal type for the vector store.
9073 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9074 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9075 StoredVal = DAG.getConstant(0, Ty);
9077 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9078 APInt StoreInt(StoreBW, 0);
9080 // Construct a single integer constant which is made of the smaller
9082 bool IsLE = TLI.isLittleEndian();
9083 for (unsigned i = 0; i < NumElem ; ++i) {
9084 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9085 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9086 SDValue Val = St->getValue();
9087 StoreInt<<=ElementSizeBytes*8;
9088 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9089 StoreInt|=C->getAPIntValue().zext(StoreBW);
9090 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9091 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9093 assert(false && "Invalid constant element type");
9097 // Create the new Load and Store operations.
9098 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9099 StoredVal = DAG.getConstant(StoreInt, StoreTy);
9102 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9103 FirstInChain->getBasePtr(),
9104 FirstInChain->getPointerInfo(),
9106 FirstInChain->getAlignment());
9108 // Replace the first store with the new store
9109 CombineTo(EarliestOp, NewStore);
9110 // Erase all other stores.
9111 for (unsigned i = 0; i < NumElem ; ++i) {
9112 if (StoreNodes[i].MemNode == EarliestOp)
9114 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9115 // ReplaceAllUsesWith will replace all uses that existed when it was
9116 // called, but graph optimizations may cause new ones to appear. For
9117 // example, the case in pr14333 looks like
9119 // St's chain -> St -> another store -> X
9121 // And the only difference from St to the other store is the chain.
9122 // When we change it's chain to be St's chain they become identical,
9123 // get CSEed and the net result is that X is now a use of St.
9124 // Since we know that St is redundant, just iterate.
9125 while (!St->use_empty())
9126 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9127 removeFromWorkList(St);
9134 // Below we handle the case of multiple consecutive stores that
9135 // come from multiple consecutive loads. We merge them into a single
9136 // wide load and a single wide store.
9138 // Look for load nodes which are used by the stored values.
9139 SmallVector<MemOpLink, 8> LoadNodes;
9141 // Find acceptable loads. Loads need to have the same chain (token factor),
9142 // must not be zext, volatile, indexed, and they must be consecutive.
9143 BaseIndexOffset LdBasePtr;
9144 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9145 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9146 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9149 // Loads must only have one use.
9150 if (!Ld->hasNUsesOfValue(1, 0))
9153 // Check that the alignment is the same as the stores.
9154 if (Ld->getAlignment() != St->getAlignment())
9157 // The memory operands must not be volatile.
9158 if (Ld->isVolatile() || Ld->isIndexed())
9161 // We do not accept ext loads.
9162 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9165 // The stored memory type must be the same.
9166 if (Ld->getMemoryVT() != MemVT)
9169 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9170 // If this is not the first ptr that we check.
9171 if (LdBasePtr.Base.getNode()) {
9172 // The base ptr must be the same.
9173 if (!LdPtr.equalBaseIndex(LdBasePtr))
9176 // Check that all other base pointers are the same as this one.
9180 // We found a potential memory operand to merge.
9181 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9184 if (LoadNodes.size() < 2)
9187 // Scan the memory operations on the chain and find the first non-consecutive
9188 // load memory address. These variables hold the index in the store node
9190 unsigned LastConsecutiveLoad = 0;
9191 // This variable refers to the size and not index in the array.
9192 unsigned LastLegalVectorType = 0;
9193 unsigned LastLegalIntegerType = 0;
9194 StartAddress = LoadNodes[0].OffsetFromBase;
9195 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9196 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9197 // All loads much share the same chain.
9198 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9201 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9202 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9204 LastConsecutiveLoad = i;
9206 // Find a legal type for the vector store.
9207 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9208 if (TLI.isTypeLegal(StoreTy))
9209 LastLegalVectorType = i + 1;
9211 // Find a legal type for the integer store.
9212 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9213 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9214 if (TLI.isTypeLegal(StoreTy))
9215 LastLegalIntegerType = i + 1;
9216 // Or check whether a truncstore and extload is legal.
9217 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9218 TargetLowering::TypePromoteInteger) {
9219 EVT LegalizedStoredValueTy =
9220 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9221 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9222 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9223 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9224 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9225 LastLegalIntegerType = i+1;
9229 // Only use vector types if the vector type is larger than the integer type.
9230 // If they are the same, use integers.
9231 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9232 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9234 // We add +1 here because the LastXXX variables refer to location while
9235 // the NumElem refers to array/index size.
9236 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9237 NumElem = std::min(LastLegalType, NumElem);
9242 // The earliest Node in the DAG.
9243 unsigned EarliestNodeUsed = 0;
9244 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9245 for (unsigned i=1; i<NumElem; ++i) {
9246 // Find a chain for the new wide-store operand. Notice that some
9247 // of the store nodes that we found may not be selected for inclusion
9248 // in the wide store. The chain we use needs to be the chain of the
9249 // earliest store node which is *used* and replaced by the wide store.
9250 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9251 EarliestNodeUsed = i;
9254 // Find if it is better to use vectors or integers to load and store
9258 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9260 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9261 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9264 SDLoc LoadDL(LoadNodes[0].MemNode);
9265 SDLoc StoreDL(StoreNodes[0].MemNode);
9267 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9268 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9269 FirstLoad->getChain(),
9270 FirstLoad->getBasePtr(),
9271 FirstLoad->getPointerInfo(),
9272 false, false, false,
9273 FirstLoad->getAlignment());
9275 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9276 FirstInChain->getBasePtr(),
9277 FirstInChain->getPointerInfo(), false, false,
9278 FirstInChain->getAlignment());
9280 // Replace one of the loads with the new load.
9281 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9282 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9283 SDValue(NewLoad.getNode(), 1));
9285 // Remove the rest of the load chains.
9286 for (unsigned i = 1; i < NumElem ; ++i) {
9287 // Replace all chain users of the old load nodes with the chain of the new
9289 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9290 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9293 // Replace the first store with the new store.
9294 CombineTo(EarliestOp, NewStore);
9295 // Erase all other stores.
9296 for (unsigned i = 0; i < NumElem ; ++i) {
9297 // Remove all Store nodes.
9298 if (StoreNodes[i].MemNode == EarliestOp)
9300 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9301 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9302 removeFromWorkList(St);
9309 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9310 StoreSDNode *ST = cast<StoreSDNode>(N);
9311 SDValue Chain = ST->getChain();
9312 SDValue Value = ST->getValue();
9313 SDValue Ptr = ST->getBasePtr();
9315 // If this is a store of a bit convert, store the input value if the
9316 // resultant store does not need a higher alignment than the original.
9317 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9318 ST->isUnindexed()) {
9319 unsigned OrigAlign = ST->getAlignment();
9320 EVT SVT = Value.getOperand(0).getValueType();
9321 unsigned Align = TLI.getDataLayout()->
9322 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9323 if (Align <= OrigAlign &&
9324 ((!LegalOperations && !ST->isVolatile()) ||
9325 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9326 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9327 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9328 ST->isNonTemporal(), OrigAlign,
9332 // Turn 'store undef, Ptr' -> nothing.
9333 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9336 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9337 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9338 // NOTE: If the original store is volatile, this transform must not increase
9339 // the number of stores. For example, on x86-32 an f64 can be stored in one
9340 // processor operation but an i64 (which is not legal) requires two. So the
9341 // transform should not be done in this case.
9342 if (Value.getOpcode() != ISD::TargetConstantFP) {
9344 switch (CFP->getSimpleValueType(0).SimpleTy) {
9345 default: llvm_unreachable("Unknown FP type");
9346 case MVT::f16: // We don't do this for these yet.
9352 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9353 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9354 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9355 bitcastToAPInt().getZExtValue(), MVT::i32);
9356 return DAG.getStore(Chain, SDLoc(N), Tmp,
9357 Ptr, ST->getMemOperand());
9361 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9362 !ST->isVolatile()) ||
9363 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9364 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9365 getZExtValue(), MVT::i64);
9366 return DAG.getStore(Chain, SDLoc(N), Tmp,
9367 Ptr, ST->getMemOperand());
9370 if (!ST->isVolatile() &&
9371 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9372 // Many FP stores are not made apparent until after legalize, e.g. for
9373 // argument passing. Since this is so common, custom legalize the
9374 // 64-bit integer store into two 32-bit stores.
9375 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9376 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9377 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9378 if (TLI.isBigEndian()) std::swap(Lo, Hi);
9380 unsigned Alignment = ST->getAlignment();
9381 bool isVolatile = ST->isVolatile();
9382 bool isNonTemporal = ST->isNonTemporal();
9383 const MDNode *TBAAInfo = ST->getTBAAInfo();
9385 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9386 Ptr, ST->getPointerInfo(),
9387 isVolatile, isNonTemporal,
9388 ST->getAlignment(), TBAAInfo);
9389 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9390 DAG.getConstant(4, Ptr.getValueType()));
9391 Alignment = MinAlign(Alignment, 4U);
9392 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9393 Ptr, ST->getPointerInfo().getWithOffset(4),
9394 isVolatile, isNonTemporal,
9395 Alignment, TBAAInfo);
9396 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9405 // Try to infer better alignment information than the store already has.
9406 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9407 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9408 if (Align > ST->getAlignment())
9409 return DAG.getTruncStore(Chain, SDLoc(N), Value,
9410 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9411 ST->isVolatile(), ST->isNonTemporal(), Align,
9416 // Try transforming a pair floating point load / store ops to integer
9417 // load / store ops.
9418 SDValue NewST = TransformFPLoadStorePair(N);
9419 if (NewST.getNode())
9422 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9423 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9425 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9426 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9429 if (UseAA && ST->isUnindexed()) {
9430 // Walk up chain skipping non-aliasing memory nodes.
9431 SDValue BetterChain = FindBetterChain(N, Chain);
9433 // If there is a better chain.
9434 if (Chain != BetterChain) {
9437 // Replace the chain to avoid dependency.
9438 if (ST->isTruncatingStore()) {
9439 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9440 ST->getMemoryVT(), ST->getMemOperand());
9442 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9443 ST->getMemOperand());
9446 // Create token to keep both nodes around.
9447 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9448 MVT::Other, Chain, ReplStore);
9450 // Make sure the new and old chains are cleaned up.
9451 AddToWorkList(Token.getNode());
9453 // Don't add users to work list.
9454 return CombineTo(N, Token, false);
9458 // Try transforming N to an indexed store.
9459 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9460 return SDValue(N, 0);
9462 // FIXME: is there such a thing as a truncating indexed store?
9463 if (ST->isTruncatingStore() && ST->isUnindexed() &&
9464 Value.getValueType().isInteger()) {
9465 // See if we can simplify the input to this truncstore with knowledge that
9466 // only the low bits are being used. For example:
9467 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
9469 GetDemandedBits(Value,
9470 APInt::getLowBitsSet(
9471 Value.getValueType().getScalarType().getSizeInBits(),
9472 ST->getMemoryVT().getScalarType().getSizeInBits()));
9473 AddToWorkList(Value.getNode());
9474 if (Shorter.getNode())
9475 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9476 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9478 // Otherwise, see if we can simplify the operation with
9479 // SimplifyDemandedBits, which only works if the value has a single use.
9480 if (SimplifyDemandedBits(Value,
9481 APInt::getLowBitsSet(
9482 Value.getValueType().getScalarType().getSizeInBits(),
9483 ST->getMemoryVT().getScalarType().getSizeInBits())))
9484 return SDValue(N, 0);
9487 // If this is a load followed by a store to the same location, then the store
9489 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9490 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9491 ST->isUnindexed() && !ST->isVolatile() &&
9492 // There can't be any side effects between the load and store, such as
9494 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9495 // The store is dead, remove it.
9500 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9501 // truncating store. We can do this even if this is already a truncstore.
9502 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9503 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9504 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9505 ST->getMemoryVT())) {
9506 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9507 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9510 // Only perform this optimization before the types are legal, because we
9511 // don't want to perform this optimization on every DAGCombine invocation.
9513 bool EverChanged = false;
9516 // There can be multiple store sequences on the same chain.
9517 // Keep trying to merge store sequences until we are unable to do so
9518 // or until we merge the last store on the chain.
9519 bool Changed = MergeConsecutiveStores(ST);
9520 EverChanged |= Changed;
9521 if (!Changed) break;
9522 } while (ST->getOpcode() != ISD::DELETED_NODE);
9525 return SDValue(N, 0);
9528 return ReduceLoadOpStoreWidth(N);
9531 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9532 SDValue InVec = N->getOperand(0);
9533 SDValue InVal = N->getOperand(1);
9534 SDValue EltNo = N->getOperand(2);
9537 // If the inserted element is an UNDEF, just use the input vector.
9538 if (InVal.getOpcode() == ISD::UNDEF)
9541 EVT VT = InVec.getValueType();
9543 // If we can't generate a legal BUILD_VECTOR, exit
9544 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9547 // Check that we know which element is being inserted
9548 if (!isa<ConstantSDNode>(EltNo))
9550 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9552 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9553 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9555 SmallVector<SDValue, 8> Ops;
9556 // Do not combine these two vectors if the output vector will not replace
9557 // the input vector.
9558 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9559 Ops.append(InVec.getNode()->op_begin(),
9560 InVec.getNode()->op_end());
9561 } else if (InVec.getOpcode() == ISD::UNDEF) {
9562 unsigned NElts = VT.getVectorNumElements();
9563 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9568 // Insert the element
9569 if (Elt < Ops.size()) {
9570 // All the operands of BUILD_VECTOR must have the same type;
9571 // we enforce that here.
9572 EVT OpVT = Ops[0].getValueType();
9573 if (InVal.getValueType() != OpVT)
9574 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9575 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9576 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9580 // Return the new vector
9581 return DAG.getNode(ISD::BUILD_VECTOR, dl,
9582 VT, &Ops[0], Ops.size());
9585 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9586 // (vextract (scalar_to_vector val, 0) -> val
9587 SDValue InVec = N->getOperand(0);
9588 EVT VT = InVec.getValueType();
9589 EVT NVT = N->getValueType(0);
9591 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9592 // Check if the result type doesn't match the inserted element type. A
9593 // SCALAR_TO_VECTOR may truncate the inserted element and the
9594 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9595 SDValue InOp = InVec.getOperand(0);
9596 if (InOp.getValueType() != NVT) {
9597 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9598 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9603 SDValue EltNo = N->getOperand(1);
9604 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9606 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9607 // We only perform this optimization before the op legalization phase because
9608 // we may introduce new vector instructions which are not backed by TD
9609 // patterns. For example on AVX, extracting elements from a wide vector
9610 // without using extract_subvector.
9611 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9612 && ConstEltNo && !LegalOperations) {
9613 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9614 int NumElem = VT.getVectorNumElements();
9615 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9616 // Find the new index to extract from.
9617 int OrigElt = SVOp->getMaskElt(Elt);
9619 // Extracting an undef index is undef.
9621 return DAG.getUNDEF(NVT);
9623 // Select the right vector half to extract from.
9624 if (OrigElt < NumElem) {
9625 InVec = InVec->getOperand(0);
9627 InVec = InVec->getOperand(1);
9631 EVT IndexTy = TLI.getVectorIdxTy();
9632 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9633 InVec, DAG.getConstant(OrigElt, IndexTy));
9636 // Perform only after legalization to ensure build_vector / vector_shuffle
9637 // optimizations have already been done.
9638 if (!LegalOperations) return SDValue();
9640 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9641 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9642 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9645 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9646 bool NewLoad = false;
9647 bool BCNumEltsChanged = false;
9648 EVT ExtVT = VT.getVectorElementType();
9651 // If the result of load has to be truncated, then it's not necessarily
9653 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9656 if (InVec.getOpcode() == ISD::BITCAST) {
9657 // Don't duplicate a load with other uses.
9658 if (!InVec.hasOneUse())
9661 EVT BCVT = InVec.getOperand(0).getValueType();
9662 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9664 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9665 BCNumEltsChanged = true;
9666 InVec = InVec.getOperand(0);
9667 ExtVT = BCVT.getVectorElementType();
9671 LoadSDNode *LN0 = NULL;
9672 const ShuffleVectorSDNode *SVN = NULL;
9673 if (ISD::isNormalLoad(InVec.getNode())) {
9674 LN0 = cast<LoadSDNode>(InVec);
9675 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9676 InVec.getOperand(0).getValueType() == ExtVT &&
9677 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9678 // Don't duplicate a load with other uses.
9679 if (!InVec.hasOneUse())
9682 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9683 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9684 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9686 // (load $addr+1*size)
9688 // Don't duplicate a load with other uses.
9689 if (!InVec.hasOneUse())
9692 // If the bit convert changed the number of elements, it is unsafe
9693 // to examine the mask.
9694 if (BCNumEltsChanged)
9697 // Select the input vector, guarding against out of range extract vector.
9698 unsigned NumElems = VT.getVectorNumElements();
9699 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9700 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9702 if (InVec.getOpcode() == ISD::BITCAST) {
9703 // Don't duplicate a load with other uses.
9704 if (!InVec.hasOneUse())
9707 InVec = InVec.getOperand(0);
9709 if (ISD::isNormalLoad(InVec.getNode())) {
9710 LN0 = cast<LoadSDNode>(InVec);
9711 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9715 // Make sure we found a non-volatile load and the extractelement is
9717 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9720 // If Idx was -1 above, Elt is going to be -1, so just return undef.
9722 return DAG.getUNDEF(LVT);
9724 unsigned Align = LN0->getAlignment();
9726 // Check the resultant load doesn't need a higher alignment than the
9730 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9732 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9738 SDValue NewPtr = LN0->getBasePtr();
9739 unsigned PtrOff = 0;
9742 PtrOff = LVT.getSizeInBits() * Elt / 8;
9743 EVT PtrType = NewPtr.getValueType();
9744 if (TLI.isBigEndian())
9745 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9746 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9747 DAG.getConstant(PtrOff, PtrType));
9750 // The replacement we need to do here is a little tricky: we need to
9751 // replace an extractelement of a load with a load.
9752 // Use ReplaceAllUsesOfValuesWith to do the replacement.
9753 // Note that this replacement assumes that the extractvalue is the only
9754 // use of the load; that's okay because we don't want to perform this
9755 // transformation in other cases anyway.
9758 if (NVT.bitsGT(LVT)) {
9759 // If the result type of vextract is wider than the load, then issue an
9760 // extending load instead.
9761 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9762 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9763 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9764 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9765 LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9766 Align, LN0->getTBAAInfo());
9767 Chain = Load.getValue(1);
9769 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9770 LN0->getPointerInfo().getWithOffset(PtrOff),
9771 LN0->isVolatile(), LN0->isNonTemporal(),
9772 LN0->isInvariant(), Align, LN0->getTBAAInfo());
9773 Chain = Load.getValue(1);
9774 if (NVT.bitsLT(LVT))
9775 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
9777 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
9779 WorkListRemover DeadNodes(*this);
9780 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
9781 SDValue To[] = { Load, Chain };
9782 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9783 // Since we're explcitly calling ReplaceAllUses, add the new node to the
9784 // worklist explicitly as well.
9785 AddToWorkList(Load.getNode());
9786 AddUsersToWorkList(Load.getNode()); // Add users too
9787 // Make sure to revisit this node to clean it up; it will usually be dead.
9789 return SDValue(N, 0);
9795 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
9796 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9797 // We perform this optimization post type-legalization because
9798 // the type-legalizer often scalarizes integer-promoted vectors.
9799 // Performing this optimization before may create bit-casts which
9800 // will be type-legalized to complex code sequences.
9801 // We perform this optimization only before the operation legalizer because we
9802 // may introduce illegal operations.
9803 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9806 unsigned NumInScalars = N->getNumOperands();
9808 EVT VT = N->getValueType(0);
9810 // Check to see if this is a BUILD_VECTOR of a bunch of values
9811 // which come from any_extend or zero_extend nodes. If so, we can create
9812 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
9813 // optimizations. We do not handle sign-extend because we can't fill the sign
9815 EVT SourceType = MVT::Other;
9816 bool AllAnyExt = true;
9818 for (unsigned i = 0; i != NumInScalars; ++i) {
9819 SDValue In = N->getOperand(i);
9820 // Ignore undef inputs.
9821 if (In.getOpcode() == ISD::UNDEF) continue;
9823 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
9824 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9826 // Abort if the element is not an extension.
9827 if (!ZeroExt && !AnyExt) {
9828 SourceType = MVT::Other;
9832 // The input is a ZeroExt or AnyExt. Check the original type.
9833 EVT InTy = In.getOperand(0).getValueType();
9835 // Check that all of the widened source types are the same.
9836 if (SourceType == MVT::Other)
9839 else if (InTy != SourceType) {
9840 // Multiple income types. Abort.
9841 SourceType = MVT::Other;
9845 // Check if all of the extends are ANY_EXTENDs.
9846 AllAnyExt &= AnyExt;
9849 // In order to have valid types, all of the inputs must be extended from the
9850 // same source type and all of the inputs must be any or zero extend.
9851 // Scalar sizes must be a power of two.
9852 EVT OutScalarTy = VT.getScalarType();
9853 bool ValidTypes = SourceType != MVT::Other &&
9854 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9855 isPowerOf2_32(SourceType.getSizeInBits());
9857 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9858 // turn into a single shuffle instruction.
9862 bool isLE = TLI.isLittleEndian();
9863 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
9864 assert(ElemRatio > 1 && "Invalid element size ratio");
9865 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
9866 DAG.getConstant(0, SourceType);
9868 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
9869 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
9871 // Populate the new build_vector
9872 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9873 SDValue Cast = N->getOperand(i);
9874 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
9875 Cast.getOpcode() == ISD::ZERO_EXTEND ||
9876 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
9878 if (Cast.getOpcode() == ISD::UNDEF)
9879 In = DAG.getUNDEF(SourceType);
9881 In = Cast->getOperand(0);
9882 unsigned Index = isLE ? (i * ElemRatio) :
9883 (i * ElemRatio + (ElemRatio - 1));
9885 assert(Index < Ops.size() && "Invalid index");
9889 // The type of the new BUILD_VECTOR node.
9890 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
9891 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
9892 "Invalid vector size");
9893 // Check if the new vector type is legal.
9894 if (!isTypeLegal(VecVT)) return SDValue();
9896 // Make the new BUILD_VECTOR.
9897 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
9899 // The new BUILD_VECTOR node has the potential to be further optimized.
9900 AddToWorkList(BV.getNode());
9901 // Bitcast to the desired type.
9902 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9905 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
9906 EVT VT = N->getValueType(0);
9908 unsigned NumInScalars = N->getNumOperands();
9911 EVT SrcVT = MVT::Other;
9912 unsigned Opcode = ISD::DELETED_NODE;
9913 unsigned NumDefs = 0;
9915 for (unsigned i = 0; i != NumInScalars; ++i) {
9916 SDValue In = N->getOperand(i);
9917 unsigned Opc = In.getOpcode();
9919 if (Opc == ISD::UNDEF)
9922 // If all scalar values are floats and converted from integers.
9923 if (Opcode == ISD::DELETED_NODE &&
9924 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
9931 EVT InVT = In.getOperand(0).getValueType();
9933 // If all scalar values are typed differently, bail out. It's chosen to
9934 // simplify BUILD_VECTOR of integer types.
9935 if (SrcVT == MVT::Other)
9942 // If the vector has just one element defined, it's not worth to fold it into
9943 // a vectorized one.
9947 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
9948 && "Should only handle conversion from integer to float.");
9949 assert(SrcVT != MVT::Other && "Cannot determine source type!");
9951 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
9953 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
9956 SmallVector<SDValue, 8> Opnds;
9957 for (unsigned i = 0; i != NumInScalars; ++i) {
9958 SDValue In = N->getOperand(i);
9960 if (In.getOpcode() == ISD::UNDEF)
9961 Opnds.push_back(DAG.getUNDEF(SrcVT));
9963 Opnds.push_back(In.getOperand(0));
9965 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
9966 &Opnds[0], Opnds.size());
9967 AddToWorkList(BV.getNode());
9969 return DAG.getNode(Opcode, dl, VT, BV);
9972 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
9973 unsigned NumInScalars = N->getNumOperands();
9975 EVT VT = N->getValueType(0);
9977 // A vector built entirely of undefs is undef.
9978 if (ISD::allOperandsUndef(N))
9979 return DAG.getUNDEF(VT);
9981 SDValue V = reduceBuildVecExtToExtBuildVec(N);
9985 V = reduceBuildVecConvertToConvertBuildVec(N);
9989 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
9990 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
9991 // at most two distinct vectors, turn this into a shuffle node.
9993 // May only combine to shuffle after legalize if shuffle is legal.
9994 if (LegalOperations &&
9995 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
9998 SDValue VecIn1, VecIn2;
9999 for (unsigned i = 0; i != NumInScalars; ++i) {
10000 // Ignore undef inputs.
10001 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10003 // If this input is something other than a EXTRACT_VECTOR_ELT with a
10004 // constant index, bail out.
10005 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10006 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10007 VecIn1 = VecIn2 = SDValue(0, 0);
10011 // We allow up to two distinct input vectors.
10012 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10013 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10016 if (VecIn1.getNode() == 0) {
10017 VecIn1 = ExtractedFromVec;
10018 } else if (VecIn2.getNode() == 0) {
10019 VecIn2 = ExtractedFromVec;
10021 // Too many inputs.
10022 VecIn1 = VecIn2 = SDValue(0, 0);
10027 // If everything is good, we can make a shuffle operation.
10028 if (VecIn1.getNode()) {
10029 SmallVector<int, 8> Mask;
10030 for (unsigned i = 0; i != NumInScalars; ++i) {
10031 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10032 Mask.push_back(-1);
10036 // If extracting from the first vector, just use the index directly.
10037 SDValue Extract = N->getOperand(i);
10038 SDValue ExtVal = Extract.getOperand(1);
10039 if (Extract.getOperand(0) == VecIn1) {
10040 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10041 if (ExtIndex > VT.getVectorNumElements())
10044 Mask.push_back(ExtIndex);
10048 // Otherwise, use InIdx + VecSize
10049 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10050 Mask.push_back(Idx+NumInScalars);
10053 // We can't generate a shuffle node with mismatched input and output types.
10054 // Attempt to transform a single input vector to the correct type.
10055 if ((VT != VecIn1.getValueType())) {
10056 // We don't support shuffeling between TWO values of different types.
10057 if (VecIn2.getNode() != 0)
10060 // We only support widening of vectors which are half the size of the
10061 // output registers. For example XMM->YMM widening on X86 with AVX.
10062 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10065 // If the input vector type has a different base type to the output
10066 // vector type, bail out.
10067 if (VecIn1.getValueType().getVectorElementType() !=
10068 VT.getVectorElementType())
10071 // Widen the input vector by adding undef values.
10072 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10073 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10076 // If VecIn2 is unused then change it to undef.
10077 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10079 // Check that we were able to transform all incoming values to the same
10081 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10082 VecIn1.getValueType() != VT)
10085 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10086 if (!isTypeLegal(VT))
10089 // Return the new VECTOR_SHUFFLE node.
10093 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10099 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10100 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10101 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10102 // inputs come from at most two distinct vectors, turn this into a shuffle
10105 // If we only have one input vector, we don't need to do any concatenation.
10106 if (N->getNumOperands() == 1)
10107 return N->getOperand(0);
10109 // Check if all of the operands are undefs.
10110 EVT VT = N->getValueType(0);
10111 if (ISD::allOperandsUndef(N))
10112 return DAG.getUNDEF(VT);
10114 // Optimize concat_vectors where one of the vectors is undef.
10115 if (N->getNumOperands() == 2 &&
10116 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10117 SDValue In = N->getOperand(0);
10118 assert(In.getValueType().isVector() && "Must concat vectors");
10120 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10121 if (In->getOpcode() == ISD::BITCAST &&
10122 !In->getOperand(0)->getValueType(0).isVector()) {
10123 SDValue Scalar = In->getOperand(0);
10124 EVT SclTy = Scalar->getValueType(0);
10126 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10129 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10130 VT.getSizeInBits() / SclTy.getSizeInBits());
10131 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10134 SDLoc dl = SDLoc(N);
10135 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10136 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10140 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10141 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10142 if (N->getNumOperands() == 2 &&
10143 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10144 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10145 EVT VT = N->getValueType(0);
10146 SDValue N0 = N->getOperand(0);
10147 SDValue N1 = N->getOperand(1);
10148 SmallVector<SDValue, 8> Opnds;
10149 unsigned BuildVecNumElts = N0.getNumOperands();
10151 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10152 Opnds.push_back(N0.getOperand(i));
10153 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10154 Opnds.push_back(N1.getOperand(i));
10156 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
10160 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10161 // nodes often generate nop CONCAT_VECTOR nodes.
10162 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10163 // place the incoming vectors at the exact same location.
10164 SDValue SingleSource = SDValue();
10165 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10167 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10168 SDValue Op = N->getOperand(i);
10170 if (Op.getOpcode() == ISD::UNDEF)
10173 // Check if this is the identity extract:
10174 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10177 // Find the single incoming vector for the extract_subvector.
10178 if (SingleSource.getNode()) {
10179 if (Op.getOperand(0) != SingleSource)
10182 SingleSource = Op.getOperand(0);
10184 // Check the source type is the same as the type of the result.
10185 // If not, this concat may extend the vector, so we can not
10186 // optimize it away.
10187 if (SingleSource.getValueType() != N->getValueType(0))
10191 unsigned IdentityIndex = i * PartNumElem;
10192 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10193 // The extract index must be constant.
10197 // Check that we are reading from the identity index.
10198 if (CS->getZExtValue() != IdentityIndex)
10202 if (SingleSource.getNode())
10203 return SingleSource;
10208 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10209 EVT NVT = N->getValueType(0);
10210 SDValue V = N->getOperand(0);
10212 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10214 // (extract_subvec (concat V1, V2, ...), i)
10217 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10219 if (V->getOperand(0).getValueType() != NVT)
10221 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10222 unsigned NumElems = NVT.getVectorNumElements();
10223 assert((Idx % NumElems) == 0 &&
10224 "IDX in concat is not a multiple of the result vector length.");
10225 return V->getOperand(Idx / NumElems);
10229 if (V->getOpcode() == ISD::BITCAST)
10230 V = V.getOperand(0);
10232 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10234 // Handle only simple case where vector being inserted and vector
10235 // being extracted are of same type, and are half size of larger vectors.
10236 EVT BigVT = V->getOperand(0).getValueType();
10237 EVT SmallVT = V->getOperand(1).getValueType();
10238 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10241 // Only handle cases where both indexes are constants with the same type.
10242 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10243 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10245 if (InsIdx && ExtIdx &&
10246 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10247 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10249 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10251 // indices are equal or bit offsets are equal => V1
10252 // otherwise => (extract_subvec V1, ExtIdx)
10253 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10254 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10255 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10256 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10257 DAG.getNode(ISD::BITCAST, dl,
10258 N->getOperand(0).getValueType(),
10259 V->getOperand(0)), N->getOperand(1));
10266 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10267 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10268 EVT VT = N->getValueType(0);
10269 unsigned NumElts = VT.getVectorNumElements();
10271 SDValue N0 = N->getOperand(0);
10272 SDValue N1 = N->getOperand(1);
10273 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10275 SmallVector<SDValue, 4> Ops;
10276 EVT ConcatVT = N0.getOperand(0).getValueType();
10277 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10278 unsigned NumConcats = NumElts / NumElemsPerConcat;
10280 // Look at every vector that's inserted. We're looking for exact
10281 // subvector-sized copies from a concatenated vector
10282 for (unsigned I = 0; I != NumConcats; ++I) {
10283 // Make sure we're dealing with a copy.
10284 unsigned Begin = I * NumElemsPerConcat;
10285 bool AllUndef = true, NoUndef = true;
10286 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10287 if (SVN->getMaskElt(J) >= 0)
10294 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10297 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10298 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10301 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10302 if (FirstElt < N0.getNumOperands())
10303 Ops.push_back(N0.getOperand(FirstElt));
10305 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10307 } else if (AllUndef) {
10308 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10309 } else { // Mixed with general masks and undefs, can't do optimization.
10314 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
10318 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10319 EVT VT = N->getValueType(0);
10320 unsigned NumElts = VT.getVectorNumElements();
10322 SDValue N0 = N->getOperand(0);
10323 SDValue N1 = N->getOperand(1);
10325 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10327 // Canonicalize shuffle undef, undef -> undef
10328 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10329 return DAG.getUNDEF(VT);
10331 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10333 // Canonicalize shuffle v, v -> v, undef
10335 SmallVector<int, 8> NewMask;
10336 for (unsigned i = 0; i != NumElts; ++i) {
10337 int Idx = SVN->getMaskElt(i);
10338 if (Idx >= (int)NumElts) Idx -= NumElts;
10339 NewMask.push_back(Idx);
10341 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10345 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10346 if (N0.getOpcode() == ISD::UNDEF) {
10347 SmallVector<int, 8> NewMask;
10348 for (unsigned i = 0; i != NumElts; ++i) {
10349 int Idx = SVN->getMaskElt(i);
10351 if (Idx >= (int)NumElts)
10354 Idx = -1; // remove reference to lhs
10356 NewMask.push_back(Idx);
10358 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10362 // Remove references to rhs if it is undef
10363 if (N1.getOpcode() == ISD::UNDEF) {
10364 bool Changed = false;
10365 SmallVector<int, 8> NewMask;
10366 for (unsigned i = 0; i != NumElts; ++i) {
10367 int Idx = SVN->getMaskElt(i);
10368 if (Idx >= (int)NumElts) {
10372 NewMask.push_back(Idx);
10375 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10378 // If it is a splat, check if the argument vector is another splat or a
10379 // build_vector with all scalar elements the same.
10380 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10381 SDNode *V = N0.getNode();
10383 // If this is a bit convert that changes the element type of the vector but
10384 // not the number of vector elements, look through it. Be careful not to
10385 // look though conversions that change things like v4f32 to v2f64.
10386 if (V->getOpcode() == ISD::BITCAST) {
10387 SDValue ConvInput = V->getOperand(0);
10388 if (ConvInput.getValueType().isVector() &&
10389 ConvInput.getValueType().getVectorNumElements() == NumElts)
10390 V = ConvInput.getNode();
10393 if (V->getOpcode() == ISD::BUILD_VECTOR) {
10394 assert(V->getNumOperands() == NumElts &&
10395 "BUILD_VECTOR has wrong number of operands");
10397 bool AllSame = true;
10398 for (unsigned i = 0; i != NumElts; ++i) {
10399 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10400 Base = V->getOperand(i);
10404 // Splat of <u, u, u, u>, return <u, u, u, u>
10405 if (!Base.getNode())
10407 for (unsigned i = 0; i != NumElts; ++i) {
10408 if (V->getOperand(i) != Base) {
10413 // Splat of <x, x, x, x>, return <x, x, x, x>
10419 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10420 Level < AfterLegalizeVectorOps &&
10421 (N1.getOpcode() == ISD::UNDEF ||
10422 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10423 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10424 SDValue V = partitionShuffleOfConcats(N, DAG);
10430 // If this shuffle node is simply a swizzle of another shuffle node,
10431 // and it reverses the swizzle of the previous shuffle then we can
10432 // optimize shuffle(shuffle(x, undef), undef) -> x.
10433 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10434 N1.getOpcode() == ISD::UNDEF) {
10436 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10438 // Shuffle nodes can only reverse shuffles with a single non-undef value.
10439 if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10442 // The incoming shuffle must be of the same type as the result of the
10443 // current shuffle.
10444 assert(OtherSV->getOperand(0).getValueType() == VT &&
10445 "Shuffle types don't match");
10447 for (unsigned i = 0; i != NumElts; ++i) {
10448 int Idx = SVN->getMaskElt(i);
10449 assert(Idx < (int)NumElts && "Index references undef operand");
10450 // Next, this index comes from the first value, which is the incoming
10451 // shuffle. Adopt the incoming index.
10453 Idx = OtherSV->getMaskElt(Idx);
10455 // The combined shuffle must map each index to itself.
10456 if (Idx >= 0 && (unsigned)Idx != i)
10460 return OtherSV->getOperand(0);
10466 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10467 SDValue N0 = N->getOperand(0);
10468 SDValue N2 = N->getOperand(2);
10470 // If the input vector is a concatenation, and the insert replaces
10471 // one of the halves, we can optimize into a single concat_vectors.
10472 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10473 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10474 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10475 EVT VT = N->getValueType(0);
10477 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10478 // (concat_vectors Z, Y)
10480 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10481 N->getOperand(1), N0.getOperand(1));
10483 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10484 // (concat_vectors X, Z)
10485 if (InsIdx == VT.getVectorNumElements()/2)
10486 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10487 N0.getOperand(0), N->getOperand(1));
10493 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10494 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10495 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10496 /// vector_shuffle V, Zero, <0, 4, 2, 4>
10497 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10498 EVT VT = N->getValueType(0);
10500 SDValue LHS = N->getOperand(0);
10501 SDValue RHS = N->getOperand(1);
10502 if (N->getOpcode() == ISD::AND) {
10503 if (RHS.getOpcode() == ISD::BITCAST)
10504 RHS = RHS.getOperand(0);
10505 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10506 SmallVector<int, 8> Indices;
10507 unsigned NumElts = RHS.getNumOperands();
10508 for (unsigned i = 0; i != NumElts; ++i) {
10509 SDValue Elt = RHS.getOperand(i);
10510 if (!isa<ConstantSDNode>(Elt))
10513 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10514 Indices.push_back(i);
10515 else if (cast<ConstantSDNode>(Elt)->isNullValue())
10516 Indices.push_back(NumElts);
10521 // Let's see if the target supports this vector_shuffle.
10522 EVT RVT = RHS.getValueType();
10523 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10526 // Return the new VECTOR_SHUFFLE node.
10527 EVT EltVT = RVT.getVectorElementType();
10528 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10529 DAG.getConstant(0, EltVT));
10530 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10531 RVT, &ZeroOps[0], ZeroOps.size());
10532 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10533 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10534 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10541 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10542 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10543 assert(N->getValueType(0).isVector() &&
10544 "SimplifyVBinOp only works on vectors!");
10546 SDValue LHS = N->getOperand(0);
10547 SDValue RHS = N->getOperand(1);
10548 SDValue Shuffle = XformToShuffleWithZero(N);
10549 if (Shuffle.getNode()) return Shuffle;
10551 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10553 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10554 RHS.getOpcode() == ISD::BUILD_VECTOR) {
10555 // Check if both vectors are constants. If not bail out.
10556 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10557 cast<BuildVectorSDNode>(RHS)->isConstant()))
10560 SmallVector<SDValue, 8> Ops;
10561 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10562 SDValue LHSOp = LHS.getOperand(i);
10563 SDValue RHSOp = RHS.getOperand(i);
10565 // Can't fold divide by zero.
10566 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10567 N->getOpcode() == ISD::FDIV) {
10568 if ((RHSOp.getOpcode() == ISD::Constant &&
10569 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10570 (RHSOp.getOpcode() == ISD::ConstantFP &&
10571 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10575 EVT VT = LHSOp.getValueType();
10576 EVT RVT = RHSOp.getValueType();
10578 // Integer BUILD_VECTOR operands may have types larger than the element
10579 // size (e.g., when the element type is not legal). Prior to type
10580 // legalization, the types may not match between the two BUILD_VECTORS.
10581 // Truncate one of the operands to make them match.
10582 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10583 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10585 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10589 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10591 if (FoldOp.getOpcode() != ISD::UNDEF &&
10592 FoldOp.getOpcode() != ISD::Constant &&
10593 FoldOp.getOpcode() != ISD::ConstantFP)
10595 Ops.push_back(FoldOp);
10596 AddToWorkList(FoldOp.getNode());
10599 if (Ops.size() == LHS.getNumOperands())
10600 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10601 LHS.getValueType(), &Ops[0], Ops.size());
10607 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10608 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10609 assert(N->getValueType(0).isVector() &&
10610 "SimplifyVUnaryOp only works on vectors!");
10612 SDValue N0 = N->getOperand(0);
10614 if (N0.getOpcode() != ISD::BUILD_VECTOR)
10617 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10618 SmallVector<SDValue, 8> Ops;
10619 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10620 SDValue Op = N0.getOperand(i);
10621 if (Op.getOpcode() != ISD::UNDEF &&
10622 Op.getOpcode() != ISD::ConstantFP)
10624 EVT EltVT = Op.getValueType();
10625 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
10626 if (FoldOp.getOpcode() != ISD::UNDEF &&
10627 FoldOp.getOpcode() != ISD::ConstantFP)
10629 Ops.push_back(FoldOp);
10630 AddToWorkList(FoldOp.getNode());
10633 if (Ops.size() != N0.getNumOperands())
10636 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10637 N0.getValueType(), &Ops[0], Ops.size());
10640 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10641 SDValue N1, SDValue N2){
10642 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10644 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
10645 cast<CondCodeSDNode>(N0.getOperand(2))->get());
10647 // If we got a simplified select_cc node back from SimplifySelectCC, then
10648 // break it down into a new SETCC node, and a new SELECT node, and then return
10649 // the SELECT node, since we were called with a SELECT node.
10650 if (SCC.getNode()) {
10651 // Check to see if we got a select_cc back (to turn into setcc/select).
10652 // Otherwise, just return whatever node we got back, like fabs.
10653 if (SCC.getOpcode() == ISD::SELECT_CC) {
10654 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
10656 SCC.getOperand(0), SCC.getOperand(1),
10657 SCC.getOperand(4));
10658 AddToWorkList(SETCC.getNode());
10659 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10660 SCC.getOperand(2), SCC.getOperand(3), SETCC);
10668 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10669 /// are the two values being selected between, see if we can simplify the
10670 /// select. Callers of this should assume that TheSelect is deleted if this
10671 /// returns true. As such, they should return the appropriate thing (e.g. the
10672 /// node) back to the top-level of the DAG combiner loop to avoid it being
10674 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
10677 // Cannot simplify select with vector condition
10678 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10680 // If this is a select from two identical things, try to pull the operation
10681 // through the select.
10682 if (LHS.getOpcode() != RHS.getOpcode() ||
10683 !LHS.hasOneUse() || !RHS.hasOneUse())
10686 // If this is a load and the token chain is identical, replace the select
10687 // of two loads with a load through a select of the address to load from.
10688 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10689 // constants have been dropped into the constant pool.
10690 if (LHS.getOpcode() == ISD::LOAD) {
10691 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10692 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
10694 // Token chains must be identical.
10695 if (LHS.getOperand(0) != RHS.getOperand(0) ||
10696 // Do not let this transformation reduce the number of volatile loads.
10697 LLD->isVolatile() || RLD->isVolatile() ||
10698 // If this is an EXTLOAD, the VT's must match.
10699 LLD->getMemoryVT() != RLD->getMemoryVT() ||
10700 // If this is an EXTLOAD, the kind of extension must match.
10701 (LLD->getExtensionType() != RLD->getExtensionType() &&
10702 // The only exception is if one of the extensions is anyext.
10703 LLD->getExtensionType() != ISD::EXTLOAD &&
10704 RLD->getExtensionType() != ISD::EXTLOAD) ||
10705 // FIXME: this discards src value information. This is
10706 // over-conservative. It would be beneficial to be able to remember
10707 // both potential memory locations. Since we are discarding
10708 // src value info, don't do the transformation if the memory
10709 // locations are not in the default address space.
10710 LLD->getPointerInfo().getAddrSpace() != 0 ||
10711 RLD->getPointerInfo().getAddrSpace() != 0 ||
10712 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10713 LLD->getBasePtr().getValueType()))
10716 // Check that the select condition doesn't reach either load. If so,
10717 // folding this will induce a cycle into the DAG. If not, this is safe to
10718 // xform, so create a select of the addresses.
10720 if (TheSelect->getOpcode() == ISD::SELECT) {
10721 SDNode *CondNode = TheSelect->getOperand(0).getNode();
10722 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10723 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10725 // The loads must not depend on one another.
10726 if (LLD->isPredecessorOf(RLD) ||
10727 RLD->isPredecessorOf(LLD))
10729 Addr = DAG.getSelect(SDLoc(TheSelect),
10730 LLD->getBasePtr().getValueType(),
10731 TheSelect->getOperand(0), LLD->getBasePtr(),
10732 RLD->getBasePtr());
10733 } else { // Otherwise SELECT_CC
10734 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10735 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10737 if ((LLD->hasAnyUseOfValue(1) &&
10738 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
10739 (RLD->hasAnyUseOfValue(1) &&
10740 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
10743 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
10744 LLD->getBasePtr().getValueType(),
10745 TheSelect->getOperand(0),
10746 TheSelect->getOperand(1),
10747 LLD->getBasePtr(), RLD->getBasePtr(),
10748 TheSelect->getOperand(4));
10752 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10753 Load = DAG.getLoad(TheSelect->getValueType(0),
10755 // FIXME: Discards pointer and TBAA info.
10756 LLD->getChain(), Addr, MachinePointerInfo(),
10757 LLD->isVolatile(), LLD->isNonTemporal(),
10758 LLD->isInvariant(), LLD->getAlignment());
10760 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10761 RLD->getExtensionType() : LLD->getExtensionType(),
10763 TheSelect->getValueType(0),
10764 // FIXME: Discards pointer and TBAA info.
10765 LLD->getChain(), Addr, MachinePointerInfo(),
10766 LLD->getMemoryVT(), LLD->isVolatile(),
10767 LLD->isNonTemporal(), LLD->getAlignment());
10770 // Users of the select now use the result of the load.
10771 CombineTo(TheSelect, Load);
10773 // Users of the old loads now use the new load's chain. We know the
10774 // old-load value is dead now.
10775 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10776 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10783 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10784 /// where 'cond' is the comparison specified by CC.
10785 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
10786 SDValue N2, SDValue N3,
10787 ISD::CondCode CC, bool NotExtCompare) {
10788 // (x ? y : y) -> y.
10789 if (N2 == N3) return N2;
10791 EVT VT = N2.getValueType();
10792 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10793 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10794 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
10796 // Determine if the condition we're dealing with is constant
10797 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
10798 N0, N1, CC, DL, false);
10799 if (SCC.getNode()) AddToWorkList(SCC.getNode());
10800 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
10802 // fold select_cc true, x, y -> x
10803 if (SCCC && !SCCC->isNullValue())
10805 // fold select_cc false, x, y -> y
10806 if (SCCC && SCCC->isNullValue())
10809 // Check to see if we can simplify the select into an fabs node
10810 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10811 // Allow either -0.0 or 0.0
10812 if (CFP->getValueAPF().isZero()) {
10813 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10814 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10815 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10816 N2 == N3.getOperand(0))
10817 return DAG.getNode(ISD::FABS, DL, VT, N0);
10819 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10820 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10821 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10822 N2.getOperand(0) == N3)
10823 return DAG.getNode(ISD::FABS, DL, VT, N3);
10827 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10828 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10829 // in it. This is a win when the constant is not otherwise available because
10830 // it replaces two constant pool loads with one. We only do this if the FP
10831 // type is known to be legal, because if it isn't, then we are before legalize
10832 // types an we want the other legalization to happen first (e.g. to avoid
10833 // messing with soft float) and if the ConstantFP is not legal, because if
10834 // it is legal, we may not need to store the FP constant in a constant pool.
10835 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10836 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10837 if (TLI.isTypeLegal(N2.getValueType()) &&
10838 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10839 TargetLowering::Legal) &&
10840 // If both constants have multiple uses, then we won't need to do an
10841 // extra load, they are likely around in registers for other users.
10842 (TV->hasOneUse() || FV->hasOneUse())) {
10843 Constant *Elts[] = {
10844 const_cast<ConstantFP*>(FV->getConstantFPValue()),
10845 const_cast<ConstantFP*>(TV->getConstantFPValue())
10847 Type *FPTy = Elts[0]->getType();
10848 const DataLayout &TD = *TLI.getDataLayout();
10850 // Create a ConstantArray of the two constants.
10851 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
10852 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10853 TD.getPrefTypeAlignment(FPTy));
10854 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10856 // Get the offsets to the 0 and 1 element of the array so that we can
10857 // select between them.
10858 SDValue Zero = DAG.getIntPtrConstant(0);
10859 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
10860 SDValue One = DAG.getIntPtrConstant(EltSize);
10862 SDValue Cond = DAG.getSetCC(DL,
10863 getSetCCResultType(N0.getValueType()),
10865 AddToWorkList(Cond.getNode());
10866 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
10868 AddToWorkList(CstOffset.getNode());
10869 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
10871 AddToWorkList(CPIdx.getNode());
10872 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
10873 MachinePointerInfo::getConstantPool(), false,
10874 false, false, Alignment);
10879 // Check to see if we can perform the "gzip trick", transforming
10880 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
10881 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
10882 (N1C->isNullValue() || // (a < 0) ? b : 0
10883 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
10884 EVT XType = N0.getValueType();
10885 EVT AType = N2.getValueType();
10886 if (XType.bitsGE(AType)) {
10887 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
10888 // single-bit constant.
10889 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
10890 unsigned ShCtV = N2C->getAPIntValue().logBase2();
10891 ShCtV = XType.getSizeInBits()-ShCtV-1;
10892 SDValue ShCt = DAG.getConstant(ShCtV,
10893 getShiftAmountTy(N0.getValueType()));
10894 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
10896 AddToWorkList(Shift.getNode());
10898 if (XType.bitsGT(AType)) {
10899 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
10900 AddToWorkList(Shift.getNode());
10903 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
10906 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
10908 DAG.getConstant(XType.getSizeInBits()-1,
10909 getShiftAmountTy(N0.getValueType())));
10910 AddToWorkList(Shift.getNode());
10912 if (XType.bitsGT(AType)) {
10913 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
10914 AddToWorkList(Shift.getNode());
10917 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
10921 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
10922 // where y is has a single bit set.
10923 // A plaintext description would be, we can turn the SELECT_CC into an AND
10924 // when the condition can be materialized as an all-ones register. Any
10925 // single bit-test can be materialized as an all-ones register with
10926 // shift-left and shift-right-arith.
10927 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
10928 N0->getValueType(0) == VT &&
10929 N1C && N1C->isNullValue() &&
10930 N2C && N2C->isNullValue()) {
10931 SDValue AndLHS = N0->getOperand(0);
10932 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
10933 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
10934 // Shift the tested bit over the sign bit.
10935 APInt AndMask = ConstAndRHS->getAPIntValue();
10937 DAG.getConstant(AndMask.countLeadingZeros(),
10938 getShiftAmountTy(AndLHS.getValueType()));
10939 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
10941 // Now arithmetic right shift it all the way over, so the result is either
10942 // all-ones, or zero.
10944 DAG.getConstant(AndMask.getBitWidth()-1,
10945 getShiftAmountTy(Shl.getValueType()));
10946 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
10948 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
10952 // fold select C, 16, 0 -> shl C, 4
10953 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
10954 TLI.getBooleanContents(N0.getValueType().isVector()) ==
10955 TargetLowering::ZeroOrOneBooleanContent) {
10957 // If the caller doesn't want us to simplify this into a zext of a compare,
10959 if (NotExtCompare && N2C->getAPIntValue() == 1)
10962 // Get a SetCC of the condition
10963 // NOTE: Don't create a SETCC if it's not legal on this target.
10964 if (!LegalOperations ||
10965 TLI.isOperationLegal(ISD::SETCC,
10966 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
10968 // cast from setcc result type to select result type
10970 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
10972 if (N2.getValueType().bitsLT(SCC.getValueType()))
10973 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
10974 N2.getValueType());
10976 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10977 N2.getValueType(), SCC);
10979 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
10980 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10981 N2.getValueType(), SCC);
10984 AddToWorkList(SCC.getNode());
10985 AddToWorkList(Temp.getNode());
10987 if (N2C->getAPIntValue() == 1)
10990 // shl setcc result by log2 n2c
10991 return DAG.getNode(
10992 ISD::SHL, DL, N2.getValueType(), Temp,
10993 DAG.getConstant(N2C->getAPIntValue().logBase2(),
10994 getShiftAmountTy(Temp.getValueType())));
10998 // Check to see if this is the equivalent of setcc
10999 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11000 // otherwise, go ahead with the folds.
11001 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11002 EVT XType = N0.getValueType();
11003 if (!LegalOperations ||
11004 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11005 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11006 if (Res.getValueType() != VT)
11007 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11011 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11012 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11013 (!LegalOperations ||
11014 TLI.isOperationLegal(ISD::CTLZ, XType))) {
11015 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11016 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11017 DAG.getConstant(Log2_32(XType.getSizeInBits()),
11018 getShiftAmountTy(Ctlz.getValueType())));
11020 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11021 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11022 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11023 XType, DAG.getConstant(0, XType), N0);
11024 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11025 return DAG.getNode(ISD::SRL, DL, XType,
11026 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11027 DAG.getConstant(XType.getSizeInBits()-1,
11028 getShiftAmountTy(XType)));
11030 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11031 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11032 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11033 DAG.getConstant(XType.getSizeInBits()-1,
11034 getShiftAmountTy(N0.getValueType())));
11035 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11039 // Check to see if this is an integer abs.
11040 // select_cc setg[te] X, 0, X, -X ->
11041 // select_cc setgt X, -1, X, -X ->
11042 // select_cc setl[te] X, 0, -X, X ->
11043 // select_cc setlt X, 1, -X, X ->
11044 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11046 ConstantSDNode *SubC = NULL;
11047 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11048 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11049 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11050 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11051 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11052 (N1C->isOne() && CC == ISD::SETLT)) &&
11053 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11054 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11056 EVT XType = N0.getValueType();
11057 if (SubC && SubC->isNullValue() && XType.isInteger()) {
11058 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11060 DAG.getConstant(XType.getSizeInBits()-1,
11061 getShiftAmountTy(N0.getValueType())));
11062 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11064 AddToWorkList(Shift.getNode());
11065 AddToWorkList(Add.getNode());
11066 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11073 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11074 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11075 SDValue N1, ISD::CondCode Cond,
11076 SDLoc DL, bool foldBooleans) {
11077 TargetLowering::DAGCombinerInfo
11078 DagCombineInfo(DAG, Level, false, this);
11079 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11082 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11083 /// return a DAG expression to select that will generate the same value by
11084 /// multiplying by a magic number. See:
11085 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11086 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11087 std::vector<SDNode*> Built;
11088 SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
11090 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
11092 AddToWorkList(*ii);
11096 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
11097 /// return a DAG expression to select that will generate the same value by
11098 /// multiplying by a magic number. See:
11099 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11100 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11101 std::vector<SDNode*> Built;
11102 SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
11104 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
11106 AddToWorkList(*ii);
11110 /// FindBaseOffset - Return true if base is a frame index, which is known not
11111 // to alias with anything but itself. Provides base object and offset as
11113 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11114 const GlobalValue *&GV, const void *&CV) {
11115 // Assume it is a primitive operation.
11116 Base = Ptr; Offset = 0; GV = 0; CV = 0;
11118 // If it's an adding a simple constant then integrate the offset.
11119 if (Base.getOpcode() == ISD::ADD) {
11120 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11121 Base = Base.getOperand(0);
11122 Offset += C->getZExtValue();
11126 // Return the underlying GlobalValue, and update the Offset. Return false
11127 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11128 // by multiple nodes with different offsets.
11129 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11130 GV = G->getGlobal();
11131 Offset += G->getOffset();
11135 // Return the underlying Constant value, and update the Offset. Return false
11136 // for ConstantSDNodes since the same constant pool entry may be represented
11137 // by multiple nodes with different offsets.
11138 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11139 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11140 : (const void *)C->getConstVal();
11141 Offset += C->getOffset();
11144 // If it's any of the following then it can't alias with anything but itself.
11145 return isa<FrameIndexSDNode>(Base);
11148 /// isAlias - Return true if there is any possibility that the two addresses
11150 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
11151 const Value *SrcValue1, int SrcValueOffset1,
11152 unsigned SrcValueAlign1,
11153 const MDNode *TBAAInfo1,
11154 SDValue Ptr2, int64_t Size2, bool IsVolatile2,
11155 const Value *SrcValue2, int SrcValueOffset2,
11156 unsigned SrcValueAlign2,
11157 const MDNode *TBAAInfo2) const {
11158 // If they are the same then they must be aliases.
11159 if (Ptr1 == Ptr2) return true;
11161 // If they are both volatile then they cannot be reordered.
11162 if (IsVolatile1 && IsVolatile2) return true;
11164 // Gather base node and offset information.
11165 SDValue Base1, Base2;
11166 int64_t Offset1, Offset2;
11167 const GlobalValue *GV1, *GV2;
11168 const void *CV1, *CV2;
11169 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
11170 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
11172 // If they have a same base address then check to see if they overlap.
11173 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11174 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11176 // It is possible for different frame indices to alias each other, mostly
11177 // when tail call optimization reuses return address slots for arguments.
11178 // To catch this case, look up the actual index of frame indices to compute
11179 // the real alias relationship.
11180 if (isFrameIndex1 && isFrameIndex2) {
11181 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11182 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11183 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11184 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11187 // Otherwise, if we know what the bases are, and they aren't identical, then
11188 // we know they cannot alias.
11189 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11192 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11193 // compared to the size and offset of the access, we may be able to prove they
11194 // do not alias. This check is conservative for now to catch cases created by
11195 // splitting vector types.
11196 if ((SrcValueAlign1 == SrcValueAlign2) &&
11197 (SrcValueOffset1 != SrcValueOffset2) &&
11198 (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
11199 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
11200 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
11202 // There is no overlap between these relatively aligned accesses of similar
11203 // size, return no alias.
11204 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
11208 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11209 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11211 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11212 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11215 if (UseAA && SrcValue1 && SrcValue2) {
11216 // Use alias analysis information.
11217 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
11218 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
11219 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
11220 AliasAnalysis::AliasResult AAResult =
11221 AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1,
11222 UseTBAA ? TBAAInfo1 : 0),
11223 AliasAnalysis::Location(SrcValue2, Overlap2,
11224 UseTBAA ? TBAAInfo2 : 0));
11225 if (AAResult == AliasAnalysis::NoAlias)
11229 // Otherwise we have to assume they alias.
11233 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
11234 SDValue Ptr0, Ptr1;
11235 int64_t Size0, Size1;
11236 bool IsVolatile0, IsVolatile1;
11237 const Value *SrcValue0, *SrcValue1;
11238 int SrcValueOffset0, SrcValueOffset1;
11239 unsigned SrcValueAlign0, SrcValueAlign1;
11240 const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
11241 FindAliasInfo(Op0, Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
11242 SrcValueAlign0, SrcTBAAInfo0);
11243 FindAliasInfo(Op1, Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
11244 SrcValueAlign1, SrcTBAAInfo1);
11245 return isAlias(Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
11246 SrcValueAlign0, SrcTBAAInfo0,
11247 Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
11248 SrcValueAlign1, SrcTBAAInfo1);
11251 /// FindAliasInfo - Extracts the relevant alias information from the memory
11252 /// node. Returns true if the operand was a nonvolatile load.
11253 bool DAGCombiner::FindAliasInfo(SDNode *N,
11254 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
11255 const Value *&SrcValue,
11256 int &SrcValueOffset,
11257 unsigned &SrcValueAlign,
11258 const MDNode *&TBAAInfo) const {
11259 LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
11261 Ptr = LS->getBasePtr();
11262 Size = LS->getMemoryVT().getSizeInBits() >> 3;
11263 IsVolatile = LS->isVolatile();
11264 SrcValue = LS->getSrcValue();
11265 SrcValueOffset = LS->getSrcValueOffset();
11266 SrcValueAlign = LS->getOriginalAlignment();
11267 TBAAInfo = LS->getTBAAInfo();
11268 return isa<LoadSDNode>(LS) && !IsVolatile;
11271 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11272 /// looking for aliasing nodes and adding them to the Aliases vector.
11273 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11274 SmallVectorImpl<SDValue> &Aliases) {
11275 SmallVector<SDValue, 8> Chains; // List of chains to visit.
11276 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
11278 // Get alias information for node.
11282 const Value *SrcValue;
11283 int SrcValueOffset;
11284 unsigned SrcValueAlign;
11285 const MDNode *SrcTBAAInfo;
11286 bool IsLoad = FindAliasInfo(N, Ptr, Size, IsVolatile, SrcValue,
11287 SrcValueOffset, SrcValueAlign, SrcTBAAInfo);
11290 Chains.push_back(OriginalChain);
11291 unsigned Depth = 0;
11293 // Look at each chain and determine if it is an alias. If so, add it to the
11294 // aliases list. If not, then continue up the chain looking for the next
11296 while (!Chains.empty()) {
11297 SDValue Chain = Chains.back();
11300 // For TokenFactor nodes, look at each operand and only continue up the
11301 // chain until we find two aliases. If we've seen two aliases, assume we'll
11302 // find more and revert to original chain since the xform is unlikely to be
11305 // FIXME: The depth check could be made to return the last non-aliasing
11306 // chain we found before we hit a tokenfactor rather than the original
11308 if (Depth > 6 || Aliases.size() == 2) {
11310 Aliases.push_back(OriginalChain);
11314 // Don't bother if we've been before.
11315 if (!Visited.insert(Chain.getNode()))
11318 switch (Chain.getOpcode()) {
11319 case ISD::EntryToken:
11320 // Entry token is ideal chain operand, but handled in FindBetterChain.
11325 // Get alias information for Chain.
11329 const Value *OpSrcValue;
11330 int OpSrcValueOffset;
11331 unsigned OpSrcValueAlign;
11332 const MDNode *OpSrcTBAAInfo;
11333 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
11334 OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11338 // If chain is alias then stop here.
11339 if (!(IsLoad && IsOpLoad) &&
11340 isAlias(Ptr, Size, IsVolatile, SrcValue, SrcValueOffset,
11341 SrcValueAlign, SrcTBAAInfo,
11342 OpPtr, OpSize, OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11343 OpSrcValueAlign, OpSrcTBAAInfo)) {
11344 Aliases.push_back(Chain);
11346 // Look further up the chain.
11347 Chains.push_back(Chain.getOperand(0));
11353 case ISD::TokenFactor:
11354 // We have to check each of the operands of the token factor for "small"
11355 // token factors, so we queue them up. Adding the operands to the queue
11356 // (stack) in reverse order maintains the original order and increases the
11357 // likelihood that getNode will find a matching token factor (CSE.)
11358 if (Chain.getNumOperands() > 16) {
11359 Aliases.push_back(Chain);
11362 for (unsigned n = Chain.getNumOperands(); n;)
11363 Chains.push_back(Chain.getOperand(--n));
11368 // For all other instructions we will just have to take what we can get.
11369 Aliases.push_back(Chain);
11374 // We need to be careful here to also search for aliases through the
11375 // value operand of a store, etc. Consider the following situation:
11377 // L1 = load Token1, %52
11378 // S1 = store Token1, L1, %51
11379 // L2 = load Token1, %52+8
11380 // S2 = store Token1, L2, %51+8
11381 // Token2 = Token(S1, S2)
11382 // L3 = load Token2, %53
11383 // S3 = store Token2, L3, %52
11384 // L4 = load Token2, %53+8
11385 // S4 = store Token2, L4, %52+8
11386 // If we search for aliases of S3 (which loads address %52), and we look
11387 // only through the chain, then we'll miss the trivial dependence on L1
11388 // (which also loads from %52). We then might change all loads and
11389 // stores to use Token1 as their chain operand, which could result in
11390 // copying %53 into %52 before copying %52 into %51 (which should
11393 // The problem is, however, that searching for such data dependencies
11394 // can become expensive, and the cost is not directly related to the
11395 // chain depth. Instead, we'll rule out such configurations here by
11396 // insisting that we've visited all chain users (except for users
11397 // of the original chain, which is not necessary). When doing this,
11398 // we need to look through nodes we don't care about (otherwise, things
11399 // like register copies will interfere with trivial cases).
11401 SmallVector<const SDNode *, 16> Worklist;
11402 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11403 IE = Visited.end(); I != IE; ++I)
11404 if (*I != OriginalChain.getNode())
11405 Worklist.push_back(*I);
11407 while (!Worklist.empty()) {
11408 const SDNode *M = Worklist.pop_back_val();
11410 // We have already visited M, and want to make sure we've visited any uses
11411 // of M that we care about. For uses that we've not visisted, and don't
11412 // care about, queue them to the worklist.
11414 for (SDNode::use_iterator UI = M->use_begin(),
11415 UIE = M->use_end(); UI != UIE; ++UI)
11416 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11417 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11418 // We've not visited this use, and we care about it (it could have an
11419 // ordering dependency with the original node).
11421 Aliases.push_back(OriginalChain);
11425 // We've not visited this use, but we don't care about it. Mark it as
11426 // visited and enqueue it to the worklist.
11427 Worklist.push_back(*UI);
11432 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11433 /// for a better chain (aliasing node.)
11434 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11435 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
11437 // Accumulate all the aliases to this node.
11438 GatherAllAliases(N, OldChain, Aliases);
11440 // If no operands then chain to entry token.
11441 if (Aliases.size() == 0)
11442 return DAG.getEntryNode();
11444 // If a single operand then chain to it. We don't need to revisit it.
11445 if (Aliases.size() == 1)
11448 // Construct a custom tailored token factor.
11449 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
11450 &Aliases[0], Aliases.size());
11453 // SelectionDAG::Combine - This is the entry point for the file.
11455 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11456 CodeGenOpt::Level OptLevel) {
11457 /// run - This is the main entry point to this class.
11459 DAGCombiner(*this, AA, OptLevel).Run(Level);