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 ConstantSDNode *CN = BV->getConstantSplatValue();
660 // BuildVectors can truncate their operands. Ignore that case here.
661 if (CN && CN->getValueType(0) == N.getValueType().getScalarType())
668 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
669 SDValue N0, SDValue N1) {
670 EVT VT = N0.getValueType();
671 if (N0.getOpcode() == Opc) {
672 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
673 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
674 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
675 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
676 if (!OpNode.getNode())
678 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
680 if (N0.hasOneUse()) {
681 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
683 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
684 if (!OpNode.getNode())
686 AddToWorkList(OpNode.getNode());
687 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
692 if (N1.getOpcode() == Opc) {
693 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
694 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
695 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
696 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
697 if (!OpNode.getNode())
699 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
701 if (N1.hasOneUse()) {
702 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
704 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
705 if (!OpNode.getNode())
707 AddToWorkList(OpNode.getNode());
708 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
716 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
718 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
720 DEBUG(dbgs() << "\nReplacing.1 ";
722 dbgs() << "\nWith: ";
723 To[0].getNode()->dump(&DAG);
724 dbgs() << " and " << NumTo-1 << " other values\n";
725 for (unsigned i = 0, e = NumTo; i != e; ++i)
726 assert((!To[i].getNode() ||
727 N->getValueType(i) == To[i].getValueType()) &&
728 "Cannot combine value to value of different type!"));
729 WorkListRemover DeadNodes(*this);
730 DAG.ReplaceAllUsesWith(N, To);
732 // Push the new nodes and any users onto the worklist
733 for (unsigned i = 0, e = NumTo; i != e; ++i) {
734 if (To[i].getNode()) {
735 AddToWorkList(To[i].getNode());
736 AddUsersToWorkList(To[i].getNode());
741 // Finally, if the node is now dead, remove it from the graph. The node
742 // may not be dead if the replacement process recursively simplified to
743 // something else needing this node.
744 if (N->use_empty()) {
745 // Nodes can be reintroduced into the worklist. Make sure we do not
746 // process a node that has been replaced.
747 removeFromWorkList(N);
749 // Finally, since the node is now dead, remove it from the graph.
752 return SDValue(N, 0);
756 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
757 // Replace all uses. If any nodes become isomorphic to other nodes and
758 // are deleted, make sure to remove them from our worklist.
759 WorkListRemover DeadNodes(*this);
760 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
762 // Push the new node and any (possibly new) users onto the worklist.
763 AddToWorkList(TLO.New.getNode());
764 AddUsersToWorkList(TLO.New.getNode());
766 // Finally, if the node is now dead, remove it from the graph. The node
767 // may not be dead if the replacement process recursively simplified to
768 // something else needing this node.
769 if (TLO.Old.getNode()->use_empty()) {
770 removeFromWorkList(TLO.Old.getNode());
772 // If the operands of this node are only used by the node, they will now
773 // be dead. Make sure to visit them first to delete dead nodes early.
774 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
775 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
776 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
778 DAG.DeleteNode(TLO.Old.getNode());
782 /// SimplifyDemandedBits - Check the specified integer node value to see if
783 /// it can be simplified or if things it uses can be simplified by bit
784 /// propagation. If so, return true.
785 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
786 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
787 APInt KnownZero, KnownOne;
788 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
792 AddToWorkList(Op.getNode());
794 // Replace the old value with the new one.
796 DEBUG(dbgs() << "\nReplacing.2 ";
797 TLO.Old.getNode()->dump(&DAG);
798 dbgs() << "\nWith: ";
799 TLO.New.getNode()->dump(&DAG);
802 CommitTargetLoweringOpt(TLO);
806 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
808 EVT VT = Load->getValueType(0);
809 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
811 DEBUG(dbgs() << "\nReplacing.9 ";
813 dbgs() << "\nWith: ";
814 Trunc.getNode()->dump(&DAG);
816 WorkListRemover DeadNodes(*this);
817 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
818 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
819 removeFromWorkList(Load);
820 DAG.DeleteNode(Load);
821 AddToWorkList(Trunc.getNode());
824 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
827 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
828 EVT MemVT = LD->getMemoryVT();
829 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
830 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
832 : LD->getExtensionType();
834 return DAG.getExtLoad(ExtType, dl, PVT,
835 LD->getChain(), LD->getBasePtr(),
836 MemVT, LD->getMemOperand());
839 unsigned Opc = Op.getOpcode();
842 case ISD::AssertSext:
843 return DAG.getNode(ISD::AssertSext, dl, PVT,
844 SExtPromoteOperand(Op.getOperand(0), PVT),
846 case ISD::AssertZext:
847 return DAG.getNode(ISD::AssertZext, dl, PVT,
848 ZExtPromoteOperand(Op.getOperand(0), PVT),
850 case ISD::Constant: {
852 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
853 return DAG.getNode(ExtOpc, dl, PVT, Op);
857 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
859 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
862 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
863 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
865 EVT OldVT = Op.getValueType();
867 bool Replace = false;
868 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
869 if (!NewOp.getNode())
871 AddToWorkList(NewOp.getNode());
874 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
875 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
876 DAG.getValueType(OldVT));
879 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
880 EVT OldVT = Op.getValueType();
882 bool Replace = false;
883 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
884 if (!NewOp.getNode())
886 AddToWorkList(NewOp.getNode());
889 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
890 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
893 /// PromoteIntBinOp - Promote the specified integer binary operation if the
894 /// target indicates it is beneficial. e.g. On x86, it's usually better to
895 /// promote i16 operations to i32 since i16 instructions are longer.
896 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
897 if (!LegalOperations)
900 EVT VT = Op.getValueType();
901 if (VT.isVector() || !VT.isInteger())
904 // If operation type is 'undesirable', e.g. i16 on x86, consider
906 unsigned Opc = Op.getOpcode();
907 if (TLI.isTypeDesirableForOp(Opc, VT))
911 // Consult target whether it is a good idea to promote this operation and
912 // what's the right type to promote it to.
913 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
914 assert(PVT != VT && "Don't know what type to promote to!");
916 bool Replace0 = false;
917 SDValue N0 = Op.getOperand(0);
918 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
922 bool Replace1 = false;
923 SDValue N1 = Op.getOperand(1);
928 NN1 = PromoteOperand(N1, PVT, Replace1);
933 AddToWorkList(NN0.getNode());
935 AddToWorkList(NN1.getNode());
938 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
940 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
942 DEBUG(dbgs() << "\nPromoting ";
943 Op.getNode()->dump(&DAG));
945 return DAG.getNode(ISD::TRUNCATE, dl, VT,
946 DAG.getNode(Opc, dl, PVT, NN0, NN1));
951 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
952 /// target indicates it is beneficial. e.g. On x86, it's usually better to
953 /// promote i16 operations to i32 since i16 instructions are longer.
954 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
955 if (!LegalOperations)
958 EVT VT = Op.getValueType();
959 if (VT.isVector() || !VT.isInteger())
962 // If operation type is 'undesirable', e.g. i16 on x86, consider
964 unsigned Opc = Op.getOpcode();
965 if (TLI.isTypeDesirableForOp(Opc, VT))
969 // Consult target whether it is a good idea to promote this operation and
970 // what's the right type to promote it to.
971 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
972 assert(PVT != VT && "Don't know what type to promote to!");
974 bool Replace = false;
975 SDValue N0 = Op.getOperand(0);
977 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
978 else if (Opc == ISD::SRL)
979 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
981 N0 = PromoteOperand(N0, PVT, Replace);
985 AddToWorkList(N0.getNode());
987 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
989 DEBUG(dbgs() << "\nPromoting ";
990 Op.getNode()->dump(&DAG));
992 return DAG.getNode(ISD::TRUNCATE, dl, VT,
993 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
998 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
999 if (!LegalOperations)
1002 EVT VT = Op.getValueType();
1003 if (VT.isVector() || !VT.isInteger())
1006 // If operation type is 'undesirable', e.g. i16 on x86, consider
1008 unsigned Opc = Op.getOpcode();
1009 if (TLI.isTypeDesirableForOp(Opc, VT))
1013 // Consult target whether it is a good idea to promote this operation and
1014 // what's the right type to promote it to.
1015 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1016 assert(PVT != VT && "Don't know what type to promote to!");
1017 // fold (aext (aext x)) -> (aext x)
1018 // fold (aext (zext x)) -> (zext x)
1019 // fold (aext (sext x)) -> (sext x)
1020 DEBUG(dbgs() << "\nPromoting ";
1021 Op.getNode()->dump(&DAG));
1022 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1027 bool DAGCombiner::PromoteLoad(SDValue Op) {
1028 if (!LegalOperations)
1031 EVT VT = Op.getValueType();
1032 if (VT.isVector() || !VT.isInteger())
1035 // If operation type is 'undesirable', e.g. i16 on x86, consider
1037 unsigned Opc = Op.getOpcode();
1038 if (TLI.isTypeDesirableForOp(Opc, VT))
1042 // Consult target whether it is a good idea to promote this operation and
1043 // what's the right type to promote it to.
1044 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1045 assert(PVT != VT && "Don't know what type to promote to!");
1048 SDNode *N = Op.getNode();
1049 LoadSDNode *LD = cast<LoadSDNode>(N);
1050 EVT MemVT = LD->getMemoryVT();
1051 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1052 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1054 : LD->getExtensionType();
1055 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1056 LD->getChain(), LD->getBasePtr(),
1057 MemVT, LD->getMemOperand());
1058 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1060 DEBUG(dbgs() << "\nPromoting ";
1063 Result.getNode()->dump(&DAG);
1065 WorkListRemover DeadNodes(*this);
1066 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1067 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1068 removeFromWorkList(N);
1070 AddToWorkList(Result.getNode());
1077 //===----------------------------------------------------------------------===//
1078 // Main DAG Combiner implementation
1079 //===----------------------------------------------------------------------===//
1081 void DAGCombiner::Run(CombineLevel AtLevel) {
1082 // set the instance variables, so that the various visit routines may use it.
1084 LegalOperations = Level >= AfterLegalizeVectorOps;
1085 LegalTypes = Level >= AfterLegalizeTypes;
1087 // Add all the dag nodes to the worklist.
1088 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1089 E = DAG.allnodes_end(); I != E; ++I)
1092 // Create a dummy node (which is not added to allnodes), that adds a reference
1093 // to the root node, preventing it from being deleted, and tracking any
1094 // changes of the root.
1095 HandleSDNode Dummy(DAG.getRoot());
1097 // The root of the dag may dangle to deleted nodes until the dag combiner is
1098 // done. Set it to null to avoid confusion.
1099 DAG.setRoot(SDValue());
1101 // while the worklist isn't empty, find a node and
1102 // try and combine it.
1103 while (!WorkListContents.empty()) {
1105 // The WorkListOrder holds the SDNodes in order, but it may contain
1107 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1108 // worklist *should* contain, and check the node we want to visit is should
1109 // actually be visited.
1111 N = WorkListOrder.pop_back_val();
1112 } while (!WorkListContents.erase(N));
1114 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1115 // N is deleted from the DAG, since they too may now be dead or may have a
1116 // reduced number of uses, allowing other xforms.
1117 if (N->use_empty() && N != &Dummy) {
1118 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1119 AddToWorkList(N->getOperand(i).getNode());
1125 SDValue RV = combine(N);
1132 // If we get back the same node we passed in, rather than a new node or
1133 // zero, we know that the node must have defined multiple values and
1134 // CombineTo was used. Since CombineTo takes care of the worklist
1135 // mechanics for us, we have no work to do in this case.
1136 if (RV.getNode() == N)
1139 assert(N->getOpcode() != ISD::DELETED_NODE &&
1140 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1141 "Node was deleted but visit returned new node!");
1143 DEBUG(dbgs() << "\nReplacing.3 ";
1145 dbgs() << "\nWith: ";
1146 RV.getNode()->dump(&DAG);
1149 // Transfer debug value.
1150 DAG.TransferDbgValues(SDValue(N, 0), RV);
1151 WorkListRemover DeadNodes(*this);
1152 if (N->getNumValues() == RV.getNode()->getNumValues())
1153 DAG.ReplaceAllUsesWith(N, RV.getNode());
1155 assert(N->getValueType(0) == RV.getValueType() &&
1156 N->getNumValues() == 1 && "Type mismatch");
1158 DAG.ReplaceAllUsesWith(N, &OpV);
1161 // Push the new node and any users onto the worklist
1162 AddToWorkList(RV.getNode());
1163 AddUsersToWorkList(RV.getNode());
1165 // Add any uses of the old node to the worklist in case this node is the
1166 // last one that uses them. They may become dead after this node is
1168 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1169 AddToWorkList(N->getOperand(i).getNode());
1171 // Finally, if the node is now dead, remove it from the graph. The node
1172 // may not be dead if the replacement process recursively simplified to
1173 // something else needing this node.
1174 if (N->use_empty()) {
1175 // Nodes can be reintroduced into the worklist. Make sure we do not
1176 // process a node that has been replaced.
1177 removeFromWorkList(N);
1179 // Finally, since the node is now dead, remove it from the graph.
1184 // If the root changed (e.g. it was a dead load, update the root).
1185 DAG.setRoot(Dummy.getValue());
1186 DAG.RemoveDeadNodes();
1189 SDValue DAGCombiner::visit(SDNode *N) {
1190 switch (N->getOpcode()) {
1192 case ISD::TokenFactor: return visitTokenFactor(N);
1193 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1194 case ISD::ADD: return visitADD(N);
1195 case ISD::SUB: return visitSUB(N);
1196 case ISD::ADDC: return visitADDC(N);
1197 case ISD::SUBC: return visitSUBC(N);
1198 case ISD::ADDE: return visitADDE(N);
1199 case ISD::SUBE: return visitSUBE(N);
1200 case ISD::MUL: return visitMUL(N);
1201 case ISD::SDIV: return visitSDIV(N);
1202 case ISD::UDIV: return visitUDIV(N);
1203 case ISD::SREM: return visitSREM(N);
1204 case ISD::UREM: return visitUREM(N);
1205 case ISD::MULHU: return visitMULHU(N);
1206 case ISD::MULHS: return visitMULHS(N);
1207 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1208 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1209 case ISD::SMULO: return visitSMULO(N);
1210 case ISD::UMULO: return visitUMULO(N);
1211 case ISD::SDIVREM: return visitSDIVREM(N);
1212 case ISD::UDIVREM: return visitUDIVREM(N);
1213 case ISD::AND: return visitAND(N);
1214 case ISD::OR: return visitOR(N);
1215 case ISD::XOR: return visitXOR(N);
1216 case ISD::SHL: return visitSHL(N);
1217 case ISD::SRA: return visitSRA(N);
1218 case ISD::SRL: return visitSRL(N);
1220 case ISD::ROTL: return visitRotate(N);
1221 case ISD::CTLZ: return visitCTLZ(N);
1222 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1223 case ISD::CTTZ: return visitCTTZ(N);
1224 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1225 case ISD::CTPOP: return visitCTPOP(N);
1226 case ISD::SELECT: return visitSELECT(N);
1227 case ISD::VSELECT: return visitVSELECT(N);
1228 case ISD::SELECT_CC: return visitSELECT_CC(N);
1229 case ISD::SETCC: return visitSETCC(N);
1230 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1231 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1232 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1233 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1234 case ISD::TRUNCATE: return visitTRUNCATE(N);
1235 case ISD::BITCAST: return visitBITCAST(N);
1236 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1237 case ISD::FADD: return visitFADD(N);
1238 case ISD::FSUB: return visitFSUB(N);
1239 case ISD::FMUL: return visitFMUL(N);
1240 case ISD::FMA: return visitFMA(N);
1241 case ISD::FDIV: return visitFDIV(N);
1242 case ISD::FREM: return visitFREM(N);
1243 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1244 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1245 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1246 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1247 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1248 case ISD::FP_ROUND: return visitFP_ROUND(N);
1249 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1250 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1251 case ISD::FNEG: return visitFNEG(N);
1252 case ISD::FABS: return visitFABS(N);
1253 case ISD::FFLOOR: return visitFFLOOR(N);
1254 case ISD::FCEIL: return visitFCEIL(N);
1255 case ISD::FTRUNC: return visitFTRUNC(N);
1256 case ISD::BRCOND: return visitBRCOND(N);
1257 case ISD::BR_CC: return visitBR_CC(N);
1258 case ISD::LOAD: return visitLOAD(N);
1259 case ISD::STORE: return visitSTORE(N);
1260 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1261 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1262 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1263 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1264 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1265 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1266 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1271 SDValue DAGCombiner::combine(SDNode *N) {
1272 SDValue RV = visit(N);
1274 // If nothing happened, try a target-specific DAG combine.
1275 if (!RV.getNode()) {
1276 assert(N->getOpcode() != ISD::DELETED_NODE &&
1277 "Node was deleted but visit returned NULL!");
1279 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1280 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1282 // Expose the DAG combiner to the target combiner impls.
1283 TargetLowering::DAGCombinerInfo
1284 DagCombineInfo(DAG, Level, false, this);
1286 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1290 // If nothing happened still, try promoting the operation.
1291 if (!RV.getNode()) {
1292 switch (N->getOpcode()) {
1300 RV = PromoteIntBinOp(SDValue(N, 0));
1305 RV = PromoteIntShiftOp(SDValue(N, 0));
1307 case ISD::SIGN_EXTEND:
1308 case ISD::ZERO_EXTEND:
1309 case ISD::ANY_EXTEND:
1310 RV = PromoteExtend(SDValue(N, 0));
1313 if (PromoteLoad(SDValue(N, 0)))
1319 // If N is a commutative binary node, try commuting it to enable more
1321 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1322 N->getNumValues() == 1) {
1323 SDValue N0 = N->getOperand(0);
1324 SDValue N1 = N->getOperand(1);
1326 // Constant operands are canonicalized to RHS.
1327 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1328 SDValue Ops[] = {N1, N0};
1330 if (const BinaryWithFlagsSDNode *BinNode =
1331 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1332 CSENode = DAG.getNodeIfExists(
1333 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1334 BinNode->hasNoSignedWrap(), BinNode->isExact());
1336 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1339 return SDValue(CSENode, 0);
1346 /// getInputChainForNode - Given a node, return its input chain if it has one,
1347 /// otherwise return a null sd operand.
1348 static SDValue getInputChainForNode(SDNode *N) {
1349 if (unsigned NumOps = N->getNumOperands()) {
1350 if (N->getOperand(0).getValueType() == MVT::Other)
1351 return N->getOperand(0);
1352 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1353 return N->getOperand(NumOps-1);
1354 for (unsigned i = 1; i < NumOps-1; ++i)
1355 if (N->getOperand(i).getValueType() == MVT::Other)
1356 return N->getOperand(i);
1361 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1362 // If N has two operands, where one has an input chain equal to the other,
1363 // the 'other' chain is redundant.
1364 if (N->getNumOperands() == 2) {
1365 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1366 return N->getOperand(0);
1367 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1368 return N->getOperand(1);
1371 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1372 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1373 SmallPtrSet<SDNode*, 16> SeenOps;
1374 bool Changed = false; // If we should replace this token factor.
1376 // Start out with this token factor.
1379 // Iterate through token factors. The TFs grows when new token factors are
1381 for (unsigned i = 0; i < TFs.size(); ++i) {
1382 SDNode *TF = TFs[i];
1384 // Check each of the operands.
1385 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1386 SDValue Op = TF->getOperand(i);
1388 switch (Op.getOpcode()) {
1389 case ISD::EntryToken:
1390 // Entry tokens don't need to be added to the list. They are
1395 case ISD::TokenFactor:
1396 if (Op.hasOneUse() &&
1397 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1398 // Queue up for processing.
1399 TFs.push_back(Op.getNode());
1400 // Clean up in case the token factor is removed.
1401 AddToWorkList(Op.getNode());
1408 // Only add if it isn't already in the list.
1409 if (SeenOps.insert(Op.getNode()))
1420 // If we've change things around then replace token factor.
1423 // The entry token is the only possible outcome.
1424 Result = DAG.getEntryNode();
1426 // New and improved token factor.
1427 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1430 // Don't add users to work list.
1431 return CombineTo(N, Result, false);
1437 /// MERGE_VALUES can always be eliminated.
1438 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1439 WorkListRemover DeadNodes(*this);
1440 // Replacing results may cause a different MERGE_VALUES to suddenly
1441 // be CSE'd with N, and carry its uses with it. Iterate until no
1442 // uses remain, to ensure that the node can be safely deleted.
1443 // First add the users of this node to the work list so that they
1444 // can be tried again once they have new operands.
1445 AddUsersToWorkList(N);
1447 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1448 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1449 } while (!N->use_empty());
1450 removeFromWorkList(N);
1452 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1456 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1457 SelectionDAG &DAG) {
1458 EVT VT = N0.getValueType();
1459 SDValue N00 = N0.getOperand(0);
1460 SDValue N01 = N0.getOperand(1);
1461 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1463 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1464 isa<ConstantSDNode>(N00.getOperand(1))) {
1465 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1466 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1467 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1468 N00.getOperand(0), N01),
1469 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1470 N00.getOperand(1), N01));
1471 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1477 SDValue DAGCombiner::visitADD(SDNode *N) {
1478 SDValue N0 = N->getOperand(0);
1479 SDValue N1 = N->getOperand(1);
1480 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1481 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1482 EVT VT = N0.getValueType();
1485 if (VT.isVector()) {
1486 SDValue FoldedVOp = SimplifyVBinOp(N);
1487 if (FoldedVOp.getNode()) return FoldedVOp;
1489 // fold (add x, 0) -> x, vector edition
1490 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1492 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1496 // fold (add x, undef) -> undef
1497 if (N0.getOpcode() == ISD::UNDEF)
1499 if (N1.getOpcode() == ISD::UNDEF)
1501 // fold (add c1, c2) -> c1+c2
1503 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1504 // canonicalize constant to RHS
1506 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1507 // fold (add x, 0) -> x
1508 if (N1C && N1C->isNullValue())
1510 // fold (add Sym, c) -> Sym+c
1511 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1512 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1513 GA->getOpcode() == ISD::GlobalAddress)
1514 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1516 (uint64_t)N1C->getSExtValue());
1517 // fold ((c1-A)+c2) -> (c1+c2)-A
1518 if (N1C && N0.getOpcode() == ISD::SUB)
1519 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1520 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1521 DAG.getConstant(N1C->getAPIntValue()+
1522 N0C->getAPIntValue(), VT),
1525 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1528 // fold ((0-A) + B) -> B-A
1529 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1530 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1531 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1532 // fold (A + (0-B)) -> A-B
1533 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1534 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1535 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1536 // fold (A+(B-A)) -> B
1537 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1538 return N1.getOperand(0);
1539 // fold ((B-A)+A) -> B
1540 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1541 return N0.getOperand(0);
1542 // fold (A+(B-(A+C))) to (B-C)
1543 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1544 N0 == N1.getOperand(1).getOperand(0))
1545 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1546 N1.getOperand(1).getOperand(1));
1547 // fold (A+(B-(C+A))) to (B-C)
1548 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1549 N0 == N1.getOperand(1).getOperand(1))
1550 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1551 N1.getOperand(1).getOperand(0));
1552 // fold (A+((B-A)+or-C)) to (B+or-C)
1553 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1554 N1.getOperand(0).getOpcode() == ISD::SUB &&
1555 N0 == N1.getOperand(0).getOperand(1))
1556 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1557 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1559 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1560 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1561 SDValue N00 = N0.getOperand(0);
1562 SDValue N01 = N0.getOperand(1);
1563 SDValue N10 = N1.getOperand(0);
1564 SDValue N11 = N1.getOperand(1);
1566 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1567 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1568 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1569 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1572 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1573 return SDValue(N, 0);
1575 // fold (a+b) -> (a|b) iff a and b share no bits.
1576 if (VT.isInteger() && !VT.isVector()) {
1577 APInt LHSZero, LHSOne;
1578 APInt RHSZero, RHSOne;
1579 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1581 if (LHSZero.getBoolValue()) {
1582 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1584 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1585 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1586 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1587 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1588 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1593 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1594 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1595 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1596 if (Result.getNode()) return Result;
1598 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1599 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1600 if (Result.getNode()) return Result;
1603 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1604 if (N1.getOpcode() == ISD::SHL &&
1605 N1.getOperand(0).getOpcode() == ISD::SUB)
1606 if (ConstantSDNode *C =
1607 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1608 if (C->getAPIntValue() == 0)
1609 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1610 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1611 N1.getOperand(0).getOperand(1),
1613 if (N0.getOpcode() == ISD::SHL &&
1614 N0.getOperand(0).getOpcode() == ISD::SUB)
1615 if (ConstantSDNode *C =
1616 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1617 if (C->getAPIntValue() == 0)
1618 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1619 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1620 N0.getOperand(0).getOperand(1),
1623 if (N1.getOpcode() == ISD::AND) {
1624 SDValue AndOp0 = N1.getOperand(0);
1625 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1626 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1627 unsigned DestBits = VT.getScalarType().getSizeInBits();
1629 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1630 // and similar xforms where the inner op is either ~0 or 0.
1631 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1633 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1637 // add (sext i1), X -> sub X, (zext i1)
1638 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1639 N0.getOperand(0).getValueType() == MVT::i1 &&
1640 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1642 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1643 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1649 SDValue DAGCombiner::visitADDC(SDNode *N) {
1650 SDValue N0 = N->getOperand(0);
1651 SDValue N1 = N->getOperand(1);
1652 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1653 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1654 EVT VT = N0.getValueType();
1656 // If the flag result is dead, turn this into an ADD.
1657 if (!N->hasAnyUseOfValue(1))
1658 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1659 DAG.getNode(ISD::CARRY_FALSE,
1660 SDLoc(N), MVT::Glue));
1662 // canonicalize constant to RHS.
1664 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1666 // fold (addc x, 0) -> x + no carry out
1667 if (N1C && N1C->isNullValue())
1668 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1669 SDLoc(N), MVT::Glue));
1671 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1672 APInt LHSZero, LHSOne;
1673 APInt RHSZero, RHSOne;
1674 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1676 if (LHSZero.getBoolValue()) {
1677 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1679 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1680 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1681 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1682 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1683 DAG.getNode(ISD::CARRY_FALSE,
1684 SDLoc(N), MVT::Glue));
1690 SDValue DAGCombiner::visitADDE(SDNode *N) {
1691 SDValue N0 = N->getOperand(0);
1692 SDValue N1 = N->getOperand(1);
1693 SDValue CarryIn = N->getOperand(2);
1694 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1695 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1697 // canonicalize constant to RHS
1699 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1702 // fold (adde x, y, false) -> (addc x, y)
1703 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1704 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1709 // Since it may not be valid to emit a fold to zero for vector initializers
1710 // check if we can before folding.
1711 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1713 bool LegalOperations, bool LegalTypes) {
1715 return DAG.getConstant(0, VT);
1716 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1717 return DAG.getConstant(0, VT);
1721 SDValue DAGCombiner::visitSUB(SDNode *N) {
1722 SDValue N0 = N->getOperand(0);
1723 SDValue N1 = N->getOperand(1);
1724 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1725 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1726 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1727 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1728 EVT VT = N0.getValueType();
1731 if (VT.isVector()) {
1732 SDValue FoldedVOp = SimplifyVBinOp(N);
1733 if (FoldedVOp.getNode()) return FoldedVOp;
1735 // fold (sub x, 0) -> x, vector edition
1736 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1740 // fold (sub x, x) -> 0
1741 // FIXME: Refactor this and xor and other similar operations together.
1743 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1744 // fold (sub c1, c2) -> c1-c2
1746 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1747 // fold (sub x, c) -> (add x, -c)
1749 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1750 DAG.getConstant(-N1C->getAPIntValue(), VT));
1751 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1752 if (N0C && N0C->isAllOnesValue())
1753 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1754 // fold A-(A-B) -> B
1755 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1756 return N1.getOperand(1);
1757 // fold (A+B)-A -> B
1758 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1759 return N0.getOperand(1);
1760 // fold (A+B)-B -> A
1761 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1762 return N0.getOperand(0);
1763 // fold C2-(A+C1) -> (C2-C1)-A
1764 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1765 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1767 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1770 // fold ((A+(B+or-C))-B) -> A+or-C
1771 if (N0.getOpcode() == ISD::ADD &&
1772 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1773 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1774 N0.getOperand(1).getOperand(0) == N1)
1775 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1776 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1777 // fold ((A+(C+B))-B) -> A+C
1778 if (N0.getOpcode() == ISD::ADD &&
1779 N0.getOperand(1).getOpcode() == ISD::ADD &&
1780 N0.getOperand(1).getOperand(1) == N1)
1781 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1782 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1783 // fold ((A-(B-C))-C) -> A-B
1784 if (N0.getOpcode() == ISD::SUB &&
1785 N0.getOperand(1).getOpcode() == ISD::SUB &&
1786 N0.getOperand(1).getOperand(1) == N1)
1787 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1788 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1790 // If either operand of a sub is undef, the result is undef
1791 if (N0.getOpcode() == ISD::UNDEF)
1793 if (N1.getOpcode() == ISD::UNDEF)
1796 // If the relocation model supports it, consider symbol offsets.
1797 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1798 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1799 // fold (sub Sym, c) -> Sym-c
1800 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1801 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1803 (uint64_t)N1C->getSExtValue());
1804 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1805 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1806 if (GA->getGlobal() == GB->getGlobal())
1807 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1814 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1815 SDValue N0 = N->getOperand(0);
1816 SDValue N1 = N->getOperand(1);
1817 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1818 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1819 EVT VT = N0.getValueType();
1821 // If the flag result is dead, turn this into an SUB.
1822 if (!N->hasAnyUseOfValue(1))
1823 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1824 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1827 // fold (subc x, x) -> 0 + no borrow
1829 return CombineTo(N, DAG.getConstant(0, VT),
1830 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1833 // fold (subc x, 0) -> x + no borrow
1834 if (N1C && N1C->isNullValue())
1835 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1838 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1839 if (N0C && N0C->isAllOnesValue())
1840 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1841 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1847 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1848 SDValue N0 = N->getOperand(0);
1849 SDValue N1 = N->getOperand(1);
1850 SDValue CarryIn = N->getOperand(2);
1852 // fold (sube x, y, false) -> (subc x, y)
1853 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1854 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1859 SDValue DAGCombiner::visitMUL(SDNode *N) {
1860 SDValue N0 = N->getOperand(0);
1861 SDValue N1 = N->getOperand(1);
1862 EVT VT = N0.getValueType();
1864 // fold (mul x, undef) -> 0
1865 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1866 return DAG.getConstant(0, VT);
1868 bool N0IsConst = false;
1869 bool N1IsConst = false;
1870 APInt ConstValue0, ConstValue1;
1872 if (VT.isVector()) {
1873 SDValue FoldedVOp = SimplifyVBinOp(N);
1874 if (FoldedVOp.getNode()) return FoldedVOp;
1876 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1877 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1879 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1880 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1882 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1883 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1887 // fold (mul c1, c2) -> c1*c2
1888 if (N0IsConst && N1IsConst)
1889 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1891 // canonicalize constant to RHS
1892 if (N0IsConst && !N1IsConst)
1893 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1894 // fold (mul x, 0) -> 0
1895 if (N1IsConst && ConstValue1 == 0)
1897 // We require a splat of the entire scalar bit width for non-contiguous
1900 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1901 // fold (mul x, 1) -> x
1902 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1904 // fold (mul x, -1) -> 0-x
1905 if (N1IsConst && ConstValue1.isAllOnesValue())
1906 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1907 DAG.getConstant(0, VT), N0);
1908 // fold (mul x, (1 << c)) -> x << c
1909 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1910 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1911 DAG.getConstant(ConstValue1.logBase2(),
1912 getShiftAmountTy(N0.getValueType())));
1913 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1914 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1915 unsigned Log2Val = (-ConstValue1).logBase2();
1916 // FIXME: If the input is something that is easily negated (e.g. a
1917 // single-use add), we should put the negate there.
1918 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1919 DAG.getConstant(0, VT),
1920 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1921 DAG.getConstant(Log2Val,
1922 getShiftAmountTy(N0.getValueType()))));
1926 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1927 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1928 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1929 isa<ConstantSDNode>(N0.getOperand(1)))) {
1930 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1931 N1, N0.getOperand(1));
1932 AddToWorkList(C3.getNode());
1933 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1934 N0.getOperand(0), C3);
1937 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1940 SDValue Sh(nullptr,0), Y(nullptr,0);
1941 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1942 if (N0.getOpcode() == ISD::SHL &&
1943 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1944 isa<ConstantSDNode>(N0.getOperand(1))) &&
1945 N0.getNode()->hasOneUse()) {
1947 } else if (N1.getOpcode() == ISD::SHL &&
1948 isa<ConstantSDNode>(N1.getOperand(1)) &&
1949 N1.getNode()->hasOneUse()) {
1954 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1955 Sh.getOperand(0), Y);
1956 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1957 Mul, Sh.getOperand(1));
1961 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1962 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1963 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1964 isa<ConstantSDNode>(N0.getOperand(1))))
1965 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1966 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1967 N0.getOperand(0), N1),
1968 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1969 N0.getOperand(1), N1));
1972 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1979 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1980 SDValue N0 = N->getOperand(0);
1981 SDValue N1 = N->getOperand(1);
1982 ConstantSDNode *N0C = isConstOrConstSplat(N0);
1983 ConstantSDNode *N1C = isConstOrConstSplat(N1);
1984 EVT VT = N->getValueType(0);
1987 if (VT.isVector()) {
1988 SDValue FoldedVOp = SimplifyVBinOp(N);
1989 if (FoldedVOp.getNode()) return FoldedVOp;
1992 // fold (sdiv c1, c2) -> c1/c2
1993 if (N0C && N1C && !N1C->isNullValue())
1994 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1995 // fold (sdiv X, 1) -> X
1996 if (N1C && N1C->getAPIntValue() == 1LL)
1998 // fold (sdiv X, -1) -> 0-X
1999 if (N1C && N1C->isAllOnesValue())
2000 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2001 DAG.getConstant(0, VT), N0);
2002 // If we know the sign bits of both operands are zero, strength reduce to a
2003 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2004 if (!VT.isVector()) {
2005 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2006 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2010 // fold (sdiv X, pow2) -> simple ops after legalize
2011 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2012 (-N1C->getAPIntValue()).isPowerOf2())) {
2013 // If dividing by powers of two is cheap, then don't perform the following
2015 if (TLI.isPow2DivCheap())
2018 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2020 // Splat the sign bit into the register
2022 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2023 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2024 getShiftAmountTy(N0.getValueType())));
2025 AddToWorkList(SGN.getNode());
2027 // Add (N0 < 0) ? abs2 - 1 : 0;
2029 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2030 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2031 getShiftAmountTy(SGN.getValueType())));
2032 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2033 AddToWorkList(SRL.getNode());
2034 AddToWorkList(ADD.getNode()); // Divide by pow2
2035 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2036 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2038 // If we're dividing by a positive value, we're done. Otherwise, we must
2039 // negate the result.
2040 if (N1C->getAPIntValue().isNonNegative())
2043 AddToWorkList(SRA.getNode());
2044 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2047 // if integer divide is expensive and we satisfy the requirements, emit an
2048 // alternate sequence.
2049 if (N1C && !TLI.isIntDivCheap()) {
2050 SDValue Op = BuildSDIV(N);
2051 if (Op.getNode()) return Op;
2055 if (N0.getOpcode() == ISD::UNDEF)
2056 return DAG.getConstant(0, VT);
2057 // X / undef -> undef
2058 if (N1.getOpcode() == ISD::UNDEF)
2064 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2065 SDValue N0 = N->getOperand(0);
2066 SDValue N1 = N->getOperand(1);
2067 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2068 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2069 EVT VT = N->getValueType(0);
2072 if (VT.isVector()) {
2073 SDValue FoldedVOp = SimplifyVBinOp(N);
2074 if (FoldedVOp.getNode()) return FoldedVOp;
2077 // fold (udiv c1, c2) -> c1/c2
2078 if (N0C && N1C && !N1C->isNullValue())
2079 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2080 // fold (udiv x, (1 << c)) -> x >>u c
2081 if (N1C && N1C->getAPIntValue().isPowerOf2())
2082 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2083 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2084 getShiftAmountTy(N0.getValueType())));
2085 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2086 if (N1.getOpcode() == ISD::SHL) {
2087 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2088 if (SHC->getAPIntValue().isPowerOf2()) {
2089 EVT ADDVT = N1.getOperand(1).getValueType();
2090 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2092 DAG.getConstant(SHC->getAPIntValue()
2095 AddToWorkList(Add.getNode());
2096 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2100 // fold (udiv x, c) -> alternate
2101 if (N1C && !TLI.isIntDivCheap()) {
2102 SDValue Op = BuildUDIV(N);
2103 if (Op.getNode()) return Op;
2107 if (N0.getOpcode() == ISD::UNDEF)
2108 return DAG.getConstant(0, VT);
2109 // X / undef -> undef
2110 if (N1.getOpcode() == ISD::UNDEF)
2116 SDValue DAGCombiner::visitSREM(SDNode *N) {
2117 SDValue N0 = N->getOperand(0);
2118 SDValue N1 = N->getOperand(1);
2119 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2120 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2121 EVT VT = N->getValueType(0);
2123 // fold (srem c1, c2) -> c1%c2
2124 if (N0C && N1C && !N1C->isNullValue())
2125 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2126 // If we know the sign bits of both operands are zero, strength reduce to a
2127 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2128 if (!VT.isVector()) {
2129 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2130 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2133 // If X/C can be simplified by the division-by-constant logic, lower
2134 // X%C to the equivalent of X-X/C*C.
2135 if (N1C && !N1C->isNullValue()) {
2136 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2137 AddToWorkList(Div.getNode());
2138 SDValue OptimizedDiv = combine(Div.getNode());
2139 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2140 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2142 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2143 AddToWorkList(Mul.getNode());
2149 if (N0.getOpcode() == ISD::UNDEF)
2150 return DAG.getConstant(0, VT);
2151 // X % undef -> undef
2152 if (N1.getOpcode() == ISD::UNDEF)
2158 SDValue DAGCombiner::visitUREM(SDNode *N) {
2159 SDValue N0 = N->getOperand(0);
2160 SDValue N1 = N->getOperand(1);
2161 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2162 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2163 EVT VT = N->getValueType(0);
2165 // fold (urem c1, c2) -> c1%c2
2166 if (N0C && N1C && !N1C->isNullValue())
2167 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2168 // fold (urem x, pow2) -> (and x, pow2-1)
2169 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2170 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2171 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2172 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2173 if (N1.getOpcode() == ISD::SHL) {
2174 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2175 if (SHC->getAPIntValue().isPowerOf2()) {
2177 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2178 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2180 AddToWorkList(Add.getNode());
2181 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2186 // If X/C can be simplified by the division-by-constant logic, lower
2187 // X%C to the equivalent of X-X/C*C.
2188 if (N1C && !N1C->isNullValue()) {
2189 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2190 AddToWorkList(Div.getNode());
2191 SDValue OptimizedDiv = combine(Div.getNode());
2192 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2193 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2195 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2196 AddToWorkList(Mul.getNode());
2202 if (N0.getOpcode() == ISD::UNDEF)
2203 return DAG.getConstant(0, VT);
2204 // X % undef -> undef
2205 if (N1.getOpcode() == ISD::UNDEF)
2211 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2212 SDValue N0 = N->getOperand(0);
2213 SDValue N1 = N->getOperand(1);
2214 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2215 EVT VT = N->getValueType(0);
2218 // fold (mulhs x, 0) -> 0
2219 if (N1C && N1C->isNullValue())
2221 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2222 if (N1C && N1C->getAPIntValue() == 1)
2223 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2224 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2225 getShiftAmountTy(N0.getValueType())));
2226 // fold (mulhs x, undef) -> 0
2227 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2228 return DAG.getConstant(0, VT);
2230 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2232 if (VT.isSimple() && !VT.isVector()) {
2233 MVT Simple = VT.getSimpleVT();
2234 unsigned SimpleSize = Simple.getSizeInBits();
2235 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2236 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2237 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2238 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2239 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2240 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2241 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2242 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2249 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2250 SDValue N0 = N->getOperand(0);
2251 SDValue N1 = N->getOperand(1);
2252 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2253 EVT VT = N->getValueType(0);
2256 // fold (mulhu x, 0) -> 0
2257 if (N1C && N1C->isNullValue())
2259 // fold (mulhu x, 1) -> 0
2260 if (N1C && N1C->getAPIntValue() == 1)
2261 return DAG.getConstant(0, N0.getValueType());
2262 // fold (mulhu x, undef) -> 0
2263 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2264 return DAG.getConstant(0, VT);
2266 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2268 if (VT.isSimple() && !VT.isVector()) {
2269 MVT Simple = VT.getSimpleVT();
2270 unsigned SimpleSize = Simple.getSizeInBits();
2271 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2272 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2273 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2274 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2275 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2276 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2277 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2278 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2285 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2286 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2287 /// that are being performed. Return true if a simplification was made.
2289 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2291 // If the high half is not needed, just compute the low half.
2292 bool HiExists = N->hasAnyUseOfValue(1);
2294 (!LegalOperations ||
2295 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2296 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2297 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2298 return CombineTo(N, Res, Res);
2301 // If the low half is not needed, just compute the high half.
2302 bool LoExists = N->hasAnyUseOfValue(0);
2304 (!LegalOperations ||
2305 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2306 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2307 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2308 return CombineTo(N, Res, Res);
2311 // If both halves are used, return as it is.
2312 if (LoExists && HiExists)
2315 // If the two computed results can be simplified separately, separate them.
2317 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2318 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2319 AddToWorkList(Lo.getNode());
2320 SDValue LoOpt = combine(Lo.getNode());
2321 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2322 (!LegalOperations ||
2323 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2324 return CombineTo(N, LoOpt, LoOpt);
2328 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2329 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2330 AddToWorkList(Hi.getNode());
2331 SDValue HiOpt = combine(Hi.getNode());
2332 if (HiOpt.getNode() && HiOpt != Hi &&
2333 (!LegalOperations ||
2334 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2335 return CombineTo(N, HiOpt, HiOpt);
2341 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2342 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2343 if (Res.getNode()) return Res;
2345 EVT VT = N->getValueType(0);
2348 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2350 if (VT.isSimple() && !VT.isVector()) {
2351 MVT Simple = VT.getSimpleVT();
2352 unsigned SimpleSize = Simple.getSizeInBits();
2353 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2354 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2355 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2356 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2357 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2358 // Compute the high part as N1.
2359 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2360 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2361 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2362 // Compute the low part as N0.
2363 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2364 return CombineTo(N, Lo, Hi);
2371 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2372 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2373 if (Res.getNode()) return Res;
2375 EVT VT = N->getValueType(0);
2378 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2380 if (VT.isSimple() && !VT.isVector()) {
2381 MVT Simple = VT.getSimpleVT();
2382 unsigned SimpleSize = Simple.getSizeInBits();
2383 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2384 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2385 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2386 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2387 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2388 // Compute the high part as N1.
2389 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2390 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2391 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2392 // Compute the low part as N0.
2393 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2394 return CombineTo(N, Lo, Hi);
2401 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2402 // (smulo x, 2) -> (saddo x, x)
2403 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2404 if (C2->getAPIntValue() == 2)
2405 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2406 N->getOperand(0), N->getOperand(0));
2411 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2412 // (umulo x, 2) -> (uaddo x, x)
2413 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2414 if (C2->getAPIntValue() == 2)
2415 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2416 N->getOperand(0), N->getOperand(0));
2421 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2422 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2423 if (Res.getNode()) return Res;
2428 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2429 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2430 if (Res.getNode()) return Res;
2435 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2436 /// two operands of the same opcode, try to simplify it.
2437 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2438 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2439 EVT VT = N0.getValueType();
2440 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2442 // Bail early if none of these transforms apply.
2443 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2445 // For each of OP in AND/OR/XOR:
2446 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2447 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2448 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2449 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2451 // do not sink logical op inside of a vector extend, since it may combine
2453 EVT Op0VT = N0.getOperand(0).getValueType();
2454 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2455 N0.getOpcode() == ISD::SIGN_EXTEND ||
2456 // Avoid infinite looping with PromoteIntBinOp.
2457 (N0.getOpcode() == ISD::ANY_EXTEND &&
2458 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2459 (N0.getOpcode() == ISD::TRUNCATE &&
2460 (!TLI.isZExtFree(VT, Op0VT) ||
2461 !TLI.isTruncateFree(Op0VT, VT)) &&
2462 TLI.isTypeLegal(Op0VT))) &&
2464 Op0VT == N1.getOperand(0).getValueType() &&
2465 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2466 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2467 N0.getOperand(0).getValueType(),
2468 N0.getOperand(0), N1.getOperand(0));
2469 AddToWorkList(ORNode.getNode());
2470 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2473 // For each of OP in SHL/SRL/SRA/AND...
2474 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2475 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2476 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2477 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2478 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2479 N0.getOperand(1) == N1.getOperand(1)) {
2480 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2481 N0.getOperand(0).getValueType(),
2482 N0.getOperand(0), N1.getOperand(0));
2483 AddToWorkList(ORNode.getNode());
2484 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2485 ORNode, N0.getOperand(1));
2488 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2489 // Only perform this optimization after type legalization and before
2490 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2491 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2492 // we don't want to undo this promotion.
2493 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2495 if ((N0.getOpcode() == ISD::BITCAST ||
2496 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2497 Level == AfterLegalizeTypes) {
2498 SDValue In0 = N0.getOperand(0);
2499 SDValue In1 = N1.getOperand(0);
2500 EVT In0Ty = In0.getValueType();
2501 EVT In1Ty = In1.getValueType();
2503 // If both incoming values are integers, and the original types are the
2505 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2506 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2507 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2508 AddToWorkList(Op.getNode());
2513 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2514 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2515 // If both shuffles use the same mask, and both shuffle within a single
2516 // vector, then it is worthwhile to move the swizzle after the operation.
2517 // The type-legalizer generates this pattern when loading illegal
2518 // vector types from memory. In many cases this allows additional shuffle
2520 // There are other cases where moving the shuffle after the xor/and/or
2521 // is profitable even if shuffles don't perform a swizzle.
2522 // If both shuffles use the same mask, and both shuffles have the same first
2523 // or second operand, then it might still be profitable to move the shuffle
2524 // after the xor/and/or operation.
2525 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2526 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2527 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2529 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2530 "Inputs to shuffles are not the same type");
2532 // Check that both shuffles use the same mask. The masks are known to be of
2533 // the same length because the result vector type is the same.
2534 // Check also that shuffles have only one use to avoid introducing extra
2536 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2537 SVN0->getMask().equals(SVN1->getMask())) {
2538 SDValue ShOp = N0->getOperand(1);
2540 // Don't try to fold this node if it requires introducing a
2541 // build vector of all zeros that might be illegal at this stage.
2542 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2544 ShOp = DAG.getConstant(0, VT);
2549 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2550 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2551 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2552 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2553 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2554 N0->getOperand(0), N1->getOperand(0));
2555 AddToWorkList(NewNode.getNode());
2556 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2557 &SVN0->getMask()[0]);
2560 // Don't try to fold this node if it requires introducing a
2561 // build vector of all zeros that might be illegal at this stage.
2562 ShOp = N0->getOperand(0);
2563 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2565 ShOp = DAG.getConstant(0, VT);
2570 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2571 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2572 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2573 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2574 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2575 N0->getOperand(1), N1->getOperand(1));
2576 AddToWorkList(NewNode.getNode());
2577 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2578 &SVN0->getMask()[0]);
2586 SDValue DAGCombiner::visitAND(SDNode *N) {
2587 SDValue N0 = N->getOperand(0);
2588 SDValue N1 = N->getOperand(1);
2589 SDValue LL, LR, RL, RR, CC0, CC1;
2590 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2591 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2592 EVT VT = N1.getValueType();
2593 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2596 if (VT.isVector()) {
2597 SDValue FoldedVOp = SimplifyVBinOp(N);
2598 if (FoldedVOp.getNode()) return FoldedVOp;
2600 // fold (and x, 0) -> 0, vector edition
2601 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2603 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2606 // fold (and x, -1) -> x, vector edition
2607 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2609 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2613 // fold (and x, undef) -> 0
2614 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2615 return DAG.getConstant(0, VT);
2616 // fold (and c1, c2) -> c1&c2
2618 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2619 // canonicalize constant to RHS
2621 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2622 // fold (and x, -1) -> x
2623 if (N1C && N1C->isAllOnesValue())
2625 // if (and x, c) is known to be zero, return 0
2626 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2627 APInt::getAllOnesValue(BitWidth)))
2628 return DAG.getConstant(0, VT);
2630 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2633 // fold (and (or x, C), D) -> D if (C & D) == D
2634 if (N1C && N0.getOpcode() == ISD::OR)
2635 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2636 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2638 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2639 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2640 SDValue N0Op0 = N0.getOperand(0);
2641 APInt Mask = ~N1C->getAPIntValue();
2642 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2643 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2644 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2645 N0.getValueType(), N0Op0);
2647 // Replace uses of the AND with uses of the Zero extend node.
2650 // We actually want to replace all uses of the any_extend with the
2651 // zero_extend, to avoid duplicating things. This will later cause this
2652 // AND to be folded.
2653 CombineTo(N0.getNode(), Zext);
2654 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2657 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2658 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2659 // already be zero by virtue of the width of the base type of the load.
2661 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2663 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2664 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2665 N0.getOpcode() == ISD::LOAD) {
2666 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2667 N0 : N0.getOperand(0) );
2669 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2670 // This can be a pure constant or a vector splat, in which case we treat the
2671 // vector as a scalar and use the splat value.
2672 APInt Constant = APInt::getNullValue(1);
2673 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2674 Constant = C->getAPIntValue();
2675 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2676 APInt SplatValue, SplatUndef;
2677 unsigned SplatBitSize;
2679 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2680 SplatBitSize, HasAnyUndefs);
2682 // Undef bits can contribute to a possible optimisation if set, so
2684 SplatValue |= SplatUndef;
2686 // The splat value may be something like "0x00FFFFFF", which means 0 for
2687 // the first vector value and FF for the rest, repeating. We need a mask
2688 // that will apply equally to all members of the vector, so AND all the
2689 // lanes of the constant together.
2690 EVT VT = Vector->getValueType(0);
2691 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2693 // If the splat value has been compressed to a bitlength lower
2694 // than the size of the vector lane, we need to re-expand it to
2696 if (BitWidth > SplatBitSize)
2697 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2698 SplatBitSize < BitWidth;
2699 SplatBitSize = SplatBitSize * 2)
2700 SplatValue |= SplatValue.shl(SplatBitSize);
2702 Constant = APInt::getAllOnesValue(BitWidth);
2703 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2704 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2708 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2709 // actually legal and isn't going to get expanded, else this is a false
2711 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2712 Load->getMemoryVT());
2714 // Resize the constant to the same size as the original memory access before
2715 // extension. If it is still the AllOnesValue then this AND is completely
2718 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2721 switch (Load->getExtensionType()) {
2722 default: B = false; break;
2723 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2725 case ISD::NON_EXTLOAD: B = true; break;
2728 if (B && Constant.isAllOnesValue()) {
2729 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2730 // preserve semantics once we get rid of the AND.
2731 SDValue NewLoad(Load, 0);
2732 if (Load->getExtensionType() == ISD::EXTLOAD) {
2733 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2734 Load->getValueType(0), SDLoc(Load),
2735 Load->getChain(), Load->getBasePtr(),
2736 Load->getOffset(), Load->getMemoryVT(),
2737 Load->getMemOperand());
2738 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2739 if (Load->getNumValues() == 3) {
2740 // PRE/POST_INC loads have 3 values.
2741 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2742 NewLoad.getValue(2) };
2743 CombineTo(Load, To, 3, true);
2745 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2749 // Fold the AND away, taking care not to fold to the old load node if we
2751 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2753 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2756 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2757 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2758 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2759 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2761 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2762 LL.getValueType().isInteger()) {
2763 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2764 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2765 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2766 LR.getValueType(), LL, RL);
2767 AddToWorkList(ORNode.getNode());
2768 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2770 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2771 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2772 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2773 LR.getValueType(), LL, RL);
2774 AddToWorkList(ANDNode.getNode());
2775 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2777 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2778 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2779 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2780 LR.getValueType(), LL, RL);
2781 AddToWorkList(ORNode.getNode());
2782 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2785 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2786 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2787 Op0 == Op1 && LL.getValueType().isInteger() &&
2788 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2789 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2790 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2791 cast<ConstantSDNode>(RR)->isNullValue()))) {
2792 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2793 LL, DAG.getConstant(1, LL.getValueType()));
2794 AddToWorkList(ADDNode.getNode());
2795 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2796 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2798 // canonicalize equivalent to ll == rl
2799 if (LL == RR && LR == RL) {
2800 Op1 = ISD::getSetCCSwappedOperands(Op1);
2803 if (LL == RL && LR == RR) {
2804 bool isInteger = LL.getValueType().isInteger();
2805 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2806 if (Result != ISD::SETCC_INVALID &&
2807 (!LegalOperations ||
2808 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2809 TLI.isOperationLegal(ISD::SETCC,
2810 getSetCCResultType(N0.getSimpleValueType())))))
2811 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2816 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2817 if (N0.getOpcode() == N1.getOpcode()) {
2818 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2819 if (Tmp.getNode()) return Tmp;
2822 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2823 // fold (and (sra)) -> (and (srl)) when possible.
2824 if (!VT.isVector() &&
2825 SimplifyDemandedBits(SDValue(N, 0)))
2826 return SDValue(N, 0);
2828 // fold (zext_inreg (extload x)) -> (zextload x)
2829 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2830 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2831 EVT MemVT = LN0->getMemoryVT();
2832 // If we zero all the possible extended bits, then we can turn this into
2833 // a zextload if we are running before legalize or the operation is legal.
2834 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2835 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2836 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2837 ((!LegalOperations && !LN0->isVolatile()) ||
2838 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2839 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2840 LN0->getChain(), LN0->getBasePtr(),
2841 MemVT, LN0->getMemOperand());
2843 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2844 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2847 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2848 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2850 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2851 EVT MemVT = LN0->getMemoryVT();
2852 // If we zero all the possible extended bits, then we can turn this into
2853 // a zextload if we are running before legalize or the operation is legal.
2854 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2855 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2856 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2857 ((!LegalOperations && !LN0->isVolatile()) ||
2858 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2859 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2860 LN0->getChain(), LN0->getBasePtr(),
2861 MemVT, LN0->getMemOperand());
2863 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2864 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2868 // fold (and (load x), 255) -> (zextload x, i8)
2869 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2870 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2871 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2872 (N0.getOpcode() == ISD::ANY_EXTEND &&
2873 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2874 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2875 LoadSDNode *LN0 = HasAnyExt
2876 ? cast<LoadSDNode>(N0.getOperand(0))
2877 : cast<LoadSDNode>(N0);
2878 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2879 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2880 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2881 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2882 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2883 EVT LoadedVT = LN0->getMemoryVT();
2885 if (ExtVT == LoadedVT &&
2886 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2887 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2890 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2891 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2892 LN0->getMemOperand());
2894 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2895 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2898 // Do not change the width of a volatile load.
2899 // Do not generate loads of non-round integer types since these can
2900 // be expensive (and would be wrong if the type is not byte sized).
2901 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2902 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2903 EVT PtrType = LN0->getOperand(1).getValueType();
2905 unsigned Alignment = LN0->getAlignment();
2906 SDValue NewPtr = LN0->getBasePtr();
2908 // For big endian targets, we need to add an offset to the pointer
2909 // to load the correct bytes. For little endian systems, we merely
2910 // need to read fewer bytes from the same pointer.
2911 if (TLI.isBigEndian()) {
2912 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2913 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2914 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2915 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2916 NewPtr, DAG.getConstant(PtrOff, PtrType));
2917 Alignment = MinAlign(Alignment, PtrOff);
2920 AddToWorkList(NewPtr.getNode());
2922 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2924 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2925 LN0->getChain(), NewPtr,
2926 LN0->getPointerInfo(),
2927 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2928 Alignment, LN0->getTBAAInfo());
2930 CombineTo(LN0, Load, Load.getValue(1));
2931 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2937 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2938 VT.getSizeInBits() <= 64) {
2939 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2940 APInt ADDC = ADDI->getAPIntValue();
2941 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2942 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2943 // immediate for an add, but it is legal if its top c2 bits are set,
2944 // transform the ADD so the immediate doesn't need to be materialized
2946 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2947 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2948 SRLI->getZExtValue());
2949 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2951 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2953 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2954 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2955 CombineTo(N0.getNode(), NewAdd);
2956 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2964 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2965 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2966 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2967 N0.getOperand(1), false);
2968 if (BSwap.getNode())
2975 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2977 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2978 bool DemandHighBits) {
2979 if (!LegalOperations)
2982 EVT VT = N->getValueType(0);
2983 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2985 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2988 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2989 bool LookPassAnd0 = false;
2990 bool LookPassAnd1 = false;
2991 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2993 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2995 if (N0.getOpcode() == ISD::AND) {
2996 if (!N0.getNode()->hasOneUse())
2998 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2999 if (!N01C || N01C->getZExtValue() != 0xFF00)
3001 N0 = N0.getOperand(0);
3002 LookPassAnd0 = true;
3005 if (N1.getOpcode() == ISD::AND) {
3006 if (!N1.getNode()->hasOneUse())
3008 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3009 if (!N11C || N11C->getZExtValue() != 0xFF)
3011 N1 = N1.getOperand(0);
3012 LookPassAnd1 = true;
3015 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3017 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3019 if (!N0.getNode()->hasOneUse() ||
3020 !N1.getNode()->hasOneUse())
3023 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3024 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3027 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3030 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3031 SDValue N00 = N0->getOperand(0);
3032 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3033 if (!N00.getNode()->hasOneUse())
3035 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3036 if (!N001C || N001C->getZExtValue() != 0xFF)
3038 N00 = N00.getOperand(0);
3039 LookPassAnd0 = true;
3042 SDValue N10 = N1->getOperand(0);
3043 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3044 if (!N10.getNode()->hasOneUse())
3046 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3047 if (!N101C || N101C->getZExtValue() != 0xFF00)
3049 N10 = N10.getOperand(0);
3050 LookPassAnd1 = true;
3056 // Make sure everything beyond the low halfword gets set to zero since the SRL
3057 // 16 will clear the top bits.
3058 unsigned OpSizeInBits = VT.getSizeInBits();
3059 if (DemandHighBits && OpSizeInBits > 16) {
3060 // If the left-shift isn't masked out then the only way this is a bswap is
3061 // if all bits beyond the low 8 are 0. In that case the entire pattern
3062 // reduces to a left shift anyway: leave it for other parts of the combiner.
3066 // However, if the right shift isn't masked out then it might be because
3067 // it's not needed. See if we can spot that too.
3068 if (!LookPassAnd1 &&
3069 !DAG.MaskedValueIsZero(
3070 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3074 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3075 if (OpSizeInBits > 16)
3076 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3077 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3081 /// isBSwapHWordElement - Return true if the specified node is an element
3082 /// that makes up a 32-bit packed halfword byteswap. i.e.
3083 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3084 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3085 if (!N.getNode()->hasOneUse())
3088 unsigned Opc = N.getOpcode();
3089 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3092 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3097 switch (N1C->getZExtValue()) {
3100 case 0xFF: Num = 0; break;
3101 case 0xFF00: Num = 1; break;
3102 case 0xFF0000: Num = 2; break;
3103 case 0xFF000000: Num = 3; break;
3106 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3107 SDValue N0 = N.getOperand(0);
3108 if (Opc == ISD::AND) {
3109 if (Num == 0 || Num == 2) {
3111 // (x >> 8) & 0xff0000
3112 if (N0.getOpcode() != ISD::SRL)
3114 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3115 if (!C || C->getZExtValue() != 8)
3118 // (x << 8) & 0xff00
3119 // (x << 8) & 0xff000000
3120 if (N0.getOpcode() != ISD::SHL)
3122 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3123 if (!C || C->getZExtValue() != 8)
3126 } else if (Opc == ISD::SHL) {
3128 // (x & 0xff0000) << 8
3129 if (Num != 0 && Num != 2)
3131 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3132 if (!C || C->getZExtValue() != 8)
3134 } else { // Opc == ISD::SRL
3135 // (x & 0xff00) >> 8
3136 // (x & 0xff000000) >> 8
3137 if (Num != 1 && Num != 3)
3139 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3140 if (!C || C->getZExtValue() != 8)
3147 Parts[Num] = N0.getOperand(0).getNode();
3151 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3152 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3153 /// => (rotl (bswap x), 16)
3154 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3155 if (!LegalOperations)
3158 EVT VT = N->getValueType(0);
3161 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3164 SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3166 // (or (or (and), (and)), (or (and), (and)))
3167 // (or (or (or (and), (and)), (and)), (and))
3168 if (N0.getOpcode() != ISD::OR)
3170 SDValue N00 = N0.getOperand(0);
3171 SDValue N01 = N0.getOperand(1);
3173 if (N1.getOpcode() == ISD::OR &&
3174 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3175 // (or (or (and), (and)), (or (and), (and)))
3176 SDValue N000 = N00.getOperand(0);
3177 if (!isBSwapHWordElement(N000, Parts))
3180 SDValue N001 = N00.getOperand(1);
3181 if (!isBSwapHWordElement(N001, Parts))
3183 SDValue N010 = N01.getOperand(0);
3184 if (!isBSwapHWordElement(N010, Parts))
3186 SDValue N011 = N01.getOperand(1);
3187 if (!isBSwapHWordElement(N011, Parts))
3190 // (or (or (or (and), (and)), (and)), (and))
3191 if (!isBSwapHWordElement(N1, Parts))
3193 if (!isBSwapHWordElement(N01, Parts))
3195 if (N00.getOpcode() != ISD::OR)
3197 SDValue N000 = N00.getOperand(0);
3198 if (!isBSwapHWordElement(N000, Parts))
3200 SDValue N001 = N00.getOperand(1);
3201 if (!isBSwapHWordElement(N001, Parts))
3205 // Make sure the parts are all coming from the same node.
3206 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3209 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3210 SDValue(Parts[0],0));
3212 // Result of the bswap should be rotated by 16. If it's not legal, then
3213 // do (x << 16) | (x >> 16).
3214 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3215 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3216 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3217 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3218 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3219 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3220 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3221 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3224 SDValue DAGCombiner::visitOR(SDNode *N) {
3225 SDValue N0 = N->getOperand(0);
3226 SDValue N1 = N->getOperand(1);
3227 SDValue LL, LR, RL, RR, CC0, CC1;
3228 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3229 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3230 EVT VT = N1.getValueType();
3233 if (VT.isVector()) {
3234 SDValue FoldedVOp = SimplifyVBinOp(N);
3235 if (FoldedVOp.getNode()) return FoldedVOp;
3237 // fold (or x, 0) -> x, vector edition
3238 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3240 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3243 // fold (or x, -1) -> -1, vector edition
3244 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3246 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3249 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3250 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3251 // Do this only if the resulting shuffle is legal.
3252 if (isa<ShuffleVectorSDNode>(N0) &&
3253 isa<ShuffleVectorSDNode>(N1) &&
3254 N0->getOperand(1) == N1->getOperand(1) &&
3255 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3256 bool CanFold = true;
3257 unsigned NumElts = VT.getVectorNumElements();
3258 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3259 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3260 // We construct two shuffle masks:
3261 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3262 // and N1 as the second operand.
3263 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3264 // and N0 as the second operand.
3265 // We do this because OR is commutable and therefore there might be
3266 // two ways to fold this node into a shuffle.
3267 SmallVector<int,4> Mask1;
3268 SmallVector<int,4> Mask2;
3270 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3271 int M0 = SV0->getMaskElt(i);
3272 int M1 = SV1->getMaskElt(i);
3274 // Both shuffle indexes are undef. Propagate Undef.
3275 if (M0 < 0 && M1 < 0) {
3276 Mask1.push_back(M0);
3277 Mask2.push_back(M0);
3281 if (M0 < 0 || M1 < 0 ||
3282 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3283 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3288 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3289 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3293 // Fold this sequence only if the resulting shuffle is 'legal'.
3294 if (TLI.isShuffleMaskLegal(Mask1, VT))
3295 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3296 N1->getOperand(0), &Mask1[0]);
3297 if (TLI.isShuffleMaskLegal(Mask2, VT))
3298 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3299 N0->getOperand(0), &Mask2[0]);
3304 // fold (or x, undef) -> -1
3305 if (!LegalOperations &&
3306 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3307 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3308 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3310 // fold (or c1, c2) -> c1|c2
3312 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3313 // canonicalize constant to RHS
3315 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3316 // fold (or x, 0) -> x
3317 if (N1C && N1C->isNullValue())
3319 // fold (or x, -1) -> -1
3320 if (N1C && N1C->isAllOnesValue())
3322 // fold (or x, c) -> c iff (x & ~c) == 0
3323 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3326 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3327 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3328 if (BSwap.getNode())
3330 BSwap = MatchBSwapHWordLow(N, N0, N1);
3331 if (BSwap.getNode())
3335 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3338 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3339 // iff (c1 & c2) == 0.
3340 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3341 isa<ConstantSDNode>(N0.getOperand(1))) {
3342 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3343 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3344 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3347 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3348 DAG.getNode(ISD::OR, SDLoc(N0), VT,
3349 N0.getOperand(0), N1), COR);
3352 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3353 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3354 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3355 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3357 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3358 LL.getValueType().isInteger()) {
3359 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3360 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3361 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3362 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3363 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3364 LR.getValueType(), LL, RL);
3365 AddToWorkList(ORNode.getNode());
3366 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3368 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3369 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3370 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3371 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3372 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3373 LR.getValueType(), LL, RL);
3374 AddToWorkList(ANDNode.getNode());
3375 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3378 // canonicalize equivalent to ll == rl
3379 if (LL == RR && LR == RL) {
3380 Op1 = ISD::getSetCCSwappedOperands(Op1);
3383 if (LL == RL && LR == RR) {
3384 bool isInteger = LL.getValueType().isInteger();
3385 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3386 if (Result != ISD::SETCC_INVALID &&
3387 (!LegalOperations ||
3388 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3389 TLI.isOperationLegal(ISD::SETCC,
3390 getSetCCResultType(N0.getValueType())))))
3391 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3396 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3397 if (N0.getOpcode() == N1.getOpcode()) {
3398 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3399 if (Tmp.getNode()) return Tmp;
3402 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3403 if (N0.getOpcode() == ISD::AND &&
3404 N1.getOpcode() == ISD::AND &&
3405 N0.getOperand(1).getOpcode() == ISD::Constant &&
3406 N1.getOperand(1).getOpcode() == ISD::Constant &&
3407 // Don't increase # computations.
3408 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3409 // We can only do this xform if we know that bits from X that are set in C2
3410 // but not in C1 are already zero. Likewise for Y.
3411 const APInt &LHSMask =
3412 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3413 const APInt &RHSMask =
3414 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3416 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3417 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3418 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3419 N0.getOperand(0), N1.getOperand(0));
3420 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3421 DAG.getConstant(LHSMask | RHSMask, VT));
3425 // See if this is some rotate idiom.
3426 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3427 return SDValue(Rot, 0);
3429 // Simplify the operands using demanded-bits information.
3430 if (!VT.isVector() &&
3431 SimplifyDemandedBits(SDValue(N, 0)))
3432 return SDValue(N, 0);
3437 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3438 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3439 if (Op.getOpcode() == ISD::AND) {
3440 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3441 Mask = Op.getOperand(1);
3442 Op = Op.getOperand(0);
3448 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3456 // Return true if we can prove that, whenever Neg and Pos are both in the
3457 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3458 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3460 // (or (shift1 X, Neg), (shift2 X, Pos))
3462 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3463 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3464 // to consider shift amounts with defined behavior.
3465 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3466 // If OpSize is a power of 2 then:
3468 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3469 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3471 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3472 // for the stronger condition:
3474 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3476 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3477 // we can just replace Neg with Neg' for the rest of the function.
3479 // In other cases we check for the even stronger condition:
3481 // Neg == OpSize - Pos [B]
3483 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3484 // behavior if Pos == 0 (and consequently Neg == OpSize).
3486 // We could actually use [A] whenever OpSize is a power of 2, but the
3487 // only extra cases that it would match are those uninteresting ones
3488 // where Neg and Pos are never in range at the same time. E.g. for
3489 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3490 // as well as (sub 32, Pos), but:
3492 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3494 // always invokes undefined behavior for 32-bit X.
3496 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3497 unsigned MaskLoBits = 0;
3498 if (Neg.getOpcode() == ISD::AND &&
3499 isPowerOf2_64(OpSize) &&
3500 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3501 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3502 Neg = Neg.getOperand(0);
3503 MaskLoBits = Log2_64(OpSize);
3506 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3507 if (Neg.getOpcode() != ISD::SUB)
3509 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3512 SDValue NegOp1 = Neg.getOperand(1);
3514 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3515 // Pos'. The truncation is redundant for the purpose of the equality.
3517 Pos.getOpcode() == ISD::AND &&
3518 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3519 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3520 Pos = Pos.getOperand(0);
3522 // The condition we need is now:
3524 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3526 // If NegOp1 == Pos then we need:
3528 // OpSize & Mask == NegC & Mask
3530 // (because "x & Mask" is a truncation and distributes through subtraction).
3533 Width = NegC->getAPIntValue();
3534 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3535 // Then the condition we want to prove becomes:
3537 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3539 // which, again because "x & Mask" is a truncation, becomes:
3541 // NegC & Mask == (OpSize - PosC) & Mask
3542 // OpSize & Mask == (NegC + PosC) & Mask
3543 else if (Pos.getOpcode() == ISD::ADD &&
3544 Pos.getOperand(0) == NegOp1 &&
3545 Pos.getOperand(1).getOpcode() == ISD::Constant)
3546 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3547 NegC->getAPIntValue());
3551 // Now we just need to check that OpSize & Mask == Width & Mask.
3553 // Opsize & Mask is 0 since Mask is Opsize - 1.
3554 return Width.getLoBits(MaskLoBits) == 0;
3555 return Width == OpSize;
3558 // A subroutine of MatchRotate used once we have found an OR of two opposite
3559 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3560 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3561 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3562 // Neg with outer conversions stripped away.
3563 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3564 SDValue Neg, SDValue InnerPos,
3565 SDValue InnerNeg, unsigned PosOpcode,
3566 unsigned NegOpcode, SDLoc DL) {
3567 // fold (or (shl x, (*ext y)),
3568 // (srl x, (*ext (sub 32, y)))) ->
3569 // (rotl x, y) or (rotr x, (sub 32, y))
3571 // fold (or (shl x, (*ext (sub 32, y))),
3572 // (srl x, (*ext y))) ->
3573 // (rotr x, y) or (rotl x, (sub 32, y))
3574 EVT VT = Shifted.getValueType();
3575 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3576 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3577 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3578 HasPos ? Pos : Neg).getNode();
3584 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3585 // idioms for rotate, and if the target supports rotation instructions, generate
3587 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3588 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3589 EVT VT = LHS.getValueType();
3590 if (!TLI.isTypeLegal(VT)) return nullptr;
3592 // The target must have at least one rotate flavor.
3593 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3594 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3595 if (!HasROTL && !HasROTR) return nullptr;
3597 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3598 SDValue LHSShift; // The shift.
3599 SDValue LHSMask; // AND value if any.
3600 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3601 return nullptr; // Not part of a rotate.
3603 SDValue RHSShift; // The shift.
3604 SDValue RHSMask; // AND value if any.
3605 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3606 return nullptr; // Not part of a rotate.
3608 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3609 return nullptr; // Not shifting the same value.
3611 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3612 return nullptr; // Shifts must disagree.
3614 // Canonicalize shl to left side in a shl/srl pair.
3615 if (RHSShift.getOpcode() == ISD::SHL) {
3616 std::swap(LHS, RHS);
3617 std::swap(LHSShift, RHSShift);
3618 std::swap(LHSMask , RHSMask );
3621 unsigned OpSizeInBits = VT.getSizeInBits();
3622 SDValue LHSShiftArg = LHSShift.getOperand(0);
3623 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3624 SDValue RHSShiftArg = RHSShift.getOperand(0);
3625 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3627 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3628 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3629 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3630 RHSShiftAmt.getOpcode() == ISD::Constant) {
3631 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3632 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3633 if ((LShVal + RShVal) != OpSizeInBits)
3636 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3637 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3639 // If there is an AND of either shifted operand, apply it to the result.
3640 if (LHSMask.getNode() || RHSMask.getNode()) {
3641 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3643 if (LHSMask.getNode()) {
3644 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3645 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3647 if (RHSMask.getNode()) {
3648 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3649 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3652 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3655 return Rot.getNode();
3658 // If there is a mask here, and we have a variable shift, we can't be sure
3659 // that we're masking out the right stuff.
3660 if (LHSMask.getNode() || RHSMask.getNode())
3663 // If the shift amount is sign/zext/any-extended just peel it off.
3664 SDValue LExtOp0 = LHSShiftAmt;
3665 SDValue RExtOp0 = RHSShiftAmt;
3666 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3667 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3668 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3669 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3670 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3671 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3672 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3673 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3674 LExtOp0 = LHSShiftAmt.getOperand(0);
3675 RExtOp0 = RHSShiftAmt.getOperand(0);
3678 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3679 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3683 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3684 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3691 SDValue DAGCombiner::visitXOR(SDNode *N) {
3692 SDValue N0 = N->getOperand(0);
3693 SDValue N1 = N->getOperand(1);
3694 SDValue LHS, RHS, CC;
3695 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3696 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3697 EVT VT = N0.getValueType();
3700 if (VT.isVector()) {
3701 SDValue FoldedVOp = SimplifyVBinOp(N);
3702 if (FoldedVOp.getNode()) return FoldedVOp;
3704 // fold (xor x, 0) -> x, vector edition
3705 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3707 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3711 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3712 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3713 return DAG.getConstant(0, VT);
3714 // fold (xor x, undef) -> undef
3715 if (N0.getOpcode() == ISD::UNDEF)
3717 if (N1.getOpcode() == ISD::UNDEF)
3719 // fold (xor c1, c2) -> c1^c2
3721 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3722 // canonicalize constant to RHS
3724 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3725 // fold (xor x, 0) -> x
3726 if (N1C && N1C->isNullValue())
3729 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3733 // fold !(x cc y) -> (x !cc y)
3734 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3735 bool isInt = LHS.getValueType().isInteger();
3736 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3739 if (!LegalOperations ||
3740 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3741 switch (N0.getOpcode()) {
3743 llvm_unreachable("Unhandled SetCC Equivalent!");
3745 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3746 case ISD::SELECT_CC:
3747 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3748 N0.getOperand(3), NotCC);
3753 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3754 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3755 N0.getNode()->hasOneUse() &&
3756 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3757 SDValue V = N0.getOperand(0);
3758 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3759 DAG.getConstant(1, V.getValueType()));
3760 AddToWorkList(V.getNode());
3761 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3764 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3765 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3766 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3767 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3768 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3769 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3770 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3771 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3772 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3773 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3776 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3777 if (N1C && N1C->isAllOnesValue() &&
3778 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3779 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3780 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3781 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3782 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3783 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3784 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3785 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3788 // fold (xor (and x, y), y) -> (and (not x), y)
3789 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3790 N0->getOperand(1) == N1) {
3791 SDValue X = N0->getOperand(0);
3792 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3793 AddToWorkList(NotX.getNode());
3794 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3796 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3797 if (N1C && N0.getOpcode() == ISD::XOR) {
3798 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3799 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3801 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3802 DAG.getConstant(N1C->getAPIntValue() ^
3803 N00C->getAPIntValue(), VT));
3805 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3806 DAG.getConstant(N1C->getAPIntValue() ^
3807 N01C->getAPIntValue(), VT));
3809 // fold (xor x, x) -> 0
3811 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3813 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3814 if (N0.getOpcode() == N1.getOpcode()) {
3815 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3816 if (Tmp.getNode()) return Tmp;
3819 // Simplify the expression using non-local knowledge.
3820 if (!VT.isVector() &&
3821 SimplifyDemandedBits(SDValue(N, 0)))
3822 return SDValue(N, 0);
3827 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3828 /// the shift amount is a constant.
3829 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3830 // We can't and shouldn't fold opaque constants.
3831 if (Amt->isOpaque())
3834 SDNode *LHS = N->getOperand(0).getNode();
3835 if (!LHS->hasOneUse()) return SDValue();
3837 // We want to pull some binops through shifts, so that we have (and (shift))
3838 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3839 // thing happens with address calculations, so it's important to canonicalize
3841 bool HighBitSet = false; // Can we transform this if the high bit is set?
3843 switch (LHS->getOpcode()) {
3844 default: return SDValue();
3847 HighBitSet = false; // We can only transform sra if the high bit is clear.
3850 HighBitSet = true; // We can only transform sra if the high bit is set.
3853 if (N->getOpcode() != ISD::SHL)
3854 return SDValue(); // only shl(add) not sr[al](add).
3855 HighBitSet = false; // We can only transform sra if the high bit is clear.
3859 // We require the RHS of the binop to be a constant and not opaque as well.
3860 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3861 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3863 // FIXME: disable this unless the input to the binop is a shift by a constant.
3864 // If it is not a shift, it pessimizes some common cases like:
3866 // void foo(int *X, int i) { X[i & 1235] = 1; }
3867 // int bar(int *X, int i) { return X[i & 255]; }
3868 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3869 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3870 BinOpLHSVal->getOpcode() != ISD::SRA &&
3871 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3872 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3875 EVT VT = N->getValueType(0);
3877 // If this is a signed shift right, and the high bit is modified by the
3878 // logical operation, do not perform the transformation. The highBitSet
3879 // boolean indicates the value of the high bit of the constant which would
3880 // cause it to be modified for this operation.
3881 if (N->getOpcode() == ISD::SRA) {
3882 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3883 if (BinOpRHSSignSet != HighBitSet)
3887 if (!TLI.isDesirableToCommuteWithShift(LHS))
3890 // Fold the constants, shifting the binop RHS by the shift amount.
3891 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3893 LHS->getOperand(1), N->getOperand(1));
3894 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3896 // Create the new shift.
3897 SDValue NewShift = DAG.getNode(N->getOpcode(),
3898 SDLoc(LHS->getOperand(0)),
3899 VT, LHS->getOperand(0), N->getOperand(1));
3901 // Create the new binop.
3902 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3905 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3906 assert(N->getOpcode() == ISD::TRUNCATE);
3907 assert(N->getOperand(0).getOpcode() == ISD::AND);
3909 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3910 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3911 SDValue N01 = N->getOperand(0).getOperand(1);
3913 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3914 EVT TruncVT = N->getValueType(0);
3915 SDValue N00 = N->getOperand(0).getOperand(0);
3916 APInt TruncC = N01C->getAPIntValue();
3917 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3919 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3920 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3921 DAG.getConstant(TruncC, TruncVT));
3928 SDValue DAGCombiner::visitRotate(SDNode *N) {
3929 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3930 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3931 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3932 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3933 if (NewOp1.getNode())
3934 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3935 N->getOperand(0), NewOp1);
3940 SDValue DAGCombiner::visitSHL(SDNode *N) {
3941 SDValue N0 = N->getOperand(0);
3942 SDValue N1 = N->getOperand(1);
3943 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3944 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3945 EVT VT = N0.getValueType();
3946 unsigned OpSizeInBits = VT.getScalarSizeInBits();
3949 if (VT.isVector()) {
3950 SDValue FoldedVOp = SimplifyVBinOp(N);
3951 if (FoldedVOp.getNode()) return FoldedVOp;
3953 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3954 // If setcc produces all-one true value then:
3955 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
3956 if (N1CV && N1CV->isConstant()) {
3957 if (N0.getOpcode() == ISD::AND &&
3958 TLI.getBooleanContents(true) ==
3959 TargetLowering::ZeroOrNegativeOneBooleanContent) {
3960 SDValue N00 = N0->getOperand(0);
3961 SDValue N01 = N0->getOperand(1);
3962 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
3964 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC) {
3965 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3967 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3970 N1C = isConstOrConstSplat(N1);
3975 // fold (shl c1, c2) -> c1<<c2
3977 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3978 // fold (shl 0, x) -> 0
3979 if (N0C && N0C->isNullValue())
3981 // fold (shl x, c >= size(x)) -> undef
3982 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3983 return DAG.getUNDEF(VT);
3984 // fold (shl x, 0) -> x
3985 if (N1C && N1C->isNullValue())
3987 // fold (shl undef, x) -> 0
3988 if (N0.getOpcode() == ISD::UNDEF)
3989 return DAG.getConstant(0, VT);
3990 // if (shl x, c) is known to be zero, return 0
3991 if (DAG.MaskedValueIsZero(SDValue(N, 0),
3992 APInt::getAllOnesValue(OpSizeInBits)))
3993 return DAG.getConstant(0, VT);
3994 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3995 if (N1.getOpcode() == ISD::TRUNCATE &&
3996 N1.getOperand(0).getOpcode() == ISD::AND) {
3997 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
3998 if (NewOp1.getNode())
3999 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4002 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4003 return SDValue(N, 0);
4005 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4006 if (N1C && N0.getOpcode() == ISD::SHL) {
4007 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4008 uint64_t c1 = N0C1->getZExtValue();
4009 uint64_t c2 = N1C->getZExtValue();
4010 if (c1 + c2 >= OpSizeInBits)
4011 return DAG.getConstant(0, VT);
4012 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4013 DAG.getConstant(c1 + c2, N1.getValueType()));
4017 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4018 // For this to be valid, the second form must not preserve any of the bits
4019 // that are shifted out by the inner shift in the first form. This means
4020 // the outer shift size must be >= the number of bits added by the ext.
4021 // As a corollary, we don't care what kind of ext it is.
4022 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4023 N0.getOpcode() == ISD::ANY_EXTEND ||
4024 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4025 N0.getOperand(0).getOpcode() == ISD::SHL) {
4026 SDValue N0Op0 = N0.getOperand(0);
4027 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4028 uint64_t c1 = N0Op0C1->getZExtValue();
4029 uint64_t c2 = N1C->getZExtValue();
4030 EVT InnerShiftVT = N0Op0.getValueType();
4031 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4032 if (c2 >= OpSizeInBits - InnerShiftSize) {
4033 if (c1 + c2 >= OpSizeInBits)
4034 return DAG.getConstant(0, VT);
4035 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4036 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4037 N0Op0->getOperand(0)),
4038 DAG.getConstant(c1 + c2, N1.getValueType()));
4043 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4044 // Only fold this if the inner zext has no other uses to avoid increasing
4045 // the total number of instructions.
4046 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4047 N0.getOperand(0).getOpcode() == ISD::SRL) {
4048 SDValue N0Op0 = N0.getOperand(0);
4049 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4050 uint64_t c1 = N0Op0C1->getZExtValue();
4051 if (c1 < VT.getScalarSizeInBits()) {
4052 uint64_t c2 = N1C->getZExtValue();
4054 SDValue NewOp0 = N0.getOperand(0);
4055 EVT CountVT = NewOp0.getOperand(1).getValueType();
4056 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4057 NewOp0, DAG.getConstant(c2, CountVT));
4058 AddToWorkList(NewSHL.getNode());
4059 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4065 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4066 // (and (srl x, (sub c1, c2), MASK)
4067 // Only fold this if the inner shift has no other uses -- if it does, folding
4068 // this will increase the total number of instructions.
4069 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4070 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4071 uint64_t c1 = N0C1->getZExtValue();
4072 if (c1 < OpSizeInBits) {
4073 uint64_t c2 = N1C->getZExtValue();
4074 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4077 Mask = Mask.shl(c2 - c1);
4078 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4079 DAG.getConstant(c2 - c1, N1.getValueType()));
4081 Mask = Mask.lshr(c1 - c2);
4082 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4083 DAG.getConstant(c1 - c2, N1.getValueType()));
4085 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4086 DAG.getConstant(Mask, VT));
4090 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4091 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4092 unsigned BitSize = VT.getScalarSizeInBits();
4093 SDValue HiBitsMask =
4094 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4095 BitSize - N1C->getZExtValue()), VT);
4096 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4101 SDValue NewSHL = visitShiftByConstant(N, N1C);
4102 if (NewSHL.getNode())
4109 SDValue DAGCombiner::visitSRA(SDNode *N) {
4110 SDValue N0 = N->getOperand(0);
4111 SDValue N1 = N->getOperand(1);
4112 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4113 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4114 EVT VT = N0.getValueType();
4115 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4118 if (VT.isVector()) {
4119 SDValue FoldedVOp = SimplifyVBinOp(N);
4120 if (FoldedVOp.getNode()) return FoldedVOp;
4122 N1C = isConstOrConstSplat(N1);
4125 // fold (sra c1, c2) -> (sra c1, c2)
4127 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4128 // fold (sra 0, x) -> 0
4129 if (N0C && N0C->isNullValue())
4131 // fold (sra -1, x) -> -1
4132 if (N0C && N0C->isAllOnesValue())
4134 // fold (sra x, (setge c, size(x))) -> undef
4135 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4136 return DAG.getUNDEF(VT);
4137 // fold (sra x, 0) -> x
4138 if (N1C && N1C->isNullValue())
4140 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4142 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4143 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4144 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4146 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4147 ExtVT, VT.getVectorNumElements());
4148 if ((!LegalOperations ||
4149 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4150 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4151 N0.getOperand(0), DAG.getValueType(ExtVT));
4154 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4155 if (N1C && N0.getOpcode() == ISD::SRA) {
4156 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4157 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4158 if (Sum >= OpSizeInBits)
4159 Sum = OpSizeInBits - 1;
4160 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4161 DAG.getConstant(Sum, N1.getValueType()));
4165 // fold (sra (shl X, m), (sub result_size, n))
4166 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4167 // result_size - n != m.
4168 // If truncate is free for the target sext(shl) is likely to result in better
4170 if (N0.getOpcode() == ISD::SHL && N1C) {
4171 // Get the two constanst of the shifts, CN0 = m, CN = n.
4172 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4174 LLVMContext &Ctx = *DAG.getContext();
4175 // Determine what the truncate's result bitsize and type would be.
4176 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4179 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4181 // Determine the residual right-shift amount.
4182 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4184 // If the shift is not a no-op (in which case this should be just a sign
4185 // extend already), the truncated to type is legal, sign_extend is legal
4186 // on that type, and the truncate to that type is both legal and free,
4187 // perform the transform.
4188 if ((ShiftAmt > 0) &&
4189 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4190 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4191 TLI.isTruncateFree(VT, TruncVT)) {
4193 SDValue Amt = DAG.getConstant(ShiftAmt,
4194 getShiftAmountTy(N0.getOperand(0).getValueType()));
4195 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4196 N0.getOperand(0), Amt);
4197 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4199 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4200 N->getValueType(0), Trunc);
4205 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4206 if (N1.getOpcode() == ISD::TRUNCATE &&
4207 N1.getOperand(0).getOpcode() == ISD::AND) {
4208 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4209 if (NewOp1.getNode())
4210 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4213 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4214 // if c1 is equal to the number of bits the trunc removes
4215 if (N0.getOpcode() == ISD::TRUNCATE &&
4216 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4217 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4218 N0.getOperand(0).hasOneUse() &&
4219 N0.getOperand(0).getOperand(1).hasOneUse() &&
4221 SDValue N0Op0 = N0.getOperand(0);
4222 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4223 unsigned LargeShiftVal = LargeShift->getZExtValue();
4224 EVT LargeVT = N0Op0.getValueType();
4226 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4228 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4229 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4230 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4231 N0Op0.getOperand(0), Amt);
4232 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4237 // Simplify, based on bits shifted out of the LHS.
4238 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4239 return SDValue(N, 0);
4242 // If the sign bit is known to be zero, switch this to a SRL.
4243 if (DAG.SignBitIsZero(N0))
4244 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4247 SDValue NewSRA = visitShiftByConstant(N, N1C);
4248 if (NewSRA.getNode())
4255 SDValue DAGCombiner::visitSRL(SDNode *N) {
4256 SDValue N0 = N->getOperand(0);
4257 SDValue N1 = N->getOperand(1);
4258 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4259 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4260 EVT VT = N0.getValueType();
4261 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4264 if (VT.isVector()) {
4265 SDValue FoldedVOp = SimplifyVBinOp(N);
4266 if (FoldedVOp.getNode()) return FoldedVOp;
4268 N1C = isConstOrConstSplat(N1);
4271 // fold (srl c1, c2) -> c1 >>u c2
4273 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4274 // fold (srl 0, x) -> 0
4275 if (N0C && N0C->isNullValue())
4277 // fold (srl x, c >= size(x)) -> undef
4278 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4279 return DAG.getUNDEF(VT);
4280 // fold (srl x, 0) -> x
4281 if (N1C && N1C->isNullValue())
4283 // if (srl x, c) is known to be zero, return 0
4284 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4285 APInt::getAllOnesValue(OpSizeInBits)))
4286 return DAG.getConstant(0, VT);
4288 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4289 if (N1C && N0.getOpcode() == ISD::SRL) {
4290 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4291 uint64_t c1 = N01C->getZExtValue();
4292 uint64_t c2 = N1C->getZExtValue();
4293 if (c1 + c2 >= OpSizeInBits)
4294 return DAG.getConstant(0, VT);
4295 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4296 DAG.getConstant(c1 + c2, N1.getValueType()));
4300 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4301 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4302 N0.getOperand(0).getOpcode() == ISD::SRL &&
4303 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4305 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4306 uint64_t c2 = N1C->getZExtValue();
4307 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4308 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4309 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4310 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4311 if (c1 + OpSizeInBits == InnerShiftSize) {
4312 if (c1 + c2 >= InnerShiftSize)
4313 return DAG.getConstant(0, VT);
4314 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4315 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4316 N0.getOperand(0)->getOperand(0),
4317 DAG.getConstant(c1 + c2, ShiftCountVT)));
4321 // fold (srl (shl x, c), c) -> (and x, cst2)
4322 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4323 unsigned BitSize = N0.getScalarValueSizeInBits();
4324 if (BitSize <= 64) {
4325 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4326 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4327 DAG.getConstant(~0ULL >> ShAmt, VT));
4331 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4332 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4333 // Shifting in all undef bits?
4334 EVT SmallVT = N0.getOperand(0).getValueType();
4335 unsigned BitSize = SmallVT.getScalarSizeInBits();
4336 if (N1C->getZExtValue() >= BitSize)
4337 return DAG.getUNDEF(VT);
4339 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4340 uint64_t ShiftAmt = N1C->getZExtValue();
4341 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4343 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4344 AddToWorkList(SmallShift.getNode());
4345 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4346 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4347 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4348 DAG.getConstant(Mask, VT));
4352 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4353 // bit, which is unmodified by sra.
4354 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4355 if (N0.getOpcode() == ISD::SRA)
4356 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4359 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4360 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4361 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4362 APInt KnownZero, KnownOne;
4363 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4365 // If any of the input bits are KnownOne, then the input couldn't be all
4366 // zeros, thus the result of the srl will always be zero.
4367 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4369 // If all of the bits input the to ctlz node are known to be zero, then
4370 // the result of the ctlz is "32" and the result of the shift is one.
4371 APInt UnknownBits = ~KnownZero;
4372 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4374 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4375 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4376 // Okay, we know that only that the single bit specified by UnknownBits
4377 // could be set on input to the CTLZ node. If this bit is set, the SRL
4378 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4379 // to an SRL/XOR pair, which is likely to simplify more.
4380 unsigned ShAmt = UnknownBits.countTrailingZeros();
4381 SDValue Op = N0.getOperand(0);
4384 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4385 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4386 AddToWorkList(Op.getNode());
4389 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4390 Op, DAG.getConstant(1, VT));
4394 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4395 if (N1.getOpcode() == ISD::TRUNCATE &&
4396 N1.getOperand(0).getOpcode() == ISD::AND) {
4397 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4398 if (NewOp1.getNode())
4399 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4402 // fold operands of srl based on knowledge that the low bits are not
4404 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4405 return SDValue(N, 0);
4408 SDValue NewSRL = visitShiftByConstant(N, N1C);
4409 if (NewSRL.getNode())
4413 // Attempt to convert a srl of a load into a narrower zero-extending load.
4414 SDValue NarrowLoad = ReduceLoadWidth(N);
4415 if (NarrowLoad.getNode())
4418 // Here is a common situation. We want to optimize:
4421 // %b = and i32 %a, 2
4422 // %c = srl i32 %b, 1
4423 // brcond i32 %c ...
4429 // %c = setcc eq %b, 0
4432 // However when after the source operand of SRL is optimized into AND, the SRL
4433 // itself may not be optimized further. Look for it and add the BRCOND into
4435 if (N->hasOneUse()) {
4436 SDNode *Use = *N->use_begin();
4437 if (Use->getOpcode() == ISD::BRCOND)
4439 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4440 // Also look pass the truncate.
4441 Use = *Use->use_begin();
4442 if (Use->getOpcode() == ISD::BRCOND)
4450 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4451 SDValue N0 = N->getOperand(0);
4452 EVT VT = N->getValueType(0);
4454 // fold (ctlz c1) -> c2
4455 if (isa<ConstantSDNode>(N0))
4456 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4460 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4461 SDValue N0 = N->getOperand(0);
4462 EVT VT = N->getValueType(0);
4464 // fold (ctlz_zero_undef c1) -> c2
4465 if (isa<ConstantSDNode>(N0))
4466 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4470 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4471 SDValue N0 = N->getOperand(0);
4472 EVT VT = N->getValueType(0);
4474 // fold (cttz c1) -> c2
4475 if (isa<ConstantSDNode>(N0))
4476 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4480 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4481 SDValue N0 = N->getOperand(0);
4482 EVT VT = N->getValueType(0);
4484 // fold (cttz_zero_undef c1) -> c2
4485 if (isa<ConstantSDNode>(N0))
4486 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4490 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4491 SDValue N0 = N->getOperand(0);
4492 EVT VT = N->getValueType(0);
4494 // fold (ctpop c1) -> c2
4495 if (isa<ConstantSDNode>(N0))
4496 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4500 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4501 SDValue N0 = N->getOperand(0);
4502 SDValue N1 = N->getOperand(1);
4503 SDValue N2 = N->getOperand(2);
4504 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4505 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4506 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4507 EVT VT = N->getValueType(0);
4508 EVT VT0 = N0.getValueType();
4510 // fold (select C, X, X) -> X
4513 // fold (select true, X, Y) -> X
4514 if (N0C && !N0C->isNullValue())
4516 // fold (select false, X, Y) -> Y
4517 if (N0C && N0C->isNullValue())
4519 // fold (select C, 1, X) -> (or C, X)
4520 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4521 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4522 // fold (select C, 0, 1) -> (xor C, 1)
4523 if (VT.isInteger() &&
4526 TLI.getBooleanContents(false) ==
4527 TargetLowering::ZeroOrOneBooleanContent)) &&
4528 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4531 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4532 N0, DAG.getConstant(1, VT0));
4533 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4534 N0, DAG.getConstant(1, VT0));
4535 AddToWorkList(XORNode.getNode());
4537 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4538 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4540 // fold (select C, 0, X) -> (and (not C), X)
4541 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4542 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4543 AddToWorkList(NOTNode.getNode());
4544 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4546 // fold (select C, X, 1) -> (or (not C), X)
4547 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4548 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4549 AddToWorkList(NOTNode.getNode());
4550 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4552 // fold (select C, X, 0) -> (and C, X)
4553 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4554 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4555 // fold (select X, X, Y) -> (or X, Y)
4556 // fold (select X, 1, Y) -> (or X, Y)
4557 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4558 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4559 // fold (select X, Y, X) -> (and X, Y)
4560 // fold (select X, Y, 0) -> (and X, Y)
4561 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4562 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4564 // If we can fold this based on the true/false value, do so.
4565 if (SimplifySelectOps(N, N1, N2))
4566 return SDValue(N, 0); // Don't revisit N.
4568 // fold selects based on a setcc into other things, such as min/max/abs
4569 if (N0.getOpcode() == ISD::SETCC) {
4570 if ((!LegalOperations &&
4571 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4572 TLI.isOperationLegal(ISD::SELECT_CC, VT))
4573 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4574 N0.getOperand(0), N0.getOperand(1),
4575 N1, N2, N0.getOperand(2));
4576 return SimplifySelect(SDLoc(N), N0, N1, N2);
4583 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4586 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4588 // Split the inputs.
4589 SDValue Lo, Hi, LL, LH, RL, RH;
4590 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4591 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4593 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4594 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4596 return std::make_pair(Lo, Hi);
4599 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4600 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4601 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4603 SDValue Cond = N->getOperand(0);
4604 SDValue LHS = N->getOperand(1);
4605 SDValue RHS = N->getOperand(2);
4606 MVT VT = N->getSimpleValueType(0);
4607 int NumElems = VT.getVectorNumElements();
4608 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4609 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4610 Cond.getOpcode() == ISD::BUILD_VECTOR);
4612 // We're sure we have an even number of elements due to the
4613 // concat_vectors we have as arguments to vselect.
4614 // Skip BV elements until we find one that's not an UNDEF
4615 // After we find an UNDEF element, keep looping until we get to half the
4616 // length of the BV and see if all the non-undef nodes are the same.
4617 ConstantSDNode *BottomHalf = nullptr;
4618 for (int i = 0; i < NumElems / 2; ++i) {
4619 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4622 if (BottomHalf == nullptr)
4623 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4624 else if (Cond->getOperand(i).getNode() != BottomHalf)
4628 // Do the same for the second half of the BuildVector
4629 ConstantSDNode *TopHalf = nullptr;
4630 for (int i = NumElems / 2; i < NumElems; ++i) {
4631 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4634 if (TopHalf == nullptr)
4635 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4636 else if (Cond->getOperand(i).getNode() != TopHalf)
4640 assert(TopHalf && BottomHalf &&
4641 "One half of the selector was all UNDEFs and the other was all the "
4642 "same value. This should have been addressed before this function.");
4644 ISD::CONCAT_VECTORS, dl, VT,
4645 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4646 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4649 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4650 SDValue N0 = N->getOperand(0);
4651 SDValue N1 = N->getOperand(1);
4652 SDValue N2 = N->getOperand(2);
4655 // Canonicalize integer abs.
4656 // vselect (setg[te] X, 0), X, -X ->
4657 // vselect (setgt X, -1), X, -X ->
4658 // vselect (setl[te] X, 0), -X, X ->
4659 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4660 if (N0.getOpcode() == ISD::SETCC) {
4661 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4662 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4664 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4666 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4667 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4668 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4669 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4670 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4671 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4672 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4675 EVT VT = LHS.getValueType();
4676 SDValue Shift = DAG.getNode(
4677 ISD::SRA, DL, VT, LHS,
4678 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4679 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4680 AddToWorkList(Shift.getNode());
4681 AddToWorkList(Add.getNode());
4682 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4686 // If the VSELECT result requires splitting and the mask is provided by a
4687 // SETCC, then split both nodes and its operands before legalization. This
4688 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4689 // and enables future optimizations (e.g. min/max pattern matching on X86).
4690 if (N0.getOpcode() == ISD::SETCC) {
4691 EVT VT = N->getValueType(0);
4693 // Check if any splitting is required.
4694 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4695 TargetLowering::TypeSplitVector)
4698 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4699 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4700 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4701 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4703 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4704 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4706 // Add the new VSELECT nodes to the work list in case they need to be split
4708 AddToWorkList(Lo.getNode());
4709 AddToWorkList(Hi.getNode());
4711 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4714 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4715 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4717 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4718 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4721 // The ConvertSelectToConcatVector function is assuming both the above
4722 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4724 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4725 N2.getOpcode() == ISD::CONCAT_VECTORS &&
4726 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4727 SDValue CV = ConvertSelectToConcatVector(N, DAG);
4735 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4736 SDValue N0 = N->getOperand(0);
4737 SDValue N1 = N->getOperand(1);
4738 SDValue N2 = N->getOperand(2);
4739 SDValue N3 = N->getOperand(3);
4740 SDValue N4 = N->getOperand(4);
4741 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4743 // fold select_cc lhs, rhs, x, x, cc -> x
4747 // Determine if the condition we're dealing with is constant
4748 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4749 N0, N1, CC, SDLoc(N), false);
4750 if (SCC.getNode()) {
4751 AddToWorkList(SCC.getNode());
4753 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4754 if (!SCCC->isNullValue())
4755 return N2; // cond always true -> true val
4757 return N3; // cond always false -> false val
4760 // Fold to a simpler select_cc
4761 if (SCC.getOpcode() == ISD::SETCC)
4762 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4763 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4767 // If we can fold this based on the true/false value, do so.
4768 if (SimplifySelectOps(N, N2, N3))
4769 return SDValue(N, 0); // Don't revisit N.
4771 // fold select_cc into other things, such as min/max/abs
4772 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4775 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4776 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4777 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4781 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4782 // dag node into a ConstantSDNode or a build_vector of constants.
4783 // This function is called by the DAGCombiner when visiting sext/zext/aext
4784 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4785 // Vector extends are not folded if operations are legal; this is to
4786 // avoid introducing illegal build_vector dag nodes.
4787 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4788 SelectionDAG &DAG, bool LegalTypes,
4789 bool LegalOperations) {
4790 unsigned Opcode = N->getOpcode();
4791 SDValue N0 = N->getOperand(0);
4792 EVT VT = N->getValueType(0);
4794 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4795 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4797 // fold (sext c1) -> c1
4798 // fold (zext c1) -> c1
4799 // fold (aext c1) -> c1
4800 if (isa<ConstantSDNode>(N0))
4801 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4803 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4804 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4805 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4806 EVT SVT = VT.getScalarType();
4807 if (!(VT.isVector() &&
4808 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4809 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4812 // We can fold this node into a build_vector.
4813 unsigned VTBits = SVT.getSizeInBits();
4814 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4815 unsigned ShAmt = VTBits - EVTBits;
4816 SmallVector<SDValue, 8> Elts;
4817 unsigned NumElts = N0->getNumOperands();
4820 for (unsigned i=0; i != NumElts; ++i) {
4821 SDValue Op = N0->getOperand(i);
4822 if (Op->getOpcode() == ISD::UNDEF) {
4823 Elts.push_back(DAG.getUNDEF(SVT));
4827 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4828 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4829 if (Opcode == ISD::SIGN_EXTEND)
4830 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4833 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4837 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4840 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4841 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4842 // transformation. Returns true if extension are possible and the above
4843 // mentioned transformation is profitable.
4844 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4846 SmallVectorImpl<SDNode *> &ExtendNodes,
4847 const TargetLowering &TLI) {
4848 bool HasCopyToRegUses = false;
4849 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4850 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4851 UE = N0.getNode()->use_end();
4856 if (UI.getUse().getResNo() != N0.getResNo())
4858 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4859 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4860 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4861 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4862 // Sign bits will be lost after a zext.
4865 for (unsigned i = 0; i != 2; ++i) {
4866 SDValue UseOp = User->getOperand(i);
4869 if (!isa<ConstantSDNode>(UseOp))
4874 ExtendNodes.push_back(User);
4877 // If truncates aren't free and there are users we can't
4878 // extend, it isn't worthwhile.
4881 // Remember if this value is live-out.
4882 if (User->getOpcode() == ISD::CopyToReg)
4883 HasCopyToRegUses = true;
4886 if (HasCopyToRegUses) {
4887 bool BothLiveOut = false;
4888 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4890 SDUse &Use = UI.getUse();
4891 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4897 // Both unextended and extended values are live out. There had better be
4898 // a good reason for the transformation.
4899 return ExtendNodes.size();
4904 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4905 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4906 ISD::NodeType ExtType) {
4907 // Extend SetCC uses if necessary.
4908 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4909 SDNode *SetCC = SetCCs[i];
4910 SmallVector<SDValue, 4> Ops;
4912 for (unsigned j = 0; j != 2; ++j) {
4913 SDValue SOp = SetCC->getOperand(j);
4915 Ops.push_back(ExtLoad);
4917 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4920 Ops.push_back(SetCC->getOperand(2));
4921 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
4925 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4926 SDValue N0 = N->getOperand(0);
4927 EVT VT = N->getValueType(0);
4929 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4931 return SDValue(Res, 0);
4933 // fold (sext (sext x)) -> (sext x)
4934 // fold (sext (aext x)) -> (sext x)
4935 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4936 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4939 if (N0.getOpcode() == ISD::TRUNCATE) {
4940 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4941 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4942 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4943 if (NarrowLoad.getNode()) {
4944 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4945 if (NarrowLoad.getNode() != N0.getNode()) {
4946 CombineTo(N0.getNode(), NarrowLoad);
4947 // CombineTo deleted the truncate, if needed, but not what's under it.
4950 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4953 // See if the value being truncated is already sign extended. If so, just
4954 // eliminate the trunc/sext pair.
4955 SDValue Op = N0.getOperand(0);
4956 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4957 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4958 unsigned DestBits = VT.getScalarType().getSizeInBits();
4959 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4961 if (OpBits == DestBits) {
4962 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4963 // bits, it is already ready.
4964 if (NumSignBits > DestBits-MidBits)
4966 } else if (OpBits < DestBits) {
4967 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4968 // bits, just sext from i32.
4969 if (NumSignBits > OpBits-MidBits)
4970 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4972 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4973 // bits, just truncate to i32.
4974 if (NumSignBits > OpBits-MidBits)
4975 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4978 // fold (sext (truncate x)) -> (sextinreg x).
4979 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4980 N0.getValueType())) {
4981 if (OpBits < DestBits)
4982 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4983 else if (OpBits > DestBits)
4984 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4985 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4986 DAG.getValueType(N0.getValueType()));
4990 // fold (sext (load x)) -> (sext (truncate (sextload x)))
4991 // None of the supported targets knows how to perform load and sign extend
4992 // on vectors in one instruction. We only perform this transformation on
4994 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4995 ISD::isUNINDEXEDLoad(N0.getNode()) &&
4996 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4997 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4998 bool DoXform = true;
4999 SmallVector<SDNode*, 4> SetCCs;
5000 if (!N0.hasOneUse())
5001 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5003 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5004 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5006 LN0->getBasePtr(), N0.getValueType(),
5007 LN0->getMemOperand());
5008 CombineTo(N, ExtLoad);
5009 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5010 N0.getValueType(), ExtLoad);
5011 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5012 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5014 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5018 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5019 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5020 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5021 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5022 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5023 EVT MemVT = LN0->getMemoryVT();
5024 if ((!LegalOperations && !LN0->isVolatile()) ||
5025 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5026 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5028 LN0->getBasePtr(), MemVT,
5029 LN0->getMemOperand());
5030 CombineTo(N, ExtLoad);
5031 CombineTo(N0.getNode(),
5032 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5033 N0.getValueType(), ExtLoad),
5034 ExtLoad.getValue(1));
5035 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5039 // fold (sext (and/or/xor (load x), cst)) ->
5040 // (and/or/xor (sextload x), (sext cst))
5041 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5042 N0.getOpcode() == ISD::XOR) &&
5043 isa<LoadSDNode>(N0.getOperand(0)) &&
5044 N0.getOperand(1).getOpcode() == ISD::Constant &&
5045 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5046 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5047 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5048 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5049 bool DoXform = true;
5050 SmallVector<SDNode*, 4> SetCCs;
5051 if (!N0.hasOneUse())
5052 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5055 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5056 LN0->getChain(), LN0->getBasePtr(),
5058 LN0->getMemOperand());
5059 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5060 Mask = Mask.sext(VT.getSizeInBits());
5061 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5062 ExtLoad, DAG.getConstant(Mask, VT));
5063 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5064 SDLoc(N0.getOperand(0)),
5065 N0.getOperand(0).getValueType(), ExtLoad);
5067 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5068 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5070 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5075 if (N0.getOpcode() == ISD::SETCC) {
5076 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5077 // Only do this before legalize for now.
5078 if (VT.isVector() && !LegalOperations &&
5079 TLI.getBooleanContents(true) ==
5080 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5081 EVT N0VT = N0.getOperand(0).getValueType();
5082 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5083 // of the same size as the compared operands. Only optimize sext(setcc())
5084 // if this is the case.
5085 EVT SVT = getSetCCResultType(N0VT);
5087 // We know that the # elements of the results is the same as the
5088 // # elements of the compare (and the # elements of the compare result
5089 // for that matter). Check to see that they are the same size. If so,
5090 // we know that the element size of the sext'd result matches the
5091 // element size of the compare operands.
5092 if (VT.getSizeInBits() == SVT.getSizeInBits())
5093 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5095 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5097 // If the desired elements are smaller or larger than the source
5098 // elements we can use a matching integer vector type and then
5099 // truncate/sign extend
5100 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5101 if (SVT == MatchingVectorType) {
5102 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5103 N0.getOperand(0), N0.getOperand(1),
5104 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5105 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5109 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5110 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5112 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5114 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5115 NegOne, DAG.getConstant(0, VT),
5116 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5117 if (SCC.getNode()) return SCC;
5119 if (!VT.isVector()) {
5120 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5121 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5123 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5124 SDValue SetCC = DAG.getSetCC(DL,
5126 N0.getOperand(0), N0.getOperand(1), CC);
5127 EVT SelectVT = getSetCCResultType(VT);
5128 return DAG.getSelect(DL, VT,
5129 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5130 NegOne, DAG.getConstant(0, VT));
5136 // fold (sext x) -> (zext x) if the sign bit is known zero.
5137 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5138 DAG.SignBitIsZero(N0))
5139 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5144 // isTruncateOf - If N is a truncate of some other value, return true, record
5145 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5146 // This function computes KnownZero to avoid a duplicated call to
5147 // computeKnownBits in the caller.
5148 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5151 if (N->getOpcode() == ISD::TRUNCATE) {
5152 Op = N->getOperand(0);
5153 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5157 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5158 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5161 SDValue Op0 = N->getOperand(0);
5162 SDValue Op1 = N->getOperand(1);
5163 assert(Op0.getValueType() == Op1.getValueType());
5165 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5166 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5167 if (COp0 && COp0->isNullValue())
5169 else if (COp1 && COp1->isNullValue())
5174 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5176 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5182 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5183 SDValue N0 = N->getOperand(0);
5184 EVT VT = N->getValueType(0);
5186 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5188 return SDValue(Res, 0);
5190 // fold (zext (zext x)) -> (zext x)
5191 // fold (zext (aext x)) -> (zext x)
5192 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5193 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5196 // fold (zext (truncate x)) -> (zext x) or
5197 // (zext (truncate x)) -> (truncate x)
5198 // This is valid when the truncated bits of x are already zero.
5199 // FIXME: We should extend this to work for vectors too.
5202 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5203 APInt TruncatedBits =
5204 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5205 APInt(Op.getValueSizeInBits(), 0) :
5206 APInt::getBitsSet(Op.getValueSizeInBits(),
5207 N0.getValueSizeInBits(),
5208 std::min(Op.getValueSizeInBits(),
5209 VT.getSizeInBits()));
5210 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5211 if (VT.bitsGT(Op.getValueType()))
5212 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5213 if (VT.bitsLT(Op.getValueType()))
5214 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5220 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5221 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5222 if (N0.getOpcode() == ISD::TRUNCATE) {
5223 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5224 if (NarrowLoad.getNode()) {
5225 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5226 if (NarrowLoad.getNode() != N0.getNode()) {
5227 CombineTo(N0.getNode(), NarrowLoad);
5228 // CombineTo deleted the truncate, if needed, but not what's under it.
5231 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5235 // fold (zext (truncate x)) -> (and x, mask)
5236 if (N0.getOpcode() == ISD::TRUNCATE &&
5237 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5239 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5240 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5241 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5242 if (NarrowLoad.getNode()) {
5243 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5244 if (NarrowLoad.getNode() != N0.getNode()) {
5245 CombineTo(N0.getNode(), NarrowLoad);
5246 // CombineTo deleted the truncate, if needed, but not what's under it.
5249 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5252 SDValue Op = N0.getOperand(0);
5253 if (Op.getValueType().bitsLT(VT)) {
5254 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5255 AddToWorkList(Op.getNode());
5256 } else if (Op.getValueType().bitsGT(VT)) {
5257 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5258 AddToWorkList(Op.getNode());
5260 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5261 N0.getValueType().getScalarType());
5264 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5265 // if either of the casts is not free.
5266 if (N0.getOpcode() == ISD::AND &&
5267 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5268 N0.getOperand(1).getOpcode() == ISD::Constant &&
5269 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5270 N0.getValueType()) ||
5271 !TLI.isZExtFree(N0.getValueType(), VT))) {
5272 SDValue X = N0.getOperand(0).getOperand(0);
5273 if (X.getValueType().bitsLT(VT)) {
5274 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5275 } else if (X.getValueType().bitsGT(VT)) {
5276 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5278 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5279 Mask = Mask.zext(VT.getSizeInBits());
5280 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5281 X, DAG.getConstant(Mask, VT));
5284 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5285 // None of the supported targets knows how to perform load and vector_zext
5286 // on vectors in one instruction. We only perform this transformation on
5288 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5289 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5290 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5291 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5292 bool DoXform = true;
5293 SmallVector<SDNode*, 4> SetCCs;
5294 if (!N0.hasOneUse())
5295 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5297 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5298 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5300 LN0->getBasePtr(), N0.getValueType(),
5301 LN0->getMemOperand());
5302 CombineTo(N, ExtLoad);
5303 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5304 N0.getValueType(), ExtLoad);
5305 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5307 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5309 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5313 // fold (zext (and/or/xor (load x), cst)) ->
5314 // (and/or/xor (zextload x), (zext cst))
5315 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5316 N0.getOpcode() == ISD::XOR) &&
5317 isa<LoadSDNode>(N0.getOperand(0)) &&
5318 N0.getOperand(1).getOpcode() == ISD::Constant &&
5319 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5320 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5321 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5322 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5323 bool DoXform = true;
5324 SmallVector<SDNode*, 4> SetCCs;
5325 if (!N0.hasOneUse())
5326 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5329 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5330 LN0->getChain(), LN0->getBasePtr(),
5332 LN0->getMemOperand());
5333 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5334 Mask = Mask.zext(VT.getSizeInBits());
5335 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5336 ExtLoad, DAG.getConstant(Mask, VT));
5337 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5338 SDLoc(N0.getOperand(0)),
5339 N0.getOperand(0).getValueType(), ExtLoad);
5341 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5342 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5344 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5349 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5350 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5351 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5352 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5353 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5354 EVT MemVT = LN0->getMemoryVT();
5355 if ((!LegalOperations && !LN0->isVolatile()) ||
5356 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5357 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5359 LN0->getBasePtr(), MemVT,
5360 LN0->getMemOperand());
5361 CombineTo(N, ExtLoad);
5362 CombineTo(N0.getNode(),
5363 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5365 ExtLoad.getValue(1));
5366 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5370 if (N0.getOpcode() == ISD::SETCC) {
5371 if (!LegalOperations && VT.isVector() &&
5372 N0.getValueType().getVectorElementType() == MVT::i1) {
5373 EVT N0VT = N0.getOperand(0).getValueType();
5374 if (getSetCCResultType(N0VT) == N0.getValueType())
5377 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5378 // Only do this before legalize for now.
5379 EVT EltVT = VT.getVectorElementType();
5380 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5381 DAG.getConstant(1, EltVT));
5382 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5383 // We know that the # elements of the results is the same as the
5384 // # elements of the compare (and the # elements of the compare result
5385 // for that matter). Check to see that they are the same size. If so,
5386 // we know that the element size of the sext'd result matches the
5387 // element size of the compare operands.
5388 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5389 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5391 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5392 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5395 // If the desired elements are smaller or larger than the source
5396 // elements we can use a matching integer vector type and then
5397 // truncate/sign extend
5398 EVT MatchingElementType =
5399 EVT::getIntegerVT(*DAG.getContext(),
5400 N0VT.getScalarType().getSizeInBits());
5401 EVT MatchingVectorType =
5402 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5403 N0VT.getVectorNumElements());
5405 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5407 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5408 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5409 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5410 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5413 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5415 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5416 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5417 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5418 if (SCC.getNode()) return SCC;
5421 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5422 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5423 isa<ConstantSDNode>(N0.getOperand(1)) &&
5424 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5426 SDValue ShAmt = N0.getOperand(1);
5427 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5428 if (N0.getOpcode() == ISD::SHL) {
5429 SDValue InnerZExt = N0.getOperand(0);
5430 // If the original shl may be shifting out bits, do not perform this
5432 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5433 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5434 if (ShAmtVal > KnownZeroBits)
5440 // Ensure that the shift amount is wide enough for the shifted value.
5441 if (VT.getSizeInBits() >= 256)
5442 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5444 return DAG.getNode(N0.getOpcode(), DL, VT,
5445 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5452 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5453 SDValue N0 = N->getOperand(0);
5454 EVT VT = N->getValueType(0);
5456 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5458 return SDValue(Res, 0);
5460 // fold (aext (aext x)) -> (aext x)
5461 // fold (aext (zext x)) -> (zext x)
5462 // fold (aext (sext x)) -> (sext x)
5463 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5464 N0.getOpcode() == ISD::ZERO_EXTEND ||
5465 N0.getOpcode() == ISD::SIGN_EXTEND)
5466 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5468 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5469 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5470 if (N0.getOpcode() == ISD::TRUNCATE) {
5471 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5472 if (NarrowLoad.getNode()) {
5473 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5474 if (NarrowLoad.getNode() != N0.getNode()) {
5475 CombineTo(N0.getNode(), NarrowLoad);
5476 // CombineTo deleted the truncate, if needed, but not what's under it.
5479 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5483 // fold (aext (truncate x))
5484 if (N0.getOpcode() == ISD::TRUNCATE) {
5485 SDValue TruncOp = N0.getOperand(0);
5486 if (TruncOp.getValueType() == VT)
5487 return TruncOp; // x iff x size == zext size.
5488 if (TruncOp.getValueType().bitsGT(VT))
5489 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5490 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5493 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5494 // if the trunc is not free.
5495 if (N0.getOpcode() == ISD::AND &&
5496 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5497 N0.getOperand(1).getOpcode() == ISD::Constant &&
5498 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5499 N0.getValueType())) {
5500 SDValue X = N0.getOperand(0).getOperand(0);
5501 if (X.getValueType().bitsLT(VT)) {
5502 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5503 } else if (X.getValueType().bitsGT(VT)) {
5504 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5506 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5507 Mask = Mask.zext(VT.getSizeInBits());
5508 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5509 X, DAG.getConstant(Mask, VT));
5512 // fold (aext (load x)) -> (aext (truncate (extload x)))
5513 // None of the supported targets knows how to perform load and any_ext
5514 // on vectors in one instruction. We only perform this transformation on
5516 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5517 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5518 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5519 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5520 bool DoXform = true;
5521 SmallVector<SDNode*, 4> SetCCs;
5522 if (!N0.hasOneUse())
5523 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5525 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5526 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5528 LN0->getBasePtr(), N0.getValueType(),
5529 LN0->getMemOperand());
5530 CombineTo(N, ExtLoad);
5531 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5532 N0.getValueType(), ExtLoad);
5533 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5534 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5536 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5540 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5541 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5542 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5543 if (N0.getOpcode() == ISD::LOAD &&
5544 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5546 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5547 ISD::LoadExtType ExtType = LN0->getExtensionType();
5548 EVT MemVT = LN0->getMemoryVT();
5549 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5550 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5551 VT, LN0->getChain(), LN0->getBasePtr(),
5552 MemVT, LN0->getMemOperand());
5553 CombineTo(N, ExtLoad);
5554 CombineTo(N0.getNode(),
5555 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5556 N0.getValueType(), ExtLoad),
5557 ExtLoad.getValue(1));
5558 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5562 if (N0.getOpcode() == ISD::SETCC) {
5564 // aext(setcc) -> vsetcc
5565 // aext(setcc) -> truncate(vsetcc)
5566 // aext(setcc) -> aext(vsetcc)
5567 // Only do this before legalize for now.
5568 if (VT.isVector() && !LegalOperations) {
5569 EVT N0VT = N0.getOperand(0).getValueType();
5570 // We know that the # elements of the results is the same as the
5571 // # elements of the compare (and the # elements of the compare result
5572 // for that matter). Check to see that they are the same size. If so,
5573 // we know that the element size of the sext'd result matches the
5574 // element size of the compare operands.
5575 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5576 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5578 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5579 // If the desired elements are smaller or larger than the source
5580 // elements we can use a matching integer vector type and then
5581 // truncate/any extend
5583 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5585 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5587 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5588 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5592 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5594 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5595 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5596 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5604 /// GetDemandedBits - See if the specified operand can be simplified with the
5605 /// knowledge that only the bits specified by Mask are used. If so, return the
5606 /// simpler operand, otherwise return a null SDValue.
5607 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5608 switch (V.getOpcode()) {
5610 case ISD::Constant: {
5611 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5612 assert(CV && "Const value should be ConstSDNode.");
5613 const APInt &CVal = CV->getAPIntValue();
5614 APInt NewVal = CVal & Mask;
5616 return DAG.getConstant(NewVal, V.getValueType());
5621 // If the LHS or RHS don't contribute bits to the or, drop them.
5622 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5623 return V.getOperand(1);
5624 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5625 return V.getOperand(0);
5628 // Only look at single-use SRLs.
5629 if (!V.getNode()->hasOneUse())
5631 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5632 // See if we can recursively simplify the LHS.
5633 unsigned Amt = RHSC->getZExtValue();
5635 // Watch out for shift count overflow though.
5636 if (Amt >= Mask.getBitWidth()) break;
5637 APInt NewMask = Mask << Amt;
5638 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5639 if (SimplifyLHS.getNode())
5640 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5641 SimplifyLHS, V.getOperand(1));
5647 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5648 /// bits and then truncated to a narrower type and where N is a multiple
5649 /// of number of bits of the narrower type, transform it to a narrower load
5650 /// from address + N / num of bits of new type. If the result is to be
5651 /// extended, also fold the extension to form a extending load.
5652 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5653 unsigned Opc = N->getOpcode();
5655 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5656 SDValue N0 = N->getOperand(0);
5657 EVT VT = N->getValueType(0);
5660 // This transformation isn't valid for vector loads.
5664 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5666 if (Opc == ISD::SIGN_EXTEND_INREG) {
5667 ExtType = ISD::SEXTLOAD;
5668 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5669 } else if (Opc == ISD::SRL) {
5670 // Another special-case: SRL is basically zero-extending a narrower value.
5671 ExtType = ISD::ZEXTLOAD;
5673 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5674 if (!N01) return SDValue();
5675 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5676 VT.getSizeInBits() - N01->getZExtValue());
5678 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5681 unsigned EVTBits = ExtVT.getSizeInBits();
5683 // Do not generate loads of non-round integer types since these can
5684 // be expensive (and would be wrong if the type is not byte sized).
5685 if (!ExtVT.isRound())
5689 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5690 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5691 ShAmt = N01->getZExtValue();
5692 // Is the shift amount a multiple of size of VT?
5693 if ((ShAmt & (EVTBits-1)) == 0) {
5694 N0 = N0.getOperand(0);
5695 // Is the load width a multiple of size of VT?
5696 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5700 // At this point, we must have a load or else we can't do the transform.
5701 if (!isa<LoadSDNode>(N0)) return SDValue();
5703 // Because a SRL must be assumed to *need* to zero-extend the high bits
5704 // (as opposed to anyext the high bits), we can't combine the zextload
5705 // lowering of SRL and an sextload.
5706 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5709 // If the shift amount is larger than the input type then we're not
5710 // accessing any of the loaded bytes. If the load was a zextload/extload
5711 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5712 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5717 // If the load is shifted left (and the result isn't shifted back right),
5718 // we can fold the truncate through the shift.
5719 unsigned ShLeftAmt = 0;
5720 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5721 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5722 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5723 ShLeftAmt = N01->getZExtValue();
5724 N0 = N0.getOperand(0);
5728 // If we haven't found a load, we can't narrow it. Don't transform one with
5729 // multiple uses, this would require adding a new load.
5730 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5733 // Don't change the width of a volatile load.
5734 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5735 if (LN0->isVolatile())
5738 // Verify that we are actually reducing a load width here.
5739 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5742 // For the transform to be legal, the load must produce only two values
5743 // (the value loaded and the chain). Don't transform a pre-increment
5744 // load, for example, which produces an extra value. Otherwise the
5745 // transformation is not equivalent, and the downstream logic to replace
5746 // uses gets things wrong.
5747 if (LN0->getNumValues() > 2)
5750 // If the load that we're shrinking is an extload and we're not just
5751 // discarding the extension we can't simply shrink the load. Bail.
5752 // TODO: It would be possible to merge the extensions in some cases.
5753 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5754 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5757 EVT PtrType = N0.getOperand(1).getValueType();
5759 if (PtrType == MVT::Untyped || PtrType.isExtended())
5760 // It's not possible to generate a constant of extended or untyped type.
5763 // For big endian targets, we need to adjust the offset to the pointer to
5764 // load the correct bytes.
5765 if (TLI.isBigEndian()) {
5766 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5767 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5768 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5771 uint64_t PtrOff = ShAmt / 8;
5772 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5773 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5774 PtrType, LN0->getBasePtr(),
5775 DAG.getConstant(PtrOff, PtrType));
5776 AddToWorkList(NewPtr.getNode());
5779 if (ExtType == ISD::NON_EXTLOAD)
5780 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5781 LN0->getPointerInfo().getWithOffset(PtrOff),
5782 LN0->isVolatile(), LN0->isNonTemporal(),
5783 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5785 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5786 LN0->getPointerInfo().getWithOffset(PtrOff),
5787 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5788 NewAlign, LN0->getTBAAInfo());
5790 // Replace the old load's chain with the new load's chain.
5791 WorkListRemover DeadNodes(*this);
5792 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5794 // Shift the result left, if we've swallowed a left shift.
5795 SDValue Result = Load;
5796 if (ShLeftAmt != 0) {
5797 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5798 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5800 // If the shift amount is as large as the result size (but, presumably,
5801 // no larger than the source) then the useful bits of the result are
5802 // zero; we can't simply return the shortened shift, because the result
5803 // of that operation is undefined.
5804 if (ShLeftAmt >= VT.getSizeInBits())
5805 Result = DAG.getConstant(0, VT);
5807 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5808 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5811 // Return the new loaded value.
5815 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5816 SDValue N0 = N->getOperand(0);
5817 SDValue N1 = N->getOperand(1);
5818 EVT VT = N->getValueType(0);
5819 EVT EVT = cast<VTSDNode>(N1)->getVT();
5820 unsigned VTBits = VT.getScalarType().getSizeInBits();
5821 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5823 // fold (sext_in_reg c1) -> c1
5824 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5825 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5827 // If the input is already sign extended, just drop the extension.
5828 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5831 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5832 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5833 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5834 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5835 N0.getOperand(0), N1);
5837 // fold (sext_in_reg (sext x)) -> (sext x)
5838 // fold (sext_in_reg (aext x)) -> (sext x)
5839 // if x is small enough.
5840 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5841 SDValue N00 = N0.getOperand(0);
5842 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5843 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5844 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5847 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5848 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5849 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5851 // fold operands of sext_in_reg based on knowledge that the top bits are not
5853 if (SimplifyDemandedBits(SDValue(N, 0)))
5854 return SDValue(N, 0);
5856 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5857 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5858 SDValue NarrowLoad = ReduceLoadWidth(N);
5859 if (NarrowLoad.getNode())
5862 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5863 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5864 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5865 if (N0.getOpcode() == ISD::SRL) {
5866 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5867 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5868 // We can turn this into an SRA iff the input to the SRL is already sign
5870 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5871 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5872 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5873 N0.getOperand(0), N0.getOperand(1));
5877 // fold (sext_inreg (extload x)) -> (sextload x)
5878 if (ISD::isEXTLoad(N0.getNode()) &&
5879 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5880 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5881 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5882 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5883 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5884 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5886 LN0->getBasePtr(), EVT,
5887 LN0->getMemOperand());
5888 CombineTo(N, ExtLoad);
5889 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5890 AddToWorkList(ExtLoad.getNode());
5891 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5893 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5894 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5896 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5897 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5898 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5899 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5900 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5902 LN0->getBasePtr(), EVT,
5903 LN0->getMemOperand());
5904 CombineTo(N, ExtLoad);
5905 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5906 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5909 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5910 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5911 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5912 N0.getOperand(1), false);
5913 if (BSwap.getNode())
5914 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5918 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5919 // into a build_vector.
5920 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5921 SmallVector<SDValue, 8> Elts;
5922 unsigned NumElts = N0->getNumOperands();
5923 unsigned ShAmt = VTBits - EVTBits;
5925 for (unsigned i = 0; i != NumElts; ++i) {
5926 SDValue Op = N0->getOperand(i);
5927 if (Op->getOpcode() == ISD::UNDEF) {
5932 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5933 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5934 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5935 Op.getValueType()));
5938 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
5944 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5945 SDValue N0 = N->getOperand(0);
5946 EVT VT = N->getValueType(0);
5947 bool isLE = TLI.isLittleEndian();
5950 if (N0.getValueType() == N->getValueType(0))
5952 // fold (truncate c1) -> c1
5953 if (isa<ConstantSDNode>(N0))
5954 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5955 // fold (truncate (truncate x)) -> (truncate x)
5956 if (N0.getOpcode() == ISD::TRUNCATE)
5957 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5958 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5959 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5960 N0.getOpcode() == ISD::SIGN_EXTEND ||
5961 N0.getOpcode() == ISD::ANY_EXTEND) {
5962 if (N0.getOperand(0).getValueType().bitsLT(VT))
5963 // if the source is smaller than the dest, we still need an extend
5964 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5966 if (N0.getOperand(0).getValueType().bitsGT(VT))
5967 // if the source is larger than the dest, than we just need the truncate
5968 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5969 // if the source and dest are the same type, we can drop both the extend
5970 // and the truncate.
5971 return N0.getOperand(0);
5974 // Fold extract-and-trunc into a narrow extract. For example:
5975 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5976 // i32 y = TRUNCATE(i64 x)
5978 // v16i8 b = BITCAST (v2i64 val)
5979 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5981 // Note: We only run this optimization after type legalization (which often
5982 // creates this pattern) and before operation legalization after which
5983 // we need to be more careful about the vector instructions that we generate.
5984 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5985 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
5987 EVT VecTy = N0.getOperand(0).getValueType();
5988 EVT ExTy = N0.getValueType();
5989 EVT TrTy = N->getValueType(0);
5991 unsigned NumElem = VecTy.getVectorNumElements();
5992 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5994 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5995 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5997 SDValue EltNo = N0->getOperand(1);
5998 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5999 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6000 EVT IndexTy = TLI.getVectorIdxTy();
6001 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6003 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6004 NVT, N0.getOperand(0));
6006 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6008 DAG.getConstant(Index, IndexTy));
6012 // Fold a series of buildvector, bitcast, and truncate if possible.
6014 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6015 // (2xi32 (buildvector x, y)).
6016 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6017 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6018 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6019 N0.getOperand(0).hasOneUse()) {
6021 SDValue BuildVect = N0.getOperand(0);
6022 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6023 EVT TruncVecEltTy = VT.getVectorElementType();
6025 // Check that the element types match.
6026 if (BuildVectEltTy == TruncVecEltTy) {
6027 // Now we only need to compute the offset of the truncated elements.
6028 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6029 unsigned TruncVecNumElts = VT.getVectorNumElements();
6030 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6032 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6033 "Invalid number of elements");
6035 SmallVector<SDValue, 8> Opnds;
6036 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6037 Opnds.push_back(BuildVect.getOperand(i));
6039 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6043 // See if we can simplify the input to this truncate through knowledge that
6044 // only the low bits are being used.
6045 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6046 // Currently we only perform this optimization on scalars because vectors
6047 // may have different active low bits.
6048 if (!VT.isVector()) {
6050 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6051 VT.getSizeInBits()));
6052 if (Shorter.getNode())
6053 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6055 // fold (truncate (load x)) -> (smaller load x)
6056 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6057 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6058 SDValue Reduced = ReduceLoadWidth(N);
6059 if (Reduced.getNode())
6061 // Handle the case where the load remains an extending load even
6062 // after truncation.
6063 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6064 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6065 if (!LN0->isVolatile() &&
6066 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6067 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6068 VT, LN0->getChain(), LN0->getBasePtr(),
6070 LN0->getMemOperand());
6071 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6076 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6077 // where ... are all 'undef'.
6078 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6079 SmallVector<EVT, 8> VTs;
6082 unsigned NumDefs = 0;
6084 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6085 SDValue X = N0.getOperand(i);
6086 if (X.getOpcode() != ISD::UNDEF) {
6091 // Stop if more than one members are non-undef.
6094 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6095 VT.getVectorElementType(),
6096 X.getValueType().getVectorNumElements()));
6100 return DAG.getUNDEF(VT);
6103 assert(V.getNode() && "The single defined operand is empty!");
6104 SmallVector<SDValue, 8> Opnds;
6105 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6107 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6110 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6111 AddToWorkList(NV.getNode());
6112 Opnds.push_back(NV);
6114 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6118 // Simplify the operands using demanded-bits information.
6119 if (!VT.isVector() &&
6120 SimplifyDemandedBits(SDValue(N, 0)))
6121 return SDValue(N, 0);
6126 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6127 SDValue Elt = N->getOperand(i);
6128 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6129 return Elt.getNode();
6130 return Elt.getOperand(Elt.getResNo()).getNode();
6133 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6134 /// if load locations are consecutive.
6135 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6136 assert(N->getOpcode() == ISD::BUILD_PAIR);
6138 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6139 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6140 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6141 LD1->getAddressSpace() != LD2->getAddressSpace())
6143 EVT LD1VT = LD1->getValueType(0);
6145 if (ISD::isNON_EXTLoad(LD2) &&
6147 // If both are volatile this would reduce the number of volatile loads.
6148 // If one is volatile it might be ok, but play conservative and bail out.
6149 !LD1->isVolatile() &&
6150 !LD2->isVolatile() &&
6151 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6152 unsigned Align = LD1->getAlignment();
6153 unsigned NewAlign = TLI.getDataLayout()->
6154 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6156 if (NewAlign <= Align &&
6157 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6158 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6159 LD1->getBasePtr(), LD1->getPointerInfo(),
6160 false, false, false, Align);
6166 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6167 SDValue N0 = N->getOperand(0);
6168 EVT VT = N->getValueType(0);
6170 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6171 // Only do this before legalize, since afterward the target may be depending
6172 // on the bitconvert.
6173 // First check to see if this is all constant.
6175 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6177 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6179 EVT DestEltVT = N->getValueType(0).getVectorElementType();
6180 assert(!DestEltVT.isVector() &&
6181 "Element type of vector ValueType must not be vector!");
6183 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6186 // If the input is a constant, let getNode fold it.
6187 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6188 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6189 if (Res.getNode() != N) {
6190 if (!LegalOperations ||
6191 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6194 // Folding it resulted in an illegal node, and it's too late to
6195 // do that. Clean up the old node and forego the transformation.
6196 // Ideally this won't happen very often, because instcombine
6197 // and the earlier dagcombine runs (where illegal nodes are
6198 // permitted) should have folded most of them already.
6199 DAG.DeleteNode(Res.getNode());
6203 // (conv (conv x, t1), t2) -> (conv x, t2)
6204 if (N0.getOpcode() == ISD::BITCAST)
6205 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6208 // fold (conv (load x)) -> (load (conv*)x)
6209 // If the resultant load doesn't need a higher alignment than the original!
6210 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6211 // Do not change the width of a volatile load.
6212 !cast<LoadSDNode>(N0)->isVolatile() &&
6213 // Do not remove the cast if the types differ in endian layout.
6214 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6215 TLI.hasBigEndianPartOrdering(VT) &&
6216 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6217 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6218 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6219 unsigned Align = TLI.getDataLayout()->
6220 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6221 unsigned OrigAlign = LN0->getAlignment();
6223 if (Align <= OrigAlign) {
6224 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6225 LN0->getBasePtr(), LN0->getPointerInfo(),
6226 LN0->isVolatile(), LN0->isNonTemporal(),
6227 LN0->isInvariant(), OrigAlign,
6228 LN0->getTBAAInfo());
6230 CombineTo(N0.getNode(),
6231 DAG.getNode(ISD::BITCAST, SDLoc(N0),
6232 N0.getValueType(), Load),
6238 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6239 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6240 // This often reduces constant pool loads.
6241 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6242 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6243 N0.getNode()->hasOneUse() && VT.isInteger() &&
6244 !VT.isVector() && !N0.getValueType().isVector()) {
6245 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6247 AddToWorkList(NewConv.getNode());
6249 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6250 if (N0.getOpcode() == ISD::FNEG)
6251 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6252 NewConv, DAG.getConstant(SignBit, VT));
6253 assert(N0.getOpcode() == ISD::FABS);
6254 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6255 NewConv, DAG.getConstant(~SignBit, VT));
6258 // fold (bitconvert (fcopysign cst, x)) ->
6259 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6260 // Note that we don't handle (copysign x, cst) because this can always be
6261 // folded to an fneg or fabs.
6262 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6263 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6264 VT.isInteger() && !VT.isVector()) {
6265 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6266 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6267 if (isTypeLegal(IntXVT)) {
6268 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6269 IntXVT, N0.getOperand(1));
6270 AddToWorkList(X.getNode());
6272 // If X has a different width than the result/lhs, sext it or truncate it.
6273 unsigned VTWidth = VT.getSizeInBits();
6274 if (OrigXWidth < VTWidth) {
6275 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6276 AddToWorkList(X.getNode());
6277 } else if (OrigXWidth > VTWidth) {
6278 // To get the sign bit in the right place, we have to shift it right
6279 // before truncating.
6280 X = DAG.getNode(ISD::SRL, SDLoc(X),
6281 X.getValueType(), X,
6282 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6283 AddToWorkList(X.getNode());
6284 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6285 AddToWorkList(X.getNode());
6288 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6289 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6290 X, DAG.getConstant(SignBit, VT));
6291 AddToWorkList(X.getNode());
6293 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6294 VT, N0.getOperand(0));
6295 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6296 Cst, DAG.getConstant(~SignBit, VT));
6297 AddToWorkList(Cst.getNode());
6299 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6303 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6304 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6305 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6306 if (CombineLD.getNode())
6313 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6314 EVT VT = N->getValueType(0);
6315 return CombineConsecutiveLoads(N, VT);
6318 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6319 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
6320 /// destination element value type.
6321 SDValue DAGCombiner::
6322 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6323 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6325 // If this is already the right type, we're done.
6326 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6328 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6329 unsigned DstBitSize = DstEltVT.getSizeInBits();
6331 // If this is a conversion of N elements of one type to N elements of another
6332 // type, convert each element. This handles FP<->INT cases.
6333 if (SrcBitSize == DstBitSize) {
6334 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6335 BV->getValueType(0).getVectorNumElements());
6337 // Due to the FP element handling below calling this routine recursively,
6338 // we can end up with a scalar-to-vector node here.
6339 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6340 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6341 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6342 DstEltVT, BV->getOperand(0)));
6344 SmallVector<SDValue, 8> Ops;
6345 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6346 SDValue Op = BV->getOperand(i);
6347 // If the vector element type is not legal, the BUILD_VECTOR operands
6348 // are promoted and implicitly truncated. Make that explicit here.
6349 if (Op.getValueType() != SrcEltVT)
6350 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6351 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6353 AddToWorkList(Ops.back().getNode());
6355 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6358 // Otherwise, we're growing or shrinking the elements. To avoid having to
6359 // handle annoying details of growing/shrinking FP values, we convert them to
6361 if (SrcEltVT.isFloatingPoint()) {
6362 // Convert the input float vector to a int vector where the elements are the
6364 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6365 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6366 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6370 // Now we know the input is an integer vector. If the output is a FP type,
6371 // convert to integer first, then to FP of the right size.
6372 if (DstEltVT.isFloatingPoint()) {
6373 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6374 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6375 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6377 // Next, convert to FP elements of the same size.
6378 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6381 // Okay, we know the src/dst types are both integers of differing types.
6382 // Handling growing first.
6383 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6384 if (SrcBitSize < DstBitSize) {
6385 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6387 SmallVector<SDValue, 8> Ops;
6388 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6389 i += NumInputsPerOutput) {
6390 bool isLE = TLI.isLittleEndian();
6391 APInt NewBits = APInt(DstBitSize, 0);
6392 bool EltIsUndef = true;
6393 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6394 // Shift the previously computed bits over.
6395 NewBits <<= SrcBitSize;
6396 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6397 if (Op.getOpcode() == ISD::UNDEF) continue;
6400 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6401 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6405 Ops.push_back(DAG.getUNDEF(DstEltVT));
6407 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6410 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6411 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6414 // Finally, this must be the case where we are shrinking elements: each input
6415 // turns into multiple outputs.
6416 bool isS2V = ISD::isScalarToVector(BV);
6417 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6418 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6419 NumOutputsPerInput*BV->getNumOperands());
6420 SmallVector<SDValue, 8> Ops;
6422 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6423 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6424 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6425 Ops.push_back(DAG.getUNDEF(DstEltVT));
6429 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6430 getAPIntValue().zextOrTrunc(SrcBitSize);
6432 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6433 APInt ThisVal = OpVal.trunc(DstBitSize);
6434 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6435 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6436 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6437 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6439 OpVal = OpVal.lshr(DstBitSize);
6442 // For big endian targets, swap the order of the pieces of each element.
6443 if (TLI.isBigEndian())
6444 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6447 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6450 SDValue DAGCombiner::visitFADD(SDNode *N) {
6451 SDValue N0 = N->getOperand(0);
6452 SDValue N1 = N->getOperand(1);
6453 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6454 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6455 EVT VT = N->getValueType(0);
6458 if (VT.isVector()) {
6459 SDValue FoldedVOp = SimplifyVBinOp(N);
6460 if (FoldedVOp.getNode()) return FoldedVOp;
6463 // fold (fadd c1, c2) -> c1 + c2
6465 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6466 // canonicalize constant to RHS
6467 if (N0CFP && !N1CFP)
6468 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6469 // fold (fadd A, 0) -> A
6470 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6471 N1CFP->getValueAPF().isZero())
6473 // fold (fadd A, (fneg B)) -> (fsub A, B)
6474 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6475 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6476 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6477 GetNegatedExpression(N1, DAG, LegalOperations));
6478 // fold (fadd (fneg A), B) -> (fsub B, A)
6479 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6480 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6481 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6482 GetNegatedExpression(N0, DAG, LegalOperations));
6484 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6485 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6486 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6487 isa<ConstantFPSDNode>(N0.getOperand(1)))
6488 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6489 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6490 N0.getOperand(1), N1));
6492 // No FP constant should be created after legalization as Instruction
6493 // Selection pass has hard time in dealing with FP constant.
6495 // We don't need test this condition for transformation like following, as
6496 // the DAG being transformed implies it is legal to take FP constant as
6499 // (fadd (fmul c, x), x) -> (fmul c+1, x)
6501 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6503 // If allow, fold (fadd (fneg x), x) -> 0.0
6504 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6505 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6506 return DAG.getConstantFP(0.0, VT);
6508 // If allow, fold (fadd x, (fneg x)) -> 0.0
6509 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6510 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6511 return DAG.getConstantFP(0.0, VT);
6513 // In unsafe math mode, we can fold chains of FADD's of the same value
6514 // into multiplications. This transform is not safe in general because
6515 // we are reducing the number of rounding steps.
6516 if (DAG.getTarget().Options.UnsafeFPMath &&
6517 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6519 if (N0.getOpcode() == ISD::FMUL) {
6520 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6521 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6523 // (fadd (fmul c, x), x) -> (fmul x, c+1)
6524 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6525 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6527 DAG.getConstantFP(1.0, VT));
6528 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6532 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6533 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6534 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6536 DAG.getConstantFP(1.0, VT));
6537 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6541 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6542 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6543 N1.getOperand(0) == N1.getOperand(1) &&
6544 N0.getOperand(1) == N1.getOperand(0)) {
6545 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6547 DAG.getConstantFP(2.0, VT));
6548 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6549 N0.getOperand(1), NewCFP);
6552 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6553 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6554 N1.getOperand(0) == N1.getOperand(1) &&
6555 N0.getOperand(0) == N1.getOperand(0)) {
6556 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6558 DAG.getConstantFP(2.0, VT));
6559 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6560 N0.getOperand(0), NewCFP);
6564 if (N1.getOpcode() == ISD::FMUL) {
6565 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6566 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6568 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6569 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6570 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6572 DAG.getConstantFP(1.0, VT));
6573 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6577 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6578 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6579 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6581 DAG.getConstantFP(1.0, VT));
6582 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6587 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6588 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6589 N0.getOperand(0) == N0.getOperand(1) &&
6590 N1.getOperand(1) == N0.getOperand(0)) {
6591 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6593 DAG.getConstantFP(2.0, VT));
6594 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6595 N1.getOperand(1), NewCFP);
6598 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6599 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6600 N0.getOperand(0) == N0.getOperand(1) &&
6601 N1.getOperand(0) == N0.getOperand(0)) {
6602 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6604 DAG.getConstantFP(2.0, VT));
6605 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6606 N1.getOperand(0), NewCFP);
6610 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6611 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6612 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6613 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6614 (N0.getOperand(0) == N1))
6615 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6616 N1, DAG.getConstantFP(3.0, VT));
6619 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6620 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6621 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6622 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6623 N1.getOperand(0) == N0)
6624 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6625 N0, DAG.getConstantFP(3.0, VT));
6628 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6629 if (AllowNewFpConst &&
6630 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6631 N0.getOperand(0) == N0.getOperand(1) &&
6632 N1.getOperand(0) == N1.getOperand(1) &&
6633 N0.getOperand(0) == N1.getOperand(0))
6634 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6636 DAG.getConstantFP(4.0, VT));
6639 // FADD -> FMA combines:
6640 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6641 DAG.getTarget().Options.UnsafeFPMath) &&
6642 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6643 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6645 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6646 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6647 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6648 N0.getOperand(0), N0.getOperand(1), N1);
6650 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6651 // Note: Commutes FADD operands.
6652 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6653 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6654 N1.getOperand(0), N1.getOperand(1), N0);
6660 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6661 SDValue N0 = N->getOperand(0);
6662 SDValue N1 = N->getOperand(1);
6663 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6664 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6665 EVT VT = N->getValueType(0);
6669 if (VT.isVector()) {
6670 SDValue FoldedVOp = SimplifyVBinOp(N);
6671 if (FoldedVOp.getNode()) return FoldedVOp;
6674 // fold (fsub c1, c2) -> c1-c2
6676 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6677 // fold (fsub A, 0) -> A
6678 if (DAG.getTarget().Options.UnsafeFPMath &&
6679 N1CFP && N1CFP->getValueAPF().isZero())
6681 // fold (fsub 0, B) -> -B
6682 if (DAG.getTarget().Options.UnsafeFPMath &&
6683 N0CFP && N0CFP->getValueAPF().isZero()) {
6684 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6685 return GetNegatedExpression(N1, DAG, LegalOperations);
6686 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6687 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6689 // fold (fsub A, (fneg B)) -> (fadd A, B)
6690 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6691 return DAG.getNode(ISD::FADD, dl, VT, N0,
6692 GetNegatedExpression(N1, DAG, LegalOperations));
6694 // If 'unsafe math' is enabled, fold
6695 // (fsub x, x) -> 0.0 &
6696 // (fsub x, (fadd x, y)) -> (fneg y) &
6697 // (fsub x, (fadd y, x)) -> (fneg y)
6698 if (DAG.getTarget().Options.UnsafeFPMath) {
6700 return DAG.getConstantFP(0.0f, VT);
6702 if (N1.getOpcode() == ISD::FADD) {
6703 SDValue N10 = N1->getOperand(0);
6704 SDValue N11 = N1->getOperand(1);
6706 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6707 &DAG.getTarget().Options))
6708 return GetNegatedExpression(N11, DAG, LegalOperations);
6710 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6711 &DAG.getTarget().Options))
6712 return GetNegatedExpression(N10, DAG, LegalOperations);
6716 // FSUB -> FMA combines:
6717 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6718 DAG.getTarget().Options.UnsafeFPMath) &&
6719 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6720 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6722 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6723 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6724 return DAG.getNode(ISD::FMA, dl, VT,
6725 N0.getOperand(0), N0.getOperand(1),
6726 DAG.getNode(ISD::FNEG, dl, VT, N1));
6728 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6729 // Note: Commutes FSUB operands.
6730 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6731 return DAG.getNode(ISD::FMA, dl, VT,
6732 DAG.getNode(ISD::FNEG, dl, VT,
6734 N1.getOperand(1), N0);
6736 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6737 if (N0.getOpcode() == ISD::FNEG &&
6738 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6739 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6740 SDValue N00 = N0.getOperand(0).getOperand(0);
6741 SDValue N01 = N0.getOperand(0).getOperand(1);
6742 return DAG.getNode(ISD::FMA, dl, VT,
6743 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6744 DAG.getNode(ISD::FNEG, dl, VT, N1));
6751 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6752 SDValue N0 = N->getOperand(0);
6753 SDValue N1 = N->getOperand(1);
6754 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6755 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6756 EVT VT = N->getValueType(0);
6757 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6760 if (VT.isVector()) {
6761 SDValue FoldedVOp = SimplifyVBinOp(N);
6762 if (FoldedVOp.getNode()) return FoldedVOp;
6765 // fold (fmul c1, c2) -> c1*c2
6767 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6768 // canonicalize constant to RHS
6769 if (N0CFP && !N1CFP)
6770 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6771 // fold (fmul A, 0) -> 0
6772 if (DAG.getTarget().Options.UnsafeFPMath &&
6773 N1CFP && N1CFP->getValueAPF().isZero())
6775 // fold (fmul A, 0) -> 0, vector edition.
6776 if (DAG.getTarget().Options.UnsafeFPMath &&
6777 ISD::isBuildVectorAllZeros(N1.getNode()))
6779 // fold (fmul A, 1.0) -> A
6780 if (N1CFP && N1CFP->isExactlyValue(1.0))
6782 // fold (fmul X, 2.0) -> (fadd X, X)
6783 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6784 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6785 // fold (fmul X, -1.0) -> (fneg X)
6786 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6787 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6788 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6790 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6791 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6792 &DAG.getTarget().Options)) {
6793 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6794 &DAG.getTarget().Options)) {
6795 // Both can be negated for free, check to see if at least one is cheaper
6797 if (LHSNeg == 2 || RHSNeg == 2)
6798 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6799 GetNegatedExpression(N0, DAG, LegalOperations),
6800 GetNegatedExpression(N1, DAG, LegalOperations));
6804 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6805 if (DAG.getTarget().Options.UnsafeFPMath &&
6806 N1CFP && N0.getOpcode() == ISD::FMUL &&
6807 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6808 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6809 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6810 N0.getOperand(1), N1));
6815 SDValue DAGCombiner::visitFMA(SDNode *N) {
6816 SDValue N0 = N->getOperand(0);
6817 SDValue N1 = N->getOperand(1);
6818 SDValue N2 = N->getOperand(2);
6819 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6820 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6821 EVT VT = N->getValueType(0);
6824 if (DAG.getTarget().Options.UnsafeFPMath) {
6825 if (N0CFP && N0CFP->isZero())
6827 if (N1CFP && N1CFP->isZero())
6830 if (N0CFP && N0CFP->isExactlyValue(1.0))
6831 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6832 if (N1CFP && N1CFP->isExactlyValue(1.0))
6833 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6835 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6836 if (N0CFP && !N1CFP)
6837 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6839 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6840 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6841 N2.getOpcode() == ISD::FMUL &&
6842 N0 == N2.getOperand(0) &&
6843 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6844 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6845 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6849 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6850 if (DAG.getTarget().Options.UnsafeFPMath &&
6851 N0.getOpcode() == ISD::FMUL && N1CFP &&
6852 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6853 return DAG.getNode(ISD::FMA, dl, VT,
6855 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6859 // (fma x, 1, y) -> (fadd x, y)
6860 // (fma x, -1, y) -> (fadd (fneg x), y)
6862 if (N1CFP->isExactlyValue(1.0))
6863 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6865 if (N1CFP->isExactlyValue(-1.0) &&
6866 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6867 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6868 AddToWorkList(RHSNeg.getNode());
6869 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6873 // (fma x, c, x) -> (fmul x, (c+1))
6874 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6875 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6876 DAG.getNode(ISD::FADD, dl, VT,
6877 N1, DAG.getConstantFP(1.0, VT)));
6879 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6880 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6881 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6882 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6883 DAG.getNode(ISD::FADD, dl, VT,
6884 N1, DAG.getConstantFP(-1.0, VT)));
6890 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6891 SDValue N0 = N->getOperand(0);
6892 SDValue N1 = N->getOperand(1);
6893 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6894 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6895 EVT VT = N->getValueType(0);
6896 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6899 if (VT.isVector()) {
6900 SDValue FoldedVOp = SimplifyVBinOp(N);
6901 if (FoldedVOp.getNode()) return FoldedVOp;
6904 // fold (fdiv c1, c2) -> c1/c2
6906 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6908 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6909 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6910 // Compute the reciprocal 1.0 / c2.
6911 APFloat N1APF = N1CFP->getValueAPF();
6912 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6913 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6914 // Only do the transform if the reciprocal is a legal fp immediate that
6915 // isn't too nasty (eg NaN, denormal, ...).
6916 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6917 (!LegalOperations ||
6918 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6919 // backend)... we should handle this gracefully after Legalize.
6920 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6921 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6922 TLI.isFPImmLegal(Recip, VT)))
6923 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6924 DAG.getConstantFP(Recip, VT));
6927 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6928 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6929 &DAG.getTarget().Options)) {
6930 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6931 &DAG.getTarget().Options)) {
6932 // Both can be negated for free, check to see if at least one is cheaper
6934 if (LHSNeg == 2 || RHSNeg == 2)
6935 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6936 GetNegatedExpression(N0, DAG, LegalOperations),
6937 GetNegatedExpression(N1, DAG, LegalOperations));
6944 SDValue DAGCombiner::visitFREM(SDNode *N) {
6945 SDValue N0 = N->getOperand(0);
6946 SDValue N1 = N->getOperand(1);
6947 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6948 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6949 EVT VT = N->getValueType(0);
6951 // fold (frem c1, c2) -> fmod(c1,c2)
6953 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6958 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6959 SDValue N0 = N->getOperand(0);
6960 SDValue N1 = N->getOperand(1);
6961 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6962 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6963 EVT VT = N->getValueType(0);
6965 if (N0CFP && N1CFP) // Constant fold
6966 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6969 const APFloat& V = N1CFP->getValueAPF();
6970 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6971 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6972 if (!V.isNegative()) {
6973 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6974 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6976 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6977 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6978 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6982 // copysign(fabs(x), y) -> copysign(x, y)
6983 // copysign(fneg(x), y) -> copysign(x, y)
6984 // copysign(copysign(x,z), y) -> copysign(x, y)
6985 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6986 N0.getOpcode() == ISD::FCOPYSIGN)
6987 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6988 N0.getOperand(0), N1);
6990 // copysign(x, abs(y)) -> abs(x)
6991 if (N1.getOpcode() == ISD::FABS)
6992 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6994 // copysign(x, copysign(y,z)) -> copysign(x, z)
6995 if (N1.getOpcode() == ISD::FCOPYSIGN)
6996 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6997 N0, N1.getOperand(1));
6999 // copysign(x, fp_extend(y)) -> copysign(x, y)
7000 // copysign(x, fp_round(y)) -> copysign(x, y)
7001 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7002 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7003 N0, N1.getOperand(0));
7008 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7009 SDValue N0 = N->getOperand(0);
7010 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7011 EVT VT = N->getValueType(0);
7012 EVT OpVT = N0.getValueType();
7014 // fold (sint_to_fp c1) -> c1fp
7016 // ...but only if the target supports immediate floating-point values
7017 (!LegalOperations ||
7018 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7019 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7021 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7022 // but UINT_TO_FP is legal on this target, try to convert.
7023 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7024 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7025 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7026 if (DAG.SignBitIsZero(N0))
7027 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7030 // The next optimizations are desirable only if SELECT_CC can be lowered.
7031 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7032 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7033 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7035 (!LegalOperations ||
7036 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7038 { N0.getOperand(0), N0.getOperand(1),
7039 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7041 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7044 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7045 // (select_cc x, y, 1.0, 0.0,, cc)
7046 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7047 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7048 (!LegalOperations ||
7049 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7051 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7052 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7053 N0.getOperand(0).getOperand(2) };
7054 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7061 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7062 SDValue N0 = N->getOperand(0);
7063 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7064 EVT VT = N->getValueType(0);
7065 EVT OpVT = N0.getValueType();
7067 // fold (uint_to_fp c1) -> c1fp
7069 // ...but only if the target supports immediate floating-point values
7070 (!LegalOperations ||
7071 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7072 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7074 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7075 // but SINT_TO_FP is legal on this target, try to convert.
7076 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7077 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7078 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7079 if (DAG.SignBitIsZero(N0))
7080 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7083 // The next optimizations are desirable only if SELECT_CC can be lowered.
7084 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7085 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7087 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7088 (!LegalOperations ||
7089 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7091 { N0.getOperand(0), N0.getOperand(1),
7092 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7094 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7101 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7102 SDValue N0 = N->getOperand(0);
7103 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7104 EVT VT = N->getValueType(0);
7106 // fold (fp_to_sint c1fp) -> c1
7108 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7113 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7114 SDValue N0 = N->getOperand(0);
7115 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7116 EVT VT = N->getValueType(0);
7118 // fold (fp_to_uint c1fp) -> c1
7120 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7125 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7126 SDValue N0 = N->getOperand(0);
7127 SDValue N1 = N->getOperand(1);
7128 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7129 EVT VT = N->getValueType(0);
7131 // fold (fp_round c1fp) -> c1fp
7133 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7135 // fold (fp_round (fp_extend x)) -> x
7136 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7137 return N0.getOperand(0);
7139 // fold (fp_round (fp_round x)) -> (fp_round x)
7140 if (N0.getOpcode() == ISD::FP_ROUND) {
7141 // This is a value preserving truncation if both round's are.
7142 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7143 N0.getNode()->getConstantOperandVal(1) == 1;
7144 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7145 DAG.getIntPtrConstant(IsTrunc));
7148 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7149 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7150 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7151 N0.getOperand(0), N1);
7152 AddToWorkList(Tmp.getNode());
7153 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7154 Tmp, N0.getOperand(1));
7160 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7161 SDValue N0 = N->getOperand(0);
7162 EVT VT = N->getValueType(0);
7163 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7164 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7166 // fold (fp_round_inreg c1fp) -> c1fp
7167 if (N0CFP && isTypeLegal(EVT)) {
7168 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7169 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7175 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7176 SDValue N0 = N->getOperand(0);
7177 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7178 EVT VT = N->getValueType(0);
7180 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7181 if (N->hasOneUse() &&
7182 N->use_begin()->getOpcode() == ISD::FP_ROUND)
7185 // fold (fp_extend c1fp) -> c1fp
7187 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7189 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7191 if (N0.getOpcode() == ISD::FP_ROUND
7192 && N0.getNode()->getConstantOperandVal(1) == 1) {
7193 SDValue In = N0.getOperand(0);
7194 if (In.getValueType() == VT) return In;
7195 if (VT.bitsLT(In.getValueType()))
7196 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7197 In, N0.getOperand(1));
7198 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7201 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7202 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7203 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7204 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
7205 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7206 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7208 LN0->getBasePtr(), N0.getValueType(),
7209 LN0->getMemOperand());
7210 CombineTo(N, ExtLoad);
7211 CombineTo(N0.getNode(),
7212 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7213 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7214 ExtLoad.getValue(1));
7215 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7221 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7222 SDValue N0 = N->getOperand(0);
7223 EVT VT = N->getValueType(0);
7225 if (VT.isVector()) {
7226 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7227 if (FoldedVOp.getNode()) return FoldedVOp;
7230 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7231 &DAG.getTarget().Options))
7232 return GetNegatedExpression(N0, DAG, LegalOperations);
7234 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7235 // constant pool values.
7236 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7238 N0.getNode()->hasOneUse() &&
7239 N0.getOperand(0).getValueType().isInteger()) {
7240 SDValue Int = N0.getOperand(0);
7241 EVT IntVT = Int.getValueType();
7242 if (IntVT.isInteger() && !IntVT.isVector()) {
7243 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7244 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7245 AddToWorkList(Int.getNode());
7246 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7251 // (fneg (fmul c, x)) -> (fmul -c, x)
7252 if (N0.getOpcode() == ISD::FMUL) {
7253 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7255 APFloat CVal = CFP1->getValueAPF();
7257 if (Level >= AfterLegalizeDAG &&
7258 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7259 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7261 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7262 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7269 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7270 SDValue N0 = N->getOperand(0);
7271 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7272 EVT VT = N->getValueType(0);
7274 // fold (fceil c1) -> fceil(c1)
7276 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7281 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7282 SDValue N0 = N->getOperand(0);
7283 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7284 EVT VT = N->getValueType(0);
7286 // fold (ftrunc c1) -> ftrunc(c1)
7288 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7293 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7294 SDValue N0 = N->getOperand(0);
7295 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7296 EVT VT = N->getValueType(0);
7298 // fold (ffloor c1) -> ffloor(c1)
7300 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7305 SDValue DAGCombiner::visitFABS(SDNode *N) {
7306 SDValue N0 = N->getOperand(0);
7307 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7308 EVT VT = N->getValueType(0);
7310 if (VT.isVector()) {
7311 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7312 if (FoldedVOp.getNode()) return FoldedVOp;
7315 // fold (fabs c1) -> fabs(c1)
7317 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7318 // fold (fabs (fabs x)) -> (fabs x)
7319 if (N0.getOpcode() == ISD::FABS)
7320 return N->getOperand(0);
7321 // fold (fabs (fneg x)) -> (fabs x)
7322 // fold (fabs (fcopysign x, y)) -> (fabs x)
7323 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7324 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7326 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7327 // constant pool values.
7328 if (!TLI.isFAbsFree(VT) &&
7329 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7330 N0.getOperand(0).getValueType().isInteger() &&
7331 !N0.getOperand(0).getValueType().isVector()) {
7332 SDValue Int = N0.getOperand(0);
7333 EVT IntVT = Int.getValueType();
7334 if (IntVT.isInteger() && !IntVT.isVector()) {
7335 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7336 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7337 AddToWorkList(Int.getNode());
7338 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7339 N->getValueType(0), Int);
7346 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7347 SDValue Chain = N->getOperand(0);
7348 SDValue N1 = N->getOperand(1);
7349 SDValue N2 = N->getOperand(2);
7351 // If N is a constant we could fold this into a fallthrough or unconditional
7352 // branch. However that doesn't happen very often in normal code, because
7353 // Instcombine/SimplifyCFG should have handled the available opportunities.
7354 // If we did this folding here, it would be necessary to update the
7355 // MachineBasicBlock CFG, which is awkward.
7357 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7359 if (N1.getOpcode() == ISD::SETCC &&
7360 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7361 N1.getOperand(0).getValueType())) {
7362 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7363 Chain, N1.getOperand(2),
7364 N1.getOperand(0), N1.getOperand(1), N2);
7367 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7368 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7369 (N1.getOperand(0).hasOneUse() &&
7370 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7371 SDNode *Trunc = nullptr;
7372 if (N1.getOpcode() == ISD::TRUNCATE) {
7373 // Look pass the truncate.
7374 Trunc = N1.getNode();
7375 N1 = N1.getOperand(0);
7378 // Match this pattern so that we can generate simpler code:
7381 // %b = and i32 %a, 2
7382 // %c = srl i32 %b, 1
7383 // brcond i32 %c ...
7388 // %b = and i32 %a, 2
7389 // %c = setcc eq %b, 0
7392 // This applies only when the AND constant value has one bit set and the
7393 // SRL constant is equal to the log2 of the AND constant. The back-end is
7394 // smart enough to convert the result into a TEST/JMP sequence.
7395 SDValue Op0 = N1.getOperand(0);
7396 SDValue Op1 = N1.getOperand(1);
7398 if (Op0.getOpcode() == ISD::AND &&
7399 Op1.getOpcode() == ISD::Constant) {
7400 SDValue AndOp1 = Op0.getOperand(1);
7402 if (AndOp1.getOpcode() == ISD::Constant) {
7403 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7405 if (AndConst.isPowerOf2() &&
7406 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7408 DAG.getSetCC(SDLoc(N),
7409 getSetCCResultType(Op0.getValueType()),
7410 Op0, DAG.getConstant(0, Op0.getValueType()),
7413 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7414 MVT::Other, Chain, SetCC, N2);
7415 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7416 // will convert it back to (X & C1) >> C2.
7417 CombineTo(N, NewBRCond, false);
7418 // Truncate is dead.
7420 removeFromWorkList(Trunc);
7421 DAG.DeleteNode(Trunc);
7423 // Replace the uses of SRL with SETCC
7424 WorkListRemover DeadNodes(*this);
7425 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7426 removeFromWorkList(N1.getNode());
7427 DAG.DeleteNode(N1.getNode());
7428 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7434 // Restore N1 if the above transformation doesn't match.
7435 N1 = N->getOperand(1);
7438 // Transform br(xor(x, y)) -> br(x != y)
7439 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7440 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7441 SDNode *TheXor = N1.getNode();
7442 SDValue Op0 = TheXor->getOperand(0);
7443 SDValue Op1 = TheXor->getOperand(1);
7444 if (Op0.getOpcode() == Op1.getOpcode()) {
7445 // Avoid missing important xor optimizations.
7446 SDValue Tmp = visitXOR(TheXor);
7447 if (Tmp.getNode()) {
7448 if (Tmp.getNode() != TheXor) {
7449 DEBUG(dbgs() << "\nReplacing.8 ";
7451 dbgs() << "\nWith: ";
7452 Tmp.getNode()->dump(&DAG);
7454 WorkListRemover DeadNodes(*this);
7455 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7456 removeFromWorkList(TheXor);
7457 DAG.DeleteNode(TheXor);
7458 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7459 MVT::Other, Chain, Tmp, N2);
7462 // visitXOR has changed XOR's operands or replaced the XOR completely,
7464 return SDValue(N, 0);
7468 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7470 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7471 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7472 Op0.getOpcode() == ISD::XOR) {
7473 TheXor = Op0.getNode();
7477 EVT SetCCVT = N1.getValueType();
7479 SetCCVT = getSetCCResultType(SetCCVT);
7480 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7483 Equal ? ISD::SETEQ : ISD::SETNE);
7484 // Replace the uses of XOR with SETCC
7485 WorkListRemover DeadNodes(*this);
7486 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7487 removeFromWorkList(N1.getNode());
7488 DAG.DeleteNode(N1.getNode());
7489 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7490 MVT::Other, Chain, SetCC, N2);
7497 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7499 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7500 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7501 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7503 // If N is a constant we could fold this into a fallthrough or unconditional
7504 // branch. However that doesn't happen very often in normal code, because
7505 // Instcombine/SimplifyCFG should have handled the available opportunities.
7506 // If we did this folding here, it would be necessary to update the
7507 // MachineBasicBlock CFG, which is awkward.
7509 // Use SimplifySetCC to simplify SETCC's.
7510 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7511 CondLHS, CondRHS, CC->get(), SDLoc(N),
7513 if (Simp.getNode()) AddToWorkList(Simp.getNode());
7515 // fold to a simpler setcc
7516 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7517 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7518 N->getOperand(0), Simp.getOperand(2),
7519 Simp.getOperand(0), Simp.getOperand(1),
7525 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7526 /// uses N as its base pointer and that N may be folded in the load / store
7527 /// addressing mode.
7528 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7530 const TargetLowering &TLI) {
7532 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7533 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7535 VT = Use->getValueType(0);
7536 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7537 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7539 VT = ST->getValue().getValueType();
7543 TargetLowering::AddrMode AM;
7544 if (N->getOpcode() == ISD::ADD) {
7545 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7548 AM.BaseOffs = Offset->getSExtValue();
7552 } else if (N->getOpcode() == ISD::SUB) {
7553 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7556 AM.BaseOffs = -Offset->getSExtValue();
7563 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7566 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7567 /// pre-indexed load / store when the base pointer is an add or subtract
7568 /// and it has other uses besides the load / store. After the
7569 /// transformation, the new indexed load / store has effectively folded
7570 /// the add / subtract in and all of its other uses are redirected to the
7571 /// new load / store.
7572 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7573 if (Level < AfterLegalizeDAG)
7579 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7580 if (LD->isIndexed())
7582 VT = LD->getMemoryVT();
7583 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7584 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7586 Ptr = LD->getBasePtr();
7587 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7588 if (ST->isIndexed())
7590 VT = ST->getMemoryVT();
7591 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7592 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7594 Ptr = ST->getBasePtr();
7600 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7601 // out. There is no reason to make this a preinc/predec.
7602 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7603 Ptr.getNode()->hasOneUse())
7606 // Ask the target to do addressing mode selection.
7609 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7610 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7613 // Backends without true r+i pre-indexed forms may need to pass a
7614 // constant base with a variable offset so that constant coercion
7615 // will work with the patterns in canonical form.
7616 bool Swapped = false;
7617 if (isa<ConstantSDNode>(BasePtr)) {
7618 std::swap(BasePtr, Offset);
7622 // Don't create a indexed load / store with zero offset.
7623 if (isa<ConstantSDNode>(Offset) &&
7624 cast<ConstantSDNode>(Offset)->isNullValue())
7627 // Try turning it into a pre-indexed load / store except when:
7628 // 1) The new base ptr is a frame index.
7629 // 2) If N is a store and the new base ptr is either the same as or is a
7630 // predecessor of the value being stored.
7631 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7632 // that would create a cycle.
7633 // 4) All uses are load / store ops that use it as old base ptr.
7635 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7636 // (plus the implicit offset) to a register to preinc anyway.
7637 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7642 SDValue Val = cast<StoreSDNode>(N)->getValue();
7643 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7647 // If the offset is a constant, there may be other adds of constants that
7648 // can be folded with this one. We should do this to avoid having to keep
7649 // a copy of the original base pointer.
7650 SmallVector<SDNode *, 16> OtherUses;
7651 if (isa<ConstantSDNode>(Offset))
7652 for (SDNode *Use : BasePtr.getNode()->uses()) {
7653 if (Use == Ptr.getNode())
7656 if (Use->isPredecessorOf(N))
7659 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7664 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7665 if (Op1.getNode() == BasePtr.getNode())
7666 std::swap(Op0, Op1);
7667 assert(Op0.getNode() == BasePtr.getNode() &&
7668 "Use of ADD/SUB but not an operand");
7670 if (!isa<ConstantSDNode>(Op1)) {
7675 // FIXME: In some cases, we can be smarter about this.
7676 if (Op1.getValueType() != Offset.getValueType()) {
7681 OtherUses.push_back(Use);
7685 std::swap(BasePtr, Offset);
7687 // Now check for #3 and #4.
7688 bool RealUse = false;
7690 // Caches for hasPredecessorHelper
7691 SmallPtrSet<const SDNode *, 32> Visited;
7692 SmallVector<const SDNode *, 16> Worklist;
7694 for (SDNode *Use : Ptr.getNode()->uses()) {
7697 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7700 // If Ptr may be folded in addressing mode of other use, then it's
7701 // not profitable to do this transformation.
7702 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7711 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7712 BasePtr, Offset, AM);
7714 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7715 BasePtr, Offset, AM);
7718 DEBUG(dbgs() << "\nReplacing.4 ";
7720 dbgs() << "\nWith: ";
7721 Result.getNode()->dump(&DAG);
7723 WorkListRemover DeadNodes(*this);
7725 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7726 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7728 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7731 // Finally, since the node is now dead, remove it from the graph.
7735 std::swap(BasePtr, Offset);
7737 // Replace other uses of BasePtr that can be updated to use Ptr
7738 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7739 unsigned OffsetIdx = 1;
7740 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7742 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7743 BasePtr.getNode() && "Expected BasePtr operand");
7745 // We need to replace ptr0 in the following expression:
7746 // x0 * offset0 + y0 * ptr0 = t0
7748 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7750 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7751 // indexed load/store and the expresion that needs to be re-written.
7753 // Therefore, we have:
7754 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7756 ConstantSDNode *CN =
7757 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7759 APInt Offset0 = CN->getAPIntValue();
7760 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7762 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7763 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7764 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7765 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7767 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7769 APInt CNV = Offset0;
7770 if (X0 < 0) CNV = -CNV;
7771 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7772 else CNV = CNV - Offset1;
7774 // We can now generate the new expression.
7775 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7776 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7778 SDValue NewUse = DAG.getNode(Opcode,
7779 SDLoc(OtherUses[i]),
7780 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7781 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7782 removeFromWorkList(OtherUses[i]);
7783 DAG.DeleteNode(OtherUses[i]);
7786 // Replace the uses of Ptr with uses of the updated base value.
7787 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7788 removeFromWorkList(Ptr.getNode());
7789 DAG.DeleteNode(Ptr.getNode());
7794 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7795 /// add / sub of the base pointer node into a post-indexed load / store.
7796 /// The transformation folded the add / subtract into the new indexed
7797 /// load / store effectively and all of its uses are redirected to the
7798 /// new load / store.
7799 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7800 if (Level < AfterLegalizeDAG)
7806 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7807 if (LD->isIndexed())
7809 VT = LD->getMemoryVT();
7810 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7811 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7813 Ptr = LD->getBasePtr();
7814 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7815 if (ST->isIndexed())
7817 VT = ST->getMemoryVT();
7818 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7819 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7821 Ptr = ST->getBasePtr();
7827 if (Ptr.getNode()->hasOneUse())
7830 for (SDNode *Op : Ptr.getNode()->uses()) {
7832 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7837 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7838 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7839 // Don't create a indexed load / store with zero offset.
7840 if (isa<ConstantSDNode>(Offset) &&
7841 cast<ConstantSDNode>(Offset)->isNullValue())
7844 // Try turning it into a post-indexed load / store except when
7845 // 1) All uses are load / store ops that use it as base ptr (and
7846 // it may be folded as addressing mmode).
7847 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7848 // nor a successor of N. Otherwise, if Op is folded that would
7851 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7855 bool TryNext = false;
7856 for (SDNode *Use : BasePtr.getNode()->uses()) {
7857 if (Use == Ptr.getNode())
7860 // If all the uses are load / store addresses, then don't do the
7862 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7863 bool RealUse = false;
7864 for (SDNode *UseUse : Use->uses()) {
7865 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7880 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7881 SDValue Result = isLoad
7882 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7883 BasePtr, Offset, AM)
7884 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7885 BasePtr, Offset, AM);
7888 DEBUG(dbgs() << "\nReplacing.5 ";
7890 dbgs() << "\nWith: ";
7891 Result.getNode()->dump(&DAG);
7893 WorkListRemover DeadNodes(*this);
7895 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7896 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7898 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7901 // Finally, since the node is now dead, remove it from the graph.
7904 // Replace the uses of Use with uses of the updated base value.
7905 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7906 Result.getValue(isLoad ? 1 : 0));
7907 removeFromWorkList(Op);
7917 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7918 LoadSDNode *LD = cast<LoadSDNode>(N);
7919 SDValue Chain = LD->getChain();
7920 SDValue Ptr = LD->getBasePtr();
7922 // If load is not volatile and there are no uses of the loaded value (and
7923 // the updated indexed value in case of indexed loads), change uses of the
7924 // chain value into uses of the chain input (i.e. delete the dead load).
7925 if (!LD->isVolatile()) {
7926 if (N->getValueType(1) == MVT::Other) {
7928 if (!N->hasAnyUseOfValue(0)) {
7929 // It's not safe to use the two value CombineTo variant here. e.g.
7930 // v1, chain2 = load chain1, loc
7931 // v2, chain3 = load chain2, loc
7933 // Now we replace use of chain2 with chain1. This makes the second load
7934 // isomorphic to the one we are deleting, and thus makes this load live.
7935 DEBUG(dbgs() << "\nReplacing.6 ";
7937 dbgs() << "\nWith chain: ";
7938 Chain.getNode()->dump(&DAG);
7940 WorkListRemover DeadNodes(*this);
7941 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7943 if (N->use_empty()) {
7944 removeFromWorkList(N);
7948 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7952 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7953 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7954 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7955 DEBUG(dbgs() << "\nReplacing.7 ";
7957 dbgs() << "\nWith: ";
7958 Undef.getNode()->dump(&DAG);
7959 dbgs() << " and 2 other values\n");
7960 WorkListRemover DeadNodes(*this);
7961 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7962 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7963 DAG.getUNDEF(N->getValueType(1)));
7964 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7965 removeFromWorkList(N);
7967 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7972 // If this load is directly stored, replace the load value with the stored
7974 // TODO: Handle store large -> read small portion.
7975 // TODO: Handle TRUNCSTORE/LOADEXT
7976 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7977 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7978 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7979 if (PrevST->getBasePtr() == Ptr &&
7980 PrevST->getValue().getValueType() == N->getValueType(0))
7981 return CombineTo(N, Chain.getOperand(1), Chain);
7985 // Try to infer better alignment information than the load already has.
7986 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7987 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7988 if (Align > LD->getMemOperand()->getBaseAlignment()) {
7990 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7991 LD->getValueType(0),
7992 Chain, Ptr, LD->getPointerInfo(),
7994 LD->isVolatile(), LD->isNonTemporal(), Align,
7996 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8001 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8002 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
8004 if (CombinerAAOnlyFunc.getNumOccurrences() &&
8005 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8008 if (UseAA && LD->isUnindexed()) {
8009 // Walk up chain skipping non-aliasing memory nodes.
8010 SDValue BetterChain = FindBetterChain(N, Chain);
8012 // If there is a better chain.
8013 if (Chain != BetterChain) {
8016 // Replace the chain to void dependency.
8017 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8018 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8019 BetterChain, Ptr, LD->getMemOperand());
8021 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8022 LD->getValueType(0),
8023 BetterChain, Ptr, LD->getMemoryVT(),
8024 LD->getMemOperand());
8027 // Create token factor to keep old chain connected.
8028 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8029 MVT::Other, Chain, ReplLoad.getValue(1));
8031 // Make sure the new and old chains are cleaned up.
8032 AddToWorkList(Token.getNode());
8034 // Replace uses with load result and token factor. Don't add users
8036 return CombineTo(N, ReplLoad.getValue(0), Token, false);
8040 // Try transforming N to an indexed load.
8041 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8042 return SDValue(N, 0);
8044 // Try to slice up N to more direct loads if the slices are mapped to
8045 // different register banks or pairing can take place.
8047 return SDValue(N, 0);
8053 /// \brief Helper structure used to slice a load in smaller loads.
8054 /// Basically a slice is obtained from the following sequence:
8055 /// Origin = load Ty1, Base
8056 /// Shift = srl Ty1 Origin, CstTy Amount
8057 /// Inst = trunc Shift to Ty2
8059 /// Then, it will be rewriten into:
8060 /// Slice = load SliceTy, Base + SliceOffset
8061 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8063 /// SliceTy is deduced from the number of bits that are actually used to
8065 struct LoadedSlice {
8066 /// \brief Helper structure used to compute the cost of a slice.
8068 /// Are we optimizing for code size.
8073 unsigned CrossRegisterBanksCopies;
8077 Cost(bool ForCodeSize = false)
8078 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8079 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8081 /// \brief Get the cost of one isolated slice.
8082 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8083 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8084 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8085 EVT TruncType = LS.Inst->getValueType(0);
8086 EVT LoadedType = LS.getLoadedType();
8087 if (TruncType != LoadedType &&
8088 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8092 /// \brief Account for slicing gain in the current cost.
8093 /// Slicing provide a few gains like removing a shift or a
8094 /// truncate. This method allows to grow the cost of the original
8095 /// load with the gain from this slice.
8096 void addSliceGain(const LoadedSlice &LS) {
8097 // Each slice saves a truncate.
8098 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8099 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8100 LS.Inst->getOperand(0).getValueType()))
8102 // If there is a shift amount, this slice gets rid of it.
8105 // If this slice can merge a cross register bank copy, account for it.
8106 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8107 ++CrossRegisterBanksCopies;
8110 Cost &operator+=(const Cost &RHS) {
8112 Truncates += RHS.Truncates;
8113 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8119 bool operator==(const Cost &RHS) const {
8120 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8121 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8122 ZExts == RHS.ZExts && Shift == RHS.Shift;
8125 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8127 bool operator<(const Cost &RHS) const {
8128 // Assume cross register banks copies are as expensive as loads.
8129 // FIXME: Do we want some more target hooks?
8130 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8131 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8132 // Unless we are optimizing for code size, consider the
8133 // expensive operation first.
8134 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8135 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8136 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8137 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8140 bool operator>(const Cost &RHS) const { return RHS < *this; }
8142 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8144 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8146 // The last instruction that represent the slice. This should be a
8147 // truncate instruction.
8149 // The original load instruction.
8151 // The right shift amount in bits from the original load.
8153 // The DAG from which Origin came from.
8154 // This is used to get some contextual information about legal types, etc.
8157 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8158 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8159 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8161 LoadedSlice(const LoadedSlice &LS)
8162 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8164 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8165 /// \return Result is \p BitWidth and has used bits set to 1 and
8166 /// not used bits set to 0.
8167 APInt getUsedBits() const {
8168 // Reproduce the trunc(lshr) sequence:
8169 // - Start from the truncated value.
8170 // - Zero extend to the desired bit width.
8172 assert(Origin && "No original load to compare against.");
8173 unsigned BitWidth = Origin->getValueSizeInBits(0);
8174 assert(Inst && "This slice is not bound to an instruction");
8175 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8176 "Extracted slice is bigger than the whole type!");
8177 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8178 UsedBits.setAllBits();
8179 UsedBits = UsedBits.zext(BitWidth);
8184 /// \brief Get the size of the slice to be loaded in bytes.
8185 unsigned getLoadedSize() const {
8186 unsigned SliceSize = getUsedBits().countPopulation();
8187 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8188 return SliceSize / 8;
8191 /// \brief Get the type that will be loaded for this slice.
8192 /// Note: This may not be the final type for the slice.
8193 EVT getLoadedType() const {
8194 assert(DAG && "Missing context");
8195 LLVMContext &Ctxt = *DAG->getContext();
8196 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8199 /// \brief Get the alignment of the load used for this slice.
8200 unsigned getAlignment() const {
8201 unsigned Alignment = Origin->getAlignment();
8202 unsigned Offset = getOffsetFromBase();
8204 Alignment = MinAlign(Alignment, Alignment + Offset);
8208 /// \brief Check if this slice can be rewritten with legal operations.
8209 bool isLegal() const {
8210 // An invalid slice is not legal.
8211 if (!Origin || !Inst || !DAG)
8214 // Offsets are for indexed load only, we do not handle that.
8215 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8218 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8220 // Check that the type is legal.
8221 EVT SliceType = getLoadedType();
8222 if (!TLI.isTypeLegal(SliceType))
8225 // Check that the load is legal for this type.
8226 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8229 // Check that the offset can be computed.
8230 // 1. Check its type.
8231 EVT PtrType = Origin->getBasePtr().getValueType();
8232 if (PtrType == MVT::Untyped || PtrType.isExtended())
8235 // 2. Check that it fits in the immediate.
8236 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8239 // 3. Check that the computation is legal.
8240 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8243 // Check that the zext is legal if it needs one.
8244 EVT TruncateType = Inst->getValueType(0);
8245 if (TruncateType != SliceType &&
8246 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8252 /// \brief Get the offset in bytes of this slice in the original chunk of
8254 /// \pre DAG != nullptr.
8255 uint64_t getOffsetFromBase() const {
8256 assert(DAG && "Missing context.");
8258 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8259 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8260 uint64_t Offset = Shift / 8;
8261 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8262 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8263 "The size of the original loaded type is not a multiple of a"
8265 // If Offset is bigger than TySizeInBytes, it means we are loading all
8266 // zeros. This should have been optimized before in the process.
8267 assert(TySizeInBytes > Offset &&
8268 "Invalid shift amount for given loaded size");
8270 Offset = TySizeInBytes - Offset - getLoadedSize();
8274 /// \brief Generate the sequence of instructions to load the slice
8275 /// represented by this object and redirect the uses of this slice to
8276 /// this new sequence of instructions.
8277 /// \pre this->Inst && this->Origin are valid Instructions and this
8278 /// object passed the legal check: LoadedSlice::isLegal returned true.
8279 /// \return The last instruction of the sequence used to load the slice.
8280 SDValue loadSlice() const {
8281 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8282 const SDValue &OldBaseAddr = Origin->getBasePtr();
8283 SDValue BaseAddr = OldBaseAddr;
8284 // Get the offset in that chunk of bytes w.r.t. the endianess.
8285 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8286 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8288 // BaseAddr = BaseAddr + Offset.
8289 EVT ArithType = BaseAddr.getValueType();
8290 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8291 DAG->getConstant(Offset, ArithType));
8294 // Create the type of the loaded slice according to its size.
8295 EVT SliceType = getLoadedType();
8297 // Create the load for the slice.
8298 SDValue LastInst = DAG->getLoad(
8299 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8300 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8301 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8302 // If the final type is not the same as the loaded type, this means that
8303 // we have to pad with zero. Create a zero extend for that.
8304 EVT FinalType = Inst->getValueType(0);
8305 if (SliceType != FinalType)
8307 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8311 /// \brief Check if this slice can be merged with an expensive cross register
8312 /// bank copy. E.g.,
8314 /// f = bitcast i32 i to float
8315 bool canMergeExpensiveCrossRegisterBankCopy() const {
8316 if (!Inst || !Inst->hasOneUse())
8318 SDNode *Use = *Inst->use_begin();
8319 if (Use->getOpcode() != ISD::BITCAST)
8321 assert(DAG && "Missing context");
8322 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8323 EVT ResVT = Use->getValueType(0);
8324 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8325 const TargetRegisterClass *ArgRC =
8326 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8327 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8330 // At this point, we know that we perform a cross-register-bank copy.
8331 // Check if it is expensive.
8332 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8333 // Assume bitcasts are cheap, unless both register classes do not
8334 // explicitly share a common sub class.
8335 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8338 // Check if it will be merged with the load.
8339 // 1. Check the alignment constraint.
8340 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8341 ResVT.getTypeForEVT(*DAG->getContext()));
8343 if (RequiredAlignment > getAlignment())
8346 // 2. Check that the load is a legal operation for that type.
8347 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8350 // 3. Check that we do not have a zext in the way.
8351 if (Inst->getValueType(0) != getLoadedType())
8359 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8360 /// \p UsedBits looks like 0..0 1..1 0..0.
8361 static bool areUsedBitsDense(const APInt &UsedBits) {
8362 // If all the bits are one, this is dense!
8363 if (UsedBits.isAllOnesValue())
8366 // Get rid of the unused bits on the right.
8367 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8368 // Get rid of the unused bits on the left.
8369 if (NarrowedUsedBits.countLeadingZeros())
8370 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8371 // Check that the chunk of bits is completely used.
8372 return NarrowedUsedBits.isAllOnesValue();
8375 /// \brief Check whether or not \p First and \p Second are next to each other
8376 /// in memory. This means that there is no hole between the bits loaded
8377 /// by \p First and the bits loaded by \p Second.
8378 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8379 const LoadedSlice &Second) {
8380 assert(First.Origin == Second.Origin && First.Origin &&
8381 "Unable to match different memory origins.");
8382 APInt UsedBits = First.getUsedBits();
8383 assert((UsedBits & Second.getUsedBits()) == 0 &&
8384 "Slices are not supposed to overlap.");
8385 UsedBits |= Second.getUsedBits();
8386 return areUsedBitsDense(UsedBits);
8389 /// \brief Adjust the \p GlobalLSCost according to the target
8390 /// paring capabilities and the layout of the slices.
8391 /// \pre \p GlobalLSCost should account for at least as many loads as
8392 /// there is in the slices in \p LoadedSlices.
8393 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8394 LoadedSlice::Cost &GlobalLSCost) {
8395 unsigned NumberOfSlices = LoadedSlices.size();
8396 // If there is less than 2 elements, no pairing is possible.
8397 if (NumberOfSlices < 2)
8400 // Sort the slices so that elements that are likely to be next to each
8401 // other in memory are next to each other in the list.
8402 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8403 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8404 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8405 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8407 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8408 // First (resp. Second) is the first (resp. Second) potentially candidate
8409 // to be placed in a paired load.
8410 const LoadedSlice *First = nullptr;
8411 const LoadedSlice *Second = nullptr;
8412 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8413 // Set the beginning of the pair.
8416 Second = &LoadedSlices[CurrSlice];
8418 // If First is NULL, it means we start a new pair.
8419 // Get to the next slice.
8423 EVT LoadedType = First->getLoadedType();
8425 // If the types of the slices are different, we cannot pair them.
8426 if (LoadedType != Second->getLoadedType())
8429 // Check if the target supplies paired loads for this type.
8430 unsigned RequiredAlignment = 0;
8431 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8432 // move to the next pair, this type is hopeless.
8436 // Check if we meet the alignment requirement.
8437 if (RequiredAlignment > First->getAlignment())
8440 // Check that both loads are next to each other in memory.
8441 if (!areSlicesNextToEachOther(*First, *Second))
8444 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8445 --GlobalLSCost.Loads;
8446 // Move to the next pair.
8451 /// \brief Check the profitability of all involved LoadedSlice.
8452 /// Currently, it is considered profitable if there is exactly two
8453 /// involved slices (1) which are (2) next to each other in memory, and
8454 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8456 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8457 /// the elements themselves.
8459 /// FIXME: When the cost model will be mature enough, we can relax
8460 /// constraints (1) and (2).
8461 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8462 const APInt &UsedBits, bool ForCodeSize) {
8463 unsigned NumberOfSlices = LoadedSlices.size();
8464 if (StressLoadSlicing)
8465 return NumberOfSlices > 1;
8468 if (NumberOfSlices != 2)
8472 if (!areUsedBitsDense(UsedBits))
8476 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8477 // The original code has one big load.
8479 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8480 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8481 // Accumulate the cost of all the slices.
8482 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8483 GlobalSlicingCost += SliceCost;
8485 // Account as cost in the original configuration the gain obtained
8486 // with the current slices.
8487 OrigCost.addSliceGain(LS);
8490 // If the target supports paired load, adjust the cost accordingly.
8491 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8492 return OrigCost > GlobalSlicingCost;
8495 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8496 /// operations, split it in the various pieces being extracted.
8498 /// This sort of thing is introduced by SROA.
8499 /// This slicing takes care not to insert overlapping loads.
8500 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8501 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8502 if (Level < AfterLegalizeDAG)
8505 LoadSDNode *LD = cast<LoadSDNode>(N);
8506 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8507 !LD->getValueType(0).isInteger())
8510 // Keep track of already used bits to detect overlapping values.
8511 // In that case, we will just abort the transformation.
8512 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8514 SmallVector<LoadedSlice, 4> LoadedSlices;
8516 // Check if this load is used as several smaller chunks of bits.
8517 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8518 // of computation for each trunc.
8519 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8520 UI != UIEnd; ++UI) {
8521 // Skip the uses of the chain.
8522 if (UI.getUse().getResNo() != 0)
8528 // Check if this is a trunc(lshr).
8529 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8530 isa<ConstantSDNode>(User->getOperand(1))) {
8531 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8532 User = *User->use_begin();
8535 // At this point, User is a Truncate, iff we encountered, trunc or
8537 if (User->getOpcode() != ISD::TRUNCATE)
8540 // The width of the type must be a power of 2 and greater than 8-bits.
8541 // Otherwise the load cannot be represented in LLVM IR.
8542 // Moreover, if we shifted with a non-8-bits multiple, the slice
8543 // will be across several bytes. We do not support that.
8544 unsigned Width = User->getValueSizeInBits(0);
8545 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8548 // Build the slice for this chain of computations.
8549 LoadedSlice LS(User, LD, Shift, &DAG);
8550 APInt CurrentUsedBits = LS.getUsedBits();
8552 // Check if this slice overlaps with another.
8553 if ((CurrentUsedBits & UsedBits) != 0)
8555 // Update the bits used globally.
8556 UsedBits |= CurrentUsedBits;
8558 // Check if the new slice would be legal.
8562 // Record the slice.
8563 LoadedSlices.push_back(LS);
8566 // Abort slicing if it does not seem to be profitable.
8567 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8572 // Rewrite each chain to use an independent load.
8573 // By construction, each chain can be represented by a unique load.
8575 // Prepare the argument for the new token factor for all the slices.
8576 SmallVector<SDValue, 8> ArgChains;
8577 for (SmallVectorImpl<LoadedSlice>::const_iterator
8578 LSIt = LoadedSlices.begin(),
8579 LSItEnd = LoadedSlices.end();
8580 LSIt != LSItEnd; ++LSIt) {
8581 SDValue SliceInst = LSIt->loadSlice();
8582 CombineTo(LSIt->Inst, SliceInst, true);
8583 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8584 SliceInst = SliceInst.getOperand(0);
8585 assert(SliceInst->getOpcode() == ISD::LOAD &&
8586 "It takes more than a zext to get to the loaded slice!!");
8587 ArgChains.push_back(SliceInst.getValue(1));
8590 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8592 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8596 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8597 /// load is having specific bytes cleared out. If so, return the byte size
8598 /// being masked out and the shift amount.
8599 static std::pair<unsigned, unsigned>
8600 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8601 std::pair<unsigned, unsigned> Result(0, 0);
8603 // Check for the structure we're looking for.
8604 if (V->getOpcode() != ISD::AND ||
8605 !isa<ConstantSDNode>(V->getOperand(1)) ||
8606 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8609 // Check the chain and pointer.
8610 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8611 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
8613 // The store should be chained directly to the load or be an operand of a
8615 if (LD == Chain.getNode())
8617 else if (Chain->getOpcode() != ISD::TokenFactor)
8618 return Result; // Fail.
8621 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8622 if (Chain->getOperand(i).getNode() == LD) {
8626 if (!isOk) return Result;
8629 // This only handles simple types.
8630 if (V.getValueType() != MVT::i16 &&
8631 V.getValueType() != MVT::i32 &&
8632 V.getValueType() != MVT::i64)
8635 // Check the constant mask. Invert it so that the bits being masked out are
8636 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8637 // follow the sign bit for uniformity.
8638 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8639 unsigned NotMaskLZ = countLeadingZeros(NotMask);
8640 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
8641 unsigned NotMaskTZ = countTrailingZeros(NotMask);
8642 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8643 if (NotMaskLZ == 64) return Result; // All zero mask.
8645 // See if we have a continuous run of bits. If so, we have 0*1+0*
8646 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8649 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8650 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8651 NotMaskLZ -= 64-V.getValueSizeInBits();
8653 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8654 switch (MaskedBytes) {
8658 default: return Result; // All one mask, or 5-byte mask.
8661 // Verify that the first bit starts at a multiple of mask so that the access
8662 // is aligned the same as the access width.
8663 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8665 Result.first = MaskedBytes;
8666 Result.second = NotMaskTZ/8;
8671 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8672 /// provides a value as specified by MaskInfo. If so, replace the specified
8673 /// store with a narrower store of truncated IVal.
8675 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8676 SDValue IVal, StoreSDNode *St,
8678 unsigned NumBytes = MaskInfo.first;
8679 unsigned ByteShift = MaskInfo.second;
8680 SelectionDAG &DAG = DC->getDAG();
8682 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8683 // that uses this. If not, this is not a replacement.
8684 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8685 ByteShift*8, (ByteShift+NumBytes)*8);
8686 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8688 // Check that it is legal on the target to do this. It is legal if the new
8689 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8691 MVT VT = MVT::getIntegerVT(NumBytes*8);
8692 if (!DC->isTypeLegal(VT))
8695 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8696 // shifted by ByteShift and truncated down to NumBytes.
8698 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8699 DAG.getConstant(ByteShift*8,
8700 DC->getShiftAmountTy(IVal.getValueType())));
8702 // Figure out the offset for the store and the alignment of the access.
8704 unsigned NewAlign = St->getAlignment();
8706 if (DAG.getTargetLoweringInfo().isLittleEndian())
8707 StOffset = ByteShift;
8709 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8711 SDValue Ptr = St->getBasePtr();
8713 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8714 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8715 NewAlign = MinAlign(NewAlign, StOffset);
8718 // Truncate down to the new size.
8719 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8722 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8723 St->getPointerInfo().getWithOffset(StOffset),
8724 false, false, NewAlign).getNode();
8728 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8729 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8730 /// of the loaded bits, try narrowing the load and store if it would end up
8731 /// being a win for performance or code size.
8732 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8733 StoreSDNode *ST = cast<StoreSDNode>(N);
8734 if (ST->isVolatile())
8737 SDValue Chain = ST->getChain();
8738 SDValue Value = ST->getValue();
8739 SDValue Ptr = ST->getBasePtr();
8740 EVT VT = Value.getValueType();
8742 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8745 unsigned Opc = Value.getOpcode();
8747 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8748 // is a byte mask indicating a consecutive number of bytes, check to see if
8749 // Y is known to provide just those bytes. If so, we try to replace the
8750 // load + replace + store sequence with a single (narrower) store, which makes
8752 if (Opc == ISD::OR) {
8753 std::pair<unsigned, unsigned> MaskedLoad;
8754 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8755 if (MaskedLoad.first)
8756 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8757 Value.getOperand(1), ST,this))
8758 return SDValue(NewST, 0);
8760 // Or is commutative, so try swapping X and Y.
8761 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8762 if (MaskedLoad.first)
8763 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8764 Value.getOperand(0), ST,this))
8765 return SDValue(NewST, 0);
8768 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8769 Value.getOperand(1).getOpcode() != ISD::Constant)
8772 SDValue N0 = Value.getOperand(0);
8773 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8774 Chain == SDValue(N0.getNode(), 1)) {
8775 LoadSDNode *LD = cast<LoadSDNode>(N0);
8776 if (LD->getBasePtr() != Ptr ||
8777 LD->getPointerInfo().getAddrSpace() !=
8778 ST->getPointerInfo().getAddrSpace())
8781 // Find the type to narrow it the load / op / store to.
8782 SDValue N1 = Value.getOperand(1);
8783 unsigned BitWidth = N1.getValueSizeInBits();
8784 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8785 if (Opc == ISD::AND)
8786 Imm ^= APInt::getAllOnesValue(BitWidth);
8787 if (Imm == 0 || Imm.isAllOnesValue())
8789 unsigned ShAmt = Imm.countTrailingZeros();
8790 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8791 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8792 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8793 while (NewBW < BitWidth &&
8794 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8795 TLI.isNarrowingProfitable(VT, NewVT))) {
8796 NewBW = NextPowerOf2(NewBW);
8797 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8799 if (NewBW >= BitWidth)
8802 // If the lsb changed does not start at the type bitwidth boundary,
8803 // start at the previous one.
8805 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8806 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8807 std::min(BitWidth, ShAmt + NewBW));
8808 if ((Imm & Mask) == Imm) {
8809 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8810 if (Opc == ISD::AND)
8811 NewImm ^= APInt::getAllOnesValue(NewBW);
8812 uint64_t PtrOff = ShAmt / 8;
8813 // For big endian targets, we need to adjust the offset to the pointer to
8814 // load the correct bytes.
8815 if (TLI.isBigEndian())
8816 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8818 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8819 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8820 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8823 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8824 Ptr.getValueType(), Ptr,
8825 DAG.getConstant(PtrOff, Ptr.getValueType()));
8826 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8827 LD->getChain(), NewPtr,
8828 LD->getPointerInfo().getWithOffset(PtrOff),
8829 LD->isVolatile(), LD->isNonTemporal(),
8830 LD->isInvariant(), NewAlign,
8832 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8833 DAG.getConstant(NewImm, NewVT));
8834 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8836 ST->getPointerInfo().getWithOffset(PtrOff),
8837 false, false, NewAlign);
8839 AddToWorkList(NewPtr.getNode());
8840 AddToWorkList(NewLD.getNode());
8841 AddToWorkList(NewVal.getNode());
8842 WorkListRemover DeadNodes(*this);
8843 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8852 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8853 /// if the load value isn't used by any other operations, then consider
8854 /// transforming the pair to integer load / store operations if the target
8855 /// deems the transformation profitable.
8856 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8857 StoreSDNode *ST = cast<StoreSDNode>(N);
8858 SDValue Chain = ST->getChain();
8859 SDValue Value = ST->getValue();
8860 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8861 Value.hasOneUse() &&
8862 Chain == SDValue(Value.getNode(), 1)) {
8863 LoadSDNode *LD = cast<LoadSDNode>(Value);
8864 EVT VT = LD->getMemoryVT();
8865 if (!VT.isFloatingPoint() ||
8866 VT != ST->getMemoryVT() ||
8867 LD->isNonTemporal() ||
8868 ST->isNonTemporal() ||
8869 LD->getPointerInfo().getAddrSpace() != 0 ||
8870 ST->getPointerInfo().getAddrSpace() != 0)
8873 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8874 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8875 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8876 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8877 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8880 unsigned LDAlign = LD->getAlignment();
8881 unsigned STAlign = ST->getAlignment();
8882 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8883 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8884 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8887 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8888 LD->getChain(), LD->getBasePtr(),
8889 LD->getPointerInfo(),
8890 false, false, false, LDAlign);
8892 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8893 NewLD, ST->getBasePtr(),
8894 ST->getPointerInfo(),
8895 false, false, STAlign);
8897 AddToWorkList(NewLD.getNode());
8898 AddToWorkList(NewST.getNode());
8899 WorkListRemover DeadNodes(*this);
8900 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8908 /// Helper struct to parse and store a memory address as base + index + offset.
8909 /// We ignore sign extensions when it is safe to do so.
8910 /// The following two expressions are not equivalent. To differentiate we need
8911 /// to store whether there was a sign extension involved in the index
8913 /// (load (i64 add (i64 copyfromreg %c)
8914 /// (i64 signextend (add (i8 load %index)
8918 /// (load (i64 add (i64 copyfromreg %c)
8919 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8921 struct BaseIndexOffset {
8925 bool IsIndexSignExt;
8927 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8929 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8930 bool IsIndexSignExt) :
8931 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8933 bool equalBaseIndex(const BaseIndexOffset &Other) {
8934 return Other.Base == Base && Other.Index == Index &&
8935 Other.IsIndexSignExt == IsIndexSignExt;
8938 /// Parses tree in Ptr for base, index, offset addresses.
8939 static BaseIndexOffset match(SDValue Ptr) {
8940 bool IsIndexSignExt = false;
8942 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8943 // instruction, then it could be just the BASE or everything else we don't
8944 // know how to handle. Just use Ptr as BASE and give up.
8945 if (Ptr->getOpcode() != ISD::ADD)
8946 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8948 // We know that we have at least an ADD instruction. Try to pattern match
8949 // the simple case of BASE + OFFSET.
8950 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8951 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8952 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8956 // Inside a loop the current BASE pointer is calculated using an ADD and a
8957 // MUL instruction. In this case Ptr is the actual BASE pointer.
8958 // (i64 add (i64 %array_ptr)
8959 // (i64 mul (i64 %induction_var)
8960 // (i64 %element_size)))
8961 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8962 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8964 // Look at Base + Index + Offset cases.
8965 SDValue Base = Ptr->getOperand(0);
8966 SDValue IndexOffset = Ptr->getOperand(1);
8968 // Skip signextends.
8969 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8970 IndexOffset = IndexOffset->getOperand(0);
8971 IsIndexSignExt = true;
8974 // Either the case of Base + Index (no offset) or something else.
8975 if (IndexOffset->getOpcode() != ISD::ADD)
8976 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8978 // Now we have the case of Base + Index + offset.
8979 SDValue Index = IndexOffset->getOperand(0);
8980 SDValue Offset = IndexOffset->getOperand(1);
8982 if (!isa<ConstantSDNode>(Offset))
8983 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8985 // Ignore signextends.
8986 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8987 Index = Index->getOperand(0);
8988 IsIndexSignExt = true;
8989 } else IsIndexSignExt = false;
8991 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8992 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8996 /// Holds a pointer to an LSBaseSDNode as well as information on where it
8997 /// is located in a sequence of memory operations connected by a chain.
8999 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9000 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9001 // Ptr to the mem node.
9002 LSBaseSDNode *MemNode;
9003 // Offset from the base ptr.
9004 int64_t OffsetFromBase;
9005 // What is the sequence number of this mem node.
9006 // Lowest mem operand in the DAG starts at zero.
9007 unsigned SequenceNum;
9010 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9011 EVT MemVT = St->getMemoryVT();
9012 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9013 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9014 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9016 // Don't merge vectors into wider inputs.
9017 if (MemVT.isVector() || !MemVT.isSimple())
9020 // Perform an early exit check. Do not bother looking at stored values that
9021 // are not constants or loads.
9022 SDValue StoredVal = St->getValue();
9023 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9024 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9028 // Only look at ends of store sequences.
9029 SDValue Chain = SDValue(St, 1);
9030 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9033 // This holds the base pointer, index, and the offset in bytes from the base
9035 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9037 // We must have a base and an offset.
9038 if (!BasePtr.Base.getNode())
9041 // Do not handle stores to undef base pointers.
9042 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9045 // Save the LoadSDNodes that we find in the chain.
9046 // We need to make sure that these nodes do not interfere with
9047 // any of the store nodes.
9048 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9050 // Save the StoreSDNodes that we find in the chain.
9051 SmallVector<MemOpLink, 8> StoreNodes;
9053 // Walk up the chain and look for nodes with offsets from the same
9054 // base pointer. Stop when reaching an instruction with a different kind
9055 // or instruction which has a different base pointer.
9057 StoreSDNode *Index = St;
9059 // If the chain has more than one use, then we can't reorder the mem ops.
9060 if (Index != St && !SDValue(Index, 1)->hasOneUse())
9063 // Find the base pointer and offset for this memory node.
9064 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9066 // Check that the base pointer is the same as the original one.
9067 if (!Ptr.equalBaseIndex(BasePtr))
9070 // Check that the alignment is the same.
9071 if (Index->getAlignment() != St->getAlignment())
9074 // The memory operands must not be volatile.
9075 if (Index->isVolatile() || Index->isIndexed())
9079 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9080 if (St->isTruncatingStore())
9083 // The stored memory type must be the same.
9084 if (Index->getMemoryVT() != MemVT)
9087 // We do not allow unaligned stores because we want to prevent overriding
9089 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9092 // We found a potential memory operand to merge.
9093 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9095 // Find the next memory operand in the chain. If the next operand in the
9096 // chain is a store then move up and continue the scan with the next
9097 // memory operand. If the next operand is a load save it and use alias
9098 // information to check if it interferes with anything.
9099 SDNode *NextInChain = Index->getChain().getNode();
9101 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9102 // We found a store node. Use it for the next iteration.
9105 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9106 if (Ldn->isVolatile()) {
9111 // Save the load node for later. Continue the scan.
9112 AliasLoadNodes.push_back(Ldn);
9113 NextInChain = Ldn->getChain().getNode();
9122 // Check if there is anything to merge.
9123 if (StoreNodes.size() < 2)
9126 // Sort the memory operands according to their distance from the base pointer.
9127 std::sort(StoreNodes.begin(), StoreNodes.end(),
9128 [](MemOpLink LHS, MemOpLink RHS) {
9129 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9130 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9131 LHS.SequenceNum > RHS.SequenceNum);
9134 // Scan the memory operations on the chain and find the first non-consecutive
9135 // store memory address.
9136 unsigned LastConsecutiveStore = 0;
9137 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9138 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9140 // Check that the addresses are consecutive starting from the second
9141 // element in the list of stores.
9143 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9144 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9149 // Check if this store interferes with any of the loads that we found.
9150 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9151 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9155 // We found a load that alias with this store. Stop the sequence.
9159 // Mark this node as useful.
9160 LastConsecutiveStore = i;
9163 // The node with the lowest store address.
9164 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9166 // Store the constants into memory as one consecutive store.
9168 unsigned LastLegalType = 0;
9169 unsigned LastLegalVectorType = 0;
9170 bool NonZero = false;
9171 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9172 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9173 SDValue StoredVal = St->getValue();
9175 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9176 NonZero |= !C->isNullValue();
9177 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9178 NonZero |= !C->getConstantFPValue()->isNullValue();
9184 // Find a legal type for the constant store.
9185 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9186 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9187 if (TLI.isTypeLegal(StoreTy))
9188 LastLegalType = i+1;
9189 // Or check whether a truncstore is legal.
9190 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9191 TargetLowering::TypePromoteInteger) {
9192 EVT LegalizedStoredValueTy =
9193 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9194 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9195 LastLegalType = i+1;
9198 // Find a legal type for the vector store.
9199 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9200 if (TLI.isTypeLegal(Ty))
9201 LastLegalVectorType = i + 1;
9204 // We only use vectors if the constant is known to be zero and the
9205 // function is not marked with the noimplicitfloat attribute.
9206 if (NonZero || NoVectors)
9207 LastLegalVectorType = 0;
9209 // Check if we found a legal integer type to store.
9210 if (LastLegalType == 0 && LastLegalVectorType == 0)
9213 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9214 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9216 // Make sure we have something to merge.
9220 unsigned EarliestNodeUsed = 0;
9221 for (unsigned i=0; i < NumElem; ++i) {
9222 // Find a chain for the new wide-store operand. Notice that some
9223 // of the store nodes that we found may not be selected for inclusion
9224 // in the wide store. The chain we use needs to be the chain of the
9225 // earliest store node which is *used* and replaced by the wide store.
9226 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9227 EarliestNodeUsed = i;
9230 // The earliest Node in the DAG.
9231 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9232 SDLoc DL(StoreNodes[0].MemNode);
9236 // Find a legal type for the vector store.
9237 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9238 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9239 StoredVal = DAG.getConstant(0, Ty);
9241 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9242 APInt StoreInt(StoreBW, 0);
9244 // Construct a single integer constant which is made of the smaller
9246 bool IsLE = TLI.isLittleEndian();
9247 for (unsigned i = 0; i < NumElem ; ++i) {
9248 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9249 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9250 SDValue Val = St->getValue();
9251 StoreInt<<=ElementSizeBytes*8;
9252 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9253 StoreInt|=C->getAPIntValue().zext(StoreBW);
9254 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9255 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9257 assert(false && "Invalid constant element type");
9261 // Create the new Load and Store operations.
9262 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9263 StoredVal = DAG.getConstant(StoreInt, StoreTy);
9266 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9267 FirstInChain->getBasePtr(),
9268 FirstInChain->getPointerInfo(),
9270 FirstInChain->getAlignment());
9272 // Replace the first store with the new store
9273 CombineTo(EarliestOp, NewStore);
9274 // Erase all other stores.
9275 for (unsigned i = 0; i < NumElem ; ++i) {
9276 if (StoreNodes[i].MemNode == EarliestOp)
9278 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9279 // ReplaceAllUsesWith will replace all uses that existed when it was
9280 // called, but graph optimizations may cause new ones to appear. For
9281 // example, the case in pr14333 looks like
9283 // St's chain -> St -> another store -> X
9285 // And the only difference from St to the other store is the chain.
9286 // When we change it's chain to be St's chain they become identical,
9287 // get CSEed and the net result is that X is now a use of St.
9288 // Since we know that St is redundant, just iterate.
9289 while (!St->use_empty())
9290 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9291 removeFromWorkList(St);
9298 // Below we handle the case of multiple consecutive stores that
9299 // come from multiple consecutive loads. We merge them into a single
9300 // wide load and a single wide store.
9302 // Look for load nodes which are used by the stored values.
9303 SmallVector<MemOpLink, 8> LoadNodes;
9305 // Find acceptable loads. Loads need to have the same chain (token factor),
9306 // must not be zext, volatile, indexed, and they must be consecutive.
9307 BaseIndexOffset LdBasePtr;
9308 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9309 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9310 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9313 // Loads must only have one use.
9314 if (!Ld->hasNUsesOfValue(1, 0))
9317 // Check that the alignment is the same as the stores.
9318 if (Ld->getAlignment() != St->getAlignment())
9321 // The memory operands must not be volatile.
9322 if (Ld->isVolatile() || Ld->isIndexed())
9325 // We do not accept ext loads.
9326 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9329 // The stored memory type must be the same.
9330 if (Ld->getMemoryVT() != MemVT)
9333 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9334 // If this is not the first ptr that we check.
9335 if (LdBasePtr.Base.getNode()) {
9336 // The base ptr must be the same.
9337 if (!LdPtr.equalBaseIndex(LdBasePtr))
9340 // Check that all other base pointers are the same as this one.
9344 // We found a potential memory operand to merge.
9345 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9348 if (LoadNodes.size() < 2)
9351 // Scan the memory operations on the chain and find the first non-consecutive
9352 // load memory address. These variables hold the index in the store node
9354 unsigned LastConsecutiveLoad = 0;
9355 // This variable refers to the size and not index in the array.
9356 unsigned LastLegalVectorType = 0;
9357 unsigned LastLegalIntegerType = 0;
9358 StartAddress = LoadNodes[0].OffsetFromBase;
9359 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9360 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9361 // All loads much share the same chain.
9362 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9365 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9366 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9368 LastConsecutiveLoad = i;
9370 // Find a legal type for the vector store.
9371 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9372 if (TLI.isTypeLegal(StoreTy))
9373 LastLegalVectorType = i + 1;
9375 // Find a legal type for the integer store.
9376 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9377 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9378 if (TLI.isTypeLegal(StoreTy))
9379 LastLegalIntegerType = i + 1;
9380 // Or check whether a truncstore and extload is legal.
9381 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9382 TargetLowering::TypePromoteInteger) {
9383 EVT LegalizedStoredValueTy =
9384 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9385 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9386 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9387 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9388 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9389 LastLegalIntegerType = i+1;
9393 // Only use vector types if the vector type is larger than the integer type.
9394 // If they are the same, use integers.
9395 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9396 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9398 // We add +1 here because the LastXXX variables refer to location while
9399 // the NumElem refers to array/index size.
9400 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9401 NumElem = std::min(LastLegalType, NumElem);
9406 // The earliest Node in the DAG.
9407 unsigned EarliestNodeUsed = 0;
9408 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9409 for (unsigned i=1; i<NumElem; ++i) {
9410 // Find a chain for the new wide-store operand. Notice that some
9411 // of the store nodes that we found may not be selected for inclusion
9412 // in the wide store. The chain we use needs to be the chain of the
9413 // earliest store node which is *used* and replaced by the wide store.
9414 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9415 EarliestNodeUsed = i;
9418 // Find if it is better to use vectors or integers to load and store
9422 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9424 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9425 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9428 SDLoc LoadDL(LoadNodes[0].MemNode);
9429 SDLoc StoreDL(StoreNodes[0].MemNode);
9431 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9432 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9433 FirstLoad->getChain(),
9434 FirstLoad->getBasePtr(),
9435 FirstLoad->getPointerInfo(),
9436 false, false, false,
9437 FirstLoad->getAlignment());
9439 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9440 FirstInChain->getBasePtr(),
9441 FirstInChain->getPointerInfo(), false, false,
9442 FirstInChain->getAlignment());
9444 // Replace one of the loads with the new load.
9445 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9446 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9447 SDValue(NewLoad.getNode(), 1));
9449 // Remove the rest of the load chains.
9450 for (unsigned i = 1; i < NumElem ; ++i) {
9451 // Replace all chain users of the old load nodes with the chain of the new
9453 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9454 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9457 // Replace the first store with the new store.
9458 CombineTo(EarliestOp, NewStore);
9459 // Erase all other stores.
9460 for (unsigned i = 0; i < NumElem ; ++i) {
9461 // Remove all Store nodes.
9462 if (StoreNodes[i].MemNode == EarliestOp)
9464 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9465 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9466 removeFromWorkList(St);
9473 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9474 StoreSDNode *ST = cast<StoreSDNode>(N);
9475 SDValue Chain = ST->getChain();
9476 SDValue Value = ST->getValue();
9477 SDValue Ptr = ST->getBasePtr();
9479 // If this is a store of a bit convert, store the input value if the
9480 // resultant store does not need a higher alignment than the original.
9481 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9482 ST->isUnindexed()) {
9483 unsigned OrigAlign = ST->getAlignment();
9484 EVT SVT = Value.getOperand(0).getValueType();
9485 unsigned Align = TLI.getDataLayout()->
9486 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9487 if (Align <= OrigAlign &&
9488 ((!LegalOperations && !ST->isVolatile()) ||
9489 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9490 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9491 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9492 ST->isNonTemporal(), OrigAlign,
9496 // Turn 'store undef, Ptr' -> nothing.
9497 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9500 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9501 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9502 // NOTE: If the original store is volatile, this transform must not increase
9503 // the number of stores. For example, on x86-32 an f64 can be stored in one
9504 // processor operation but an i64 (which is not legal) requires two. So the
9505 // transform should not be done in this case.
9506 if (Value.getOpcode() != ISD::TargetConstantFP) {
9508 switch (CFP->getSimpleValueType(0).SimpleTy) {
9509 default: llvm_unreachable("Unknown FP type");
9510 case MVT::f16: // We don't do this for these yet.
9516 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9517 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9518 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9519 bitcastToAPInt().getZExtValue(), MVT::i32);
9520 return DAG.getStore(Chain, SDLoc(N), Tmp,
9521 Ptr, ST->getMemOperand());
9525 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9526 !ST->isVolatile()) ||
9527 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9528 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9529 getZExtValue(), MVT::i64);
9530 return DAG.getStore(Chain, SDLoc(N), Tmp,
9531 Ptr, ST->getMemOperand());
9534 if (!ST->isVolatile() &&
9535 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9536 // Many FP stores are not made apparent until after legalize, e.g. for
9537 // argument passing. Since this is so common, custom legalize the
9538 // 64-bit integer store into two 32-bit stores.
9539 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9540 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9541 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9542 if (TLI.isBigEndian()) std::swap(Lo, Hi);
9544 unsigned Alignment = ST->getAlignment();
9545 bool isVolatile = ST->isVolatile();
9546 bool isNonTemporal = ST->isNonTemporal();
9547 const MDNode *TBAAInfo = ST->getTBAAInfo();
9549 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9550 Ptr, ST->getPointerInfo(),
9551 isVolatile, isNonTemporal,
9552 ST->getAlignment(), TBAAInfo);
9553 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9554 DAG.getConstant(4, Ptr.getValueType()));
9555 Alignment = MinAlign(Alignment, 4U);
9556 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9557 Ptr, ST->getPointerInfo().getWithOffset(4),
9558 isVolatile, isNonTemporal,
9559 Alignment, TBAAInfo);
9560 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9569 // Try to infer better alignment information than the store already has.
9570 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9571 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9572 if (Align > ST->getAlignment())
9573 return DAG.getTruncStore(Chain, SDLoc(N), Value,
9574 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9575 ST->isVolatile(), ST->isNonTemporal(), Align,
9580 // Try transforming a pair floating point load / store ops to integer
9581 // load / store ops.
9582 SDValue NewST = TransformFPLoadStorePair(N);
9583 if (NewST.getNode())
9586 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9587 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9589 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9590 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9593 if (UseAA && ST->isUnindexed()) {
9594 // Walk up chain skipping non-aliasing memory nodes.
9595 SDValue BetterChain = FindBetterChain(N, Chain);
9597 // If there is a better chain.
9598 if (Chain != BetterChain) {
9601 // Replace the chain to avoid dependency.
9602 if (ST->isTruncatingStore()) {
9603 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9604 ST->getMemoryVT(), ST->getMemOperand());
9606 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9607 ST->getMemOperand());
9610 // Create token to keep both nodes around.
9611 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9612 MVT::Other, Chain, ReplStore);
9614 // Make sure the new and old chains are cleaned up.
9615 AddToWorkList(Token.getNode());
9617 // Don't add users to work list.
9618 return CombineTo(N, Token, false);
9622 // Try transforming N to an indexed store.
9623 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9624 return SDValue(N, 0);
9626 // FIXME: is there such a thing as a truncating indexed store?
9627 if (ST->isTruncatingStore() && ST->isUnindexed() &&
9628 Value.getValueType().isInteger()) {
9629 // See if we can simplify the input to this truncstore with knowledge that
9630 // only the low bits are being used. For example:
9631 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
9633 GetDemandedBits(Value,
9634 APInt::getLowBitsSet(
9635 Value.getValueType().getScalarType().getSizeInBits(),
9636 ST->getMemoryVT().getScalarType().getSizeInBits()));
9637 AddToWorkList(Value.getNode());
9638 if (Shorter.getNode())
9639 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9640 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9642 // Otherwise, see if we can simplify the operation with
9643 // SimplifyDemandedBits, which only works if the value has a single use.
9644 if (SimplifyDemandedBits(Value,
9645 APInt::getLowBitsSet(
9646 Value.getValueType().getScalarType().getSizeInBits(),
9647 ST->getMemoryVT().getScalarType().getSizeInBits())))
9648 return SDValue(N, 0);
9651 // If this is a load followed by a store to the same location, then the store
9653 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9654 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9655 ST->isUnindexed() && !ST->isVolatile() &&
9656 // There can't be any side effects between the load and store, such as
9658 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9659 // The store is dead, remove it.
9664 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9665 // truncating store. We can do this even if this is already a truncstore.
9666 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9667 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9668 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9669 ST->getMemoryVT())) {
9670 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9671 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9674 // Only perform this optimization before the types are legal, because we
9675 // don't want to perform this optimization on every DAGCombine invocation.
9677 bool EverChanged = false;
9680 // There can be multiple store sequences on the same chain.
9681 // Keep trying to merge store sequences until we are unable to do so
9682 // or until we merge the last store on the chain.
9683 bool Changed = MergeConsecutiveStores(ST);
9684 EverChanged |= Changed;
9685 if (!Changed) break;
9686 } while (ST->getOpcode() != ISD::DELETED_NODE);
9689 return SDValue(N, 0);
9692 return ReduceLoadOpStoreWidth(N);
9695 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9696 SDValue InVec = N->getOperand(0);
9697 SDValue InVal = N->getOperand(1);
9698 SDValue EltNo = N->getOperand(2);
9701 // If the inserted element is an UNDEF, just use the input vector.
9702 if (InVal.getOpcode() == ISD::UNDEF)
9705 EVT VT = InVec.getValueType();
9707 // If we can't generate a legal BUILD_VECTOR, exit
9708 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9711 // Check that we know which element is being inserted
9712 if (!isa<ConstantSDNode>(EltNo))
9714 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9716 // Canonicalize insert_vector_elt dag nodes.
9718 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9719 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9721 // Do this only if the child insert_vector node has one use; also
9722 // do this only if indices are both constants and Idx1 < Idx0.
9723 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9724 && isa<ConstantSDNode>(InVec.getOperand(2))) {
9726 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9727 if (Elt < OtherElt) {
9729 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9730 InVec.getOperand(0), InVal, EltNo);
9731 AddToWorkList(NewOp.getNode());
9732 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9733 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9737 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9738 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9740 SmallVector<SDValue, 8> Ops;
9741 // Do not combine these two vectors if the output vector will not replace
9742 // the input vector.
9743 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9744 Ops.append(InVec.getNode()->op_begin(),
9745 InVec.getNode()->op_end());
9746 } else if (InVec.getOpcode() == ISD::UNDEF) {
9747 unsigned NElts = VT.getVectorNumElements();
9748 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9753 // Insert the element
9754 if (Elt < Ops.size()) {
9755 // All the operands of BUILD_VECTOR must have the same type;
9756 // we enforce that here.
9757 EVT OpVT = Ops[0].getValueType();
9758 if (InVal.getValueType() != OpVT)
9759 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9760 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9761 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9765 // Return the new vector
9766 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
9769 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
9770 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
9771 EVT ResultVT = EVE->getValueType(0);
9772 EVT VecEltVT = InVecVT.getVectorElementType();
9773 unsigned Align = OriginalLoad->getAlignment();
9774 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
9775 VecEltVT.getTypeForEVT(*DAG.getContext()));
9777 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
9782 SDValue NewPtr = OriginalLoad->getBasePtr();
9784 EVT PtrType = NewPtr.getValueType();
9785 MachinePointerInfo MPI;
9786 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
9787 int Elt = ConstEltNo->getZExtValue();
9788 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
9789 if (TLI.isBigEndian())
9790 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
9791 Offset = DAG.getConstant(PtrOff, PtrType);
9792 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
9794 Offset = DAG.getNode(
9795 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
9796 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
9797 if (TLI.isBigEndian())
9798 Offset = DAG.getNode(
9799 ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
9800 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
9801 MPI = OriginalLoad->getPointerInfo();
9803 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
9805 // The replacement we need to do here is a little tricky: we need to
9806 // replace an extractelement of a load with a load.
9807 // Use ReplaceAllUsesOfValuesWith to do the replacement.
9808 // Note that this replacement assumes that the extractvalue is the only
9809 // use of the load; that's okay because we don't want to perform this
9810 // transformation in other cases anyway.
9813 if (ResultVT.bitsGT(VecEltVT)) {
9814 // If the result type of vextract is wider than the load, then issue an
9815 // extending load instead.
9816 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
9819 Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(),
9820 NewPtr, MPI, VecEltVT, OriginalLoad->isVolatile(),
9821 OriginalLoad->isNonTemporal(), Align,
9822 OriginalLoad->getTBAAInfo());
9823 Chain = Load.getValue(1);
9826 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
9827 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
9828 OriginalLoad->isInvariant(), Align, OriginalLoad->getTBAAInfo());
9829 Chain = Load.getValue(1);
9830 if (ResultVT.bitsLT(VecEltVT))
9831 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
9833 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
9835 WorkListRemover DeadNodes(*this);
9836 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
9837 SDValue To[] = { Load, Chain };
9838 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9839 // Since we're explicitly calling ReplaceAllUses, add the new node to the
9840 // worklist explicitly as well.
9841 AddToWorkList(Load.getNode());
9842 AddUsersToWorkList(Load.getNode()); // Add users too
9843 // Make sure to revisit this node to clean it up; it will usually be dead.
9846 return SDValue(EVE, 0);
9849 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9850 // (vextract (scalar_to_vector val, 0) -> val
9851 SDValue InVec = N->getOperand(0);
9852 EVT VT = InVec.getValueType();
9853 EVT NVT = N->getValueType(0);
9855 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9856 // Check if the result type doesn't match the inserted element type. A
9857 // SCALAR_TO_VECTOR may truncate the inserted element and the
9858 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9859 SDValue InOp = InVec.getOperand(0);
9860 if (InOp.getValueType() != NVT) {
9861 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9862 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9867 SDValue EltNo = N->getOperand(1);
9868 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9870 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9871 // We only perform this optimization before the op legalization phase because
9872 // we may introduce new vector instructions which are not backed by TD
9873 // patterns. For example on AVX, extracting elements from a wide vector
9874 // without using extract_subvector. However, if we can find an underlying
9875 // scalar value, then we can always use that.
9876 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9878 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9879 int NumElem = VT.getVectorNumElements();
9880 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9881 // Find the new index to extract from.
9882 int OrigElt = SVOp->getMaskElt(Elt);
9884 // Extracting an undef index is undef.
9886 return DAG.getUNDEF(NVT);
9888 // Select the right vector half to extract from.
9890 if (OrigElt < NumElem) {
9891 SVInVec = InVec->getOperand(0);
9893 SVInVec = InVec->getOperand(1);
9897 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9898 SDValue InOp = SVInVec.getOperand(OrigElt);
9899 if (InOp.getValueType() != NVT) {
9900 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9901 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9907 // FIXME: We should handle recursing on other vector shuffles and
9908 // scalar_to_vector here as well.
9910 if (!LegalOperations) {
9911 EVT IndexTy = TLI.getVectorIdxTy();
9912 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9913 SVInVec, DAG.getConstant(OrigElt, IndexTy));
9917 bool BCNumEltsChanged = false;
9918 EVT ExtVT = VT.getVectorElementType();
9921 // If the result of load has to be truncated, then it's not necessarily
9923 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9926 if (InVec.getOpcode() == ISD::BITCAST) {
9927 // Don't duplicate a load with other uses.
9928 if (!InVec.hasOneUse())
9931 EVT BCVT = InVec.getOperand(0).getValueType();
9932 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9934 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9935 BCNumEltsChanged = true;
9936 InVec = InVec.getOperand(0);
9937 ExtVT = BCVT.getVectorElementType();
9940 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
9941 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
9942 ISD::isNormalLoad(InVec.getNode())) {
9943 SDValue Index = N->getOperand(1);
9944 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
9945 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
9949 // Perform only after legalization to ensure build_vector / vector_shuffle
9950 // optimizations have already been done.
9951 if (!LegalOperations) return SDValue();
9953 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9954 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9955 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9958 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9960 LoadSDNode *LN0 = nullptr;
9961 const ShuffleVectorSDNode *SVN = nullptr;
9962 if (ISD::isNormalLoad(InVec.getNode())) {
9963 LN0 = cast<LoadSDNode>(InVec);
9964 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9965 InVec.getOperand(0).getValueType() == ExtVT &&
9966 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9967 // Don't duplicate a load with other uses.
9968 if (!InVec.hasOneUse())
9971 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9972 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9973 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9975 // (load $addr+1*size)
9977 // Don't duplicate a load with other uses.
9978 if (!InVec.hasOneUse())
9981 // If the bit convert changed the number of elements, it is unsafe
9982 // to examine the mask.
9983 if (BCNumEltsChanged)
9986 // Select the input vector, guarding against out of range extract vector.
9987 unsigned NumElems = VT.getVectorNumElements();
9988 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9989 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9991 if (InVec.getOpcode() == ISD::BITCAST) {
9992 // Don't duplicate a load with other uses.
9993 if (!InVec.hasOneUse())
9996 InVec = InVec.getOperand(0);
9998 if (ISD::isNormalLoad(InVec.getNode())) {
9999 LN0 = cast<LoadSDNode>(InVec);
10000 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10001 EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10005 // Make sure we found a non-volatile load and the extractelement is
10007 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10010 // If Idx was -1 above, Elt is going to be -1, so just return undef.
10012 return DAG.getUNDEF(LVT);
10014 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10020 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10021 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10022 // We perform this optimization post type-legalization because
10023 // the type-legalizer often scalarizes integer-promoted vectors.
10024 // Performing this optimization before may create bit-casts which
10025 // will be type-legalized to complex code sequences.
10026 // We perform this optimization only before the operation legalizer because we
10027 // may introduce illegal operations.
10028 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10031 unsigned NumInScalars = N->getNumOperands();
10033 EVT VT = N->getValueType(0);
10035 // Check to see if this is a BUILD_VECTOR of a bunch of values
10036 // which come from any_extend or zero_extend nodes. If so, we can create
10037 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10038 // optimizations. We do not handle sign-extend because we can't fill the sign
10040 EVT SourceType = MVT::Other;
10041 bool AllAnyExt = true;
10043 for (unsigned i = 0; i != NumInScalars; ++i) {
10044 SDValue In = N->getOperand(i);
10045 // Ignore undef inputs.
10046 if (In.getOpcode() == ISD::UNDEF) continue;
10048 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
10049 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10051 // Abort if the element is not an extension.
10052 if (!ZeroExt && !AnyExt) {
10053 SourceType = MVT::Other;
10057 // The input is a ZeroExt or AnyExt. Check the original type.
10058 EVT InTy = In.getOperand(0).getValueType();
10060 // Check that all of the widened source types are the same.
10061 if (SourceType == MVT::Other)
10064 else if (InTy != SourceType) {
10065 // Multiple income types. Abort.
10066 SourceType = MVT::Other;
10070 // Check if all of the extends are ANY_EXTENDs.
10071 AllAnyExt &= AnyExt;
10074 // In order to have valid types, all of the inputs must be extended from the
10075 // same source type and all of the inputs must be any or zero extend.
10076 // Scalar sizes must be a power of two.
10077 EVT OutScalarTy = VT.getScalarType();
10078 bool ValidTypes = SourceType != MVT::Other &&
10079 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10080 isPowerOf2_32(SourceType.getSizeInBits());
10082 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10083 // turn into a single shuffle instruction.
10087 bool isLE = TLI.isLittleEndian();
10088 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10089 assert(ElemRatio > 1 && "Invalid element size ratio");
10090 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10091 DAG.getConstant(0, SourceType);
10093 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10094 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10096 // Populate the new build_vector
10097 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10098 SDValue Cast = N->getOperand(i);
10099 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10100 Cast.getOpcode() == ISD::ZERO_EXTEND ||
10101 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10103 if (Cast.getOpcode() == ISD::UNDEF)
10104 In = DAG.getUNDEF(SourceType);
10106 In = Cast->getOperand(0);
10107 unsigned Index = isLE ? (i * ElemRatio) :
10108 (i * ElemRatio + (ElemRatio - 1));
10110 assert(Index < Ops.size() && "Invalid index");
10114 // The type of the new BUILD_VECTOR node.
10115 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10116 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10117 "Invalid vector size");
10118 // Check if the new vector type is legal.
10119 if (!isTypeLegal(VecVT)) return SDValue();
10121 // Make the new BUILD_VECTOR.
10122 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10124 // The new BUILD_VECTOR node has the potential to be further optimized.
10125 AddToWorkList(BV.getNode());
10126 // Bitcast to the desired type.
10127 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10130 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10131 EVT VT = N->getValueType(0);
10133 unsigned NumInScalars = N->getNumOperands();
10136 EVT SrcVT = MVT::Other;
10137 unsigned Opcode = ISD::DELETED_NODE;
10138 unsigned NumDefs = 0;
10140 for (unsigned i = 0; i != NumInScalars; ++i) {
10141 SDValue In = N->getOperand(i);
10142 unsigned Opc = In.getOpcode();
10144 if (Opc == ISD::UNDEF)
10147 // If all scalar values are floats and converted from integers.
10148 if (Opcode == ISD::DELETED_NODE &&
10149 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10156 EVT InVT = In.getOperand(0).getValueType();
10158 // If all scalar values are typed differently, bail out. It's chosen to
10159 // simplify BUILD_VECTOR of integer types.
10160 if (SrcVT == MVT::Other)
10167 // If the vector has just one element defined, it's not worth to fold it into
10168 // a vectorized one.
10172 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10173 && "Should only handle conversion from integer to float.");
10174 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10176 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10178 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10181 SmallVector<SDValue, 8> Opnds;
10182 for (unsigned i = 0; i != NumInScalars; ++i) {
10183 SDValue In = N->getOperand(i);
10185 if (In.getOpcode() == ISD::UNDEF)
10186 Opnds.push_back(DAG.getUNDEF(SrcVT));
10188 Opnds.push_back(In.getOperand(0));
10190 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10191 AddToWorkList(BV.getNode());
10193 return DAG.getNode(Opcode, dl, VT, BV);
10196 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10197 unsigned NumInScalars = N->getNumOperands();
10199 EVT VT = N->getValueType(0);
10201 // A vector built entirely of undefs is undef.
10202 if (ISD::allOperandsUndef(N))
10203 return DAG.getUNDEF(VT);
10205 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10209 V = reduceBuildVecConvertToConvertBuildVec(N);
10213 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10214 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10215 // at most two distinct vectors, turn this into a shuffle node.
10217 // May only combine to shuffle after legalize if shuffle is legal.
10218 if (LegalOperations &&
10219 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10222 SDValue VecIn1, VecIn2;
10223 for (unsigned i = 0; i != NumInScalars; ++i) {
10224 // Ignore undef inputs.
10225 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10227 // If this input is something other than a EXTRACT_VECTOR_ELT with a
10228 // constant index, bail out.
10229 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10230 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10231 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10235 // We allow up to two distinct input vectors.
10236 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10237 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10240 if (!VecIn1.getNode()) {
10241 VecIn1 = ExtractedFromVec;
10242 } else if (!VecIn2.getNode()) {
10243 VecIn2 = ExtractedFromVec;
10245 // Too many inputs.
10246 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10251 // If everything is good, we can make a shuffle operation.
10252 if (VecIn1.getNode()) {
10253 SmallVector<int, 8> Mask;
10254 for (unsigned i = 0; i != NumInScalars; ++i) {
10255 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10256 Mask.push_back(-1);
10260 // If extracting from the first vector, just use the index directly.
10261 SDValue Extract = N->getOperand(i);
10262 SDValue ExtVal = Extract.getOperand(1);
10263 if (Extract.getOperand(0) == VecIn1) {
10264 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10265 if (ExtIndex > VT.getVectorNumElements())
10268 Mask.push_back(ExtIndex);
10272 // Otherwise, use InIdx + VecSize
10273 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10274 Mask.push_back(Idx+NumInScalars);
10277 // We can't generate a shuffle node with mismatched input and output types.
10278 // Attempt to transform a single input vector to the correct type.
10279 if ((VT != VecIn1.getValueType())) {
10280 // We don't support shuffeling between TWO values of different types.
10281 if (VecIn2.getNode())
10284 // We only support widening of vectors which are half the size of the
10285 // output registers. For example XMM->YMM widening on X86 with AVX.
10286 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10289 // If the input vector type has a different base type to the output
10290 // vector type, bail out.
10291 if (VecIn1.getValueType().getVectorElementType() !=
10292 VT.getVectorElementType())
10295 // Widen the input vector by adding undef values.
10296 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10297 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10300 // If VecIn2 is unused then change it to undef.
10301 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10303 // Check that we were able to transform all incoming values to the same
10305 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10306 VecIn1.getValueType() != VT)
10309 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10310 if (!isTypeLegal(VT))
10313 // Return the new VECTOR_SHUFFLE node.
10317 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10323 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10324 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10325 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10326 // inputs come from at most two distinct vectors, turn this into a shuffle
10329 // If we only have one input vector, we don't need to do any concatenation.
10330 if (N->getNumOperands() == 1)
10331 return N->getOperand(0);
10333 // Check if all of the operands are undefs.
10334 EVT VT = N->getValueType(0);
10335 if (ISD::allOperandsUndef(N))
10336 return DAG.getUNDEF(VT);
10338 // Optimize concat_vectors where one of the vectors is undef.
10339 if (N->getNumOperands() == 2 &&
10340 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10341 SDValue In = N->getOperand(0);
10342 assert(In.getValueType().isVector() && "Must concat vectors");
10344 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10345 if (In->getOpcode() == ISD::BITCAST &&
10346 !In->getOperand(0)->getValueType(0).isVector()) {
10347 SDValue Scalar = In->getOperand(0);
10348 EVT SclTy = Scalar->getValueType(0);
10350 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10353 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10354 VT.getSizeInBits() / SclTy.getSizeInBits());
10355 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10358 SDLoc dl = SDLoc(N);
10359 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10360 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10364 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10365 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10366 if (N->getNumOperands() == 2 &&
10367 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10368 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10369 EVT VT = N->getValueType(0);
10370 SDValue N0 = N->getOperand(0);
10371 SDValue N1 = N->getOperand(1);
10372 SmallVector<SDValue, 8> Opnds;
10373 unsigned BuildVecNumElts = N0.getNumOperands();
10375 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10376 Opnds.push_back(N0.getOperand(i));
10377 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10378 Opnds.push_back(N1.getOperand(i));
10380 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10383 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10384 // nodes often generate nop CONCAT_VECTOR nodes.
10385 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10386 // place the incoming vectors at the exact same location.
10387 SDValue SingleSource = SDValue();
10388 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10390 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10391 SDValue Op = N->getOperand(i);
10393 if (Op.getOpcode() == ISD::UNDEF)
10396 // Check if this is the identity extract:
10397 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10400 // Find the single incoming vector for the extract_subvector.
10401 if (SingleSource.getNode()) {
10402 if (Op.getOperand(0) != SingleSource)
10405 SingleSource = Op.getOperand(0);
10407 // Check the source type is the same as the type of the result.
10408 // If not, this concat may extend the vector, so we can not
10409 // optimize it away.
10410 if (SingleSource.getValueType() != N->getValueType(0))
10414 unsigned IdentityIndex = i * PartNumElem;
10415 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10416 // The extract index must be constant.
10420 // Check that we are reading from the identity index.
10421 if (CS->getZExtValue() != IdentityIndex)
10425 if (SingleSource.getNode())
10426 return SingleSource;
10431 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10432 EVT NVT = N->getValueType(0);
10433 SDValue V = N->getOperand(0);
10435 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10437 // (extract_subvec (concat V1, V2, ...), i)
10440 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10442 if (V->getOperand(0).getValueType() != NVT)
10444 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10445 unsigned NumElems = NVT.getVectorNumElements();
10446 assert((Idx % NumElems) == 0 &&
10447 "IDX in concat is not a multiple of the result vector length.");
10448 return V->getOperand(Idx / NumElems);
10452 if (V->getOpcode() == ISD::BITCAST)
10453 V = V.getOperand(0);
10455 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10457 // Handle only simple case where vector being inserted and vector
10458 // being extracted are of same type, and are half size of larger vectors.
10459 EVT BigVT = V->getOperand(0).getValueType();
10460 EVT SmallVT = V->getOperand(1).getValueType();
10461 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10464 // Only handle cases where both indexes are constants with the same type.
10465 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10466 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10468 if (InsIdx && ExtIdx &&
10469 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10470 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10472 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10474 // indices are equal or bit offsets are equal => V1
10475 // otherwise => (extract_subvec V1, ExtIdx)
10476 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10477 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10478 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10479 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10480 DAG.getNode(ISD::BITCAST, dl,
10481 N->getOperand(0).getValueType(),
10482 V->getOperand(0)), N->getOperand(1));
10489 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10490 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10491 EVT VT = N->getValueType(0);
10492 unsigned NumElts = VT.getVectorNumElements();
10494 SDValue N0 = N->getOperand(0);
10495 SDValue N1 = N->getOperand(1);
10496 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10498 SmallVector<SDValue, 4> Ops;
10499 EVT ConcatVT = N0.getOperand(0).getValueType();
10500 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10501 unsigned NumConcats = NumElts / NumElemsPerConcat;
10503 // Look at every vector that's inserted. We're looking for exact
10504 // subvector-sized copies from a concatenated vector
10505 for (unsigned I = 0; I != NumConcats; ++I) {
10506 // Make sure we're dealing with a copy.
10507 unsigned Begin = I * NumElemsPerConcat;
10508 bool AllUndef = true, NoUndef = true;
10509 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10510 if (SVN->getMaskElt(J) >= 0)
10517 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10520 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10521 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10524 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10525 if (FirstElt < N0.getNumOperands())
10526 Ops.push_back(N0.getOperand(FirstElt));
10528 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10530 } else if (AllUndef) {
10531 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10532 } else { // Mixed with general masks and undefs, can't do optimization.
10537 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10540 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10541 EVT VT = N->getValueType(0);
10542 unsigned NumElts = VT.getVectorNumElements();
10544 SDValue N0 = N->getOperand(0);
10545 SDValue N1 = N->getOperand(1);
10547 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10549 // Canonicalize shuffle undef, undef -> undef
10550 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10551 return DAG.getUNDEF(VT);
10553 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10555 // Canonicalize shuffle v, v -> v, undef
10557 SmallVector<int, 8> NewMask;
10558 for (unsigned i = 0; i != NumElts; ++i) {
10559 int Idx = SVN->getMaskElt(i);
10560 if (Idx >= (int)NumElts) Idx -= NumElts;
10561 NewMask.push_back(Idx);
10563 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10567 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10568 if (N0.getOpcode() == ISD::UNDEF) {
10569 SmallVector<int, 8> NewMask;
10570 for (unsigned i = 0; i != NumElts; ++i) {
10571 int Idx = SVN->getMaskElt(i);
10573 if (Idx >= (int)NumElts)
10576 Idx = -1; // remove reference to lhs
10578 NewMask.push_back(Idx);
10580 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10584 // Remove references to rhs if it is undef
10585 if (N1.getOpcode() == ISD::UNDEF) {
10586 bool Changed = false;
10587 SmallVector<int, 8> NewMask;
10588 for (unsigned i = 0; i != NumElts; ++i) {
10589 int Idx = SVN->getMaskElt(i);
10590 if (Idx >= (int)NumElts) {
10594 NewMask.push_back(Idx);
10597 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10600 // If it is a splat, check if the argument vector is another splat or a
10601 // build_vector with all scalar elements the same.
10602 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10603 SDNode *V = N0.getNode();
10605 // If this is a bit convert that changes the element type of the vector but
10606 // not the number of vector elements, look through it. Be careful not to
10607 // look though conversions that change things like v4f32 to v2f64.
10608 if (V->getOpcode() == ISD::BITCAST) {
10609 SDValue ConvInput = V->getOperand(0);
10610 if (ConvInput.getValueType().isVector() &&
10611 ConvInput.getValueType().getVectorNumElements() == NumElts)
10612 V = ConvInput.getNode();
10615 if (V->getOpcode() == ISD::BUILD_VECTOR) {
10616 assert(V->getNumOperands() == NumElts &&
10617 "BUILD_VECTOR has wrong number of operands");
10619 bool AllSame = true;
10620 for (unsigned i = 0; i != NumElts; ++i) {
10621 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10622 Base = V->getOperand(i);
10626 // Splat of <u, u, u, u>, return <u, u, u, u>
10627 if (!Base.getNode())
10629 for (unsigned i = 0; i != NumElts; ++i) {
10630 if (V->getOperand(i) != Base) {
10635 // Splat of <x, x, x, x>, return <x, x, x, x>
10641 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10642 Level < AfterLegalizeVectorOps &&
10643 (N1.getOpcode() == ISD::UNDEF ||
10644 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10645 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10646 SDValue V = partitionShuffleOfConcats(N, DAG);
10652 // If this shuffle node is simply a swizzle of another shuffle node,
10653 // and it reverses the swizzle of the previous shuffle then we can
10654 // optimize shuffle(shuffle(x, undef), undef) -> x.
10655 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10656 N1.getOpcode() == ISD::UNDEF) {
10658 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10660 // Shuffle nodes can only reverse shuffles with a single non-undef value.
10661 if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10664 // The incoming shuffle must be of the same type as the result of the
10665 // current shuffle.
10666 assert(OtherSV->getOperand(0).getValueType() == VT &&
10667 "Shuffle types don't match");
10669 for (unsigned i = 0; i != NumElts; ++i) {
10670 int Idx = SVN->getMaskElt(i);
10671 assert(Idx < (int)NumElts && "Index references undef operand");
10672 // Next, this index comes from the first value, which is the incoming
10673 // shuffle. Adopt the incoming index.
10675 Idx = OtherSV->getMaskElt(Idx);
10677 // The combined shuffle must map each index to itself.
10678 if (Idx >= 0 && (unsigned)Idx != i)
10682 return OtherSV->getOperand(0);
10688 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10689 SDValue N0 = N->getOperand(0);
10690 SDValue N2 = N->getOperand(2);
10692 // If the input vector is a concatenation, and the insert replaces
10693 // one of the halves, we can optimize into a single concat_vectors.
10694 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10695 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10696 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10697 EVT VT = N->getValueType(0);
10699 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10700 // (concat_vectors Z, Y)
10702 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10703 N->getOperand(1), N0.getOperand(1));
10705 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10706 // (concat_vectors X, Z)
10707 if (InsIdx == VT.getVectorNumElements()/2)
10708 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10709 N0.getOperand(0), N->getOperand(1));
10715 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10716 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10717 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10718 /// vector_shuffle V, Zero, <0, 4, 2, 4>
10719 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10720 EVT VT = N->getValueType(0);
10722 SDValue LHS = N->getOperand(0);
10723 SDValue RHS = N->getOperand(1);
10724 if (N->getOpcode() == ISD::AND) {
10725 if (RHS.getOpcode() == ISD::BITCAST)
10726 RHS = RHS.getOperand(0);
10727 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10728 SmallVector<int, 8> Indices;
10729 unsigned NumElts = RHS.getNumOperands();
10730 for (unsigned i = 0; i != NumElts; ++i) {
10731 SDValue Elt = RHS.getOperand(i);
10732 if (!isa<ConstantSDNode>(Elt))
10735 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10736 Indices.push_back(i);
10737 else if (cast<ConstantSDNode>(Elt)->isNullValue())
10738 Indices.push_back(NumElts);
10743 // Let's see if the target supports this vector_shuffle.
10744 EVT RVT = RHS.getValueType();
10745 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10748 // Return the new VECTOR_SHUFFLE node.
10749 EVT EltVT = RVT.getVectorElementType();
10750 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10751 DAG.getConstant(0, EltVT));
10752 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
10753 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10754 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10755 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10762 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10763 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10764 assert(N->getValueType(0).isVector() &&
10765 "SimplifyVBinOp only works on vectors!");
10767 SDValue LHS = N->getOperand(0);
10768 SDValue RHS = N->getOperand(1);
10769 SDValue Shuffle = XformToShuffleWithZero(N);
10770 if (Shuffle.getNode()) return Shuffle;
10772 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10774 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10775 RHS.getOpcode() == ISD::BUILD_VECTOR) {
10776 // Check if both vectors are constants. If not bail out.
10777 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10778 cast<BuildVectorSDNode>(RHS)->isConstant()))
10781 SmallVector<SDValue, 8> Ops;
10782 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10783 SDValue LHSOp = LHS.getOperand(i);
10784 SDValue RHSOp = RHS.getOperand(i);
10786 // Can't fold divide by zero.
10787 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10788 N->getOpcode() == ISD::FDIV) {
10789 if ((RHSOp.getOpcode() == ISD::Constant &&
10790 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10791 (RHSOp.getOpcode() == ISD::ConstantFP &&
10792 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10796 EVT VT = LHSOp.getValueType();
10797 EVT RVT = RHSOp.getValueType();
10799 // Integer BUILD_VECTOR operands may have types larger than the element
10800 // size (e.g., when the element type is not legal). Prior to type
10801 // legalization, the types may not match between the two BUILD_VECTORS.
10802 // Truncate one of the operands to make them match.
10803 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10804 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10806 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10810 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10812 if (FoldOp.getOpcode() != ISD::UNDEF &&
10813 FoldOp.getOpcode() != ISD::Constant &&
10814 FoldOp.getOpcode() != ISD::ConstantFP)
10816 Ops.push_back(FoldOp);
10817 AddToWorkList(FoldOp.getNode());
10820 if (Ops.size() == LHS.getNumOperands())
10821 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
10824 // Type legalization might introduce new shuffles in the DAG.
10825 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
10826 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
10827 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
10828 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
10829 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
10830 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
10831 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
10832 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
10834 if (SVN0->getMask().equals(SVN1->getMask())) {
10835 EVT VT = N->getValueType(0);
10836 SDValue UndefVector = LHS.getOperand(1);
10837 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
10838 LHS.getOperand(0), RHS.getOperand(0));
10839 AddUsersToWorkList(N);
10840 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
10841 &SVN0->getMask()[0]);
10848 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10849 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10850 assert(N->getValueType(0).isVector() &&
10851 "SimplifyVUnaryOp only works on vectors!");
10853 SDValue N0 = N->getOperand(0);
10855 if (N0.getOpcode() != ISD::BUILD_VECTOR)
10858 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10859 SmallVector<SDValue, 8> Ops;
10860 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10861 SDValue Op = N0.getOperand(i);
10862 if (Op.getOpcode() != ISD::UNDEF &&
10863 Op.getOpcode() != ISD::ConstantFP)
10865 EVT EltVT = Op.getValueType();
10866 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
10867 if (FoldOp.getOpcode() != ISD::UNDEF &&
10868 FoldOp.getOpcode() != ISD::ConstantFP)
10870 Ops.push_back(FoldOp);
10871 AddToWorkList(FoldOp.getNode());
10874 if (Ops.size() != N0.getNumOperands())
10877 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
10880 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10881 SDValue N1, SDValue N2){
10882 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10884 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
10885 cast<CondCodeSDNode>(N0.getOperand(2))->get());
10887 // If we got a simplified select_cc node back from SimplifySelectCC, then
10888 // break it down into a new SETCC node, and a new SELECT node, and then return
10889 // the SELECT node, since we were called with a SELECT node.
10890 if (SCC.getNode()) {
10891 // Check to see if we got a select_cc back (to turn into setcc/select).
10892 // Otherwise, just return whatever node we got back, like fabs.
10893 if (SCC.getOpcode() == ISD::SELECT_CC) {
10894 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
10896 SCC.getOperand(0), SCC.getOperand(1),
10897 SCC.getOperand(4));
10898 AddToWorkList(SETCC.getNode());
10899 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10900 SCC.getOperand(2), SCC.getOperand(3), SETCC);
10908 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10909 /// are the two values being selected between, see if we can simplify the
10910 /// select. Callers of this should assume that TheSelect is deleted if this
10911 /// returns true. As such, they should return the appropriate thing (e.g. the
10912 /// node) back to the top-level of the DAG combiner loop to avoid it being
10914 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
10917 // Cannot simplify select with vector condition
10918 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10920 // If this is a select from two identical things, try to pull the operation
10921 // through the select.
10922 if (LHS.getOpcode() != RHS.getOpcode() ||
10923 !LHS.hasOneUse() || !RHS.hasOneUse())
10926 // If this is a load and the token chain is identical, replace the select
10927 // of two loads with a load through a select of the address to load from.
10928 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10929 // constants have been dropped into the constant pool.
10930 if (LHS.getOpcode() == ISD::LOAD) {
10931 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10932 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
10934 // Token chains must be identical.
10935 if (LHS.getOperand(0) != RHS.getOperand(0) ||
10936 // Do not let this transformation reduce the number of volatile loads.
10937 LLD->isVolatile() || RLD->isVolatile() ||
10938 // If this is an EXTLOAD, the VT's must match.
10939 LLD->getMemoryVT() != RLD->getMemoryVT() ||
10940 // If this is an EXTLOAD, the kind of extension must match.
10941 (LLD->getExtensionType() != RLD->getExtensionType() &&
10942 // The only exception is if one of the extensions is anyext.
10943 LLD->getExtensionType() != ISD::EXTLOAD &&
10944 RLD->getExtensionType() != ISD::EXTLOAD) ||
10945 // FIXME: this discards src value information. This is
10946 // over-conservative. It would be beneficial to be able to remember
10947 // both potential memory locations. Since we are discarding
10948 // src value info, don't do the transformation if the memory
10949 // locations are not in the default address space.
10950 LLD->getPointerInfo().getAddrSpace() != 0 ||
10951 RLD->getPointerInfo().getAddrSpace() != 0 ||
10952 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10953 LLD->getBasePtr().getValueType()))
10956 // Check that the select condition doesn't reach either load. If so,
10957 // folding this will induce a cycle into the DAG. If not, this is safe to
10958 // xform, so create a select of the addresses.
10960 if (TheSelect->getOpcode() == ISD::SELECT) {
10961 SDNode *CondNode = TheSelect->getOperand(0).getNode();
10962 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10963 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10965 // The loads must not depend on one another.
10966 if (LLD->isPredecessorOf(RLD) ||
10967 RLD->isPredecessorOf(LLD))
10969 Addr = DAG.getSelect(SDLoc(TheSelect),
10970 LLD->getBasePtr().getValueType(),
10971 TheSelect->getOperand(0), LLD->getBasePtr(),
10972 RLD->getBasePtr());
10973 } else { // Otherwise SELECT_CC
10974 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10975 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10977 if ((LLD->hasAnyUseOfValue(1) &&
10978 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
10979 (RLD->hasAnyUseOfValue(1) &&
10980 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
10983 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
10984 LLD->getBasePtr().getValueType(),
10985 TheSelect->getOperand(0),
10986 TheSelect->getOperand(1),
10987 LLD->getBasePtr(), RLD->getBasePtr(),
10988 TheSelect->getOperand(4));
10992 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10993 Load = DAG.getLoad(TheSelect->getValueType(0),
10995 // FIXME: Discards pointer and TBAA info.
10996 LLD->getChain(), Addr, MachinePointerInfo(),
10997 LLD->isVolatile(), LLD->isNonTemporal(),
10998 LLD->isInvariant(), LLD->getAlignment());
11000 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11001 RLD->getExtensionType() : LLD->getExtensionType(),
11003 TheSelect->getValueType(0),
11004 // FIXME: Discards pointer and TBAA info.
11005 LLD->getChain(), Addr, MachinePointerInfo(),
11006 LLD->getMemoryVT(), LLD->isVolatile(),
11007 LLD->isNonTemporal(), LLD->getAlignment());
11010 // Users of the select now use the result of the load.
11011 CombineTo(TheSelect, Load);
11013 // Users of the old loads now use the new load's chain. We know the
11014 // old-load value is dead now.
11015 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11016 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11023 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
11024 /// where 'cond' is the comparison specified by CC.
11025 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11026 SDValue N2, SDValue N3,
11027 ISD::CondCode CC, bool NotExtCompare) {
11028 // (x ? y : y) -> y.
11029 if (N2 == N3) return N2;
11031 EVT VT = N2.getValueType();
11032 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11033 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11034 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11036 // Determine if the condition we're dealing with is constant
11037 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11038 N0, N1, CC, DL, false);
11039 if (SCC.getNode()) AddToWorkList(SCC.getNode());
11040 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11042 // fold select_cc true, x, y -> x
11043 if (SCCC && !SCCC->isNullValue())
11045 // fold select_cc false, x, y -> y
11046 if (SCCC && SCCC->isNullValue())
11049 // Check to see if we can simplify the select into an fabs node
11050 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11051 // Allow either -0.0 or 0.0
11052 if (CFP->getValueAPF().isZero()) {
11053 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11054 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11055 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11056 N2 == N3.getOperand(0))
11057 return DAG.getNode(ISD::FABS, DL, VT, N0);
11059 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11060 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11061 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11062 N2.getOperand(0) == N3)
11063 return DAG.getNode(ISD::FABS, DL, VT, N3);
11067 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11068 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11069 // in it. This is a win when the constant is not otherwise available because
11070 // it replaces two constant pool loads with one. We only do this if the FP
11071 // type is known to be legal, because if it isn't, then we are before legalize
11072 // types an we want the other legalization to happen first (e.g. to avoid
11073 // messing with soft float) and if the ConstantFP is not legal, because if
11074 // it is legal, we may not need to store the FP constant in a constant pool.
11075 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11076 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11077 if (TLI.isTypeLegal(N2.getValueType()) &&
11078 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11079 TargetLowering::Legal &&
11080 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11081 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11082 // If both constants have multiple uses, then we won't need to do an
11083 // extra load, they are likely around in registers for other users.
11084 (TV->hasOneUse() || FV->hasOneUse())) {
11085 Constant *Elts[] = {
11086 const_cast<ConstantFP*>(FV->getConstantFPValue()),
11087 const_cast<ConstantFP*>(TV->getConstantFPValue())
11089 Type *FPTy = Elts[0]->getType();
11090 const DataLayout &TD = *TLI.getDataLayout();
11092 // Create a ConstantArray of the two constants.
11093 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11094 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11095 TD.getPrefTypeAlignment(FPTy));
11096 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11098 // Get the offsets to the 0 and 1 element of the array so that we can
11099 // select between them.
11100 SDValue Zero = DAG.getIntPtrConstant(0);
11101 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11102 SDValue One = DAG.getIntPtrConstant(EltSize);
11104 SDValue Cond = DAG.getSetCC(DL,
11105 getSetCCResultType(N0.getValueType()),
11107 AddToWorkList(Cond.getNode());
11108 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11110 AddToWorkList(CstOffset.getNode());
11111 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11113 AddToWorkList(CPIdx.getNode());
11114 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11115 MachinePointerInfo::getConstantPool(), false,
11116 false, false, Alignment);
11121 // Check to see if we can perform the "gzip trick", transforming
11122 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11123 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11124 (N1C->isNullValue() || // (a < 0) ? b : 0
11125 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
11126 EVT XType = N0.getValueType();
11127 EVT AType = N2.getValueType();
11128 if (XType.bitsGE(AType)) {
11129 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11130 // single-bit constant.
11131 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11132 unsigned ShCtV = N2C->getAPIntValue().logBase2();
11133 ShCtV = XType.getSizeInBits()-ShCtV-1;
11134 SDValue ShCt = DAG.getConstant(ShCtV,
11135 getShiftAmountTy(N0.getValueType()));
11136 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11138 AddToWorkList(Shift.getNode());
11140 if (XType.bitsGT(AType)) {
11141 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11142 AddToWorkList(Shift.getNode());
11145 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11148 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11150 DAG.getConstant(XType.getSizeInBits()-1,
11151 getShiftAmountTy(N0.getValueType())));
11152 AddToWorkList(Shift.getNode());
11154 if (XType.bitsGT(AType)) {
11155 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11156 AddToWorkList(Shift.getNode());
11159 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11163 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11164 // where y is has a single bit set.
11165 // A plaintext description would be, we can turn the SELECT_CC into an AND
11166 // when the condition can be materialized as an all-ones register. Any
11167 // single bit-test can be materialized as an all-ones register with
11168 // shift-left and shift-right-arith.
11169 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11170 N0->getValueType(0) == VT &&
11171 N1C && N1C->isNullValue() &&
11172 N2C && N2C->isNullValue()) {
11173 SDValue AndLHS = N0->getOperand(0);
11174 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11175 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11176 // Shift the tested bit over the sign bit.
11177 APInt AndMask = ConstAndRHS->getAPIntValue();
11179 DAG.getConstant(AndMask.countLeadingZeros(),
11180 getShiftAmountTy(AndLHS.getValueType()));
11181 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11183 // Now arithmetic right shift it all the way over, so the result is either
11184 // all-ones, or zero.
11186 DAG.getConstant(AndMask.getBitWidth()-1,
11187 getShiftAmountTy(Shl.getValueType()));
11188 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11190 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11194 // fold select C, 16, 0 -> shl C, 4
11195 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11196 TLI.getBooleanContents(N0.getValueType().isVector()) ==
11197 TargetLowering::ZeroOrOneBooleanContent) {
11199 // If the caller doesn't want us to simplify this into a zext of a compare,
11201 if (NotExtCompare && N2C->getAPIntValue() == 1)
11204 // Get a SetCC of the condition
11205 // NOTE: Don't create a SETCC if it's not legal on this target.
11206 if (!LegalOperations ||
11207 TLI.isOperationLegal(ISD::SETCC,
11208 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11210 // cast from setcc result type to select result type
11212 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11214 if (N2.getValueType().bitsLT(SCC.getValueType()))
11215 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11216 N2.getValueType());
11218 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11219 N2.getValueType(), SCC);
11221 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11222 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11223 N2.getValueType(), SCC);
11226 AddToWorkList(SCC.getNode());
11227 AddToWorkList(Temp.getNode());
11229 if (N2C->getAPIntValue() == 1)
11232 // shl setcc result by log2 n2c
11233 return DAG.getNode(
11234 ISD::SHL, DL, N2.getValueType(), Temp,
11235 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11236 getShiftAmountTy(Temp.getValueType())));
11240 // Check to see if this is the equivalent of setcc
11241 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11242 // otherwise, go ahead with the folds.
11243 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11244 EVT XType = N0.getValueType();
11245 if (!LegalOperations ||
11246 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11247 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11248 if (Res.getValueType() != VT)
11249 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11253 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11254 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11255 (!LegalOperations ||
11256 TLI.isOperationLegal(ISD::CTLZ, XType))) {
11257 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11258 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11259 DAG.getConstant(Log2_32(XType.getSizeInBits()),
11260 getShiftAmountTy(Ctlz.getValueType())));
11262 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11263 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11264 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11265 XType, DAG.getConstant(0, XType), N0);
11266 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11267 return DAG.getNode(ISD::SRL, DL, XType,
11268 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11269 DAG.getConstant(XType.getSizeInBits()-1,
11270 getShiftAmountTy(XType)));
11272 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11273 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11274 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11275 DAG.getConstant(XType.getSizeInBits()-1,
11276 getShiftAmountTy(N0.getValueType())));
11277 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11281 // Check to see if this is an integer abs.
11282 // select_cc setg[te] X, 0, X, -X ->
11283 // select_cc setgt X, -1, X, -X ->
11284 // select_cc setl[te] X, 0, -X, X ->
11285 // select_cc setlt X, 1, -X, X ->
11286 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11288 ConstantSDNode *SubC = nullptr;
11289 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11290 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11291 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11292 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11293 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11294 (N1C->isOne() && CC == ISD::SETLT)) &&
11295 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11296 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11298 EVT XType = N0.getValueType();
11299 if (SubC && SubC->isNullValue() && XType.isInteger()) {
11300 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11302 DAG.getConstant(XType.getSizeInBits()-1,
11303 getShiftAmountTy(N0.getValueType())));
11304 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11306 AddToWorkList(Shift.getNode());
11307 AddToWorkList(Add.getNode());
11308 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11315 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11316 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11317 SDValue N1, ISD::CondCode Cond,
11318 SDLoc DL, bool foldBooleans) {
11319 TargetLowering::DAGCombinerInfo
11320 DagCombineInfo(DAG, Level, false, this);
11321 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11324 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11325 /// return a DAG expression to select that will generate the same value by
11326 /// multiplying by a magic number. See:
11327 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11328 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11329 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11333 // Avoid division by zero.
11334 if (!C->getAPIntValue())
11337 std::vector<SDNode*> Built;
11339 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11341 for (SDNode *N : Built)
11346 /// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant,
11347 /// return a DAG expression to select that will generate the same value by
11348 /// multiplying by a magic number. See:
11349 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11350 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11351 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11355 // Avoid division by zero.
11356 if (!C->getAPIntValue())
11359 std::vector<SDNode*> Built;
11361 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11363 for (SDNode *N : Built)
11368 /// FindBaseOffset - Return true if base is a frame index, which is known not
11369 // to alias with anything but itself. Provides base object and offset as
11371 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11372 const GlobalValue *&GV, const void *&CV) {
11373 // Assume it is a primitive operation.
11374 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11376 // If it's an adding a simple constant then integrate the offset.
11377 if (Base.getOpcode() == ISD::ADD) {
11378 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11379 Base = Base.getOperand(0);
11380 Offset += C->getZExtValue();
11384 // Return the underlying GlobalValue, and update the Offset. Return false
11385 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11386 // by multiple nodes with different offsets.
11387 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11388 GV = G->getGlobal();
11389 Offset += G->getOffset();
11393 // Return the underlying Constant value, and update the Offset. Return false
11394 // for ConstantSDNodes since the same constant pool entry may be represented
11395 // by multiple nodes with different offsets.
11396 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11397 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11398 : (const void *)C->getConstVal();
11399 Offset += C->getOffset();
11402 // If it's any of the following then it can't alias with anything but itself.
11403 return isa<FrameIndexSDNode>(Base);
11406 /// isAlias - Return true if there is any possibility that the two addresses
11408 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11409 // If they are the same then they must be aliases.
11410 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11412 // If they are both volatile then they cannot be reordered.
11413 if (Op0->isVolatile() && Op1->isVolatile()) return true;
11415 // Gather base node and offset information.
11416 SDValue Base1, Base2;
11417 int64_t Offset1, Offset2;
11418 const GlobalValue *GV1, *GV2;
11419 const void *CV1, *CV2;
11420 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11421 Base1, Offset1, GV1, CV1);
11422 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11423 Base2, Offset2, GV2, CV2);
11425 // If they have a same base address then check to see if they overlap.
11426 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11427 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11428 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11430 // It is possible for different frame indices to alias each other, mostly
11431 // when tail call optimization reuses return address slots for arguments.
11432 // To catch this case, look up the actual index of frame indices to compute
11433 // the real alias relationship.
11434 if (isFrameIndex1 && isFrameIndex2) {
11435 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11436 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11437 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11438 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11439 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11442 // Otherwise, if we know what the bases are, and they aren't identical, then
11443 // we know they cannot alias.
11444 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11447 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11448 // compared to the size and offset of the access, we may be able to prove they
11449 // do not alias. This check is conservative for now to catch cases created by
11450 // splitting vector types.
11451 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11452 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11453 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11454 Op1->getMemoryVT().getSizeInBits() >> 3) &&
11455 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11456 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11457 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11459 // There is no overlap between these relatively aligned accesses of similar
11460 // size, return no alias.
11461 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11462 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11466 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11467 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11469 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11470 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11474 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11475 // Use alias analysis information.
11476 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11477 Op1->getSrcValueOffset());
11478 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11479 Op0->getSrcValueOffset() - MinOffset;
11480 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11481 Op1->getSrcValueOffset() - MinOffset;
11482 AliasAnalysis::AliasResult AAResult =
11483 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11485 UseTBAA ? Op0->getTBAAInfo() : nullptr),
11486 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11488 UseTBAA ? Op1->getTBAAInfo() : nullptr));
11489 if (AAResult == AliasAnalysis::NoAlias)
11493 // Otherwise we have to assume they alias.
11497 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11498 /// looking for aliasing nodes and adding them to the Aliases vector.
11499 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11500 SmallVectorImpl<SDValue> &Aliases) {
11501 SmallVector<SDValue, 8> Chains; // List of chains to visit.
11502 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
11504 // Get alias information for node.
11505 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11508 Chains.push_back(OriginalChain);
11509 unsigned Depth = 0;
11511 // Look at each chain and determine if it is an alias. If so, add it to the
11512 // aliases list. If not, then continue up the chain looking for the next
11514 while (!Chains.empty()) {
11515 SDValue Chain = Chains.back();
11518 // For TokenFactor nodes, look at each operand and only continue up the
11519 // chain until we find two aliases. If we've seen two aliases, assume we'll
11520 // find more and revert to original chain since the xform is unlikely to be
11523 // FIXME: The depth check could be made to return the last non-aliasing
11524 // chain we found before we hit a tokenfactor rather than the original
11526 if (Depth > 6 || Aliases.size() == 2) {
11528 Aliases.push_back(OriginalChain);
11532 // Don't bother if we've been before.
11533 if (!Visited.insert(Chain.getNode()))
11536 switch (Chain.getOpcode()) {
11537 case ISD::EntryToken:
11538 // Entry token is ideal chain operand, but handled in FindBetterChain.
11543 // Get alias information for Chain.
11544 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11545 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11547 // If chain is alias then stop here.
11548 if (!(IsLoad && IsOpLoad) &&
11549 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11550 Aliases.push_back(Chain);
11552 // Look further up the chain.
11553 Chains.push_back(Chain.getOperand(0));
11559 case ISD::TokenFactor:
11560 // We have to check each of the operands of the token factor for "small"
11561 // token factors, so we queue them up. Adding the operands to the queue
11562 // (stack) in reverse order maintains the original order and increases the
11563 // likelihood that getNode will find a matching token factor (CSE.)
11564 if (Chain.getNumOperands() > 16) {
11565 Aliases.push_back(Chain);
11568 for (unsigned n = Chain.getNumOperands(); n;)
11569 Chains.push_back(Chain.getOperand(--n));
11574 // For all other instructions we will just have to take what we can get.
11575 Aliases.push_back(Chain);
11580 // We need to be careful here to also search for aliases through the
11581 // value operand of a store, etc. Consider the following situation:
11583 // L1 = load Token1, %52
11584 // S1 = store Token1, L1, %51
11585 // L2 = load Token1, %52+8
11586 // S2 = store Token1, L2, %51+8
11587 // Token2 = Token(S1, S2)
11588 // L3 = load Token2, %53
11589 // S3 = store Token2, L3, %52
11590 // L4 = load Token2, %53+8
11591 // S4 = store Token2, L4, %52+8
11592 // If we search for aliases of S3 (which loads address %52), and we look
11593 // only through the chain, then we'll miss the trivial dependence on L1
11594 // (which also loads from %52). We then might change all loads and
11595 // stores to use Token1 as their chain operand, which could result in
11596 // copying %53 into %52 before copying %52 into %51 (which should
11599 // The problem is, however, that searching for such data dependencies
11600 // can become expensive, and the cost is not directly related to the
11601 // chain depth. Instead, we'll rule out such configurations here by
11602 // insisting that we've visited all chain users (except for users
11603 // of the original chain, which is not necessary). When doing this,
11604 // we need to look through nodes we don't care about (otherwise, things
11605 // like register copies will interfere with trivial cases).
11607 SmallVector<const SDNode *, 16> Worklist;
11608 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11609 IE = Visited.end(); I != IE; ++I)
11610 if (*I != OriginalChain.getNode())
11611 Worklist.push_back(*I);
11613 while (!Worklist.empty()) {
11614 const SDNode *M = Worklist.pop_back_val();
11616 // We have already visited M, and want to make sure we've visited any uses
11617 // of M that we care about. For uses that we've not visisted, and don't
11618 // care about, queue them to the worklist.
11620 for (SDNode::use_iterator UI = M->use_begin(),
11621 UIE = M->use_end(); UI != UIE; ++UI)
11622 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11623 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11624 // We've not visited this use, and we care about it (it could have an
11625 // ordering dependency with the original node).
11627 Aliases.push_back(OriginalChain);
11631 // We've not visited this use, but we don't care about it. Mark it as
11632 // visited and enqueue it to the worklist.
11633 Worklist.push_back(*UI);
11638 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11639 /// for a better chain (aliasing node.)
11640 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11641 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
11643 // Accumulate all the aliases to this node.
11644 GatherAllAliases(N, OldChain, Aliases);
11646 // If no operands then chain to entry token.
11647 if (Aliases.size() == 0)
11648 return DAG.getEntryNode();
11650 // If a single operand then chain to it. We don't need to revisit it.
11651 if (Aliases.size() == 1)
11654 // Construct a custom tailored token factor.
11655 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
11658 // SelectionDAG::Combine - This is the entry point for the file.
11660 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11661 CodeGenOpt::Level OptLevel) {
11662 /// run - This is the main entry point to this class.
11664 DAGCombiner(*this, AA, OptLevel).Run(Level);