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 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetLowering.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Target/TargetOptions.h"
37 #include "llvm/Target/TargetRegisterInfo.h"
38 #include "llvm/Target/TargetSubtargetInfo.h"
42 #define DEBUG_TYPE "dagcombine"
44 STATISTIC(NodesCombined , "Number of dag nodes combined");
45 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
46 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
47 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
48 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
49 STATISTIC(SlicedLoads, "Number of load sliced");
53 CombinerAA("combiner-alias-analysis", cl::Hidden,
54 cl::desc("Enable DAG combiner alias-analysis heuristics"));
57 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
58 cl::desc("Enable DAG combiner's use of IR alias analysis"));
61 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
62 cl::desc("Enable DAG combiner's use of TBAA"));
65 static cl::opt<std::string>
66 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
67 cl::desc("Only use DAG-combiner alias analysis in this"
71 /// Hidden option to stress test load slicing, i.e., when this option
72 /// is enabled, load slicing bypasses most of its profitability guards.
74 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
75 cl::desc("Bypass the profitability model of load "
79 //------------------------------ DAGCombiner ---------------------------------//
83 const TargetLowering &TLI;
85 CodeGenOpt::Level OptLevel;
90 // Worklist of all of the nodes that need to be simplified.
92 // This has the semantics that when adding to the worklist,
93 // the item added must be next to be processed. It should
94 // also only appear once. The naive approach to this takes
97 // To reduce the insert/remove time to logarithmic, we use
98 // a set and a vector to maintain our worklist.
100 // The set contains the items on the worklist, but does not
101 // maintain the order they should be visited.
103 // The vector maintains the order nodes should be visited, but may
104 // contain duplicate or removed nodes. When choosing a node to
105 // visit, we pop off the order stack until we find an item that is
106 // also in the contents set. All operations are O(log N).
107 SmallPtrSet<SDNode*, 64> WorkListContents;
108 SmallVector<SDNode*, 64> WorkListOrder;
110 // AA - Used for DAG load/store alias analysis.
113 /// AddUsersToWorkList - When an instruction is simplified, add all users of
114 /// the instruction to the work lists because they might get more simplified
117 void AddUsersToWorkList(SDNode *N) {
118 for (SDNode *Node : N->uses())
122 /// visit - call the node-specific routine that knows how to fold each
123 /// particular type of node.
124 SDValue visit(SDNode *N);
127 /// AddToWorkList - Add to the work list making sure its instance is at the
128 /// back (next to be processed.)
129 void AddToWorkList(SDNode *N) {
130 WorkListContents.insert(N);
131 WorkListOrder.push_back(N);
134 /// removeFromWorkList - remove all instances of N from the worklist.
136 void removeFromWorkList(SDNode *N) {
137 WorkListContents.erase(N);
140 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
143 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
144 return CombineTo(N, &Res, 1, AddTo);
147 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
149 SDValue To[] = { Res0, Res1 };
150 return CombineTo(N, To, 2, AddTo);
153 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
157 /// SimplifyDemandedBits - Check the specified integer node value to see if
158 /// it can be simplified or if things it uses can be simplified by bit
159 /// propagation. If so, return true.
160 bool SimplifyDemandedBits(SDValue Op) {
161 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
162 APInt Demanded = APInt::getAllOnesValue(BitWidth);
163 return SimplifyDemandedBits(Op, Demanded);
166 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
168 bool CombineToPreIndexedLoadStore(SDNode *N);
169 bool CombineToPostIndexedLoadStore(SDNode *N);
170 bool SliceUpLoad(SDNode *N);
172 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
175 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
176 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
177 /// \param EltNo index of the vector element to load.
178 /// \param OriginalLoad load that EVE came from to be replaced.
179 /// \returns EVE on success SDValue() on failure.
180 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
181 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
182 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
183 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
184 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
185 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
186 SDValue PromoteIntBinOp(SDValue Op);
187 SDValue PromoteIntShiftOp(SDValue Op);
188 SDValue PromoteExtend(SDValue Op);
189 bool PromoteLoad(SDValue Op);
191 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
192 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
193 ISD::NodeType ExtType);
195 /// combine - call the node-specific routine that knows how to fold each
196 /// particular type of node. If that doesn't do anything, try the
197 /// target-specific DAG combines.
198 SDValue combine(SDNode *N);
200 // Visitation implementation - Implement dag node combining for different
201 // node types. The semantics are as follows:
203 // SDValue.getNode() == 0 - No change was made
204 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
205 // otherwise - N should be replaced by the returned Operand.
207 SDValue visitTokenFactor(SDNode *N);
208 SDValue visitMERGE_VALUES(SDNode *N);
209 SDValue visitADD(SDNode *N);
210 SDValue visitSUB(SDNode *N);
211 SDValue visitADDC(SDNode *N);
212 SDValue visitSUBC(SDNode *N);
213 SDValue visitADDE(SDNode *N);
214 SDValue visitSUBE(SDNode *N);
215 SDValue visitMUL(SDNode *N);
216 SDValue visitSDIV(SDNode *N);
217 SDValue visitUDIV(SDNode *N);
218 SDValue visitSREM(SDNode *N);
219 SDValue visitUREM(SDNode *N);
220 SDValue visitMULHU(SDNode *N);
221 SDValue visitMULHS(SDNode *N);
222 SDValue visitSMUL_LOHI(SDNode *N);
223 SDValue visitUMUL_LOHI(SDNode *N);
224 SDValue visitSMULO(SDNode *N);
225 SDValue visitUMULO(SDNode *N);
226 SDValue visitSDIVREM(SDNode *N);
227 SDValue visitUDIVREM(SDNode *N);
228 SDValue visitAND(SDNode *N);
229 SDValue visitOR(SDNode *N);
230 SDValue visitXOR(SDNode *N);
231 SDValue SimplifyVBinOp(SDNode *N);
232 SDValue SimplifyVUnaryOp(SDNode *N);
233 SDValue visitSHL(SDNode *N);
234 SDValue visitSRA(SDNode *N);
235 SDValue visitSRL(SDNode *N);
236 SDValue visitRotate(SDNode *N);
237 SDValue visitCTLZ(SDNode *N);
238 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
239 SDValue visitCTTZ(SDNode *N);
240 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
241 SDValue visitCTPOP(SDNode *N);
242 SDValue visitSELECT(SDNode *N);
243 SDValue visitVSELECT(SDNode *N);
244 SDValue visitSELECT_CC(SDNode *N);
245 SDValue visitSETCC(SDNode *N);
246 SDValue visitSIGN_EXTEND(SDNode *N);
247 SDValue visitZERO_EXTEND(SDNode *N);
248 SDValue visitANY_EXTEND(SDNode *N);
249 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
250 SDValue visitTRUNCATE(SDNode *N);
251 SDValue visitBITCAST(SDNode *N);
252 SDValue visitBUILD_PAIR(SDNode *N);
253 SDValue visitFADD(SDNode *N);
254 SDValue visitFSUB(SDNode *N);
255 SDValue visitFMUL(SDNode *N);
256 SDValue visitFMA(SDNode *N);
257 SDValue visitFDIV(SDNode *N);
258 SDValue visitFREM(SDNode *N);
259 SDValue visitFCOPYSIGN(SDNode *N);
260 SDValue visitSINT_TO_FP(SDNode *N);
261 SDValue visitUINT_TO_FP(SDNode *N);
262 SDValue visitFP_TO_SINT(SDNode *N);
263 SDValue visitFP_TO_UINT(SDNode *N);
264 SDValue visitFP_ROUND(SDNode *N);
265 SDValue visitFP_ROUND_INREG(SDNode *N);
266 SDValue visitFP_EXTEND(SDNode *N);
267 SDValue visitFNEG(SDNode *N);
268 SDValue visitFABS(SDNode *N);
269 SDValue visitFCEIL(SDNode *N);
270 SDValue visitFTRUNC(SDNode *N);
271 SDValue visitFFLOOR(SDNode *N);
272 SDValue visitBRCOND(SDNode *N);
273 SDValue visitBR_CC(SDNode *N);
274 SDValue visitLOAD(SDNode *N);
275 SDValue visitSTORE(SDNode *N);
276 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
277 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
278 SDValue visitBUILD_VECTOR(SDNode *N);
279 SDValue visitCONCAT_VECTORS(SDNode *N);
280 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
281 SDValue visitVECTOR_SHUFFLE(SDNode *N);
282 SDValue visitINSERT_SUBVECTOR(SDNode *N);
284 SDValue XformToShuffleWithZero(SDNode *N);
285 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
287 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
289 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
290 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
291 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
292 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
293 SDValue N3, ISD::CondCode CC,
294 bool NotExtCompare = false);
295 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
296 SDLoc DL, bool foldBooleans = true);
298 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
300 bool isOneUseSetCC(SDValue N) const;
302 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
304 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
305 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
306 SDValue BuildSDIV(SDNode *N);
307 SDValue BuildUDIV(SDNode *N);
308 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
309 bool DemandHighBits = true);
310 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
311 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
312 SDValue InnerPos, SDValue InnerNeg,
313 unsigned PosOpcode, unsigned NegOpcode,
315 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
316 SDValue ReduceLoadWidth(SDNode *N);
317 SDValue ReduceLoadOpStoreWidth(SDNode *N);
318 SDValue TransformFPLoadStorePair(SDNode *N);
319 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
320 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
322 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
324 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
325 /// looking for aliasing nodes and adding them to the Aliases vector.
326 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
327 SmallVectorImpl<SDValue> &Aliases);
329 /// isAlias - Return true if there is any possibility that the two addresses
331 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
333 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
334 /// looking for a better chain (aliasing node.)
335 SDValue FindBetterChain(SDNode *N, SDValue Chain);
337 /// Merge consecutive store operations into a wide store.
338 /// This optimization uses wide integers or vectors when possible.
339 /// \return True if some memory operations were changed.
340 bool MergeConsecutiveStores(StoreSDNode *N);
342 /// \brief Try to transform a truncation where C is a constant:
343 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
345 /// \p N needs to be a truncation and its first operand an AND. Other
346 /// requirements are checked by the function (e.g. that trunc is
347 /// single-use) and if missed an empty SDValue is returned.
348 SDValue distributeTruncateThroughAnd(SDNode *N);
351 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
352 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
353 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
354 AttributeSet FnAttrs =
355 DAG.getMachineFunction().getFunction()->getAttributes();
357 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
358 Attribute::OptimizeForSize) ||
359 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
362 /// Run - runs the dag combiner on all nodes in the work list
363 void Run(CombineLevel AtLevel);
365 SelectionDAG &getDAG() const { return DAG; }
367 /// getShiftAmountTy - Returns a type large enough to hold any valid
368 /// shift amount - before type legalization these can be huge.
369 EVT getShiftAmountTy(EVT LHSTy) {
370 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
371 if (LHSTy.isVector())
373 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
374 : TLI.getPointerTy();
377 /// isTypeLegal - This method returns true if we are running before type
378 /// legalization or if the specified VT is legal.
379 bool isTypeLegal(const EVT &VT) {
380 if (!LegalTypes) return true;
381 return TLI.isTypeLegal(VT);
384 /// getSetCCResultType - Convenience wrapper around
385 /// TargetLowering::getSetCCResultType
386 EVT getSetCCResultType(EVT VT) const {
387 return TLI.getSetCCResultType(*DAG.getContext(), VT);
394 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
395 /// nodes from the worklist.
396 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
399 explicit WorkListRemover(DAGCombiner &dc)
400 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
402 void NodeDeleted(SDNode *N, SDNode *E) override {
403 DC.removeFromWorkList(N);
408 //===----------------------------------------------------------------------===//
409 // TargetLowering::DAGCombinerInfo implementation
410 //===----------------------------------------------------------------------===//
412 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
413 ((DAGCombiner*)DC)->AddToWorkList(N);
416 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
417 ((DAGCombiner*)DC)->removeFromWorkList(N);
420 SDValue TargetLowering::DAGCombinerInfo::
421 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
422 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
425 SDValue TargetLowering::DAGCombinerInfo::
426 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
427 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
431 SDValue TargetLowering::DAGCombinerInfo::
432 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
433 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
436 void TargetLowering::DAGCombinerInfo::
437 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
438 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
441 //===----------------------------------------------------------------------===//
443 //===----------------------------------------------------------------------===//
445 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
446 /// specified expression for the same cost as the expression itself, or 2 if we
447 /// can compute the negated form more cheaply than the expression itself.
448 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
449 const TargetLowering &TLI,
450 const TargetOptions *Options,
451 unsigned Depth = 0) {
452 // fneg is removable even if it has multiple uses.
453 if (Op.getOpcode() == ISD::FNEG) return 2;
455 // Don't allow anything with multiple uses.
456 if (!Op.hasOneUse()) return 0;
458 // Don't recurse exponentially.
459 if (Depth > 6) return 0;
461 switch (Op.getOpcode()) {
462 default: return false;
463 case ISD::ConstantFP:
464 // Don't invert constant FP values after legalize. The negated constant
465 // isn't necessarily legal.
466 return LegalOperations ? 0 : 1;
468 // FIXME: determine better conditions for this xform.
469 if (!Options->UnsafeFPMath) return 0;
471 // After operation legalization, it might not be legal to create new FSUBs.
472 if (LegalOperations &&
473 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
476 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
477 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
480 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
481 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
484 // We can't turn -(A-B) into B-A when we honor signed zeros.
485 if (!Options->UnsafeFPMath) return 0;
487 // fold (fneg (fsub A, B)) -> (fsub B, A)
492 if (Options->HonorSignDependentRoundingFPMath()) return 0;
494 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
495 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
499 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
505 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
510 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
511 /// returns the newly negated expression.
512 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
513 bool LegalOperations, unsigned Depth = 0) {
514 // fneg is removable even if it has multiple uses.
515 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
517 // Don't allow anything with multiple uses.
518 assert(Op.hasOneUse() && "Unknown reuse!");
520 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
521 switch (Op.getOpcode()) {
522 default: llvm_unreachable("Unknown code");
523 case ISD::ConstantFP: {
524 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
526 return DAG.getConstantFP(V, Op.getValueType());
529 // FIXME: determine better conditions for this xform.
530 assert(DAG.getTarget().Options.UnsafeFPMath);
532 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
533 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
534 DAG.getTargetLoweringInfo(),
535 &DAG.getTarget().Options, Depth+1))
536 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
537 GetNegatedExpression(Op.getOperand(0), DAG,
538 LegalOperations, Depth+1),
540 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
541 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
542 GetNegatedExpression(Op.getOperand(1), DAG,
543 LegalOperations, Depth+1),
546 // We can't turn -(A-B) into B-A when we honor signed zeros.
547 assert(DAG.getTarget().Options.UnsafeFPMath);
549 // fold (fneg (fsub 0, B)) -> B
550 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
551 if (N0CFP->getValueAPF().isZero())
552 return Op.getOperand(1);
554 // fold (fneg (fsub A, B)) -> (fsub B, A)
555 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
556 Op.getOperand(1), Op.getOperand(0));
560 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
562 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
563 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
564 DAG.getTargetLoweringInfo(),
565 &DAG.getTarget().Options, Depth+1))
566 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
567 GetNegatedExpression(Op.getOperand(0), DAG,
568 LegalOperations, Depth+1),
571 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
572 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
574 GetNegatedExpression(Op.getOperand(1), DAG,
575 LegalOperations, Depth+1));
579 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
580 GetNegatedExpression(Op.getOperand(0), DAG,
581 LegalOperations, Depth+1));
583 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
584 GetNegatedExpression(Op.getOperand(0), DAG,
585 LegalOperations, Depth+1),
590 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
591 // that selects between the target values used for true and false, making it
592 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
593 // the appropriate nodes based on the type of node we are checking. This
594 // simplifies life a bit for the callers.
595 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
597 if (N.getOpcode() == ISD::SETCC) {
598 LHS = N.getOperand(0);
599 RHS = N.getOperand(1);
600 CC = N.getOperand(2);
604 if (N.getOpcode() != ISD::SELECT_CC ||
605 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
606 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
609 LHS = N.getOperand(0);
610 RHS = N.getOperand(1);
611 CC = N.getOperand(4);
615 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
616 // one use. If this is true, it allows the users to invert the operation for
617 // free when it is profitable to do so.
618 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
620 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
625 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
626 /// elements are all the same constant or undefined.
627 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
628 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
633 unsigned SplatBitSize;
635 EVT EltVT = N->getValueType(0).getVectorElementType();
636 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
638 EltVT.getSizeInBits() >= SplatBitSize);
641 // \brief Returns the SDNode if it is a constant BuildVector or constant.
642 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
643 if (isa<ConstantSDNode>(N))
645 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
646 if(BV && BV->isConstant())
651 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
653 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
654 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
657 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N))
658 if (SDValue Splat = BV->getConstantSplatValue())
659 if (auto *CN = dyn_cast<ConstantSDNode>(Splat))
660 // BuildVectors can truncate their operands. Ignore that case here.
661 if (CN->getValueType(0) == N.getValueType().getScalarType())
667 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
668 SDValue N0, SDValue N1) {
669 EVT VT = N0.getValueType();
670 if (N0.getOpcode() == Opc) {
671 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
672 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
673 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
674 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
675 if (!OpNode.getNode())
677 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
679 if (N0.hasOneUse()) {
680 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
682 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
683 if (!OpNode.getNode())
685 AddToWorkList(OpNode.getNode());
686 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
691 if (N1.getOpcode() == Opc) {
692 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
693 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
694 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
695 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
696 if (!OpNode.getNode())
698 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
700 if (N1.hasOneUse()) {
701 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
703 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
704 if (!OpNode.getNode())
706 AddToWorkList(OpNode.getNode());
707 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
715 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
717 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
719 DEBUG(dbgs() << "\nReplacing.1 ";
721 dbgs() << "\nWith: ";
722 To[0].getNode()->dump(&DAG);
723 dbgs() << " and " << NumTo-1 << " other values\n";
724 for (unsigned i = 0, e = NumTo; i != e; ++i)
725 assert((!To[i].getNode() ||
726 N->getValueType(i) == To[i].getValueType()) &&
727 "Cannot combine value to value of different type!"));
728 WorkListRemover DeadNodes(*this);
729 DAG.ReplaceAllUsesWith(N, To);
731 // Push the new nodes and any users onto the worklist
732 for (unsigned i = 0, e = NumTo; i != e; ++i) {
733 if (To[i].getNode()) {
734 AddToWorkList(To[i].getNode());
735 AddUsersToWorkList(To[i].getNode());
740 // Finally, if the node is now dead, remove it from the graph. The node
741 // may not be dead if the replacement process recursively simplified to
742 // something else needing this node.
743 if (N->use_empty()) {
744 // Nodes can be reintroduced into the worklist. Make sure we do not
745 // process a node that has been replaced.
746 removeFromWorkList(N);
748 // Finally, since the node is now dead, remove it from the graph.
751 return SDValue(N, 0);
755 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
756 // Replace all uses. If any nodes become isomorphic to other nodes and
757 // are deleted, make sure to remove them from our worklist.
758 WorkListRemover DeadNodes(*this);
759 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
761 // Push the new node and any (possibly new) users onto the worklist.
762 AddToWorkList(TLO.New.getNode());
763 AddUsersToWorkList(TLO.New.getNode());
765 // Finally, if the node is now dead, remove it from the graph. The node
766 // may not be dead if the replacement process recursively simplified to
767 // something else needing this node.
768 if (TLO.Old.getNode()->use_empty()) {
769 removeFromWorkList(TLO.Old.getNode());
771 // If the operands of this node are only used by the node, they will now
772 // be dead. Make sure to visit them first to delete dead nodes early.
773 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
774 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
775 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
777 DAG.DeleteNode(TLO.Old.getNode());
781 /// SimplifyDemandedBits - Check the specified integer node value to see if
782 /// it can be simplified or if things it uses can be simplified by bit
783 /// propagation. If so, return true.
784 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
785 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
786 APInt KnownZero, KnownOne;
787 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
791 AddToWorkList(Op.getNode());
793 // Replace the old value with the new one.
795 DEBUG(dbgs() << "\nReplacing.2 ";
796 TLO.Old.getNode()->dump(&DAG);
797 dbgs() << "\nWith: ";
798 TLO.New.getNode()->dump(&DAG);
801 CommitTargetLoweringOpt(TLO);
805 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
807 EVT VT = Load->getValueType(0);
808 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
810 DEBUG(dbgs() << "\nReplacing.9 ";
812 dbgs() << "\nWith: ";
813 Trunc.getNode()->dump(&DAG);
815 WorkListRemover DeadNodes(*this);
816 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
817 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
818 removeFromWorkList(Load);
819 DAG.DeleteNode(Load);
820 AddToWorkList(Trunc.getNode());
823 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
826 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
827 EVT MemVT = LD->getMemoryVT();
828 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
829 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
831 : LD->getExtensionType();
833 return DAG.getExtLoad(ExtType, dl, PVT,
834 LD->getChain(), LD->getBasePtr(),
835 MemVT, LD->getMemOperand());
838 unsigned Opc = Op.getOpcode();
841 case ISD::AssertSext:
842 return DAG.getNode(ISD::AssertSext, dl, PVT,
843 SExtPromoteOperand(Op.getOperand(0), PVT),
845 case ISD::AssertZext:
846 return DAG.getNode(ISD::AssertZext, dl, PVT,
847 ZExtPromoteOperand(Op.getOperand(0), PVT),
849 case ISD::Constant: {
851 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
852 return DAG.getNode(ExtOpc, dl, PVT, Op);
856 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
858 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
861 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
862 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
864 EVT OldVT = Op.getValueType();
866 bool Replace = false;
867 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
868 if (!NewOp.getNode())
870 AddToWorkList(NewOp.getNode());
873 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
874 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
875 DAG.getValueType(OldVT));
878 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
879 EVT OldVT = Op.getValueType();
881 bool Replace = false;
882 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
883 if (!NewOp.getNode())
885 AddToWorkList(NewOp.getNode());
888 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
889 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
892 /// PromoteIntBinOp - Promote the specified integer binary operation if the
893 /// target indicates it is beneficial. e.g. On x86, it's usually better to
894 /// promote i16 operations to i32 since i16 instructions are longer.
895 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
896 if (!LegalOperations)
899 EVT VT = Op.getValueType();
900 if (VT.isVector() || !VT.isInteger())
903 // If operation type is 'undesirable', e.g. i16 on x86, consider
905 unsigned Opc = Op.getOpcode();
906 if (TLI.isTypeDesirableForOp(Opc, VT))
910 // Consult target whether it is a good idea to promote this operation and
911 // what's the right type to promote it to.
912 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
913 assert(PVT != VT && "Don't know what type to promote to!");
915 bool Replace0 = false;
916 SDValue N0 = Op.getOperand(0);
917 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
921 bool Replace1 = false;
922 SDValue N1 = Op.getOperand(1);
927 NN1 = PromoteOperand(N1, PVT, Replace1);
932 AddToWorkList(NN0.getNode());
934 AddToWorkList(NN1.getNode());
937 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
939 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
941 DEBUG(dbgs() << "\nPromoting ";
942 Op.getNode()->dump(&DAG));
944 return DAG.getNode(ISD::TRUNCATE, dl, VT,
945 DAG.getNode(Opc, dl, PVT, NN0, NN1));
950 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
951 /// target indicates it is beneficial. e.g. On x86, it's usually better to
952 /// promote i16 operations to i32 since i16 instructions are longer.
953 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
954 if (!LegalOperations)
957 EVT VT = Op.getValueType();
958 if (VT.isVector() || !VT.isInteger())
961 // If operation type is 'undesirable', e.g. i16 on x86, consider
963 unsigned Opc = Op.getOpcode();
964 if (TLI.isTypeDesirableForOp(Opc, VT))
968 // Consult target whether it is a good idea to promote this operation and
969 // what's the right type to promote it to.
970 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
971 assert(PVT != VT && "Don't know what type to promote to!");
973 bool Replace = false;
974 SDValue N0 = Op.getOperand(0);
976 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
977 else if (Opc == ISD::SRL)
978 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
980 N0 = PromoteOperand(N0, PVT, Replace);
984 AddToWorkList(N0.getNode());
986 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
988 DEBUG(dbgs() << "\nPromoting ";
989 Op.getNode()->dump(&DAG));
991 return DAG.getNode(ISD::TRUNCATE, dl, VT,
992 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
997 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
998 if (!LegalOperations)
1001 EVT VT = Op.getValueType();
1002 if (VT.isVector() || !VT.isInteger())
1005 // If operation type is 'undesirable', e.g. i16 on x86, consider
1007 unsigned Opc = Op.getOpcode();
1008 if (TLI.isTypeDesirableForOp(Opc, VT))
1012 // Consult target whether it is a good idea to promote this operation and
1013 // what's the right type to promote it to.
1014 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1015 assert(PVT != VT && "Don't know what type to promote to!");
1016 // fold (aext (aext x)) -> (aext x)
1017 // fold (aext (zext x)) -> (zext x)
1018 // fold (aext (sext x)) -> (sext x)
1019 DEBUG(dbgs() << "\nPromoting ";
1020 Op.getNode()->dump(&DAG));
1021 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1026 bool DAGCombiner::PromoteLoad(SDValue Op) {
1027 if (!LegalOperations)
1030 EVT VT = Op.getValueType();
1031 if (VT.isVector() || !VT.isInteger())
1034 // If operation type is 'undesirable', e.g. i16 on x86, consider
1036 unsigned Opc = Op.getOpcode();
1037 if (TLI.isTypeDesirableForOp(Opc, VT))
1041 // Consult target whether it is a good idea to promote this operation and
1042 // what's the right type to promote it to.
1043 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1044 assert(PVT != VT && "Don't know what type to promote to!");
1047 SDNode *N = Op.getNode();
1048 LoadSDNode *LD = cast<LoadSDNode>(N);
1049 EVT MemVT = LD->getMemoryVT();
1050 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1051 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1053 : LD->getExtensionType();
1054 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1055 LD->getChain(), LD->getBasePtr(),
1056 MemVT, LD->getMemOperand());
1057 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1059 DEBUG(dbgs() << "\nPromoting ";
1062 Result.getNode()->dump(&DAG);
1064 WorkListRemover DeadNodes(*this);
1065 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1066 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1067 removeFromWorkList(N);
1069 AddToWorkList(Result.getNode());
1076 //===----------------------------------------------------------------------===//
1077 // Main DAG Combiner implementation
1078 //===----------------------------------------------------------------------===//
1080 void DAGCombiner::Run(CombineLevel AtLevel) {
1081 // set the instance variables, so that the various visit routines may use it.
1083 LegalOperations = Level >= AfterLegalizeVectorOps;
1084 LegalTypes = Level >= AfterLegalizeTypes;
1086 // Add all the dag nodes to the worklist.
1087 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1088 E = DAG.allnodes_end(); I != E; ++I)
1091 // Create a dummy node (which is not added to allnodes), that adds a reference
1092 // to the root node, preventing it from being deleted, and tracking any
1093 // changes of the root.
1094 HandleSDNode Dummy(DAG.getRoot());
1096 // The root of the dag may dangle to deleted nodes until the dag combiner is
1097 // done. Set it to null to avoid confusion.
1098 DAG.setRoot(SDValue());
1100 // while the worklist isn't empty, find a node and
1101 // try and combine it.
1102 while (!WorkListContents.empty()) {
1104 // The WorkListOrder holds the SDNodes in order, but it may contain
1106 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1107 // worklist *should* contain, and check the node we want to visit is should
1108 // actually be visited.
1110 N = WorkListOrder.pop_back_val();
1111 } while (!WorkListContents.erase(N));
1113 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1114 // N is deleted from the DAG, since they too may now be dead or may have a
1115 // reduced number of uses, allowing other xforms.
1116 if (N->use_empty() && N != &Dummy) {
1117 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1118 AddToWorkList(N->getOperand(i).getNode());
1124 SDValue RV = combine(N);
1131 // If we get back the same node we passed in, rather than a new node or
1132 // zero, we know that the node must have defined multiple values and
1133 // CombineTo was used. Since CombineTo takes care of the worklist
1134 // mechanics for us, we have no work to do in this case.
1135 if (RV.getNode() == N)
1138 assert(N->getOpcode() != ISD::DELETED_NODE &&
1139 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1140 "Node was deleted but visit returned new node!");
1142 DEBUG(dbgs() << "\nReplacing.3 ";
1144 dbgs() << "\nWith: ";
1145 RV.getNode()->dump(&DAG);
1148 // Transfer debug value.
1149 DAG.TransferDbgValues(SDValue(N, 0), RV);
1150 WorkListRemover DeadNodes(*this);
1151 if (N->getNumValues() == RV.getNode()->getNumValues())
1152 DAG.ReplaceAllUsesWith(N, RV.getNode());
1154 assert(N->getValueType(0) == RV.getValueType() &&
1155 N->getNumValues() == 1 && "Type mismatch");
1157 DAG.ReplaceAllUsesWith(N, &OpV);
1160 // Push the new node and any users onto the worklist
1161 AddToWorkList(RV.getNode());
1162 AddUsersToWorkList(RV.getNode());
1164 // Add any uses of the old node to the worklist in case this node is the
1165 // last one that uses them. They may become dead after this node is
1167 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1168 AddToWorkList(N->getOperand(i).getNode());
1170 // Finally, if the node is now dead, remove it from the graph. The node
1171 // may not be dead if the replacement process recursively simplified to
1172 // something else needing this node.
1173 if (N->use_empty()) {
1174 // Nodes can be reintroduced into the worklist. Make sure we do not
1175 // process a node that has been replaced.
1176 removeFromWorkList(N);
1178 // Finally, since the node is now dead, remove it from the graph.
1183 // If the root changed (e.g. it was a dead load, update the root).
1184 DAG.setRoot(Dummy.getValue());
1185 DAG.RemoveDeadNodes();
1188 SDValue DAGCombiner::visit(SDNode *N) {
1189 switch (N->getOpcode()) {
1191 case ISD::TokenFactor: return visitTokenFactor(N);
1192 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1193 case ISD::ADD: return visitADD(N);
1194 case ISD::SUB: return visitSUB(N);
1195 case ISD::ADDC: return visitADDC(N);
1196 case ISD::SUBC: return visitSUBC(N);
1197 case ISD::ADDE: return visitADDE(N);
1198 case ISD::SUBE: return visitSUBE(N);
1199 case ISD::MUL: return visitMUL(N);
1200 case ISD::SDIV: return visitSDIV(N);
1201 case ISD::UDIV: return visitUDIV(N);
1202 case ISD::SREM: return visitSREM(N);
1203 case ISD::UREM: return visitUREM(N);
1204 case ISD::MULHU: return visitMULHU(N);
1205 case ISD::MULHS: return visitMULHS(N);
1206 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1207 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1208 case ISD::SMULO: return visitSMULO(N);
1209 case ISD::UMULO: return visitUMULO(N);
1210 case ISD::SDIVREM: return visitSDIVREM(N);
1211 case ISD::UDIVREM: return visitUDIVREM(N);
1212 case ISD::AND: return visitAND(N);
1213 case ISD::OR: return visitOR(N);
1214 case ISD::XOR: return visitXOR(N);
1215 case ISD::SHL: return visitSHL(N);
1216 case ISD::SRA: return visitSRA(N);
1217 case ISD::SRL: return visitSRL(N);
1219 case ISD::ROTL: return visitRotate(N);
1220 case ISD::CTLZ: return visitCTLZ(N);
1221 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1222 case ISD::CTTZ: return visitCTTZ(N);
1223 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1224 case ISD::CTPOP: return visitCTPOP(N);
1225 case ISD::SELECT: return visitSELECT(N);
1226 case ISD::VSELECT: return visitVSELECT(N);
1227 case ISD::SELECT_CC: return visitSELECT_CC(N);
1228 case ISD::SETCC: return visitSETCC(N);
1229 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1230 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1231 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1232 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1233 case ISD::TRUNCATE: return visitTRUNCATE(N);
1234 case ISD::BITCAST: return visitBITCAST(N);
1235 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1236 case ISD::FADD: return visitFADD(N);
1237 case ISD::FSUB: return visitFSUB(N);
1238 case ISD::FMUL: return visitFMUL(N);
1239 case ISD::FMA: return visitFMA(N);
1240 case ISD::FDIV: return visitFDIV(N);
1241 case ISD::FREM: return visitFREM(N);
1242 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1243 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1244 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1245 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1246 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1247 case ISD::FP_ROUND: return visitFP_ROUND(N);
1248 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1249 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1250 case ISD::FNEG: return visitFNEG(N);
1251 case ISD::FABS: return visitFABS(N);
1252 case ISD::FFLOOR: return visitFFLOOR(N);
1253 case ISD::FCEIL: return visitFCEIL(N);
1254 case ISD::FTRUNC: return visitFTRUNC(N);
1255 case ISD::BRCOND: return visitBRCOND(N);
1256 case ISD::BR_CC: return visitBR_CC(N);
1257 case ISD::LOAD: return visitLOAD(N);
1258 case ISD::STORE: return visitSTORE(N);
1259 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1260 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1261 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1262 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1263 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1264 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1265 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1270 SDValue DAGCombiner::combine(SDNode *N) {
1271 SDValue RV = visit(N);
1273 // If nothing happened, try a target-specific DAG combine.
1274 if (!RV.getNode()) {
1275 assert(N->getOpcode() != ISD::DELETED_NODE &&
1276 "Node was deleted but visit returned NULL!");
1278 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1279 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1281 // Expose the DAG combiner to the target combiner impls.
1282 TargetLowering::DAGCombinerInfo
1283 DagCombineInfo(DAG, Level, false, this);
1285 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1289 // If nothing happened still, try promoting the operation.
1290 if (!RV.getNode()) {
1291 switch (N->getOpcode()) {
1299 RV = PromoteIntBinOp(SDValue(N, 0));
1304 RV = PromoteIntShiftOp(SDValue(N, 0));
1306 case ISD::SIGN_EXTEND:
1307 case ISD::ZERO_EXTEND:
1308 case ISD::ANY_EXTEND:
1309 RV = PromoteExtend(SDValue(N, 0));
1312 if (PromoteLoad(SDValue(N, 0)))
1318 // If N is a commutative binary node, try commuting it to enable more
1320 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1321 N->getNumValues() == 1) {
1322 SDValue N0 = N->getOperand(0);
1323 SDValue N1 = N->getOperand(1);
1325 // Constant operands are canonicalized to RHS.
1326 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1327 SDValue Ops[] = {N1, N0};
1329 if (const BinaryWithFlagsSDNode *BinNode =
1330 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1331 CSENode = DAG.getNodeIfExists(
1332 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1333 BinNode->hasNoSignedWrap(), BinNode->isExact());
1335 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1338 return SDValue(CSENode, 0);
1345 /// getInputChainForNode - Given a node, return its input chain if it has one,
1346 /// otherwise return a null sd operand.
1347 static SDValue getInputChainForNode(SDNode *N) {
1348 if (unsigned NumOps = N->getNumOperands()) {
1349 if (N->getOperand(0).getValueType() == MVT::Other)
1350 return N->getOperand(0);
1351 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1352 return N->getOperand(NumOps-1);
1353 for (unsigned i = 1; i < NumOps-1; ++i)
1354 if (N->getOperand(i).getValueType() == MVT::Other)
1355 return N->getOperand(i);
1360 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1361 // If N has two operands, where one has an input chain equal to the other,
1362 // the 'other' chain is redundant.
1363 if (N->getNumOperands() == 2) {
1364 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1365 return N->getOperand(0);
1366 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1367 return N->getOperand(1);
1370 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1371 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1372 SmallPtrSet<SDNode*, 16> SeenOps;
1373 bool Changed = false; // If we should replace this token factor.
1375 // Start out with this token factor.
1378 // Iterate through token factors. The TFs grows when new token factors are
1380 for (unsigned i = 0; i < TFs.size(); ++i) {
1381 SDNode *TF = TFs[i];
1383 // Check each of the operands.
1384 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1385 SDValue Op = TF->getOperand(i);
1387 switch (Op.getOpcode()) {
1388 case ISD::EntryToken:
1389 // Entry tokens don't need to be added to the list. They are
1394 case ISD::TokenFactor:
1395 if (Op.hasOneUse() &&
1396 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1397 // Queue up for processing.
1398 TFs.push_back(Op.getNode());
1399 // Clean up in case the token factor is removed.
1400 AddToWorkList(Op.getNode());
1407 // Only add if it isn't already in the list.
1408 if (SeenOps.insert(Op.getNode()))
1419 // If we've change things around then replace token factor.
1422 // The entry token is the only possible outcome.
1423 Result = DAG.getEntryNode();
1425 // New and improved token factor.
1426 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1429 // Don't add users to work list.
1430 return CombineTo(N, Result, false);
1436 /// MERGE_VALUES can always be eliminated.
1437 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1438 WorkListRemover DeadNodes(*this);
1439 // Replacing results may cause a different MERGE_VALUES to suddenly
1440 // be CSE'd with N, and carry its uses with it. Iterate until no
1441 // uses remain, to ensure that the node can be safely deleted.
1442 // First add the users of this node to the work list so that they
1443 // can be tried again once they have new operands.
1444 AddUsersToWorkList(N);
1446 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1447 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1448 } while (!N->use_empty());
1449 removeFromWorkList(N);
1451 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1455 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1456 SelectionDAG &DAG) {
1457 EVT VT = N0.getValueType();
1458 SDValue N00 = N0.getOperand(0);
1459 SDValue N01 = N0.getOperand(1);
1460 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1462 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1463 isa<ConstantSDNode>(N00.getOperand(1))) {
1464 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1465 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1466 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1467 N00.getOperand(0), N01),
1468 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1469 N00.getOperand(1), N01));
1470 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1476 SDValue DAGCombiner::visitADD(SDNode *N) {
1477 SDValue N0 = N->getOperand(0);
1478 SDValue N1 = N->getOperand(1);
1479 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1480 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1481 EVT VT = N0.getValueType();
1484 if (VT.isVector()) {
1485 SDValue FoldedVOp = SimplifyVBinOp(N);
1486 if (FoldedVOp.getNode()) return FoldedVOp;
1488 // fold (add x, 0) -> x, vector edition
1489 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1491 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1495 // fold (add x, undef) -> undef
1496 if (N0.getOpcode() == ISD::UNDEF)
1498 if (N1.getOpcode() == ISD::UNDEF)
1500 // fold (add c1, c2) -> c1+c2
1502 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1503 // canonicalize constant to RHS
1505 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1506 // fold (add x, 0) -> x
1507 if (N1C && N1C->isNullValue())
1509 // fold (add Sym, c) -> Sym+c
1510 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1511 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1512 GA->getOpcode() == ISD::GlobalAddress)
1513 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1515 (uint64_t)N1C->getSExtValue());
1516 // fold ((c1-A)+c2) -> (c1+c2)-A
1517 if (N1C && N0.getOpcode() == ISD::SUB)
1518 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1519 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1520 DAG.getConstant(N1C->getAPIntValue()+
1521 N0C->getAPIntValue(), VT),
1524 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1527 // fold ((0-A) + B) -> B-A
1528 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1529 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1530 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1531 // fold (A + (0-B)) -> A-B
1532 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1533 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1534 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1535 // fold (A+(B-A)) -> B
1536 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1537 return N1.getOperand(0);
1538 // fold ((B-A)+A) -> B
1539 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1540 return N0.getOperand(0);
1541 // fold (A+(B-(A+C))) to (B-C)
1542 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1543 N0 == N1.getOperand(1).getOperand(0))
1544 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1545 N1.getOperand(1).getOperand(1));
1546 // fold (A+(B-(C+A))) to (B-C)
1547 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1548 N0 == N1.getOperand(1).getOperand(1))
1549 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1550 N1.getOperand(1).getOperand(0));
1551 // fold (A+((B-A)+or-C)) to (B+or-C)
1552 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1553 N1.getOperand(0).getOpcode() == ISD::SUB &&
1554 N0 == N1.getOperand(0).getOperand(1))
1555 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1556 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1558 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1559 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1560 SDValue N00 = N0.getOperand(0);
1561 SDValue N01 = N0.getOperand(1);
1562 SDValue N10 = N1.getOperand(0);
1563 SDValue N11 = N1.getOperand(1);
1565 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1566 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1567 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1568 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1571 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1572 return SDValue(N, 0);
1574 // fold (a+b) -> (a|b) iff a and b share no bits.
1575 if (VT.isInteger() && !VT.isVector()) {
1576 APInt LHSZero, LHSOne;
1577 APInt RHSZero, RHSOne;
1578 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1580 if (LHSZero.getBoolValue()) {
1581 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1583 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1584 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1585 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1586 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1587 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1592 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1593 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1594 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1595 if (Result.getNode()) return Result;
1597 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1598 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1599 if (Result.getNode()) return Result;
1602 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1603 if (N1.getOpcode() == ISD::SHL &&
1604 N1.getOperand(0).getOpcode() == ISD::SUB)
1605 if (ConstantSDNode *C =
1606 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1607 if (C->getAPIntValue() == 0)
1608 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1609 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1610 N1.getOperand(0).getOperand(1),
1612 if (N0.getOpcode() == ISD::SHL &&
1613 N0.getOperand(0).getOpcode() == ISD::SUB)
1614 if (ConstantSDNode *C =
1615 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1616 if (C->getAPIntValue() == 0)
1617 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1618 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1619 N0.getOperand(0).getOperand(1),
1622 if (N1.getOpcode() == ISD::AND) {
1623 SDValue AndOp0 = N1.getOperand(0);
1624 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1625 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1626 unsigned DestBits = VT.getScalarType().getSizeInBits();
1628 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1629 // and similar xforms where the inner op is either ~0 or 0.
1630 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1632 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1636 // add (sext i1), X -> sub X, (zext i1)
1637 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1638 N0.getOperand(0).getValueType() == MVT::i1 &&
1639 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1641 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1642 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1648 SDValue DAGCombiner::visitADDC(SDNode *N) {
1649 SDValue N0 = N->getOperand(0);
1650 SDValue N1 = N->getOperand(1);
1651 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1652 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1653 EVT VT = N0.getValueType();
1655 // If the flag result is dead, turn this into an ADD.
1656 if (!N->hasAnyUseOfValue(1))
1657 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1658 DAG.getNode(ISD::CARRY_FALSE,
1659 SDLoc(N), MVT::Glue));
1661 // canonicalize constant to RHS.
1663 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1665 // fold (addc x, 0) -> x + no carry out
1666 if (N1C && N1C->isNullValue())
1667 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1668 SDLoc(N), MVT::Glue));
1670 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1671 APInt LHSZero, LHSOne;
1672 APInt RHSZero, RHSOne;
1673 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1675 if (LHSZero.getBoolValue()) {
1676 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1678 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1679 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1680 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1681 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1682 DAG.getNode(ISD::CARRY_FALSE,
1683 SDLoc(N), MVT::Glue));
1689 SDValue DAGCombiner::visitADDE(SDNode *N) {
1690 SDValue N0 = N->getOperand(0);
1691 SDValue N1 = N->getOperand(1);
1692 SDValue CarryIn = N->getOperand(2);
1693 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1694 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1696 // canonicalize constant to RHS
1698 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1701 // fold (adde x, y, false) -> (addc x, y)
1702 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1703 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1708 // Since it may not be valid to emit a fold to zero for vector initializers
1709 // check if we can before folding.
1710 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1712 bool LegalOperations, bool LegalTypes) {
1714 return DAG.getConstant(0, VT);
1715 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1716 return DAG.getConstant(0, VT);
1720 SDValue DAGCombiner::visitSUB(SDNode *N) {
1721 SDValue N0 = N->getOperand(0);
1722 SDValue N1 = N->getOperand(1);
1723 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1724 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1725 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1726 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1727 EVT VT = N0.getValueType();
1730 if (VT.isVector()) {
1731 SDValue FoldedVOp = SimplifyVBinOp(N);
1732 if (FoldedVOp.getNode()) return FoldedVOp;
1734 // fold (sub x, 0) -> x, vector edition
1735 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1739 // fold (sub x, x) -> 0
1740 // FIXME: Refactor this and xor and other similar operations together.
1742 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1743 // fold (sub c1, c2) -> c1-c2
1745 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1746 // fold (sub x, c) -> (add x, -c)
1748 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1749 DAG.getConstant(-N1C->getAPIntValue(), VT));
1750 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1751 if (N0C && N0C->isAllOnesValue())
1752 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1753 // fold A-(A-B) -> B
1754 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1755 return N1.getOperand(1);
1756 // fold (A+B)-A -> B
1757 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1758 return N0.getOperand(1);
1759 // fold (A+B)-B -> A
1760 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1761 return N0.getOperand(0);
1762 // fold C2-(A+C1) -> (C2-C1)-A
1763 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1764 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1766 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1769 // fold ((A+(B+or-C))-B) -> A+or-C
1770 if (N0.getOpcode() == ISD::ADD &&
1771 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1772 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1773 N0.getOperand(1).getOperand(0) == N1)
1774 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1775 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1776 // fold ((A+(C+B))-B) -> A+C
1777 if (N0.getOpcode() == ISD::ADD &&
1778 N0.getOperand(1).getOpcode() == ISD::ADD &&
1779 N0.getOperand(1).getOperand(1) == N1)
1780 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1781 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1782 // fold ((A-(B-C))-C) -> A-B
1783 if (N0.getOpcode() == ISD::SUB &&
1784 N0.getOperand(1).getOpcode() == ISD::SUB &&
1785 N0.getOperand(1).getOperand(1) == N1)
1786 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1787 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1789 // If either operand of a sub is undef, the result is undef
1790 if (N0.getOpcode() == ISD::UNDEF)
1792 if (N1.getOpcode() == ISD::UNDEF)
1795 // If the relocation model supports it, consider symbol offsets.
1796 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1797 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1798 // fold (sub Sym, c) -> Sym-c
1799 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1800 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1802 (uint64_t)N1C->getSExtValue());
1803 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1804 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1805 if (GA->getGlobal() == GB->getGlobal())
1806 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1813 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1814 SDValue N0 = N->getOperand(0);
1815 SDValue N1 = N->getOperand(1);
1816 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1817 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1818 EVT VT = N0.getValueType();
1820 // If the flag result is dead, turn this into an SUB.
1821 if (!N->hasAnyUseOfValue(1))
1822 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1823 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1826 // fold (subc x, x) -> 0 + no borrow
1828 return CombineTo(N, DAG.getConstant(0, VT),
1829 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1832 // fold (subc x, 0) -> x + no borrow
1833 if (N1C && N1C->isNullValue())
1834 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1837 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1838 if (N0C && N0C->isAllOnesValue())
1839 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1840 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1846 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1847 SDValue N0 = N->getOperand(0);
1848 SDValue N1 = N->getOperand(1);
1849 SDValue CarryIn = N->getOperand(2);
1851 // fold (sube x, y, false) -> (subc x, y)
1852 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1853 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1858 SDValue DAGCombiner::visitMUL(SDNode *N) {
1859 SDValue N0 = N->getOperand(0);
1860 SDValue N1 = N->getOperand(1);
1861 EVT VT = N0.getValueType();
1863 // fold (mul x, undef) -> 0
1864 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1865 return DAG.getConstant(0, VT);
1867 bool N0IsConst = false;
1868 bool N1IsConst = false;
1869 APInt ConstValue0, ConstValue1;
1871 if (VT.isVector()) {
1872 SDValue FoldedVOp = SimplifyVBinOp(N);
1873 if (FoldedVOp.getNode()) return FoldedVOp;
1875 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1876 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1878 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1879 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1881 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1882 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1886 // fold (mul c1, c2) -> c1*c2
1887 if (N0IsConst && N1IsConst)
1888 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1890 // canonicalize constant to RHS
1891 if (N0IsConst && !N1IsConst)
1892 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1893 // fold (mul x, 0) -> 0
1894 if (N1IsConst && ConstValue1 == 0)
1896 // We require a splat of the entire scalar bit width for non-contiguous
1899 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1900 // fold (mul x, 1) -> x
1901 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1903 // fold (mul x, -1) -> 0-x
1904 if (N1IsConst && ConstValue1.isAllOnesValue())
1905 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1906 DAG.getConstant(0, VT), N0);
1907 // fold (mul x, (1 << c)) -> x << c
1908 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1909 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1910 DAG.getConstant(ConstValue1.logBase2(),
1911 getShiftAmountTy(N0.getValueType())));
1912 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1913 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1914 unsigned Log2Val = (-ConstValue1).logBase2();
1915 // FIXME: If the input is something that is easily negated (e.g. a
1916 // single-use add), we should put the negate there.
1917 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1918 DAG.getConstant(0, VT),
1919 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1920 DAG.getConstant(Log2Val,
1921 getShiftAmountTy(N0.getValueType()))));
1925 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1926 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1927 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1928 isa<ConstantSDNode>(N0.getOperand(1)))) {
1929 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1930 N1, N0.getOperand(1));
1931 AddToWorkList(C3.getNode());
1932 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1933 N0.getOperand(0), C3);
1936 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1939 SDValue Sh(nullptr,0), Y(nullptr,0);
1940 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1941 if (N0.getOpcode() == ISD::SHL &&
1942 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1943 isa<ConstantSDNode>(N0.getOperand(1))) &&
1944 N0.getNode()->hasOneUse()) {
1946 } else if (N1.getOpcode() == ISD::SHL &&
1947 isa<ConstantSDNode>(N1.getOperand(1)) &&
1948 N1.getNode()->hasOneUse()) {
1953 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1954 Sh.getOperand(0), Y);
1955 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1956 Mul, Sh.getOperand(1));
1960 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1961 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1962 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1963 isa<ConstantSDNode>(N0.getOperand(1))))
1964 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1965 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1966 N0.getOperand(0), N1),
1967 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1968 N0.getOperand(1), N1));
1971 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1978 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1979 SDValue N0 = N->getOperand(0);
1980 SDValue N1 = N->getOperand(1);
1981 ConstantSDNode *N0C = isConstOrConstSplat(N0);
1982 ConstantSDNode *N1C = isConstOrConstSplat(N1);
1983 EVT VT = N->getValueType(0);
1986 if (VT.isVector()) {
1987 SDValue FoldedVOp = SimplifyVBinOp(N);
1988 if (FoldedVOp.getNode()) return FoldedVOp;
1991 // fold (sdiv c1, c2) -> c1/c2
1992 if (N0C && N1C && !N1C->isNullValue())
1993 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1994 // fold (sdiv X, 1) -> X
1995 if (N1C && N1C->getAPIntValue() == 1LL)
1997 // fold (sdiv X, -1) -> 0-X
1998 if (N1C && N1C->isAllOnesValue())
1999 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2000 DAG.getConstant(0, VT), N0);
2001 // If we know the sign bits of both operands are zero, strength reduce to a
2002 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2003 if (!VT.isVector()) {
2004 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2005 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2009 // fold (sdiv X, pow2) -> simple ops after legalize
2010 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2011 (-N1C->getAPIntValue()).isPowerOf2())) {
2012 // If dividing by powers of two is cheap, then don't perform the following
2014 if (TLI.isPow2DivCheap())
2017 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2019 // Splat the sign bit into the register
2021 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2022 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2023 getShiftAmountTy(N0.getValueType())));
2024 AddToWorkList(SGN.getNode());
2026 // Add (N0 < 0) ? abs2 - 1 : 0;
2028 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2029 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2030 getShiftAmountTy(SGN.getValueType())));
2031 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2032 AddToWorkList(SRL.getNode());
2033 AddToWorkList(ADD.getNode()); // Divide by pow2
2034 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2035 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2037 // If we're dividing by a positive value, we're done. Otherwise, we must
2038 // negate the result.
2039 if (N1C->getAPIntValue().isNonNegative())
2042 AddToWorkList(SRA.getNode());
2043 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2046 // if integer divide is expensive and we satisfy the requirements, emit an
2047 // alternate sequence.
2048 if (N1C && !TLI.isIntDivCheap()) {
2049 SDValue Op = BuildSDIV(N);
2050 if (Op.getNode()) return Op;
2054 if (N0.getOpcode() == ISD::UNDEF)
2055 return DAG.getConstant(0, VT);
2056 // X / undef -> undef
2057 if (N1.getOpcode() == ISD::UNDEF)
2063 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2064 SDValue N0 = N->getOperand(0);
2065 SDValue N1 = N->getOperand(1);
2066 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2067 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2068 EVT VT = N->getValueType(0);
2071 if (VT.isVector()) {
2072 SDValue FoldedVOp = SimplifyVBinOp(N);
2073 if (FoldedVOp.getNode()) return FoldedVOp;
2076 // fold (udiv c1, c2) -> c1/c2
2077 if (N0C && N1C && !N1C->isNullValue())
2078 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2079 // fold (udiv x, (1 << c)) -> x >>u c
2080 if (N1C && N1C->getAPIntValue().isPowerOf2())
2081 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2082 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2083 getShiftAmountTy(N0.getValueType())));
2084 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2085 if (N1.getOpcode() == ISD::SHL) {
2086 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2087 if (SHC->getAPIntValue().isPowerOf2()) {
2088 EVT ADDVT = N1.getOperand(1).getValueType();
2089 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2091 DAG.getConstant(SHC->getAPIntValue()
2094 AddToWorkList(Add.getNode());
2095 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2099 // fold (udiv x, c) -> alternate
2100 if (N1C && !TLI.isIntDivCheap()) {
2101 SDValue Op = BuildUDIV(N);
2102 if (Op.getNode()) return Op;
2106 if (N0.getOpcode() == ISD::UNDEF)
2107 return DAG.getConstant(0, VT);
2108 // X / undef -> undef
2109 if (N1.getOpcode() == ISD::UNDEF)
2115 SDValue DAGCombiner::visitSREM(SDNode *N) {
2116 SDValue N0 = N->getOperand(0);
2117 SDValue N1 = N->getOperand(1);
2118 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2119 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2120 EVT VT = N->getValueType(0);
2122 // fold (srem c1, c2) -> c1%c2
2123 if (N0C && N1C && !N1C->isNullValue())
2124 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2125 // If we know the sign bits of both operands are zero, strength reduce to a
2126 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2127 if (!VT.isVector()) {
2128 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2129 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2132 // If X/C can be simplified by the division-by-constant logic, lower
2133 // X%C to the equivalent of X-X/C*C.
2134 if (N1C && !N1C->isNullValue()) {
2135 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2136 AddToWorkList(Div.getNode());
2137 SDValue OptimizedDiv = combine(Div.getNode());
2138 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2139 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2141 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2142 AddToWorkList(Mul.getNode());
2148 if (N0.getOpcode() == ISD::UNDEF)
2149 return DAG.getConstant(0, VT);
2150 // X % undef -> undef
2151 if (N1.getOpcode() == ISD::UNDEF)
2157 SDValue DAGCombiner::visitUREM(SDNode *N) {
2158 SDValue N0 = N->getOperand(0);
2159 SDValue N1 = N->getOperand(1);
2160 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2161 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2162 EVT VT = N->getValueType(0);
2164 // fold (urem c1, c2) -> c1%c2
2165 if (N0C && N1C && !N1C->isNullValue())
2166 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2167 // fold (urem x, pow2) -> (and x, pow2-1)
2168 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2169 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2170 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2171 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2172 if (N1.getOpcode() == ISD::SHL) {
2173 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2174 if (SHC->getAPIntValue().isPowerOf2()) {
2176 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2177 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2179 AddToWorkList(Add.getNode());
2180 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2185 // If X/C can be simplified by the division-by-constant logic, lower
2186 // X%C to the equivalent of X-X/C*C.
2187 if (N1C && !N1C->isNullValue()) {
2188 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2189 AddToWorkList(Div.getNode());
2190 SDValue OptimizedDiv = combine(Div.getNode());
2191 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2192 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2194 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2195 AddToWorkList(Mul.getNode());
2201 if (N0.getOpcode() == ISD::UNDEF)
2202 return DAG.getConstant(0, VT);
2203 // X % undef -> undef
2204 if (N1.getOpcode() == ISD::UNDEF)
2210 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2211 SDValue N0 = N->getOperand(0);
2212 SDValue N1 = N->getOperand(1);
2213 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2214 EVT VT = N->getValueType(0);
2217 // fold (mulhs x, 0) -> 0
2218 if (N1C && N1C->isNullValue())
2220 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2221 if (N1C && N1C->getAPIntValue() == 1)
2222 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2223 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2224 getShiftAmountTy(N0.getValueType())));
2225 // fold (mulhs x, undef) -> 0
2226 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2227 return DAG.getConstant(0, VT);
2229 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2231 if (VT.isSimple() && !VT.isVector()) {
2232 MVT Simple = VT.getSimpleVT();
2233 unsigned SimpleSize = Simple.getSizeInBits();
2234 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2235 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2236 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2237 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2238 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2239 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2240 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2241 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2248 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2249 SDValue N0 = N->getOperand(0);
2250 SDValue N1 = N->getOperand(1);
2251 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2252 EVT VT = N->getValueType(0);
2255 // fold (mulhu x, 0) -> 0
2256 if (N1C && N1C->isNullValue())
2258 // fold (mulhu x, 1) -> 0
2259 if (N1C && N1C->getAPIntValue() == 1)
2260 return DAG.getConstant(0, N0.getValueType());
2261 // fold (mulhu x, undef) -> 0
2262 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2263 return DAG.getConstant(0, VT);
2265 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2267 if (VT.isSimple() && !VT.isVector()) {
2268 MVT Simple = VT.getSimpleVT();
2269 unsigned SimpleSize = Simple.getSizeInBits();
2270 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2271 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2272 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2273 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2274 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2275 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2276 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2277 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2284 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2285 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2286 /// that are being performed. Return true if a simplification was made.
2288 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2290 // If the high half is not needed, just compute the low half.
2291 bool HiExists = N->hasAnyUseOfValue(1);
2293 (!LegalOperations ||
2294 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2295 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2296 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2297 return CombineTo(N, Res, Res);
2300 // If the low half is not needed, just compute the high half.
2301 bool LoExists = N->hasAnyUseOfValue(0);
2303 (!LegalOperations ||
2304 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2305 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2306 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2307 return CombineTo(N, Res, Res);
2310 // If both halves are used, return as it is.
2311 if (LoExists && HiExists)
2314 // If the two computed results can be simplified separately, separate them.
2316 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2317 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2318 AddToWorkList(Lo.getNode());
2319 SDValue LoOpt = combine(Lo.getNode());
2320 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2321 (!LegalOperations ||
2322 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2323 return CombineTo(N, LoOpt, LoOpt);
2327 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2328 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2329 AddToWorkList(Hi.getNode());
2330 SDValue HiOpt = combine(Hi.getNode());
2331 if (HiOpt.getNode() && HiOpt != Hi &&
2332 (!LegalOperations ||
2333 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2334 return CombineTo(N, HiOpt, HiOpt);
2340 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2341 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2342 if (Res.getNode()) return Res;
2344 EVT VT = N->getValueType(0);
2347 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2349 if (VT.isSimple() && !VT.isVector()) {
2350 MVT Simple = VT.getSimpleVT();
2351 unsigned SimpleSize = Simple.getSizeInBits();
2352 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2353 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2354 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2355 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2356 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2357 // Compute the high part as N1.
2358 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2359 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2360 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2361 // Compute the low part as N0.
2362 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2363 return CombineTo(N, Lo, Hi);
2370 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2371 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2372 if (Res.getNode()) return Res;
2374 EVT VT = N->getValueType(0);
2377 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2379 if (VT.isSimple() && !VT.isVector()) {
2380 MVT Simple = VT.getSimpleVT();
2381 unsigned SimpleSize = Simple.getSizeInBits();
2382 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2383 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2384 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2385 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2386 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2387 // Compute the high part as N1.
2388 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2389 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2390 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2391 // Compute the low part as N0.
2392 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2393 return CombineTo(N, Lo, Hi);
2400 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2401 // (smulo x, 2) -> (saddo x, x)
2402 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2403 if (C2->getAPIntValue() == 2)
2404 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2405 N->getOperand(0), N->getOperand(0));
2410 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2411 // (umulo x, 2) -> (uaddo x, x)
2412 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2413 if (C2->getAPIntValue() == 2)
2414 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2415 N->getOperand(0), N->getOperand(0));
2420 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2421 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2422 if (Res.getNode()) return Res;
2427 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2428 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2429 if (Res.getNode()) return Res;
2434 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2435 /// two operands of the same opcode, try to simplify it.
2436 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2437 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2438 EVT VT = N0.getValueType();
2439 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2441 // Bail early if none of these transforms apply.
2442 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2444 // For each of OP in AND/OR/XOR:
2445 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2446 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2447 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2448 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2450 // do not sink logical op inside of a vector extend, since it may combine
2452 EVT Op0VT = N0.getOperand(0).getValueType();
2453 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2454 N0.getOpcode() == ISD::SIGN_EXTEND ||
2455 // Avoid infinite looping with PromoteIntBinOp.
2456 (N0.getOpcode() == ISD::ANY_EXTEND &&
2457 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2458 (N0.getOpcode() == ISD::TRUNCATE &&
2459 (!TLI.isZExtFree(VT, Op0VT) ||
2460 !TLI.isTruncateFree(Op0VT, VT)) &&
2461 TLI.isTypeLegal(Op0VT))) &&
2463 Op0VT == N1.getOperand(0).getValueType() &&
2464 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2465 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2466 N0.getOperand(0).getValueType(),
2467 N0.getOperand(0), N1.getOperand(0));
2468 AddToWorkList(ORNode.getNode());
2469 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2472 // For each of OP in SHL/SRL/SRA/AND...
2473 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2474 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2475 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2476 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2477 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2478 N0.getOperand(1) == N1.getOperand(1)) {
2479 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2480 N0.getOperand(0).getValueType(),
2481 N0.getOperand(0), N1.getOperand(0));
2482 AddToWorkList(ORNode.getNode());
2483 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2484 ORNode, N0.getOperand(1));
2487 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2488 // Only perform this optimization after type legalization and before
2489 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2490 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2491 // we don't want to undo this promotion.
2492 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2494 if ((N0.getOpcode() == ISD::BITCAST ||
2495 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2496 Level == AfterLegalizeTypes) {
2497 SDValue In0 = N0.getOperand(0);
2498 SDValue In1 = N1.getOperand(0);
2499 EVT In0Ty = In0.getValueType();
2500 EVT In1Ty = In1.getValueType();
2502 // If both incoming values are integers, and the original types are the
2504 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2505 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2506 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2507 AddToWorkList(Op.getNode());
2512 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2513 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2514 // If both shuffles use the same mask, and both shuffle within a single
2515 // vector, then it is worthwhile to move the swizzle after the operation.
2516 // The type-legalizer generates this pattern when loading illegal
2517 // vector types from memory. In many cases this allows additional shuffle
2519 // There are other cases where moving the shuffle after the xor/and/or
2520 // is profitable even if shuffles don't perform a swizzle.
2521 // If both shuffles use the same mask, and both shuffles have the same first
2522 // or second operand, then it might still be profitable to move the shuffle
2523 // after the xor/and/or operation.
2524 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2525 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2526 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2528 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2529 "Inputs to shuffles are not the same type");
2531 // Check that both shuffles use the same mask. The masks are known to be of
2532 // the same length because the result vector type is the same.
2533 // Check also that shuffles have only one use to avoid introducing extra
2535 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2536 SVN0->getMask().equals(SVN1->getMask())) {
2537 SDValue ShOp = N0->getOperand(1);
2539 // Don't try to fold this node if it requires introducing a
2540 // build vector of all zeros that might be illegal at this stage.
2541 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2543 ShOp = DAG.getConstant(0, VT);
2548 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2549 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2550 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2551 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2552 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2553 N0->getOperand(0), N1->getOperand(0));
2554 AddToWorkList(NewNode.getNode());
2555 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2556 &SVN0->getMask()[0]);
2559 // Don't try to fold this node if it requires introducing a
2560 // build vector of all zeros that might be illegal at this stage.
2561 ShOp = N0->getOperand(0);
2562 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2564 ShOp = DAG.getConstant(0, VT);
2569 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2570 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2571 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2572 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2573 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2574 N0->getOperand(1), N1->getOperand(1));
2575 AddToWorkList(NewNode.getNode());
2576 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2577 &SVN0->getMask()[0]);
2585 SDValue DAGCombiner::visitAND(SDNode *N) {
2586 SDValue N0 = N->getOperand(0);
2587 SDValue N1 = N->getOperand(1);
2588 SDValue LL, LR, RL, RR, CC0, CC1;
2589 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2590 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2591 EVT VT = N1.getValueType();
2592 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2595 if (VT.isVector()) {
2596 SDValue FoldedVOp = SimplifyVBinOp(N);
2597 if (FoldedVOp.getNode()) return FoldedVOp;
2599 // fold (and x, 0) -> 0, vector edition
2600 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2602 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2605 // fold (and x, -1) -> x, vector edition
2606 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2608 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2612 // fold (and x, undef) -> 0
2613 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2614 return DAG.getConstant(0, VT);
2615 // fold (and c1, c2) -> c1&c2
2617 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2618 // canonicalize constant to RHS
2620 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2621 // fold (and x, -1) -> x
2622 if (N1C && N1C->isAllOnesValue())
2624 // if (and x, c) is known to be zero, return 0
2625 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2626 APInt::getAllOnesValue(BitWidth)))
2627 return DAG.getConstant(0, VT);
2629 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2632 // fold (and (or x, C), D) -> D if (C & D) == D
2633 if (N1C && N0.getOpcode() == ISD::OR)
2634 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2635 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2637 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2638 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2639 SDValue N0Op0 = N0.getOperand(0);
2640 APInt Mask = ~N1C->getAPIntValue();
2641 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2642 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2643 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2644 N0.getValueType(), N0Op0);
2646 // Replace uses of the AND with uses of the Zero extend node.
2649 // We actually want to replace all uses of the any_extend with the
2650 // zero_extend, to avoid duplicating things. This will later cause this
2651 // AND to be folded.
2652 CombineTo(N0.getNode(), Zext);
2653 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2656 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2657 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2658 // already be zero by virtue of the width of the base type of the load.
2660 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2662 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2663 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2664 N0.getOpcode() == ISD::LOAD) {
2665 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2666 N0 : N0.getOperand(0) );
2668 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2669 // This can be a pure constant or a vector splat, in which case we treat the
2670 // vector as a scalar and use the splat value.
2671 APInt Constant = APInt::getNullValue(1);
2672 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2673 Constant = C->getAPIntValue();
2674 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2675 APInt SplatValue, SplatUndef;
2676 unsigned SplatBitSize;
2678 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2679 SplatBitSize, HasAnyUndefs);
2681 // Undef bits can contribute to a possible optimisation if set, so
2683 SplatValue |= SplatUndef;
2685 // The splat value may be something like "0x00FFFFFF", which means 0 for
2686 // the first vector value and FF for the rest, repeating. We need a mask
2687 // that will apply equally to all members of the vector, so AND all the
2688 // lanes of the constant together.
2689 EVT VT = Vector->getValueType(0);
2690 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2692 // If the splat value has been compressed to a bitlength lower
2693 // than the size of the vector lane, we need to re-expand it to
2695 if (BitWidth > SplatBitSize)
2696 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2697 SplatBitSize < BitWidth;
2698 SplatBitSize = SplatBitSize * 2)
2699 SplatValue |= SplatValue.shl(SplatBitSize);
2701 Constant = APInt::getAllOnesValue(BitWidth);
2702 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2703 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2707 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2708 // actually legal and isn't going to get expanded, else this is a false
2710 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2711 Load->getMemoryVT());
2713 // Resize the constant to the same size as the original memory access before
2714 // extension. If it is still the AllOnesValue then this AND is completely
2717 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2720 switch (Load->getExtensionType()) {
2721 default: B = false; break;
2722 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2724 case ISD::NON_EXTLOAD: B = true; break;
2727 if (B && Constant.isAllOnesValue()) {
2728 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2729 // preserve semantics once we get rid of the AND.
2730 SDValue NewLoad(Load, 0);
2731 if (Load->getExtensionType() == ISD::EXTLOAD) {
2732 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2733 Load->getValueType(0), SDLoc(Load),
2734 Load->getChain(), Load->getBasePtr(),
2735 Load->getOffset(), Load->getMemoryVT(),
2736 Load->getMemOperand());
2737 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2738 if (Load->getNumValues() == 3) {
2739 // PRE/POST_INC loads have 3 values.
2740 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2741 NewLoad.getValue(2) };
2742 CombineTo(Load, To, 3, true);
2744 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2748 // Fold the AND away, taking care not to fold to the old load node if we
2750 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2752 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2755 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2756 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2757 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2758 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2760 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2761 LL.getValueType().isInteger()) {
2762 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2763 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2764 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2765 LR.getValueType(), LL, RL);
2766 AddToWorkList(ORNode.getNode());
2767 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2769 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2770 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2771 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2772 LR.getValueType(), LL, RL);
2773 AddToWorkList(ANDNode.getNode());
2774 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2776 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2777 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2778 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2779 LR.getValueType(), LL, RL);
2780 AddToWorkList(ORNode.getNode());
2781 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2784 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2785 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2786 Op0 == Op1 && LL.getValueType().isInteger() &&
2787 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2788 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2789 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2790 cast<ConstantSDNode>(RR)->isNullValue()))) {
2791 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2792 LL, DAG.getConstant(1, LL.getValueType()));
2793 AddToWorkList(ADDNode.getNode());
2794 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2795 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2797 // canonicalize equivalent to ll == rl
2798 if (LL == RR && LR == RL) {
2799 Op1 = ISD::getSetCCSwappedOperands(Op1);
2802 if (LL == RL && LR == RR) {
2803 bool isInteger = LL.getValueType().isInteger();
2804 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2805 if (Result != ISD::SETCC_INVALID &&
2806 (!LegalOperations ||
2807 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2808 TLI.isOperationLegal(ISD::SETCC,
2809 getSetCCResultType(N0.getSimpleValueType())))))
2810 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2815 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2816 if (N0.getOpcode() == N1.getOpcode()) {
2817 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2818 if (Tmp.getNode()) return Tmp;
2821 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2822 // fold (and (sra)) -> (and (srl)) when possible.
2823 if (!VT.isVector() &&
2824 SimplifyDemandedBits(SDValue(N, 0)))
2825 return SDValue(N, 0);
2827 // fold (zext_inreg (extload x)) -> (zextload x)
2828 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2829 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2830 EVT MemVT = LN0->getMemoryVT();
2831 // If we zero all the possible extended bits, then we can turn this into
2832 // a zextload if we are running before legalize or the operation is legal.
2833 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2834 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2835 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2836 ((!LegalOperations && !LN0->isVolatile()) ||
2837 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2838 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2839 LN0->getChain(), LN0->getBasePtr(),
2840 MemVT, LN0->getMemOperand());
2842 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2843 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2846 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2847 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2849 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2850 EVT MemVT = LN0->getMemoryVT();
2851 // If we zero all the possible extended bits, then we can turn this into
2852 // a zextload if we are running before legalize or the operation is legal.
2853 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2854 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2855 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2856 ((!LegalOperations && !LN0->isVolatile()) ||
2857 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2858 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2859 LN0->getChain(), LN0->getBasePtr(),
2860 MemVT, LN0->getMemOperand());
2862 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2863 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2867 // fold (and (load x), 255) -> (zextload x, i8)
2868 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2869 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2870 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2871 (N0.getOpcode() == ISD::ANY_EXTEND &&
2872 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2873 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2874 LoadSDNode *LN0 = HasAnyExt
2875 ? cast<LoadSDNode>(N0.getOperand(0))
2876 : cast<LoadSDNode>(N0);
2877 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2878 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2879 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2880 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2881 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2882 EVT LoadedVT = LN0->getMemoryVT();
2884 if (ExtVT == LoadedVT &&
2885 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2886 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2889 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2890 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2891 LN0->getMemOperand());
2893 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2894 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2897 // Do not change the width of a volatile load.
2898 // Do not generate loads of non-round integer types since these can
2899 // be expensive (and would be wrong if the type is not byte sized).
2900 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2901 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2902 EVT PtrType = LN0->getOperand(1).getValueType();
2904 unsigned Alignment = LN0->getAlignment();
2905 SDValue NewPtr = LN0->getBasePtr();
2907 // For big endian targets, we need to add an offset to the pointer
2908 // to load the correct bytes. For little endian systems, we merely
2909 // need to read fewer bytes from the same pointer.
2910 if (TLI.isBigEndian()) {
2911 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2912 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2913 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2914 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2915 NewPtr, DAG.getConstant(PtrOff, PtrType));
2916 Alignment = MinAlign(Alignment, PtrOff);
2919 AddToWorkList(NewPtr.getNode());
2921 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2923 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2924 LN0->getChain(), NewPtr,
2925 LN0->getPointerInfo(),
2926 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2927 Alignment, LN0->getTBAAInfo());
2929 CombineTo(LN0, Load, Load.getValue(1));
2930 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2936 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2937 VT.getSizeInBits() <= 64) {
2938 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2939 APInt ADDC = ADDI->getAPIntValue();
2940 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2941 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2942 // immediate for an add, but it is legal if its top c2 bits are set,
2943 // transform the ADD so the immediate doesn't need to be materialized
2945 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2946 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2947 SRLI->getZExtValue());
2948 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2950 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2952 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2953 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2954 CombineTo(N0.getNode(), NewAdd);
2955 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2963 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2964 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2965 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2966 N0.getOperand(1), false);
2967 if (BSwap.getNode())
2974 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2976 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2977 bool DemandHighBits) {
2978 if (!LegalOperations)
2981 EVT VT = N->getValueType(0);
2982 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2984 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2987 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2988 bool LookPassAnd0 = false;
2989 bool LookPassAnd1 = false;
2990 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2992 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2994 if (N0.getOpcode() == ISD::AND) {
2995 if (!N0.getNode()->hasOneUse())
2997 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2998 if (!N01C || N01C->getZExtValue() != 0xFF00)
3000 N0 = N0.getOperand(0);
3001 LookPassAnd0 = true;
3004 if (N1.getOpcode() == ISD::AND) {
3005 if (!N1.getNode()->hasOneUse())
3007 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3008 if (!N11C || N11C->getZExtValue() != 0xFF)
3010 N1 = N1.getOperand(0);
3011 LookPassAnd1 = true;
3014 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3016 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3018 if (!N0.getNode()->hasOneUse() ||
3019 !N1.getNode()->hasOneUse())
3022 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3023 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3026 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3029 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3030 SDValue N00 = N0->getOperand(0);
3031 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3032 if (!N00.getNode()->hasOneUse())
3034 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3035 if (!N001C || N001C->getZExtValue() != 0xFF)
3037 N00 = N00.getOperand(0);
3038 LookPassAnd0 = true;
3041 SDValue N10 = N1->getOperand(0);
3042 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3043 if (!N10.getNode()->hasOneUse())
3045 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3046 if (!N101C || N101C->getZExtValue() != 0xFF00)
3048 N10 = N10.getOperand(0);
3049 LookPassAnd1 = true;
3055 // Make sure everything beyond the low halfword gets set to zero since the SRL
3056 // 16 will clear the top bits.
3057 unsigned OpSizeInBits = VT.getSizeInBits();
3058 if (DemandHighBits && OpSizeInBits > 16) {
3059 // If the left-shift isn't masked out then the only way this is a bswap is
3060 // if all bits beyond the low 8 are 0. In that case the entire pattern
3061 // reduces to a left shift anyway: leave it for other parts of the combiner.
3065 // However, if the right shift isn't masked out then it might be because
3066 // it's not needed. See if we can spot that too.
3067 if (!LookPassAnd1 &&
3068 !DAG.MaskedValueIsZero(
3069 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3073 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3074 if (OpSizeInBits > 16)
3075 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3076 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3080 /// isBSwapHWordElement - Return true if the specified node is an element
3081 /// that makes up a 32-bit packed halfword byteswap. i.e.
3082 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3083 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3084 if (!N.getNode()->hasOneUse())
3087 unsigned Opc = N.getOpcode();
3088 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3091 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3096 switch (N1C->getZExtValue()) {
3099 case 0xFF: Num = 0; break;
3100 case 0xFF00: Num = 1; break;
3101 case 0xFF0000: Num = 2; break;
3102 case 0xFF000000: Num = 3; break;
3105 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3106 SDValue N0 = N.getOperand(0);
3107 if (Opc == ISD::AND) {
3108 if (Num == 0 || Num == 2) {
3110 // (x >> 8) & 0xff0000
3111 if (N0.getOpcode() != ISD::SRL)
3113 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3114 if (!C || C->getZExtValue() != 8)
3117 // (x << 8) & 0xff00
3118 // (x << 8) & 0xff000000
3119 if (N0.getOpcode() != ISD::SHL)
3121 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3122 if (!C || C->getZExtValue() != 8)
3125 } else if (Opc == ISD::SHL) {
3127 // (x & 0xff0000) << 8
3128 if (Num != 0 && Num != 2)
3130 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3131 if (!C || C->getZExtValue() != 8)
3133 } else { // Opc == ISD::SRL
3134 // (x & 0xff00) >> 8
3135 // (x & 0xff000000) >> 8
3136 if (Num != 1 && Num != 3)
3138 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3139 if (!C || C->getZExtValue() != 8)
3146 Parts[Num] = N0.getOperand(0).getNode();
3150 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3151 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3152 /// => (rotl (bswap x), 16)
3153 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3154 if (!LegalOperations)
3157 EVT VT = N->getValueType(0);
3160 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3163 SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3165 // (or (or (and), (and)), (or (and), (and)))
3166 // (or (or (or (and), (and)), (and)), (and))
3167 if (N0.getOpcode() != ISD::OR)
3169 SDValue N00 = N0.getOperand(0);
3170 SDValue N01 = N0.getOperand(1);
3172 if (N1.getOpcode() == ISD::OR &&
3173 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3174 // (or (or (and), (and)), (or (and), (and)))
3175 SDValue N000 = N00.getOperand(0);
3176 if (!isBSwapHWordElement(N000, Parts))
3179 SDValue N001 = N00.getOperand(1);
3180 if (!isBSwapHWordElement(N001, Parts))
3182 SDValue N010 = N01.getOperand(0);
3183 if (!isBSwapHWordElement(N010, Parts))
3185 SDValue N011 = N01.getOperand(1);
3186 if (!isBSwapHWordElement(N011, Parts))
3189 // (or (or (or (and), (and)), (and)), (and))
3190 if (!isBSwapHWordElement(N1, Parts))
3192 if (!isBSwapHWordElement(N01, Parts))
3194 if (N00.getOpcode() != ISD::OR)
3196 SDValue N000 = N00.getOperand(0);
3197 if (!isBSwapHWordElement(N000, Parts))
3199 SDValue N001 = N00.getOperand(1);
3200 if (!isBSwapHWordElement(N001, Parts))
3204 // Make sure the parts are all coming from the same node.
3205 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3208 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3209 SDValue(Parts[0],0));
3211 // Result of the bswap should be rotated by 16. If it's not legal, then
3212 // do (x << 16) | (x >> 16).
3213 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3214 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3215 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3216 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3217 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3218 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3219 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3220 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3223 SDValue DAGCombiner::visitOR(SDNode *N) {
3224 SDValue N0 = N->getOperand(0);
3225 SDValue N1 = N->getOperand(1);
3226 SDValue LL, LR, RL, RR, CC0, CC1;
3227 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3228 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3229 EVT VT = N1.getValueType();
3232 if (VT.isVector()) {
3233 SDValue FoldedVOp = SimplifyVBinOp(N);
3234 if (FoldedVOp.getNode()) return FoldedVOp;
3236 // fold (or x, 0) -> x, vector edition
3237 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3239 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3242 // fold (or x, -1) -> -1, vector edition
3243 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3245 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3248 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3249 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3250 // Do this only if the resulting shuffle is legal.
3251 if (isa<ShuffleVectorSDNode>(N0) &&
3252 isa<ShuffleVectorSDNode>(N1) &&
3253 N0->getOperand(1) == N1->getOperand(1) &&
3254 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3255 bool CanFold = true;
3256 unsigned NumElts = VT.getVectorNumElements();
3257 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3258 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3259 // We construct two shuffle masks:
3260 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3261 // and N1 as the second operand.
3262 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3263 // and N0 as the second operand.
3264 // We do this because OR is commutable and therefore there might be
3265 // two ways to fold this node into a shuffle.
3266 SmallVector<int,4> Mask1;
3267 SmallVector<int,4> Mask2;
3269 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3270 int M0 = SV0->getMaskElt(i);
3271 int M1 = SV1->getMaskElt(i);
3273 // Both shuffle indexes are undef. Propagate Undef.
3274 if (M0 < 0 && M1 < 0) {
3275 Mask1.push_back(M0);
3276 Mask2.push_back(M0);
3280 if (M0 < 0 || M1 < 0 ||
3281 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3282 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3287 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3288 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3292 // Fold this sequence only if the resulting shuffle is 'legal'.
3293 if (TLI.isShuffleMaskLegal(Mask1, VT))
3294 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3295 N1->getOperand(0), &Mask1[0]);
3296 if (TLI.isShuffleMaskLegal(Mask2, VT))
3297 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3298 N0->getOperand(0), &Mask2[0]);
3303 // fold (or x, undef) -> -1
3304 if (!LegalOperations &&
3305 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3306 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3307 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3309 // fold (or c1, c2) -> c1|c2
3311 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3312 // canonicalize constant to RHS
3314 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3315 // fold (or x, 0) -> x
3316 if (N1C && N1C->isNullValue())
3318 // fold (or x, -1) -> -1
3319 if (N1C && N1C->isAllOnesValue())
3321 // fold (or x, c) -> c iff (x & ~c) == 0
3322 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3325 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3326 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3327 if (BSwap.getNode())
3329 BSwap = MatchBSwapHWordLow(N, N0, N1);
3330 if (BSwap.getNode())
3334 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3337 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3338 // iff (c1 & c2) == 0.
3339 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3340 isa<ConstantSDNode>(N0.getOperand(1))) {
3341 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3342 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3343 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3346 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3347 DAG.getNode(ISD::OR, SDLoc(N0), VT,
3348 N0.getOperand(0), N1), COR);
3351 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3352 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3353 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3354 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3356 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3357 LL.getValueType().isInteger()) {
3358 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3359 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3360 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3361 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3362 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3363 LR.getValueType(), LL, RL);
3364 AddToWorkList(ORNode.getNode());
3365 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3367 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3368 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3369 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3370 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3371 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3372 LR.getValueType(), LL, RL);
3373 AddToWorkList(ANDNode.getNode());
3374 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3377 // canonicalize equivalent to ll == rl
3378 if (LL == RR && LR == RL) {
3379 Op1 = ISD::getSetCCSwappedOperands(Op1);
3382 if (LL == RL && LR == RR) {
3383 bool isInteger = LL.getValueType().isInteger();
3384 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3385 if (Result != ISD::SETCC_INVALID &&
3386 (!LegalOperations ||
3387 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3388 TLI.isOperationLegal(ISD::SETCC,
3389 getSetCCResultType(N0.getValueType())))))
3390 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3395 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3396 if (N0.getOpcode() == N1.getOpcode()) {
3397 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3398 if (Tmp.getNode()) return Tmp;
3401 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3402 if (N0.getOpcode() == ISD::AND &&
3403 N1.getOpcode() == ISD::AND &&
3404 N0.getOperand(1).getOpcode() == ISD::Constant &&
3405 N1.getOperand(1).getOpcode() == ISD::Constant &&
3406 // Don't increase # computations.
3407 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3408 // We can only do this xform if we know that bits from X that are set in C2
3409 // but not in C1 are already zero. Likewise for Y.
3410 const APInt &LHSMask =
3411 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3412 const APInt &RHSMask =
3413 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3415 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3416 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3417 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3418 N0.getOperand(0), N1.getOperand(0));
3419 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3420 DAG.getConstant(LHSMask | RHSMask, VT));
3424 // See if this is some rotate idiom.
3425 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3426 return SDValue(Rot, 0);
3428 // Simplify the operands using demanded-bits information.
3429 if (!VT.isVector() &&
3430 SimplifyDemandedBits(SDValue(N, 0)))
3431 return SDValue(N, 0);
3436 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3437 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3438 if (Op.getOpcode() == ISD::AND) {
3439 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3440 Mask = Op.getOperand(1);
3441 Op = Op.getOperand(0);
3447 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3455 // Return true if we can prove that, whenever Neg and Pos are both in the
3456 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3457 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3459 // (or (shift1 X, Neg), (shift2 X, Pos))
3461 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3462 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3463 // to consider shift amounts with defined behavior.
3464 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3465 // If OpSize is a power of 2 then:
3467 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3468 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3470 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3471 // for the stronger condition:
3473 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3475 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3476 // we can just replace Neg with Neg' for the rest of the function.
3478 // In other cases we check for the even stronger condition:
3480 // Neg == OpSize - Pos [B]
3482 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3483 // behavior if Pos == 0 (and consequently Neg == OpSize).
3485 // We could actually use [A] whenever OpSize is a power of 2, but the
3486 // only extra cases that it would match are those uninteresting ones
3487 // where Neg and Pos are never in range at the same time. E.g. for
3488 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3489 // as well as (sub 32, Pos), but:
3491 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3493 // always invokes undefined behavior for 32-bit X.
3495 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3496 unsigned MaskLoBits = 0;
3497 if (Neg.getOpcode() == ISD::AND &&
3498 isPowerOf2_64(OpSize) &&
3499 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3500 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3501 Neg = Neg.getOperand(0);
3502 MaskLoBits = Log2_64(OpSize);
3505 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3506 if (Neg.getOpcode() != ISD::SUB)
3508 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3511 SDValue NegOp1 = Neg.getOperand(1);
3513 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3514 // Pos'. The truncation is redundant for the purpose of the equality.
3516 Pos.getOpcode() == ISD::AND &&
3517 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3518 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3519 Pos = Pos.getOperand(0);
3521 // The condition we need is now:
3523 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3525 // If NegOp1 == Pos then we need:
3527 // OpSize & Mask == NegC & Mask
3529 // (because "x & Mask" is a truncation and distributes through subtraction).
3532 Width = NegC->getAPIntValue();
3533 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3534 // Then the condition we want to prove becomes:
3536 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3538 // which, again because "x & Mask" is a truncation, becomes:
3540 // NegC & Mask == (OpSize - PosC) & Mask
3541 // OpSize & Mask == (NegC + PosC) & Mask
3542 else if (Pos.getOpcode() == ISD::ADD &&
3543 Pos.getOperand(0) == NegOp1 &&
3544 Pos.getOperand(1).getOpcode() == ISD::Constant)
3545 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3546 NegC->getAPIntValue());
3550 // Now we just need to check that OpSize & Mask == Width & Mask.
3552 // Opsize & Mask is 0 since Mask is Opsize - 1.
3553 return Width.getLoBits(MaskLoBits) == 0;
3554 return Width == OpSize;
3557 // A subroutine of MatchRotate used once we have found an OR of two opposite
3558 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3559 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3560 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3561 // Neg with outer conversions stripped away.
3562 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3563 SDValue Neg, SDValue InnerPos,
3564 SDValue InnerNeg, unsigned PosOpcode,
3565 unsigned NegOpcode, SDLoc DL) {
3566 // fold (or (shl x, (*ext y)),
3567 // (srl x, (*ext (sub 32, y)))) ->
3568 // (rotl x, y) or (rotr x, (sub 32, y))
3570 // fold (or (shl x, (*ext (sub 32, y))),
3571 // (srl x, (*ext y))) ->
3572 // (rotr x, y) or (rotl x, (sub 32, y))
3573 EVT VT = Shifted.getValueType();
3574 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3575 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3576 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3577 HasPos ? Pos : Neg).getNode();
3583 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3584 // idioms for rotate, and if the target supports rotation instructions, generate
3586 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3587 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3588 EVT VT = LHS.getValueType();
3589 if (!TLI.isTypeLegal(VT)) return nullptr;
3591 // The target must have at least one rotate flavor.
3592 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3593 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3594 if (!HasROTL && !HasROTR) return nullptr;
3596 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3597 SDValue LHSShift; // The shift.
3598 SDValue LHSMask; // AND value if any.
3599 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3600 return nullptr; // Not part of a rotate.
3602 SDValue RHSShift; // The shift.
3603 SDValue RHSMask; // AND value if any.
3604 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3605 return nullptr; // Not part of a rotate.
3607 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3608 return nullptr; // Not shifting the same value.
3610 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3611 return nullptr; // Shifts must disagree.
3613 // Canonicalize shl to left side in a shl/srl pair.
3614 if (RHSShift.getOpcode() == ISD::SHL) {
3615 std::swap(LHS, RHS);
3616 std::swap(LHSShift, RHSShift);
3617 std::swap(LHSMask , RHSMask );
3620 unsigned OpSizeInBits = VT.getSizeInBits();
3621 SDValue LHSShiftArg = LHSShift.getOperand(0);
3622 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3623 SDValue RHSShiftArg = RHSShift.getOperand(0);
3624 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3626 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3627 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3628 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3629 RHSShiftAmt.getOpcode() == ISD::Constant) {
3630 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3631 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3632 if ((LShVal + RShVal) != OpSizeInBits)
3635 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3636 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3638 // If there is an AND of either shifted operand, apply it to the result.
3639 if (LHSMask.getNode() || RHSMask.getNode()) {
3640 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3642 if (LHSMask.getNode()) {
3643 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3644 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3646 if (RHSMask.getNode()) {
3647 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3648 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3651 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3654 return Rot.getNode();
3657 // If there is a mask here, and we have a variable shift, we can't be sure
3658 // that we're masking out the right stuff.
3659 if (LHSMask.getNode() || RHSMask.getNode())
3662 // If the shift amount is sign/zext/any-extended just peel it off.
3663 SDValue LExtOp0 = LHSShiftAmt;
3664 SDValue RExtOp0 = RHSShiftAmt;
3665 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3666 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3667 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3668 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3669 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3670 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3671 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3672 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3673 LExtOp0 = LHSShiftAmt.getOperand(0);
3674 RExtOp0 = RHSShiftAmt.getOperand(0);
3677 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3678 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3682 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3683 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3690 SDValue DAGCombiner::visitXOR(SDNode *N) {
3691 SDValue N0 = N->getOperand(0);
3692 SDValue N1 = N->getOperand(1);
3693 SDValue LHS, RHS, CC;
3694 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3695 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3696 EVT VT = N0.getValueType();
3699 if (VT.isVector()) {
3700 SDValue FoldedVOp = SimplifyVBinOp(N);
3701 if (FoldedVOp.getNode()) return FoldedVOp;
3703 // fold (xor x, 0) -> x, vector edition
3704 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3706 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3710 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3711 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3712 return DAG.getConstant(0, VT);
3713 // fold (xor x, undef) -> undef
3714 if (N0.getOpcode() == ISD::UNDEF)
3716 if (N1.getOpcode() == ISD::UNDEF)
3718 // fold (xor c1, c2) -> c1^c2
3720 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3721 // canonicalize constant to RHS
3723 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3724 // fold (xor x, 0) -> x
3725 if (N1C && N1C->isNullValue())
3728 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3732 // fold !(x cc y) -> (x !cc y)
3733 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3734 bool isInt = LHS.getValueType().isInteger();
3735 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3738 if (!LegalOperations ||
3739 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3740 switch (N0.getOpcode()) {
3742 llvm_unreachable("Unhandled SetCC Equivalent!");
3744 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3745 case ISD::SELECT_CC:
3746 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3747 N0.getOperand(3), NotCC);
3752 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3753 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3754 N0.getNode()->hasOneUse() &&
3755 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3756 SDValue V = N0.getOperand(0);
3757 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3758 DAG.getConstant(1, V.getValueType()));
3759 AddToWorkList(V.getNode());
3760 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3763 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3764 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3765 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3766 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3767 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3768 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3769 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3770 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3771 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3772 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3775 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3776 if (N1C && N1C->isAllOnesValue() &&
3777 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3778 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3779 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3780 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3781 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3782 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3783 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3784 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3787 // fold (xor (and x, y), y) -> (and (not x), y)
3788 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3789 N0->getOperand(1) == N1) {
3790 SDValue X = N0->getOperand(0);
3791 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3792 AddToWorkList(NotX.getNode());
3793 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3795 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3796 if (N1C && N0.getOpcode() == ISD::XOR) {
3797 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3798 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3800 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3801 DAG.getConstant(N1C->getAPIntValue() ^
3802 N00C->getAPIntValue(), VT));
3804 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3805 DAG.getConstant(N1C->getAPIntValue() ^
3806 N01C->getAPIntValue(), VT));
3808 // fold (xor x, x) -> 0
3810 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3812 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3813 if (N0.getOpcode() == N1.getOpcode()) {
3814 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3815 if (Tmp.getNode()) return Tmp;
3818 // Simplify the expression using non-local knowledge.
3819 if (!VT.isVector() &&
3820 SimplifyDemandedBits(SDValue(N, 0)))
3821 return SDValue(N, 0);
3826 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3827 /// the shift amount is a constant.
3828 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3829 // We can't and shouldn't fold opaque constants.
3830 if (Amt->isOpaque())
3833 SDNode *LHS = N->getOperand(0).getNode();
3834 if (!LHS->hasOneUse()) return SDValue();
3836 // We want to pull some binops through shifts, so that we have (and (shift))
3837 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3838 // thing happens with address calculations, so it's important to canonicalize
3840 bool HighBitSet = false; // Can we transform this if the high bit is set?
3842 switch (LHS->getOpcode()) {
3843 default: return SDValue();
3846 HighBitSet = false; // We can only transform sra if the high bit is clear.
3849 HighBitSet = true; // We can only transform sra if the high bit is set.
3852 if (N->getOpcode() != ISD::SHL)
3853 return SDValue(); // only shl(add) not sr[al](add).
3854 HighBitSet = false; // We can only transform sra if the high bit is clear.
3858 // We require the RHS of the binop to be a constant and not opaque as well.
3859 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3860 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3862 // FIXME: disable this unless the input to the binop is a shift by a constant.
3863 // If it is not a shift, it pessimizes some common cases like:
3865 // void foo(int *X, int i) { X[i & 1235] = 1; }
3866 // int bar(int *X, int i) { return X[i & 255]; }
3867 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3868 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3869 BinOpLHSVal->getOpcode() != ISD::SRA &&
3870 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3871 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3874 EVT VT = N->getValueType(0);
3876 // If this is a signed shift right, and the high bit is modified by the
3877 // logical operation, do not perform the transformation. The highBitSet
3878 // boolean indicates the value of the high bit of the constant which would
3879 // cause it to be modified for this operation.
3880 if (N->getOpcode() == ISD::SRA) {
3881 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3882 if (BinOpRHSSignSet != HighBitSet)
3886 if (!TLI.isDesirableToCommuteWithShift(LHS))
3889 // Fold the constants, shifting the binop RHS by the shift amount.
3890 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3892 LHS->getOperand(1), N->getOperand(1));
3893 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3895 // Create the new shift.
3896 SDValue NewShift = DAG.getNode(N->getOpcode(),
3897 SDLoc(LHS->getOperand(0)),
3898 VT, LHS->getOperand(0), N->getOperand(1));
3900 // Create the new binop.
3901 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3904 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3905 assert(N->getOpcode() == ISD::TRUNCATE);
3906 assert(N->getOperand(0).getOpcode() == ISD::AND);
3908 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3909 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3910 SDValue N01 = N->getOperand(0).getOperand(1);
3912 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3913 EVT TruncVT = N->getValueType(0);
3914 SDValue N00 = N->getOperand(0).getOperand(0);
3915 APInt TruncC = N01C->getAPIntValue();
3916 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3918 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3919 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3920 DAG.getConstant(TruncC, TruncVT));
3927 SDValue DAGCombiner::visitRotate(SDNode *N) {
3928 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3929 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3930 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3931 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3932 if (NewOp1.getNode())
3933 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3934 N->getOperand(0), NewOp1);
3939 SDValue DAGCombiner::visitSHL(SDNode *N) {
3940 SDValue N0 = N->getOperand(0);
3941 SDValue N1 = N->getOperand(1);
3942 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3943 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3944 EVT VT = N0.getValueType();
3945 unsigned OpSizeInBits = VT.getScalarSizeInBits();
3948 if (VT.isVector()) {
3949 SDValue FoldedVOp = SimplifyVBinOp(N);
3950 if (FoldedVOp.getNode()) return FoldedVOp;
3952 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3953 // If setcc produces all-one true value then:
3954 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
3955 if (N1CV && N1CV->isConstant()) {
3956 if (N0.getOpcode() == ISD::AND &&
3957 TLI.getBooleanContents(true) ==
3958 TargetLowering::ZeroOrNegativeOneBooleanContent) {
3959 SDValue N00 = N0->getOperand(0);
3960 SDValue N01 = N0->getOperand(1);
3961 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
3963 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC) {
3964 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3966 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3969 N1C = isConstOrConstSplat(N1);
3974 // fold (shl c1, c2) -> c1<<c2
3976 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3977 // fold (shl 0, x) -> 0
3978 if (N0C && N0C->isNullValue())
3980 // fold (shl x, c >= size(x)) -> undef
3981 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3982 return DAG.getUNDEF(VT);
3983 // fold (shl x, 0) -> x
3984 if (N1C && N1C->isNullValue())
3986 // fold (shl undef, x) -> 0
3987 if (N0.getOpcode() == ISD::UNDEF)
3988 return DAG.getConstant(0, VT);
3989 // if (shl x, c) is known to be zero, return 0
3990 if (DAG.MaskedValueIsZero(SDValue(N, 0),
3991 APInt::getAllOnesValue(OpSizeInBits)))
3992 return DAG.getConstant(0, VT);
3993 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3994 if (N1.getOpcode() == ISD::TRUNCATE &&
3995 N1.getOperand(0).getOpcode() == ISD::AND) {
3996 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
3997 if (NewOp1.getNode())
3998 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4001 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4002 return SDValue(N, 0);
4004 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4005 if (N1C && N0.getOpcode() == ISD::SHL) {
4006 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4007 uint64_t c1 = N0C1->getZExtValue();
4008 uint64_t c2 = N1C->getZExtValue();
4009 if (c1 + c2 >= OpSizeInBits)
4010 return DAG.getConstant(0, VT);
4011 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4012 DAG.getConstant(c1 + c2, N1.getValueType()));
4016 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4017 // For this to be valid, the second form must not preserve any of the bits
4018 // that are shifted out by the inner shift in the first form. This means
4019 // the outer shift size must be >= the number of bits added by the ext.
4020 // As a corollary, we don't care what kind of ext it is.
4021 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4022 N0.getOpcode() == ISD::ANY_EXTEND ||
4023 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4024 N0.getOperand(0).getOpcode() == ISD::SHL) {
4025 SDValue N0Op0 = N0.getOperand(0);
4026 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4027 uint64_t c1 = N0Op0C1->getZExtValue();
4028 uint64_t c2 = N1C->getZExtValue();
4029 EVT InnerShiftVT = N0Op0.getValueType();
4030 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4031 if (c2 >= OpSizeInBits - InnerShiftSize) {
4032 if (c1 + c2 >= OpSizeInBits)
4033 return DAG.getConstant(0, VT);
4034 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4035 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4036 N0Op0->getOperand(0)),
4037 DAG.getConstant(c1 + c2, N1.getValueType()));
4042 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4043 // Only fold this if the inner zext has no other uses to avoid increasing
4044 // the total number of instructions.
4045 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4046 N0.getOperand(0).getOpcode() == ISD::SRL) {
4047 SDValue N0Op0 = N0.getOperand(0);
4048 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4049 uint64_t c1 = N0Op0C1->getZExtValue();
4050 if (c1 < VT.getScalarSizeInBits()) {
4051 uint64_t c2 = N1C->getZExtValue();
4053 SDValue NewOp0 = N0.getOperand(0);
4054 EVT CountVT = NewOp0.getOperand(1).getValueType();
4055 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4056 NewOp0, DAG.getConstant(c2, CountVT));
4057 AddToWorkList(NewSHL.getNode());
4058 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4064 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4065 // (and (srl x, (sub c1, c2), MASK)
4066 // Only fold this if the inner shift has no other uses -- if it does, folding
4067 // this will increase the total number of instructions.
4068 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4069 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4070 uint64_t c1 = N0C1->getZExtValue();
4071 if (c1 < OpSizeInBits) {
4072 uint64_t c2 = N1C->getZExtValue();
4073 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4076 Mask = Mask.shl(c2 - c1);
4077 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4078 DAG.getConstant(c2 - c1, N1.getValueType()));
4080 Mask = Mask.lshr(c1 - c2);
4081 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4082 DAG.getConstant(c1 - c2, N1.getValueType()));
4084 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4085 DAG.getConstant(Mask, VT));
4089 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4090 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4091 unsigned BitSize = VT.getScalarSizeInBits();
4092 SDValue HiBitsMask =
4093 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4094 BitSize - N1C->getZExtValue()), VT);
4095 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4100 SDValue NewSHL = visitShiftByConstant(N, N1C);
4101 if (NewSHL.getNode())
4108 SDValue DAGCombiner::visitSRA(SDNode *N) {
4109 SDValue N0 = N->getOperand(0);
4110 SDValue N1 = N->getOperand(1);
4111 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4112 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4113 EVT VT = N0.getValueType();
4114 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4117 if (VT.isVector()) {
4118 SDValue FoldedVOp = SimplifyVBinOp(N);
4119 if (FoldedVOp.getNode()) return FoldedVOp;
4121 N1C = isConstOrConstSplat(N1);
4124 // fold (sra c1, c2) -> (sra c1, c2)
4126 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4127 // fold (sra 0, x) -> 0
4128 if (N0C && N0C->isNullValue())
4130 // fold (sra -1, x) -> -1
4131 if (N0C && N0C->isAllOnesValue())
4133 // fold (sra x, (setge c, size(x))) -> undef
4134 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4135 return DAG.getUNDEF(VT);
4136 // fold (sra x, 0) -> x
4137 if (N1C && N1C->isNullValue())
4139 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4141 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4142 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4143 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4145 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4146 ExtVT, VT.getVectorNumElements());
4147 if ((!LegalOperations ||
4148 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4149 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4150 N0.getOperand(0), DAG.getValueType(ExtVT));
4153 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4154 if (N1C && N0.getOpcode() == ISD::SRA) {
4155 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4156 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4157 if (Sum >= OpSizeInBits)
4158 Sum = OpSizeInBits - 1;
4159 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4160 DAG.getConstant(Sum, N1.getValueType()));
4164 // fold (sra (shl X, m), (sub result_size, n))
4165 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4166 // result_size - n != m.
4167 // If truncate is free for the target sext(shl) is likely to result in better
4169 if (N0.getOpcode() == ISD::SHL && N1C) {
4170 // Get the two constanst of the shifts, CN0 = m, CN = n.
4171 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4173 LLVMContext &Ctx = *DAG.getContext();
4174 // Determine what the truncate's result bitsize and type would be.
4175 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4178 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4180 // Determine the residual right-shift amount.
4181 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4183 // If the shift is not a no-op (in which case this should be just a sign
4184 // extend already), the truncated to type is legal, sign_extend is legal
4185 // on that type, and the truncate to that type is both legal and free,
4186 // perform the transform.
4187 if ((ShiftAmt > 0) &&
4188 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4189 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4190 TLI.isTruncateFree(VT, TruncVT)) {
4192 SDValue Amt = DAG.getConstant(ShiftAmt,
4193 getShiftAmountTy(N0.getOperand(0).getValueType()));
4194 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4195 N0.getOperand(0), Amt);
4196 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4198 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4199 N->getValueType(0), Trunc);
4204 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4205 if (N1.getOpcode() == ISD::TRUNCATE &&
4206 N1.getOperand(0).getOpcode() == ISD::AND) {
4207 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4208 if (NewOp1.getNode())
4209 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4212 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4213 // if c1 is equal to the number of bits the trunc removes
4214 if (N0.getOpcode() == ISD::TRUNCATE &&
4215 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4216 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4217 N0.getOperand(0).hasOneUse() &&
4218 N0.getOperand(0).getOperand(1).hasOneUse() &&
4220 SDValue N0Op0 = N0.getOperand(0);
4221 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4222 unsigned LargeShiftVal = LargeShift->getZExtValue();
4223 EVT LargeVT = N0Op0.getValueType();
4225 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4227 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4228 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4229 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4230 N0Op0.getOperand(0), Amt);
4231 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4236 // Simplify, based on bits shifted out of the LHS.
4237 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4238 return SDValue(N, 0);
4241 // If the sign bit is known to be zero, switch this to a SRL.
4242 if (DAG.SignBitIsZero(N0))
4243 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4246 SDValue NewSRA = visitShiftByConstant(N, N1C);
4247 if (NewSRA.getNode())
4254 SDValue DAGCombiner::visitSRL(SDNode *N) {
4255 SDValue N0 = N->getOperand(0);
4256 SDValue N1 = N->getOperand(1);
4257 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4258 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4259 EVT VT = N0.getValueType();
4260 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4263 if (VT.isVector()) {
4264 SDValue FoldedVOp = SimplifyVBinOp(N);
4265 if (FoldedVOp.getNode()) return FoldedVOp;
4267 N1C = isConstOrConstSplat(N1);
4270 // fold (srl c1, c2) -> c1 >>u c2
4272 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4273 // fold (srl 0, x) -> 0
4274 if (N0C && N0C->isNullValue())
4276 // fold (srl x, c >= size(x)) -> undef
4277 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4278 return DAG.getUNDEF(VT);
4279 // fold (srl x, 0) -> x
4280 if (N1C && N1C->isNullValue())
4282 // if (srl x, c) is known to be zero, return 0
4283 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4284 APInt::getAllOnesValue(OpSizeInBits)))
4285 return DAG.getConstant(0, VT);
4287 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4288 if (N1C && N0.getOpcode() == ISD::SRL) {
4289 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4290 uint64_t c1 = N01C->getZExtValue();
4291 uint64_t c2 = N1C->getZExtValue();
4292 if (c1 + c2 >= OpSizeInBits)
4293 return DAG.getConstant(0, VT);
4294 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4295 DAG.getConstant(c1 + c2, N1.getValueType()));
4299 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4300 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4301 N0.getOperand(0).getOpcode() == ISD::SRL &&
4302 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4304 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4305 uint64_t c2 = N1C->getZExtValue();
4306 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4307 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4308 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4309 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4310 if (c1 + OpSizeInBits == InnerShiftSize) {
4311 if (c1 + c2 >= InnerShiftSize)
4312 return DAG.getConstant(0, VT);
4313 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4314 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4315 N0.getOperand(0)->getOperand(0),
4316 DAG.getConstant(c1 + c2, ShiftCountVT)));
4320 // fold (srl (shl x, c), c) -> (and x, cst2)
4321 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4322 unsigned BitSize = N0.getScalarValueSizeInBits();
4323 if (BitSize <= 64) {
4324 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4325 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4326 DAG.getConstant(~0ULL >> ShAmt, VT));
4330 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4331 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4332 // Shifting in all undef bits?
4333 EVT SmallVT = N0.getOperand(0).getValueType();
4334 unsigned BitSize = SmallVT.getScalarSizeInBits();
4335 if (N1C->getZExtValue() >= BitSize)
4336 return DAG.getUNDEF(VT);
4338 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4339 uint64_t ShiftAmt = N1C->getZExtValue();
4340 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4342 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4343 AddToWorkList(SmallShift.getNode());
4344 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4345 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4346 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4347 DAG.getConstant(Mask, VT));
4351 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4352 // bit, which is unmodified by sra.
4353 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4354 if (N0.getOpcode() == ISD::SRA)
4355 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4358 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4359 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4360 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4361 APInt KnownZero, KnownOne;
4362 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4364 // If any of the input bits are KnownOne, then the input couldn't be all
4365 // zeros, thus the result of the srl will always be zero.
4366 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4368 // If all of the bits input the to ctlz node are known to be zero, then
4369 // the result of the ctlz is "32" and the result of the shift is one.
4370 APInt UnknownBits = ~KnownZero;
4371 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4373 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4374 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4375 // Okay, we know that only that the single bit specified by UnknownBits
4376 // could be set on input to the CTLZ node. If this bit is set, the SRL
4377 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4378 // to an SRL/XOR pair, which is likely to simplify more.
4379 unsigned ShAmt = UnknownBits.countTrailingZeros();
4380 SDValue Op = N0.getOperand(0);
4383 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4384 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4385 AddToWorkList(Op.getNode());
4388 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4389 Op, DAG.getConstant(1, VT));
4393 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4394 if (N1.getOpcode() == ISD::TRUNCATE &&
4395 N1.getOperand(0).getOpcode() == ISD::AND) {
4396 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4397 if (NewOp1.getNode())
4398 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4401 // fold operands of srl based on knowledge that the low bits are not
4403 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4404 return SDValue(N, 0);
4407 SDValue NewSRL = visitShiftByConstant(N, N1C);
4408 if (NewSRL.getNode())
4412 // Attempt to convert a srl of a load into a narrower zero-extending load.
4413 SDValue NarrowLoad = ReduceLoadWidth(N);
4414 if (NarrowLoad.getNode())
4417 // Here is a common situation. We want to optimize:
4420 // %b = and i32 %a, 2
4421 // %c = srl i32 %b, 1
4422 // brcond i32 %c ...
4428 // %c = setcc eq %b, 0
4431 // However when after the source operand of SRL is optimized into AND, the SRL
4432 // itself may not be optimized further. Look for it and add the BRCOND into
4434 if (N->hasOneUse()) {
4435 SDNode *Use = *N->use_begin();
4436 if (Use->getOpcode() == ISD::BRCOND)
4438 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4439 // Also look pass the truncate.
4440 Use = *Use->use_begin();
4441 if (Use->getOpcode() == ISD::BRCOND)
4449 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4450 SDValue N0 = N->getOperand(0);
4451 EVT VT = N->getValueType(0);
4453 // fold (ctlz c1) -> c2
4454 if (isa<ConstantSDNode>(N0))
4455 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4459 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4460 SDValue N0 = N->getOperand(0);
4461 EVT VT = N->getValueType(0);
4463 // fold (ctlz_zero_undef c1) -> c2
4464 if (isa<ConstantSDNode>(N0))
4465 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4469 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4470 SDValue N0 = N->getOperand(0);
4471 EVT VT = N->getValueType(0);
4473 // fold (cttz c1) -> c2
4474 if (isa<ConstantSDNode>(N0))
4475 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4479 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4480 SDValue N0 = N->getOperand(0);
4481 EVT VT = N->getValueType(0);
4483 // fold (cttz_zero_undef c1) -> c2
4484 if (isa<ConstantSDNode>(N0))
4485 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4489 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4490 SDValue N0 = N->getOperand(0);
4491 EVT VT = N->getValueType(0);
4493 // fold (ctpop c1) -> c2
4494 if (isa<ConstantSDNode>(N0))
4495 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4499 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4500 SDValue N0 = N->getOperand(0);
4501 SDValue N1 = N->getOperand(1);
4502 SDValue N2 = N->getOperand(2);
4503 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4504 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4505 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4506 EVT VT = N->getValueType(0);
4507 EVT VT0 = N0.getValueType();
4509 // fold (select C, X, X) -> X
4512 // fold (select true, X, Y) -> X
4513 if (N0C && !N0C->isNullValue())
4515 // fold (select false, X, Y) -> Y
4516 if (N0C && N0C->isNullValue())
4518 // fold (select C, 1, X) -> (or C, X)
4519 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4520 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4521 // fold (select C, 0, 1) -> (xor C, 1)
4522 if (VT.isInteger() &&
4525 TLI.getBooleanContents(false) ==
4526 TargetLowering::ZeroOrOneBooleanContent)) &&
4527 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4530 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4531 N0, DAG.getConstant(1, VT0));
4532 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4533 N0, DAG.getConstant(1, VT0));
4534 AddToWorkList(XORNode.getNode());
4536 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4537 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4539 // fold (select C, 0, X) -> (and (not C), X)
4540 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4541 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4542 AddToWorkList(NOTNode.getNode());
4543 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4545 // fold (select C, X, 1) -> (or (not C), X)
4546 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4547 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4548 AddToWorkList(NOTNode.getNode());
4549 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4551 // fold (select C, X, 0) -> (and C, X)
4552 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4553 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4554 // fold (select X, X, Y) -> (or X, Y)
4555 // fold (select X, 1, Y) -> (or X, Y)
4556 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4557 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4558 // fold (select X, Y, X) -> (and X, Y)
4559 // fold (select X, Y, 0) -> (and X, Y)
4560 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4561 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4563 // If we can fold this based on the true/false value, do so.
4564 if (SimplifySelectOps(N, N1, N2))
4565 return SDValue(N, 0); // Don't revisit N.
4567 // fold selects based on a setcc into other things, such as min/max/abs
4568 if (N0.getOpcode() == ISD::SETCC) {
4569 if ((!LegalOperations &&
4570 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4571 TLI.isOperationLegal(ISD::SELECT_CC, VT))
4572 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4573 N0.getOperand(0), N0.getOperand(1),
4574 N1, N2, N0.getOperand(2));
4575 return SimplifySelect(SDLoc(N), N0, N1, N2);
4582 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4585 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4587 // Split the inputs.
4588 SDValue Lo, Hi, LL, LH, RL, RH;
4589 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4590 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4592 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4593 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4595 return std::make_pair(Lo, Hi);
4598 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4599 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4600 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4602 SDValue Cond = N->getOperand(0);
4603 SDValue LHS = N->getOperand(1);
4604 SDValue RHS = N->getOperand(2);
4605 MVT VT = N->getSimpleValueType(0);
4606 int NumElems = VT.getVectorNumElements();
4607 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4608 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4609 Cond.getOpcode() == ISD::BUILD_VECTOR);
4611 // We're sure we have an even number of elements due to the
4612 // concat_vectors we have as arguments to vselect.
4613 // Skip BV elements until we find one that's not an UNDEF
4614 // After we find an UNDEF element, keep looping until we get to half the
4615 // length of the BV and see if all the non-undef nodes are the same.
4616 ConstantSDNode *BottomHalf = nullptr;
4617 for (int i = 0; i < NumElems / 2; ++i) {
4618 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4621 if (BottomHalf == nullptr)
4622 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4623 else if (Cond->getOperand(i).getNode() != BottomHalf)
4627 // Do the same for the second half of the BuildVector
4628 ConstantSDNode *TopHalf = nullptr;
4629 for (int i = NumElems / 2; i < NumElems; ++i) {
4630 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4633 if (TopHalf == nullptr)
4634 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4635 else if (Cond->getOperand(i).getNode() != TopHalf)
4639 assert(TopHalf && BottomHalf &&
4640 "One half of the selector was all UNDEFs and the other was all the "
4641 "same value. This should have been addressed before this function.");
4643 ISD::CONCAT_VECTORS, dl, VT,
4644 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4645 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4648 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4649 SDValue N0 = N->getOperand(0);
4650 SDValue N1 = N->getOperand(1);
4651 SDValue N2 = N->getOperand(2);
4654 // Canonicalize integer abs.
4655 // vselect (setg[te] X, 0), X, -X ->
4656 // vselect (setgt X, -1), X, -X ->
4657 // vselect (setl[te] X, 0), -X, X ->
4658 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4659 if (N0.getOpcode() == ISD::SETCC) {
4660 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4661 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4663 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4665 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4666 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4667 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4668 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4669 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4670 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4671 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4674 EVT VT = LHS.getValueType();
4675 SDValue Shift = DAG.getNode(
4676 ISD::SRA, DL, VT, LHS,
4677 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4678 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4679 AddToWorkList(Shift.getNode());
4680 AddToWorkList(Add.getNode());
4681 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4685 // If the VSELECT result requires splitting and the mask is provided by a
4686 // SETCC, then split both nodes and its operands before legalization. This
4687 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4688 // and enables future optimizations (e.g. min/max pattern matching on X86).
4689 if (N0.getOpcode() == ISD::SETCC) {
4690 EVT VT = N->getValueType(0);
4692 // Check if any splitting is required.
4693 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4694 TargetLowering::TypeSplitVector)
4697 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4698 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4699 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4700 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4702 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4703 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4705 // Add the new VSELECT nodes to the work list in case they need to be split
4707 AddToWorkList(Lo.getNode());
4708 AddToWorkList(Hi.getNode());
4710 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4713 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4714 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4716 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4717 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4720 // The ConvertSelectToConcatVector function is assuming both the above
4721 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4723 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4724 N2.getOpcode() == ISD::CONCAT_VECTORS &&
4725 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4726 SDValue CV = ConvertSelectToConcatVector(N, DAG);
4734 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4735 SDValue N0 = N->getOperand(0);
4736 SDValue N1 = N->getOperand(1);
4737 SDValue N2 = N->getOperand(2);
4738 SDValue N3 = N->getOperand(3);
4739 SDValue N4 = N->getOperand(4);
4740 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4742 // fold select_cc lhs, rhs, x, x, cc -> x
4746 // Determine if the condition we're dealing with is constant
4747 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4748 N0, N1, CC, SDLoc(N), false);
4749 if (SCC.getNode()) {
4750 AddToWorkList(SCC.getNode());
4752 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4753 if (!SCCC->isNullValue())
4754 return N2; // cond always true -> true val
4756 return N3; // cond always false -> false val
4759 // Fold to a simpler select_cc
4760 if (SCC.getOpcode() == ISD::SETCC)
4761 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4762 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4766 // If we can fold this based on the true/false value, do so.
4767 if (SimplifySelectOps(N, N2, N3))
4768 return SDValue(N, 0); // Don't revisit N.
4770 // fold select_cc into other things, such as min/max/abs
4771 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4774 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4775 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4776 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4780 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4781 // dag node into a ConstantSDNode or a build_vector of constants.
4782 // This function is called by the DAGCombiner when visiting sext/zext/aext
4783 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4784 // Vector extends are not folded if operations are legal; this is to
4785 // avoid introducing illegal build_vector dag nodes.
4786 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4787 SelectionDAG &DAG, bool LegalTypes,
4788 bool LegalOperations) {
4789 unsigned Opcode = N->getOpcode();
4790 SDValue N0 = N->getOperand(0);
4791 EVT VT = N->getValueType(0);
4793 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4794 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4796 // fold (sext c1) -> c1
4797 // fold (zext c1) -> c1
4798 // fold (aext c1) -> c1
4799 if (isa<ConstantSDNode>(N0))
4800 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4802 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4803 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4804 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4805 EVT SVT = VT.getScalarType();
4806 if (!(VT.isVector() &&
4807 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4808 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4811 // We can fold this node into a build_vector.
4812 unsigned VTBits = SVT.getSizeInBits();
4813 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4814 unsigned ShAmt = VTBits - EVTBits;
4815 SmallVector<SDValue, 8> Elts;
4816 unsigned NumElts = N0->getNumOperands();
4819 for (unsigned i=0; i != NumElts; ++i) {
4820 SDValue Op = N0->getOperand(i);
4821 if (Op->getOpcode() == ISD::UNDEF) {
4822 Elts.push_back(DAG.getUNDEF(SVT));
4826 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4827 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4828 if (Opcode == ISD::SIGN_EXTEND)
4829 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4832 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4836 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4839 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4840 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4841 // transformation. Returns true if extension are possible and the above
4842 // mentioned transformation is profitable.
4843 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4845 SmallVectorImpl<SDNode *> &ExtendNodes,
4846 const TargetLowering &TLI) {
4847 bool HasCopyToRegUses = false;
4848 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4849 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4850 UE = N0.getNode()->use_end();
4855 if (UI.getUse().getResNo() != N0.getResNo())
4857 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4858 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4859 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4860 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4861 // Sign bits will be lost after a zext.
4864 for (unsigned i = 0; i != 2; ++i) {
4865 SDValue UseOp = User->getOperand(i);
4868 if (!isa<ConstantSDNode>(UseOp))
4873 ExtendNodes.push_back(User);
4876 // If truncates aren't free and there are users we can't
4877 // extend, it isn't worthwhile.
4880 // Remember if this value is live-out.
4881 if (User->getOpcode() == ISD::CopyToReg)
4882 HasCopyToRegUses = true;
4885 if (HasCopyToRegUses) {
4886 bool BothLiveOut = false;
4887 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4889 SDUse &Use = UI.getUse();
4890 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4896 // Both unextended and extended values are live out. There had better be
4897 // a good reason for the transformation.
4898 return ExtendNodes.size();
4903 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4904 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4905 ISD::NodeType ExtType) {
4906 // Extend SetCC uses if necessary.
4907 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4908 SDNode *SetCC = SetCCs[i];
4909 SmallVector<SDValue, 4> Ops;
4911 for (unsigned j = 0; j != 2; ++j) {
4912 SDValue SOp = SetCC->getOperand(j);
4914 Ops.push_back(ExtLoad);
4916 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4919 Ops.push_back(SetCC->getOperand(2));
4920 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
4924 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4925 SDValue N0 = N->getOperand(0);
4926 EVT VT = N->getValueType(0);
4928 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4930 return SDValue(Res, 0);
4932 // fold (sext (sext x)) -> (sext x)
4933 // fold (sext (aext x)) -> (sext x)
4934 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4935 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4938 if (N0.getOpcode() == ISD::TRUNCATE) {
4939 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4940 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4941 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4942 if (NarrowLoad.getNode()) {
4943 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4944 if (NarrowLoad.getNode() != N0.getNode()) {
4945 CombineTo(N0.getNode(), NarrowLoad);
4946 // CombineTo deleted the truncate, if needed, but not what's under it.
4949 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4952 // See if the value being truncated is already sign extended. If so, just
4953 // eliminate the trunc/sext pair.
4954 SDValue Op = N0.getOperand(0);
4955 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4956 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4957 unsigned DestBits = VT.getScalarType().getSizeInBits();
4958 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4960 if (OpBits == DestBits) {
4961 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4962 // bits, it is already ready.
4963 if (NumSignBits > DestBits-MidBits)
4965 } else if (OpBits < DestBits) {
4966 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4967 // bits, just sext from i32.
4968 if (NumSignBits > OpBits-MidBits)
4969 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4971 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4972 // bits, just truncate to i32.
4973 if (NumSignBits > OpBits-MidBits)
4974 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4977 // fold (sext (truncate x)) -> (sextinreg x).
4978 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4979 N0.getValueType())) {
4980 if (OpBits < DestBits)
4981 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4982 else if (OpBits > DestBits)
4983 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4984 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4985 DAG.getValueType(N0.getValueType()));
4989 // fold (sext (load x)) -> (sext (truncate (sextload x)))
4990 // None of the supported targets knows how to perform load and sign extend
4991 // on vectors in one instruction. We only perform this transformation on
4993 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4994 ISD::isUNINDEXEDLoad(N0.getNode()) &&
4995 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4996 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4997 bool DoXform = true;
4998 SmallVector<SDNode*, 4> SetCCs;
4999 if (!N0.hasOneUse())
5000 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5002 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5003 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5005 LN0->getBasePtr(), N0.getValueType(),
5006 LN0->getMemOperand());
5007 CombineTo(N, ExtLoad);
5008 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5009 N0.getValueType(), ExtLoad);
5010 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5011 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5013 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5017 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5018 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5019 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5020 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5021 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5022 EVT MemVT = LN0->getMemoryVT();
5023 if ((!LegalOperations && !LN0->isVolatile()) ||
5024 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5025 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5027 LN0->getBasePtr(), MemVT,
5028 LN0->getMemOperand());
5029 CombineTo(N, ExtLoad);
5030 CombineTo(N0.getNode(),
5031 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5032 N0.getValueType(), ExtLoad),
5033 ExtLoad.getValue(1));
5034 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5038 // fold (sext (and/or/xor (load x), cst)) ->
5039 // (and/or/xor (sextload x), (sext cst))
5040 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5041 N0.getOpcode() == ISD::XOR) &&
5042 isa<LoadSDNode>(N0.getOperand(0)) &&
5043 N0.getOperand(1).getOpcode() == ISD::Constant &&
5044 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5045 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5046 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5047 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5048 bool DoXform = true;
5049 SmallVector<SDNode*, 4> SetCCs;
5050 if (!N0.hasOneUse())
5051 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5054 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5055 LN0->getChain(), LN0->getBasePtr(),
5057 LN0->getMemOperand());
5058 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5059 Mask = Mask.sext(VT.getSizeInBits());
5060 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5061 ExtLoad, DAG.getConstant(Mask, VT));
5062 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5063 SDLoc(N0.getOperand(0)),
5064 N0.getOperand(0).getValueType(), ExtLoad);
5066 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5067 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5069 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5074 if (N0.getOpcode() == ISD::SETCC) {
5075 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5076 // Only do this before legalize for now.
5077 if (VT.isVector() && !LegalOperations &&
5078 TLI.getBooleanContents(true) ==
5079 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5080 EVT N0VT = N0.getOperand(0).getValueType();
5081 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5082 // of the same size as the compared operands. Only optimize sext(setcc())
5083 // if this is the case.
5084 EVT SVT = getSetCCResultType(N0VT);
5086 // We know that the # elements of the results is the same as the
5087 // # elements of the compare (and the # elements of the compare result
5088 // for that matter). Check to see that they are the same size. If so,
5089 // we know that the element size of the sext'd result matches the
5090 // element size of the compare operands.
5091 if (VT.getSizeInBits() == SVT.getSizeInBits())
5092 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5094 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5096 // If the desired elements are smaller or larger than the source
5097 // elements we can use a matching integer vector type and then
5098 // truncate/sign extend
5099 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5100 if (SVT == MatchingVectorType) {
5101 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5102 N0.getOperand(0), N0.getOperand(1),
5103 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5104 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5108 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5109 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5111 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5113 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5114 NegOne, DAG.getConstant(0, VT),
5115 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5116 if (SCC.getNode()) return SCC;
5118 if (!VT.isVector()) {
5119 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5120 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5122 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5123 SDValue SetCC = DAG.getSetCC(DL,
5125 N0.getOperand(0), N0.getOperand(1), CC);
5126 EVT SelectVT = getSetCCResultType(VT);
5127 return DAG.getSelect(DL, VT,
5128 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5129 NegOne, DAG.getConstant(0, VT));
5135 // fold (sext x) -> (zext x) if the sign bit is known zero.
5136 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5137 DAG.SignBitIsZero(N0))
5138 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5143 // isTruncateOf - If N is a truncate of some other value, return true, record
5144 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5145 // This function computes KnownZero to avoid a duplicated call to
5146 // computeKnownBits in the caller.
5147 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5150 if (N->getOpcode() == ISD::TRUNCATE) {
5151 Op = N->getOperand(0);
5152 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5156 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5157 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5160 SDValue Op0 = N->getOperand(0);
5161 SDValue Op1 = N->getOperand(1);
5162 assert(Op0.getValueType() == Op1.getValueType());
5164 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5165 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5166 if (COp0 && COp0->isNullValue())
5168 else if (COp1 && COp1->isNullValue())
5173 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5175 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5181 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5182 SDValue N0 = N->getOperand(0);
5183 EVT VT = N->getValueType(0);
5185 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5187 return SDValue(Res, 0);
5189 // fold (zext (zext x)) -> (zext x)
5190 // fold (zext (aext x)) -> (zext x)
5191 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5192 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5195 // fold (zext (truncate x)) -> (zext x) or
5196 // (zext (truncate x)) -> (truncate x)
5197 // This is valid when the truncated bits of x are already zero.
5198 // FIXME: We should extend this to work for vectors too.
5201 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5202 APInt TruncatedBits =
5203 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5204 APInt(Op.getValueSizeInBits(), 0) :
5205 APInt::getBitsSet(Op.getValueSizeInBits(),
5206 N0.getValueSizeInBits(),
5207 std::min(Op.getValueSizeInBits(),
5208 VT.getSizeInBits()));
5209 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5210 if (VT.bitsGT(Op.getValueType()))
5211 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5212 if (VT.bitsLT(Op.getValueType()))
5213 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5219 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5220 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5221 if (N0.getOpcode() == ISD::TRUNCATE) {
5222 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5223 if (NarrowLoad.getNode()) {
5224 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5225 if (NarrowLoad.getNode() != N0.getNode()) {
5226 CombineTo(N0.getNode(), NarrowLoad);
5227 // CombineTo deleted the truncate, if needed, but not what's under it.
5230 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5234 // fold (zext (truncate x)) -> (and x, mask)
5235 if (N0.getOpcode() == ISD::TRUNCATE &&
5236 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5238 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5239 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5240 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5241 if (NarrowLoad.getNode()) {
5242 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5243 if (NarrowLoad.getNode() != N0.getNode()) {
5244 CombineTo(N0.getNode(), NarrowLoad);
5245 // CombineTo deleted the truncate, if needed, but not what's under it.
5248 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5251 SDValue Op = N0.getOperand(0);
5252 if (Op.getValueType().bitsLT(VT)) {
5253 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5254 AddToWorkList(Op.getNode());
5255 } else if (Op.getValueType().bitsGT(VT)) {
5256 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5257 AddToWorkList(Op.getNode());
5259 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5260 N0.getValueType().getScalarType());
5263 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5264 // if either of the casts is not free.
5265 if (N0.getOpcode() == ISD::AND &&
5266 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5267 N0.getOperand(1).getOpcode() == ISD::Constant &&
5268 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5269 N0.getValueType()) ||
5270 !TLI.isZExtFree(N0.getValueType(), VT))) {
5271 SDValue X = N0.getOperand(0).getOperand(0);
5272 if (X.getValueType().bitsLT(VT)) {
5273 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5274 } else if (X.getValueType().bitsGT(VT)) {
5275 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5277 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5278 Mask = Mask.zext(VT.getSizeInBits());
5279 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5280 X, DAG.getConstant(Mask, VT));
5283 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5284 // None of the supported targets knows how to perform load and vector_zext
5285 // on vectors in one instruction. We only perform this transformation on
5287 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5288 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5289 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5290 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5291 bool DoXform = true;
5292 SmallVector<SDNode*, 4> SetCCs;
5293 if (!N0.hasOneUse())
5294 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5296 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5297 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5299 LN0->getBasePtr(), N0.getValueType(),
5300 LN0->getMemOperand());
5301 CombineTo(N, ExtLoad);
5302 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5303 N0.getValueType(), ExtLoad);
5304 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5306 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5308 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5312 // fold (zext (and/or/xor (load x), cst)) ->
5313 // (and/or/xor (zextload x), (zext cst))
5314 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5315 N0.getOpcode() == ISD::XOR) &&
5316 isa<LoadSDNode>(N0.getOperand(0)) &&
5317 N0.getOperand(1).getOpcode() == ISD::Constant &&
5318 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5319 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5320 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5321 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5322 bool DoXform = true;
5323 SmallVector<SDNode*, 4> SetCCs;
5324 if (!N0.hasOneUse())
5325 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5328 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5329 LN0->getChain(), LN0->getBasePtr(),
5331 LN0->getMemOperand());
5332 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5333 Mask = Mask.zext(VT.getSizeInBits());
5334 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5335 ExtLoad, DAG.getConstant(Mask, VT));
5336 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5337 SDLoc(N0.getOperand(0)),
5338 N0.getOperand(0).getValueType(), ExtLoad);
5340 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5341 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5343 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5348 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5349 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5350 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5351 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5352 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5353 EVT MemVT = LN0->getMemoryVT();
5354 if ((!LegalOperations && !LN0->isVolatile()) ||
5355 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5356 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5358 LN0->getBasePtr(), MemVT,
5359 LN0->getMemOperand());
5360 CombineTo(N, ExtLoad);
5361 CombineTo(N0.getNode(),
5362 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5364 ExtLoad.getValue(1));
5365 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5369 if (N0.getOpcode() == ISD::SETCC) {
5370 if (!LegalOperations && VT.isVector() &&
5371 N0.getValueType().getVectorElementType() == MVT::i1) {
5372 EVT N0VT = N0.getOperand(0).getValueType();
5373 if (getSetCCResultType(N0VT) == N0.getValueType())
5376 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5377 // Only do this before legalize for now.
5378 EVT EltVT = VT.getVectorElementType();
5379 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5380 DAG.getConstant(1, EltVT));
5381 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5382 // We know that the # elements of the results is the same as the
5383 // # elements of the compare (and the # elements of the compare result
5384 // for that matter). Check to see that they are the same size. If so,
5385 // we know that the element size of the sext'd result matches the
5386 // element size of the compare operands.
5387 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5388 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5390 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5391 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5394 // If the desired elements are smaller or larger than the source
5395 // elements we can use a matching integer vector type and then
5396 // truncate/sign extend
5397 EVT MatchingElementType =
5398 EVT::getIntegerVT(*DAG.getContext(),
5399 N0VT.getScalarType().getSizeInBits());
5400 EVT MatchingVectorType =
5401 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5402 N0VT.getVectorNumElements());
5404 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5406 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5407 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5408 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5409 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5412 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5414 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5415 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5416 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5417 if (SCC.getNode()) return SCC;
5420 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5421 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5422 isa<ConstantSDNode>(N0.getOperand(1)) &&
5423 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5425 SDValue ShAmt = N0.getOperand(1);
5426 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5427 if (N0.getOpcode() == ISD::SHL) {
5428 SDValue InnerZExt = N0.getOperand(0);
5429 // If the original shl may be shifting out bits, do not perform this
5431 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5432 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5433 if (ShAmtVal > KnownZeroBits)
5439 // Ensure that the shift amount is wide enough for the shifted value.
5440 if (VT.getSizeInBits() >= 256)
5441 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5443 return DAG.getNode(N0.getOpcode(), DL, VT,
5444 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5451 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5452 SDValue N0 = N->getOperand(0);
5453 EVT VT = N->getValueType(0);
5455 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5457 return SDValue(Res, 0);
5459 // fold (aext (aext x)) -> (aext x)
5460 // fold (aext (zext x)) -> (zext x)
5461 // fold (aext (sext x)) -> (sext x)
5462 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5463 N0.getOpcode() == ISD::ZERO_EXTEND ||
5464 N0.getOpcode() == ISD::SIGN_EXTEND)
5465 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5467 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5468 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5469 if (N0.getOpcode() == ISD::TRUNCATE) {
5470 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5471 if (NarrowLoad.getNode()) {
5472 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5473 if (NarrowLoad.getNode() != N0.getNode()) {
5474 CombineTo(N0.getNode(), NarrowLoad);
5475 // CombineTo deleted the truncate, if needed, but not what's under it.
5478 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5482 // fold (aext (truncate x))
5483 if (N0.getOpcode() == ISD::TRUNCATE) {
5484 SDValue TruncOp = N0.getOperand(0);
5485 if (TruncOp.getValueType() == VT)
5486 return TruncOp; // x iff x size == zext size.
5487 if (TruncOp.getValueType().bitsGT(VT))
5488 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5489 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5492 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5493 // if the trunc is not free.
5494 if (N0.getOpcode() == ISD::AND &&
5495 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5496 N0.getOperand(1).getOpcode() == ISD::Constant &&
5497 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5498 N0.getValueType())) {
5499 SDValue X = N0.getOperand(0).getOperand(0);
5500 if (X.getValueType().bitsLT(VT)) {
5501 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5502 } else if (X.getValueType().bitsGT(VT)) {
5503 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5505 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5506 Mask = Mask.zext(VT.getSizeInBits());
5507 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5508 X, DAG.getConstant(Mask, VT));
5511 // fold (aext (load x)) -> (aext (truncate (extload x)))
5512 // None of the supported targets knows how to perform load and any_ext
5513 // on vectors in one instruction. We only perform this transformation on
5515 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5516 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5517 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5518 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5519 bool DoXform = true;
5520 SmallVector<SDNode*, 4> SetCCs;
5521 if (!N0.hasOneUse())
5522 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5524 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5525 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5527 LN0->getBasePtr(), N0.getValueType(),
5528 LN0->getMemOperand());
5529 CombineTo(N, ExtLoad);
5530 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5531 N0.getValueType(), ExtLoad);
5532 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5533 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5535 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5539 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5540 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5541 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5542 if (N0.getOpcode() == ISD::LOAD &&
5543 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5545 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5546 ISD::LoadExtType ExtType = LN0->getExtensionType();
5547 EVT MemVT = LN0->getMemoryVT();
5548 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5549 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5550 VT, LN0->getChain(), LN0->getBasePtr(),
5551 MemVT, LN0->getMemOperand());
5552 CombineTo(N, ExtLoad);
5553 CombineTo(N0.getNode(),
5554 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5555 N0.getValueType(), ExtLoad),
5556 ExtLoad.getValue(1));
5557 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5561 if (N0.getOpcode() == ISD::SETCC) {
5563 // aext(setcc) -> vsetcc
5564 // aext(setcc) -> truncate(vsetcc)
5565 // aext(setcc) -> aext(vsetcc)
5566 // Only do this before legalize for now.
5567 if (VT.isVector() && !LegalOperations) {
5568 EVT N0VT = N0.getOperand(0).getValueType();
5569 // We know that the # elements of the results is the same as the
5570 // # elements of the compare (and the # elements of the compare result
5571 // for that matter). Check to see that they are the same size. If so,
5572 // we know that the element size of the sext'd result matches the
5573 // element size of the compare operands.
5574 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5575 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5577 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5578 // If the desired elements are smaller or larger than the source
5579 // elements we can use a matching integer vector type and then
5580 // truncate/any extend
5582 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5584 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5586 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5587 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5591 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5593 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5594 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5595 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5603 /// GetDemandedBits - See if the specified operand can be simplified with the
5604 /// knowledge that only the bits specified by Mask are used. If so, return the
5605 /// simpler operand, otherwise return a null SDValue.
5606 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5607 switch (V.getOpcode()) {
5609 case ISD::Constant: {
5610 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5611 assert(CV && "Const value should be ConstSDNode.");
5612 const APInt &CVal = CV->getAPIntValue();
5613 APInt NewVal = CVal & Mask;
5615 return DAG.getConstant(NewVal, V.getValueType());
5620 // If the LHS or RHS don't contribute bits to the or, drop them.
5621 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5622 return V.getOperand(1);
5623 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5624 return V.getOperand(0);
5627 // Only look at single-use SRLs.
5628 if (!V.getNode()->hasOneUse())
5630 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5631 // See if we can recursively simplify the LHS.
5632 unsigned Amt = RHSC->getZExtValue();
5634 // Watch out for shift count overflow though.
5635 if (Amt >= Mask.getBitWidth()) break;
5636 APInt NewMask = Mask << Amt;
5637 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5638 if (SimplifyLHS.getNode())
5639 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5640 SimplifyLHS, V.getOperand(1));
5646 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5647 /// bits and then truncated to a narrower type and where N is a multiple
5648 /// of number of bits of the narrower type, transform it to a narrower load
5649 /// from address + N / num of bits of new type. If the result is to be
5650 /// extended, also fold the extension to form a extending load.
5651 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5652 unsigned Opc = N->getOpcode();
5654 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5655 SDValue N0 = N->getOperand(0);
5656 EVT VT = N->getValueType(0);
5659 // This transformation isn't valid for vector loads.
5663 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5665 if (Opc == ISD::SIGN_EXTEND_INREG) {
5666 ExtType = ISD::SEXTLOAD;
5667 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5668 } else if (Opc == ISD::SRL) {
5669 // Another special-case: SRL is basically zero-extending a narrower value.
5670 ExtType = ISD::ZEXTLOAD;
5672 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5673 if (!N01) return SDValue();
5674 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5675 VT.getSizeInBits() - N01->getZExtValue());
5677 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5680 unsigned EVTBits = ExtVT.getSizeInBits();
5682 // Do not generate loads of non-round integer types since these can
5683 // be expensive (and would be wrong if the type is not byte sized).
5684 if (!ExtVT.isRound())
5688 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5689 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5690 ShAmt = N01->getZExtValue();
5691 // Is the shift amount a multiple of size of VT?
5692 if ((ShAmt & (EVTBits-1)) == 0) {
5693 N0 = N0.getOperand(0);
5694 // Is the load width a multiple of size of VT?
5695 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5699 // At this point, we must have a load or else we can't do the transform.
5700 if (!isa<LoadSDNode>(N0)) return SDValue();
5702 // Because a SRL must be assumed to *need* to zero-extend the high bits
5703 // (as opposed to anyext the high bits), we can't combine the zextload
5704 // lowering of SRL and an sextload.
5705 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5708 // If the shift amount is larger than the input type then we're not
5709 // accessing any of the loaded bytes. If the load was a zextload/extload
5710 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5711 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5716 // If the load is shifted left (and the result isn't shifted back right),
5717 // we can fold the truncate through the shift.
5718 unsigned ShLeftAmt = 0;
5719 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5720 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5721 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5722 ShLeftAmt = N01->getZExtValue();
5723 N0 = N0.getOperand(0);
5727 // If we haven't found a load, we can't narrow it. Don't transform one with
5728 // multiple uses, this would require adding a new load.
5729 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5732 // Don't change the width of a volatile load.
5733 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5734 if (LN0->isVolatile())
5737 // Verify that we are actually reducing a load width here.
5738 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5741 // For the transform to be legal, the load must produce only two values
5742 // (the value loaded and the chain). Don't transform a pre-increment
5743 // load, for example, which produces an extra value. Otherwise the
5744 // transformation is not equivalent, and the downstream logic to replace
5745 // uses gets things wrong.
5746 if (LN0->getNumValues() > 2)
5749 // If the load that we're shrinking is an extload and we're not just
5750 // discarding the extension we can't simply shrink the load. Bail.
5751 // TODO: It would be possible to merge the extensions in some cases.
5752 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5753 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5756 EVT PtrType = N0.getOperand(1).getValueType();
5758 if (PtrType == MVT::Untyped || PtrType.isExtended())
5759 // It's not possible to generate a constant of extended or untyped type.
5762 // For big endian targets, we need to adjust the offset to the pointer to
5763 // load the correct bytes.
5764 if (TLI.isBigEndian()) {
5765 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5766 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5767 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5770 uint64_t PtrOff = ShAmt / 8;
5771 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5772 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5773 PtrType, LN0->getBasePtr(),
5774 DAG.getConstant(PtrOff, PtrType));
5775 AddToWorkList(NewPtr.getNode());
5778 if (ExtType == ISD::NON_EXTLOAD)
5779 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5780 LN0->getPointerInfo().getWithOffset(PtrOff),
5781 LN0->isVolatile(), LN0->isNonTemporal(),
5782 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5784 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5785 LN0->getPointerInfo().getWithOffset(PtrOff),
5786 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5787 NewAlign, LN0->getTBAAInfo());
5789 // Replace the old load's chain with the new load's chain.
5790 WorkListRemover DeadNodes(*this);
5791 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5793 // Shift the result left, if we've swallowed a left shift.
5794 SDValue Result = Load;
5795 if (ShLeftAmt != 0) {
5796 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5797 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5799 // If the shift amount is as large as the result size (but, presumably,
5800 // no larger than the source) then the useful bits of the result are
5801 // zero; we can't simply return the shortened shift, because the result
5802 // of that operation is undefined.
5803 if (ShLeftAmt >= VT.getSizeInBits())
5804 Result = DAG.getConstant(0, VT);
5806 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5807 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5810 // Return the new loaded value.
5814 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5815 SDValue N0 = N->getOperand(0);
5816 SDValue N1 = N->getOperand(1);
5817 EVT VT = N->getValueType(0);
5818 EVT EVT = cast<VTSDNode>(N1)->getVT();
5819 unsigned VTBits = VT.getScalarType().getSizeInBits();
5820 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5822 // fold (sext_in_reg c1) -> c1
5823 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5824 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5826 // If the input is already sign extended, just drop the extension.
5827 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5830 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5831 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5832 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5833 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5834 N0.getOperand(0), N1);
5836 // fold (sext_in_reg (sext x)) -> (sext x)
5837 // fold (sext_in_reg (aext x)) -> (sext x)
5838 // if x is small enough.
5839 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5840 SDValue N00 = N0.getOperand(0);
5841 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5842 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5843 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5846 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5847 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5848 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5850 // fold operands of sext_in_reg based on knowledge that the top bits are not
5852 if (SimplifyDemandedBits(SDValue(N, 0)))
5853 return SDValue(N, 0);
5855 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5856 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5857 SDValue NarrowLoad = ReduceLoadWidth(N);
5858 if (NarrowLoad.getNode())
5861 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5862 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5863 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5864 if (N0.getOpcode() == ISD::SRL) {
5865 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5866 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5867 // We can turn this into an SRA iff the input to the SRL is already sign
5869 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5870 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5871 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5872 N0.getOperand(0), N0.getOperand(1));
5876 // fold (sext_inreg (extload x)) -> (sextload x)
5877 if (ISD::isEXTLoad(N0.getNode()) &&
5878 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5879 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5880 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5881 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5882 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5883 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5885 LN0->getBasePtr(), EVT,
5886 LN0->getMemOperand());
5887 CombineTo(N, ExtLoad);
5888 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5889 AddToWorkList(ExtLoad.getNode());
5890 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5892 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5893 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5895 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5896 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5897 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5898 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5899 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5901 LN0->getBasePtr(), EVT,
5902 LN0->getMemOperand());
5903 CombineTo(N, ExtLoad);
5904 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5905 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5908 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5909 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5910 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5911 N0.getOperand(1), false);
5912 if (BSwap.getNode())
5913 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5917 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5918 // into a build_vector.
5919 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5920 SmallVector<SDValue, 8> Elts;
5921 unsigned NumElts = N0->getNumOperands();
5922 unsigned ShAmt = VTBits - EVTBits;
5924 for (unsigned i = 0; i != NumElts; ++i) {
5925 SDValue Op = N0->getOperand(i);
5926 if (Op->getOpcode() == ISD::UNDEF) {
5931 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5932 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5933 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5934 Op.getValueType()));
5937 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
5943 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5944 SDValue N0 = N->getOperand(0);
5945 EVT VT = N->getValueType(0);
5946 bool isLE = TLI.isLittleEndian();
5949 if (N0.getValueType() == N->getValueType(0))
5951 // fold (truncate c1) -> c1
5952 if (isa<ConstantSDNode>(N0))
5953 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5954 // fold (truncate (truncate x)) -> (truncate x)
5955 if (N0.getOpcode() == ISD::TRUNCATE)
5956 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5957 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5958 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5959 N0.getOpcode() == ISD::SIGN_EXTEND ||
5960 N0.getOpcode() == ISD::ANY_EXTEND) {
5961 if (N0.getOperand(0).getValueType().bitsLT(VT))
5962 // if the source is smaller than the dest, we still need an extend
5963 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5965 if (N0.getOperand(0).getValueType().bitsGT(VT))
5966 // if the source is larger than the dest, than we just need the truncate
5967 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5968 // if the source and dest are the same type, we can drop both the extend
5969 // and the truncate.
5970 return N0.getOperand(0);
5973 // Fold extract-and-trunc into a narrow extract. For example:
5974 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5975 // i32 y = TRUNCATE(i64 x)
5977 // v16i8 b = BITCAST (v2i64 val)
5978 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5980 // Note: We only run this optimization after type legalization (which often
5981 // creates this pattern) and before operation legalization after which
5982 // we need to be more careful about the vector instructions that we generate.
5983 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5984 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
5986 EVT VecTy = N0.getOperand(0).getValueType();
5987 EVT ExTy = N0.getValueType();
5988 EVT TrTy = N->getValueType(0);
5990 unsigned NumElem = VecTy.getVectorNumElements();
5991 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5993 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5994 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5996 SDValue EltNo = N0->getOperand(1);
5997 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5998 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5999 EVT IndexTy = TLI.getVectorIdxTy();
6000 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6002 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6003 NVT, N0.getOperand(0));
6005 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6007 DAG.getConstant(Index, IndexTy));
6011 // Fold a series of buildvector, bitcast, and truncate if possible.
6013 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6014 // (2xi32 (buildvector x, y)).
6015 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6016 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6017 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6018 N0.getOperand(0).hasOneUse()) {
6020 SDValue BuildVect = N0.getOperand(0);
6021 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6022 EVT TruncVecEltTy = VT.getVectorElementType();
6024 // Check that the element types match.
6025 if (BuildVectEltTy == TruncVecEltTy) {
6026 // Now we only need to compute the offset of the truncated elements.
6027 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6028 unsigned TruncVecNumElts = VT.getVectorNumElements();
6029 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6031 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6032 "Invalid number of elements");
6034 SmallVector<SDValue, 8> Opnds;
6035 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6036 Opnds.push_back(BuildVect.getOperand(i));
6038 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6042 // See if we can simplify the input to this truncate through knowledge that
6043 // only the low bits are being used.
6044 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6045 // Currently we only perform this optimization on scalars because vectors
6046 // may have different active low bits.
6047 if (!VT.isVector()) {
6049 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6050 VT.getSizeInBits()));
6051 if (Shorter.getNode())
6052 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6054 // fold (truncate (load x)) -> (smaller load x)
6055 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6056 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6057 SDValue Reduced = ReduceLoadWidth(N);
6058 if (Reduced.getNode())
6060 // Handle the case where the load remains an extending load even
6061 // after truncation.
6062 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6063 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6064 if (!LN0->isVolatile() &&
6065 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6066 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6067 VT, LN0->getChain(), LN0->getBasePtr(),
6069 LN0->getMemOperand());
6070 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6075 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6076 // where ... are all 'undef'.
6077 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6078 SmallVector<EVT, 8> VTs;
6081 unsigned NumDefs = 0;
6083 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6084 SDValue X = N0.getOperand(i);
6085 if (X.getOpcode() != ISD::UNDEF) {
6090 // Stop if more than one members are non-undef.
6093 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6094 VT.getVectorElementType(),
6095 X.getValueType().getVectorNumElements()));
6099 return DAG.getUNDEF(VT);
6102 assert(V.getNode() && "The single defined operand is empty!");
6103 SmallVector<SDValue, 8> Opnds;
6104 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6106 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6109 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6110 AddToWorkList(NV.getNode());
6111 Opnds.push_back(NV);
6113 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6117 // Simplify the operands using demanded-bits information.
6118 if (!VT.isVector() &&
6119 SimplifyDemandedBits(SDValue(N, 0)))
6120 return SDValue(N, 0);
6125 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6126 SDValue Elt = N->getOperand(i);
6127 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6128 return Elt.getNode();
6129 return Elt.getOperand(Elt.getResNo()).getNode();
6132 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6133 /// if load locations are consecutive.
6134 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6135 assert(N->getOpcode() == ISD::BUILD_PAIR);
6137 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6138 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6139 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6140 LD1->getAddressSpace() != LD2->getAddressSpace())
6142 EVT LD1VT = LD1->getValueType(0);
6144 if (ISD::isNON_EXTLoad(LD2) &&
6146 // If both are volatile this would reduce the number of volatile loads.
6147 // If one is volatile it might be ok, but play conservative and bail out.
6148 !LD1->isVolatile() &&
6149 !LD2->isVolatile() &&
6150 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6151 unsigned Align = LD1->getAlignment();
6152 unsigned NewAlign = TLI.getDataLayout()->
6153 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6155 if (NewAlign <= Align &&
6156 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6157 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6158 LD1->getBasePtr(), LD1->getPointerInfo(),
6159 false, false, false, Align);
6165 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6166 SDValue N0 = N->getOperand(0);
6167 EVT VT = N->getValueType(0);
6169 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6170 // Only do this before legalize, since afterward the target may be depending
6171 // on the bitconvert.
6172 // First check to see if this is all constant.
6174 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6176 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6178 EVT DestEltVT = N->getValueType(0).getVectorElementType();
6179 assert(!DestEltVT.isVector() &&
6180 "Element type of vector ValueType must not be vector!");
6182 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6185 // If the input is a constant, let getNode fold it.
6186 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6187 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6188 if (Res.getNode() != N) {
6189 if (!LegalOperations ||
6190 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6193 // Folding it resulted in an illegal node, and it's too late to
6194 // do that. Clean up the old node and forego the transformation.
6195 // Ideally this won't happen very often, because instcombine
6196 // and the earlier dagcombine runs (where illegal nodes are
6197 // permitted) should have folded most of them already.
6198 DAG.DeleteNode(Res.getNode());
6202 // (conv (conv x, t1), t2) -> (conv x, t2)
6203 if (N0.getOpcode() == ISD::BITCAST)
6204 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6207 // fold (conv (load x)) -> (load (conv*)x)
6208 // If the resultant load doesn't need a higher alignment than the original!
6209 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6210 // Do not change the width of a volatile load.
6211 !cast<LoadSDNode>(N0)->isVolatile() &&
6212 // Do not remove the cast if the types differ in endian layout.
6213 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6214 TLI.hasBigEndianPartOrdering(VT) &&
6215 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6216 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6217 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6218 unsigned Align = TLI.getDataLayout()->
6219 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6220 unsigned OrigAlign = LN0->getAlignment();
6222 if (Align <= OrigAlign) {
6223 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6224 LN0->getBasePtr(), LN0->getPointerInfo(),
6225 LN0->isVolatile(), LN0->isNonTemporal(),
6226 LN0->isInvariant(), OrigAlign,
6227 LN0->getTBAAInfo());
6229 CombineTo(N0.getNode(),
6230 DAG.getNode(ISD::BITCAST, SDLoc(N0),
6231 N0.getValueType(), Load),
6237 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6238 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6239 // This often reduces constant pool loads.
6240 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6241 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6242 N0.getNode()->hasOneUse() && VT.isInteger() &&
6243 !VT.isVector() && !N0.getValueType().isVector()) {
6244 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6246 AddToWorkList(NewConv.getNode());
6248 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6249 if (N0.getOpcode() == ISD::FNEG)
6250 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6251 NewConv, DAG.getConstant(SignBit, VT));
6252 assert(N0.getOpcode() == ISD::FABS);
6253 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6254 NewConv, DAG.getConstant(~SignBit, VT));
6257 // fold (bitconvert (fcopysign cst, x)) ->
6258 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6259 // Note that we don't handle (copysign x, cst) because this can always be
6260 // folded to an fneg or fabs.
6261 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6262 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6263 VT.isInteger() && !VT.isVector()) {
6264 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6265 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6266 if (isTypeLegal(IntXVT)) {
6267 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6268 IntXVT, N0.getOperand(1));
6269 AddToWorkList(X.getNode());
6271 // If X has a different width than the result/lhs, sext it or truncate it.
6272 unsigned VTWidth = VT.getSizeInBits();
6273 if (OrigXWidth < VTWidth) {
6274 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6275 AddToWorkList(X.getNode());
6276 } else if (OrigXWidth > VTWidth) {
6277 // To get the sign bit in the right place, we have to shift it right
6278 // before truncating.
6279 X = DAG.getNode(ISD::SRL, SDLoc(X),
6280 X.getValueType(), X,
6281 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6282 AddToWorkList(X.getNode());
6283 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6284 AddToWorkList(X.getNode());
6287 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6288 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6289 X, DAG.getConstant(SignBit, VT));
6290 AddToWorkList(X.getNode());
6292 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6293 VT, N0.getOperand(0));
6294 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6295 Cst, DAG.getConstant(~SignBit, VT));
6296 AddToWorkList(Cst.getNode());
6298 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6302 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6303 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6304 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6305 if (CombineLD.getNode())
6312 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6313 EVT VT = N->getValueType(0);
6314 return CombineConsecutiveLoads(N, VT);
6317 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6318 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
6319 /// destination element value type.
6320 SDValue DAGCombiner::
6321 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6322 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6324 // If this is already the right type, we're done.
6325 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6327 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6328 unsigned DstBitSize = DstEltVT.getSizeInBits();
6330 // If this is a conversion of N elements of one type to N elements of another
6331 // type, convert each element. This handles FP<->INT cases.
6332 if (SrcBitSize == DstBitSize) {
6333 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6334 BV->getValueType(0).getVectorNumElements());
6336 // Due to the FP element handling below calling this routine recursively,
6337 // we can end up with a scalar-to-vector node here.
6338 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6339 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6340 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6341 DstEltVT, BV->getOperand(0)));
6343 SmallVector<SDValue, 8> Ops;
6344 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6345 SDValue Op = BV->getOperand(i);
6346 // If the vector element type is not legal, the BUILD_VECTOR operands
6347 // are promoted and implicitly truncated. Make that explicit here.
6348 if (Op.getValueType() != SrcEltVT)
6349 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6350 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6352 AddToWorkList(Ops.back().getNode());
6354 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6357 // Otherwise, we're growing or shrinking the elements. To avoid having to
6358 // handle annoying details of growing/shrinking FP values, we convert them to
6360 if (SrcEltVT.isFloatingPoint()) {
6361 // Convert the input float vector to a int vector where the elements are the
6363 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6364 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6365 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6369 // Now we know the input is an integer vector. If the output is a FP type,
6370 // convert to integer first, then to FP of the right size.
6371 if (DstEltVT.isFloatingPoint()) {
6372 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6373 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6374 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6376 // Next, convert to FP elements of the same size.
6377 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6380 // Okay, we know the src/dst types are both integers of differing types.
6381 // Handling growing first.
6382 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6383 if (SrcBitSize < DstBitSize) {
6384 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6386 SmallVector<SDValue, 8> Ops;
6387 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6388 i += NumInputsPerOutput) {
6389 bool isLE = TLI.isLittleEndian();
6390 APInt NewBits = APInt(DstBitSize, 0);
6391 bool EltIsUndef = true;
6392 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6393 // Shift the previously computed bits over.
6394 NewBits <<= SrcBitSize;
6395 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6396 if (Op.getOpcode() == ISD::UNDEF) continue;
6399 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6400 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6404 Ops.push_back(DAG.getUNDEF(DstEltVT));
6406 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6409 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6410 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6413 // Finally, this must be the case where we are shrinking elements: each input
6414 // turns into multiple outputs.
6415 bool isS2V = ISD::isScalarToVector(BV);
6416 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6417 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6418 NumOutputsPerInput*BV->getNumOperands());
6419 SmallVector<SDValue, 8> Ops;
6421 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6422 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6423 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6424 Ops.push_back(DAG.getUNDEF(DstEltVT));
6428 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6429 getAPIntValue().zextOrTrunc(SrcBitSize);
6431 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6432 APInt ThisVal = OpVal.trunc(DstBitSize);
6433 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6434 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6435 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6436 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6438 OpVal = OpVal.lshr(DstBitSize);
6441 // For big endian targets, swap the order of the pieces of each element.
6442 if (TLI.isBigEndian())
6443 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6446 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6449 SDValue DAGCombiner::visitFADD(SDNode *N) {
6450 SDValue N0 = N->getOperand(0);
6451 SDValue N1 = N->getOperand(1);
6452 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6453 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6454 EVT VT = N->getValueType(0);
6457 if (VT.isVector()) {
6458 SDValue FoldedVOp = SimplifyVBinOp(N);
6459 if (FoldedVOp.getNode()) return FoldedVOp;
6462 // fold (fadd c1, c2) -> c1 + c2
6464 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6465 // canonicalize constant to RHS
6466 if (N0CFP && !N1CFP)
6467 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6468 // fold (fadd A, 0) -> A
6469 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6470 N1CFP->getValueAPF().isZero())
6472 // fold (fadd A, (fneg B)) -> (fsub A, B)
6473 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6474 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6475 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6476 GetNegatedExpression(N1, DAG, LegalOperations));
6477 // fold (fadd (fneg A), B) -> (fsub B, A)
6478 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6479 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6480 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6481 GetNegatedExpression(N0, DAG, LegalOperations));
6483 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6484 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6485 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6486 isa<ConstantFPSDNode>(N0.getOperand(1)))
6487 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6488 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6489 N0.getOperand(1), N1));
6491 // No FP constant should be created after legalization as Instruction
6492 // Selection pass has hard time in dealing with FP constant.
6494 // We don't need test this condition for transformation like following, as
6495 // the DAG being transformed implies it is legal to take FP constant as
6498 // (fadd (fmul c, x), x) -> (fmul c+1, x)
6500 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6502 // If allow, fold (fadd (fneg x), x) -> 0.0
6503 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6504 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6505 return DAG.getConstantFP(0.0, VT);
6507 // If allow, fold (fadd x, (fneg x)) -> 0.0
6508 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6509 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6510 return DAG.getConstantFP(0.0, VT);
6512 // In unsafe math mode, we can fold chains of FADD's of the same value
6513 // into multiplications. This transform is not safe in general because
6514 // we are reducing the number of rounding steps.
6515 if (DAG.getTarget().Options.UnsafeFPMath &&
6516 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6518 if (N0.getOpcode() == ISD::FMUL) {
6519 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6520 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6522 // (fadd (fmul c, x), x) -> (fmul x, c+1)
6523 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6524 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6526 DAG.getConstantFP(1.0, VT));
6527 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6531 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6532 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6533 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6535 DAG.getConstantFP(1.0, VT));
6536 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6540 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6541 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6542 N1.getOperand(0) == N1.getOperand(1) &&
6543 N0.getOperand(1) == N1.getOperand(0)) {
6544 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6546 DAG.getConstantFP(2.0, VT));
6547 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6548 N0.getOperand(1), NewCFP);
6551 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6552 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6553 N1.getOperand(0) == N1.getOperand(1) &&
6554 N0.getOperand(0) == N1.getOperand(0)) {
6555 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6557 DAG.getConstantFP(2.0, VT));
6558 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6559 N0.getOperand(0), NewCFP);
6563 if (N1.getOpcode() == ISD::FMUL) {
6564 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6565 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6567 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6568 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6569 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6571 DAG.getConstantFP(1.0, VT));
6572 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6576 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6577 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6578 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6580 DAG.getConstantFP(1.0, VT));
6581 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6586 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6587 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6588 N0.getOperand(0) == N0.getOperand(1) &&
6589 N1.getOperand(1) == N0.getOperand(0)) {
6590 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6592 DAG.getConstantFP(2.0, VT));
6593 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6594 N1.getOperand(1), NewCFP);
6597 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6598 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6599 N0.getOperand(0) == N0.getOperand(1) &&
6600 N1.getOperand(0) == N0.getOperand(0)) {
6601 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6603 DAG.getConstantFP(2.0, VT));
6604 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6605 N1.getOperand(0), NewCFP);
6609 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6610 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6611 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6612 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6613 (N0.getOperand(0) == N1))
6614 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6615 N1, DAG.getConstantFP(3.0, VT));
6618 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6619 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6620 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6621 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6622 N1.getOperand(0) == N0)
6623 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6624 N0, DAG.getConstantFP(3.0, VT));
6627 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6628 if (AllowNewFpConst &&
6629 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6630 N0.getOperand(0) == N0.getOperand(1) &&
6631 N1.getOperand(0) == N1.getOperand(1) &&
6632 N0.getOperand(0) == N1.getOperand(0))
6633 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6635 DAG.getConstantFP(4.0, VT));
6638 // FADD -> FMA combines:
6639 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6640 DAG.getTarget().Options.UnsafeFPMath) &&
6641 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6642 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6644 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6645 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6646 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6647 N0.getOperand(0), N0.getOperand(1), N1);
6649 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6650 // Note: Commutes FADD operands.
6651 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6652 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6653 N1.getOperand(0), N1.getOperand(1), N0);
6659 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6660 SDValue N0 = N->getOperand(0);
6661 SDValue N1 = N->getOperand(1);
6662 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6663 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6664 EVT VT = N->getValueType(0);
6668 if (VT.isVector()) {
6669 SDValue FoldedVOp = SimplifyVBinOp(N);
6670 if (FoldedVOp.getNode()) return FoldedVOp;
6673 // fold (fsub c1, c2) -> c1-c2
6675 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6676 // fold (fsub A, 0) -> A
6677 if (DAG.getTarget().Options.UnsafeFPMath &&
6678 N1CFP && N1CFP->getValueAPF().isZero())
6680 // fold (fsub 0, B) -> -B
6681 if (DAG.getTarget().Options.UnsafeFPMath &&
6682 N0CFP && N0CFP->getValueAPF().isZero()) {
6683 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6684 return GetNegatedExpression(N1, DAG, LegalOperations);
6685 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6686 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6688 // fold (fsub A, (fneg B)) -> (fadd A, B)
6689 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6690 return DAG.getNode(ISD::FADD, dl, VT, N0,
6691 GetNegatedExpression(N1, DAG, LegalOperations));
6693 // If 'unsafe math' is enabled, fold
6694 // (fsub x, x) -> 0.0 &
6695 // (fsub x, (fadd x, y)) -> (fneg y) &
6696 // (fsub x, (fadd y, x)) -> (fneg y)
6697 if (DAG.getTarget().Options.UnsafeFPMath) {
6699 return DAG.getConstantFP(0.0f, VT);
6701 if (N1.getOpcode() == ISD::FADD) {
6702 SDValue N10 = N1->getOperand(0);
6703 SDValue N11 = N1->getOperand(1);
6705 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6706 &DAG.getTarget().Options))
6707 return GetNegatedExpression(N11, DAG, LegalOperations);
6709 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6710 &DAG.getTarget().Options))
6711 return GetNegatedExpression(N10, DAG, LegalOperations);
6715 // FSUB -> FMA combines:
6716 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6717 DAG.getTarget().Options.UnsafeFPMath) &&
6718 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6719 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6721 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6722 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6723 return DAG.getNode(ISD::FMA, dl, VT,
6724 N0.getOperand(0), N0.getOperand(1),
6725 DAG.getNode(ISD::FNEG, dl, VT, N1));
6727 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6728 // Note: Commutes FSUB operands.
6729 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6730 return DAG.getNode(ISD::FMA, dl, VT,
6731 DAG.getNode(ISD::FNEG, dl, VT,
6733 N1.getOperand(1), N0);
6735 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6736 if (N0.getOpcode() == ISD::FNEG &&
6737 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6738 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6739 SDValue N00 = N0.getOperand(0).getOperand(0);
6740 SDValue N01 = N0.getOperand(0).getOperand(1);
6741 return DAG.getNode(ISD::FMA, dl, VT,
6742 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6743 DAG.getNode(ISD::FNEG, dl, VT, N1));
6750 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6751 SDValue N0 = N->getOperand(0);
6752 SDValue N1 = N->getOperand(1);
6753 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6754 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6755 EVT VT = N->getValueType(0);
6756 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6759 if (VT.isVector()) {
6760 SDValue FoldedVOp = SimplifyVBinOp(N);
6761 if (FoldedVOp.getNode()) return FoldedVOp;
6764 // fold (fmul c1, c2) -> c1*c2
6766 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6767 // canonicalize constant to RHS
6768 if (N0CFP && !N1CFP)
6769 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6770 // fold (fmul A, 0) -> 0
6771 if (DAG.getTarget().Options.UnsafeFPMath &&
6772 N1CFP && N1CFP->getValueAPF().isZero())
6774 // fold (fmul A, 0) -> 0, vector edition.
6775 if (DAG.getTarget().Options.UnsafeFPMath &&
6776 ISD::isBuildVectorAllZeros(N1.getNode()))
6778 // fold (fmul A, 1.0) -> A
6779 if (N1CFP && N1CFP->isExactlyValue(1.0))
6781 // fold (fmul X, 2.0) -> (fadd X, X)
6782 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6783 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6784 // fold (fmul X, -1.0) -> (fneg X)
6785 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6786 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6787 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6789 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6790 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6791 &DAG.getTarget().Options)) {
6792 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6793 &DAG.getTarget().Options)) {
6794 // Both can be negated for free, check to see if at least one is cheaper
6796 if (LHSNeg == 2 || RHSNeg == 2)
6797 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6798 GetNegatedExpression(N0, DAG, LegalOperations),
6799 GetNegatedExpression(N1, DAG, LegalOperations));
6803 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6804 if (DAG.getTarget().Options.UnsafeFPMath &&
6805 N1CFP && N0.getOpcode() == ISD::FMUL &&
6806 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6807 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6808 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6809 N0.getOperand(1), N1));
6814 SDValue DAGCombiner::visitFMA(SDNode *N) {
6815 SDValue N0 = N->getOperand(0);
6816 SDValue N1 = N->getOperand(1);
6817 SDValue N2 = N->getOperand(2);
6818 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6819 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6820 EVT VT = N->getValueType(0);
6823 if (DAG.getTarget().Options.UnsafeFPMath) {
6824 if (N0CFP && N0CFP->isZero())
6826 if (N1CFP && N1CFP->isZero())
6829 if (N0CFP && N0CFP->isExactlyValue(1.0))
6830 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6831 if (N1CFP && N1CFP->isExactlyValue(1.0))
6832 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6834 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6835 if (N0CFP && !N1CFP)
6836 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6838 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6839 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6840 N2.getOpcode() == ISD::FMUL &&
6841 N0 == N2.getOperand(0) &&
6842 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6843 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6844 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6848 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6849 if (DAG.getTarget().Options.UnsafeFPMath &&
6850 N0.getOpcode() == ISD::FMUL && N1CFP &&
6851 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6852 return DAG.getNode(ISD::FMA, dl, VT,
6854 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6858 // (fma x, 1, y) -> (fadd x, y)
6859 // (fma x, -1, y) -> (fadd (fneg x), y)
6861 if (N1CFP->isExactlyValue(1.0))
6862 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6864 if (N1CFP->isExactlyValue(-1.0) &&
6865 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6866 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6867 AddToWorkList(RHSNeg.getNode());
6868 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6872 // (fma x, c, x) -> (fmul x, (c+1))
6873 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6874 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6875 DAG.getNode(ISD::FADD, dl, VT,
6876 N1, DAG.getConstantFP(1.0, VT)));
6878 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6879 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6880 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6881 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6882 DAG.getNode(ISD::FADD, dl, VT,
6883 N1, DAG.getConstantFP(-1.0, VT)));
6889 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6890 SDValue N0 = N->getOperand(0);
6891 SDValue N1 = N->getOperand(1);
6892 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6893 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6894 EVT VT = N->getValueType(0);
6895 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6898 if (VT.isVector()) {
6899 SDValue FoldedVOp = SimplifyVBinOp(N);
6900 if (FoldedVOp.getNode()) return FoldedVOp;
6903 // fold (fdiv c1, c2) -> c1/c2
6905 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6907 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6908 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6909 // Compute the reciprocal 1.0 / c2.
6910 APFloat N1APF = N1CFP->getValueAPF();
6911 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6912 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6913 // Only do the transform if the reciprocal is a legal fp immediate that
6914 // isn't too nasty (eg NaN, denormal, ...).
6915 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6916 (!LegalOperations ||
6917 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6918 // backend)... we should handle this gracefully after Legalize.
6919 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6920 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6921 TLI.isFPImmLegal(Recip, VT)))
6922 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6923 DAG.getConstantFP(Recip, VT));
6926 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6927 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6928 &DAG.getTarget().Options)) {
6929 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6930 &DAG.getTarget().Options)) {
6931 // Both can be negated for free, check to see if at least one is cheaper
6933 if (LHSNeg == 2 || RHSNeg == 2)
6934 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6935 GetNegatedExpression(N0, DAG, LegalOperations),
6936 GetNegatedExpression(N1, DAG, LegalOperations));
6943 SDValue DAGCombiner::visitFREM(SDNode *N) {
6944 SDValue N0 = N->getOperand(0);
6945 SDValue N1 = N->getOperand(1);
6946 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6947 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6948 EVT VT = N->getValueType(0);
6950 // fold (frem c1, c2) -> fmod(c1,c2)
6952 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6957 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6958 SDValue N0 = N->getOperand(0);
6959 SDValue N1 = N->getOperand(1);
6960 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6961 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6962 EVT VT = N->getValueType(0);
6964 if (N0CFP && N1CFP) // Constant fold
6965 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6968 const APFloat& V = N1CFP->getValueAPF();
6969 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6970 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6971 if (!V.isNegative()) {
6972 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6973 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6975 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6976 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6977 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6981 // copysign(fabs(x), y) -> copysign(x, y)
6982 // copysign(fneg(x), y) -> copysign(x, y)
6983 // copysign(copysign(x,z), y) -> copysign(x, y)
6984 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6985 N0.getOpcode() == ISD::FCOPYSIGN)
6986 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6987 N0.getOperand(0), N1);
6989 // copysign(x, abs(y)) -> abs(x)
6990 if (N1.getOpcode() == ISD::FABS)
6991 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6993 // copysign(x, copysign(y,z)) -> copysign(x, z)
6994 if (N1.getOpcode() == ISD::FCOPYSIGN)
6995 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6996 N0, N1.getOperand(1));
6998 // copysign(x, fp_extend(y)) -> copysign(x, y)
6999 // copysign(x, fp_round(y)) -> copysign(x, y)
7000 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7001 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7002 N0, N1.getOperand(0));
7007 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7008 SDValue N0 = N->getOperand(0);
7009 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7010 EVT VT = N->getValueType(0);
7011 EVT OpVT = N0.getValueType();
7013 // fold (sint_to_fp c1) -> c1fp
7015 // ...but only if the target supports immediate floating-point values
7016 (!LegalOperations ||
7017 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7018 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7020 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7021 // but UINT_TO_FP is legal on this target, try to convert.
7022 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7023 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7024 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7025 if (DAG.SignBitIsZero(N0))
7026 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7029 // The next optimizations are desirable only if SELECT_CC can be lowered.
7030 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7031 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7032 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7034 (!LegalOperations ||
7035 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7037 { N0.getOperand(0), N0.getOperand(1),
7038 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7040 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7043 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7044 // (select_cc x, y, 1.0, 0.0,, cc)
7045 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7046 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7047 (!LegalOperations ||
7048 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7050 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7051 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7052 N0.getOperand(0).getOperand(2) };
7053 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7060 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7061 SDValue N0 = N->getOperand(0);
7062 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7063 EVT VT = N->getValueType(0);
7064 EVT OpVT = N0.getValueType();
7066 // fold (uint_to_fp c1) -> c1fp
7068 // ...but only if the target supports immediate floating-point values
7069 (!LegalOperations ||
7070 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7071 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7073 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7074 // but SINT_TO_FP is legal on this target, try to convert.
7075 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7076 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7077 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7078 if (DAG.SignBitIsZero(N0))
7079 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7082 // The next optimizations are desirable only if SELECT_CC can be lowered.
7083 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7084 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7086 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7087 (!LegalOperations ||
7088 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7090 { N0.getOperand(0), N0.getOperand(1),
7091 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7093 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7100 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7101 SDValue N0 = N->getOperand(0);
7102 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7103 EVT VT = N->getValueType(0);
7105 // fold (fp_to_sint c1fp) -> c1
7107 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7112 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7113 SDValue N0 = N->getOperand(0);
7114 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7115 EVT VT = N->getValueType(0);
7117 // fold (fp_to_uint c1fp) -> c1
7119 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7124 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7125 SDValue N0 = N->getOperand(0);
7126 SDValue N1 = N->getOperand(1);
7127 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7128 EVT VT = N->getValueType(0);
7130 // fold (fp_round c1fp) -> c1fp
7132 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7134 // fold (fp_round (fp_extend x)) -> x
7135 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7136 return N0.getOperand(0);
7138 // fold (fp_round (fp_round x)) -> (fp_round x)
7139 if (N0.getOpcode() == ISD::FP_ROUND) {
7140 // This is a value preserving truncation if both round's are.
7141 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7142 N0.getNode()->getConstantOperandVal(1) == 1;
7143 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7144 DAG.getIntPtrConstant(IsTrunc));
7147 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7148 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7149 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7150 N0.getOperand(0), N1);
7151 AddToWorkList(Tmp.getNode());
7152 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7153 Tmp, N0.getOperand(1));
7159 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7160 SDValue N0 = N->getOperand(0);
7161 EVT VT = N->getValueType(0);
7162 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7163 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7165 // fold (fp_round_inreg c1fp) -> c1fp
7166 if (N0CFP && isTypeLegal(EVT)) {
7167 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7168 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7174 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7175 SDValue N0 = N->getOperand(0);
7176 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7177 EVT VT = N->getValueType(0);
7179 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7180 if (N->hasOneUse() &&
7181 N->use_begin()->getOpcode() == ISD::FP_ROUND)
7184 // fold (fp_extend c1fp) -> c1fp
7186 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7188 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7190 if (N0.getOpcode() == ISD::FP_ROUND
7191 && N0.getNode()->getConstantOperandVal(1) == 1) {
7192 SDValue In = N0.getOperand(0);
7193 if (In.getValueType() == VT) return In;
7194 if (VT.bitsLT(In.getValueType()))
7195 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7196 In, N0.getOperand(1));
7197 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7200 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7201 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7202 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7203 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
7204 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7205 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7207 LN0->getBasePtr(), N0.getValueType(),
7208 LN0->getMemOperand());
7209 CombineTo(N, ExtLoad);
7210 CombineTo(N0.getNode(),
7211 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7212 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7213 ExtLoad.getValue(1));
7214 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7220 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7221 SDValue N0 = N->getOperand(0);
7222 EVT VT = N->getValueType(0);
7224 if (VT.isVector()) {
7225 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7226 if (FoldedVOp.getNode()) return FoldedVOp;
7229 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7230 &DAG.getTarget().Options))
7231 return GetNegatedExpression(N0, DAG, LegalOperations);
7233 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7234 // constant pool values.
7235 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7237 N0.getNode()->hasOneUse() &&
7238 N0.getOperand(0).getValueType().isInteger()) {
7239 SDValue Int = N0.getOperand(0);
7240 EVT IntVT = Int.getValueType();
7241 if (IntVT.isInteger() && !IntVT.isVector()) {
7242 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7243 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7244 AddToWorkList(Int.getNode());
7245 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7250 // (fneg (fmul c, x)) -> (fmul -c, x)
7251 if (N0.getOpcode() == ISD::FMUL) {
7252 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7254 APFloat CVal = CFP1->getValueAPF();
7256 if (Level >= AfterLegalizeDAG &&
7257 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7258 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7260 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7261 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7268 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7269 SDValue N0 = N->getOperand(0);
7270 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7271 EVT VT = N->getValueType(0);
7273 // fold (fceil c1) -> fceil(c1)
7275 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7280 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7281 SDValue N0 = N->getOperand(0);
7282 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7283 EVT VT = N->getValueType(0);
7285 // fold (ftrunc c1) -> ftrunc(c1)
7287 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7292 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7293 SDValue N0 = N->getOperand(0);
7294 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7295 EVT VT = N->getValueType(0);
7297 // fold (ffloor c1) -> ffloor(c1)
7299 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7304 SDValue DAGCombiner::visitFABS(SDNode *N) {
7305 SDValue N0 = N->getOperand(0);
7306 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7307 EVT VT = N->getValueType(0);
7309 if (VT.isVector()) {
7310 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7311 if (FoldedVOp.getNode()) return FoldedVOp;
7314 // fold (fabs c1) -> fabs(c1)
7316 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7317 // fold (fabs (fabs x)) -> (fabs x)
7318 if (N0.getOpcode() == ISD::FABS)
7319 return N->getOperand(0);
7320 // fold (fabs (fneg x)) -> (fabs x)
7321 // fold (fabs (fcopysign x, y)) -> (fabs x)
7322 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7323 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7325 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7326 // constant pool values.
7327 if (!TLI.isFAbsFree(VT) &&
7328 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7329 N0.getOperand(0).getValueType().isInteger() &&
7330 !N0.getOperand(0).getValueType().isVector()) {
7331 SDValue Int = N0.getOperand(0);
7332 EVT IntVT = Int.getValueType();
7333 if (IntVT.isInteger() && !IntVT.isVector()) {
7334 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7335 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7336 AddToWorkList(Int.getNode());
7337 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7338 N->getValueType(0), Int);
7345 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7346 SDValue Chain = N->getOperand(0);
7347 SDValue N1 = N->getOperand(1);
7348 SDValue N2 = N->getOperand(2);
7350 // If N is a constant we could fold this into a fallthrough or unconditional
7351 // branch. However that doesn't happen very often in normal code, because
7352 // Instcombine/SimplifyCFG should have handled the available opportunities.
7353 // If we did this folding here, it would be necessary to update the
7354 // MachineBasicBlock CFG, which is awkward.
7356 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7358 if (N1.getOpcode() == ISD::SETCC &&
7359 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7360 N1.getOperand(0).getValueType())) {
7361 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7362 Chain, N1.getOperand(2),
7363 N1.getOperand(0), N1.getOperand(1), N2);
7366 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7367 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7368 (N1.getOperand(0).hasOneUse() &&
7369 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7370 SDNode *Trunc = nullptr;
7371 if (N1.getOpcode() == ISD::TRUNCATE) {
7372 // Look pass the truncate.
7373 Trunc = N1.getNode();
7374 N1 = N1.getOperand(0);
7377 // Match this pattern so that we can generate simpler code:
7380 // %b = and i32 %a, 2
7381 // %c = srl i32 %b, 1
7382 // brcond i32 %c ...
7387 // %b = and i32 %a, 2
7388 // %c = setcc eq %b, 0
7391 // This applies only when the AND constant value has one bit set and the
7392 // SRL constant is equal to the log2 of the AND constant. The back-end is
7393 // smart enough to convert the result into a TEST/JMP sequence.
7394 SDValue Op0 = N1.getOperand(0);
7395 SDValue Op1 = N1.getOperand(1);
7397 if (Op0.getOpcode() == ISD::AND &&
7398 Op1.getOpcode() == ISD::Constant) {
7399 SDValue AndOp1 = Op0.getOperand(1);
7401 if (AndOp1.getOpcode() == ISD::Constant) {
7402 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7404 if (AndConst.isPowerOf2() &&
7405 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7407 DAG.getSetCC(SDLoc(N),
7408 getSetCCResultType(Op0.getValueType()),
7409 Op0, DAG.getConstant(0, Op0.getValueType()),
7412 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7413 MVT::Other, Chain, SetCC, N2);
7414 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7415 // will convert it back to (X & C1) >> C2.
7416 CombineTo(N, NewBRCond, false);
7417 // Truncate is dead.
7419 removeFromWorkList(Trunc);
7420 DAG.DeleteNode(Trunc);
7422 // Replace the uses of SRL with SETCC
7423 WorkListRemover DeadNodes(*this);
7424 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7425 removeFromWorkList(N1.getNode());
7426 DAG.DeleteNode(N1.getNode());
7427 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7433 // Restore N1 if the above transformation doesn't match.
7434 N1 = N->getOperand(1);
7437 // Transform br(xor(x, y)) -> br(x != y)
7438 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7439 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7440 SDNode *TheXor = N1.getNode();
7441 SDValue Op0 = TheXor->getOperand(0);
7442 SDValue Op1 = TheXor->getOperand(1);
7443 if (Op0.getOpcode() == Op1.getOpcode()) {
7444 // Avoid missing important xor optimizations.
7445 SDValue Tmp = visitXOR(TheXor);
7446 if (Tmp.getNode()) {
7447 if (Tmp.getNode() != TheXor) {
7448 DEBUG(dbgs() << "\nReplacing.8 ";
7450 dbgs() << "\nWith: ";
7451 Tmp.getNode()->dump(&DAG);
7453 WorkListRemover DeadNodes(*this);
7454 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7455 removeFromWorkList(TheXor);
7456 DAG.DeleteNode(TheXor);
7457 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7458 MVT::Other, Chain, Tmp, N2);
7461 // visitXOR has changed XOR's operands or replaced the XOR completely,
7463 return SDValue(N, 0);
7467 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7469 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7470 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7471 Op0.getOpcode() == ISD::XOR) {
7472 TheXor = Op0.getNode();
7476 EVT SetCCVT = N1.getValueType();
7478 SetCCVT = getSetCCResultType(SetCCVT);
7479 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7482 Equal ? ISD::SETEQ : ISD::SETNE);
7483 // Replace the uses of XOR with SETCC
7484 WorkListRemover DeadNodes(*this);
7485 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7486 removeFromWorkList(N1.getNode());
7487 DAG.DeleteNode(N1.getNode());
7488 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7489 MVT::Other, Chain, SetCC, N2);
7496 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7498 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7499 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7500 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7502 // If N is a constant we could fold this into a fallthrough or unconditional
7503 // branch. However that doesn't happen very often in normal code, because
7504 // Instcombine/SimplifyCFG should have handled the available opportunities.
7505 // If we did this folding here, it would be necessary to update the
7506 // MachineBasicBlock CFG, which is awkward.
7508 // Use SimplifySetCC to simplify SETCC's.
7509 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7510 CondLHS, CondRHS, CC->get(), SDLoc(N),
7512 if (Simp.getNode()) AddToWorkList(Simp.getNode());
7514 // fold to a simpler setcc
7515 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7516 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7517 N->getOperand(0), Simp.getOperand(2),
7518 Simp.getOperand(0), Simp.getOperand(1),
7524 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7525 /// uses N as its base pointer and that N may be folded in the load / store
7526 /// addressing mode.
7527 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7529 const TargetLowering &TLI) {
7531 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7532 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7534 VT = Use->getValueType(0);
7535 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7536 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7538 VT = ST->getValue().getValueType();
7542 TargetLowering::AddrMode AM;
7543 if (N->getOpcode() == ISD::ADD) {
7544 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7547 AM.BaseOffs = Offset->getSExtValue();
7551 } else if (N->getOpcode() == ISD::SUB) {
7552 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7555 AM.BaseOffs = -Offset->getSExtValue();
7562 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7565 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7566 /// pre-indexed load / store when the base pointer is an add or subtract
7567 /// and it has other uses besides the load / store. After the
7568 /// transformation, the new indexed load / store has effectively folded
7569 /// the add / subtract in and all of its other uses are redirected to the
7570 /// new load / store.
7571 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7572 if (Level < AfterLegalizeDAG)
7578 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7579 if (LD->isIndexed())
7581 VT = LD->getMemoryVT();
7582 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7583 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7585 Ptr = LD->getBasePtr();
7586 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7587 if (ST->isIndexed())
7589 VT = ST->getMemoryVT();
7590 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7591 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7593 Ptr = ST->getBasePtr();
7599 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7600 // out. There is no reason to make this a preinc/predec.
7601 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7602 Ptr.getNode()->hasOneUse())
7605 // Ask the target to do addressing mode selection.
7608 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7609 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7612 // Backends without true r+i pre-indexed forms may need to pass a
7613 // constant base with a variable offset so that constant coercion
7614 // will work with the patterns in canonical form.
7615 bool Swapped = false;
7616 if (isa<ConstantSDNode>(BasePtr)) {
7617 std::swap(BasePtr, Offset);
7621 // Don't create a indexed load / store with zero offset.
7622 if (isa<ConstantSDNode>(Offset) &&
7623 cast<ConstantSDNode>(Offset)->isNullValue())
7626 // Try turning it into a pre-indexed load / store except when:
7627 // 1) The new base ptr is a frame index.
7628 // 2) If N is a store and the new base ptr is either the same as or is a
7629 // predecessor of the value being stored.
7630 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7631 // that would create a cycle.
7632 // 4) All uses are load / store ops that use it as old base ptr.
7634 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7635 // (plus the implicit offset) to a register to preinc anyway.
7636 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7641 SDValue Val = cast<StoreSDNode>(N)->getValue();
7642 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7646 // If the offset is a constant, there may be other adds of constants that
7647 // can be folded with this one. We should do this to avoid having to keep
7648 // a copy of the original base pointer.
7649 SmallVector<SDNode *, 16> OtherUses;
7650 if (isa<ConstantSDNode>(Offset))
7651 for (SDNode *Use : BasePtr.getNode()->uses()) {
7652 if (Use == Ptr.getNode())
7655 if (Use->isPredecessorOf(N))
7658 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7663 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7664 if (Op1.getNode() == BasePtr.getNode())
7665 std::swap(Op0, Op1);
7666 assert(Op0.getNode() == BasePtr.getNode() &&
7667 "Use of ADD/SUB but not an operand");
7669 if (!isa<ConstantSDNode>(Op1)) {
7674 // FIXME: In some cases, we can be smarter about this.
7675 if (Op1.getValueType() != Offset.getValueType()) {
7680 OtherUses.push_back(Use);
7684 std::swap(BasePtr, Offset);
7686 // Now check for #3 and #4.
7687 bool RealUse = false;
7689 // Caches for hasPredecessorHelper
7690 SmallPtrSet<const SDNode *, 32> Visited;
7691 SmallVector<const SDNode *, 16> Worklist;
7693 for (SDNode *Use : Ptr.getNode()->uses()) {
7696 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7699 // If Ptr may be folded in addressing mode of other use, then it's
7700 // not profitable to do this transformation.
7701 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7710 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7711 BasePtr, Offset, AM);
7713 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7714 BasePtr, Offset, AM);
7717 DEBUG(dbgs() << "\nReplacing.4 ";
7719 dbgs() << "\nWith: ";
7720 Result.getNode()->dump(&DAG);
7722 WorkListRemover DeadNodes(*this);
7724 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7725 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7727 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7730 // Finally, since the node is now dead, remove it from the graph.
7734 std::swap(BasePtr, Offset);
7736 // Replace other uses of BasePtr that can be updated to use Ptr
7737 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7738 unsigned OffsetIdx = 1;
7739 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7741 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7742 BasePtr.getNode() && "Expected BasePtr operand");
7744 // We need to replace ptr0 in the following expression:
7745 // x0 * offset0 + y0 * ptr0 = t0
7747 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7749 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7750 // indexed load/store and the expresion that needs to be re-written.
7752 // Therefore, we have:
7753 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7755 ConstantSDNode *CN =
7756 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7758 APInt Offset0 = CN->getAPIntValue();
7759 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7761 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7762 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7763 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7764 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7766 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7768 APInt CNV = Offset0;
7769 if (X0 < 0) CNV = -CNV;
7770 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7771 else CNV = CNV - Offset1;
7773 // We can now generate the new expression.
7774 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7775 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7777 SDValue NewUse = DAG.getNode(Opcode,
7778 SDLoc(OtherUses[i]),
7779 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7780 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7781 removeFromWorkList(OtherUses[i]);
7782 DAG.DeleteNode(OtherUses[i]);
7785 // Replace the uses of Ptr with uses of the updated base value.
7786 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7787 removeFromWorkList(Ptr.getNode());
7788 DAG.DeleteNode(Ptr.getNode());
7793 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7794 /// add / sub of the base pointer node into a post-indexed load / store.
7795 /// The transformation folded the add / subtract into the new indexed
7796 /// load / store effectively and all of its uses are redirected to the
7797 /// new load / store.
7798 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7799 if (Level < AfterLegalizeDAG)
7805 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7806 if (LD->isIndexed())
7808 VT = LD->getMemoryVT();
7809 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7810 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7812 Ptr = LD->getBasePtr();
7813 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7814 if (ST->isIndexed())
7816 VT = ST->getMemoryVT();
7817 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7818 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7820 Ptr = ST->getBasePtr();
7826 if (Ptr.getNode()->hasOneUse())
7829 for (SDNode *Op : Ptr.getNode()->uses()) {
7831 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7836 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7837 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7838 // Don't create a indexed load / store with zero offset.
7839 if (isa<ConstantSDNode>(Offset) &&
7840 cast<ConstantSDNode>(Offset)->isNullValue())
7843 // Try turning it into a post-indexed load / store except when
7844 // 1) All uses are load / store ops that use it as base ptr (and
7845 // it may be folded as addressing mmode).
7846 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7847 // nor a successor of N. Otherwise, if Op is folded that would
7850 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7854 bool TryNext = false;
7855 for (SDNode *Use : BasePtr.getNode()->uses()) {
7856 if (Use == Ptr.getNode())
7859 // If all the uses are load / store addresses, then don't do the
7861 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7862 bool RealUse = false;
7863 for (SDNode *UseUse : Use->uses()) {
7864 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7879 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7880 SDValue Result = isLoad
7881 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7882 BasePtr, Offset, AM)
7883 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7884 BasePtr, Offset, AM);
7887 DEBUG(dbgs() << "\nReplacing.5 ";
7889 dbgs() << "\nWith: ";
7890 Result.getNode()->dump(&DAG);
7892 WorkListRemover DeadNodes(*this);
7894 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7895 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7897 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7900 // Finally, since the node is now dead, remove it from the graph.
7903 // Replace the uses of Use with uses of the updated base value.
7904 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7905 Result.getValue(isLoad ? 1 : 0));
7906 removeFromWorkList(Op);
7916 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7917 LoadSDNode *LD = cast<LoadSDNode>(N);
7918 SDValue Chain = LD->getChain();
7919 SDValue Ptr = LD->getBasePtr();
7921 // If load is not volatile and there are no uses of the loaded value (and
7922 // the updated indexed value in case of indexed loads), change uses of the
7923 // chain value into uses of the chain input (i.e. delete the dead load).
7924 if (!LD->isVolatile()) {
7925 if (N->getValueType(1) == MVT::Other) {
7927 if (!N->hasAnyUseOfValue(0)) {
7928 // It's not safe to use the two value CombineTo variant here. e.g.
7929 // v1, chain2 = load chain1, loc
7930 // v2, chain3 = load chain2, loc
7932 // Now we replace use of chain2 with chain1. This makes the second load
7933 // isomorphic to the one we are deleting, and thus makes this load live.
7934 DEBUG(dbgs() << "\nReplacing.6 ";
7936 dbgs() << "\nWith chain: ";
7937 Chain.getNode()->dump(&DAG);
7939 WorkListRemover DeadNodes(*this);
7940 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7942 if (N->use_empty()) {
7943 removeFromWorkList(N);
7947 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7951 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7952 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7953 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7954 DEBUG(dbgs() << "\nReplacing.7 ";
7956 dbgs() << "\nWith: ";
7957 Undef.getNode()->dump(&DAG);
7958 dbgs() << " and 2 other values\n");
7959 WorkListRemover DeadNodes(*this);
7960 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7961 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7962 DAG.getUNDEF(N->getValueType(1)));
7963 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7964 removeFromWorkList(N);
7966 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7971 // If this load is directly stored, replace the load value with the stored
7973 // TODO: Handle store large -> read small portion.
7974 // TODO: Handle TRUNCSTORE/LOADEXT
7975 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7976 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7977 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7978 if (PrevST->getBasePtr() == Ptr &&
7979 PrevST->getValue().getValueType() == N->getValueType(0))
7980 return CombineTo(N, Chain.getOperand(1), Chain);
7984 // Try to infer better alignment information than the load already has.
7985 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7986 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7987 if (Align > LD->getMemOperand()->getBaseAlignment()) {
7989 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7990 LD->getValueType(0),
7991 Chain, Ptr, LD->getPointerInfo(),
7993 LD->isVolatile(), LD->isNonTemporal(), Align,
7995 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8000 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8001 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
8003 if (CombinerAAOnlyFunc.getNumOccurrences() &&
8004 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8007 if (UseAA && LD->isUnindexed()) {
8008 // Walk up chain skipping non-aliasing memory nodes.
8009 SDValue BetterChain = FindBetterChain(N, Chain);
8011 // If there is a better chain.
8012 if (Chain != BetterChain) {
8015 // Replace the chain to void dependency.
8016 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8017 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8018 BetterChain, Ptr, LD->getMemOperand());
8020 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8021 LD->getValueType(0),
8022 BetterChain, Ptr, LD->getMemoryVT(),
8023 LD->getMemOperand());
8026 // Create token factor to keep old chain connected.
8027 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8028 MVT::Other, Chain, ReplLoad.getValue(1));
8030 // Make sure the new and old chains are cleaned up.
8031 AddToWorkList(Token.getNode());
8033 // Replace uses with load result and token factor. Don't add users
8035 return CombineTo(N, ReplLoad.getValue(0), Token, false);
8039 // Try transforming N to an indexed load.
8040 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8041 return SDValue(N, 0);
8043 // Try to slice up N to more direct loads if the slices are mapped to
8044 // different register banks or pairing can take place.
8046 return SDValue(N, 0);
8052 /// \brief Helper structure used to slice a load in smaller loads.
8053 /// Basically a slice is obtained from the following sequence:
8054 /// Origin = load Ty1, Base
8055 /// Shift = srl Ty1 Origin, CstTy Amount
8056 /// Inst = trunc Shift to Ty2
8058 /// Then, it will be rewriten into:
8059 /// Slice = load SliceTy, Base + SliceOffset
8060 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8062 /// SliceTy is deduced from the number of bits that are actually used to
8064 struct LoadedSlice {
8065 /// \brief Helper structure used to compute the cost of a slice.
8067 /// Are we optimizing for code size.
8072 unsigned CrossRegisterBanksCopies;
8076 Cost(bool ForCodeSize = false)
8077 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8078 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8080 /// \brief Get the cost of one isolated slice.
8081 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8082 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8083 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8084 EVT TruncType = LS.Inst->getValueType(0);
8085 EVT LoadedType = LS.getLoadedType();
8086 if (TruncType != LoadedType &&
8087 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8091 /// \brief Account for slicing gain in the current cost.
8092 /// Slicing provide a few gains like removing a shift or a
8093 /// truncate. This method allows to grow the cost of the original
8094 /// load with the gain from this slice.
8095 void addSliceGain(const LoadedSlice &LS) {
8096 // Each slice saves a truncate.
8097 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8098 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8099 LS.Inst->getOperand(0).getValueType()))
8101 // If there is a shift amount, this slice gets rid of it.
8104 // If this slice can merge a cross register bank copy, account for it.
8105 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8106 ++CrossRegisterBanksCopies;
8109 Cost &operator+=(const Cost &RHS) {
8111 Truncates += RHS.Truncates;
8112 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8118 bool operator==(const Cost &RHS) const {
8119 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8120 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8121 ZExts == RHS.ZExts && Shift == RHS.Shift;
8124 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8126 bool operator<(const Cost &RHS) const {
8127 // Assume cross register banks copies are as expensive as loads.
8128 // FIXME: Do we want some more target hooks?
8129 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8130 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8131 // Unless we are optimizing for code size, consider the
8132 // expensive operation first.
8133 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8134 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8135 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8136 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8139 bool operator>(const Cost &RHS) const { return RHS < *this; }
8141 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8143 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8145 // The last instruction that represent the slice. This should be a
8146 // truncate instruction.
8148 // The original load instruction.
8150 // The right shift amount in bits from the original load.
8152 // The DAG from which Origin came from.
8153 // This is used to get some contextual information about legal types, etc.
8156 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8157 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8158 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8160 LoadedSlice(const LoadedSlice &LS)
8161 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8163 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8164 /// \return Result is \p BitWidth and has used bits set to 1 and
8165 /// not used bits set to 0.
8166 APInt getUsedBits() const {
8167 // Reproduce the trunc(lshr) sequence:
8168 // - Start from the truncated value.
8169 // - Zero extend to the desired bit width.
8171 assert(Origin && "No original load to compare against.");
8172 unsigned BitWidth = Origin->getValueSizeInBits(0);
8173 assert(Inst && "This slice is not bound to an instruction");
8174 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8175 "Extracted slice is bigger than the whole type!");
8176 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8177 UsedBits.setAllBits();
8178 UsedBits = UsedBits.zext(BitWidth);
8183 /// \brief Get the size of the slice to be loaded in bytes.
8184 unsigned getLoadedSize() const {
8185 unsigned SliceSize = getUsedBits().countPopulation();
8186 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8187 return SliceSize / 8;
8190 /// \brief Get the type that will be loaded for this slice.
8191 /// Note: This may not be the final type for the slice.
8192 EVT getLoadedType() const {
8193 assert(DAG && "Missing context");
8194 LLVMContext &Ctxt = *DAG->getContext();
8195 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8198 /// \brief Get the alignment of the load used for this slice.
8199 unsigned getAlignment() const {
8200 unsigned Alignment = Origin->getAlignment();
8201 unsigned Offset = getOffsetFromBase();
8203 Alignment = MinAlign(Alignment, Alignment + Offset);
8207 /// \brief Check if this slice can be rewritten with legal operations.
8208 bool isLegal() const {
8209 // An invalid slice is not legal.
8210 if (!Origin || !Inst || !DAG)
8213 // Offsets are for indexed load only, we do not handle that.
8214 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8217 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8219 // Check that the type is legal.
8220 EVT SliceType = getLoadedType();
8221 if (!TLI.isTypeLegal(SliceType))
8224 // Check that the load is legal for this type.
8225 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8228 // Check that the offset can be computed.
8229 // 1. Check its type.
8230 EVT PtrType = Origin->getBasePtr().getValueType();
8231 if (PtrType == MVT::Untyped || PtrType.isExtended())
8234 // 2. Check that it fits in the immediate.
8235 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8238 // 3. Check that the computation is legal.
8239 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8242 // Check that the zext is legal if it needs one.
8243 EVT TruncateType = Inst->getValueType(0);
8244 if (TruncateType != SliceType &&
8245 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8251 /// \brief Get the offset in bytes of this slice in the original chunk of
8253 /// \pre DAG != nullptr.
8254 uint64_t getOffsetFromBase() const {
8255 assert(DAG && "Missing context.");
8257 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8258 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8259 uint64_t Offset = Shift / 8;
8260 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8261 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8262 "The size of the original loaded type is not a multiple of a"
8264 // If Offset is bigger than TySizeInBytes, it means we are loading all
8265 // zeros. This should have been optimized before in the process.
8266 assert(TySizeInBytes > Offset &&
8267 "Invalid shift amount for given loaded size");
8269 Offset = TySizeInBytes - Offset - getLoadedSize();
8273 /// \brief Generate the sequence of instructions to load the slice
8274 /// represented by this object and redirect the uses of this slice to
8275 /// this new sequence of instructions.
8276 /// \pre this->Inst && this->Origin are valid Instructions and this
8277 /// object passed the legal check: LoadedSlice::isLegal returned true.
8278 /// \return The last instruction of the sequence used to load the slice.
8279 SDValue loadSlice() const {
8280 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8281 const SDValue &OldBaseAddr = Origin->getBasePtr();
8282 SDValue BaseAddr = OldBaseAddr;
8283 // Get the offset in that chunk of bytes w.r.t. the endianess.
8284 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8285 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8287 // BaseAddr = BaseAddr + Offset.
8288 EVT ArithType = BaseAddr.getValueType();
8289 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8290 DAG->getConstant(Offset, ArithType));
8293 // Create the type of the loaded slice according to its size.
8294 EVT SliceType = getLoadedType();
8296 // Create the load for the slice.
8297 SDValue LastInst = DAG->getLoad(
8298 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8299 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8300 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8301 // If the final type is not the same as the loaded type, this means that
8302 // we have to pad with zero. Create a zero extend for that.
8303 EVT FinalType = Inst->getValueType(0);
8304 if (SliceType != FinalType)
8306 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8310 /// \brief Check if this slice can be merged with an expensive cross register
8311 /// bank copy. E.g.,
8313 /// f = bitcast i32 i to float
8314 bool canMergeExpensiveCrossRegisterBankCopy() const {
8315 if (!Inst || !Inst->hasOneUse())
8317 SDNode *Use = *Inst->use_begin();
8318 if (Use->getOpcode() != ISD::BITCAST)
8320 assert(DAG && "Missing context");
8321 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8322 EVT ResVT = Use->getValueType(0);
8323 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8324 const TargetRegisterClass *ArgRC =
8325 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8326 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8329 // At this point, we know that we perform a cross-register-bank copy.
8330 // Check if it is expensive.
8331 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8332 // Assume bitcasts are cheap, unless both register classes do not
8333 // explicitly share a common sub class.
8334 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8337 // Check if it will be merged with the load.
8338 // 1. Check the alignment constraint.
8339 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8340 ResVT.getTypeForEVT(*DAG->getContext()));
8342 if (RequiredAlignment > getAlignment())
8345 // 2. Check that the load is a legal operation for that type.
8346 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8349 // 3. Check that we do not have a zext in the way.
8350 if (Inst->getValueType(0) != getLoadedType())
8358 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8359 /// \p UsedBits looks like 0..0 1..1 0..0.
8360 static bool areUsedBitsDense(const APInt &UsedBits) {
8361 // If all the bits are one, this is dense!
8362 if (UsedBits.isAllOnesValue())
8365 // Get rid of the unused bits on the right.
8366 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8367 // Get rid of the unused bits on the left.
8368 if (NarrowedUsedBits.countLeadingZeros())
8369 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8370 // Check that the chunk of bits is completely used.
8371 return NarrowedUsedBits.isAllOnesValue();
8374 /// \brief Check whether or not \p First and \p Second are next to each other
8375 /// in memory. This means that there is no hole between the bits loaded
8376 /// by \p First and the bits loaded by \p Second.
8377 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8378 const LoadedSlice &Second) {
8379 assert(First.Origin == Second.Origin && First.Origin &&
8380 "Unable to match different memory origins.");
8381 APInt UsedBits = First.getUsedBits();
8382 assert((UsedBits & Second.getUsedBits()) == 0 &&
8383 "Slices are not supposed to overlap.");
8384 UsedBits |= Second.getUsedBits();
8385 return areUsedBitsDense(UsedBits);
8388 /// \brief Adjust the \p GlobalLSCost according to the target
8389 /// paring capabilities and the layout of the slices.
8390 /// \pre \p GlobalLSCost should account for at least as many loads as
8391 /// there is in the slices in \p LoadedSlices.
8392 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8393 LoadedSlice::Cost &GlobalLSCost) {
8394 unsigned NumberOfSlices = LoadedSlices.size();
8395 // If there is less than 2 elements, no pairing is possible.
8396 if (NumberOfSlices < 2)
8399 // Sort the slices so that elements that are likely to be next to each
8400 // other in memory are next to each other in the list.
8401 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8402 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8403 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8404 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8406 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8407 // First (resp. Second) is the first (resp. Second) potentially candidate
8408 // to be placed in a paired load.
8409 const LoadedSlice *First = nullptr;
8410 const LoadedSlice *Second = nullptr;
8411 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8412 // Set the beginning of the pair.
8415 Second = &LoadedSlices[CurrSlice];
8417 // If First is NULL, it means we start a new pair.
8418 // Get to the next slice.
8422 EVT LoadedType = First->getLoadedType();
8424 // If the types of the slices are different, we cannot pair them.
8425 if (LoadedType != Second->getLoadedType())
8428 // Check if the target supplies paired loads for this type.
8429 unsigned RequiredAlignment = 0;
8430 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8431 // move to the next pair, this type is hopeless.
8435 // Check if we meet the alignment requirement.
8436 if (RequiredAlignment > First->getAlignment())
8439 // Check that both loads are next to each other in memory.
8440 if (!areSlicesNextToEachOther(*First, *Second))
8443 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8444 --GlobalLSCost.Loads;
8445 // Move to the next pair.
8450 /// \brief Check the profitability of all involved LoadedSlice.
8451 /// Currently, it is considered profitable if there is exactly two
8452 /// involved slices (1) which are (2) next to each other in memory, and
8453 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8455 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8456 /// the elements themselves.
8458 /// FIXME: When the cost model will be mature enough, we can relax
8459 /// constraints (1) and (2).
8460 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8461 const APInt &UsedBits, bool ForCodeSize) {
8462 unsigned NumberOfSlices = LoadedSlices.size();
8463 if (StressLoadSlicing)
8464 return NumberOfSlices > 1;
8467 if (NumberOfSlices != 2)
8471 if (!areUsedBitsDense(UsedBits))
8475 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8476 // The original code has one big load.
8478 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8479 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8480 // Accumulate the cost of all the slices.
8481 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8482 GlobalSlicingCost += SliceCost;
8484 // Account as cost in the original configuration the gain obtained
8485 // with the current slices.
8486 OrigCost.addSliceGain(LS);
8489 // If the target supports paired load, adjust the cost accordingly.
8490 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8491 return OrigCost > GlobalSlicingCost;
8494 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8495 /// operations, split it in the various pieces being extracted.
8497 /// This sort of thing is introduced by SROA.
8498 /// This slicing takes care not to insert overlapping loads.
8499 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8500 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8501 if (Level < AfterLegalizeDAG)
8504 LoadSDNode *LD = cast<LoadSDNode>(N);
8505 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8506 !LD->getValueType(0).isInteger())
8509 // Keep track of already used bits to detect overlapping values.
8510 // In that case, we will just abort the transformation.
8511 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8513 SmallVector<LoadedSlice, 4> LoadedSlices;
8515 // Check if this load is used as several smaller chunks of bits.
8516 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8517 // of computation for each trunc.
8518 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8519 UI != UIEnd; ++UI) {
8520 // Skip the uses of the chain.
8521 if (UI.getUse().getResNo() != 0)
8527 // Check if this is a trunc(lshr).
8528 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8529 isa<ConstantSDNode>(User->getOperand(1))) {
8530 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8531 User = *User->use_begin();
8534 // At this point, User is a Truncate, iff we encountered, trunc or
8536 if (User->getOpcode() != ISD::TRUNCATE)
8539 // The width of the type must be a power of 2 and greater than 8-bits.
8540 // Otherwise the load cannot be represented in LLVM IR.
8541 // Moreover, if we shifted with a non-8-bits multiple, the slice
8542 // will be across several bytes. We do not support that.
8543 unsigned Width = User->getValueSizeInBits(0);
8544 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8547 // Build the slice for this chain of computations.
8548 LoadedSlice LS(User, LD, Shift, &DAG);
8549 APInt CurrentUsedBits = LS.getUsedBits();
8551 // Check if this slice overlaps with another.
8552 if ((CurrentUsedBits & UsedBits) != 0)
8554 // Update the bits used globally.
8555 UsedBits |= CurrentUsedBits;
8557 // Check if the new slice would be legal.
8561 // Record the slice.
8562 LoadedSlices.push_back(LS);
8565 // Abort slicing if it does not seem to be profitable.
8566 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8571 // Rewrite each chain to use an independent load.
8572 // By construction, each chain can be represented by a unique load.
8574 // Prepare the argument for the new token factor for all the slices.
8575 SmallVector<SDValue, 8> ArgChains;
8576 for (SmallVectorImpl<LoadedSlice>::const_iterator
8577 LSIt = LoadedSlices.begin(),
8578 LSItEnd = LoadedSlices.end();
8579 LSIt != LSItEnd; ++LSIt) {
8580 SDValue SliceInst = LSIt->loadSlice();
8581 CombineTo(LSIt->Inst, SliceInst, true);
8582 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8583 SliceInst = SliceInst.getOperand(0);
8584 assert(SliceInst->getOpcode() == ISD::LOAD &&
8585 "It takes more than a zext to get to the loaded slice!!");
8586 ArgChains.push_back(SliceInst.getValue(1));
8589 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8591 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8595 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8596 /// load is having specific bytes cleared out. If so, return the byte size
8597 /// being masked out and the shift amount.
8598 static std::pair<unsigned, unsigned>
8599 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8600 std::pair<unsigned, unsigned> Result(0, 0);
8602 // Check for the structure we're looking for.
8603 if (V->getOpcode() != ISD::AND ||
8604 !isa<ConstantSDNode>(V->getOperand(1)) ||
8605 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8608 // Check the chain and pointer.
8609 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8610 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
8612 // The store should be chained directly to the load or be an operand of a
8614 if (LD == Chain.getNode())
8616 else if (Chain->getOpcode() != ISD::TokenFactor)
8617 return Result; // Fail.
8620 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8621 if (Chain->getOperand(i).getNode() == LD) {
8625 if (!isOk) return Result;
8628 // This only handles simple types.
8629 if (V.getValueType() != MVT::i16 &&
8630 V.getValueType() != MVT::i32 &&
8631 V.getValueType() != MVT::i64)
8634 // Check the constant mask. Invert it so that the bits being masked out are
8635 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8636 // follow the sign bit for uniformity.
8637 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8638 unsigned NotMaskLZ = countLeadingZeros(NotMask);
8639 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
8640 unsigned NotMaskTZ = countTrailingZeros(NotMask);
8641 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8642 if (NotMaskLZ == 64) return Result; // All zero mask.
8644 // See if we have a continuous run of bits. If so, we have 0*1+0*
8645 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8648 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8649 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8650 NotMaskLZ -= 64-V.getValueSizeInBits();
8652 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8653 switch (MaskedBytes) {
8657 default: return Result; // All one mask, or 5-byte mask.
8660 // Verify that the first bit starts at a multiple of mask so that the access
8661 // is aligned the same as the access width.
8662 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8664 Result.first = MaskedBytes;
8665 Result.second = NotMaskTZ/8;
8670 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8671 /// provides a value as specified by MaskInfo. If so, replace the specified
8672 /// store with a narrower store of truncated IVal.
8674 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8675 SDValue IVal, StoreSDNode *St,
8677 unsigned NumBytes = MaskInfo.first;
8678 unsigned ByteShift = MaskInfo.second;
8679 SelectionDAG &DAG = DC->getDAG();
8681 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8682 // that uses this. If not, this is not a replacement.
8683 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8684 ByteShift*8, (ByteShift+NumBytes)*8);
8685 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8687 // Check that it is legal on the target to do this. It is legal if the new
8688 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8690 MVT VT = MVT::getIntegerVT(NumBytes*8);
8691 if (!DC->isTypeLegal(VT))
8694 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8695 // shifted by ByteShift and truncated down to NumBytes.
8697 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8698 DAG.getConstant(ByteShift*8,
8699 DC->getShiftAmountTy(IVal.getValueType())));
8701 // Figure out the offset for the store and the alignment of the access.
8703 unsigned NewAlign = St->getAlignment();
8705 if (DAG.getTargetLoweringInfo().isLittleEndian())
8706 StOffset = ByteShift;
8708 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8710 SDValue Ptr = St->getBasePtr();
8712 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8713 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8714 NewAlign = MinAlign(NewAlign, StOffset);
8717 // Truncate down to the new size.
8718 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8721 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8722 St->getPointerInfo().getWithOffset(StOffset),
8723 false, false, NewAlign).getNode();
8727 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8728 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8729 /// of the loaded bits, try narrowing the load and store if it would end up
8730 /// being a win for performance or code size.
8731 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8732 StoreSDNode *ST = cast<StoreSDNode>(N);
8733 if (ST->isVolatile())
8736 SDValue Chain = ST->getChain();
8737 SDValue Value = ST->getValue();
8738 SDValue Ptr = ST->getBasePtr();
8739 EVT VT = Value.getValueType();
8741 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8744 unsigned Opc = Value.getOpcode();
8746 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8747 // is a byte mask indicating a consecutive number of bytes, check to see if
8748 // Y is known to provide just those bytes. If so, we try to replace the
8749 // load + replace + store sequence with a single (narrower) store, which makes
8751 if (Opc == ISD::OR) {
8752 std::pair<unsigned, unsigned> MaskedLoad;
8753 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8754 if (MaskedLoad.first)
8755 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8756 Value.getOperand(1), ST,this))
8757 return SDValue(NewST, 0);
8759 // Or is commutative, so try swapping X and Y.
8760 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8761 if (MaskedLoad.first)
8762 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8763 Value.getOperand(0), ST,this))
8764 return SDValue(NewST, 0);
8767 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8768 Value.getOperand(1).getOpcode() != ISD::Constant)
8771 SDValue N0 = Value.getOperand(0);
8772 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8773 Chain == SDValue(N0.getNode(), 1)) {
8774 LoadSDNode *LD = cast<LoadSDNode>(N0);
8775 if (LD->getBasePtr() != Ptr ||
8776 LD->getPointerInfo().getAddrSpace() !=
8777 ST->getPointerInfo().getAddrSpace())
8780 // Find the type to narrow it the load / op / store to.
8781 SDValue N1 = Value.getOperand(1);
8782 unsigned BitWidth = N1.getValueSizeInBits();
8783 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8784 if (Opc == ISD::AND)
8785 Imm ^= APInt::getAllOnesValue(BitWidth);
8786 if (Imm == 0 || Imm.isAllOnesValue())
8788 unsigned ShAmt = Imm.countTrailingZeros();
8789 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8790 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8791 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8792 while (NewBW < BitWidth &&
8793 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8794 TLI.isNarrowingProfitable(VT, NewVT))) {
8795 NewBW = NextPowerOf2(NewBW);
8796 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8798 if (NewBW >= BitWidth)
8801 // If the lsb changed does not start at the type bitwidth boundary,
8802 // start at the previous one.
8804 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8805 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8806 std::min(BitWidth, ShAmt + NewBW));
8807 if ((Imm & Mask) == Imm) {
8808 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8809 if (Opc == ISD::AND)
8810 NewImm ^= APInt::getAllOnesValue(NewBW);
8811 uint64_t PtrOff = ShAmt / 8;
8812 // For big endian targets, we need to adjust the offset to the pointer to
8813 // load the correct bytes.
8814 if (TLI.isBigEndian())
8815 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8817 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8818 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8819 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8822 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8823 Ptr.getValueType(), Ptr,
8824 DAG.getConstant(PtrOff, Ptr.getValueType()));
8825 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8826 LD->getChain(), NewPtr,
8827 LD->getPointerInfo().getWithOffset(PtrOff),
8828 LD->isVolatile(), LD->isNonTemporal(),
8829 LD->isInvariant(), NewAlign,
8831 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8832 DAG.getConstant(NewImm, NewVT));
8833 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8835 ST->getPointerInfo().getWithOffset(PtrOff),
8836 false, false, NewAlign);
8838 AddToWorkList(NewPtr.getNode());
8839 AddToWorkList(NewLD.getNode());
8840 AddToWorkList(NewVal.getNode());
8841 WorkListRemover DeadNodes(*this);
8842 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8851 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8852 /// if the load value isn't used by any other operations, then consider
8853 /// transforming the pair to integer load / store operations if the target
8854 /// deems the transformation profitable.
8855 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8856 StoreSDNode *ST = cast<StoreSDNode>(N);
8857 SDValue Chain = ST->getChain();
8858 SDValue Value = ST->getValue();
8859 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8860 Value.hasOneUse() &&
8861 Chain == SDValue(Value.getNode(), 1)) {
8862 LoadSDNode *LD = cast<LoadSDNode>(Value);
8863 EVT VT = LD->getMemoryVT();
8864 if (!VT.isFloatingPoint() ||
8865 VT != ST->getMemoryVT() ||
8866 LD->isNonTemporal() ||
8867 ST->isNonTemporal() ||
8868 LD->getPointerInfo().getAddrSpace() != 0 ||
8869 ST->getPointerInfo().getAddrSpace() != 0)
8872 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8873 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8874 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8875 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8876 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8879 unsigned LDAlign = LD->getAlignment();
8880 unsigned STAlign = ST->getAlignment();
8881 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8882 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8883 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8886 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8887 LD->getChain(), LD->getBasePtr(),
8888 LD->getPointerInfo(),
8889 false, false, false, LDAlign);
8891 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8892 NewLD, ST->getBasePtr(),
8893 ST->getPointerInfo(),
8894 false, false, STAlign);
8896 AddToWorkList(NewLD.getNode());
8897 AddToWorkList(NewST.getNode());
8898 WorkListRemover DeadNodes(*this);
8899 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8907 /// Helper struct to parse and store a memory address as base + index + offset.
8908 /// We ignore sign extensions when it is safe to do so.
8909 /// The following two expressions are not equivalent. To differentiate we need
8910 /// to store whether there was a sign extension involved in the index
8912 /// (load (i64 add (i64 copyfromreg %c)
8913 /// (i64 signextend (add (i8 load %index)
8917 /// (load (i64 add (i64 copyfromreg %c)
8918 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8920 struct BaseIndexOffset {
8924 bool IsIndexSignExt;
8926 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8928 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8929 bool IsIndexSignExt) :
8930 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8932 bool equalBaseIndex(const BaseIndexOffset &Other) {
8933 return Other.Base == Base && Other.Index == Index &&
8934 Other.IsIndexSignExt == IsIndexSignExt;
8937 /// Parses tree in Ptr for base, index, offset addresses.
8938 static BaseIndexOffset match(SDValue Ptr) {
8939 bool IsIndexSignExt = false;
8941 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8942 // instruction, then it could be just the BASE or everything else we don't
8943 // know how to handle. Just use Ptr as BASE and give up.
8944 if (Ptr->getOpcode() != ISD::ADD)
8945 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8947 // We know that we have at least an ADD instruction. Try to pattern match
8948 // the simple case of BASE + OFFSET.
8949 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8950 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8951 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8955 // Inside a loop the current BASE pointer is calculated using an ADD and a
8956 // MUL instruction. In this case Ptr is the actual BASE pointer.
8957 // (i64 add (i64 %array_ptr)
8958 // (i64 mul (i64 %induction_var)
8959 // (i64 %element_size)))
8960 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8961 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8963 // Look at Base + Index + Offset cases.
8964 SDValue Base = Ptr->getOperand(0);
8965 SDValue IndexOffset = Ptr->getOperand(1);
8967 // Skip signextends.
8968 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8969 IndexOffset = IndexOffset->getOperand(0);
8970 IsIndexSignExt = true;
8973 // Either the case of Base + Index (no offset) or something else.
8974 if (IndexOffset->getOpcode() != ISD::ADD)
8975 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8977 // Now we have the case of Base + Index + offset.
8978 SDValue Index = IndexOffset->getOperand(0);
8979 SDValue Offset = IndexOffset->getOperand(1);
8981 if (!isa<ConstantSDNode>(Offset))
8982 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8984 // Ignore signextends.
8985 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8986 Index = Index->getOperand(0);
8987 IsIndexSignExt = true;
8988 } else IsIndexSignExt = false;
8990 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8991 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8995 /// Holds a pointer to an LSBaseSDNode as well as information on where it
8996 /// is located in a sequence of memory operations connected by a chain.
8998 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8999 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9000 // Ptr to the mem node.
9001 LSBaseSDNode *MemNode;
9002 // Offset from the base ptr.
9003 int64_t OffsetFromBase;
9004 // What is the sequence number of this mem node.
9005 // Lowest mem operand in the DAG starts at zero.
9006 unsigned SequenceNum;
9009 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9010 EVT MemVT = St->getMemoryVT();
9011 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9012 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9013 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9015 // Don't merge vectors into wider inputs.
9016 if (MemVT.isVector() || !MemVT.isSimple())
9019 // Perform an early exit check. Do not bother looking at stored values that
9020 // are not constants or loads.
9021 SDValue StoredVal = St->getValue();
9022 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9023 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9027 // Only look at ends of store sequences.
9028 SDValue Chain = SDValue(St, 1);
9029 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9032 // This holds the base pointer, index, and the offset in bytes from the base
9034 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9036 // We must have a base and an offset.
9037 if (!BasePtr.Base.getNode())
9040 // Do not handle stores to undef base pointers.
9041 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9044 // Save the LoadSDNodes that we find in the chain.
9045 // We need to make sure that these nodes do not interfere with
9046 // any of the store nodes.
9047 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9049 // Save the StoreSDNodes that we find in the chain.
9050 SmallVector<MemOpLink, 8> StoreNodes;
9052 // Walk up the chain and look for nodes with offsets from the same
9053 // base pointer. Stop when reaching an instruction with a different kind
9054 // or instruction which has a different base pointer.
9056 StoreSDNode *Index = St;
9058 // If the chain has more than one use, then we can't reorder the mem ops.
9059 if (Index != St && !SDValue(Index, 1)->hasOneUse())
9062 // Find the base pointer and offset for this memory node.
9063 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9065 // Check that the base pointer is the same as the original one.
9066 if (!Ptr.equalBaseIndex(BasePtr))
9069 // Check that the alignment is the same.
9070 if (Index->getAlignment() != St->getAlignment())
9073 // The memory operands must not be volatile.
9074 if (Index->isVolatile() || Index->isIndexed())
9078 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9079 if (St->isTruncatingStore())
9082 // The stored memory type must be the same.
9083 if (Index->getMemoryVT() != MemVT)
9086 // We do not allow unaligned stores because we want to prevent overriding
9088 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9091 // We found a potential memory operand to merge.
9092 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9094 // Find the next memory operand in the chain. If the next operand in the
9095 // chain is a store then move up and continue the scan with the next
9096 // memory operand. If the next operand is a load save it and use alias
9097 // information to check if it interferes with anything.
9098 SDNode *NextInChain = Index->getChain().getNode();
9100 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9101 // We found a store node. Use it for the next iteration.
9104 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9105 if (Ldn->isVolatile()) {
9110 // Save the load node for later. Continue the scan.
9111 AliasLoadNodes.push_back(Ldn);
9112 NextInChain = Ldn->getChain().getNode();
9121 // Check if there is anything to merge.
9122 if (StoreNodes.size() < 2)
9125 // Sort the memory operands according to their distance from the base pointer.
9126 std::sort(StoreNodes.begin(), StoreNodes.end(),
9127 [](MemOpLink LHS, MemOpLink RHS) {
9128 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9129 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9130 LHS.SequenceNum > RHS.SequenceNum);
9133 // Scan the memory operations on the chain and find the first non-consecutive
9134 // store memory address.
9135 unsigned LastConsecutiveStore = 0;
9136 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9137 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9139 // Check that the addresses are consecutive starting from the second
9140 // element in the list of stores.
9142 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9143 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9148 // Check if this store interferes with any of the loads that we found.
9149 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9150 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9154 // We found a load that alias with this store. Stop the sequence.
9158 // Mark this node as useful.
9159 LastConsecutiveStore = i;
9162 // The node with the lowest store address.
9163 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9165 // Store the constants into memory as one consecutive store.
9167 unsigned LastLegalType = 0;
9168 unsigned LastLegalVectorType = 0;
9169 bool NonZero = false;
9170 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9171 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9172 SDValue StoredVal = St->getValue();
9174 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9175 NonZero |= !C->isNullValue();
9176 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9177 NonZero |= !C->getConstantFPValue()->isNullValue();
9183 // Find a legal type for the constant store.
9184 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9185 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9186 if (TLI.isTypeLegal(StoreTy))
9187 LastLegalType = i+1;
9188 // Or check whether a truncstore is legal.
9189 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9190 TargetLowering::TypePromoteInteger) {
9191 EVT LegalizedStoredValueTy =
9192 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9193 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9194 LastLegalType = i+1;
9197 // Find a legal type for the vector store.
9198 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9199 if (TLI.isTypeLegal(Ty))
9200 LastLegalVectorType = i + 1;
9203 // We only use vectors if the constant is known to be zero and the
9204 // function is not marked with the noimplicitfloat attribute.
9205 if (NonZero || NoVectors)
9206 LastLegalVectorType = 0;
9208 // Check if we found a legal integer type to store.
9209 if (LastLegalType == 0 && LastLegalVectorType == 0)
9212 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9213 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9215 // Make sure we have something to merge.
9219 unsigned EarliestNodeUsed = 0;
9220 for (unsigned i=0; i < NumElem; ++i) {
9221 // Find a chain for the new wide-store operand. Notice that some
9222 // of the store nodes that we found may not be selected for inclusion
9223 // in the wide store. The chain we use needs to be the chain of the
9224 // earliest store node which is *used* and replaced by the wide store.
9225 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9226 EarliestNodeUsed = i;
9229 // The earliest Node in the DAG.
9230 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9231 SDLoc DL(StoreNodes[0].MemNode);
9235 // Find a legal type for the vector store.
9236 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9237 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9238 StoredVal = DAG.getConstant(0, Ty);
9240 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9241 APInt StoreInt(StoreBW, 0);
9243 // Construct a single integer constant which is made of the smaller
9245 bool IsLE = TLI.isLittleEndian();
9246 for (unsigned i = 0; i < NumElem ; ++i) {
9247 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9248 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9249 SDValue Val = St->getValue();
9250 StoreInt<<=ElementSizeBytes*8;
9251 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9252 StoreInt|=C->getAPIntValue().zext(StoreBW);
9253 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9254 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9256 assert(false && "Invalid constant element type");
9260 // Create the new Load and Store operations.
9261 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9262 StoredVal = DAG.getConstant(StoreInt, StoreTy);
9265 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9266 FirstInChain->getBasePtr(),
9267 FirstInChain->getPointerInfo(),
9269 FirstInChain->getAlignment());
9271 // Replace the first store with the new store
9272 CombineTo(EarliestOp, NewStore);
9273 // Erase all other stores.
9274 for (unsigned i = 0; i < NumElem ; ++i) {
9275 if (StoreNodes[i].MemNode == EarliestOp)
9277 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9278 // ReplaceAllUsesWith will replace all uses that existed when it was
9279 // called, but graph optimizations may cause new ones to appear. For
9280 // example, the case in pr14333 looks like
9282 // St's chain -> St -> another store -> X
9284 // And the only difference from St to the other store is the chain.
9285 // When we change it's chain to be St's chain they become identical,
9286 // get CSEed and the net result is that X is now a use of St.
9287 // Since we know that St is redundant, just iterate.
9288 while (!St->use_empty())
9289 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9290 removeFromWorkList(St);
9297 // Below we handle the case of multiple consecutive stores that
9298 // come from multiple consecutive loads. We merge them into a single
9299 // wide load and a single wide store.
9301 // Look for load nodes which are used by the stored values.
9302 SmallVector<MemOpLink, 8> LoadNodes;
9304 // Find acceptable loads. Loads need to have the same chain (token factor),
9305 // must not be zext, volatile, indexed, and they must be consecutive.
9306 BaseIndexOffset LdBasePtr;
9307 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9308 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9309 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9312 // Loads must only have one use.
9313 if (!Ld->hasNUsesOfValue(1, 0))
9316 // Check that the alignment is the same as the stores.
9317 if (Ld->getAlignment() != St->getAlignment())
9320 // The memory operands must not be volatile.
9321 if (Ld->isVolatile() || Ld->isIndexed())
9324 // We do not accept ext loads.
9325 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9328 // The stored memory type must be the same.
9329 if (Ld->getMemoryVT() != MemVT)
9332 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9333 // If this is not the first ptr that we check.
9334 if (LdBasePtr.Base.getNode()) {
9335 // The base ptr must be the same.
9336 if (!LdPtr.equalBaseIndex(LdBasePtr))
9339 // Check that all other base pointers are the same as this one.
9343 // We found a potential memory operand to merge.
9344 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9347 if (LoadNodes.size() < 2)
9350 // Scan the memory operations on the chain and find the first non-consecutive
9351 // load memory address. These variables hold the index in the store node
9353 unsigned LastConsecutiveLoad = 0;
9354 // This variable refers to the size and not index in the array.
9355 unsigned LastLegalVectorType = 0;
9356 unsigned LastLegalIntegerType = 0;
9357 StartAddress = LoadNodes[0].OffsetFromBase;
9358 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9359 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9360 // All loads much share the same chain.
9361 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9364 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9365 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9367 LastConsecutiveLoad = i;
9369 // Find a legal type for the vector store.
9370 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9371 if (TLI.isTypeLegal(StoreTy))
9372 LastLegalVectorType = i + 1;
9374 // Find a legal type for the integer store.
9375 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9376 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9377 if (TLI.isTypeLegal(StoreTy))
9378 LastLegalIntegerType = i + 1;
9379 // Or check whether a truncstore and extload is legal.
9380 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9381 TargetLowering::TypePromoteInteger) {
9382 EVT LegalizedStoredValueTy =
9383 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9384 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9385 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9386 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9387 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9388 LastLegalIntegerType = i+1;
9392 // Only use vector types if the vector type is larger than the integer type.
9393 // If they are the same, use integers.
9394 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9395 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9397 // We add +1 here because the LastXXX variables refer to location while
9398 // the NumElem refers to array/index size.
9399 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9400 NumElem = std::min(LastLegalType, NumElem);
9405 // The earliest Node in the DAG.
9406 unsigned EarliestNodeUsed = 0;
9407 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9408 for (unsigned i=1; i<NumElem; ++i) {
9409 // Find a chain for the new wide-store operand. Notice that some
9410 // of the store nodes that we found may not be selected for inclusion
9411 // in the wide store. The chain we use needs to be the chain of the
9412 // earliest store node which is *used* and replaced by the wide store.
9413 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9414 EarliestNodeUsed = i;
9417 // Find if it is better to use vectors or integers to load and store
9421 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9423 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9424 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9427 SDLoc LoadDL(LoadNodes[0].MemNode);
9428 SDLoc StoreDL(StoreNodes[0].MemNode);
9430 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9431 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9432 FirstLoad->getChain(),
9433 FirstLoad->getBasePtr(),
9434 FirstLoad->getPointerInfo(),
9435 false, false, false,
9436 FirstLoad->getAlignment());
9438 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9439 FirstInChain->getBasePtr(),
9440 FirstInChain->getPointerInfo(), false, false,
9441 FirstInChain->getAlignment());
9443 // Replace one of the loads with the new load.
9444 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9445 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9446 SDValue(NewLoad.getNode(), 1));
9448 // Remove the rest of the load chains.
9449 for (unsigned i = 1; i < NumElem ; ++i) {
9450 // Replace all chain users of the old load nodes with the chain of the new
9452 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9453 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9456 // Replace the first store with the new store.
9457 CombineTo(EarliestOp, NewStore);
9458 // Erase all other stores.
9459 for (unsigned i = 0; i < NumElem ; ++i) {
9460 // Remove all Store nodes.
9461 if (StoreNodes[i].MemNode == EarliestOp)
9463 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9464 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9465 removeFromWorkList(St);
9472 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9473 StoreSDNode *ST = cast<StoreSDNode>(N);
9474 SDValue Chain = ST->getChain();
9475 SDValue Value = ST->getValue();
9476 SDValue Ptr = ST->getBasePtr();
9478 // If this is a store of a bit convert, store the input value if the
9479 // resultant store does not need a higher alignment than the original.
9480 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9481 ST->isUnindexed()) {
9482 unsigned OrigAlign = ST->getAlignment();
9483 EVT SVT = Value.getOperand(0).getValueType();
9484 unsigned Align = TLI.getDataLayout()->
9485 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9486 if (Align <= OrigAlign &&
9487 ((!LegalOperations && !ST->isVolatile()) ||
9488 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9489 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9490 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9491 ST->isNonTemporal(), OrigAlign,
9495 // Turn 'store undef, Ptr' -> nothing.
9496 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9499 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9500 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9501 // NOTE: If the original store is volatile, this transform must not increase
9502 // the number of stores. For example, on x86-32 an f64 can be stored in one
9503 // processor operation but an i64 (which is not legal) requires two. So the
9504 // transform should not be done in this case.
9505 if (Value.getOpcode() != ISD::TargetConstantFP) {
9507 switch (CFP->getSimpleValueType(0).SimpleTy) {
9508 default: llvm_unreachable("Unknown FP type");
9509 case MVT::f16: // We don't do this for these yet.
9515 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9516 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9517 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9518 bitcastToAPInt().getZExtValue(), MVT::i32);
9519 return DAG.getStore(Chain, SDLoc(N), Tmp,
9520 Ptr, ST->getMemOperand());
9524 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9525 !ST->isVolatile()) ||
9526 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9527 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9528 getZExtValue(), MVT::i64);
9529 return DAG.getStore(Chain, SDLoc(N), Tmp,
9530 Ptr, ST->getMemOperand());
9533 if (!ST->isVolatile() &&
9534 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9535 // Many FP stores are not made apparent until after legalize, e.g. for
9536 // argument passing. Since this is so common, custom legalize the
9537 // 64-bit integer store into two 32-bit stores.
9538 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9539 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9540 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9541 if (TLI.isBigEndian()) std::swap(Lo, Hi);
9543 unsigned Alignment = ST->getAlignment();
9544 bool isVolatile = ST->isVolatile();
9545 bool isNonTemporal = ST->isNonTemporal();
9546 const MDNode *TBAAInfo = ST->getTBAAInfo();
9548 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9549 Ptr, ST->getPointerInfo(),
9550 isVolatile, isNonTemporal,
9551 ST->getAlignment(), TBAAInfo);
9552 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9553 DAG.getConstant(4, Ptr.getValueType()));
9554 Alignment = MinAlign(Alignment, 4U);
9555 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9556 Ptr, ST->getPointerInfo().getWithOffset(4),
9557 isVolatile, isNonTemporal,
9558 Alignment, TBAAInfo);
9559 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9568 // Try to infer better alignment information than the store already has.
9569 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9570 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9571 if (Align > ST->getAlignment())
9572 return DAG.getTruncStore(Chain, SDLoc(N), Value,
9573 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9574 ST->isVolatile(), ST->isNonTemporal(), Align,
9579 // Try transforming a pair floating point load / store ops to integer
9580 // load / store ops.
9581 SDValue NewST = TransformFPLoadStorePair(N);
9582 if (NewST.getNode())
9585 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9586 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9588 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9589 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9592 if (UseAA && ST->isUnindexed()) {
9593 // Walk up chain skipping non-aliasing memory nodes.
9594 SDValue BetterChain = FindBetterChain(N, Chain);
9596 // If there is a better chain.
9597 if (Chain != BetterChain) {
9600 // Replace the chain to avoid dependency.
9601 if (ST->isTruncatingStore()) {
9602 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9603 ST->getMemoryVT(), ST->getMemOperand());
9605 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9606 ST->getMemOperand());
9609 // Create token to keep both nodes around.
9610 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9611 MVT::Other, Chain, ReplStore);
9613 // Make sure the new and old chains are cleaned up.
9614 AddToWorkList(Token.getNode());
9616 // Don't add users to work list.
9617 return CombineTo(N, Token, false);
9621 // Try transforming N to an indexed store.
9622 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9623 return SDValue(N, 0);
9625 // FIXME: is there such a thing as a truncating indexed store?
9626 if (ST->isTruncatingStore() && ST->isUnindexed() &&
9627 Value.getValueType().isInteger()) {
9628 // See if we can simplify the input to this truncstore with knowledge that
9629 // only the low bits are being used. For example:
9630 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
9632 GetDemandedBits(Value,
9633 APInt::getLowBitsSet(
9634 Value.getValueType().getScalarType().getSizeInBits(),
9635 ST->getMemoryVT().getScalarType().getSizeInBits()));
9636 AddToWorkList(Value.getNode());
9637 if (Shorter.getNode())
9638 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9639 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9641 // Otherwise, see if we can simplify the operation with
9642 // SimplifyDemandedBits, which only works if the value has a single use.
9643 if (SimplifyDemandedBits(Value,
9644 APInt::getLowBitsSet(
9645 Value.getValueType().getScalarType().getSizeInBits(),
9646 ST->getMemoryVT().getScalarType().getSizeInBits())))
9647 return SDValue(N, 0);
9650 // If this is a load followed by a store to the same location, then the store
9652 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9653 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9654 ST->isUnindexed() && !ST->isVolatile() &&
9655 // There can't be any side effects between the load and store, such as
9657 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9658 // The store is dead, remove it.
9663 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9664 // truncating store. We can do this even if this is already a truncstore.
9665 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9666 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9667 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9668 ST->getMemoryVT())) {
9669 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9670 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9673 // Only perform this optimization before the types are legal, because we
9674 // don't want to perform this optimization on every DAGCombine invocation.
9676 bool EverChanged = false;
9679 // There can be multiple store sequences on the same chain.
9680 // Keep trying to merge store sequences until we are unable to do so
9681 // or until we merge the last store on the chain.
9682 bool Changed = MergeConsecutiveStores(ST);
9683 EverChanged |= Changed;
9684 if (!Changed) break;
9685 } while (ST->getOpcode() != ISD::DELETED_NODE);
9688 return SDValue(N, 0);
9691 return ReduceLoadOpStoreWidth(N);
9694 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9695 SDValue InVec = N->getOperand(0);
9696 SDValue InVal = N->getOperand(1);
9697 SDValue EltNo = N->getOperand(2);
9700 // If the inserted element is an UNDEF, just use the input vector.
9701 if (InVal.getOpcode() == ISD::UNDEF)
9704 EVT VT = InVec.getValueType();
9706 // If we can't generate a legal BUILD_VECTOR, exit
9707 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9710 // Check that we know which element is being inserted
9711 if (!isa<ConstantSDNode>(EltNo))
9713 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9715 // Canonicalize insert_vector_elt dag nodes.
9717 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9718 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9720 // Do this only if the child insert_vector node has one use; also
9721 // do this only if indices are both constants and Idx1 < Idx0.
9722 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9723 && isa<ConstantSDNode>(InVec.getOperand(2))) {
9725 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9726 if (Elt < OtherElt) {
9728 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9729 InVec.getOperand(0), InVal, EltNo);
9730 AddToWorkList(NewOp.getNode());
9731 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9732 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9736 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9737 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9739 SmallVector<SDValue, 8> Ops;
9740 // Do not combine these two vectors if the output vector will not replace
9741 // the input vector.
9742 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9743 Ops.append(InVec.getNode()->op_begin(),
9744 InVec.getNode()->op_end());
9745 } else if (InVec.getOpcode() == ISD::UNDEF) {
9746 unsigned NElts = VT.getVectorNumElements();
9747 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9752 // Insert the element
9753 if (Elt < Ops.size()) {
9754 // All the operands of BUILD_VECTOR must have the same type;
9755 // we enforce that here.
9756 EVT OpVT = Ops[0].getValueType();
9757 if (InVal.getValueType() != OpVT)
9758 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9759 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9760 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9764 // Return the new vector
9765 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
9768 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
9769 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
9770 EVT ResultVT = EVE->getValueType(0);
9771 EVT VecEltVT = InVecVT.getVectorElementType();
9772 unsigned Align = OriginalLoad->getAlignment();
9773 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
9774 VecEltVT.getTypeForEVT(*DAG.getContext()));
9776 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
9781 SDValue NewPtr = OriginalLoad->getBasePtr();
9783 EVT PtrType = NewPtr.getValueType();
9784 MachinePointerInfo MPI;
9785 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
9786 int Elt = ConstEltNo->getZExtValue();
9787 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
9788 if (TLI.isBigEndian())
9789 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
9790 Offset = DAG.getConstant(PtrOff, PtrType);
9791 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
9793 Offset = DAG.getNode(
9794 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
9795 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
9796 if (TLI.isBigEndian())
9797 Offset = DAG.getNode(
9798 ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
9799 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
9800 MPI = OriginalLoad->getPointerInfo();
9802 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
9804 // The replacement we need to do here is a little tricky: we need to
9805 // replace an extractelement of a load with a load.
9806 // Use ReplaceAllUsesOfValuesWith to do the replacement.
9807 // Note that this replacement assumes that the extractvalue is the only
9808 // use of the load; that's okay because we don't want to perform this
9809 // transformation in other cases anyway.
9812 if (ResultVT.bitsGT(VecEltVT)) {
9813 // If the result type of vextract is wider than the load, then issue an
9814 // extending load instead.
9815 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
9818 Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(),
9819 NewPtr, MPI, VecEltVT, OriginalLoad->isVolatile(),
9820 OriginalLoad->isNonTemporal(), Align,
9821 OriginalLoad->getTBAAInfo());
9822 Chain = Load.getValue(1);
9825 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
9826 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
9827 OriginalLoad->isInvariant(), Align, OriginalLoad->getTBAAInfo());
9828 Chain = Load.getValue(1);
9829 if (ResultVT.bitsLT(VecEltVT))
9830 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
9832 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
9834 WorkListRemover DeadNodes(*this);
9835 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
9836 SDValue To[] = { Load, Chain };
9837 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9838 // Since we're explicitly calling ReplaceAllUses, add the new node to the
9839 // worklist explicitly as well.
9840 AddToWorkList(Load.getNode());
9841 AddUsersToWorkList(Load.getNode()); // Add users too
9842 // Make sure to revisit this node to clean it up; it will usually be dead.
9845 return SDValue(EVE, 0);
9848 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9849 // (vextract (scalar_to_vector val, 0) -> val
9850 SDValue InVec = N->getOperand(0);
9851 EVT VT = InVec.getValueType();
9852 EVT NVT = N->getValueType(0);
9854 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9855 // Check if the result type doesn't match the inserted element type. A
9856 // SCALAR_TO_VECTOR may truncate the inserted element and the
9857 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9858 SDValue InOp = InVec.getOperand(0);
9859 if (InOp.getValueType() != NVT) {
9860 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9861 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9866 SDValue EltNo = N->getOperand(1);
9867 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9869 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9870 // We only perform this optimization before the op legalization phase because
9871 // we may introduce new vector instructions which are not backed by TD
9872 // patterns. For example on AVX, extracting elements from a wide vector
9873 // without using extract_subvector. However, if we can find an underlying
9874 // scalar value, then we can always use that.
9875 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9877 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9878 int NumElem = VT.getVectorNumElements();
9879 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9880 // Find the new index to extract from.
9881 int OrigElt = SVOp->getMaskElt(Elt);
9883 // Extracting an undef index is undef.
9885 return DAG.getUNDEF(NVT);
9887 // Select the right vector half to extract from.
9889 if (OrigElt < NumElem) {
9890 SVInVec = InVec->getOperand(0);
9892 SVInVec = InVec->getOperand(1);
9896 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9897 SDValue InOp = SVInVec.getOperand(OrigElt);
9898 if (InOp.getValueType() != NVT) {
9899 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9900 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9906 // FIXME: We should handle recursing on other vector shuffles and
9907 // scalar_to_vector here as well.
9909 if (!LegalOperations) {
9910 EVT IndexTy = TLI.getVectorIdxTy();
9911 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9912 SVInVec, DAG.getConstant(OrigElt, IndexTy));
9916 bool BCNumEltsChanged = false;
9917 EVT ExtVT = VT.getVectorElementType();
9920 // If the result of load has to be truncated, then it's not necessarily
9922 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9925 if (InVec.getOpcode() == ISD::BITCAST) {
9926 // Don't duplicate a load with other uses.
9927 if (!InVec.hasOneUse())
9930 EVT BCVT = InVec.getOperand(0).getValueType();
9931 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9933 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9934 BCNumEltsChanged = true;
9935 InVec = InVec.getOperand(0);
9936 ExtVT = BCVT.getVectorElementType();
9939 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
9940 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
9941 ISD::isNormalLoad(InVec.getNode())) {
9942 SDValue Index = N->getOperand(1);
9943 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
9944 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
9948 // Perform only after legalization to ensure build_vector / vector_shuffle
9949 // optimizations have already been done.
9950 if (!LegalOperations) return SDValue();
9952 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9953 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9954 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9957 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9959 LoadSDNode *LN0 = nullptr;
9960 const ShuffleVectorSDNode *SVN = nullptr;
9961 if (ISD::isNormalLoad(InVec.getNode())) {
9962 LN0 = cast<LoadSDNode>(InVec);
9963 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9964 InVec.getOperand(0).getValueType() == ExtVT &&
9965 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9966 // Don't duplicate a load with other uses.
9967 if (!InVec.hasOneUse())
9970 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9971 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9972 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9974 // (load $addr+1*size)
9976 // Don't duplicate a load with other uses.
9977 if (!InVec.hasOneUse())
9980 // If the bit convert changed the number of elements, it is unsafe
9981 // to examine the mask.
9982 if (BCNumEltsChanged)
9985 // Select the input vector, guarding against out of range extract vector.
9986 unsigned NumElems = VT.getVectorNumElements();
9987 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9988 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9990 if (InVec.getOpcode() == ISD::BITCAST) {
9991 // Don't duplicate a load with other uses.
9992 if (!InVec.hasOneUse())
9995 InVec = InVec.getOperand(0);
9997 if (ISD::isNormalLoad(InVec.getNode())) {
9998 LN0 = cast<LoadSDNode>(InVec);
9999 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10000 EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10004 // Make sure we found a non-volatile load and the extractelement is
10006 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10009 // If Idx was -1 above, Elt is going to be -1, so just return undef.
10011 return DAG.getUNDEF(LVT);
10013 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10019 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10020 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10021 // We perform this optimization post type-legalization because
10022 // the type-legalizer often scalarizes integer-promoted vectors.
10023 // Performing this optimization before may create bit-casts which
10024 // will be type-legalized to complex code sequences.
10025 // We perform this optimization only before the operation legalizer because we
10026 // may introduce illegal operations.
10027 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10030 unsigned NumInScalars = N->getNumOperands();
10032 EVT VT = N->getValueType(0);
10034 // Check to see if this is a BUILD_VECTOR of a bunch of values
10035 // which come from any_extend or zero_extend nodes. If so, we can create
10036 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10037 // optimizations. We do not handle sign-extend because we can't fill the sign
10039 EVT SourceType = MVT::Other;
10040 bool AllAnyExt = true;
10042 for (unsigned i = 0; i != NumInScalars; ++i) {
10043 SDValue In = N->getOperand(i);
10044 // Ignore undef inputs.
10045 if (In.getOpcode() == ISD::UNDEF) continue;
10047 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
10048 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10050 // Abort if the element is not an extension.
10051 if (!ZeroExt && !AnyExt) {
10052 SourceType = MVT::Other;
10056 // The input is a ZeroExt or AnyExt. Check the original type.
10057 EVT InTy = In.getOperand(0).getValueType();
10059 // Check that all of the widened source types are the same.
10060 if (SourceType == MVT::Other)
10063 else if (InTy != SourceType) {
10064 // Multiple income types. Abort.
10065 SourceType = MVT::Other;
10069 // Check if all of the extends are ANY_EXTENDs.
10070 AllAnyExt &= AnyExt;
10073 // In order to have valid types, all of the inputs must be extended from the
10074 // same source type and all of the inputs must be any or zero extend.
10075 // Scalar sizes must be a power of two.
10076 EVT OutScalarTy = VT.getScalarType();
10077 bool ValidTypes = SourceType != MVT::Other &&
10078 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10079 isPowerOf2_32(SourceType.getSizeInBits());
10081 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10082 // turn into a single shuffle instruction.
10086 bool isLE = TLI.isLittleEndian();
10087 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10088 assert(ElemRatio > 1 && "Invalid element size ratio");
10089 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10090 DAG.getConstant(0, SourceType);
10092 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10093 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10095 // Populate the new build_vector
10096 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10097 SDValue Cast = N->getOperand(i);
10098 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10099 Cast.getOpcode() == ISD::ZERO_EXTEND ||
10100 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10102 if (Cast.getOpcode() == ISD::UNDEF)
10103 In = DAG.getUNDEF(SourceType);
10105 In = Cast->getOperand(0);
10106 unsigned Index = isLE ? (i * ElemRatio) :
10107 (i * ElemRatio + (ElemRatio - 1));
10109 assert(Index < Ops.size() && "Invalid index");
10113 // The type of the new BUILD_VECTOR node.
10114 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10115 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10116 "Invalid vector size");
10117 // Check if the new vector type is legal.
10118 if (!isTypeLegal(VecVT)) return SDValue();
10120 // Make the new BUILD_VECTOR.
10121 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10123 // The new BUILD_VECTOR node has the potential to be further optimized.
10124 AddToWorkList(BV.getNode());
10125 // Bitcast to the desired type.
10126 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10129 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10130 EVT VT = N->getValueType(0);
10132 unsigned NumInScalars = N->getNumOperands();
10135 EVT SrcVT = MVT::Other;
10136 unsigned Opcode = ISD::DELETED_NODE;
10137 unsigned NumDefs = 0;
10139 for (unsigned i = 0; i != NumInScalars; ++i) {
10140 SDValue In = N->getOperand(i);
10141 unsigned Opc = In.getOpcode();
10143 if (Opc == ISD::UNDEF)
10146 // If all scalar values are floats and converted from integers.
10147 if (Opcode == ISD::DELETED_NODE &&
10148 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10155 EVT InVT = In.getOperand(0).getValueType();
10157 // If all scalar values are typed differently, bail out. It's chosen to
10158 // simplify BUILD_VECTOR of integer types.
10159 if (SrcVT == MVT::Other)
10166 // If the vector has just one element defined, it's not worth to fold it into
10167 // a vectorized one.
10171 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10172 && "Should only handle conversion from integer to float.");
10173 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10175 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10177 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10180 SmallVector<SDValue, 8> Opnds;
10181 for (unsigned i = 0; i != NumInScalars; ++i) {
10182 SDValue In = N->getOperand(i);
10184 if (In.getOpcode() == ISD::UNDEF)
10185 Opnds.push_back(DAG.getUNDEF(SrcVT));
10187 Opnds.push_back(In.getOperand(0));
10189 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10190 AddToWorkList(BV.getNode());
10192 return DAG.getNode(Opcode, dl, VT, BV);
10195 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10196 unsigned NumInScalars = N->getNumOperands();
10198 EVT VT = N->getValueType(0);
10200 // A vector built entirely of undefs is undef.
10201 if (ISD::allOperandsUndef(N))
10202 return DAG.getUNDEF(VT);
10204 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10208 V = reduceBuildVecConvertToConvertBuildVec(N);
10212 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10213 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10214 // at most two distinct vectors, turn this into a shuffle node.
10216 // May only combine to shuffle after legalize if shuffle is legal.
10217 if (LegalOperations &&
10218 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10221 SDValue VecIn1, VecIn2;
10222 for (unsigned i = 0; i != NumInScalars; ++i) {
10223 // Ignore undef inputs.
10224 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10226 // If this input is something other than a EXTRACT_VECTOR_ELT with a
10227 // constant index, bail out.
10228 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10229 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10230 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10234 // We allow up to two distinct input vectors.
10235 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10236 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10239 if (!VecIn1.getNode()) {
10240 VecIn1 = ExtractedFromVec;
10241 } else if (!VecIn2.getNode()) {
10242 VecIn2 = ExtractedFromVec;
10244 // Too many inputs.
10245 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10250 // If everything is good, we can make a shuffle operation.
10251 if (VecIn1.getNode()) {
10252 SmallVector<int, 8> Mask;
10253 for (unsigned i = 0; i != NumInScalars; ++i) {
10254 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10255 Mask.push_back(-1);
10259 // If extracting from the first vector, just use the index directly.
10260 SDValue Extract = N->getOperand(i);
10261 SDValue ExtVal = Extract.getOperand(1);
10262 if (Extract.getOperand(0) == VecIn1) {
10263 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10264 if (ExtIndex > VT.getVectorNumElements())
10267 Mask.push_back(ExtIndex);
10271 // Otherwise, use InIdx + VecSize
10272 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10273 Mask.push_back(Idx+NumInScalars);
10276 // We can't generate a shuffle node with mismatched input and output types.
10277 // Attempt to transform a single input vector to the correct type.
10278 if ((VT != VecIn1.getValueType())) {
10279 // We don't support shuffeling between TWO values of different types.
10280 if (VecIn2.getNode())
10283 // We only support widening of vectors which are half the size of the
10284 // output registers. For example XMM->YMM widening on X86 with AVX.
10285 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10288 // If the input vector type has a different base type to the output
10289 // vector type, bail out.
10290 if (VecIn1.getValueType().getVectorElementType() !=
10291 VT.getVectorElementType())
10294 // Widen the input vector by adding undef values.
10295 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10296 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10299 // If VecIn2 is unused then change it to undef.
10300 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10302 // Check that we were able to transform all incoming values to the same
10304 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10305 VecIn1.getValueType() != VT)
10308 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10309 if (!isTypeLegal(VT))
10312 // Return the new VECTOR_SHUFFLE node.
10316 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10322 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10323 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10324 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10325 // inputs come from at most two distinct vectors, turn this into a shuffle
10328 // If we only have one input vector, we don't need to do any concatenation.
10329 if (N->getNumOperands() == 1)
10330 return N->getOperand(0);
10332 // Check if all of the operands are undefs.
10333 EVT VT = N->getValueType(0);
10334 if (ISD::allOperandsUndef(N))
10335 return DAG.getUNDEF(VT);
10337 // Optimize concat_vectors where one of the vectors is undef.
10338 if (N->getNumOperands() == 2 &&
10339 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10340 SDValue In = N->getOperand(0);
10341 assert(In.getValueType().isVector() && "Must concat vectors");
10343 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10344 if (In->getOpcode() == ISD::BITCAST &&
10345 !In->getOperand(0)->getValueType(0).isVector()) {
10346 SDValue Scalar = In->getOperand(0);
10347 EVT SclTy = Scalar->getValueType(0);
10349 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10352 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10353 VT.getSizeInBits() / SclTy.getSizeInBits());
10354 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10357 SDLoc dl = SDLoc(N);
10358 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10359 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10363 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10364 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10365 if (N->getNumOperands() == 2 &&
10366 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10367 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10368 EVT VT = N->getValueType(0);
10369 SDValue N0 = N->getOperand(0);
10370 SDValue N1 = N->getOperand(1);
10371 SmallVector<SDValue, 8> Opnds;
10372 unsigned BuildVecNumElts = N0.getNumOperands();
10374 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10375 Opnds.push_back(N0.getOperand(i));
10376 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10377 Opnds.push_back(N1.getOperand(i));
10379 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10382 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10383 // nodes often generate nop CONCAT_VECTOR nodes.
10384 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10385 // place the incoming vectors at the exact same location.
10386 SDValue SingleSource = SDValue();
10387 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10389 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10390 SDValue Op = N->getOperand(i);
10392 if (Op.getOpcode() == ISD::UNDEF)
10395 // Check if this is the identity extract:
10396 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10399 // Find the single incoming vector for the extract_subvector.
10400 if (SingleSource.getNode()) {
10401 if (Op.getOperand(0) != SingleSource)
10404 SingleSource = Op.getOperand(0);
10406 // Check the source type is the same as the type of the result.
10407 // If not, this concat may extend the vector, so we can not
10408 // optimize it away.
10409 if (SingleSource.getValueType() != N->getValueType(0))
10413 unsigned IdentityIndex = i * PartNumElem;
10414 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10415 // The extract index must be constant.
10419 // Check that we are reading from the identity index.
10420 if (CS->getZExtValue() != IdentityIndex)
10424 if (SingleSource.getNode())
10425 return SingleSource;
10430 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10431 EVT NVT = N->getValueType(0);
10432 SDValue V = N->getOperand(0);
10434 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10436 // (extract_subvec (concat V1, V2, ...), i)
10439 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10441 if (V->getOperand(0).getValueType() != NVT)
10443 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10444 unsigned NumElems = NVT.getVectorNumElements();
10445 assert((Idx % NumElems) == 0 &&
10446 "IDX in concat is not a multiple of the result vector length.");
10447 return V->getOperand(Idx / NumElems);
10451 if (V->getOpcode() == ISD::BITCAST)
10452 V = V.getOperand(0);
10454 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10456 // Handle only simple case where vector being inserted and vector
10457 // being extracted are of same type, and are half size of larger vectors.
10458 EVT BigVT = V->getOperand(0).getValueType();
10459 EVT SmallVT = V->getOperand(1).getValueType();
10460 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10463 // Only handle cases where both indexes are constants with the same type.
10464 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10465 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10467 if (InsIdx && ExtIdx &&
10468 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10469 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10471 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10473 // indices are equal or bit offsets are equal => V1
10474 // otherwise => (extract_subvec V1, ExtIdx)
10475 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10476 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10477 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10478 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10479 DAG.getNode(ISD::BITCAST, dl,
10480 N->getOperand(0).getValueType(),
10481 V->getOperand(0)), N->getOperand(1));
10488 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10489 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10490 EVT VT = N->getValueType(0);
10491 unsigned NumElts = VT.getVectorNumElements();
10493 SDValue N0 = N->getOperand(0);
10494 SDValue N1 = N->getOperand(1);
10495 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10497 SmallVector<SDValue, 4> Ops;
10498 EVT ConcatVT = N0.getOperand(0).getValueType();
10499 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10500 unsigned NumConcats = NumElts / NumElemsPerConcat;
10502 // Look at every vector that's inserted. We're looking for exact
10503 // subvector-sized copies from a concatenated vector
10504 for (unsigned I = 0; I != NumConcats; ++I) {
10505 // Make sure we're dealing with a copy.
10506 unsigned Begin = I * NumElemsPerConcat;
10507 bool AllUndef = true, NoUndef = true;
10508 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10509 if (SVN->getMaskElt(J) >= 0)
10516 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10519 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10520 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10523 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10524 if (FirstElt < N0.getNumOperands())
10525 Ops.push_back(N0.getOperand(FirstElt));
10527 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10529 } else if (AllUndef) {
10530 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10531 } else { // Mixed with general masks and undefs, can't do optimization.
10536 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10539 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10540 EVT VT = N->getValueType(0);
10541 unsigned NumElts = VT.getVectorNumElements();
10543 SDValue N0 = N->getOperand(0);
10544 SDValue N1 = N->getOperand(1);
10546 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10548 // Canonicalize shuffle undef, undef -> undef
10549 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10550 return DAG.getUNDEF(VT);
10552 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10554 // Canonicalize shuffle v, v -> v, undef
10556 SmallVector<int, 8> NewMask;
10557 for (unsigned i = 0; i != NumElts; ++i) {
10558 int Idx = SVN->getMaskElt(i);
10559 if (Idx >= (int)NumElts) Idx -= NumElts;
10560 NewMask.push_back(Idx);
10562 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10566 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10567 if (N0.getOpcode() == ISD::UNDEF) {
10568 SmallVector<int, 8> NewMask;
10569 for (unsigned i = 0; i != NumElts; ++i) {
10570 int Idx = SVN->getMaskElt(i);
10572 if (Idx >= (int)NumElts)
10575 Idx = -1; // remove reference to lhs
10577 NewMask.push_back(Idx);
10579 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10583 // Remove references to rhs if it is undef
10584 if (N1.getOpcode() == ISD::UNDEF) {
10585 bool Changed = false;
10586 SmallVector<int, 8> NewMask;
10587 for (unsigned i = 0; i != NumElts; ++i) {
10588 int Idx = SVN->getMaskElt(i);
10589 if (Idx >= (int)NumElts) {
10593 NewMask.push_back(Idx);
10596 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10599 // If it is a splat, check if the argument vector is another splat or a
10600 // build_vector with all scalar elements the same.
10601 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10602 SDNode *V = N0.getNode();
10604 // If this is a bit convert that changes the element type of the vector but
10605 // not the number of vector elements, look through it. Be careful not to
10606 // look though conversions that change things like v4f32 to v2f64.
10607 if (V->getOpcode() == ISD::BITCAST) {
10608 SDValue ConvInput = V->getOperand(0);
10609 if (ConvInput.getValueType().isVector() &&
10610 ConvInput.getValueType().getVectorNumElements() == NumElts)
10611 V = ConvInput.getNode();
10614 if (V->getOpcode() == ISD::BUILD_VECTOR) {
10615 assert(V->getNumOperands() == NumElts &&
10616 "BUILD_VECTOR has wrong number of operands");
10618 bool AllSame = true;
10619 for (unsigned i = 0; i != NumElts; ++i) {
10620 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10621 Base = V->getOperand(i);
10625 // Splat of <u, u, u, u>, return <u, u, u, u>
10626 if (!Base.getNode())
10628 for (unsigned i = 0; i != NumElts; ++i) {
10629 if (V->getOperand(i) != Base) {
10634 // Splat of <x, x, x, x>, return <x, x, x, x>
10640 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10641 Level < AfterLegalizeVectorOps &&
10642 (N1.getOpcode() == ISD::UNDEF ||
10643 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10644 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10645 SDValue V = partitionShuffleOfConcats(N, DAG);
10651 // If this shuffle node is simply a swizzle of another shuffle node,
10652 // and it reverses the swizzle of the previous shuffle then we can
10653 // optimize shuffle(shuffle(x, undef), undef) -> x.
10654 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10655 N1.getOpcode() == ISD::UNDEF) {
10657 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10659 // Shuffle nodes can only reverse shuffles with a single non-undef value.
10660 if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10663 // The incoming shuffle must be of the same type as the result of the
10664 // current shuffle.
10665 assert(OtherSV->getOperand(0).getValueType() == VT &&
10666 "Shuffle types don't match");
10668 for (unsigned i = 0; i != NumElts; ++i) {
10669 int Idx = SVN->getMaskElt(i);
10670 assert(Idx < (int)NumElts && "Index references undef operand");
10671 // Next, this index comes from the first value, which is the incoming
10672 // shuffle. Adopt the incoming index.
10674 Idx = OtherSV->getMaskElt(Idx);
10676 // The combined shuffle must map each index to itself.
10677 if (Idx >= 0 && (unsigned)Idx != i)
10681 return OtherSV->getOperand(0);
10687 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10688 SDValue N0 = N->getOperand(0);
10689 SDValue N2 = N->getOperand(2);
10691 // If the input vector is a concatenation, and the insert replaces
10692 // one of the halves, we can optimize into a single concat_vectors.
10693 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10694 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10695 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10696 EVT VT = N->getValueType(0);
10698 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10699 // (concat_vectors Z, Y)
10701 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10702 N->getOperand(1), N0.getOperand(1));
10704 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10705 // (concat_vectors X, Z)
10706 if (InsIdx == VT.getVectorNumElements()/2)
10707 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10708 N0.getOperand(0), N->getOperand(1));
10714 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10715 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10716 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10717 /// vector_shuffle V, Zero, <0, 4, 2, 4>
10718 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10719 EVT VT = N->getValueType(0);
10721 SDValue LHS = N->getOperand(0);
10722 SDValue RHS = N->getOperand(1);
10723 if (N->getOpcode() == ISD::AND) {
10724 if (RHS.getOpcode() == ISD::BITCAST)
10725 RHS = RHS.getOperand(0);
10726 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10727 SmallVector<int, 8> Indices;
10728 unsigned NumElts = RHS.getNumOperands();
10729 for (unsigned i = 0; i != NumElts; ++i) {
10730 SDValue Elt = RHS.getOperand(i);
10731 if (!isa<ConstantSDNode>(Elt))
10734 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10735 Indices.push_back(i);
10736 else if (cast<ConstantSDNode>(Elt)->isNullValue())
10737 Indices.push_back(NumElts);
10742 // Let's see if the target supports this vector_shuffle.
10743 EVT RVT = RHS.getValueType();
10744 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10747 // Return the new VECTOR_SHUFFLE node.
10748 EVT EltVT = RVT.getVectorElementType();
10749 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10750 DAG.getConstant(0, EltVT));
10751 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
10752 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10753 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10754 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10761 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10762 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10763 assert(N->getValueType(0).isVector() &&
10764 "SimplifyVBinOp only works on vectors!");
10766 SDValue LHS = N->getOperand(0);
10767 SDValue RHS = N->getOperand(1);
10768 SDValue Shuffle = XformToShuffleWithZero(N);
10769 if (Shuffle.getNode()) return Shuffle;
10771 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10773 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10774 RHS.getOpcode() == ISD::BUILD_VECTOR) {
10775 // Check if both vectors are constants. If not bail out.
10776 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10777 cast<BuildVectorSDNode>(RHS)->isConstant()))
10780 SmallVector<SDValue, 8> Ops;
10781 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10782 SDValue LHSOp = LHS.getOperand(i);
10783 SDValue RHSOp = RHS.getOperand(i);
10785 // Can't fold divide by zero.
10786 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10787 N->getOpcode() == ISD::FDIV) {
10788 if ((RHSOp.getOpcode() == ISD::Constant &&
10789 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10790 (RHSOp.getOpcode() == ISD::ConstantFP &&
10791 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10795 EVT VT = LHSOp.getValueType();
10796 EVT RVT = RHSOp.getValueType();
10798 // Integer BUILD_VECTOR operands may have types larger than the element
10799 // size (e.g., when the element type is not legal). Prior to type
10800 // legalization, the types may not match between the two BUILD_VECTORS.
10801 // Truncate one of the operands to make them match.
10802 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10803 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10805 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10809 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10811 if (FoldOp.getOpcode() != ISD::UNDEF &&
10812 FoldOp.getOpcode() != ISD::Constant &&
10813 FoldOp.getOpcode() != ISD::ConstantFP)
10815 Ops.push_back(FoldOp);
10816 AddToWorkList(FoldOp.getNode());
10819 if (Ops.size() == LHS.getNumOperands())
10820 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
10823 // Type legalization might introduce new shuffles in the DAG.
10824 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
10825 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
10826 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
10827 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
10828 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
10829 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
10830 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
10831 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
10833 if (SVN0->getMask().equals(SVN1->getMask())) {
10834 EVT VT = N->getValueType(0);
10835 SDValue UndefVector = LHS.getOperand(1);
10836 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
10837 LHS.getOperand(0), RHS.getOperand(0));
10838 AddUsersToWorkList(N);
10839 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
10840 &SVN0->getMask()[0]);
10847 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10848 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10849 assert(N->getValueType(0).isVector() &&
10850 "SimplifyVUnaryOp only works on vectors!");
10852 SDValue N0 = N->getOperand(0);
10854 if (N0.getOpcode() != ISD::BUILD_VECTOR)
10857 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10858 SmallVector<SDValue, 8> Ops;
10859 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10860 SDValue Op = N0.getOperand(i);
10861 if (Op.getOpcode() != ISD::UNDEF &&
10862 Op.getOpcode() != ISD::ConstantFP)
10864 EVT EltVT = Op.getValueType();
10865 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
10866 if (FoldOp.getOpcode() != ISD::UNDEF &&
10867 FoldOp.getOpcode() != ISD::ConstantFP)
10869 Ops.push_back(FoldOp);
10870 AddToWorkList(FoldOp.getNode());
10873 if (Ops.size() != N0.getNumOperands())
10876 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
10879 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10880 SDValue N1, SDValue N2){
10881 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10883 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
10884 cast<CondCodeSDNode>(N0.getOperand(2))->get());
10886 // If we got a simplified select_cc node back from SimplifySelectCC, then
10887 // break it down into a new SETCC node, and a new SELECT node, and then return
10888 // the SELECT node, since we were called with a SELECT node.
10889 if (SCC.getNode()) {
10890 // Check to see if we got a select_cc back (to turn into setcc/select).
10891 // Otherwise, just return whatever node we got back, like fabs.
10892 if (SCC.getOpcode() == ISD::SELECT_CC) {
10893 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
10895 SCC.getOperand(0), SCC.getOperand(1),
10896 SCC.getOperand(4));
10897 AddToWorkList(SETCC.getNode());
10898 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10899 SCC.getOperand(2), SCC.getOperand(3), SETCC);
10907 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10908 /// are the two values being selected between, see if we can simplify the
10909 /// select. Callers of this should assume that TheSelect is deleted if this
10910 /// returns true. As such, they should return the appropriate thing (e.g. the
10911 /// node) back to the top-level of the DAG combiner loop to avoid it being
10913 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
10916 // Cannot simplify select with vector condition
10917 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10919 // If this is a select from two identical things, try to pull the operation
10920 // through the select.
10921 if (LHS.getOpcode() != RHS.getOpcode() ||
10922 !LHS.hasOneUse() || !RHS.hasOneUse())
10925 // If this is a load and the token chain is identical, replace the select
10926 // of two loads with a load through a select of the address to load from.
10927 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10928 // constants have been dropped into the constant pool.
10929 if (LHS.getOpcode() == ISD::LOAD) {
10930 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10931 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
10933 // Token chains must be identical.
10934 if (LHS.getOperand(0) != RHS.getOperand(0) ||
10935 // Do not let this transformation reduce the number of volatile loads.
10936 LLD->isVolatile() || RLD->isVolatile() ||
10937 // If this is an EXTLOAD, the VT's must match.
10938 LLD->getMemoryVT() != RLD->getMemoryVT() ||
10939 // If this is an EXTLOAD, the kind of extension must match.
10940 (LLD->getExtensionType() != RLD->getExtensionType() &&
10941 // The only exception is if one of the extensions is anyext.
10942 LLD->getExtensionType() != ISD::EXTLOAD &&
10943 RLD->getExtensionType() != ISD::EXTLOAD) ||
10944 // FIXME: this discards src value information. This is
10945 // over-conservative. It would be beneficial to be able to remember
10946 // both potential memory locations. Since we are discarding
10947 // src value info, don't do the transformation if the memory
10948 // locations are not in the default address space.
10949 LLD->getPointerInfo().getAddrSpace() != 0 ||
10950 RLD->getPointerInfo().getAddrSpace() != 0 ||
10951 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10952 LLD->getBasePtr().getValueType()))
10955 // Check that the select condition doesn't reach either load. If so,
10956 // folding this will induce a cycle into the DAG. If not, this is safe to
10957 // xform, so create a select of the addresses.
10959 if (TheSelect->getOpcode() == ISD::SELECT) {
10960 SDNode *CondNode = TheSelect->getOperand(0).getNode();
10961 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10962 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10964 // The loads must not depend on one another.
10965 if (LLD->isPredecessorOf(RLD) ||
10966 RLD->isPredecessorOf(LLD))
10968 Addr = DAG.getSelect(SDLoc(TheSelect),
10969 LLD->getBasePtr().getValueType(),
10970 TheSelect->getOperand(0), LLD->getBasePtr(),
10971 RLD->getBasePtr());
10972 } else { // Otherwise SELECT_CC
10973 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10974 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10976 if ((LLD->hasAnyUseOfValue(1) &&
10977 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
10978 (RLD->hasAnyUseOfValue(1) &&
10979 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
10982 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
10983 LLD->getBasePtr().getValueType(),
10984 TheSelect->getOperand(0),
10985 TheSelect->getOperand(1),
10986 LLD->getBasePtr(), RLD->getBasePtr(),
10987 TheSelect->getOperand(4));
10991 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10992 Load = DAG.getLoad(TheSelect->getValueType(0),
10994 // FIXME: Discards pointer and TBAA info.
10995 LLD->getChain(), Addr, MachinePointerInfo(),
10996 LLD->isVolatile(), LLD->isNonTemporal(),
10997 LLD->isInvariant(), LLD->getAlignment());
10999 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11000 RLD->getExtensionType() : LLD->getExtensionType(),
11002 TheSelect->getValueType(0),
11003 // FIXME: Discards pointer and TBAA info.
11004 LLD->getChain(), Addr, MachinePointerInfo(),
11005 LLD->getMemoryVT(), LLD->isVolatile(),
11006 LLD->isNonTemporal(), LLD->getAlignment());
11009 // Users of the select now use the result of the load.
11010 CombineTo(TheSelect, Load);
11012 // Users of the old loads now use the new load's chain. We know the
11013 // old-load value is dead now.
11014 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11015 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11022 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
11023 /// where 'cond' is the comparison specified by CC.
11024 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11025 SDValue N2, SDValue N3,
11026 ISD::CondCode CC, bool NotExtCompare) {
11027 // (x ? y : y) -> y.
11028 if (N2 == N3) return N2;
11030 EVT VT = N2.getValueType();
11031 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11032 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11033 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11035 // Determine if the condition we're dealing with is constant
11036 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11037 N0, N1, CC, DL, false);
11038 if (SCC.getNode()) AddToWorkList(SCC.getNode());
11039 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11041 // fold select_cc true, x, y -> x
11042 if (SCCC && !SCCC->isNullValue())
11044 // fold select_cc false, x, y -> y
11045 if (SCCC && SCCC->isNullValue())
11048 // Check to see if we can simplify the select into an fabs node
11049 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11050 // Allow either -0.0 or 0.0
11051 if (CFP->getValueAPF().isZero()) {
11052 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11053 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11054 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11055 N2 == N3.getOperand(0))
11056 return DAG.getNode(ISD::FABS, DL, VT, N0);
11058 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11059 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11060 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11061 N2.getOperand(0) == N3)
11062 return DAG.getNode(ISD::FABS, DL, VT, N3);
11066 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11067 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11068 // in it. This is a win when the constant is not otherwise available because
11069 // it replaces two constant pool loads with one. We only do this if the FP
11070 // type is known to be legal, because if it isn't, then we are before legalize
11071 // types an we want the other legalization to happen first (e.g. to avoid
11072 // messing with soft float) and if the ConstantFP is not legal, because if
11073 // it is legal, we may not need to store the FP constant in a constant pool.
11074 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11075 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11076 if (TLI.isTypeLegal(N2.getValueType()) &&
11077 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11078 TargetLowering::Legal &&
11079 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11080 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11081 // If both constants have multiple uses, then we won't need to do an
11082 // extra load, they are likely around in registers for other users.
11083 (TV->hasOneUse() || FV->hasOneUse())) {
11084 Constant *Elts[] = {
11085 const_cast<ConstantFP*>(FV->getConstantFPValue()),
11086 const_cast<ConstantFP*>(TV->getConstantFPValue())
11088 Type *FPTy = Elts[0]->getType();
11089 const DataLayout &TD = *TLI.getDataLayout();
11091 // Create a ConstantArray of the two constants.
11092 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11093 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11094 TD.getPrefTypeAlignment(FPTy));
11095 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11097 // Get the offsets to the 0 and 1 element of the array so that we can
11098 // select between them.
11099 SDValue Zero = DAG.getIntPtrConstant(0);
11100 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11101 SDValue One = DAG.getIntPtrConstant(EltSize);
11103 SDValue Cond = DAG.getSetCC(DL,
11104 getSetCCResultType(N0.getValueType()),
11106 AddToWorkList(Cond.getNode());
11107 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11109 AddToWorkList(CstOffset.getNode());
11110 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11112 AddToWorkList(CPIdx.getNode());
11113 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11114 MachinePointerInfo::getConstantPool(), false,
11115 false, false, Alignment);
11120 // Check to see if we can perform the "gzip trick", transforming
11121 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11122 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11123 (N1C->isNullValue() || // (a < 0) ? b : 0
11124 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
11125 EVT XType = N0.getValueType();
11126 EVT AType = N2.getValueType();
11127 if (XType.bitsGE(AType)) {
11128 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11129 // single-bit constant.
11130 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11131 unsigned ShCtV = N2C->getAPIntValue().logBase2();
11132 ShCtV = XType.getSizeInBits()-ShCtV-1;
11133 SDValue ShCt = DAG.getConstant(ShCtV,
11134 getShiftAmountTy(N0.getValueType()));
11135 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11137 AddToWorkList(Shift.getNode());
11139 if (XType.bitsGT(AType)) {
11140 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11141 AddToWorkList(Shift.getNode());
11144 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11147 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11149 DAG.getConstant(XType.getSizeInBits()-1,
11150 getShiftAmountTy(N0.getValueType())));
11151 AddToWorkList(Shift.getNode());
11153 if (XType.bitsGT(AType)) {
11154 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11155 AddToWorkList(Shift.getNode());
11158 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11162 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11163 // where y is has a single bit set.
11164 // A plaintext description would be, we can turn the SELECT_CC into an AND
11165 // when the condition can be materialized as an all-ones register. Any
11166 // single bit-test can be materialized as an all-ones register with
11167 // shift-left and shift-right-arith.
11168 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11169 N0->getValueType(0) == VT &&
11170 N1C && N1C->isNullValue() &&
11171 N2C && N2C->isNullValue()) {
11172 SDValue AndLHS = N0->getOperand(0);
11173 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11174 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11175 // Shift the tested bit over the sign bit.
11176 APInt AndMask = ConstAndRHS->getAPIntValue();
11178 DAG.getConstant(AndMask.countLeadingZeros(),
11179 getShiftAmountTy(AndLHS.getValueType()));
11180 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11182 // Now arithmetic right shift it all the way over, so the result is either
11183 // all-ones, or zero.
11185 DAG.getConstant(AndMask.getBitWidth()-1,
11186 getShiftAmountTy(Shl.getValueType()));
11187 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11189 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11193 // fold select C, 16, 0 -> shl C, 4
11194 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11195 TLI.getBooleanContents(N0.getValueType().isVector()) ==
11196 TargetLowering::ZeroOrOneBooleanContent) {
11198 // If the caller doesn't want us to simplify this into a zext of a compare,
11200 if (NotExtCompare && N2C->getAPIntValue() == 1)
11203 // Get a SetCC of the condition
11204 // NOTE: Don't create a SETCC if it's not legal on this target.
11205 if (!LegalOperations ||
11206 TLI.isOperationLegal(ISD::SETCC,
11207 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11209 // cast from setcc result type to select result type
11211 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11213 if (N2.getValueType().bitsLT(SCC.getValueType()))
11214 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11215 N2.getValueType());
11217 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11218 N2.getValueType(), SCC);
11220 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11221 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11222 N2.getValueType(), SCC);
11225 AddToWorkList(SCC.getNode());
11226 AddToWorkList(Temp.getNode());
11228 if (N2C->getAPIntValue() == 1)
11231 // shl setcc result by log2 n2c
11232 return DAG.getNode(
11233 ISD::SHL, DL, N2.getValueType(), Temp,
11234 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11235 getShiftAmountTy(Temp.getValueType())));
11239 // Check to see if this is the equivalent of setcc
11240 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11241 // otherwise, go ahead with the folds.
11242 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11243 EVT XType = N0.getValueType();
11244 if (!LegalOperations ||
11245 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11246 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11247 if (Res.getValueType() != VT)
11248 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11252 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11253 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11254 (!LegalOperations ||
11255 TLI.isOperationLegal(ISD::CTLZ, XType))) {
11256 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11257 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11258 DAG.getConstant(Log2_32(XType.getSizeInBits()),
11259 getShiftAmountTy(Ctlz.getValueType())));
11261 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11262 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11263 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11264 XType, DAG.getConstant(0, XType), N0);
11265 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11266 return DAG.getNode(ISD::SRL, DL, XType,
11267 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11268 DAG.getConstant(XType.getSizeInBits()-1,
11269 getShiftAmountTy(XType)));
11271 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11272 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11273 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11274 DAG.getConstant(XType.getSizeInBits()-1,
11275 getShiftAmountTy(N0.getValueType())));
11276 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11280 // Check to see if this is an integer abs.
11281 // select_cc setg[te] X, 0, X, -X ->
11282 // select_cc setgt X, -1, X, -X ->
11283 // select_cc setl[te] X, 0, -X, X ->
11284 // select_cc setlt X, 1, -X, X ->
11285 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11287 ConstantSDNode *SubC = nullptr;
11288 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11289 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11290 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11291 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11292 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11293 (N1C->isOne() && CC == ISD::SETLT)) &&
11294 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11295 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11297 EVT XType = N0.getValueType();
11298 if (SubC && SubC->isNullValue() && XType.isInteger()) {
11299 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11301 DAG.getConstant(XType.getSizeInBits()-1,
11302 getShiftAmountTy(N0.getValueType())));
11303 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11305 AddToWorkList(Shift.getNode());
11306 AddToWorkList(Add.getNode());
11307 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11314 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11315 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11316 SDValue N1, ISD::CondCode Cond,
11317 SDLoc DL, bool foldBooleans) {
11318 TargetLowering::DAGCombinerInfo
11319 DagCombineInfo(DAG, Level, false, this);
11320 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11323 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11324 /// return a DAG expression to select that will generate the same value by
11325 /// multiplying by a magic number. See:
11326 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11327 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11328 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11332 // Avoid division by zero.
11333 if (!C->getAPIntValue())
11336 std::vector<SDNode*> Built;
11338 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11340 for (SDNode *N : Built)
11345 /// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant,
11346 /// return a DAG expression to select that will generate the same value by
11347 /// multiplying by a magic number. See:
11348 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11349 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11350 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11354 // Avoid division by zero.
11355 if (!C->getAPIntValue())
11358 std::vector<SDNode*> Built;
11360 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11362 for (SDNode *N : Built)
11367 /// FindBaseOffset - Return true if base is a frame index, which is known not
11368 // to alias with anything but itself. Provides base object and offset as
11370 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11371 const GlobalValue *&GV, const void *&CV) {
11372 // Assume it is a primitive operation.
11373 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11375 // If it's an adding a simple constant then integrate the offset.
11376 if (Base.getOpcode() == ISD::ADD) {
11377 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11378 Base = Base.getOperand(0);
11379 Offset += C->getZExtValue();
11383 // Return the underlying GlobalValue, and update the Offset. Return false
11384 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11385 // by multiple nodes with different offsets.
11386 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11387 GV = G->getGlobal();
11388 Offset += G->getOffset();
11392 // Return the underlying Constant value, and update the Offset. Return false
11393 // for ConstantSDNodes since the same constant pool entry may be represented
11394 // by multiple nodes with different offsets.
11395 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11396 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11397 : (const void *)C->getConstVal();
11398 Offset += C->getOffset();
11401 // If it's any of the following then it can't alias with anything but itself.
11402 return isa<FrameIndexSDNode>(Base);
11405 /// isAlias - Return true if there is any possibility that the two addresses
11407 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11408 // If they are the same then they must be aliases.
11409 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11411 // If they are both volatile then they cannot be reordered.
11412 if (Op0->isVolatile() && Op1->isVolatile()) return true;
11414 // Gather base node and offset information.
11415 SDValue Base1, Base2;
11416 int64_t Offset1, Offset2;
11417 const GlobalValue *GV1, *GV2;
11418 const void *CV1, *CV2;
11419 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11420 Base1, Offset1, GV1, CV1);
11421 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11422 Base2, Offset2, GV2, CV2);
11424 // If they have a same base address then check to see if they overlap.
11425 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11426 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11427 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11429 // It is possible for different frame indices to alias each other, mostly
11430 // when tail call optimization reuses return address slots for arguments.
11431 // To catch this case, look up the actual index of frame indices to compute
11432 // the real alias relationship.
11433 if (isFrameIndex1 && isFrameIndex2) {
11434 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11435 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11436 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11437 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11438 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11441 // Otherwise, if we know what the bases are, and they aren't identical, then
11442 // we know they cannot alias.
11443 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11446 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11447 // compared to the size and offset of the access, we may be able to prove they
11448 // do not alias. This check is conservative for now to catch cases created by
11449 // splitting vector types.
11450 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11451 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11452 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11453 Op1->getMemoryVT().getSizeInBits() >> 3) &&
11454 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11455 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11456 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11458 // There is no overlap between these relatively aligned accesses of similar
11459 // size, return no alias.
11460 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11461 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11465 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11466 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11468 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11469 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11473 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11474 // Use alias analysis information.
11475 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11476 Op1->getSrcValueOffset());
11477 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11478 Op0->getSrcValueOffset() - MinOffset;
11479 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11480 Op1->getSrcValueOffset() - MinOffset;
11481 AliasAnalysis::AliasResult AAResult =
11482 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11484 UseTBAA ? Op0->getTBAAInfo() : nullptr),
11485 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11487 UseTBAA ? Op1->getTBAAInfo() : nullptr));
11488 if (AAResult == AliasAnalysis::NoAlias)
11492 // Otherwise we have to assume they alias.
11496 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11497 /// looking for aliasing nodes and adding them to the Aliases vector.
11498 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11499 SmallVectorImpl<SDValue> &Aliases) {
11500 SmallVector<SDValue, 8> Chains; // List of chains to visit.
11501 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
11503 // Get alias information for node.
11504 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11507 Chains.push_back(OriginalChain);
11508 unsigned Depth = 0;
11510 // Look at each chain and determine if it is an alias. If so, add it to the
11511 // aliases list. If not, then continue up the chain looking for the next
11513 while (!Chains.empty()) {
11514 SDValue Chain = Chains.back();
11517 // For TokenFactor nodes, look at each operand and only continue up the
11518 // chain until we find two aliases. If we've seen two aliases, assume we'll
11519 // find more and revert to original chain since the xform is unlikely to be
11522 // FIXME: The depth check could be made to return the last non-aliasing
11523 // chain we found before we hit a tokenfactor rather than the original
11525 if (Depth > 6 || Aliases.size() == 2) {
11527 Aliases.push_back(OriginalChain);
11531 // Don't bother if we've been before.
11532 if (!Visited.insert(Chain.getNode()))
11535 switch (Chain.getOpcode()) {
11536 case ISD::EntryToken:
11537 // Entry token is ideal chain operand, but handled in FindBetterChain.
11542 // Get alias information for Chain.
11543 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11544 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11546 // If chain is alias then stop here.
11547 if (!(IsLoad && IsOpLoad) &&
11548 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11549 Aliases.push_back(Chain);
11551 // Look further up the chain.
11552 Chains.push_back(Chain.getOperand(0));
11558 case ISD::TokenFactor:
11559 // We have to check each of the operands of the token factor for "small"
11560 // token factors, so we queue them up. Adding the operands to the queue
11561 // (stack) in reverse order maintains the original order and increases the
11562 // likelihood that getNode will find a matching token factor (CSE.)
11563 if (Chain.getNumOperands() > 16) {
11564 Aliases.push_back(Chain);
11567 for (unsigned n = Chain.getNumOperands(); n;)
11568 Chains.push_back(Chain.getOperand(--n));
11573 // For all other instructions we will just have to take what we can get.
11574 Aliases.push_back(Chain);
11579 // We need to be careful here to also search for aliases through the
11580 // value operand of a store, etc. Consider the following situation:
11582 // L1 = load Token1, %52
11583 // S1 = store Token1, L1, %51
11584 // L2 = load Token1, %52+8
11585 // S2 = store Token1, L2, %51+8
11586 // Token2 = Token(S1, S2)
11587 // L3 = load Token2, %53
11588 // S3 = store Token2, L3, %52
11589 // L4 = load Token2, %53+8
11590 // S4 = store Token2, L4, %52+8
11591 // If we search for aliases of S3 (which loads address %52), and we look
11592 // only through the chain, then we'll miss the trivial dependence on L1
11593 // (which also loads from %52). We then might change all loads and
11594 // stores to use Token1 as their chain operand, which could result in
11595 // copying %53 into %52 before copying %52 into %51 (which should
11598 // The problem is, however, that searching for such data dependencies
11599 // can become expensive, and the cost is not directly related to the
11600 // chain depth. Instead, we'll rule out such configurations here by
11601 // insisting that we've visited all chain users (except for users
11602 // of the original chain, which is not necessary). When doing this,
11603 // we need to look through nodes we don't care about (otherwise, things
11604 // like register copies will interfere with trivial cases).
11606 SmallVector<const SDNode *, 16> Worklist;
11607 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11608 IE = Visited.end(); I != IE; ++I)
11609 if (*I != OriginalChain.getNode())
11610 Worklist.push_back(*I);
11612 while (!Worklist.empty()) {
11613 const SDNode *M = Worklist.pop_back_val();
11615 // We have already visited M, and want to make sure we've visited any uses
11616 // of M that we care about. For uses that we've not visisted, and don't
11617 // care about, queue them to the worklist.
11619 for (SDNode::use_iterator UI = M->use_begin(),
11620 UIE = M->use_end(); UI != UIE; ++UI)
11621 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11622 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11623 // We've not visited this use, and we care about it (it could have an
11624 // ordering dependency with the original node).
11626 Aliases.push_back(OriginalChain);
11630 // We've not visited this use, but we don't care about it. Mark it as
11631 // visited and enqueue it to the worklist.
11632 Worklist.push_back(*UI);
11637 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11638 /// for a better chain (aliasing node.)
11639 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11640 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
11642 // Accumulate all the aliases to this node.
11643 GatherAllAliases(N, OldChain, Aliases);
11645 // If no operands then chain to entry token.
11646 if (Aliases.size() == 0)
11647 return DAG.getEntryNode();
11649 // If a single operand then chain to it. We don't need to revisit it.
11650 if (Aliases.size() == 1)
11653 // Construct a custom tailored token factor.
11654 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
11657 // SelectionDAG::Combine - This is the entry point for the file.
11659 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11660 CodeGenOpt::Level OptLevel) {
11661 /// run - This is the main entry point to this class.
11663 DAGCombiner(*this, AA, OptLevel).Run(Level);