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/SetVector.h"
21 #include "llvm/ADT/SmallBitVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetLowering.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
43 #define DEBUG_TYPE "dagcombine"
45 STATISTIC(NodesCombined , "Number of dag nodes combined");
46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
48 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
49 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
50 STATISTIC(SlicedLoads, "Number of load sliced");
54 CombinerAA("combiner-alias-analysis", cl::Hidden,
55 cl::desc("Enable DAG combiner alias-analysis heuristics"));
58 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59 cl::desc("Enable DAG combiner's use of IR alias analysis"));
62 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63 cl::desc("Enable DAG combiner's use of TBAA"));
66 static cl::opt<std::string>
67 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68 cl::desc("Only use DAG-combiner alias analysis in this"
72 /// Hidden option to stress test load slicing, i.e., when this option
73 /// is enabled, load slicing bypasses most of its profitability guards.
75 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76 cl::desc("Bypass the profitability model of load "
81 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82 cl::desc("DAG combiner may split indexing from loads"));
84 //------------------------------ DAGCombiner ---------------------------------//
88 const TargetLowering &TLI;
90 CodeGenOpt::Level OptLevel;
95 /// \brief Worklist of all of the nodes that need to be simplified.
97 /// This must behave as a stack -- new nodes to process are pushed onto the
98 /// back and when processing we pop off of the back.
100 /// The worklist will not contain duplicates but may contain null entries
101 /// due to nodes being deleted from the underlying DAG.
102 SmallVector<SDNode *, 64> Worklist;
104 /// \brief Mapping from an SDNode to its position on the worklist.
106 /// This is used to find and remove nodes from the worklist (by nulling
107 /// them) when they are deleted from the underlying DAG. It relies on
108 /// stable indices of nodes within the worklist.
109 DenseMap<SDNode *, unsigned> WorklistMap;
111 /// \brief Set of nodes which have been combined (at least once).
113 /// This is used to allow us to reliably add any operands of a DAG node
114 /// which have not yet been combined to the worklist.
115 SmallPtrSet<SDNode *, 64> CombinedNodes;
117 // AA - Used for DAG load/store alias analysis.
120 /// When an instruction is simplified, add all users of the instruction to
121 /// the work lists because they might get more simplified now.
122 void AddUsersToWorklist(SDNode *N) {
123 for (SDNode *Node : N->uses())
127 /// Call the node-specific routine that folds each particular type of node.
128 SDValue visit(SDNode *N);
131 /// Add to the worklist making sure its instance is at the back (next to be
133 void AddToWorklist(SDNode *N) {
134 // Skip handle nodes as they can't usefully be combined and confuse the
135 // zero-use deletion strategy.
136 if (N->getOpcode() == ISD::HANDLENODE)
139 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140 Worklist.push_back(N);
143 /// Remove all instances of N from the worklist.
144 void removeFromWorklist(SDNode *N) {
145 CombinedNodes.erase(N);
147 auto It = WorklistMap.find(N);
148 if (It == WorklistMap.end())
149 return; // Not in the worklist.
151 // Null out the entry rather than erasing it to avoid a linear operation.
152 Worklist[It->second] = nullptr;
153 WorklistMap.erase(It);
156 void deleteAndRecombine(SDNode *N);
157 bool recursivelyDeleteUnusedNodes(SDNode *N);
159 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
162 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
163 return CombineTo(N, &Res, 1, AddTo);
166 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
168 SDValue To[] = { Res0, Res1 };
169 return CombineTo(N, To, 2, AddTo);
172 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
176 /// Check the specified integer node value to see if it can be simplified or
177 /// if things it uses can be simplified by bit propagation.
178 /// If so, return true.
179 bool SimplifyDemandedBits(SDValue Op) {
180 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181 APInt Demanded = APInt::getAllOnesValue(BitWidth);
182 return SimplifyDemandedBits(Op, Demanded);
185 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
187 bool CombineToPreIndexedLoadStore(SDNode *N);
188 bool CombineToPostIndexedLoadStore(SDNode *N);
189 SDValue SplitIndexingFromLoad(LoadSDNode *LD);
190 bool SliceUpLoad(SDNode *N);
192 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
195 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
196 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
197 /// \param EltNo index of the vector element to load.
198 /// \param OriginalLoad load that EVE came from to be replaced.
199 /// \returns EVE on success SDValue() on failure.
200 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
201 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
202 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
203 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
204 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
205 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
206 SDValue PromoteIntBinOp(SDValue Op);
207 SDValue PromoteIntShiftOp(SDValue Op);
208 SDValue PromoteExtend(SDValue Op);
209 bool PromoteLoad(SDValue Op);
211 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
212 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
213 ISD::NodeType ExtType);
215 /// Call the node-specific routine that knows how to fold each
216 /// particular type of node. If that doesn't do anything, try the
217 /// target-specific DAG combines.
218 SDValue combine(SDNode *N);
220 // Visitation implementation - Implement dag node combining for different
221 // node types. The semantics are as follows:
223 // SDValue.getNode() == 0 - No change was made
224 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
225 // otherwise - N should be replaced by the returned Operand.
227 SDValue visitTokenFactor(SDNode *N);
228 SDValue visitMERGE_VALUES(SDNode *N);
229 SDValue visitADD(SDNode *N);
230 SDValue visitSUB(SDNode *N);
231 SDValue visitADDC(SDNode *N);
232 SDValue visitSUBC(SDNode *N);
233 SDValue visitADDE(SDNode *N);
234 SDValue visitSUBE(SDNode *N);
235 SDValue visitMUL(SDNode *N);
236 SDValue visitSDIV(SDNode *N);
237 SDValue visitUDIV(SDNode *N);
238 SDValue visitSREM(SDNode *N);
239 SDValue visitUREM(SDNode *N);
240 SDValue visitMULHU(SDNode *N);
241 SDValue visitMULHS(SDNode *N);
242 SDValue visitSMUL_LOHI(SDNode *N);
243 SDValue visitUMUL_LOHI(SDNode *N);
244 SDValue visitSMULO(SDNode *N);
245 SDValue visitUMULO(SDNode *N);
246 SDValue visitSDIVREM(SDNode *N);
247 SDValue visitUDIVREM(SDNode *N);
248 SDValue visitAND(SDNode *N);
249 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
250 SDValue visitOR(SDNode *N);
251 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
252 SDValue visitXOR(SDNode *N);
253 SDValue SimplifyVBinOp(SDNode *N);
254 SDValue SimplifyVUnaryOp(SDNode *N);
255 SDValue visitSHL(SDNode *N);
256 SDValue visitSRA(SDNode *N);
257 SDValue visitSRL(SDNode *N);
258 SDValue visitRotate(SDNode *N);
259 SDValue visitCTLZ(SDNode *N);
260 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
261 SDValue visitCTTZ(SDNode *N);
262 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
263 SDValue visitCTPOP(SDNode *N);
264 SDValue visitSELECT(SDNode *N);
265 SDValue visitVSELECT(SDNode *N);
266 SDValue visitSELECT_CC(SDNode *N);
267 SDValue visitSETCC(SDNode *N);
268 SDValue visitSIGN_EXTEND(SDNode *N);
269 SDValue visitZERO_EXTEND(SDNode *N);
270 SDValue visitANY_EXTEND(SDNode *N);
271 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
272 SDValue visitTRUNCATE(SDNode *N);
273 SDValue visitBITCAST(SDNode *N);
274 SDValue visitBUILD_PAIR(SDNode *N);
275 SDValue visitFADD(SDNode *N);
276 SDValue visitFSUB(SDNode *N);
277 SDValue visitFMUL(SDNode *N);
278 SDValue visitFMA(SDNode *N);
279 SDValue visitFDIV(SDNode *N);
280 SDValue visitFREM(SDNode *N);
281 SDValue visitFSQRT(SDNode *N);
282 SDValue visitFCOPYSIGN(SDNode *N);
283 SDValue visitSINT_TO_FP(SDNode *N);
284 SDValue visitUINT_TO_FP(SDNode *N);
285 SDValue visitFP_TO_SINT(SDNode *N);
286 SDValue visitFP_TO_UINT(SDNode *N);
287 SDValue visitFP_ROUND(SDNode *N);
288 SDValue visitFP_ROUND_INREG(SDNode *N);
289 SDValue visitFP_EXTEND(SDNode *N);
290 SDValue visitFNEG(SDNode *N);
291 SDValue visitFABS(SDNode *N);
292 SDValue visitFCEIL(SDNode *N);
293 SDValue visitFTRUNC(SDNode *N);
294 SDValue visitFFLOOR(SDNode *N);
295 SDValue visitFMINNUM(SDNode *N);
296 SDValue visitFMAXNUM(SDNode *N);
297 SDValue visitBRCOND(SDNode *N);
298 SDValue visitBR_CC(SDNode *N);
299 SDValue visitLOAD(SDNode *N);
300 SDValue visitSTORE(SDNode *N);
301 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
302 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
303 SDValue visitBUILD_VECTOR(SDNode *N);
304 SDValue visitCONCAT_VECTORS(SDNode *N);
305 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
306 SDValue visitVECTOR_SHUFFLE(SDNode *N);
307 SDValue visitSCALAR_TO_VECTOR(SDNode *N);
308 SDValue visitINSERT_SUBVECTOR(SDNode *N);
309 SDValue visitMLOAD(SDNode *N);
310 SDValue visitMSTORE(SDNode *N);
312 SDValue XformToShuffleWithZero(SDNode *N);
313 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
315 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
317 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
318 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
319 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
320 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
321 SDValue N3, ISD::CondCode CC,
322 bool NotExtCompare = false);
323 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
324 SDLoc DL, bool foldBooleans = true);
326 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
328 bool isOneUseSetCC(SDValue N) const;
330 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
332 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
333 SDValue CombineExtLoad(SDNode *N);
334 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
335 SDValue BuildSDIV(SDNode *N);
336 SDValue BuildSDIVPow2(SDNode *N);
337 SDValue BuildUDIV(SDNode *N);
338 SDValue BuildReciprocalEstimate(SDValue Op);
339 SDValue BuildRsqrtEstimate(SDValue Op);
340 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
341 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
342 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
343 bool DemandHighBits = true);
344 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
345 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
346 SDValue InnerPos, SDValue InnerNeg,
347 unsigned PosOpcode, unsigned NegOpcode,
349 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
350 SDValue ReduceLoadWidth(SDNode *N);
351 SDValue ReduceLoadOpStoreWidth(SDNode *N);
352 SDValue TransformFPLoadStorePair(SDNode *N);
353 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
354 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
356 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
358 /// Walk up chain skipping non-aliasing memory nodes,
359 /// looking for aliasing nodes and adding them to the Aliases vector.
360 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
361 SmallVectorImpl<SDValue> &Aliases);
363 /// Return true if there is any possibility that the two addresses overlap.
364 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
366 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
367 /// chain (aliasing node.)
368 SDValue FindBetterChain(SDNode *N, SDValue Chain);
370 /// Holds a pointer to an LSBaseSDNode as well as information on where it
371 /// is located in a sequence of memory operations connected by a chain.
373 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
374 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
375 // Ptr to the mem node.
376 LSBaseSDNode *MemNode;
377 // Offset from the base ptr.
378 int64_t OffsetFromBase;
379 // What is the sequence number of this mem node.
380 // Lowest mem operand in the DAG starts at zero.
381 unsigned SequenceNum;
384 /// This is a helper function for MergeConsecutiveStores. When the source
385 /// elements of the consecutive stores are all constants or all extracted
386 /// vector elements, try to merge them into one larger store.
387 /// \return True if a merged store was created.
388 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
389 EVT MemVT, unsigned NumElem,
390 bool IsConstantSrc, bool UseVector);
392 /// Merge consecutive store operations into a wide store.
393 /// This optimization uses wide integers or vectors when possible.
394 /// \return True if some memory operations were changed.
395 bool MergeConsecutiveStores(StoreSDNode *N);
397 /// \brief Try to transform a truncation where C is a constant:
398 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
400 /// \p N needs to be a truncation and its first operand an AND. Other
401 /// requirements are checked by the function (e.g. that trunc is
402 /// single-use) and if missed an empty SDValue is returned.
403 SDValue distributeTruncateThroughAnd(SDNode *N);
406 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
407 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
408 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
409 auto *F = DAG.getMachineFunction().getFunction();
410 ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) ||
411 F->hasFnAttribute(Attribute::MinSize);
414 /// Runs the dag combiner on all nodes in the work list
415 void Run(CombineLevel AtLevel);
417 SelectionDAG &getDAG() const { return DAG; }
419 /// Returns a type large enough to hold any valid shift amount - before type
420 /// legalization these can be huge.
421 EVT getShiftAmountTy(EVT LHSTy) {
422 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
423 if (LHSTy.isVector())
425 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
426 : TLI.getPointerTy();
429 /// This method returns true if we are running before type legalization or
430 /// if the specified VT is legal.
431 bool isTypeLegal(const EVT &VT) {
432 if (!LegalTypes) return true;
433 return TLI.isTypeLegal(VT);
436 /// Convenience wrapper around TargetLowering::getSetCCResultType
437 EVT getSetCCResultType(EVT VT) const {
438 return TLI.getSetCCResultType(*DAG.getContext(), VT);
445 /// This class is a DAGUpdateListener that removes any deleted
446 /// nodes from the worklist.
447 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
450 explicit WorklistRemover(DAGCombiner &dc)
451 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
453 void NodeDeleted(SDNode *N, SDNode *E) override {
454 DC.removeFromWorklist(N);
459 //===----------------------------------------------------------------------===//
460 // TargetLowering::DAGCombinerInfo implementation
461 //===----------------------------------------------------------------------===//
463 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
464 ((DAGCombiner*)DC)->AddToWorklist(N);
467 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
468 ((DAGCombiner*)DC)->removeFromWorklist(N);
471 SDValue TargetLowering::DAGCombinerInfo::
472 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
473 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
476 SDValue TargetLowering::DAGCombinerInfo::
477 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
478 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
482 SDValue TargetLowering::DAGCombinerInfo::
483 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
484 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
487 void TargetLowering::DAGCombinerInfo::
488 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
489 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
492 //===----------------------------------------------------------------------===//
494 //===----------------------------------------------------------------------===//
496 void DAGCombiner::deleteAndRecombine(SDNode *N) {
497 removeFromWorklist(N);
499 // If the operands of this node are only used by the node, they will now be
500 // dead. Make sure to re-visit them and recursively delete dead nodes.
501 for (const SDValue &Op : N->ops())
502 // For an operand generating multiple values, one of the values may
503 // become dead allowing further simplification (e.g. split index
504 // arithmetic from an indexed load).
505 if (Op->hasOneUse() || Op->getNumValues() > 1)
506 AddToWorklist(Op.getNode());
511 /// Return 1 if we can compute the negated form of the specified expression for
512 /// the same cost as the expression itself, or 2 if we can compute the negated
513 /// form more cheaply than the expression itself.
514 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
515 const TargetLowering &TLI,
516 const TargetOptions *Options,
517 unsigned Depth = 0) {
518 // fneg is removable even if it has multiple uses.
519 if (Op.getOpcode() == ISD::FNEG) return 2;
521 // Don't allow anything with multiple uses.
522 if (!Op.hasOneUse()) return 0;
524 // Don't recurse exponentially.
525 if (Depth > 6) return 0;
527 switch (Op.getOpcode()) {
528 default: return false;
529 case ISD::ConstantFP:
530 // Don't invert constant FP values after legalize. The negated constant
531 // isn't necessarily legal.
532 return LegalOperations ? 0 : 1;
534 // FIXME: determine better conditions for this xform.
535 if (!Options->UnsafeFPMath) return 0;
537 // After operation legalization, it might not be legal to create new FSUBs.
538 if (LegalOperations &&
539 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
542 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
543 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
546 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
547 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
550 // We can't turn -(A-B) into B-A when we honor signed zeros.
551 if (!Options->UnsafeFPMath) return 0;
553 // fold (fneg (fsub A, B)) -> (fsub B, A)
558 if (Options->HonorSignDependentRoundingFPMath()) return 0;
560 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
561 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
565 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
571 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
576 /// If isNegatibleForFree returns true, return the newly negated expression.
577 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
578 bool LegalOperations, unsigned Depth = 0) {
579 const TargetOptions &Options = DAG.getTarget().Options;
580 // fneg is removable even if it has multiple uses.
581 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
583 // Don't allow anything with multiple uses.
584 assert(Op.hasOneUse() && "Unknown reuse!");
586 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
587 switch (Op.getOpcode()) {
588 default: llvm_unreachable("Unknown code");
589 case ISD::ConstantFP: {
590 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
592 return DAG.getConstantFP(V, Op.getValueType());
595 // FIXME: determine better conditions for this xform.
596 assert(Options.UnsafeFPMath);
598 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
599 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
600 DAG.getTargetLoweringInfo(), &Options, Depth+1))
601 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
602 GetNegatedExpression(Op.getOperand(0), DAG,
603 LegalOperations, Depth+1),
605 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
606 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
607 GetNegatedExpression(Op.getOperand(1), DAG,
608 LegalOperations, Depth+1),
611 // We can't turn -(A-B) into B-A when we honor signed zeros.
612 assert(Options.UnsafeFPMath);
614 // fold (fneg (fsub 0, B)) -> B
615 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
616 if (N0CFP->getValueAPF().isZero())
617 return Op.getOperand(1);
619 // fold (fneg (fsub A, B)) -> (fsub B, A)
620 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
621 Op.getOperand(1), Op.getOperand(0));
625 assert(!Options.HonorSignDependentRoundingFPMath());
627 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
628 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
629 DAG.getTargetLoweringInfo(), &Options, Depth+1))
630 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
631 GetNegatedExpression(Op.getOperand(0), DAG,
632 LegalOperations, Depth+1),
635 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
636 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
638 GetNegatedExpression(Op.getOperand(1), DAG,
639 LegalOperations, Depth+1));
643 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
644 GetNegatedExpression(Op.getOperand(0), DAG,
645 LegalOperations, Depth+1));
647 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
648 GetNegatedExpression(Op.getOperand(0), DAG,
649 LegalOperations, Depth+1),
654 // Return true if this node is a setcc, or is a select_cc
655 // that selects between the target values used for true and false, making it
656 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
657 // the appropriate nodes based on the type of node we are checking. This
658 // simplifies life a bit for the callers.
659 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
661 if (N.getOpcode() == ISD::SETCC) {
662 LHS = N.getOperand(0);
663 RHS = N.getOperand(1);
664 CC = N.getOperand(2);
668 if (N.getOpcode() != ISD::SELECT_CC ||
669 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
670 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
673 if (TLI.getBooleanContents(N.getValueType()) ==
674 TargetLowering::UndefinedBooleanContent)
677 LHS = N.getOperand(0);
678 RHS = N.getOperand(1);
679 CC = N.getOperand(4);
683 /// Return true if this is a SetCC-equivalent operation with only one use.
684 /// If this is true, it allows the users to invert the operation for free when
685 /// it is profitable to do so.
686 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
688 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
693 /// Returns true if N is a BUILD_VECTOR node whose
694 /// elements are all the same constant or undefined.
695 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
696 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
701 unsigned SplatBitSize;
703 EVT EltVT = N->getValueType(0).getVectorElementType();
704 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
706 EltVT.getSizeInBits() >= SplatBitSize);
709 // \brief Returns the SDNode if it is a constant BuildVector or constant.
710 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
711 if (isa<ConstantSDNode>(N))
713 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
714 if (BV && BV->isConstant())
719 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
721 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
722 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
725 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
726 BitVector UndefElements;
727 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
729 // BuildVectors can truncate their operands. Ignore that case here.
730 // FIXME: We blindly ignore splats which include undef which is overly
732 if (CN && UndefElements.none() &&
733 CN->getValueType(0) == N.getValueType().getScalarType())
740 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
742 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
743 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
746 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
747 BitVector UndefElements;
748 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
750 if (CN && UndefElements.none())
757 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
758 SDValue N0, SDValue N1) {
759 EVT VT = N0.getValueType();
760 if (N0.getOpcode() == Opc) {
761 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
762 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
763 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
764 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R))
765 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
768 if (N0.hasOneUse()) {
769 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
771 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
772 if (!OpNode.getNode())
774 AddToWorklist(OpNode.getNode());
775 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
780 if (N1.getOpcode() == Opc) {
781 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
782 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
783 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
784 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L))
785 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
788 if (N1.hasOneUse()) {
789 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
791 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
792 if (!OpNode.getNode())
794 AddToWorklist(OpNode.getNode());
795 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
803 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
805 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
807 DEBUG(dbgs() << "\nReplacing.1 ";
809 dbgs() << "\nWith: ";
810 To[0].getNode()->dump(&DAG);
811 dbgs() << " and " << NumTo-1 << " other values\n");
812 for (unsigned i = 0, e = NumTo; i != e; ++i)
813 assert((!To[i].getNode() ||
814 N->getValueType(i) == To[i].getValueType()) &&
815 "Cannot combine value to value of different type!");
817 WorklistRemover DeadNodes(*this);
818 DAG.ReplaceAllUsesWith(N, To);
820 // Push the new nodes and any users onto the worklist
821 for (unsigned i = 0, e = NumTo; i != e; ++i) {
822 if (To[i].getNode()) {
823 AddToWorklist(To[i].getNode());
824 AddUsersToWorklist(To[i].getNode());
829 // Finally, if the node is now dead, remove it from the graph. The node
830 // may not be dead if the replacement process recursively simplified to
831 // something else needing this node.
833 deleteAndRecombine(N);
834 return SDValue(N, 0);
838 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
839 // Replace all uses. If any nodes become isomorphic to other nodes and
840 // are deleted, make sure to remove them from our worklist.
841 WorklistRemover DeadNodes(*this);
842 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
844 // Push the new node and any (possibly new) users onto the worklist.
845 AddToWorklist(TLO.New.getNode());
846 AddUsersToWorklist(TLO.New.getNode());
848 // Finally, if the node is now dead, remove it from the graph. The node
849 // may not be dead if the replacement process recursively simplified to
850 // something else needing this node.
851 if (TLO.Old.getNode()->use_empty())
852 deleteAndRecombine(TLO.Old.getNode());
855 /// Check the specified integer node value to see if it can be simplified or if
856 /// things it uses can be simplified by bit propagation. If so, return true.
857 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
858 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
859 APInt KnownZero, KnownOne;
860 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
864 AddToWorklist(Op.getNode());
866 // Replace the old value with the new one.
868 DEBUG(dbgs() << "\nReplacing.2 ";
869 TLO.Old.getNode()->dump(&DAG);
870 dbgs() << "\nWith: ";
871 TLO.New.getNode()->dump(&DAG);
874 CommitTargetLoweringOpt(TLO);
878 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
880 EVT VT = Load->getValueType(0);
881 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
883 DEBUG(dbgs() << "\nReplacing.9 ";
885 dbgs() << "\nWith: ";
886 Trunc.getNode()->dump(&DAG);
888 WorklistRemover DeadNodes(*this);
889 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
890 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
891 deleteAndRecombine(Load);
892 AddToWorklist(Trunc.getNode());
895 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
898 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
899 EVT MemVT = LD->getMemoryVT();
900 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
901 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
903 : LD->getExtensionType();
905 return DAG.getExtLoad(ExtType, dl, PVT,
906 LD->getChain(), LD->getBasePtr(),
907 MemVT, LD->getMemOperand());
910 unsigned Opc = Op.getOpcode();
913 case ISD::AssertSext:
914 return DAG.getNode(ISD::AssertSext, dl, PVT,
915 SExtPromoteOperand(Op.getOperand(0), PVT),
917 case ISD::AssertZext:
918 return DAG.getNode(ISD::AssertZext, dl, PVT,
919 ZExtPromoteOperand(Op.getOperand(0), PVT),
921 case ISD::Constant: {
923 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
924 return DAG.getNode(ExtOpc, dl, PVT, Op);
928 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
930 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
933 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
934 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
936 EVT OldVT = Op.getValueType();
938 bool Replace = false;
939 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
940 if (!NewOp.getNode())
942 AddToWorklist(NewOp.getNode());
945 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
946 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
947 DAG.getValueType(OldVT));
950 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
951 EVT OldVT = Op.getValueType();
953 bool Replace = false;
954 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
955 if (!NewOp.getNode())
957 AddToWorklist(NewOp.getNode());
960 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
961 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
964 /// Promote the specified integer binary operation if the target indicates it is
965 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
966 /// i32 since i16 instructions are longer.
967 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
968 if (!LegalOperations)
971 EVT VT = Op.getValueType();
972 if (VT.isVector() || !VT.isInteger())
975 // If operation type is 'undesirable', e.g. i16 on x86, consider
977 unsigned Opc = Op.getOpcode();
978 if (TLI.isTypeDesirableForOp(Opc, VT))
982 // Consult target whether it is a good idea to promote this operation and
983 // what's the right type to promote it to.
984 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
985 assert(PVT != VT && "Don't know what type to promote to!");
987 bool Replace0 = false;
988 SDValue N0 = Op.getOperand(0);
989 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
993 bool Replace1 = false;
994 SDValue N1 = Op.getOperand(1);
999 NN1 = PromoteOperand(N1, PVT, Replace1);
1004 AddToWorklist(NN0.getNode());
1006 AddToWorklist(NN1.getNode());
1009 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1011 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1013 DEBUG(dbgs() << "\nPromoting ";
1014 Op.getNode()->dump(&DAG));
1016 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1017 DAG.getNode(Opc, dl, PVT, NN0, NN1));
1022 /// Promote the specified integer shift operation if the target indicates it is
1023 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1024 /// i32 since i16 instructions are longer.
1025 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1026 if (!LegalOperations)
1029 EVT VT = Op.getValueType();
1030 if (VT.isVector() || !VT.isInteger())
1033 // If operation type is 'undesirable', e.g. i16 on x86, consider
1035 unsigned Opc = Op.getOpcode();
1036 if (TLI.isTypeDesirableForOp(Opc, VT))
1040 // Consult target whether it is a good idea to promote this operation and
1041 // what's the right type to promote it to.
1042 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1043 assert(PVT != VT && "Don't know what type to promote to!");
1045 bool Replace = false;
1046 SDValue N0 = Op.getOperand(0);
1047 if (Opc == ISD::SRA)
1048 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1049 else if (Opc == ISD::SRL)
1050 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1052 N0 = PromoteOperand(N0, PVT, Replace);
1056 AddToWorklist(N0.getNode());
1058 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1060 DEBUG(dbgs() << "\nPromoting ";
1061 Op.getNode()->dump(&DAG));
1063 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1064 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1069 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1070 if (!LegalOperations)
1073 EVT VT = Op.getValueType();
1074 if (VT.isVector() || !VT.isInteger())
1077 // If operation type is 'undesirable', e.g. i16 on x86, consider
1079 unsigned Opc = Op.getOpcode();
1080 if (TLI.isTypeDesirableForOp(Opc, VT))
1084 // Consult target whether it is a good idea to promote this operation and
1085 // what's the right type to promote it to.
1086 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1087 assert(PVT != VT && "Don't know what type to promote to!");
1088 // fold (aext (aext x)) -> (aext x)
1089 // fold (aext (zext x)) -> (zext x)
1090 // fold (aext (sext x)) -> (sext x)
1091 DEBUG(dbgs() << "\nPromoting ";
1092 Op.getNode()->dump(&DAG));
1093 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1098 bool DAGCombiner::PromoteLoad(SDValue Op) {
1099 if (!LegalOperations)
1102 EVT VT = Op.getValueType();
1103 if (VT.isVector() || !VT.isInteger())
1106 // If operation type is 'undesirable', e.g. i16 on x86, consider
1108 unsigned Opc = Op.getOpcode();
1109 if (TLI.isTypeDesirableForOp(Opc, VT))
1113 // Consult target whether it is a good idea to promote this operation and
1114 // what's the right type to promote it to.
1115 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1116 assert(PVT != VT && "Don't know what type to promote to!");
1119 SDNode *N = Op.getNode();
1120 LoadSDNode *LD = cast<LoadSDNode>(N);
1121 EVT MemVT = LD->getMemoryVT();
1122 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1123 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1125 : LD->getExtensionType();
1126 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1127 LD->getChain(), LD->getBasePtr(),
1128 MemVT, LD->getMemOperand());
1129 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1131 DEBUG(dbgs() << "\nPromoting ";
1134 Result.getNode()->dump(&DAG);
1136 WorklistRemover DeadNodes(*this);
1137 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1138 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1139 deleteAndRecombine(N);
1140 AddToWorklist(Result.getNode());
1146 /// \brief Recursively delete a node which has no uses and any operands for
1147 /// which it is the only use.
1149 /// Note that this both deletes the nodes and removes them from the worklist.
1150 /// It also adds any nodes who have had a user deleted to the worklist as they
1151 /// may now have only one use and subject to other combines.
1152 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1153 if (!N->use_empty())
1156 SmallSetVector<SDNode *, 16> Nodes;
1159 N = Nodes.pop_back_val();
1163 if (N->use_empty()) {
1164 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1165 Nodes.insert(N->getOperand(i).getNode());
1167 removeFromWorklist(N);
1172 } while (!Nodes.empty());
1176 //===----------------------------------------------------------------------===//
1177 // Main DAG Combiner implementation
1178 //===----------------------------------------------------------------------===//
1180 void DAGCombiner::Run(CombineLevel AtLevel) {
1181 // set the instance variables, so that the various visit routines may use it.
1183 LegalOperations = Level >= AfterLegalizeVectorOps;
1184 LegalTypes = Level >= AfterLegalizeTypes;
1186 // Early exit if this basic block is in an optnone function.
1187 if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
1188 Attribute::OptimizeNone))
1191 // Add all the dag nodes to the worklist.
1192 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1193 E = DAG.allnodes_end(); I != E; ++I)
1196 // Create a dummy node (which is not added to allnodes), that adds a reference
1197 // to the root node, preventing it from being deleted, and tracking any
1198 // changes of the root.
1199 HandleSDNode Dummy(DAG.getRoot());
1201 // while the worklist isn't empty, find a node and
1202 // try and combine it.
1203 while (!WorklistMap.empty()) {
1205 // The Worklist holds the SDNodes in order, but it may contain null entries.
1207 N = Worklist.pop_back_val();
1210 bool GoodWorklistEntry = WorklistMap.erase(N);
1211 (void)GoodWorklistEntry;
1212 assert(GoodWorklistEntry &&
1213 "Found a worklist entry without a corresponding map entry!");
1215 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1216 // N is deleted from the DAG, since they too may now be dead or may have a
1217 // reduced number of uses, allowing other xforms.
1218 if (recursivelyDeleteUnusedNodes(N))
1221 WorklistRemover DeadNodes(*this);
1223 // If this combine is running after legalizing the DAG, re-legalize any
1224 // nodes pulled off the worklist.
1225 if (Level == AfterLegalizeDAG) {
1226 SmallSetVector<SDNode *, 16> UpdatedNodes;
1227 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1229 for (SDNode *LN : UpdatedNodes) {
1231 AddUsersToWorklist(LN);
1237 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1239 // Add any operands of the new node which have not yet been combined to the
1240 // worklist as well. Because the worklist uniques things already, this
1241 // won't repeatedly process the same operand.
1242 CombinedNodes.insert(N);
1243 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1244 if (!CombinedNodes.count(N->getOperand(i).getNode()))
1245 AddToWorklist(N->getOperand(i).getNode());
1247 SDValue RV = combine(N);
1254 // If we get back the same node we passed in, rather than a new node or
1255 // zero, we know that the node must have defined multiple values and
1256 // CombineTo was used. Since CombineTo takes care of the worklist
1257 // mechanics for us, we have no work to do in this case.
1258 if (RV.getNode() == N)
1261 assert(N->getOpcode() != ISD::DELETED_NODE &&
1262 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1263 "Node was deleted but visit returned new node!");
1265 DEBUG(dbgs() << " ... into: ";
1266 RV.getNode()->dump(&DAG));
1268 // Transfer debug value.
1269 DAG.TransferDbgValues(SDValue(N, 0), RV);
1270 if (N->getNumValues() == RV.getNode()->getNumValues())
1271 DAG.ReplaceAllUsesWith(N, RV.getNode());
1273 assert(N->getValueType(0) == RV.getValueType() &&
1274 N->getNumValues() == 1 && "Type mismatch");
1276 DAG.ReplaceAllUsesWith(N, &OpV);
1279 // Push the new node and any users onto the worklist
1280 AddToWorklist(RV.getNode());
1281 AddUsersToWorklist(RV.getNode());
1283 // Finally, if the node is now dead, remove it from the graph. The node
1284 // may not be dead if the replacement process recursively simplified to
1285 // something else needing this node. This will also take care of adding any
1286 // operands which have lost a user to the worklist.
1287 recursivelyDeleteUnusedNodes(N);
1290 // If the root changed (e.g. it was a dead load, update the root).
1291 DAG.setRoot(Dummy.getValue());
1292 DAG.RemoveDeadNodes();
1295 SDValue DAGCombiner::visit(SDNode *N) {
1296 switch (N->getOpcode()) {
1298 case ISD::TokenFactor: return visitTokenFactor(N);
1299 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1300 case ISD::ADD: return visitADD(N);
1301 case ISD::SUB: return visitSUB(N);
1302 case ISD::ADDC: return visitADDC(N);
1303 case ISD::SUBC: return visitSUBC(N);
1304 case ISD::ADDE: return visitADDE(N);
1305 case ISD::SUBE: return visitSUBE(N);
1306 case ISD::MUL: return visitMUL(N);
1307 case ISD::SDIV: return visitSDIV(N);
1308 case ISD::UDIV: return visitUDIV(N);
1309 case ISD::SREM: return visitSREM(N);
1310 case ISD::UREM: return visitUREM(N);
1311 case ISD::MULHU: return visitMULHU(N);
1312 case ISD::MULHS: return visitMULHS(N);
1313 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1314 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1315 case ISD::SMULO: return visitSMULO(N);
1316 case ISD::UMULO: return visitUMULO(N);
1317 case ISD::SDIVREM: return visitSDIVREM(N);
1318 case ISD::UDIVREM: return visitUDIVREM(N);
1319 case ISD::AND: return visitAND(N);
1320 case ISD::OR: return visitOR(N);
1321 case ISD::XOR: return visitXOR(N);
1322 case ISD::SHL: return visitSHL(N);
1323 case ISD::SRA: return visitSRA(N);
1324 case ISD::SRL: return visitSRL(N);
1326 case ISD::ROTL: return visitRotate(N);
1327 case ISD::CTLZ: return visitCTLZ(N);
1328 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1329 case ISD::CTTZ: return visitCTTZ(N);
1330 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1331 case ISD::CTPOP: return visitCTPOP(N);
1332 case ISD::SELECT: return visitSELECT(N);
1333 case ISD::VSELECT: return visitVSELECT(N);
1334 case ISD::SELECT_CC: return visitSELECT_CC(N);
1335 case ISD::SETCC: return visitSETCC(N);
1336 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1337 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1338 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1339 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1340 case ISD::TRUNCATE: return visitTRUNCATE(N);
1341 case ISD::BITCAST: return visitBITCAST(N);
1342 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1343 case ISD::FADD: return visitFADD(N);
1344 case ISD::FSUB: return visitFSUB(N);
1345 case ISD::FMUL: return visitFMUL(N);
1346 case ISD::FMA: return visitFMA(N);
1347 case ISD::FDIV: return visitFDIV(N);
1348 case ISD::FREM: return visitFREM(N);
1349 case ISD::FSQRT: return visitFSQRT(N);
1350 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1351 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1352 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1353 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1354 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1355 case ISD::FP_ROUND: return visitFP_ROUND(N);
1356 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1357 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1358 case ISD::FNEG: return visitFNEG(N);
1359 case ISD::FABS: return visitFABS(N);
1360 case ISD::FFLOOR: return visitFFLOOR(N);
1361 case ISD::FMINNUM: return visitFMINNUM(N);
1362 case ISD::FMAXNUM: return visitFMAXNUM(N);
1363 case ISD::FCEIL: return visitFCEIL(N);
1364 case ISD::FTRUNC: return visitFTRUNC(N);
1365 case ISD::BRCOND: return visitBRCOND(N);
1366 case ISD::BR_CC: return visitBR_CC(N);
1367 case ISD::LOAD: return visitLOAD(N);
1368 case ISD::STORE: return visitSTORE(N);
1369 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1370 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1371 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1372 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1373 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1374 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1375 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
1376 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1377 case ISD::MLOAD: return visitMLOAD(N);
1378 case ISD::MSTORE: return visitMSTORE(N);
1383 SDValue DAGCombiner::combine(SDNode *N) {
1384 SDValue RV = visit(N);
1386 // If nothing happened, try a target-specific DAG combine.
1387 if (!RV.getNode()) {
1388 assert(N->getOpcode() != ISD::DELETED_NODE &&
1389 "Node was deleted but visit returned NULL!");
1391 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1392 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1394 // Expose the DAG combiner to the target combiner impls.
1395 TargetLowering::DAGCombinerInfo
1396 DagCombineInfo(DAG, Level, false, this);
1398 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1402 // If nothing happened still, try promoting the operation.
1403 if (!RV.getNode()) {
1404 switch (N->getOpcode()) {
1412 RV = PromoteIntBinOp(SDValue(N, 0));
1417 RV = PromoteIntShiftOp(SDValue(N, 0));
1419 case ISD::SIGN_EXTEND:
1420 case ISD::ZERO_EXTEND:
1421 case ISD::ANY_EXTEND:
1422 RV = PromoteExtend(SDValue(N, 0));
1425 if (PromoteLoad(SDValue(N, 0)))
1431 // If N is a commutative binary node, try commuting it to enable more
1433 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1434 N->getNumValues() == 1) {
1435 SDValue N0 = N->getOperand(0);
1436 SDValue N1 = N->getOperand(1);
1438 // Constant operands are canonicalized to RHS.
1439 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1440 SDValue Ops[] = {N1, N0};
1442 if (const BinaryWithFlagsSDNode *BinNode =
1443 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1444 CSENode = DAG.getNodeIfExists(
1445 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1446 BinNode->hasNoSignedWrap(), BinNode->isExact());
1448 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1451 return SDValue(CSENode, 0);
1458 /// Given a node, return its input chain if it has one, otherwise return a null
1460 static SDValue getInputChainForNode(SDNode *N) {
1461 if (unsigned NumOps = N->getNumOperands()) {
1462 if (N->getOperand(0).getValueType() == MVT::Other)
1463 return N->getOperand(0);
1464 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1465 return N->getOperand(NumOps-1);
1466 for (unsigned i = 1; i < NumOps-1; ++i)
1467 if (N->getOperand(i).getValueType() == MVT::Other)
1468 return N->getOperand(i);
1473 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1474 // If N has two operands, where one has an input chain equal to the other,
1475 // the 'other' chain is redundant.
1476 if (N->getNumOperands() == 2) {
1477 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1478 return N->getOperand(0);
1479 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1480 return N->getOperand(1);
1483 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1484 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1485 SmallPtrSet<SDNode*, 16> SeenOps;
1486 bool Changed = false; // If we should replace this token factor.
1488 // Start out with this token factor.
1491 // Iterate through token factors. The TFs grows when new token factors are
1493 for (unsigned i = 0; i < TFs.size(); ++i) {
1494 SDNode *TF = TFs[i];
1496 // Check each of the operands.
1497 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1498 SDValue Op = TF->getOperand(i);
1500 switch (Op.getOpcode()) {
1501 case ISD::EntryToken:
1502 // Entry tokens don't need to be added to the list. They are
1507 case ISD::TokenFactor:
1508 if (Op.hasOneUse() &&
1509 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1510 // Queue up for processing.
1511 TFs.push_back(Op.getNode());
1512 // Clean up in case the token factor is removed.
1513 AddToWorklist(Op.getNode());
1520 // Only add if it isn't already in the list.
1521 if (SeenOps.insert(Op.getNode()).second)
1532 // If we've changed things around then replace token factor.
1535 // The entry token is the only possible outcome.
1536 Result = DAG.getEntryNode();
1538 // New and improved token factor.
1539 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1542 // Add users to worklist if AA is enabled, since it may introduce
1543 // a lot of new chained token factors while removing memory deps.
1544 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1545 : DAG.getSubtarget().useAA();
1546 return CombineTo(N, Result, UseAA /*add to worklist*/);
1552 /// MERGE_VALUES can always be eliminated.
1553 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1554 WorklistRemover DeadNodes(*this);
1555 // Replacing results may cause a different MERGE_VALUES to suddenly
1556 // be CSE'd with N, and carry its uses with it. Iterate until no
1557 // uses remain, to ensure that the node can be safely deleted.
1558 // First add the users of this node to the work list so that they
1559 // can be tried again once they have new operands.
1560 AddUsersToWorklist(N);
1562 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1563 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1564 } while (!N->use_empty());
1565 deleteAndRecombine(N);
1566 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1569 SDValue DAGCombiner::visitADD(SDNode *N) {
1570 SDValue N0 = N->getOperand(0);
1571 SDValue N1 = N->getOperand(1);
1572 EVT VT = N0.getValueType();
1575 if (VT.isVector()) {
1576 SDValue FoldedVOp = SimplifyVBinOp(N);
1577 if (FoldedVOp.getNode()) return FoldedVOp;
1579 // fold (add x, 0) -> x, vector edition
1580 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1582 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1586 // fold (add x, undef) -> undef
1587 if (N0.getOpcode() == ISD::UNDEF)
1589 if (N1.getOpcode() == ISD::UNDEF)
1591 // fold (add c1, c2) -> c1+c2
1592 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1593 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1595 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1596 // canonicalize constant to RHS
1598 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1599 // fold (add x, 0) -> x
1600 if (N1C && N1C->isNullValue())
1602 // fold (add Sym, c) -> Sym+c
1603 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1604 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1605 GA->getOpcode() == ISD::GlobalAddress)
1606 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1608 (uint64_t)N1C->getSExtValue());
1609 // fold ((c1-A)+c2) -> (c1+c2)-A
1610 if (N1C && N0.getOpcode() == ISD::SUB)
1611 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1612 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1613 DAG.getConstant(N1C->getAPIntValue()+
1614 N0C->getAPIntValue(), VT),
1617 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1620 // fold ((0-A) + B) -> B-A
1621 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1622 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1623 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1624 // fold (A + (0-B)) -> A-B
1625 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1626 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1627 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1628 // fold (A+(B-A)) -> B
1629 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1630 return N1.getOperand(0);
1631 // fold ((B-A)+A) -> B
1632 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1633 return N0.getOperand(0);
1634 // fold (A+(B-(A+C))) to (B-C)
1635 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1636 N0 == N1.getOperand(1).getOperand(0))
1637 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1638 N1.getOperand(1).getOperand(1));
1639 // fold (A+(B-(C+A))) to (B-C)
1640 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1641 N0 == N1.getOperand(1).getOperand(1))
1642 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1643 N1.getOperand(1).getOperand(0));
1644 // fold (A+((B-A)+or-C)) to (B+or-C)
1645 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1646 N1.getOperand(0).getOpcode() == ISD::SUB &&
1647 N0 == N1.getOperand(0).getOperand(1))
1648 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1649 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1651 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1652 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1653 SDValue N00 = N0.getOperand(0);
1654 SDValue N01 = N0.getOperand(1);
1655 SDValue N10 = N1.getOperand(0);
1656 SDValue N11 = N1.getOperand(1);
1658 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1659 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1660 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1661 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1664 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1665 return SDValue(N, 0);
1667 // fold (a+b) -> (a|b) iff a and b share no bits.
1668 if (VT.isInteger() && !VT.isVector()) {
1669 APInt LHSZero, LHSOne;
1670 APInt RHSZero, RHSOne;
1671 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1673 if (LHSZero.getBoolValue()) {
1674 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1676 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1677 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1678 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1679 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1680 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1685 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1686 if (N1.getOpcode() == ISD::SHL &&
1687 N1.getOperand(0).getOpcode() == ISD::SUB)
1688 if (ConstantSDNode *C =
1689 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1690 if (C->getAPIntValue() == 0)
1691 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1692 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1693 N1.getOperand(0).getOperand(1),
1695 if (N0.getOpcode() == ISD::SHL &&
1696 N0.getOperand(0).getOpcode() == ISD::SUB)
1697 if (ConstantSDNode *C =
1698 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1699 if (C->getAPIntValue() == 0)
1700 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1701 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1702 N0.getOperand(0).getOperand(1),
1705 if (N1.getOpcode() == ISD::AND) {
1706 SDValue AndOp0 = N1.getOperand(0);
1707 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1708 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1709 unsigned DestBits = VT.getScalarType().getSizeInBits();
1711 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1712 // and similar xforms where the inner op is either ~0 or 0.
1713 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1715 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1719 // add (sext i1), X -> sub X, (zext i1)
1720 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1721 N0.getOperand(0).getValueType() == MVT::i1 &&
1722 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1724 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1725 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1728 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1729 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1730 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1731 if (TN->getVT() == MVT::i1) {
1733 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1734 DAG.getConstant(1, VT));
1735 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1742 SDValue DAGCombiner::visitADDC(SDNode *N) {
1743 SDValue N0 = N->getOperand(0);
1744 SDValue N1 = N->getOperand(1);
1745 EVT VT = N0.getValueType();
1747 // If the flag result is dead, turn this into an ADD.
1748 if (!N->hasAnyUseOfValue(1))
1749 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1750 DAG.getNode(ISD::CARRY_FALSE,
1751 SDLoc(N), MVT::Glue));
1753 // canonicalize constant to RHS.
1754 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1755 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1757 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1759 // fold (addc x, 0) -> x + no carry out
1760 if (N1C && N1C->isNullValue())
1761 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1762 SDLoc(N), MVT::Glue));
1764 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1765 APInt LHSZero, LHSOne;
1766 APInt RHSZero, RHSOne;
1767 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1769 if (LHSZero.getBoolValue()) {
1770 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1772 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1773 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1774 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1775 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1776 DAG.getNode(ISD::CARRY_FALSE,
1777 SDLoc(N), MVT::Glue));
1783 SDValue DAGCombiner::visitADDE(SDNode *N) {
1784 SDValue N0 = N->getOperand(0);
1785 SDValue N1 = N->getOperand(1);
1786 SDValue CarryIn = N->getOperand(2);
1788 // canonicalize constant to RHS
1789 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1790 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1792 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1795 // fold (adde x, y, false) -> (addc x, y)
1796 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1797 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1802 // Since it may not be valid to emit a fold to zero for vector initializers
1803 // check if we can before folding.
1804 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1806 bool LegalOperations, bool LegalTypes) {
1808 return DAG.getConstant(0, VT);
1809 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1810 return DAG.getConstant(0, VT);
1814 SDValue DAGCombiner::visitSUB(SDNode *N) {
1815 SDValue N0 = N->getOperand(0);
1816 SDValue N1 = N->getOperand(1);
1817 EVT VT = N0.getValueType();
1820 if (VT.isVector()) {
1821 SDValue FoldedVOp = SimplifyVBinOp(N);
1822 if (FoldedVOp.getNode()) return FoldedVOp;
1824 // fold (sub x, 0) -> x, vector edition
1825 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1829 // fold (sub x, x) -> 0
1830 // FIXME: Refactor this and xor and other similar operations together.
1832 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1833 // fold (sub c1, c2) -> c1-c2
1834 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1835 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1837 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1838 // fold (sub x, c) -> (add x, -c)
1840 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1841 DAG.getConstant(-N1C->getAPIntValue(), VT));
1842 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1843 if (N0C && N0C->isAllOnesValue())
1844 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1845 // fold A-(A-B) -> B
1846 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1847 return N1.getOperand(1);
1848 // fold (A+B)-A -> B
1849 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1850 return N0.getOperand(1);
1851 // fold (A+B)-B -> A
1852 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1853 return N0.getOperand(0);
1854 // fold C2-(A+C1) -> (C2-C1)-A
1855 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1856 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1857 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1858 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1860 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1863 // fold ((A+(B+or-C))-B) -> A+or-C
1864 if (N0.getOpcode() == ISD::ADD &&
1865 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1866 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1867 N0.getOperand(1).getOperand(0) == N1)
1868 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1869 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1870 // fold ((A+(C+B))-B) -> A+C
1871 if (N0.getOpcode() == ISD::ADD &&
1872 N0.getOperand(1).getOpcode() == ISD::ADD &&
1873 N0.getOperand(1).getOperand(1) == N1)
1874 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1875 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1876 // fold ((A-(B-C))-C) -> A-B
1877 if (N0.getOpcode() == ISD::SUB &&
1878 N0.getOperand(1).getOpcode() == ISD::SUB &&
1879 N0.getOperand(1).getOperand(1) == N1)
1880 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1881 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1883 // If either operand of a sub is undef, the result is undef
1884 if (N0.getOpcode() == ISD::UNDEF)
1886 if (N1.getOpcode() == ISD::UNDEF)
1889 // If the relocation model supports it, consider symbol offsets.
1890 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1891 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1892 // fold (sub Sym, c) -> Sym-c
1893 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1894 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1896 (uint64_t)N1C->getSExtValue());
1897 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1898 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1899 if (GA->getGlobal() == GB->getGlobal())
1900 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1904 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1905 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1906 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1907 if (TN->getVT() == MVT::i1) {
1909 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1910 DAG.getConstant(1, VT));
1911 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1918 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1919 SDValue N0 = N->getOperand(0);
1920 SDValue N1 = N->getOperand(1);
1921 EVT VT = N0.getValueType();
1923 // If the flag result is dead, turn this into an SUB.
1924 if (!N->hasAnyUseOfValue(1))
1925 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1926 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1929 // fold (subc x, x) -> 0 + no borrow
1931 return CombineTo(N, DAG.getConstant(0, VT),
1932 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1935 // fold (subc x, 0) -> x + no borrow
1936 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1937 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1938 if (N1C && N1C->isNullValue())
1939 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1942 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1943 if (N0C && N0C->isAllOnesValue())
1944 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1945 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1951 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1952 SDValue N0 = N->getOperand(0);
1953 SDValue N1 = N->getOperand(1);
1954 SDValue CarryIn = N->getOperand(2);
1956 // fold (sube x, y, false) -> (subc x, y)
1957 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1958 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1963 SDValue DAGCombiner::visitMUL(SDNode *N) {
1964 SDValue N0 = N->getOperand(0);
1965 SDValue N1 = N->getOperand(1);
1966 EVT VT = N0.getValueType();
1968 // fold (mul x, undef) -> 0
1969 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1970 return DAG.getConstant(0, VT);
1972 bool N0IsConst = false;
1973 bool N1IsConst = false;
1974 APInt ConstValue0, ConstValue1;
1976 if (VT.isVector()) {
1977 SDValue FoldedVOp = SimplifyVBinOp(N);
1978 if (FoldedVOp.getNode()) return FoldedVOp;
1980 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1981 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1983 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1984 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1986 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1987 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1991 // fold (mul c1, c2) -> c1*c2
1992 if (N0IsConst && N1IsConst)
1993 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1995 // canonicalize constant to RHS
1996 if (N0IsConst && !N1IsConst)
1997 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1998 // fold (mul x, 0) -> 0
1999 if (N1IsConst && ConstValue1 == 0)
2001 // We require a splat of the entire scalar bit width for non-contiguous
2004 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2005 // fold (mul x, 1) -> x
2006 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2008 // fold (mul x, -1) -> 0-x
2009 if (N1IsConst && ConstValue1.isAllOnesValue())
2010 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2011 DAG.getConstant(0, VT), N0);
2012 // fold (mul x, (1 << c)) -> x << c
2013 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
2014 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
2015 DAG.getConstant(ConstValue1.logBase2(),
2016 getShiftAmountTy(N0.getValueType())));
2017 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2018 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
2019 unsigned Log2Val = (-ConstValue1).logBase2();
2020 // FIXME: If the input is something that is easily negated (e.g. a
2021 // single-use add), we should put the negate there.
2022 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2023 DAG.getConstant(0, VT),
2024 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
2025 DAG.getConstant(Log2Val,
2026 getShiftAmountTy(N0.getValueType()))));
2030 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2031 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2032 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2033 isa<ConstantSDNode>(N0.getOperand(1)))) {
2034 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2035 N1, N0.getOperand(1));
2036 AddToWorklist(C3.getNode());
2037 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2038 N0.getOperand(0), C3);
2041 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2044 SDValue Sh(nullptr,0), Y(nullptr,0);
2045 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2046 if (N0.getOpcode() == ISD::SHL &&
2047 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2048 isa<ConstantSDNode>(N0.getOperand(1))) &&
2049 N0.getNode()->hasOneUse()) {
2051 } else if (N1.getOpcode() == ISD::SHL &&
2052 isa<ConstantSDNode>(N1.getOperand(1)) &&
2053 N1.getNode()->hasOneUse()) {
2058 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2059 Sh.getOperand(0), Y);
2060 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2061 Mul, Sh.getOperand(1));
2065 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2066 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2067 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2068 isa<ConstantSDNode>(N0.getOperand(1))))
2069 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2070 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2071 N0.getOperand(0), N1),
2072 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2073 N0.getOperand(1), N1));
2076 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2083 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2084 SDValue N0 = N->getOperand(0);
2085 SDValue N1 = N->getOperand(1);
2086 EVT VT = N->getValueType(0);
2089 if (VT.isVector()) {
2090 SDValue FoldedVOp = SimplifyVBinOp(N);
2091 if (FoldedVOp.getNode()) return FoldedVOp;
2094 // fold (sdiv c1, c2) -> c1/c2
2095 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2096 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2097 if (N0C && N1C && !N1C->isNullValue())
2098 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2099 // fold (sdiv X, 1) -> X
2100 if (N1C && N1C->getAPIntValue() == 1LL)
2102 // fold (sdiv X, -1) -> 0-X
2103 if (N1C && N1C->isAllOnesValue())
2104 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2105 DAG.getConstant(0, VT), N0);
2106 // If we know the sign bits of both operands are zero, strength reduce to a
2107 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2108 if (!VT.isVector()) {
2109 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2110 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2114 // fold (sdiv X, pow2) -> simple ops after legalize
2115 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2116 (-N1C->getAPIntValue()).isPowerOf2())) {
2117 // If dividing by powers of two is cheap, then don't perform the following
2119 if (TLI.isPow2SDivCheap())
2122 // Target-specific implementation of sdiv x, pow2.
2123 SDValue Res = BuildSDIVPow2(N);
2127 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2129 // Splat the sign bit into the register
2131 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2132 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2133 getShiftAmountTy(N0.getValueType())));
2134 AddToWorklist(SGN.getNode());
2136 // Add (N0 < 0) ? abs2 - 1 : 0;
2138 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2139 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2140 getShiftAmountTy(SGN.getValueType())));
2141 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2142 AddToWorklist(SRL.getNode());
2143 AddToWorklist(ADD.getNode()); // Divide by pow2
2144 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2145 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2147 // If we're dividing by a positive value, we're done. Otherwise, we must
2148 // negate the result.
2149 if (N1C->getAPIntValue().isNonNegative())
2152 AddToWorklist(SRA.getNode());
2153 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2156 // if integer divide is expensive and we satisfy the requirements, emit an
2157 // alternate sequence.
2158 if (N1C && !TLI.isIntDivCheap()) {
2159 SDValue Op = BuildSDIV(N);
2160 if (Op.getNode()) return Op;
2164 if (N0.getOpcode() == ISD::UNDEF)
2165 return DAG.getConstant(0, VT);
2166 // X / undef -> undef
2167 if (N1.getOpcode() == ISD::UNDEF)
2173 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2174 SDValue N0 = N->getOperand(0);
2175 SDValue N1 = N->getOperand(1);
2176 EVT VT = N->getValueType(0);
2179 if (VT.isVector()) {
2180 SDValue FoldedVOp = SimplifyVBinOp(N);
2181 if (FoldedVOp.getNode()) return FoldedVOp;
2184 // fold (udiv c1, c2) -> c1/c2
2185 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2186 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2187 if (N0C && N1C && !N1C->isNullValue())
2188 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2189 // fold (udiv x, (1 << c)) -> x >>u c
2190 if (N1C && N1C->getAPIntValue().isPowerOf2())
2191 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2192 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2193 getShiftAmountTy(N0.getValueType())));
2194 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2195 if (N1.getOpcode() == ISD::SHL) {
2196 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2197 if (SHC->getAPIntValue().isPowerOf2()) {
2198 EVT ADDVT = N1.getOperand(1).getValueType();
2199 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2201 DAG.getConstant(SHC->getAPIntValue()
2204 AddToWorklist(Add.getNode());
2205 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2209 // fold (udiv x, c) -> alternate
2210 if (N1C && !TLI.isIntDivCheap()) {
2211 SDValue Op = BuildUDIV(N);
2212 if (Op.getNode()) return Op;
2216 if (N0.getOpcode() == ISD::UNDEF)
2217 return DAG.getConstant(0, VT);
2218 // X / undef -> undef
2219 if (N1.getOpcode() == ISD::UNDEF)
2225 SDValue DAGCombiner::visitSREM(SDNode *N) {
2226 SDValue N0 = N->getOperand(0);
2227 SDValue N1 = N->getOperand(1);
2228 EVT VT = N->getValueType(0);
2230 // fold (srem c1, c2) -> c1%c2
2231 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2232 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2233 if (N0C && N1C && !N1C->isNullValue())
2234 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2235 // If we know the sign bits of both operands are zero, strength reduce to a
2236 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2237 if (!VT.isVector()) {
2238 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2239 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2242 // If X/C can be simplified by the division-by-constant logic, lower
2243 // X%C to the equivalent of X-X/C*C.
2244 if (N1C && !N1C->isNullValue()) {
2245 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2246 AddToWorklist(Div.getNode());
2247 SDValue OptimizedDiv = combine(Div.getNode());
2248 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2249 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2251 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2252 AddToWorklist(Mul.getNode());
2258 if (N0.getOpcode() == ISD::UNDEF)
2259 return DAG.getConstant(0, VT);
2260 // X % undef -> undef
2261 if (N1.getOpcode() == ISD::UNDEF)
2267 SDValue DAGCombiner::visitUREM(SDNode *N) {
2268 SDValue N0 = N->getOperand(0);
2269 SDValue N1 = N->getOperand(1);
2270 EVT VT = N->getValueType(0);
2272 // fold (urem c1, c2) -> c1%c2
2273 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2274 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2275 if (N0C && N1C && !N1C->isNullValue())
2276 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2277 // fold (urem x, pow2) -> (and x, pow2-1)
2278 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2279 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2280 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2281 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2282 if (N1.getOpcode() == ISD::SHL) {
2283 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2284 if (SHC->getAPIntValue().isPowerOf2()) {
2286 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2287 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2289 AddToWorklist(Add.getNode());
2290 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2295 // If X/C can be simplified by the division-by-constant logic, lower
2296 // X%C to the equivalent of X-X/C*C.
2297 if (N1C && !N1C->isNullValue()) {
2298 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2299 AddToWorklist(Div.getNode());
2300 SDValue OptimizedDiv = combine(Div.getNode());
2301 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2302 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2304 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2305 AddToWorklist(Mul.getNode());
2311 if (N0.getOpcode() == ISD::UNDEF)
2312 return DAG.getConstant(0, VT);
2313 // X % undef -> undef
2314 if (N1.getOpcode() == ISD::UNDEF)
2320 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2321 SDValue N0 = N->getOperand(0);
2322 SDValue N1 = N->getOperand(1);
2323 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2324 EVT VT = N->getValueType(0);
2327 // fold (mulhs x, 0) -> 0
2328 if (N1C && N1C->isNullValue())
2330 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2331 if (N1C && N1C->getAPIntValue() == 1)
2332 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2333 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2334 getShiftAmountTy(N0.getValueType())));
2335 // fold (mulhs x, undef) -> 0
2336 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2337 return DAG.getConstant(0, VT);
2339 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2341 if (VT.isSimple() && !VT.isVector()) {
2342 MVT Simple = VT.getSimpleVT();
2343 unsigned SimpleSize = Simple.getSizeInBits();
2344 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2345 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2346 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2347 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2348 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2349 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2350 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2351 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2358 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2359 SDValue N0 = N->getOperand(0);
2360 SDValue N1 = N->getOperand(1);
2361 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2362 EVT VT = N->getValueType(0);
2365 // fold (mulhu x, 0) -> 0
2366 if (N1C && N1C->isNullValue())
2368 // fold (mulhu x, 1) -> 0
2369 if (N1C && N1C->getAPIntValue() == 1)
2370 return DAG.getConstant(0, N0.getValueType());
2371 // fold (mulhu x, undef) -> 0
2372 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2373 return DAG.getConstant(0, VT);
2375 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2377 if (VT.isSimple() && !VT.isVector()) {
2378 MVT Simple = VT.getSimpleVT();
2379 unsigned SimpleSize = Simple.getSizeInBits();
2380 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2381 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2382 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2383 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2384 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2385 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2386 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2387 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2394 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2395 /// give the opcodes for the two computations that are being performed. Return
2396 /// true if a simplification was made.
2397 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2399 // If the high half is not needed, just compute the low half.
2400 bool HiExists = N->hasAnyUseOfValue(1);
2402 (!LegalOperations ||
2403 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2404 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2405 return CombineTo(N, Res, Res);
2408 // If the low half is not needed, just compute the high half.
2409 bool LoExists = N->hasAnyUseOfValue(0);
2411 (!LegalOperations ||
2412 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2413 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2414 return CombineTo(N, Res, Res);
2417 // If both halves are used, return as it is.
2418 if (LoExists && HiExists)
2421 // If the two computed results can be simplified separately, separate them.
2423 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2424 AddToWorklist(Lo.getNode());
2425 SDValue LoOpt = combine(Lo.getNode());
2426 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2427 (!LegalOperations ||
2428 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2429 return CombineTo(N, LoOpt, LoOpt);
2433 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2434 AddToWorklist(Hi.getNode());
2435 SDValue HiOpt = combine(Hi.getNode());
2436 if (HiOpt.getNode() && HiOpt != Hi &&
2437 (!LegalOperations ||
2438 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2439 return CombineTo(N, HiOpt, HiOpt);
2445 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2446 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2447 if (Res.getNode()) return Res;
2449 EVT VT = N->getValueType(0);
2452 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2454 if (VT.isSimple() && !VT.isVector()) {
2455 MVT Simple = VT.getSimpleVT();
2456 unsigned SimpleSize = Simple.getSizeInBits();
2457 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2458 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2459 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2460 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2461 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2462 // Compute the high part as N1.
2463 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2464 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2465 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2466 // Compute the low part as N0.
2467 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2468 return CombineTo(N, Lo, Hi);
2475 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2476 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2477 if (Res.getNode()) return Res;
2479 EVT VT = N->getValueType(0);
2482 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2484 if (VT.isSimple() && !VT.isVector()) {
2485 MVT Simple = VT.getSimpleVT();
2486 unsigned SimpleSize = Simple.getSizeInBits();
2487 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2488 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2489 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2490 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2491 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2492 // Compute the high part as N1.
2493 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2494 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2495 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2496 // Compute the low part as N0.
2497 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2498 return CombineTo(N, Lo, Hi);
2505 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2506 // (smulo x, 2) -> (saddo x, x)
2507 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2508 if (C2->getAPIntValue() == 2)
2509 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2510 N->getOperand(0), N->getOperand(0));
2515 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2516 // (umulo x, 2) -> (uaddo x, x)
2517 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2518 if (C2->getAPIntValue() == 2)
2519 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2520 N->getOperand(0), N->getOperand(0));
2525 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2526 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2527 if (Res.getNode()) return Res;
2532 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2533 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2534 if (Res.getNode()) return Res;
2539 /// If this is a binary operator with two operands of the same opcode, try to
2541 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2542 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2543 EVT VT = N0.getValueType();
2544 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2546 // Bail early if none of these transforms apply.
2547 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2549 // For each of OP in AND/OR/XOR:
2550 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2551 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2552 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2553 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2554 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2556 // do not sink logical op inside of a vector extend, since it may combine
2558 EVT Op0VT = N0.getOperand(0).getValueType();
2559 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2560 N0.getOpcode() == ISD::SIGN_EXTEND ||
2561 N0.getOpcode() == ISD::BSWAP ||
2562 // Avoid infinite looping with PromoteIntBinOp.
2563 (N0.getOpcode() == ISD::ANY_EXTEND &&
2564 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2565 (N0.getOpcode() == ISD::TRUNCATE &&
2566 (!TLI.isZExtFree(VT, Op0VT) ||
2567 !TLI.isTruncateFree(Op0VT, VT)) &&
2568 TLI.isTypeLegal(Op0VT))) &&
2570 Op0VT == N1.getOperand(0).getValueType() &&
2571 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2572 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2573 N0.getOperand(0).getValueType(),
2574 N0.getOperand(0), N1.getOperand(0));
2575 AddToWorklist(ORNode.getNode());
2576 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2579 // For each of OP in SHL/SRL/SRA/AND...
2580 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2581 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2582 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2583 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2584 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2585 N0.getOperand(1) == N1.getOperand(1)) {
2586 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2587 N0.getOperand(0).getValueType(),
2588 N0.getOperand(0), N1.getOperand(0));
2589 AddToWorklist(ORNode.getNode());
2590 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2591 ORNode, N0.getOperand(1));
2594 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2595 // Only perform this optimization after type legalization and before
2596 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2597 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2598 // we don't want to undo this promotion.
2599 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2601 if ((N0.getOpcode() == ISD::BITCAST ||
2602 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2603 Level == AfterLegalizeTypes) {
2604 SDValue In0 = N0.getOperand(0);
2605 SDValue In1 = N1.getOperand(0);
2606 EVT In0Ty = In0.getValueType();
2607 EVT In1Ty = In1.getValueType();
2609 // If both incoming values are integers, and the original types are the
2611 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2612 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2613 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2614 AddToWorklist(Op.getNode());
2619 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2620 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2621 // If both shuffles use the same mask, and both shuffle within a single
2622 // vector, then it is worthwhile to move the swizzle after the operation.
2623 // The type-legalizer generates this pattern when loading illegal
2624 // vector types from memory. In many cases this allows additional shuffle
2626 // There are other cases where moving the shuffle after the xor/and/or
2627 // is profitable even if shuffles don't perform a swizzle.
2628 // If both shuffles use the same mask, and both shuffles have the same first
2629 // or second operand, then it might still be profitable to move the shuffle
2630 // after the xor/and/or operation.
2631 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2632 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2633 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2635 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2636 "Inputs to shuffles are not the same type");
2638 // Check that both shuffles use the same mask. The masks are known to be of
2639 // the same length because the result vector type is the same.
2640 // Check also that shuffles have only one use to avoid introducing extra
2642 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2643 SVN0->getMask().equals(SVN1->getMask())) {
2644 SDValue ShOp = N0->getOperand(1);
2646 // Don't try to fold this node if it requires introducing a
2647 // build vector of all zeros that might be illegal at this stage.
2648 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2650 ShOp = DAG.getConstant(0, VT);
2655 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2656 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2657 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2658 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2659 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2660 N0->getOperand(0), N1->getOperand(0));
2661 AddToWorklist(NewNode.getNode());
2662 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2663 &SVN0->getMask()[0]);
2666 // Don't try to fold this node if it requires introducing a
2667 // build vector of all zeros that might be illegal at this stage.
2668 ShOp = N0->getOperand(0);
2669 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2671 ShOp = DAG.getConstant(0, VT);
2676 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2677 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2678 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2679 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2680 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2681 N0->getOperand(1), N1->getOperand(1));
2682 AddToWorklist(NewNode.getNode());
2683 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2684 &SVN0->getMask()[0]);
2692 /// This contains all DAGCombine rules which reduce two values combined by
2693 /// an And operation to a single value. This makes them reusable in the context
2694 /// of visitSELECT(). Rules involving constants are not included as
2695 /// visitSELECT() already handles those cases.
2696 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2697 SDNode *LocReference) {
2698 EVT VT = N1.getValueType();
2700 // fold (and x, undef) -> 0
2701 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2702 return DAG.getConstant(0, VT);
2703 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2704 SDValue LL, LR, RL, RR, CC0, CC1;
2705 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2706 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2707 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2709 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2710 LL.getValueType().isInteger()) {
2711 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2712 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2713 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2714 LR.getValueType(), LL, RL);
2715 AddToWorklist(ORNode.getNode());
2716 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2718 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2719 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2720 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2721 LR.getValueType(), LL, RL);
2722 AddToWorklist(ANDNode.getNode());
2723 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2725 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2726 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2727 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2728 LR.getValueType(), LL, RL);
2729 AddToWorklist(ORNode.getNode());
2730 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2733 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2734 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2735 Op0 == Op1 && LL.getValueType().isInteger() &&
2736 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2737 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2738 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2739 cast<ConstantSDNode>(RR)->isNullValue()))) {
2740 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2741 LL, DAG.getConstant(1, LL.getValueType()));
2742 AddToWorklist(ADDNode.getNode());
2743 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2744 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2746 // canonicalize equivalent to ll == rl
2747 if (LL == RR && LR == RL) {
2748 Op1 = ISD::getSetCCSwappedOperands(Op1);
2751 if (LL == RL && LR == RR) {
2752 bool isInteger = LL.getValueType().isInteger();
2753 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2754 if (Result != ISD::SETCC_INVALID &&
2755 (!LegalOperations ||
2756 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2757 TLI.isOperationLegal(ISD::SETCC,
2758 getSetCCResultType(N0.getSimpleValueType())))))
2759 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2764 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2765 VT.getSizeInBits() <= 64) {
2766 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2767 APInt ADDC = ADDI->getAPIntValue();
2768 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2769 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2770 // immediate for an add, but it is legal if its top c2 bits are set,
2771 // transform the ADD so the immediate doesn't need to be materialized
2773 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2774 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2775 SRLI->getZExtValue());
2776 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2778 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2780 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2781 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2782 CombineTo(N0.getNode(), NewAdd);
2783 // Return N so it doesn't get rechecked!
2784 return SDValue(LocReference, 0);
2795 SDValue DAGCombiner::visitAND(SDNode *N) {
2796 SDValue N0 = N->getOperand(0);
2797 SDValue N1 = N->getOperand(1);
2798 EVT VT = N1.getValueType();
2801 if (VT.isVector()) {
2802 SDValue FoldedVOp = SimplifyVBinOp(N);
2803 if (FoldedVOp.getNode()) return FoldedVOp;
2805 // fold (and x, 0) -> 0, vector edition
2806 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2807 // do not return N0, because undef node may exist in N0
2808 return DAG.getConstant(
2809 APInt::getNullValue(
2810 N0.getValueType().getScalarType().getSizeInBits()),
2812 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2813 // do not return N1, because undef node may exist in N1
2814 return DAG.getConstant(
2815 APInt::getNullValue(
2816 N1.getValueType().getScalarType().getSizeInBits()),
2819 // fold (and x, -1) -> x, vector edition
2820 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2822 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2826 // fold (and c1, c2) -> c1&c2
2827 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2828 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2830 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2831 // canonicalize constant to RHS
2833 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2834 // fold (and x, -1) -> x
2835 if (N1C && N1C->isAllOnesValue())
2837 // if (and x, c) is known to be zero, return 0
2838 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2839 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2840 APInt::getAllOnesValue(BitWidth)))
2841 return DAG.getConstant(0, VT);
2843 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2846 // fold (and (or x, C), D) -> D if (C & D) == D
2847 if (N1C && N0.getOpcode() == ISD::OR)
2848 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2849 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2851 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2852 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2853 SDValue N0Op0 = N0.getOperand(0);
2854 APInt Mask = ~N1C->getAPIntValue();
2855 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2856 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2857 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2858 N0.getValueType(), N0Op0);
2860 // Replace uses of the AND with uses of the Zero extend node.
2863 // We actually want to replace all uses of the any_extend with the
2864 // zero_extend, to avoid duplicating things. This will later cause this
2865 // AND to be folded.
2866 CombineTo(N0.getNode(), Zext);
2867 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2870 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2871 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2872 // already be zero by virtue of the width of the base type of the load.
2874 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2876 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2877 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2878 N0.getOpcode() == ISD::LOAD) {
2879 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2880 N0 : N0.getOperand(0) );
2882 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2883 // This can be a pure constant or a vector splat, in which case we treat the
2884 // vector as a scalar and use the splat value.
2885 APInt Constant = APInt::getNullValue(1);
2886 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2887 Constant = C->getAPIntValue();
2888 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2889 APInt SplatValue, SplatUndef;
2890 unsigned SplatBitSize;
2892 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2893 SplatBitSize, HasAnyUndefs);
2895 // Undef bits can contribute to a possible optimisation if set, so
2897 SplatValue |= SplatUndef;
2899 // The splat value may be something like "0x00FFFFFF", which means 0 for
2900 // the first vector value and FF for the rest, repeating. We need a mask
2901 // that will apply equally to all members of the vector, so AND all the
2902 // lanes of the constant together.
2903 EVT VT = Vector->getValueType(0);
2904 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2906 // If the splat value has been compressed to a bitlength lower
2907 // than the size of the vector lane, we need to re-expand it to
2909 if (BitWidth > SplatBitSize)
2910 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2911 SplatBitSize < BitWidth;
2912 SplatBitSize = SplatBitSize * 2)
2913 SplatValue |= SplatValue.shl(SplatBitSize);
2915 Constant = APInt::getAllOnesValue(BitWidth);
2916 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2917 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2921 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2922 // actually legal and isn't going to get expanded, else this is a false
2924 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2925 Load->getValueType(0),
2926 Load->getMemoryVT());
2928 // Resize the constant to the same size as the original memory access before
2929 // extension. If it is still the AllOnesValue then this AND is completely
2932 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2935 switch (Load->getExtensionType()) {
2936 default: B = false; break;
2937 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2939 case ISD::NON_EXTLOAD: B = true; break;
2942 if (B && Constant.isAllOnesValue()) {
2943 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2944 // preserve semantics once we get rid of the AND.
2945 SDValue NewLoad(Load, 0);
2946 if (Load->getExtensionType() == ISD::EXTLOAD) {
2947 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2948 Load->getValueType(0), SDLoc(Load),
2949 Load->getChain(), Load->getBasePtr(),
2950 Load->getOffset(), Load->getMemoryVT(),
2951 Load->getMemOperand());
2952 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2953 if (Load->getNumValues() == 3) {
2954 // PRE/POST_INC loads have 3 values.
2955 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2956 NewLoad.getValue(2) };
2957 CombineTo(Load, To, 3, true);
2959 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2963 // Fold the AND away, taking care not to fold to the old load node if we
2965 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2967 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2971 // fold (and (load x), 255) -> (zextload x, i8)
2972 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2973 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2974 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2975 (N0.getOpcode() == ISD::ANY_EXTEND &&
2976 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2977 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2978 LoadSDNode *LN0 = HasAnyExt
2979 ? cast<LoadSDNode>(N0.getOperand(0))
2980 : cast<LoadSDNode>(N0);
2981 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2982 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2983 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2984 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2985 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2986 EVT LoadedVT = LN0->getMemoryVT();
2987 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2989 if (ExtVT == LoadedVT &&
2990 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
2994 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2995 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2996 LN0->getMemOperand());
2998 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2999 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3002 // Do not change the width of a volatile load.
3003 // Do not generate loads of non-round integer types since these can
3004 // be expensive (and would be wrong if the type is not byte sized).
3005 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3006 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3008 EVT PtrType = LN0->getOperand(1).getValueType();
3010 unsigned Alignment = LN0->getAlignment();
3011 SDValue NewPtr = LN0->getBasePtr();
3013 // For big endian targets, we need to add an offset to the pointer
3014 // to load the correct bytes. For little endian systems, we merely
3015 // need to read fewer bytes from the same pointer.
3016 if (TLI.isBigEndian()) {
3017 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3018 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3019 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3020 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
3021 NewPtr, DAG.getConstant(PtrOff, PtrType));
3022 Alignment = MinAlign(Alignment, PtrOff);
3025 AddToWorklist(NewPtr.getNode());
3028 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3029 LN0->getChain(), NewPtr,
3030 LN0->getPointerInfo(),
3031 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3032 LN0->isInvariant(), Alignment, LN0->getAAInfo());
3034 CombineTo(LN0, Load, Load.getValue(1));
3035 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3041 if (SDValue Combined = visitANDLike(N0, N1, N))
3044 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
3045 if (N0.getOpcode() == N1.getOpcode()) {
3046 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3047 if (Tmp.getNode()) return Tmp;
3050 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3051 // fold (and (sra)) -> (and (srl)) when possible.
3052 if (!VT.isVector() &&
3053 SimplifyDemandedBits(SDValue(N, 0)))
3054 return SDValue(N, 0);
3056 // fold (zext_inreg (extload x)) -> (zextload x)
3057 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3058 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3059 EVT MemVT = LN0->getMemoryVT();
3060 // If we zero all the possible extended bits, then we can turn this into
3061 // a zextload if we are running before legalize or the operation is legal.
3062 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3063 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3064 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3065 ((!LegalOperations && !LN0->isVolatile()) ||
3066 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3067 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3068 LN0->getChain(), LN0->getBasePtr(),
3069 MemVT, LN0->getMemOperand());
3071 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3072 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3075 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3076 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3078 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3079 EVT MemVT = LN0->getMemoryVT();
3080 // If we zero all the possible extended bits, then we can turn this into
3081 // a zextload if we are running before legalize or the operation is legal.
3082 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3083 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3084 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3085 ((!LegalOperations && !LN0->isVolatile()) ||
3086 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3087 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3088 LN0->getChain(), LN0->getBasePtr(),
3089 MemVT, LN0->getMemOperand());
3091 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3092 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3095 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3096 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3097 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3098 N0.getOperand(1), false);
3099 if (BSwap.getNode())
3106 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3107 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3108 bool DemandHighBits) {
3109 if (!LegalOperations)
3112 EVT VT = N->getValueType(0);
3113 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3115 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3118 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3119 bool LookPassAnd0 = false;
3120 bool LookPassAnd1 = false;
3121 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3123 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3125 if (N0.getOpcode() == ISD::AND) {
3126 if (!N0.getNode()->hasOneUse())
3128 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3129 if (!N01C || N01C->getZExtValue() != 0xFF00)
3131 N0 = N0.getOperand(0);
3132 LookPassAnd0 = true;
3135 if (N1.getOpcode() == ISD::AND) {
3136 if (!N1.getNode()->hasOneUse())
3138 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3139 if (!N11C || N11C->getZExtValue() != 0xFF)
3141 N1 = N1.getOperand(0);
3142 LookPassAnd1 = true;
3145 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3147 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3149 if (!N0.getNode()->hasOneUse() ||
3150 !N1.getNode()->hasOneUse())
3153 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3154 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3157 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3160 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3161 SDValue N00 = N0->getOperand(0);
3162 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3163 if (!N00.getNode()->hasOneUse())
3165 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3166 if (!N001C || N001C->getZExtValue() != 0xFF)
3168 N00 = N00.getOperand(0);
3169 LookPassAnd0 = true;
3172 SDValue N10 = N1->getOperand(0);
3173 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3174 if (!N10.getNode()->hasOneUse())
3176 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3177 if (!N101C || N101C->getZExtValue() != 0xFF00)
3179 N10 = N10.getOperand(0);
3180 LookPassAnd1 = true;
3186 // Make sure everything beyond the low halfword gets set to zero since the SRL
3187 // 16 will clear the top bits.
3188 unsigned OpSizeInBits = VT.getSizeInBits();
3189 if (DemandHighBits && OpSizeInBits > 16) {
3190 // If the left-shift isn't masked out then the only way this is a bswap is
3191 // if all bits beyond the low 8 are 0. In that case the entire pattern
3192 // reduces to a left shift anyway: leave it for other parts of the combiner.
3196 // However, if the right shift isn't masked out then it might be because
3197 // it's not needed. See if we can spot that too.
3198 if (!LookPassAnd1 &&
3199 !DAG.MaskedValueIsZero(
3200 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3204 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3205 if (OpSizeInBits > 16)
3206 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3207 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3211 /// Return true if the specified node is an element that makes up a 32-bit
3212 /// packed halfword byteswap.
3213 /// ((x & 0x000000ff) << 8) |
3214 /// ((x & 0x0000ff00) >> 8) |
3215 /// ((x & 0x00ff0000) << 8) |
3216 /// ((x & 0xff000000) >> 8)
3217 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3218 if (!N.getNode()->hasOneUse())
3221 unsigned Opc = N.getOpcode();
3222 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3225 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3230 switch (N1C->getZExtValue()) {
3233 case 0xFF: Num = 0; break;
3234 case 0xFF00: Num = 1; break;
3235 case 0xFF0000: Num = 2; break;
3236 case 0xFF000000: Num = 3; break;
3239 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3240 SDValue N0 = N.getOperand(0);
3241 if (Opc == ISD::AND) {
3242 if (Num == 0 || Num == 2) {
3244 // (x >> 8) & 0xff0000
3245 if (N0.getOpcode() != ISD::SRL)
3247 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3248 if (!C || C->getZExtValue() != 8)
3251 // (x << 8) & 0xff00
3252 // (x << 8) & 0xff000000
3253 if (N0.getOpcode() != ISD::SHL)
3255 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3256 if (!C || C->getZExtValue() != 8)
3259 } else if (Opc == ISD::SHL) {
3261 // (x & 0xff0000) << 8
3262 if (Num != 0 && Num != 2)
3264 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3265 if (!C || C->getZExtValue() != 8)
3267 } else { // Opc == ISD::SRL
3268 // (x & 0xff00) >> 8
3269 // (x & 0xff000000) >> 8
3270 if (Num != 1 && Num != 3)
3272 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3273 if (!C || C->getZExtValue() != 8)
3280 Parts[Num] = N0.getOperand(0).getNode();
3284 /// Match a 32-bit packed halfword bswap. That is
3285 /// ((x & 0x000000ff) << 8) |
3286 /// ((x & 0x0000ff00) >> 8) |
3287 /// ((x & 0x00ff0000) << 8) |
3288 /// ((x & 0xff000000) >> 8)
3289 /// => (rotl (bswap x), 16)
3290 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3291 if (!LegalOperations)
3294 EVT VT = N->getValueType(0);
3297 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3301 // (or (or (and), (and)), (or (and), (and)))
3302 // (or (or (or (and), (and)), (and)), (and))
3303 if (N0.getOpcode() != ISD::OR)
3305 SDValue N00 = N0.getOperand(0);
3306 SDValue N01 = N0.getOperand(1);
3307 SDNode *Parts[4] = {};
3309 if (N1.getOpcode() == ISD::OR &&
3310 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3311 // (or (or (and), (and)), (or (and), (and)))
3312 SDValue N000 = N00.getOperand(0);
3313 if (!isBSwapHWordElement(N000, Parts))
3316 SDValue N001 = N00.getOperand(1);
3317 if (!isBSwapHWordElement(N001, Parts))
3319 SDValue N010 = N01.getOperand(0);
3320 if (!isBSwapHWordElement(N010, Parts))
3322 SDValue N011 = N01.getOperand(1);
3323 if (!isBSwapHWordElement(N011, Parts))
3326 // (or (or (or (and), (and)), (and)), (and))
3327 if (!isBSwapHWordElement(N1, Parts))
3329 if (!isBSwapHWordElement(N01, Parts))
3331 if (N00.getOpcode() != ISD::OR)
3333 SDValue N000 = N00.getOperand(0);
3334 if (!isBSwapHWordElement(N000, Parts))
3336 SDValue N001 = N00.getOperand(1);
3337 if (!isBSwapHWordElement(N001, Parts))
3341 // Make sure the parts are all coming from the same node.
3342 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3345 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3346 SDValue(Parts[0],0));
3348 // Result of the bswap should be rotated by 16. If it's not legal, then
3349 // do (x << 16) | (x >> 16).
3350 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3351 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3352 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3353 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3354 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3355 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3356 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3357 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3360 /// This contains all DAGCombine rules which reduce two values combined by
3361 /// an Or operation to a single value \see visitANDLike().
3362 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3363 EVT VT = N1.getValueType();
3364 // fold (or x, undef) -> -1
3365 if (!LegalOperations &&
3366 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3367 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3368 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3370 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3371 SDValue LL, LR, RL, RR, CC0, CC1;
3372 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3373 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3374 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3376 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3377 LL.getValueType().isInteger()) {
3378 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3379 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3380 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3381 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3382 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3383 LR.getValueType(), LL, RL);
3384 AddToWorklist(ORNode.getNode());
3385 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3387 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3388 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3389 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3390 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3391 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3392 LR.getValueType(), LL, RL);
3393 AddToWorklist(ANDNode.getNode());
3394 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3397 // canonicalize equivalent to ll == rl
3398 if (LL == RR && LR == RL) {
3399 Op1 = ISD::getSetCCSwappedOperands(Op1);
3402 if (LL == RL && LR == RR) {
3403 bool isInteger = LL.getValueType().isInteger();
3404 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3405 if (Result != ISD::SETCC_INVALID &&
3406 (!LegalOperations ||
3407 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3408 TLI.isOperationLegal(ISD::SETCC,
3409 getSetCCResultType(N0.getValueType())))))
3410 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3415 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3416 if (N0.getOpcode() == ISD::AND &&
3417 N1.getOpcode() == ISD::AND &&
3418 N0.getOperand(1).getOpcode() == ISD::Constant &&
3419 N1.getOperand(1).getOpcode() == ISD::Constant &&
3420 // Don't increase # computations.
3421 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3422 // We can only do this xform if we know that bits from X that are set in C2
3423 // but not in C1 are already zero. Likewise for Y.
3424 const APInt &LHSMask =
3425 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3426 const APInt &RHSMask =
3427 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3429 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3430 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3431 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3432 N0.getOperand(0), N1.getOperand(0));
3433 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, X,
3434 DAG.getConstant(LHSMask | RHSMask, VT));
3438 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3439 if (N0.getOpcode() == ISD::AND &&
3440 N1.getOpcode() == ISD::AND &&
3441 N0.getOperand(0) == N1.getOperand(0) &&
3442 // Don't increase # computations.
3443 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3444 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3445 N0.getOperand(1), N1.getOperand(1));
3446 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3452 SDValue DAGCombiner::visitOR(SDNode *N) {
3453 SDValue N0 = N->getOperand(0);
3454 SDValue N1 = N->getOperand(1);
3455 EVT VT = N1.getValueType();
3458 if (VT.isVector()) {
3459 SDValue FoldedVOp = SimplifyVBinOp(N);
3460 if (FoldedVOp.getNode()) return FoldedVOp;
3462 // fold (or x, 0) -> x, vector edition
3463 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3465 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3468 // fold (or x, -1) -> -1, vector edition
3469 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3470 // do not return N0, because undef node may exist in N0
3471 return DAG.getConstant(
3472 APInt::getAllOnesValue(
3473 N0.getValueType().getScalarType().getSizeInBits()),
3475 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3476 // do not return N1, because undef node may exist in N1
3477 return DAG.getConstant(
3478 APInt::getAllOnesValue(
3479 N1.getValueType().getScalarType().getSizeInBits()),
3482 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3483 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3484 // Do this only if the resulting shuffle is legal.
3485 if (isa<ShuffleVectorSDNode>(N0) &&
3486 isa<ShuffleVectorSDNode>(N1) &&
3487 // Avoid folding a node with illegal type.
3488 TLI.isTypeLegal(VT) &&
3489 N0->getOperand(1) == N1->getOperand(1) &&
3490 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3491 bool CanFold = true;
3492 unsigned NumElts = VT.getVectorNumElements();
3493 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3494 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3495 // We construct two shuffle masks:
3496 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3497 // and N1 as the second operand.
3498 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3499 // and N0 as the second operand.
3500 // We do this because OR is commutable and therefore there might be
3501 // two ways to fold this node into a shuffle.
3502 SmallVector<int,4> Mask1;
3503 SmallVector<int,4> Mask2;
3505 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3506 int M0 = SV0->getMaskElt(i);
3507 int M1 = SV1->getMaskElt(i);
3509 // Both shuffle indexes are undef. Propagate Undef.
3510 if (M0 < 0 && M1 < 0) {
3511 Mask1.push_back(M0);
3512 Mask2.push_back(M0);
3516 if (M0 < 0 || M1 < 0 ||
3517 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3518 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3523 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3524 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3528 // Fold this sequence only if the resulting shuffle is 'legal'.
3529 if (TLI.isShuffleMaskLegal(Mask1, VT))
3530 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3531 N1->getOperand(0), &Mask1[0]);
3532 if (TLI.isShuffleMaskLegal(Mask2, VT))
3533 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3534 N0->getOperand(0), &Mask2[0]);
3539 // fold (or c1, c2) -> c1|c2
3540 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3541 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3543 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3544 // canonicalize constant to RHS
3546 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3547 // fold (or x, 0) -> x
3548 if (N1C && N1C->isNullValue())
3550 // fold (or x, -1) -> -1
3551 if (N1C && N1C->isAllOnesValue())
3553 // fold (or x, c) -> c iff (x & ~c) == 0
3554 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3557 if (SDValue Combined = visitORLike(N0, N1, N))
3560 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3561 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3562 if (BSwap.getNode())
3564 BSwap = MatchBSwapHWordLow(N, N0, N1);
3565 if (BSwap.getNode())
3569 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3572 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3573 // iff (c1 & c2) == 0.
3574 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3575 isa<ConstantSDNode>(N0.getOperand(1))) {
3576 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3577 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3578 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1))
3580 ISD::AND, SDLoc(N), VT,
3581 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3585 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3586 if (N0.getOpcode() == N1.getOpcode()) {
3587 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3588 if (Tmp.getNode()) return Tmp;
3591 // See if this is some rotate idiom.
3592 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3593 return SDValue(Rot, 0);
3595 // Simplify the operands using demanded-bits information.
3596 if (!VT.isVector() &&
3597 SimplifyDemandedBits(SDValue(N, 0)))
3598 return SDValue(N, 0);
3603 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3604 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3605 if (Op.getOpcode() == ISD::AND) {
3606 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3607 Mask = Op.getOperand(1);
3608 Op = Op.getOperand(0);
3614 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3622 // Return true if we can prove that, whenever Neg and Pos are both in the
3623 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3624 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3626 // (or (shift1 X, Neg), (shift2 X, Pos))
3628 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3629 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3630 // to consider shift amounts with defined behavior.
3631 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3632 // If OpSize is a power of 2 then:
3634 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3635 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3637 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3638 // for the stronger condition:
3640 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3642 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3643 // we can just replace Neg with Neg' for the rest of the function.
3645 // In other cases we check for the even stronger condition:
3647 // Neg == OpSize - Pos [B]
3649 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3650 // behavior if Pos == 0 (and consequently Neg == OpSize).
3652 // We could actually use [A] whenever OpSize is a power of 2, but the
3653 // only extra cases that it would match are those uninteresting ones
3654 // where Neg and Pos are never in range at the same time. E.g. for
3655 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3656 // as well as (sub 32, Pos), but:
3658 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3660 // always invokes undefined behavior for 32-bit X.
3662 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3663 unsigned MaskLoBits = 0;
3664 if (Neg.getOpcode() == ISD::AND &&
3665 isPowerOf2_64(OpSize) &&
3666 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3667 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3668 Neg = Neg.getOperand(0);
3669 MaskLoBits = Log2_64(OpSize);
3672 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3673 if (Neg.getOpcode() != ISD::SUB)
3675 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3678 SDValue NegOp1 = Neg.getOperand(1);
3680 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3681 // Pos'. The truncation is redundant for the purpose of the equality.
3683 Pos.getOpcode() == ISD::AND &&
3684 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3685 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3686 Pos = Pos.getOperand(0);
3688 // The condition we need is now:
3690 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3692 // If NegOp1 == Pos then we need:
3694 // OpSize & Mask == NegC & Mask
3696 // (because "x & Mask" is a truncation and distributes through subtraction).
3699 Width = NegC->getAPIntValue();
3700 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3701 // Then the condition we want to prove becomes:
3703 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3705 // which, again because "x & Mask" is a truncation, becomes:
3707 // NegC & Mask == (OpSize - PosC) & Mask
3708 // OpSize & Mask == (NegC + PosC) & Mask
3709 else if (Pos.getOpcode() == ISD::ADD &&
3710 Pos.getOperand(0) == NegOp1 &&
3711 Pos.getOperand(1).getOpcode() == ISD::Constant)
3712 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3713 NegC->getAPIntValue());
3717 // Now we just need to check that OpSize & Mask == Width & Mask.
3719 // Opsize & Mask is 0 since Mask is Opsize - 1.
3720 return Width.getLoBits(MaskLoBits) == 0;
3721 return Width == OpSize;
3724 // A subroutine of MatchRotate used once we have found an OR of two opposite
3725 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3726 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3727 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3728 // Neg with outer conversions stripped away.
3729 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3730 SDValue Neg, SDValue InnerPos,
3731 SDValue InnerNeg, unsigned PosOpcode,
3732 unsigned NegOpcode, SDLoc DL) {
3733 // fold (or (shl x, (*ext y)),
3734 // (srl x, (*ext (sub 32, y)))) ->
3735 // (rotl x, y) or (rotr x, (sub 32, y))
3737 // fold (or (shl x, (*ext (sub 32, y))),
3738 // (srl x, (*ext y))) ->
3739 // (rotr x, y) or (rotl x, (sub 32, y))
3740 EVT VT = Shifted.getValueType();
3741 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3742 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3743 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3744 HasPos ? Pos : Neg).getNode();
3750 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3751 // idioms for rotate, and if the target supports rotation instructions, generate
3753 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3754 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3755 EVT VT = LHS.getValueType();
3756 if (!TLI.isTypeLegal(VT)) return nullptr;
3758 // The target must have at least one rotate flavor.
3759 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3760 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3761 if (!HasROTL && !HasROTR) return nullptr;
3763 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3764 SDValue LHSShift; // The shift.
3765 SDValue LHSMask; // AND value if any.
3766 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3767 return nullptr; // Not part of a rotate.
3769 SDValue RHSShift; // The shift.
3770 SDValue RHSMask; // AND value if any.
3771 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3772 return nullptr; // Not part of a rotate.
3774 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3775 return nullptr; // Not shifting the same value.
3777 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3778 return nullptr; // Shifts must disagree.
3780 // Canonicalize shl to left side in a shl/srl pair.
3781 if (RHSShift.getOpcode() == ISD::SHL) {
3782 std::swap(LHS, RHS);
3783 std::swap(LHSShift, RHSShift);
3784 std::swap(LHSMask , RHSMask );
3787 unsigned OpSizeInBits = VT.getSizeInBits();
3788 SDValue LHSShiftArg = LHSShift.getOperand(0);
3789 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3790 SDValue RHSShiftArg = RHSShift.getOperand(0);
3791 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3793 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3794 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3795 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3796 RHSShiftAmt.getOpcode() == ISD::Constant) {
3797 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3798 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3799 if ((LShVal + RShVal) != OpSizeInBits)
3802 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3803 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3805 // If there is an AND of either shifted operand, apply it to the result.
3806 if (LHSMask.getNode() || RHSMask.getNode()) {
3807 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3809 if (LHSMask.getNode()) {
3810 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3811 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3813 if (RHSMask.getNode()) {
3814 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3815 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3818 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3821 return Rot.getNode();
3824 // If there is a mask here, and we have a variable shift, we can't be sure
3825 // that we're masking out the right stuff.
3826 if (LHSMask.getNode() || RHSMask.getNode())
3829 // If the shift amount is sign/zext/any-extended just peel it off.
3830 SDValue LExtOp0 = LHSShiftAmt;
3831 SDValue RExtOp0 = RHSShiftAmt;
3832 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3833 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3834 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3835 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3836 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3837 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3838 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3839 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3840 LExtOp0 = LHSShiftAmt.getOperand(0);
3841 RExtOp0 = RHSShiftAmt.getOperand(0);
3844 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3845 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3849 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3850 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3857 SDValue DAGCombiner::visitXOR(SDNode *N) {
3858 SDValue N0 = N->getOperand(0);
3859 SDValue N1 = N->getOperand(1);
3860 EVT VT = N0.getValueType();
3863 if (VT.isVector()) {
3864 SDValue FoldedVOp = SimplifyVBinOp(N);
3865 if (FoldedVOp.getNode()) return FoldedVOp;
3867 // fold (xor x, 0) -> x, vector edition
3868 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3870 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3874 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3875 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3876 return DAG.getConstant(0, VT);
3877 // fold (xor x, undef) -> undef
3878 if (N0.getOpcode() == ISD::UNDEF)
3880 if (N1.getOpcode() == ISD::UNDEF)
3882 // fold (xor c1, c2) -> c1^c2
3883 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3884 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3886 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3887 // canonicalize constant to RHS
3889 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3890 // fold (xor x, 0) -> x
3891 if (N1C && N1C->isNullValue())
3894 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3898 // fold !(x cc y) -> (x !cc y)
3899 SDValue LHS, RHS, CC;
3900 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3901 bool isInt = LHS.getValueType().isInteger();
3902 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3905 if (!LegalOperations ||
3906 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3907 switch (N0.getOpcode()) {
3909 llvm_unreachable("Unhandled SetCC Equivalent!");
3911 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3912 case ISD::SELECT_CC:
3913 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3914 N0.getOperand(3), NotCC);
3919 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3920 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3921 N0.getNode()->hasOneUse() &&
3922 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3923 SDValue V = N0.getOperand(0);
3924 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3925 DAG.getConstant(1, V.getValueType()));
3926 AddToWorklist(V.getNode());
3927 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3930 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3931 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3932 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3933 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3934 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3935 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3936 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3937 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3938 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3939 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3942 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3943 if (N1C && N1C->isAllOnesValue() &&
3944 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3945 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3946 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3947 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3948 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3949 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3950 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3951 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3954 // fold (xor (and x, y), y) -> (and (not x), y)
3955 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3956 N0->getOperand(1) == N1) {
3957 SDValue X = N0->getOperand(0);
3958 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3959 AddToWorklist(NotX.getNode());
3960 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3962 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3963 if (N1C && N0.getOpcode() == ISD::XOR) {
3964 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3965 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3967 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3968 DAG.getConstant(N1C->getAPIntValue() ^
3969 N00C->getAPIntValue(), VT));
3971 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3972 DAG.getConstant(N1C->getAPIntValue() ^
3973 N01C->getAPIntValue(), VT));
3975 // fold (xor x, x) -> 0
3977 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3979 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3980 if (N0.getOpcode() == N1.getOpcode()) {
3981 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3982 if (Tmp.getNode()) return Tmp;
3985 // Simplify the expression using non-local knowledge.
3986 if (!VT.isVector() &&
3987 SimplifyDemandedBits(SDValue(N, 0)))
3988 return SDValue(N, 0);
3993 /// Handle transforms common to the three shifts, when the shift amount is a
3995 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3996 // We can't and shouldn't fold opaque constants.
3997 if (Amt->isOpaque())
4000 SDNode *LHS = N->getOperand(0).getNode();
4001 if (!LHS->hasOneUse()) return SDValue();
4003 // We want to pull some binops through shifts, so that we have (and (shift))
4004 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
4005 // thing happens with address calculations, so it's important to canonicalize
4007 bool HighBitSet = false; // Can we transform this if the high bit is set?
4009 switch (LHS->getOpcode()) {
4010 default: return SDValue();
4013 HighBitSet = false; // We can only transform sra if the high bit is clear.
4016 HighBitSet = true; // We can only transform sra if the high bit is set.
4019 if (N->getOpcode() != ISD::SHL)
4020 return SDValue(); // only shl(add) not sr[al](add).
4021 HighBitSet = false; // We can only transform sra if the high bit is clear.
4025 // We require the RHS of the binop to be a constant and not opaque as well.
4026 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
4027 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
4029 // FIXME: disable this unless the input to the binop is a shift by a constant.
4030 // If it is not a shift, it pessimizes some common cases like:
4032 // void foo(int *X, int i) { X[i & 1235] = 1; }
4033 // int bar(int *X, int i) { return X[i & 255]; }
4034 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4035 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4036 BinOpLHSVal->getOpcode() != ISD::SRA &&
4037 BinOpLHSVal->getOpcode() != ISD::SRL) ||
4038 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4041 EVT VT = N->getValueType(0);
4043 // If this is a signed shift right, and the high bit is modified by the
4044 // logical operation, do not perform the transformation. The highBitSet
4045 // boolean indicates the value of the high bit of the constant which would
4046 // cause it to be modified for this operation.
4047 if (N->getOpcode() == ISD::SRA) {
4048 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4049 if (BinOpRHSSignSet != HighBitSet)
4053 if (!TLI.isDesirableToCommuteWithShift(LHS))
4056 // Fold the constants, shifting the binop RHS by the shift amount.
4057 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4059 LHS->getOperand(1), N->getOperand(1));
4060 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4062 // Create the new shift.
4063 SDValue NewShift = DAG.getNode(N->getOpcode(),
4064 SDLoc(LHS->getOperand(0)),
4065 VT, LHS->getOperand(0), N->getOperand(1));
4067 // Create the new binop.
4068 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4071 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4072 assert(N->getOpcode() == ISD::TRUNCATE);
4073 assert(N->getOperand(0).getOpcode() == ISD::AND);
4075 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4076 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4077 SDValue N01 = N->getOperand(0).getOperand(1);
4079 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4080 EVT TruncVT = N->getValueType(0);
4081 SDValue N00 = N->getOperand(0).getOperand(0);
4082 APInt TruncC = N01C->getAPIntValue();
4083 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4085 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
4086 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
4087 DAG.getConstant(TruncC, TruncVT));
4094 SDValue DAGCombiner::visitRotate(SDNode *N) {
4095 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4096 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4097 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4098 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4099 if (NewOp1.getNode())
4100 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4101 N->getOperand(0), NewOp1);
4106 SDValue DAGCombiner::visitSHL(SDNode *N) {
4107 SDValue N0 = N->getOperand(0);
4108 SDValue N1 = N->getOperand(1);
4109 EVT VT = N0.getValueType();
4110 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4113 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4114 if (VT.isVector()) {
4115 SDValue FoldedVOp = SimplifyVBinOp(N);
4116 if (FoldedVOp.getNode()) return FoldedVOp;
4118 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4119 // If setcc produces all-one true value then:
4120 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4121 if (N1CV && N1CV->isConstant()) {
4122 if (N0.getOpcode() == ISD::AND) {
4123 SDValue N00 = N0->getOperand(0);
4124 SDValue N01 = N0->getOperand(1);
4125 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4127 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4128 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4129 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4130 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV))
4131 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4134 N1C = isConstOrConstSplat(N1);
4139 // fold (shl c1, c2) -> c1<<c2
4140 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4142 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4143 // fold (shl 0, x) -> 0
4144 if (N0C && N0C->isNullValue())
4146 // fold (shl x, c >= size(x)) -> undef
4147 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4148 return DAG.getUNDEF(VT);
4149 // fold (shl x, 0) -> x
4150 if (N1C && N1C->isNullValue())
4152 // fold (shl undef, x) -> 0
4153 if (N0.getOpcode() == ISD::UNDEF)
4154 return DAG.getConstant(0, VT);
4155 // if (shl x, c) is known to be zero, return 0
4156 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4157 APInt::getAllOnesValue(OpSizeInBits)))
4158 return DAG.getConstant(0, VT);
4159 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4160 if (N1.getOpcode() == ISD::TRUNCATE &&
4161 N1.getOperand(0).getOpcode() == ISD::AND) {
4162 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4163 if (NewOp1.getNode())
4164 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4167 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4168 return SDValue(N, 0);
4170 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4171 if (N1C && N0.getOpcode() == ISD::SHL) {
4172 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4173 uint64_t c1 = N0C1->getZExtValue();
4174 uint64_t c2 = N1C->getZExtValue();
4175 if (c1 + c2 >= OpSizeInBits)
4176 return DAG.getConstant(0, VT);
4177 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4178 DAG.getConstant(c1 + c2, N1.getValueType()));
4182 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4183 // For this to be valid, the second form must not preserve any of the bits
4184 // that are shifted out by the inner shift in the first form. This means
4185 // the outer shift size must be >= the number of bits added by the ext.
4186 // As a corollary, we don't care what kind of ext it is.
4187 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4188 N0.getOpcode() == ISD::ANY_EXTEND ||
4189 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4190 N0.getOperand(0).getOpcode() == ISD::SHL) {
4191 SDValue N0Op0 = N0.getOperand(0);
4192 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4193 uint64_t c1 = N0Op0C1->getZExtValue();
4194 uint64_t c2 = N1C->getZExtValue();
4195 EVT InnerShiftVT = N0Op0.getValueType();
4196 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4197 if (c2 >= OpSizeInBits - InnerShiftSize) {
4198 if (c1 + c2 >= OpSizeInBits)
4199 return DAG.getConstant(0, VT);
4200 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4201 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4202 N0Op0->getOperand(0)),
4203 DAG.getConstant(c1 + c2, N1.getValueType()));
4208 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4209 // Only fold this if the inner zext has no other uses to avoid increasing
4210 // the total number of instructions.
4211 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4212 N0.getOperand(0).getOpcode() == ISD::SRL) {
4213 SDValue N0Op0 = N0.getOperand(0);
4214 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4215 uint64_t c1 = N0Op0C1->getZExtValue();
4216 if (c1 < VT.getScalarSizeInBits()) {
4217 uint64_t c2 = N1C->getZExtValue();
4219 SDValue NewOp0 = N0.getOperand(0);
4220 EVT CountVT = NewOp0.getOperand(1).getValueType();
4221 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4222 NewOp0, DAG.getConstant(c2, CountVT));
4223 AddToWorklist(NewSHL.getNode());
4224 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4230 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4231 // (and (srl x, (sub c1, c2), MASK)
4232 // Only fold this if the inner shift has no other uses -- if it does, folding
4233 // this will increase the total number of instructions.
4234 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4235 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4236 uint64_t c1 = N0C1->getZExtValue();
4237 if (c1 < OpSizeInBits) {
4238 uint64_t c2 = N1C->getZExtValue();
4239 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4242 Mask = Mask.shl(c2 - c1);
4243 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4244 DAG.getConstant(c2 - c1, N1.getValueType()));
4246 Mask = Mask.lshr(c1 - c2);
4247 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4248 DAG.getConstant(c1 - c2, N1.getValueType()));
4250 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4251 DAG.getConstant(Mask, VT));
4255 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4256 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4257 unsigned BitSize = VT.getScalarSizeInBits();
4258 SDValue HiBitsMask =
4259 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4260 BitSize - N1C->getZExtValue()), VT);
4261 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4265 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4266 // Variant of version done on multiply, except mul by a power of 2 is turned
4269 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4270 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4271 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4272 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4273 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4274 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4278 SDValue NewSHL = visitShiftByConstant(N, N1C);
4279 if (NewSHL.getNode())
4286 SDValue DAGCombiner::visitSRA(SDNode *N) {
4287 SDValue N0 = N->getOperand(0);
4288 SDValue N1 = N->getOperand(1);
4289 EVT VT = N0.getValueType();
4290 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4293 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4294 if (VT.isVector()) {
4295 SDValue FoldedVOp = SimplifyVBinOp(N);
4296 if (FoldedVOp.getNode()) return FoldedVOp;
4298 N1C = isConstOrConstSplat(N1);
4301 // fold (sra c1, c2) -> (sra c1, c2)
4302 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4304 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4305 // fold (sra 0, x) -> 0
4306 if (N0C && N0C->isNullValue())
4308 // fold (sra -1, x) -> -1
4309 if (N0C && N0C->isAllOnesValue())
4311 // fold (sra x, (setge c, size(x))) -> undef
4312 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4313 return DAG.getUNDEF(VT);
4314 // fold (sra x, 0) -> x
4315 if (N1C && N1C->isNullValue())
4317 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4319 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4320 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4321 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4323 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4324 ExtVT, VT.getVectorNumElements());
4325 if ((!LegalOperations ||
4326 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4327 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4328 N0.getOperand(0), DAG.getValueType(ExtVT));
4331 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4332 if (N1C && N0.getOpcode() == ISD::SRA) {
4333 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4334 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4335 if (Sum >= OpSizeInBits)
4336 Sum = OpSizeInBits - 1;
4337 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4338 DAG.getConstant(Sum, N1.getValueType()));
4342 // fold (sra (shl X, m), (sub result_size, n))
4343 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4344 // result_size - n != m.
4345 // If truncate is free for the target sext(shl) is likely to result in better
4347 if (N0.getOpcode() == ISD::SHL && N1C) {
4348 // Get the two constanst of the shifts, CN0 = m, CN = n.
4349 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4351 LLVMContext &Ctx = *DAG.getContext();
4352 // Determine what the truncate's result bitsize and type would be.
4353 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4356 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4358 // Determine the residual right-shift amount.
4359 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4361 // If the shift is not a no-op (in which case this should be just a sign
4362 // extend already), the truncated to type is legal, sign_extend is legal
4363 // on that type, and the truncate to that type is both legal and free,
4364 // perform the transform.
4365 if ((ShiftAmt > 0) &&
4366 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4367 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4368 TLI.isTruncateFree(VT, TruncVT)) {
4370 SDValue Amt = DAG.getConstant(ShiftAmt,
4371 getShiftAmountTy(N0.getOperand(0).getValueType()));
4372 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4373 N0.getOperand(0), Amt);
4374 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4376 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4377 N->getValueType(0), Trunc);
4382 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4383 if (N1.getOpcode() == ISD::TRUNCATE &&
4384 N1.getOperand(0).getOpcode() == ISD::AND) {
4385 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4386 if (NewOp1.getNode())
4387 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4390 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4391 // if c1 is equal to the number of bits the trunc removes
4392 if (N0.getOpcode() == ISD::TRUNCATE &&
4393 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4394 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4395 N0.getOperand(0).hasOneUse() &&
4396 N0.getOperand(0).getOperand(1).hasOneUse() &&
4398 SDValue N0Op0 = N0.getOperand(0);
4399 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4400 unsigned LargeShiftVal = LargeShift->getZExtValue();
4401 EVT LargeVT = N0Op0.getValueType();
4403 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4405 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4406 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4407 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4408 N0Op0.getOperand(0), Amt);
4409 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4414 // Simplify, based on bits shifted out of the LHS.
4415 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4416 return SDValue(N, 0);
4419 // If the sign bit is known to be zero, switch this to a SRL.
4420 if (DAG.SignBitIsZero(N0))
4421 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4424 SDValue NewSRA = visitShiftByConstant(N, N1C);
4425 if (NewSRA.getNode())
4432 SDValue DAGCombiner::visitSRL(SDNode *N) {
4433 SDValue N0 = N->getOperand(0);
4434 SDValue N1 = N->getOperand(1);
4435 EVT VT = N0.getValueType();
4436 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4439 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4440 if (VT.isVector()) {
4441 SDValue FoldedVOp = SimplifyVBinOp(N);
4442 if (FoldedVOp.getNode()) return FoldedVOp;
4444 N1C = isConstOrConstSplat(N1);
4447 // fold (srl c1, c2) -> c1 >>u c2
4448 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4450 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4451 // fold (srl 0, x) -> 0
4452 if (N0C && N0C->isNullValue())
4454 // fold (srl x, c >= size(x)) -> undef
4455 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4456 return DAG.getUNDEF(VT);
4457 // fold (srl x, 0) -> x
4458 if (N1C && N1C->isNullValue())
4460 // if (srl x, c) is known to be zero, return 0
4461 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4462 APInt::getAllOnesValue(OpSizeInBits)))
4463 return DAG.getConstant(0, VT);
4465 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4466 if (N1C && N0.getOpcode() == ISD::SRL) {
4467 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4468 uint64_t c1 = N01C->getZExtValue();
4469 uint64_t c2 = N1C->getZExtValue();
4470 if (c1 + c2 >= OpSizeInBits)
4471 return DAG.getConstant(0, VT);
4472 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4473 DAG.getConstant(c1 + c2, N1.getValueType()));
4477 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4478 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4479 N0.getOperand(0).getOpcode() == ISD::SRL &&
4480 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4482 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4483 uint64_t c2 = N1C->getZExtValue();
4484 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4485 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4486 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4487 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4488 if (c1 + OpSizeInBits == InnerShiftSize) {
4489 if (c1 + c2 >= InnerShiftSize)
4490 return DAG.getConstant(0, VT);
4491 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4492 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4493 N0.getOperand(0)->getOperand(0),
4494 DAG.getConstant(c1 + c2, ShiftCountVT)));
4498 // fold (srl (shl x, c), c) -> (and x, cst2)
4499 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4500 unsigned BitSize = N0.getScalarValueSizeInBits();
4501 if (BitSize <= 64) {
4502 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4503 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4504 DAG.getConstant(~0ULL >> ShAmt, VT));
4508 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4509 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4510 // Shifting in all undef bits?
4511 EVT SmallVT = N0.getOperand(0).getValueType();
4512 unsigned BitSize = SmallVT.getScalarSizeInBits();
4513 if (N1C->getZExtValue() >= BitSize)
4514 return DAG.getUNDEF(VT);
4516 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4517 uint64_t ShiftAmt = N1C->getZExtValue();
4518 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4520 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4521 AddToWorklist(SmallShift.getNode());
4522 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4523 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4524 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4525 DAG.getConstant(Mask, VT));
4529 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4530 // bit, which is unmodified by sra.
4531 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4532 if (N0.getOpcode() == ISD::SRA)
4533 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4536 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4537 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4538 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4539 APInt KnownZero, KnownOne;
4540 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4542 // If any of the input bits are KnownOne, then the input couldn't be all
4543 // zeros, thus the result of the srl will always be zero.
4544 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4546 // If all of the bits input the to ctlz node are known to be zero, then
4547 // the result of the ctlz is "32" and the result of the shift is one.
4548 APInt UnknownBits = ~KnownZero;
4549 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4551 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4552 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4553 // Okay, we know that only that the single bit specified by UnknownBits
4554 // could be set on input to the CTLZ node. If this bit is set, the SRL
4555 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4556 // to an SRL/XOR pair, which is likely to simplify more.
4557 unsigned ShAmt = UnknownBits.countTrailingZeros();
4558 SDValue Op = N0.getOperand(0);
4561 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4562 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4563 AddToWorklist(Op.getNode());
4566 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4567 Op, DAG.getConstant(1, VT));
4571 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4572 if (N1.getOpcode() == ISD::TRUNCATE &&
4573 N1.getOperand(0).getOpcode() == ISD::AND) {
4574 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4575 if (NewOp1.getNode())
4576 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4579 // fold operands of srl based on knowledge that the low bits are not
4581 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4582 return SDValue(N, 0);
4585 SDValue NewSRL = visitShiftByConstant(N, N1C);
4586 if (NewSRL.getNode())
4590 // Attempt to convert a srl of a load into a narrower zero-extending load.
4591 SDValue NarrowLoad = ReduceLoadWidth(N);
4592 if (NarrowLoad.getNode())
4595 // Here is a common situation. We want to optimize:
4598 // %b = and i32 %a, 2
4599 // %c = srl i32 %b, 1
4600 // brcond i32 %c ...
4606 // %c = setcc eq %b, 0
4609 // However when after the source operand of SRL is optimized into AND, the SRL
4610 // itself may not be optimized further. Look for it and add the BRCOND into
4612 if (N->hasOneUse()) {
4613 SDNode *Use = *N->use_begin();
4614 if (Use->getOpcode() == ISD::BRCOND)
4616 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4617 // Also look pass the truncate.
4618 Use = *Use->use_begin();
4619 if (Use->getOpcode() == ISD::BRCOND)
4627 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4628 SDValue N0 = N->getOperand(0);
4629 EVT VT = N->getValueType(0);
4631 // fold (ctlz c1) -> c2
4632 if (isa<ConstantSDNode>(N0))
4633 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4637 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4638 SDValue N0 = N->getOperand(0);
4639 EVT VT = N->getValueType(0);
4641 // fold (ctlz_zero_undef c1) -> c2
4642 if (isa<ConstantSDNode>(N0))
4643 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4647 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4648 SDValue N0 = N->getOperand(0);
4649 EVT VT = N->getValueType(0);
4651 // fold (cttz c1) -> c2
4652 if (isa<ConstantSDNode>(N0))
4653 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4657 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4658 SDValue N0 = N->getOperand(0);
4659 EVT VT = N->getValueType(0);
4661 // fold (cttz_zero_undef c1) -> c2
4662 if (isa<ConstantSDNode>(N0))
4663 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4667 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4668 SDValue N0 = N->getOperand(0);
4669 EVT VT = N->getValueType(0);
4671 // fold (ctpop c1) -> c2
4672 if (isa<ConstantSDNode>(N0))
4673 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4678 /// \brief Generate Min/Max node
4679 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4680 SDValue True, SDValue False,
4681 ISD::CondCode CC, const TargetLowering &TLI,
4682 SelectionDAG &DAG) {
4683 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4693 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4694 if (TLI.isOperationLegal(Opcode, VT))
4695 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4704 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4705 if (TLI.isOperationLegal(Opcode, VT))
4706 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4714 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4715 SDValue N0 = N->getOperand(0);
4716 SDValue N1 = N->getOperand(1);
4717 SDValue N2 = N->getOperand(2);
4718 EVT VT = N->getValueType(0);
4719 EVT VT0 = N0.getValueType();
4721 // fold (select C, X, X) -> X
4724 // fold (select true, X, Y) -> X
4725 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4726 if (N0C && !N0C->isNullValue())
4728 // fold (select false, X, Y) -> Y
4729 if (N0C && N0C->isNullValue())
4731 // fold (select C, 1, X) -> (or C, X)
4732 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4733 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4734 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4735 // fold (select C, 0, 1) -> (xor C, 1)
4736 // We can't do this reliably if integer based booleans have different contents
4737 // to floating point based booleans. This is because we can't tell whether we
4738 // have an integer-based boolean or a floating-point-based boolean unless we
4739 // can find the SETCC that produced it and inspect its operands. This is
4740 // fairly easy if C is the SETCC node, but it can potentially be
4741 // undiscoverable (or not reasonably discoverable). For example, it could be
4742 // in another basic block or it could require searching a complicated
4744 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4745 if (VT.isInteger() &&
4746 (VT0 == MVT::i1 || (VT0.isInteger() &&
4747 TLI.getBooleanContents(false, false) ==
4748 TLI.getBooleanContents(false, true) &&
4749 TLI.getBooleanContents(false, false) ==
4750 TargetLowering::ZeroOrOneBooleanContent)) &&
4751 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4754 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4755 N0, DAG.getConstant(1, VT0));
4756 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4757 N0, DAG.getConstant(1, VT0));
4758 AddToWorklist(XORNode.getNode());
4760 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4761 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4763 // fold (select C, 0, X) -> (and (not C), X)
4764 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4765 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4766 AddToWorklist(NOTNode.getNode());
4767 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4769 // fold (select C, X, 1) -> (or (not C), X)
4770 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4771 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4772 AddToWorklist(NOTNode.getNode());
4773 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4775 // fold (select C, X, 0) -> (and C, X)
4776 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4777 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4778 // fold (select X, X, Y) -> (or X, Y)
4779 // fold (select X, 1, Y) -> (or X, Y)
4780 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4781 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4782 // fold (select X, Y, X) -> (and X, Y)
4783 // fold (select X, Y, 0) -> (and X, Y)
4784 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4785 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4787 // If we can fold this based on the true/false value, do so.
4788 if (SimplifySelectOps(N, N1, N2))
4789 return SDValue(N, 0); // Don't revisit N.
4791 // fold selects based on a setcc into other things, such as min/max/abs
4792 if (N0.getOpcode() == ISD::SETCC) {
4793 // select x, y (fcmp lt x, y) -> fminnum x, y
4794 // select x, y (fcmp gt x, y) -> fmaxnum x, y
4796 // This is OK if we don't care about what happens if either operand is a
4800 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4801 // no signed zeros as well as no nans.
4802 const TargetOptions &Options = DAG.getTarget().Options;
4803 if (Options.UnsafeFPMath &&
4804 VT.isFloatingPoint() && N0.hasOneUse() &&
4805 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4806 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4809 combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4810 N1, N2, CC, TLI, DAG);
4815 if ((!LegalOperations &&
4816 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4817 TLI.isOperationLegal(ISD::SELECT_CC, VT))
4818 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4819 N0.getOperand(0), N0.getOperand(1),
4820 N1, N2, N0.getOperand(2));
4821 return SimplifySelect(SDLoc(N), N0, N1, N2);
4824 if (VT0 == MVT::i1) {
4825 if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4826 // select (and Cond0, Cond1), X, Y
4827 // -> select Cond0, (select Cond1, X, Y), Y
4828 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4829 SDValue Cond0 = N0->getOperand(0);
4830 SDValue Cond1 = N0->getOperand(1);
4831 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4832 N1.getValueType(), Cond1, N1, N2);
4833 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
4836 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
4837 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
4838 SDValue Cond0 = N0->getOperand(0);
4839 SDValue Cond1 = N0->getOperand(1);
4840 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4841 N1.getValueType(), Cond1, N1, N2);
4842 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
4847 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
4848 if (N1->getOpcode() == ISD::SELECT) {
4849 SDValue N1_0 = N1->getOperand(0);
4850 SDValue N1_1 = N1->getOperand(1);
4851 SDValue N1_2 = N1->getOperand(2);
4853 // Create the actual and node if we can generate good code for it.
4854 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4855 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
4857 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
4860 // Otherwise see if we can optimize the "and" to a better pattern.
4861 if (SDValue Combined = visitANDLike(N0, N1_0, N))
4862 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4866 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
4867 if (N2->getOpcode() == ISD::SELECT) {
4868 SDValue N2_0 = N2->getOperand(0);
4869 SDValue N2_1 = N2->getOperand(1);
4870 SDValue N2_2 = N2->getOperand(2);
4872 // Create the actual or node if we can generate good code for it.
4873 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4874 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
4876 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
4879 // Otherwise see if we can optimize to a better pattern.
4880 if (SDValue Combined = visitORLike(N0, N2_0, N))
4881 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4891 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4894 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4896 // Split the inputs.
4897 SDValue Lo, Hi, LL, LH, RL, RH;
4898 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4899 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4901 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4902 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4904 return std::make_pair(Lo, Hi);
4907 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4908 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4909 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4911 SDValue Cond = N->getOperand(0);
4912 SDValue LHS = N->getOperand(1);
4913 SDValue RHS = N->getOperand(2);
4914 EVT VT = N->getValueType(0);
4915 int NumElems = VT.getVectorNumElements();
4916 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4917 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4918 Cond.getOpcode() == ISD::BUILD_VECTOR);
4920 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4921 // binary ones here.
4922 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4925 // We're sure we have an even number of elements due to the
4926 // concat_vectors we have as arguments to vselect.
4927 // Skip BV elements until we find one that's not an UNDEF
4928 // After we find an UNDEF element, keep looping until we get to half the
4929 // length of the BV and see if all the non-undef nodes are the same.
4930 ConstantSDNode *BottomHalf = nullptr;
4931 for (int i = 0; i < NumElems / 2; ++i) {
4932 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4935 if (BottomHalf == nullptr)
4936 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4937 else if (Cond->getOperand(i).getNode() != BottomHalf)
4941 // Do the same for the second half of the BuildVector
4942 ConstantSDNode *TopHalf = nullptr;
4943 for (int i = NumElems / 2; i < NumElems; ++i) {
4944 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4947 if (TopHalf == nullptr)
4948 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4949 else if (Cond->getOperand(i).getNode() != TopHalf)
4953 assert(TopHalf && BottomHalf &&
4954 "One half of the selector was all UNDEFs and the other was all the "
4955 "same value. This should have been addressed before this function.");
4957 ISD::CONCAT_VECTORS, dl, VT,
4958 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4959 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4962 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
4964 if (Level >= AfterLegalizeTypes)
4967 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
4968 SDValue Mask = MST->getMask();
4969 SDValue Data = MST->getValue();
4972 // If the MSTORE data type requires splitting and the mask is provided by a
4973 // SETCC, then split both nodes and its operands before legalization. This
4974 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4975 // and enables future optimizations (e.g. min/max pattern matching on X86).
4976 if (Mask.getOpcode() == ISD::SETCC) {
4978 // Check if any splitting is required.
4979 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
4980 TargetLowering::TypeSplitVector)
4983 SDValue MaskLo, MaskHi, Lo, Hi;
4984 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
4987 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
4989 SDValue Chain = MST->getChain();
4990 SDValue Ptr = MST->getBasePtr();
4992 EVT MemoryVT = MST->getMemoryVT();
4993 unsigned Alignment = MST->getOriginalAlignment();
4995 // if Alignment is equal to the vector size,
4996 // take the half of it for the second part
4997 unsigned SecondHalfAlignment =
4998 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
4999 Alignment/2 : Alignment;
5001 EVT LoMemVT, HiMemVT;
5002 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5004 SDValue DataLo, DataHi;
5005 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5007 MachineMemOperand *MMO = DAG.getMachineFunction().
5008 getMachineMemOperand(MST->getPointerInfo(),
5009 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5010 Alignment, MST->getAAInfo(), MST->getRanges());
5012 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5013 MST->isTruncatingStore());
5015 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5016 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5017 DAG.getConstant(IncrementSize, Ptr.getValueType()));
5019 MMO = DAG.getMachineFunction().
5020 getMachineMemOperand(MST->getPointerInfo(),
5021 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
5022 SecondHalfAlignment, MST->getAAInfo(),
5025 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5026 MST->isTruncatingStore());
5028 AddToWorklist(Lo.getNode());
5029 AddToWorklist(Hi.getNode());
5031 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5036 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5038 if (Level >= AfterLegalizeTypes)
5041 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5042 SDValue Mask = MLD->getMask();
5045 // If the MLOAD result requires splitting and the mask is provided by a
5046 // SETCC, then split both nodes and its operands before legalization. This
5047 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5048 // and enables future optimizations (e.g. min/max pattern matching on X86).
5050 if (Mask.getOpcode() == ISD::SETCC) {
5051 EVT VT = N->getValueType(0);
5053 // Check if any splitting is required.
5054 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5055 TargetLowering::TypeSplitVector)
5058 SDValue MaskLo, MaskHi, Lo, Hi;
5059 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5061 SDValue Src0 = MLD->getSrc0();
5062 SDValue Src0Lo, Src0Hi;
5063 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5066 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5068 SDValue Chain = MLD->getChain();
5069 SDValue Ptr = MLD->getBasePtr();
5070 EVT MemoryVT = MLD->getMemoryVT();
5071 unsigned Alignment = MLD->getOriginalAlignment();
5073 // if Alignment is equal to the vector size,
5074 // take the half of it for the second part
5075 unsigned SecondHalfAlignment =
5076 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5077 Alignment/2 : Alignment;
5079 EVT LoMemVT, HiMemVT;
5080 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5082 MachineMemOperand *MMO = DAG.getMachineFunction().
5083 getMachineMemOperand(MLD->getPointerInfo(),
5084 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5085 Alignment, MLD->getAAInfo(), MLD->getRanges());
5087 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5090 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5091 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5092 DAG.getConstant(IncrementSize, Ptr.getValueType()));
5094 MMO = DAG.getMachineFunction().
5095 getMachineMemOperand(MLD->getPointerInfo(),
5096 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
5097 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5099 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5102 AddToWorklist(Lo.getNode());
5103 AddToWorklist(Hi.getNode());
5105 // Build a factor node to remember that this load is independent of the
5107 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5110 // Legalized the chain result - switch anything that used the old chain to
5112 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5114 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5116 SDValue RetOps[] = { LoadRes, Chain };
5117 return DAG.getMergeValues(RetOps, DL);
5122 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5123 SDValue N0 = N->getOperand(0);
5124 SDValue N1 = N->getOperand(1);
5125 SDValue N2 = N->getOperand(2);
5128 // Canonicalize integer abs.
5129 // vselect (setg[te] X, 0), X, -X ->
5130 // vselect (setgt X, -1), X, -X ->
5131 // vselect (setl[te] X, 0), -X, X ->
5132 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5133 if (N0.getOpcode() == ISD::SETCC) {
5134 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5135 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5137 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5139 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5140 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5141 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5142 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5143 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5144 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5145 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5148 EVT VT = LHS.getValueType();
5149 SDValue Shift = DAG.getNode(
5150 ISD::SRA, DL, VT, LHS,
5151 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
5152 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5153 AddToWorklist(Shift.getNode());
5154 AddToWorklist(Add.getNode());
5155 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5159 // If the VSELECT result requires splitting and the mask is provided by a
5160 // SETCC, then split both nodes and its operands before legalization. This
5161 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5162 // and enables future optimizations (e.g. min/max pattern matching on X86).
5163 if (N0.getOpcode() == ISD::SETCC) {
5164 EVT VT = N->getValueType(0);
5166 // Check if any splitting is required.
5167 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5168 TargetLowering::TypeSplitVector)
5171 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5172 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5173 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5174 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5176 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5177 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5179 // Add the new VSELECT nodes to the work list in case they need to be split
5181 AddToWorklist(Lo.getNode());
5182 AddToWorklist(Hi.getNode());
5184 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5187 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5188 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5190 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5191 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5194 // The ConvertSelectToConcatVector function is assuming both the above
5195 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5197 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5198 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5199 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5200 SDValue CV = ConvertSelectToConcatVector(N, DAG);
5208 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5209 SDValue N0 = N->getOperand(0);
5210 SDValue N1 = N->getOperand(1);
5211 SDValue N2 = N->getOperand(2);
5212 SDValue N3 = N->getOperand(3);
5213 SDValue N4 = N->getOperand(4);
5214 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5216 // fold select_cc lhs, rhs, x, x, cc -> x
5220 // Determine if the condition we're dealing with is constant
5221 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5222 N0, N1, CC, SDLoc(N), false);
5223 if (SCC.getNode()) {
5224 AddToWorklist(SCC.getNode());
5226 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5227 if (!SCCC->isNullValue())
5228 return N2; // cond always true -> true val
5230 return N3; // cond always false -> false val
5231 } else if (SCC->getOpcode() == ISD::UNDEF) {
5232 // When the condition is UNDEF, just return the first operand. This is
5233 // coherent the DAG creation, no setcc node is created in this case
5235 } else if (SCC.getOpcode() == ISD::SETCC) {
5236 // Fold to a simpler select_cc
5237 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5238 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5243 // If we can fold this based on the true/false value, do so.
5244 if (SimplifySelectOps(N, N2, N3))
5245 return SDValue(N, 0); // Don't revisit N.
5247 // fold select_cc into other things, such as min/max/abs
5248 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5251 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5252 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5253 cast<CondCodeSDNode>(N->getOperand(2))->get(),
5257 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5258 // dag node into a ConstantSDNode or a build_vector of constants.
5259 // This function is called by the DAGCombiner when visiting sext/zext/aext
5260 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5261 // Vector extends are not folded if operations are legal; this is to
5262 // avoid introducing illegal build_vector dag nodes.
5263 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5264 SelectionDAG &DAG, bool LegalTypes,
5265 bool LegalOperations) {
5266 unsigned Opcode = N->getOpcode();
5267 SDValue N0 = N->getOperand(0);
5268 EVT VT = N->getValueType(0);
5270 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5271 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5273 // fold (sext c1) -> c1
5274 // fold (zext c1) -> c1
5275 // fold (aext c1) -> c1
5276 if (isa<ConstantSDNode>(N0))
5277 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5279 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5280 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5281 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5282 EVT SVT = VT.getScalarType();
5283 if (!(VT.isVector() &&
5284 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5285 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5288 // We can fold this node into a build_vector.
5289 unsigned VTBits = SVT.getSizeInBits();
5290 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5291 unsigned ShAmt = VTBits - EVTBits;
5292 SmallVector<SDValue, 8> Elts;
5293 unsigned NumElts = N0->getNumOperands();
5296 for (unsigned i=0; i != NumElts; ++i) {
5297 SDValue Op = N0->getOperand(i);
5298 if (Op->getOpcode() == ISD::UNDEF) {
5299 Elts.push_back(DAG.getUNDEF(SVT));
5303 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5304 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5305 if (Opcode == ISD::SIGN_EXTEND)
5306 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5309 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5313 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5316 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5317 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5318 // transformation. Returns true if extension are possible and the above
5319 // mentioned transformation is profitable.
5320 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5322 SmallVectorImpl<SDNode *> &ExtendNodes,
5323 const TargetLowering &TLI) {
5324 bool HasCopyToRegUses = false;
5325 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5326 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5327 UE = N0.getNode()->use_end();
5332 if (UI.getUse().getResNo() != N0.getResNo())
5334 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5335 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5336 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5337 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5338 // Sign bits will be lost after a zext.
5341 for (unsigned i = 0; i != 2; ++i) {
5342 SDValue UseOp = User->getOperand(i);
5345 if (!isa<ConstantSDNode>(UseOp))
5350 ExtendNodes.push_back(User);
5353 // If truncates aren't free and there are users we can't
5354 // extend, it isn't worthwhile.
5357 // Remember if this value is live-out.
5358 if (User->getOpcode() == ISD::CopyToReg)
5359 HasCopyToRegUses = true;
5362 if (HasCopyToRegUses) {
5363 bool BothLiveOut = false;
5364 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5366 SDUse &Use = UI.getUse();
5367 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5373 // Both unextended and extended values are live out. There had better be
5374 // a good reason for the transformation.
5375 return ExtendNodes.size();
5380 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5381 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5382 ISD::NodeType ExtType) {
5383 // Extend SetCC uses if necessary.
5384 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5385 SDNode *SetCC = SetCCs[i];
5386 SmallVector<SDValue, 4> Ops;
5388 for (unsigned j = 0; j != 2; ++j) {
5389 SDValue SOp = SetCC->getOperand(j);
5391 Ops.push_back(ExtLoad);
5393 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5396 Ops.push_back(SetCC->getOperand(2));
5397 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5401 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5402 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5403 SDValue N0 = N->getOperand(0);
5404 EVT DstVT = N->getValueType(0);
5405 EVT SrcVT = N0.getValueType();
5407 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5408 N->getOpcode() == ISD::ZERO_EXTEND) &&
5409 "Unexpected node type (not an extend)!");
5411 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5412 // For example, on a target with legal v4i32, but illegal v8i32, turn:
5413 // (v8i32 (sext (v8i16 (load x))))
5415 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5416 // (v4i32 (sextload (x + 16)))))
5417 // Where uses of the original load, i.e.:
5419 // are replaced with:
5421 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5422 // (v4i32 (sextload (x + 16)))))))
5424 // This combine is only applicable to illegal, but splittable, vectors.
5425 // All legal types, and illegal non-vector types, are handled elsewhere.
5426 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5428 if (N0->getOpcode() != ISD::LOAD)
5431 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5433 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5434 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5435 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5438 SmallVector<SDNode *, 4> SetCCs;
5439 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5442 ISD::LoadExtType ExtType =
5443 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5445 // Try to split the vector types to get down to legal types.
5446 EVT SplitSrcVT = SrcVT;
5447 EVT SplitDstVT = DstVT;
5448 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5449 SplitSrcVT.getVectorNumElements() > 1) {
5450 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5451 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5454 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5458 const unsigned NumSplits =
5459 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5460 const unsigned Stride = SplitSrcVT.getStoreSize();
5461 SmallVector<SDValue, 4> Loads;
5462 SmallVector<SDValue, 4> Chains;
5464 SDValue BasePtr = LN0->getBasePtr();
5465 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5466 const unsigned Offset = Idx * Stride;
5467 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5469 SDValue SplitLoad = DAG.getExtLoad(
5470 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5471 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5472 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5473 Align, LN0->getAAInfo());
5475 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5476 DAG.getConstant(Stride, BasePtr.getValueType()));
5478 Loads.push_back(SplitLoad.getValue(0));
5479 Chains.push_back(SplitLoad.getValue(1));
5482 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5483 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5485 CombineTo(N, NewValue);
5487 // Replace uses of the original load (before extension)
5488 // with a truncate of the concatenated sextloaded vectors.
5490 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5491 CombineTo(N0.getNode(), Trunc, NewChain);
5492 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5493 (ISD::NodeType)N->getOpcode());
5494 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5497 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5498 SDValue N0 = N->getOperand(0);
5499 EVT VT = N->getValueType(0);
5501 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5503 return SDValue(Res, 0);
5505 // fold (sext (sext x)) -> (sext x)
5506 // fold (sext (aext x)) -> (sext x)
5507 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5508 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5511 if (N0.getOpcode() == ISD::TRUNCATE) {
5512 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5513 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5514 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5515 if (NarrowLoad.getNode()) {
5516 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5517 if (NarrowLoad.getNode() != N0.getNode()) {
5518 CombineTo(N0.getNode(), NarrowLoad);
5519 // CombineTo deleted the truncate, if needed, but not what's under it.
5522 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5525 // See if the value being truncated is already sign extended. If so, just
5526 // eliminate the trunc/sext pair.
5527 SDValue Op = N0.getOperand(0);
5528 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5529 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5530 unsigned DestBits = VT.getScalarType().getSizeInBits();
5531 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5533 if (OpBits == DestBits) {
5534 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5535 // bits, it is already ready.
5536 if (NumSignBits > DestBits-MidBits)
5538 } else if (OpBits < DestBits) {
5539 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5540 // bits, just sext from i32.
5541 if (NumSignBits > OpBits-MidBits)
5542 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5544 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5545 // bits, just truncate to i32.
5546 if (NumSignBits > OpBits-MidBits)
5547 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5550 // fold (sext (truncate x)) -> (sextinreg x).
5551 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5552 N0.getValueType())) {
5553 if (OpBits < DestBits)
5554 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5555 else if (OpBits > DestBits)
5556 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5557 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5558 DAG.getValueType(N0.getValueType()));
5562 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5563 // Only generate vector extloads when 1) they're legal, and 2) they are
5564 // deemed desirable by the target.
5565 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5566 ((!LegalOperations && !VT.isVector() &&
5567 !cast<LoadSDNode>(N0)->isVolatile()) ||
5568 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5569 bool DoXform = true;
5570 SmallVector<SDNode*, 4> SetCCs;
5571 if (!N0.hasOneUse())
5572 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5574 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5576 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5577 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5579 LN0->getBasePtr(), N0.getValueType(),
5580 LN0->getMemOperand());
5581 CombineTo(N, ExtLoad);
5582 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5583 N0.getValueType(), ExtLoad);
5584 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5585 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5587 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5591 // fold (sext (load x)) to multiple smaller sextloads.
5592 // Only on illegal but splittable vectors.
5593 if (SDValue ExtLoad = CombineExtLoad(N))
5596 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5597 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5598 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5599 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5600 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5601 EVT MemVT = LN0->getMemoryVT();
5602 if ((!LegalOperations && !LN0->isVolatile()) ||
5603 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5604 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5606 LN0->getBasePtr(), MemVT,
5607 LN0->getMemOperand());
5608 CombineTo(N, ExtLoad);
5609 CombineTo(N0.getNode(),
5610 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5611 N0.getValueType(), ExtLoad),
5612 ExtLoad.getValue(1));
5613 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5617 // fold (sext (and/or/xor (load x), cst)) ->
5618 // (and/or/xor (sextload x), (sext cst))
5619 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5620 N0.getOpcode() == ISD::XOR) &&
5621 isa<LoadSDNode>(N0.getOperand(0)) &&
5622 N0.getOperand(1).getOpcode() == ISD::Constant &&
5623 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5624 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5625 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5626 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5627 bool DoXform = true;
5628 SmallVector<SDNode*, 4> SetCCs;
5629 if (!N0.hasOneUse())
5630 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5633 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5634 LN0->getChain(), LN0->getBasePtr(),
5636 LN0->getMemOperand());
5637 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5638 Mask = Mask.sext(VT.getSizeInBits());
5639 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5640 ExtLoad, DAG.getConstant(Mask, VT));
5641 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5642 SDLoc(N0.getOperand(0)),
5643 N0.getOperand(0).getValueType(), ExtLoad);
5645 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5646 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5648 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5653 if (N0.getOpcode() == ISD::SETCC) {
5654 EVT N0VT = N0.getOperand(0).getValueType();
5655 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5656 // Only do this before legalize for now.
5657 if (VT.isVector() && !LegalOperations &&
5658 TLI.getBooleanContents(N0VT) ==
5659 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5660 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5661 // of the same size as the compared operands. Only optimize sext(setcc())
5662 // if this is the case.
5663 EVT SVT = getSetCCResultType(N0VT);
5665 // We know that the # elements of the results is the same as the
5666 // # elements of the compare (and the # elements of the compare result
5667 // for that matter). Check to see that they are the same size. If so,
5668 // we know that the element size of the sext'd result matches the
5669 // element size of the compare operands.
5670 if (VT.getSizeInBits() == SVT.getSizeInBits())
5671 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5673 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5675 // If the desired elements are smaller or larger than the source
5676 // elements we can use a matching integer vector type and then
5677 // truncate/sign extend
5678 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5679 if (SVT == MatchingVectorType) {
5680 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5681 N0.getOperand(0), N0.getOperand(1),
5682 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5683 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5687 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5688 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5690 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5692 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5693 NegOne, DAG.getConstant(0, VT),
5694 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5695 if (SCC.getNode()) return SCC;
5697 if (!VT.isVector()) {
5698 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5699 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5701 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5702 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5703 N0.getOperand(0), N0.getOperand(1), CC);
5704 return DAG.getSelect(DL, VT, SetCC,
5705 NegOne, DAG.getConstant(0, VT));
5710 // fold (sext x) -> (zext x) if the sign bit is known zero.
5711 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5712 DAG.SignBitIsZero(N0))
5713 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5718 // isTruncateOf - If N is a truncate of some other value, return true, record
5719 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5720 // This function computes KnownZero to avoid a duplicated call to
5721 // computeKnownBits in the caller.
5722 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5725 if (N->getOpcode() == ISD::TRUNCATE) {
5726 Op = N->getOperand(0);
5727 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5731 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5732 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5735 SDValue Op0 = N->getOperand(0);
5736 SDValue Op1 = N->getOperand(1);
5737 assert(Op0.getValueType() == Op1.getValueType());
5739 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5740 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5741 if (COp0 && COp0->isNullValue())
5743 else if (COp1 && COp1->isNullValue())
5748 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5750 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5756 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5757 SDValue N0 = N->getOperand(0);
5758 EVT VT = N->getValueType(0);
5760 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5762 return SDValue(Res, 0);
5764 // fold (zext (zext x)) -> (zext x)
5765 // fold (zext (aext x)) -> (zext x)
5766 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5767 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5770 // fold (zext (truncate x)) -> (zext x) or
5771 // (zext (truncate x)) -> (truncate x)
5772 // This is valid when the truncated bits of x are already zero.
5773 // FIXME: We should extend this to work for vectors too.
5776 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5777 APInt TruncatedBits =
5778 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5779 APInt(Op.getValueSizeInBits(), 0) :
5780 APInt::getBitsSet(Op.getValueSizeInBits(),
5781 N0.getValueSizeInBits(),
5782 std::min(Op.getValueSizeInBits(),
5783 VT.getSizeInBits()));
5784 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5785 if (VT.bitsGT(Op.getValueType()))
5786 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5787 if (VT.bitsLT(Op.getValueType()))
5788 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5794 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5795 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5796 if (N0.getOpcode() == ISD::TRUNCATE) {
5797 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5798 if (NarrowLoad.getNode()) {
5799 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5800 if (NarrowLoad.getNode() != N0.getNode()) {
5801 CombineTo(N0.getNode(), NarrowLoad);
5802 // CombineTo deleted the truncate, if needed, but not what's under it.
5805 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5809 // fold (zext (truncate x)) -> (and x, mask)
5810 if (N0.getOpcode() == ISD::TRUNCATE &&
5811 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5813 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5814 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5815 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5816 if (NarrowLoad.getNode()) {
5817 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5818 if (NarrowLoad.getNode() != N0.getNode()) {
5819 CombineTo(N0.getNode(), NarrowLoad);
5820 // CombineTo deleted the truncate, if needed, but not what's under it.
5823 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5826 SDValue Op = N0.getOperand(0);
5827 if (Op.getValueType().bitsLT(VT)) {
5828 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5829 AddToWorklist(Op.getNode());
5830 } else if (Op.getValueType().bitsGT(VT)) {
5831 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5832 AddToWorklist(Op.getNode());
5834 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5835 N0.getValueType().getScalarType());
5838 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5839 // if either of the casts is not free.
5840 if (N0.getOpcode() == ISD::AND &&
5841 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5842 N0.getOperand(1).getOpcode() == ISD::Constant &&
5843 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5844 N0.getValueType()) ||
5845 !TLI.isZExtFree(N0.getValueType(), VT))) {
5846 SDValue X = N0.getOperand(0).getOperand(0);
5847 if (X.getValueType().bitsLT(VT)) {
5848 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5849 } else if (X.getValueType().bitsGT(VT)) {
5850 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5852 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5853 Mask = Mask.zext(VT.getSizeInBits());
5854 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5855 X, DAG.getConstant(Mask, VT));
5858 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5859 // Only generate vector extloads when 1) they're legal, and 2) they are
5860 // deemed desirable by the target.
5861 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5862 ((!LegalOperations && !VT.isVector() &&
5863 !cast<LoadSDNode>(N0)->isVolatile()) ||
5864 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
5865 bool DoXform = true;
5866 SmallVector<SDNode*, 4> SetCCs;
5867 if (!N0.hasOneUse())
5868 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5870 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5872 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5873 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5875 LN0->getBasePtr(), N0.getValueType(),
5876 LN0->getMemOperand());
5877 CombineTo(N, ExtLoad);
5878 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5879 N0.getValueType(), ExtLoad);
5880 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5882 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5884 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5888 // fold (zext (load x)) to multiple smaller zextloads.
5889 // Only on illegal but splittable vectors.
5890 if (SDValue ExtLoad = CombineExtLoad(N))
5893 // fold (zext (and/or/xor (load x), cst)) ->
5894 // (and/or/xor (zextload x), (zext cst))
5895 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5896 N0.getOpcode() == ISD::XOR) &&
5897 isa<LoadSDNode>(N0.getOperand(0)) &&
5898 N0.getOperand(1).getOpcode() == ISD::Constant &&
5899 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
5900 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5901 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5902 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5903 bool DoXform = true;
5904 SmallVector<SDNode*, 4> SetCCs;
5905 if (!N0.hasOneUse())
5906 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5909 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5910 LN0->getChain(), LN0->getBasePtr(),
5912 LN0->getMemOperand());
5913 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5914 Mask = Mask.zext(VT.getSizeInBits());
5915 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5916 ExtLoad, DAG.getConstant(Mask, VT));
5917 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5918 SDLoc(N0.getOperand(0)),
5919 N0.getOperand(0).getValueType(), ExtLoad);
5921 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5922 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5924 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5929 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5930 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5931 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5932 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5933 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5934 EVT MemVT = LN0->getMemoryVT();
5935 if ((!LegalOperations && !LN0->isVolatile()) ||
5936 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
5937 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5939 LN0->getBasePtr(), MemVT,
5940 LN0->getMemOperand());
5941 CombineTo(N, ExtLoad);
5942 CombineTo(N0.getNode(),
5943 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5945 ExtLoad.getValue(1));
5946 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5950 if (N0.getOpcode() == ISD::SETCC) {
5951 if (!LegalOperations && VT.isVector() &&
5952 N0.getValueType().getVectorElementType() == MVT::i1) {
5953 EVT N0VT = N0.getOperand(0).getValueType();
5954 if (getSetCCResultType(N0VT) == N0.getValueType())
5957 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5958 // Only do this before legalize for now.
5959 EVT EltVT = VT.getVectorElementType();
5960 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5961 DAG.getConstant(1, EltVT));
5962 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5963 // We know that the # elements of the results is the same as the
5964 // # elements of the compare (and the # elements of the compare result
5965 // for that matter). Check to see that they are the same size. If so,
5966 // we know that the element size of the sext'd result matches the
5967 // element size of the compare operands.
5968 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5969 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5971 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5972 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5975 // If the desired elements are smaller or larger than the source
5976 // elements we can use a matching integer vector type and then
5977 // truncate/sign extend
5978 EVT MatchingElementType =
5979 EVT::getIntegerVT(*DAG.getContext(),
5980 N0VT.getScalarType().getSizeInBits());
5981 EVT MatchingVectorType =
5982 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5983 N0VT.getVectorNumElements());
5985 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5987 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5988 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5989 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5990 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5993 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5995 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5996 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5997 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5998 if (SCC.getNode()) return SCC;
6001 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6002 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6003 isa<ConstantSDNode>(N0.getOperand(1)) &&
6004 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6006 SDValue ShAmt = N0.getOperand(1);
6007 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6008 if (N0.getOpcode() == ISD::SHL) {
6009 SDValue InnerZExt = N0.getOperand(0);
6010 // If the original shl may be shifting out bits, do not perform this
6012 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6013 InnerZExt.getOperand(0).getValueType().getSizeInBits();
6014 if (ShAmtVal > KnownZeroBits)
6020 // Ensure that the shift amount is wide enough for the shifted value.
6021 if (VT.getSizeInBits() >= 256)
6022 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6024 return DAG.getNode(N0.getOpcode(), DL, VT,
6025 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6032 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6033 SDValue N0 = N->getOperand(0);
6034 EVT VT = N->getValueType(0);
6036 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6038 return SDValue(Res, 0);
6040 // fold (aext (aext x)) -> (aext x)
6041 // fold (aext (zext x)) -> (zext x)
6042 // fold (aext (sext x)) -> (sext x)
6043 if (N0.getOpcode() == ISD::ANY_EXTEND ||
6044 N0.getOpcode() == ISD::ZERO_EXTEND ||
6045 N0.getOpcode() == ISD::SIGN_EXTEND)
6046 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6048 // fold (aext (truncate (load x))) -> (aext (smaller load x))
6049 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6050 if (N0.getOpcode() == ISD::TRUNCATE) {
6051 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6052 if (NarrowLoad.getNode()) {
6053 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6054 if (NarrowLoad.getNode() != N0.getNode()) {
6055 CombineTo(N0.getNode(), NarrowLoad);
6056 // CombineTo deleted the truncate, if needed, but not what's under it.
6059 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6063 // fold (aext (truncate x))
6064 if (N0.getOpcode() == ISD::TRUNCATE) {
6065 SDValue TruncOp = N0.getOperand(0);
6066 if (TruncOp.getValueType() == VT)
6067 return TruncOp; // x iff x size == zext size.
6068 if (TruncOp.getValueType().bitsGT(VT))
6069 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6070 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6073 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6074 // if the trunc is not free.
6075 if (N0.getOpcode() == ISD::AND &&
6076 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6077 N0.getOperand(1).getOpcode() == ISD::Constant &&
6078 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6079 N0.getValueType())) {
6080 SDValue X = N0.getOperand(0).getOperand(0);
6081 if (X.getValueType().bitsLT(VT)) {
6082 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6083 } else if (X.getValueType().bitsGT(VT)) {
6084 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6086 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6087 Mask = Mask.zext(VT.getSizeInBits());
6088 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6089 X, DAG.getConstant(Mask, VT));
6092 // fold (aext (load x)) -> (aext (truncate (extload x)))
6093 // None of the supported targets knows how to perform load and any_ext
6094 // on vectors in one instruction. We only perform this transformation on
6096 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6097 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6098 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6099 bool DoXform = true;
6100 SmallVector<SDNode*, 4> SetCCs;
6101 if (!N0.hasOneUse())
6102 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6104 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6105 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6107 LN0->getBasePtr(), N0.getValueType(),
6108 LN0->getMemOperand());
6109 CombineTo(N, ExtLoad);
6110 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6111 N0.getValueType(), ExtLoad);
6112 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6113 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6115 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6119 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6120 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6121 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
6122 if (N0.getOpcode() == ISD::LOAD &&
6123 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6125 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6126 ISD::LoadExtType ExtType = LN0->getExtensionType();
6127 EVT MemVT = LN0->getMemoryVT();
6128 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6129 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6130 VT, LN0->getChain(), LN0->getBasePtr(),
6131 MemVT, LN0->getMemOperand());
6132 CombineTo(N, ExtLoad);
6133 CombineTo(N0.getNode(),
6134 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6135 N0.getValueType(), ExtLoad),
6136 ExtLoad.getValue(1));
6137 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6141 if (N0.getOpcode() == ISD::SETCC) {
6143 // aext(setcc) -> vsetcc
6144 // aext(setcc) -> truncate(vsetcc)
6145 // aext(setcc) -> aext(vsetcc)
6146 // Only do this before legalize for now.
6147 if (VT.isVector() && !LegalOperations) {
6148 EVT N0VT = N0.getOperand(0).getValueType();
6149 // We know that the # elements of the results is the same as the
6150 // # elements of the compare (and the # elements of the compare result
6151 // for that matter). Check to see that they are the same size. If so,
6152 // we know that the element size of the sext'd result matches the
6153 // element size of the compare operands.
6154 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6155 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6157 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6158 // If the desired elements are smaller or larger than the source
6159 // elements we can use a matching integer vector type and then
6160 // truncate/any extend
6162 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6164 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6166 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6167 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6171 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6173 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
6174 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
6175 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6183 /// See if the specified operand can be simplified with the knowledge that only
6184 /// the bits specified by Mask are used. If so, return the simpler operand,
6185 /// otherwise return a null SDValue.
6186 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6187 switch (V.getOpcode()) {
6189 case ISD::Constant: {
6190 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6191 assert(CV && "Const value should be ConstSDNode.");
6192 const APInt &CVal = CV->getAPIntValue();
6193 APInt NewVal = CVal & Mask;
6195 return DAG.getConstant(NewVal, V.getValueType());
6200 // If the LHS or RHS don't contribute bits to the or, drop them.
6201 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6202 return V.getOperand(1);
6203 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6204 return V.getOperand(0);
6207 // Only look at single-use SRLs.
6208 if (!V.getNode()->hasOneUse())
6210 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
6211 // See if we can recursively simplify the LHS.
6212 unsigned Amt = RHSC->getZExtValue();
6214 // Watch out for shift count overflow though.
6215 if (Amt >= Mask.getBitWidth()) break;
6216 APInt NewMask = Mask << Amt;
6217 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
6218 if (SimplifyLHS.getNode())
6219 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6220 SimplifyLHS, V.getOperand(1));
6226 /// If the result of a wider load is shifted to right of N bits and then
6227 /// truncated to a narrower type and where N is a multiple of number of bits of
6228 /// the narrower type, transform it to a narrower load from address + N / num of
6229 /// bits of new type. If the result is to be extended, also fold the extension
6230 /// to form a extending load.
6231 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6232 unsigned Opc = N->getOpcode();
6234 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6235 SDValue N0 = N->getOperand(0);
6236 EVT VT = N->getValueType(0);
6239 // This transformation isn't valid for vector loads.
6243 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6245 if (Opc == ISD::SIGN_EXTEND_INREG) {
6246 ExtType = ISD::SEXTLOAD;
6247 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6248 } else if (Opc == ISD::SRL) {
6249 // Another special-case: SRL is basically zero-extending a narrower value.
6250 ExtType = ISD::ZEXTLOAD;
6252 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6253 if (!N01) return SDValue();
6254 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6255 VT.getSizeInBits() - N01->getZExtValue());
6257 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6260 unsigned EVTBits = ExtVT.getSizeInBits();
6262 // Do not generate loads of non-round integer types since these can
6263 // be expensive (and would be wrong if the type is not byte sized).
6264 if (!ExtVT.isRound())
6268 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6269 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6270 ShAmt = N01->getZExtValue();
6271 // Is the shift amount a multiple of size of VT?
6272 if ((ShAmt & (EVTBits-1)) == 0) {
6273 N0 = N0.getOperand(0);
6274 // Is the load width a multiple of size of VT?
6275 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6279 // At this point, we must have a load or else we can't do the transform.
6280 if (!isa<LoadSDNode>(N0)) return SDValue();
6282 // Because a SRL must be assumed to *need* to zero-extend the high bits
6283 // (as opposed to anyext the high bits), we can't combine the zextload
6284 // lowering of SRL and an sextload.
6285 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6288 // If the shift amount is larger than the input type then we're not
6289 // accessing any of the loaded bytes. If the load was a zextload/extload
6290 // then the result of the shift+trunc is zero/undef (handled elsewhere).
6291 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6296 // If the load is shifted left (and the result isn't shifted back right),
6297 // we can fold the truncate through the shift.
6298 unsigned ShLeftAmt = 0;
6299 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6300 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6301 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6302 ShLeftAmt = N01->getZExtValue();
6303 N0 = N0.getOperand(0);
6307 // If we haven't found a load, we can't narrow it. Don't transform one with
6308 // multiple uses, this would require adding a new load.
6309 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6312 // Don't change the width of a volatile load.
6313 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6314 if (LN0->isVolatile())
6317 // Verify that we are actually reducing a load width here.
6318 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6321 // For the transform to be legal, the load must produce only two values
6322 // (the value loaded and the chain). Don't transform a pre-increment
6323 // load, for example, which produces an extra value. Otherwise the
6324 // transformation is not equivalent, and the downstream logic to replace
6325 // uses gets things wrong.
6326 if (LN0->getNumValues() > 2)
6329 // If the load that we're shrinking is an extload and we're not just
6330 // discarding the extension we can't simply shrink the load. Bail.
6331 // TODO: It would be possible to merge the extensions in some cases.
6332 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6333 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6336 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6339 EVT PtrType = N0.getOperand(1).getValueType();
6341 if (PtrType == MVT::Untyped || PtrType.isExtended())
6342 // It's not possible to generate a constant of extended or untyped type.
6345 // For big endian targets, we need to adjust the offset to the pointer to
6346 // load the correct bytes.
6347 if (TLI.isBigEndian()) {
6348 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6349 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6350 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6353 uint64_t PtrOff = ShAmt / 8;
6354 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6355 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
6356 PtrType, LN0->getBasePtr(),
6357 DAG.getConstant(PtrOff, PtrType));
6358 AddToWorklist(NewPtr.getNode());
6361 if (ExtType == ISD::NON_EXTLOAD)
6362 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6363 LN0->getPointerInfo().getWithOffset(PtrOff),
6364 LN0->isVolatile(), LN0->isNonTemporal(),
6365 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6367 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6368 LN0->getPointerInfo().getWithOffset(PtrOff),
6369 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6370 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6372 // Replace the old load's chain with the new load's chain.
6373 WorklistRemover DeadNodes(*this);
6374 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6376 // Shift the result left, if we've swallowed a left shift.
6377 SDValue Result = Load;
6378 if (ShLeftAmt != 0) {
6379 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6380 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6382 // If the shift amount is as large as the result size (but, presumably,
6383 // no larger than the source) then the useful bits of the result are
6384 // zero; we can't simply return the shortened shift, because the result
6385 // of that operation is undefined.
6386 if (ShLeftAmt >= VT.getSizeInBits())
6387 Result = DAG.getConstant(0, VT);
6389 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
6390 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
6393 // Return the new loaded value.
6397 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6398 SDValue N0 = N->getOperand(0);
6399 SDValue N1 = N->getOperand(1);
6400 EVT VT = N->getValueType(0);
6401 EVT EVT = cast<VTSDNode>(N1)->getVT();
6402 unsigned VTBits = VT.getScalarType().getSizeInBits();
6403 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6405 // fold (sext_in_reg c1) -> c1
6406 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6407 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6409 // If the input is already sign extended, just drop the extension.
6410 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6413 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6414 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6415 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6416 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6417 N0.getOperand(0), N1);
6419 // fold (sext_in_reg (sext x)) -> (sext x)
6420 // fold (sext_in_reg (aext x)) -> (sext x)
6421 // if x is small enough.
6422 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6423 SDValue N00 = N0.getOperand(0);
6424 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6425 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6426 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6429 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6430 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6431 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6433 // fold operands of sext_in_reg based on knowledge that the top bits are not
6435 if (SimplifyDemandedBits(SDValue(N, 0)))
6436 return SDValue(N, 0);
6438 // fold (sext_in_reg (load x)) -> (smaller sextload x)
6439 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6440 SDValue NarrowLoad = ReduceLoadWidth(N);
6441 if (NarrowLoad.getNode())
6444 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6445 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6446 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6447 if (N0.getOpcode() == ISD::SRL) {
6448 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6449 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6450 // We can turn this into an SRA iff the input to the SRL is already sign
6452 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6453 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6454 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6455 N0.getOperand(0), N0.getOperand(1));
6459 // fold (sext_inreg (extload x)) -> (sextload x)
6460 if (ISD::isEXTLoad(N0.getNode()) &&
6461 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6462 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6463 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6464 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6465 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6466 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6468 LN0->getBasePtr(), EVT,
6469 LN0->getMemOperand());
6470 CombineTo(N, ExtLoad);
6471 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6472 AddToWorklist(ExtLoad.getNode());
6473 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6475 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6476 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6478 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6479 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6480 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6481 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6482 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6484 LN0->getBasePtr(), EVT,
6485 LN0->getMemOperand());
6486 CombineTo(N, ExtLoad);
6487 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6488 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6491 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6492 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6493 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6494 N0.getOperand(1), false);
6495 if (BSwap.getNode())
6496 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6500 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6501 // into a build_vector.
6502 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6503 SmallVector<SDValue, 8> Elts;
6504 unsigned NumElts = N0->getNumOperands();
6505 unsigned ShAmt = VTBits - EVTBits;
6507 for (unsigned i = 0; i != NumElts; ++i) {
6508 SDValue Op = N0->getOperand(i);
6509 if (Op->getOpcode() == ISD::UNDEF) {
6514 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6515 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6516 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6517 Op.getValueType()));
6520 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6526 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6527 SDValue N0 = N->getOperand(0);
6528 EVT VT = N->getValueType(0);
6529 bool isLE = TLI.isLittleEndian();
6532 if (N0.getValueType() == N->getValueType(0))
6534 // fold (truncate c1) -> c1
6535 if (isa<ConstantSDNode>(N0))
6536 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6537 // fold (truncate (truncate x)) -> (truncate x)
6538 if (N0.getOpcode() == ISD::TRUNCATE)
6539 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6540 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6541 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6542 N0.getOpcode() == ISD::SIGN_EXTEND ||
6543 N0.getOpcode() == ISD::ANY_EXTEND) {
6544 if (N0.getOperand(0).getValueType().bitsLT(VT))
6545 // if the source is smaller than the dest, we still need an extend
6546 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6548 if (N0.getOperand(0).getValueType().bitsGT(VT))
6549 // if the source is larger than the dest, than we just need the truncate
6550 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6551 // if the source and dest are the same type, we can drop both the extend
6552 // and the truncate.
6553 return N0.getOperand(0);
6556 // Fold extract-and-trunc into a narrow extract. For example:
6557 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6558 // i32 y = TRUNCATE(i64 x)
6560 // v16i8 b = BITCAST (v2i64 val)
6561 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6563 // Note: We only run this optimization after type legalization (which often
6564 // creates this pattern) and before operation legalization after which
6565 // we need to be more careful about the vector instructions that we generate.
6566 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6567 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6569 EVT VecTy = N0.getOperand(0).getValueType();
6570 EVT ExTy = N0.getValueType();
6571 EVT TrTy = N->getValueType(0);
6573 unsigned NumElem = VecTy.getVectorNumElements();
6574 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6576 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6577 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6579 SDValue EltNo = N0->getOperand(1);
6580 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6581 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6582 EVT IndexTy = TLI.getVectorIdxTy();
6583 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6585 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6586 NVT, N0.getOperand(0));
6588 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6590 DAG.getConstant(Index, IndexTy));
6594 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6595 if (N0.getOpcode() == ISD::SELECT) {
6596 EVT SrcVT = N0.getValueType();
6597 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6598 TLI.isTruncateFree(SrcVT, VT)) {
6600 SDValue Cond = N0.getOperand(0);
6601 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6602 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6603 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6607 // Fold a series of buildvector, bitcast, and truncate if possible.
6609 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6610 // (2xi32 (buildvector x, y)).
6611 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6612 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6613 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6614 N0.getOperand(0).hasOneUse()) {
6616 SDValue BuildVect = N0.getOperand(0);
6617 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6618 EVT TruncVecEltTy = VT.getVectorElementType();
6620 // Check that the element types match.
6621 if (BuildVectEltTy == TruncVecEltTy) {
6622 // Now we only need to compute the offset of the truncated elements.
6623 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6624 unsigned TruncVecNumElts = VT.getVectorNumElements();
6625 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6627 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6628 "Invalid number of elements");
6630 SmallVector<SDValue, 8> Opnds;
6631 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6632 Opnds.push_back(BuildVect.getOperand(i));
6634 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6638 // See if we can simplify the input to this truncate through knowledge that
6639 // only the low bits are being used.
6640 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6641 // Currently we only perform this optimization on scalars because vectors
6642 // may have different active low bits.
6643 if (!VT.isVector()) {
6645 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6646 VT.getSizeInBits()));
6647 if (Shorter.getNode())
6648 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6650 // fold (truncate (load x)) -> (smaller load x)
6651 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6652 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6653 SDValue Reduced = ReduceLoadWidth(N);
6654 if (Reduced.getNode())
6656 // Handle the case where the load remains an extending load even
6657 // after truncation.
6658 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6659 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6660 if (!LN0->isVolatile() &&
6661 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6662 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6663 VT, LN0->getChain(), LN0->getBasePtr(),
6665 LN0->getMemOperand());
6666 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6671 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6672 // where ... are all 'undef'.
6673 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6674 SmallVector<EVT, 8> VTs;
6677 unsigned NumDefs = 0;
6679 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6680 SDValue X = N0.getOperand(i);
6681 if (X.getOpcode() != ISD::UNDEF) {
6686 // Stop if more than one members are non-undef.
6689 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6690 VT.getVectorElementType(),
6691 X.getValueType().getVectorNumElements()));
6695 return DAG.getUNDEF(VT);
6698 assert(V.getNode() && "The single defined operand is empty!");
6699 SmallVector<SDValue, 8> Opnds;
6700 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6702 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6705 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6706 AddToWorklist(NV.getNode());
6707 Opnds.push_back(NV);
6709 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6713 // Simplify the operands using demanded-bits information.
6714 if (!VT.isVector() &&
6715 SimplifyDemandedBits(SDValue(N, 0)))
6716 return SDValue(N, 0);
6721 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6722 SDValue Elt = N->getOperand(i);
6723 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6724 return Elt.getNode();
6725 return Elt.getOperand(Elt.getResNo()).getNode();
6728 /// build_pair (load, load) -> load
6729 /// if load locations are consecutive.
6730 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6731 assert(N->getOpcode() == ISD::BUILD_PAIR);
6733 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6734 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6735 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6736 LD1->getAddressSpace() != LD2->getAddressSpace())
6738 EVT LD1VT = LD1->getValueType(0);
6740 if (ISD::isNON_EXTLoad(LD2) &&
6742 // If both are volatile this would reduce the number of volatile loads.
6743 // If one is volatile it might be ok, but play conservative and bail out.
6744 !LD1->isVolatile() &&
6745 !LD2->isVolatile() &&
6746 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6747 unsigned Align = LD1->getAlignment();
6748 unsigned NewAlign = TLI.getDataLayout()->
6749 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6751 if (NewAlign <= Align &&
6752 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6753 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6754 LD1->getBasePtr(), LD1->getPointerInfo(),
6755 false, false, false, Align);
6761 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6762 SDValue N0 = N->getOperand(0);
6763 EVT VT = N->getValueType(0);
6765 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6766 // Only do this before legalize, since afterward the target may be depending
6767 // on the bitconvert.
6768 // First check to see if this is all constant.
6770 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6772 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6774 EVT DestEltVT = N->getValueType(0).getVectorElementType();
6775 assert(!DestEltVT.isVector() &&
6776 "Element type of vector ValueType must not be vector!");
6778 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6781 // If the input is a constant, let getNode fold it.
6782 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6783 // If we can't allow illegal operations, we need to check that this is just
6784 // a fp -> int or int -> conversion and that the resulting operation will
6786 if (!LegalOperations ||
6787 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
6788 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
6789 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
6790 TLI.isOperationLegal(ISD::Constant, VT)))
6791 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6794 // (conv (conv x, t1), t2) -> (conv x, t2)
6795 if (N0.getOpcode() == ISD::BITCAST)
6796 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6799 // fold (conv (load x)) -> (load (conv*)x)
6800 // If the resultant load doesn't need a higher alignment than the original!
6801 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6802 // Do not change the width of a volatile load.
6803 !cast<LoadSDNode>(N0)->isVolatile() &&
6804 // Do not remove the cast if the types differ in endian layout.
6805 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6806 TLI.hasBigEndianPartOrdering(VT) &&
6807 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6808 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6809 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6810 unsigned Align = TLI.getDataLayout()->
6811 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6812 unsigned OrigAlign = LN0->getAlignment();
6814 if (Align <= OrigAlign) {
6815 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6816 LN0->getBasePtr(), LN0->getPointerInfo(),
6817 LN0->isVolatile(), LN0->isNonTemporal(),
6818 LN0->isInvariant(), OrigAlign,
6820 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6825 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6826 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6827 // This often reduces constant pool loads.
6828 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6829 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6830 N0.getNode()->hasOneUse() && VT.isInteger() &&
6831 !VT.isVector() && !N0.getValueType().isVector()) {
6832 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6834 AddToWorklist(NewConv.getNode());
6836 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6837 if (N0.getOpcode() == ISD::FNEG)
6838 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6839 NewConv, DAG.getConstant(SignBit, VT));
6840 assert(N0.getOpcode() == ISD::FABS);
6841 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6842 NewConv, DAG.getConstant(~SignBit, VT));
6845 // fold (bitconvert (fcopysign cst, x)) ->
6846 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6847 // Note that we don't handle (copysign x, cst) because this can always be
6848 // folded to an fneg or fabs.
6849 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6850 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6851 VT.isInteger() && !VT.isVector()) {
6852 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6853 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6854 if (isTypeLegal(IntXVT)) {
6855 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6856 IntXVT, N0.getOperand(1));
6857 AddToWorklist(X.getNode());
6859 // If X has a different width than the result/lhs, sext it or truncate it.
6860 unsigned VTWidth = VT.getSizeInBits();
6861 if (OrigXWidth < VTWidth) {
6862 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6863 AddToWorklist(X.getNode());
6864 } else if (OrigXWidth > VTWidth) {
6865 // To get the sign bit in the right place, we have to shift it right
6866 // before truncating.
6867 X = DAG.getNode(ISD::SRL, SDLoc(X),
6868 X.getValueType(), X,
6869 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6870 AddToWorklist(X.getNode());
6871 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6872 AddToWorklist(X.getNode());
6875 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6876 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6877 X, DAG.getConstant(SignBit, VT));
6878 AddToWorklist(X.getNode());
6880 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6881 VT, N0.getOperand(0));
6882 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6883 Cst, DAG.getConstant(~SignBit, VT));
6884 AddToWorklist(Cst.getNode());
6886 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6890 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6891 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6892 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6893 if (CombineLD.getNode())
6900 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6901 EVT VT = N->getValueType(0);
6902 return CombineConsecutiveLoads(N, VT);
6905 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6906 /// operands. DstEltVT indicates the destination element value type.
6907 SDValue DAGCombiner::
6908 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6909 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6911 // If this is already the right type, we're done.
6912 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6914 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6915 unsigned DstBitSize = DstEltVT.getSizeInBits();
6917 // If this is a conversion of N elements of one type to N elements of another
6918 // type, convert each element. This handles FP<->INT cases.
6919 if (SrcBitSize == DstBitSize) {
6920 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6921 BV->getValueType(0).getVectorNumElements());
6923 // Due to the FP element handling below calling this routine recursively,
6924 // we can end up with a scalar-to-vector node here.
6925 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6926 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6927 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6928 DstEltVT, BV->getOperand(0)));
6930 SmallVector<SDValue, 8> Ops;
6931 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6932 SDValue Op = BV->getOperand(i);
6933 // If the vector element type is not legal, the BUILD_VECTOR operands
6934 // are promoted and implicitly truncated. Make that explicit here.
6935 if (Op.getValueType() != SrcEltVT)
6936 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6937 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6939 AddToWorklist(Ops.back().getNode());
6941 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6944 // Otherwise, we're growing or shrinking the elements. To avoid having to
6945 // handle annoying details of growing/shrinking FP values, we convert them to
6947 if (SrcEltVT.isFloatingPoint()) {
6948 // Convert the input float vector to a int vector where the elements are the
6950 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6951 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6955 // Now we know the input is an integer vector. If the output is a FP type,
6956 // convert to integer first, then to FP of the right size.
6957 if (DstEltVT.isFloatingPoint()) {
6958 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6959 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6961 // Next, convert to FP elements of the same size.
6962 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6965 // Okay, we know the src/dst types are both integers of differing types.
6966 // Handling growing first.
6967 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6968 if (SrcBitSize < DstBitSize) {
6969 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6971 SmallVector<SDValue, 8> Ops;
6972 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6973 i += NumInputsPerOutput) {
6974 bool isLE = TLI.isLittleEndian();
6975 APInt NewBits = APInt(DstBitSize, 0);
6976 bool EltIsUndef = true;
6977 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6978 // Shift the previously computed bits over.
6979 NewBits <<= SrcBitSize;
6980 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6981 if (Op.getOpcode() == ISD::UNDEF) continue;
6984 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6985 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6989 Ops.push_back(DAG.getUNDEF(DstEltVT));
6991 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6994 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6995 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6998 // Finally, this must be the case where we are shrinking elements: each input
6999 // turns into multiple outputs.
7000 bool isS2V = ISD::isScalarToVector(BV);
7001 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7002 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7003 NumOutputsPerInput*BV->getNumOperands());
7004 SmallVector<SDValue, 8> Ops;
7006 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7007 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
7008 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7012 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
7013 getAPIntValue().zextOrTrunc(SrcBitSize);
7015 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7016 APInt ThisVal = OpVal.trunc(DstBitSize);
7017 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
7018 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
7019 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
7020 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7022 OpVal = OpVal.lshr(DstBitSize);
7025 // For big endian targets, swap the order of the pieces of each element.
7026 if (TLI.isBigEndian())
7027 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7030 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7033 // Attempt different variants of (fadd (fmul a, b), c) -> fma or fmad
7034 static SDValue performFaddFmulCombines(unsigned FusedOpcode,
7037 const TargetLowering &TLI,
7038 SelectionDAG &DAG) {
7039 SDValue N0 = N->getOperand(0);
7040 SDValue N1 = N->getOperand(1);
7041 EVT VT = N->getValueType(0);
7043 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7044 if (N0.getOpcode() == ISD::FMUL &&
7045 (Aggressive || N0->hasOneUse())) {
7046 return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7047 N0.getOperand(0), N0.getOperand(1), N1);
7050 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7051 // Note: Commutes FADD operands.
7052 if (N1.getOpcode() == ISD::FMUL &&
7053 (Aggressive || N1->hasOneUse())) {
7054 return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7055 N1.getOperand(0), N1.getOperand(1), N0);
7058 // More folding opportunities when target permits.
7060 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7061 if (N0.getOpcode() == ISD::FMA &&
7062 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7063 return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7064 N0.getOperand(0), N0.getOperand(1),
7065 DAG.getNode(FusedOpcode, SDLoc(N), VT,
7066 N0.getOperand(2).getOperand(0),
7067 N0.getOperand(2).getOperand(1),
7071 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7072 if (N1->getOpcode() == ISD::FMA &&
7073 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7074 return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7075 N1.getOperand(0), N1.getOperand(1),
7076 DAG.getNode(FusedOpcode, SDLoc(N), VT,
7077 N1.getOperand(2).getOperand(0),
7078 N1.getOperand(2).getOperand(1),
7086 static SDValue performFsubFmulCombines(unsigned FusedOpcode,
7089 const TargetLowering &TLI,
7090 SelectionDAG &DAG) {
7091 SDValue N0 = N->getOperand(0);
7092 SDValue N1 = N->getOperand(1);
7093 EVT VT = N->getValueType(0);
7097 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7098 if (N0.getOpcode() == ISD::FMUL &&
7099 (Aggressive || N0->hasOneUse())) {
7100 return DAG.getNode(FusedOpcode, SL, VT,
7101 N0.getOperand(0), N0.getOperand(1),
7102 DAG.getNode(ISD::FNEG, SL, VT, N1));
7105 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7106 // Note: Commutes FSUB operands.
7107 if (N1.getOpcode() == ISD::FMUL &&
7108 (Aggressive || N1->hasOneUse()))
7109 return DAG.getNode(FusedOpcode, SL, VT,
7110 DAG.getNode(ISD::FNEG, SL, VT,
7112 N1.getOperand(1), N0);
7114 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7115 if (N0.getOpcode() == ISD::FNEG &&
7116 N0.getOperand(0).getOpcode() == ISD::FMUL &&
7117 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7118 SDValue N00 = N0.getOperand(0).getOperand(0);
7119 SDValue N01 = N0.getOperand(0).getOperand(1);
7120 return DAG.getNode(FusedOpcode, SL, VT,
7121 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7122 DAG.getNode(ISD::FNEG, SL, VT, N1));
7125 // More folding opportunities when target permits.
7127 // fold (fsub (fma x, y, (fmul u, v)), z)
7128 // -> (fma x, y (fma u, v, (fneg z)))
7129 if (N0.getOpcode() == FusedOpcode &&
7130 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7131 return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7132 N0.getOperand(0), N0.getOperand(1),
7133 DAG.getNode(FusedOpcode, SDLoc(N), VT,
7134 N0.getOperand(2).getOperand(0),
7135 N0.getOperand(2).getOperand(1),
7136 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7140 // fold (fsub x, (fma y, z, (fmul u, v)))
7141 // -> (fma (fneg y), z, (fma (fneg u), v, x))
7142 if (N1.getOpcode() == FusedOpcode &&
7143 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7144 SDValue N20 = N1.getOperand(2).getOperand(0);
7145 SDValue N21 = N1.getOperand(2).getOperand(1);
7146 return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7147 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7150 DAG.getNode(FusedOpcode, SDLoc(N), VT,
7151 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7160 SDValue DAGCombiner::visitFADD(SDNode *N) {
7161 SDValue N0 = N->getOperand(0);
7162 SDValue N1 = N->getOperand(1);
7163 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7164 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7165 EVT VT = N->getValueType(0);
7166 const TargetOptions &Options = DAG.getTarget().Options;
7169 if (VT.isVector()) {
7170 SDValue FoldedVOp = SimplifyVBinOp(N);
7171 if (FoldedVOp.getNode()) return FoldedVOp;
7174 // fold (fadd c1, c2) -> c1 + c2
7176 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
7178 // canonicalize constant to RHS
7179 if (N0CFP && !N1CFP)
7180 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
7182 // fold (fadd A, (fneg B)) -> (fsub A, B)
7183 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7184 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7185 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
7186 GetNegatedExpression(N1, DAG, LegalOperations));
7188 // fold (fadd (fneg A), B) -> (fsub B, A)
7189 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7190 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7191 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
7192 GetNegatedExpression(N0, DAG, LegalOperations));
7194 // If 'unsafe math' is enabled, fold lots of things.
7195 if (Options.UnsafeFPMath) {
7196 // No FP constant should be created after legalization as Instruction
7197 // Selection pass has a hard time dealing with FP constants.
7198 bool AllowNewConst = (Level < AfterLegalizeDAG);
7200 // fold (fadd A, 0) -> A
7201 if (N1CFP && N1CFP->getValueAPF().isZero())
7204 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7205 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7206 isa<ConstantFPSDNode>(N0.getOperand(1)))
7207 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
7208 DAG.getNode(ISD::FADD, SDLoc(N), VT,
7209 N0.getOperand(1), N1));
7211 // If allowed, fold (fadd (fneg x), x) -> 0.0
7212 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7213 return DAG.getConstantFP(0.0, VT);
7215 // If allowed, fold (fadd x, (fneg x)) -> 0.0
7216 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7217 return DAG.getConstantFP(0.0, VT);
7219 // We can fold chains of FADD's of the same value into multiplications.
7220 // This transform is not safe in general because we are reducing the number
7221 // of rounding steps.
7222 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7223 if (N0.getOpcode() == ISD::FMUL) {
7224 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7225 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7227 // (fadd (fmul x, c), x) -> (fmul x, c+1)
7228 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7229 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7231 DAG.getConstantFP(1.0, VT));
7232 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
7235 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7236 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7237 N1.getOperand(0) == N1.getOperand(1) &&
7238 N0.getOperand(0) == N1.getOperand(0)) {
7239 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7241 DAG.getConstantFP(2.0, VT));
7242 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7243 N0.getOperand(0), NewCFP);
7247 if (N1.getOpcode() == ISD::FMUL) {
7248 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7249 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7251 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7252 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7253 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7255 DAG.getConstantFP(1.0, VT));
7256 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
7259 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7260 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7261 N0.getOperand(0) == N0.getOperand(1) &&
7262 N1.getOperand(0) == N0.getOperand(0)) {
7263 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7265 DAG.getConstantFP(2.0, VT));
7266 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
7270 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7271 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7272 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7273 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7274 (N0.getOperand(0) == N1))
7275 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7276 N1, DAG.getConstantFP(3.0, VT));
7279 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7280 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7281 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7282 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7283 N1.getOperand(0) == N0)
7284 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7285 N0, DAG.getConstantFP(3.0, VT));
7288 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7289 if (AllowNewConst &&
7290 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7291 N0.getOperand(0) == N0.getOperand(1) &&
7292 N1.getOperand(0) == N1.getOperand(1) &&
7293 N0.getOperand(0) == N1.getOperand(0))
7294 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7295 N0.getOperand(0), DAG.getConstantFP(4.0, VT));
7297 } // enable-unsafe-fp-math
7299 if (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)) {
7300 // Assume if there is an fmad instruction that it should be aggressively
7302 if (SDValue Fused = performFaddFmulCombines(ISD::FMAD, true, N, TLI, DAG))
7306 // FADD -> FMA combines:
7307 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
7308 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7309 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
7311 if (!TLI.isOperationLegal(ISD::FMAD, VT)) {
7312 // Don't form FMA if we are preferring FMAD.
7314 = performFaddFmulCombines(ISD::FMA,
7315 TLI.enableAggressiveFMAFusion(VT),
7321 // When FP_EXTEND nodes are free on the target, and there is an opportunity
7322 // to combine into FMA, arrange such nodes accordingly.
7323 if (TLI.isFPExtFree(VT)) {
7325 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7326 if (N0.getOpcode() == ISD::FP_EXTEND) {
7327 SDValue N00 = N0.getOperand(0);
7328 if (N00.getOpcode() == ISD::FMUL)
7329 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7330 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7332 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7333 N00.getOperand(1)), N1);
7336 // fold (fadd x, (fpext (fmul y, z)), z) -> (fma (fpext y), (fpext z), x)
7337 // Note: Commutes FADD operands.
7338 if (N1.getOpcode() == ISD::FP_EXTEND) {
7339 SDValue N10 = N1.getOperand(0);
7340 if (N10.getOpcode() == ISD::FMUL)
7341 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7342 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7344 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7345 N10.getOperand(1)), N0);
7353 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7354 SDValue N0 = N->getOperand(0);
7355 SDValue N1 = N->getOperand(1);
7356 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7357 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7358 EVT VT = N->getValueType(0);
7360 const TargetOptions &Options = DAG.getTarget().Options;
7363 if (VT.isVector()) {
7364 SDValue FoldedVOp = SimplifyVBinOp(N);
7365 if (FoldedVOp.getNode()) return FoldedVOp;
7368 // fold (fsub c1, c2) -> c1-c2
7370 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
7372 // fold (fsub A, (fneg B)) -> (fadd A, B)
7373 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7374 return DAG.getNode(ISD::FADD, dl, VT, N0,
7375 GetNegatedExpression(N1, DAG, LegalOperations));
7377 // If 'unsafe math' is enabled, fold lots of things.
7378 if (Options.UnsafeFPMath) {
7380 if (N1CFP && N1CFP->getValueAPF().isZero())
7383 // (fsub 0, B) -> -B
7384 if (N0CFP && N0CFP->getValueAPF().isZero()) {
7385 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7386 return GetNegatedExpression(N1, DAG, LegalOperations);
7387 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7388 return DAG.getNode(ISD::FNEG, dl, VT, N1);
7391 // (fsub x, x) -> 0.0
7393 return DAG.getConstantFP(0.0f, VT);
7395 // (fsub x, (fadd x, y)) -> (fneg y)
7396 // (fsub x, (fadd y, x)) -> (fneg y)
7397 if (N1.getOpcode() == ISD::FADD) {
7398 SDValue N10 = N1->getOperand(0);
7399 SDValue N11 = N1->getOperand(1);
7401 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
7402 return GetNegatedExpression(N11, DAG, LegalOperations);
7404 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
7405 return GetNegatedExpression(N10, DAG, LegalOperations);
7409 if (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)) {
7410 // Assume if there is an fmad instruction that it should be aggressively
7412 if (SDValue Fused = performFsubFmulCombines(ISD::FMAD, true, N, TLI, DAG))
7416 // FSUB -> FMA combines:
7417 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
7418 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7419 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
7421 if (!TLI.isOperationLegal(ISD::FMAD, VT)) {
7422 // Don't form FMA if we are preferring FMAD.
7425 = performFsubFmulCombines(ISD::FMA,
7426 TLI.enableAggressiveFMAFusion(VT),
7432 // When FP_EXTEND nodes are free on the target, and there is an opportunity
7433 // to combine into FMA, arrange such nodes accordingly.
7434 if (TLI.isFPExtFree(VT)) {
7435 // fold (fsub (fpext (fmul x, y)), z)
7436 // -> (fma (fpext x), (fpext y), (fneg z))
7437 if (N0.getOpcode() == ISD::FP_EXTEND) {
7438 SDValue N00 = N0.getOperand(0);
7439 if (N00.getOpcode() == ISD::FMUL)
7440 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7441 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7443 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7445 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N1));
7448 // fold (fsub x, (fpext (fmul y, z)))
7449 // -> (fma (fneg (fpext y)), (fpext z), x)
7450 // Note: Commutes FSUB operands.
7451 if (N1.getOpcode() == ISD::FP_EXTEND) {
7452 SDValue N10 = N1.getOperand(0);
7453 if (N10.getOpcode() == ISD::FMUL)
7454 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7455 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7456 DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7457 VT, N10.getOperand(0))),
7458 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7463 // fold (fsub (fpext (fneg (fmul, x, y))), z)
7464 // -> (fma (fneg (fpext x)), (fpext y), (fneg z))
7465 if (N0.getOpcode() == ISD::FP_EXTEND) {
7466 SDValue N00 = N0.getOperand(0);
7467 if (N00.getOpcode() == ISD::FNEG) {
7468 SDValue N000 = N00.getOperand(0);
7469 if (N000.getOpcode() == ISD::FMUL) {
7470 return DAG.getNode(ISD::FMA, dl, VT,
7471 DAG.getNode(ISD::FNEG, dl, VT,
7472 DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7473 VT, N000.getOperand(0))),
7474 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7475 N000.getOperand(1)),
7476 DAG.getNode(ISD::FNEG, dl, VT, N1));
7481 // fold (fsub (fneg (fpext (fmul, x, y))), z)
7482 // -> (fma (fneg (fpext x)), (fpext y), (fneg z))
7483 if (N0.getOpcode() == ISD::FNEG) {
7484 SDValue N00 = N0.getOperand(0);
7485 if (N00.getOpcode() == ISD::FP_EXTEND) {
7486 SDValue N000 = N00.getOperand(0);
7487 if (N000.getOpcode() == ISD::FMUL) {
7488 return DAG.getNode(ISD::FMA, dl, VT,
7489 DAG.getNode(ISD::FNEG, dl, VT,
7490 DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7491 VT, N000.getOperand(0))),
7492 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7493 N000.getOperand(1)),
7494 DAG.getNode(ISD::FNEG, dl, VT, N1));
7504 SDValue DAGCombiner::visitFMUL(SDNode *N) {
7505 SDValue N0 = N->getOperand(0);
7506 SDValue N1 = N->getOperand(1);
7507 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7508 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7509 EVT VT = N->getValueType(0);
7510 const TargetOptions &Options = DAG.getTarget().Options;
7513 if (VT.isVector()) {
7514 // This just handles C1 * C2 for vectors. Other vector folds are below.
7515 SDValue FoldedVOp = SimplifyVBinOp(N);
7516 if (FoldedVOp.getNode())
7518 // Canonicalize vector constant to RHS.
7519 if (N0.getOpcode() == ISD::BUILD_VECTOR &&
7520 N1.getOpcode() != ISD::BUILD_VECTOR)
7521 if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
7522 if (BV0->isConstant())
7523 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
7526 // fold (fmul c1, c2) -> c1*c2
7528 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
7530 // canonicalize constant to RHS
7531 if (N0CFP && !N1CFP)
7532 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
7534 // fold (fmul A, 1.0) -> A
7535 if (N1CFP && N1CFP->isExactlyValue(1.0))
7538 if (Options.UnsafeFPMath) {
7539 // fold (fmul A, 0) -> 0
7540 if (N1CFP && N1CFP->getValueAPF().isZero())
7543 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
7544 if (N0.getOpcode() == ISD::FMUL) {
7545 // Fold scalars or any vector constants (not just splats).
7546 // This fold is done in general by InstCombine, but extra fmul insts
7547 // may have been generated during lowering.
7548 SDValue N00 = N0.getOperand(0);
7549 SDValue N01 = N0.getOperand(1);
7550 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
7551 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
7552 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
7554 // Check 1: Make sure that the first operand of the inner multiply is NOT
7555 // a constant. Otherwise, we may induce infinite looping.
7556 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
7557 // Check 2: Make sure that the second operand of the inner multiply and
7558 // the second operand of the outer multiply are constants.
7559 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
7560 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
7562 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
7563 return DAG.getNode(ISD::FMUL, SL, VT, N00, MulConsts);
7568 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
7569 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
7570 // during an early run of DAGCombiner can prevent folding with fmuls
7571 // inserted during lowering.
7572 if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
7574 const SDValue Two = DAG.getConstantFP(2.0, VT);
7575 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
7576 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
7580 // fold (fmul X, 2.0) -> (fadd X, X)
7581 if (N1CFP && N1CFP->isExactlyValue(+2.0))
7582 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
7584 // fold (fmul X, -1.0) -> (fneg X)
7585 if (N1CFP && N1CFP->isExactlyValue(-1.0))
7586 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7587 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
7589 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
7590 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7591 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7592 // Both can be negated for free, check to see if at least one is cheaper
7594 if (LHSNeg == 2 || RHSNeg == 2)
7595 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7596 GetNegatedExpression(N0, DAG, LegalOperations),
7597 GetNegatedExpression(N1, DAG, LegalOperations));
7604 SDValue DAGCombiner::visitFMA(SDNode *N) {
7605 SDValue N0 = N->getOperand(0);
7606 SDValue N1 = N->getOperand(1);
7607 SDValue N2 = N->getOperand(2);
7608 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7609 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7610 EVT VT = N->getValueType(0);
7612 const TargetOptions &Options = DAG.getTarget().Options;
7614 // Constant fold FMA.
7615 if (isa<ConstantFPSDNode>(N0) &&
7616 isa<ConstantFPSDNode>(N1) &&
7617 isa<ConstantFPSDNode>(N2)) {
7618 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
7621 if (Options.UnsafeFPMath) {
7622 if (N0CFP && N0CFP->isZero())
7624 if (N1CFP && N1CFP->isZero())
7627 if (N0CFP && N0CFP->isExactlyValue(1.0))
7628 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
7629 if (N1CFP && N1CFP->isExactlyValue(1.0))
7630 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
7632 // Canonicalize (fma c, x, y) -> (fma x, c, y)
7633 if (N0CFP && !N1CFP)
7634 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
7636 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
7637 if (Options.UnsafeFPMath && N1CFP &&
7638 N2.getOpcode() == ISD::FMUL &&
7639 N0 == N2.getOperand(0) &&
7640 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
7641 return DAG.getNode(ISD::FMUL, dl, VT, N0,
7642 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
7646 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
7647 if (Options.UnsafeFPMath &&
7648 N0.getOpcode() == ISD::FMUL && N1CFP &&
7649 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
7650 return DAG.getNode(ISD::FMA, dl, VT,
7652 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
7656 // (fma x, 1, y) -> (fadd x, y)
7657 // (fma x, -1, y) -> (fadd (fneg x), y)
7659 if (N1CFP->isExactlyValue(1.0))
7660 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
7662 if (N1CFP->isExactlyValue(-1.0) &&
7663 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
7664 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
7665 AddToWorklist(RHSNeg.getNode());
7666 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
7670 // (fma x, c, x) -> (fmul x, (c+1))
7671 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
7672 return DAG.getNode(ISD::FMUL, dl, VT, N0,
7673 DAG.getNode(ISD::FADD, dl, VT,
7674 N1, DAG.getConstantFP(1.0, VT)));
7676 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
7677 if (Options.UnsafeFPMath && N1CFP &&
7678 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
7679 return DAG.getNode(ISD::FMUL, dl, VT, N0,
7680 DAG.getNode(ISD::FADD, dl, VT,
7681 N1, DAG.getConstantFP(-1.0, VT)));
7687 SDValue DAGCombiner::visitFDIV(SDNode *N) {
7688 SDValue N0 = N->getOperand(0);
7689 SDValue N1 = N->getOperand(1);
7690 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7691 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7692 EVT VT = N->getValueType(0);
7694 const TargetOptions &Options = DAG.getTarget().Options;
7697 if (VT.isVector()) {
7698 SDValue FoldedVOp = SimplifyVBinOp(N);
7699 if (FoldedVOp.getNode()) return FoldedVOp;
7702 // fold (fdiv c1, c2) -> c1/c2
7704 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7706 if (Options.UnsafeFPMath) {
7707 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7709 // Compute the reciprocal 1.0 / c2.
7710 APFloat N1APF = N1CFP->getValueAPF();
7711 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7712 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7713 // Only do the transform if the reciprocal is a legal fp immediate that
7714 // isn't too nasty (eg NaN, denormal, ...).
7715 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7716 (!LegalOperations ||
7717 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7718 // backend)... we should handle this gracefully after Legalize.
7719 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7720 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7721 TLI.isFPImmLegal(Recip, VT)))
7722 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7723 DAG.getConstantFP(Recip, VT));
7726 // If this FDIV is part of a reciprocal square root, it may be folded
7727 // into a target-specific square root estimate instruction.
7728 if (N1.getOpcode() == ISD::FSQRT) {
7729 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
7730 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7732 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7733 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7734 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7735 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7736 AddToWorklist(RV.getNode());
7737 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7739 } else if (N1.getOpcode() == ISD::FP_ROUND &&
7740 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7741 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7742 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7743 AddToWorklist(RV.getNode());
7744 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7746 } else if (N1.getOpcode() == ISD::FMUL) {
7747 // Look through an FMUL. Even though this won't remove the FDIV directly,
7748 // it's still worthwhile to get rid of the FSQRT if possible.
7751 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7752 SqrtOp = N1.getOperand(0);
7753 OtherOp = N1.getOperand(1);
7754 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
7755 SqrtOp = N1.getOperand(1);
7756 OtherOp = N1.getOperand(0);
7758 if (SqrtOp.getNode()) {
7759 // We found a FSQRT, so try to make this fold:
7760 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
7761 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
7762 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
7763 AddToWorklist(RV.getNode());
7764 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7769 // Fold into a reciprocal estimate and multiply instead of a real divide.
7770 if (SDValue RV = BuildReciprocalEstimate(N1)) {
7771 AddToWorklist(RV.getNode());
7772 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7776 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7777 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7778 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7779 // Both can be negated for free, check to see if at least one is cheaper
7781 if (LHSNeg == 2 || RHSNeg == 2)
7782 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7783 GetNegatedExpression(N0, DAG, LegalOperations),
7784 GetNegatedExpression(N1, DAG, LegalOperations));
7788 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
7790 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
7791 // Notice that this is not always beneficial. One reason is different target
7792 // may have different costs for FDIV and FMUL, so sometimes the cost of two
7793 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
7794 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
7795 if (Options.UnsafeFPMath) {
7796 // Skip if current node is a reciprocal.
7797 if (N0CFP && N0CFP->isExactlyValue(1.0))
7800 SmallVector<SDNode *, 4> Users;
7801 // Find all FDIV users of the same divisor.
7802 for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
7803 UE = N1.getNode()->use_end();
7805 SDNode *User = UI.getUse().getUser();
7806 if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
7807 Users.push_back(User);
7810 if (TLI.combineRepeatedFPDivisors(Users.size())) {
7811 SDValue FPOne = DAG.getConstantFP(1.0, VT); // floating point 1.0
7812 SDValue Reciprocal = DAG.getNode(ISD::FDIV, SDLoc(N), VT, FPOne, N1);
7814 // Dividend / Divisor -> Dividend * Reciprocal
7815 for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
7816 if ((*I)->getOperand(0) != FPOne) {
7817 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
7818 (*I)->getOperand(0), Reciprocal);
7819 DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
7829 SDValue DAGCombiner::visitFREM(SDNode *N) {
7830 SDValue N0 = N->getOperand(0);
7831 SDValue N1 = N->getOperand(1);
7832 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7833 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7834 EVT VT = N->getValueType(0);
7836 // fold (frem c1, c2) -> fmod(c1,c2)
7838 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7843 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
7844 if (DAG.getTarget().Options.UnsafeFPMath &&
7845 !TLI.isFsqrtCheap()) {
7846 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
7847 if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
7848 EVT VT = RV.getValueType();
7849 RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV);
7850 AddToWorklist(RV.getNode());
7852 // Unfortunately, RV is now NaN if the input was exactly 0.
7853 // Select out this case and force the answer to 0.
7854 SDValue Zero = DAG.getConstantFP(0.0, VT);
7856 DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
7857 N->getOperand(0), Zero, ISD::SETEQ);
7858 AddToWorklist(ZeroCmp.getNode());
7859 AddToWorklist(RV.getNode());
7861 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
7862 SDLoc(N), VT, ZeroCmp, Zero, RV);
7869 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7870 SDValue N0 = N->getOperand(0);
7871 SDValue N1 = N->getOperand(1);
7872 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7873 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7874 EVT VT = N->getValueType(0);
7876 if (N0CFP && N1CFP) // Constant fold
7877 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7880 const APFloat& V = N1CFP->getValueAPF();
7881 // copysign(x, c1) -> fabs(x) iff ispos(c1)
7882 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7883 if (!V.isNegative()) {
7884 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7885 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7887 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7888 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7889 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7893 // copysign(fabs(x), y) -> copysign(x, y)
7894 // copysign(fneg(x), y) -> copysign(x, y)
7895 // copysign(copysign(x,z), y) -> copysign(x, y)
7896 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7897 N0.getOpcode() == ISD::FCOPYSIGN)
7898 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7899 N0.getOperand(0), N1);
7901 // copysign(x, abs(y)) -> abs(x)
7902 if (N1.getOpcode() == ISD::FABS)
7903 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7905 // copysign(x, copysign(y,z)) -> copysign(x, z)
7906 if (N1.getOpcode() == ISD::FCOPYSIGN)
7907 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7908 N0, N1.getOperand(1));
7910 // copysign(x, fp_extend(y)) -> copysign(x, y)
7911 // copysign(x, fp_round(y)) -> copysign(x, y)
7912 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7913 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7914 N0, N1.getOperand(0));
7919 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7920 SDValue N0 = N->getOperand(0);
7921 EVT VT = N->getValueType(0);
7922 EVT OpVT = N0.getValueType();
7924 // fold (sint_to_fp c1) -> c1fp
7925 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7927 // ...but only if the target supports immediate floating-point values
7928 (!LegalOperations ||
7929 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7930 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7932 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7933 // but UINT_TO_FP is legal on this target, try to convert.
7934 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7935 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7936 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7937 if (DAG.SignBitIsZero(N0))
7938 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7941 // The next optimizations are desirable only if SELECT_CC can be lowered.
7942 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7943 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7944 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7946 (!LegalOperations ||
7947 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7949 { N0.getOperand(0), N0.getOperand(1),
7950 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7952 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7955 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7956 // (select_cc x, y, 1.0, 0.0,, cc)
7957 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7958 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7959 (!LegalOperations ||
7960 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7962 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7963 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7964 N0.getOperand(0).getOperand(2) };
7965 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7972 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7973 SDValue N0 = N->getOperand(0);
7974 EVT VT = N->getValueType(0);
7975 EVT OpVT = N0.getValueType();
7977 // fold (uint_to_fp c1) -> c1fp
7978 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7980 // ...but only if the target supports immediate floating-point values
7981 (!LegalOperations ||
7982 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7983 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7985 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7986 // but SINT_TO_FP is legal on this target, try to convert.
7987 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7988 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7989 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7990 if (DAG.SignBitIsZero(N0))
7991 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7994 // The next optimizations are desirable only if SELECT_CC can be lowered.
7995 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7996 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7998 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7999 (!LegalOperations ||
8000 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8002 { N0.getOperand(0), N0.getOperand(1),
8003 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
8005 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
8012 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8013 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8014 SDValue N0 = N->getOperand(0);
8015 EVT VT = N->getValueType(0);
8017 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8020 SDValue Src = N0.getOperand(0);
8021 EVT SrcVT = Src.getValueType();
8022 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8023 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8025 // We can safely assume the conversion won't overflow the output range,
8026 // because (for example) (uint8_t)18293.f is undefined behavior.
8028 // Since we can assume the conversion won't overflow, our decision as to
8029 // whether the input will fit in the float should depend on the minimum
8030 // of the input range and output range.
8032 // This means this is also safe for a signed input and unsigned output, since
8033 // a negative input would lead to undefined behavior.
8034 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8035 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8036 unsigned ActualSize = std::min(InputSize, OutputSize);
8037 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8039 // We can only fold away the float conversion if the input range can be
8040 // represented exactly in the float range.
8041 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8042 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8043 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8045 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8047 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8048 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8051 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8056 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8057 SDValue N0 = N->getOperand(0);
8058 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8059 EVT VT = N->getValueType(0);
8061 // fold (fp_to_sint c1fp) -> c1
8063 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8065 return FoldIntToFPToInt(N, DAG);
8068 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8069 SDValue N0 = N->getOperand(0);
8070 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8071 EVT VT = N->getValueType(0);
8073 // fold (fp_to_uint c1fp) -> c1
8075 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8077 return FoldIntToFPToInt(N, DAG);
8080 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8081 SDValue N0 = N->getOperand(0);
8082 SDValue N1 = N->getOperand(1);
8083 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8084 EVT VT = N->getValueType(0);
8086 // fold (fp_round c1fp) -> c1fp
8088 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8090 // fold (fp_round (fp_extend x)) -> x
8091 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8092 return N0.getOperand(0);
8094 // fold (fp_round (fp_round x)) -> (fp_round x)
8095 if (N0.getOpcode() == ISD::FP_ROUND) {
8096 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8097 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8098 // If the first fp_round isn't a value preserving truncation, it might
8099 // introduce a tie in the second fp_round, that wouldn't occur in the
8100 // single-step fp_round we want to fold to.
8101 // In other words, double rounding isn't the same as rounding.
8102 // Also, this is a value preserving truncation iff both fp_round's are.
8103 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc)
8104 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
8105 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc));
8108 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8109 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8110 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8111 N0.getOperand(0), N1);
8112 AddToWorklist(Tmp.getNode());
8113 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8114 Tmp, N0.getOperand(1));
8120 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8121 SDValue N0 = N->getOperand(0);
8122 EVT VT = N->getValueType(0);
8123 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8124 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8126 // fold (fp_round_inreg c1fp) -> c1fp
8127 if (N0CFP && isTypeLegal(EVT)) {
8128 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
8129 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
8135 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8136 SDValue N0 = N->getOperand(0);
8137 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8138 EVT VT = N->getValueType(0);
8140 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8141 if (N->hasOneUse() &&
8142 N->use_begin()->getOpcode() == ISD::FP_ROUND)
8145 // fold (fp_extend c1fp) -> c1fp
8147 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8149 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8151 if (N0.getOpcode() == ISD::FP_ROUND
8152 && N0.getNode()->getConstantOperandVal(1) == 1) {
8153 SDValue In = N0.getOperand(0);
8154 if (In.getValueType() == VT) return In;
8155 if (VT.bitsLT(In.getValueType()))
8156 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8157 In, N0.getOperand(1));
8158 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8161 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8162 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8163 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8164 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8165 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8167 LN0->getBasePtr(), N0.getValueType(),
8168 LN0->getMemOperand());
8169 CombineTo(N, ExtLoad);
8170 CombineTo(N0.getNode(),
8171 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8172 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
8173 ExtLoad.getValue(1));
8174 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8180 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8181 SDValue N0 = N->getOperand(0);
8182 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8183 EVT VT = N->getValueType(0);
8185 // fold (fceil c1) -> fceil(c1)
8187 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8192 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8193 SDValue N0 = N->getOperand(0);
8194 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8195 EVT VT = N->getValueType(0);
8197 // fold (ftrunc c1) -> ftrunc(c1)
8199 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8204 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8205 SDValue N0 = N->getOperand(0);
8206 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8207 EVT VT = N->getValueType(0);
8209 // fold (ffloor c1) -> ffloor(c1)
8211 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8216 // FIXME: FNEG and FABS have a lot in common; refactor.
8217 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8218 SDValue N0 = N->getOperand(0);
8219 EVT VT = N->getValueType(0);
8221 if (VT.isVector()) {
8222 SDValue FoldedVOp = SimplifyVUnaryOp(N);
8223 if (FoldedVOp.getNode()) return FoldedVOp;
8226 // Constant fold FNEG.
8227 if (isa<ConstantFPSDNode>(N0))
8228 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
8230 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8231 &DAG.getTarget().Options))
8232 return GetNegatedExpression(N0, DAG, LegalOperations);
8234 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8235 // constant pool values.
8236 if (!TLI.isFNegFree(VT) &&
8237 N0.getOpcode() == ISD::BITCAST &&
8238 N0.getNode()->hasOneUse()) {
8239 SDValue Int = N0.getOperand(0);
8240 EVT IntVT = Int.getValueType();
8241 if (IntVT.isInteger() && !IntVT.isVector()) {
8243 if (N0.getValueType().isVector()) {
8244 // For a vector, get a mask such as 0x80... per scalar element
8246 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8247 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8249 // For a scalar, just generate 0x80...
8250 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8252 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
8253 DAG.getConstant(SignMask, IntVT));
8254 AddToWorklist(Int.getNode());
8255 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8259 // (fneg (fmul c, x)) -> (fmul -c, x)
8260 if (N0.getOpcode() == ISD::FMUL) {
8261 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8263 APFloat CVal = CFP1->getValueAPF();
8265 if (Level >= AfterLegalizeDAG &&
8266 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8267 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8269 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8270 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8277 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8278 SDValue N0 = N->getOperand(0);
8279 SDValue N1 = N->getOperand(1);
8280 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8281 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8283 if (N0CFP && N1CFP) {
8284 const APFloat &C0 = N0CFP->getValueAPF();
8285 const APFloat &C1 = N1CFP->getValueAPF();
8286 return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0));
8290 EVT VT = N->getValueType(0);
8291 // Canonicalize to constant on RHS.
8292 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8298 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8299 SDValue N0 = N->getOperand(0);
8300 SDValue N1 = N->getOperand(1);
8301 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8302 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8304 if (N0CFP && N1CFP) {
8305 const APFloat &C0 = N0CFP->getValueAPF();
8306 const APFloat &C1 = N1CFP->getValueAPF();
8307 return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0));
8311 EVT VT = N->getValueType(0);
8312 // Canonicalize to constant on RHS.
8313 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8319 SDValue DAGCombiner::visitFABS(SDNode *N) {
8320 SDValue N0 = N->getOperand(0);
8321 EVT VT = N->getValueType(0);
8323 if (VT.isVector()) {
8324 SDValue FoldedVOp = SimplifyVUnaryOp(N);
8325 if (FoldedVOp.getNode()) return FoldedVOp;
8328 // fold (fabs c1) -> fabs(c1)
8329 if (isa<ConstantFPSDNode>(N0))
8330 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8332 // fold (fabs (fabs x)) -> (fabs x)
8333 if (N0.getOpcode() == ISD::FABS)
8334 return N->getOperand(0);
8336 // fold (fabs (fneg x)) -> (fabs x)
8337 // fold (fabs (fcopysign x, y)) -> (fabs x)
8338 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8339 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8341 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8342 // constant pool values.
8343 if (!TLI.isFAbsFree(VT) &&
8344 N0.getOpcode() == ISD::BITCAST &&
8345 N0.getNode()->hasOneUse()) {
8346 SDValue Int = N0.getOperand(0);
8347 EVT IntVT = Int.getValueType();
8348 if (IntVT.isInteger() && !IntVT.isVector()) {
8350 if (N0.getValueType().isVector()) {
8351 // For a vector, get a mask such as 0x7f... per scalar element
8353 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8354 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8356 // For a scalar, just generate 0x7f...
8357 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8359 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
8360 DAG.getConstant(SignMask, IntVT));
8361 AddToWorklist(Int.getNode());
8362 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8369 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8370 SDValue Chain = N->getOperand(0);
8371 SDValue N1 = N->getOperand(1);
8372 SDValue N2 = N->getOperand(2);
8374 // If N is a constant we could fold this into a fallthrough or unconditional
8375 // branch. However that doesn't happen very often in normal code, because
8376 // Instcombine/SimplifyCFG should have handled the available opportunities.
8377 // If we did this folding here, it would be necessary to update the
8378 // MachineBasicBlock CFG, which is awkward.
8380 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8382 if (N1.getOpcode() == ISD::SETCC &&
8383 TLI.isOperationLegalOrCustom(ISD::BR_CC,
8384 N1.getOperand(0).getValueType())) {
8385 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8386 Chain, N1.getOperand(2),
8387 N1.getOperand(0), N1.getOperand(1), N2);
8390 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8391 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8392 (N1.getOperand(0).hasOneUse() &&
8393 N1.getOperand(0).getOpcode() == ISD::SRL))) {
8394 SDNode *Trunc = nullptr;
8395 if (N1.getOpcode() == ISD::TRUNCATE) {
8396 // Look pass the truncate.
8397 Trunc = N1.getNode();
8398 N1 = N1.getOperand(0);
8401 // Match this pattern so that we can generate simpler code:
8404 // %b = and i32 %a, 2
8405 // %c = srl i32 %b, 1
8406 // brcond i32 %c ...
8411 // %b = and i32 %a, 2
8412 // %c = setcc eq %b, 0
8415 // This applies only when the AND constant value has one bit set and the
8416 // SRL constant is equal to the log2 of the AND constant. The back-end is
8417 // smart enough to convert the result into a TEST/JMP sequence.
8418 SDValue Op0 = N1.getOperand(0);
8419 SDValue Op1 = N1.getOperand(1);
8421 if (Op0.getOpcode() == ISD::AND &&
8422 Op1.getOpcode() == ISD::Constant) {
8423 SDValue AndOp1 = Op0.getOperand(1);
8425 if (AndOp1.getOpcode() == ISD::Constant) {
8426 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8428 if (AndConst.isPowerOf2() &&
8429 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8431 DAG.getSetCC(SDLoc(N),
8432 getSetCCResultType(Op0.getValueType()),
8433 Op0, DAG.getConstant(0, Op0.getValueType()),
8436 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
8437 MVT::Other, Chain, SetCC, N2);
8438 // Don't add the new BRCond into the worklist or else SimplifySelectCC
8439 // will convert it back to (X & C1) >> C2.
8440 CombineTo(N, NewBRCond, false);
8441 // Truncate is dead.
8443 deleteAndRecombine(Trunc);
8444 // Replace the uses of SRL with SETCC
8445 WorklistRemover DeadNodes(*this);
8446 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8447 deleteAndRecombine(N1.getNode());
8448 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8454 // Restore N1 if the above transformation doesn't match.
8455 N1 = N->getOperand(1);
8458 // Transform br(xor(x, y)) -> br(x != y)
8459 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8460 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8461 SDNode *TheXor = N1.getNode();
8462 SDValue Op0 = TheXor->getOperand(0);
8463 SDValue Op1 = TheXor->getOperand(1);
8464 if (Op0.getOpcode() == Op1.getOpcode()) {
8465 // Avoid missing important xor optimizations.
8466 SDValue Tmp = visitXOR(TheXor);
8467 if (Tmp.getNode()) {
8468 if (Tmp.getNode() != TheXor) {
8469 DEBUG(dbgs() << "\nReplacing.8 ";
8471 dbgs() << "\nWith: ";
8472 Tmp.getNode()->dump(&DAG);
8474 WorklistRemover DeadNodes(*this);
8475 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
8476 deleteAndRecombine(TheXor);
8477 return DAG.getNode(ISD::BRCOND, SDLoc(N),
8478 MVT::Other, Chain, Tmp, N2);
8481 // visitXOR has changed XOR's operands or replaced the XOR completely,
8483 return SDValue(N, 0);
8487 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8489 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
8490 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
8491 Op0.getOpcode() == ISD::XOR) {
8492 TheXor = Op0.getNode();
8496 EVT SetCCVT = N1.getValueType();
8498 SetCCVT = getSetCCResultType(SetCCVT);
8499 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
8502 Equal ? ISD::SETEQ : ISD::SETNE);
8503 // Replace the uses of XOR with SETCC
8504 WorklistRemover DeadNodes(*this);
8505 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8506 deleteAndRecombine(N1.getNode());
8507 return DAG.getNode(ISD::BRCOND, SDLoc(N),
8508 MVT::Other, Chain, SetCC, N2);
8515 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
8517 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
8518 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
8519 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
8521 // If N is a constant we could fold this into a fallthrough or unconditional
8522 // branch. However that doesn't happen very often in normal code, because
8523 // Instcombine/SimplifyCFG should have handled the available opportunities.
8524 // If we did this folding here, it would be necessary to update the
8525 // MachineBasicBlock CFG, which is awkward.
8527 // Use SimplifySetCC to simplify SETCC's.
8528 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
8529 CondLHS, CondRHS, CC->get(), SDLoc(N),
8531 if (Simp.getNode()) AddToWorklist(Simp.getNode());
8533 // fold to a simpler setcc
8534 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
8535 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8536 N->getOperand(0), Simp.getOperand(2),
8537 Simp.getOperand(0), Simp.getOperand(1),
8543 /// Return true if 'Use' is a load or a store that uses N as its base pointer
8544 /// and that N may be folded in the load / store addressing mode.
8545 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
8547 const TargetLowering &TLI) {
8549 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
8550 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
8552 VT = Use->getValueType(0);
8553 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
8554 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
8556 VT = ST->getValue().getValueType();
8560 TargetLowering::AddrMode AM;
8561 if (N->getOpcode() == ISD::ADD) {
8562 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8565 AM.BaseOffs = Offset->getSExtValue();
8569 } else if (N->getOpcode() == ISD::SUB) {
8570 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8573 AM.BaseOffs = -Offset->getSExtValue();
8580 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
8583 /// Try turning a load/store into a pre-indexed load/store when the base
8584 /// pointer is an add or subtract and it has other uses besides the load/store.
8585 /// After the transformation, the new indexed load/store has effectively folded
8586 /// the add/subtract in and all of its other uses are redirected to the
8588 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
8589 if (Level < AfterLegalizeDAG)
8595 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8596 if (LD->isIndexed())
8598 VT = LD->getMemoryVT();
8599 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
8600 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
8602 Ptr = LD->getBasePtr();
8603 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8604 if (ST->isIndexed())
8606 VT = ST->getMemoryVT();
8607 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
8608 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
8610 Ptr = ST->getBasePtr();
8616 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
8617 // out. There is no reason to make this a preinc/predec.
8618 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
8619 Ptr.getNode()->hasOneUse())
8622 // Ask the target to do addressing mode selection.
8625 ISD::MemIndexedMode AM = ISD::UNINDEXED;
8626 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
8629 // Backends without true r+i pre-indexed forms may need to pass a
8630 // constant base with a variable offset so that constant coercion
8631 // will work with the patterns in canonical form.
8632 bool Swapped = false;
8633 if (isa<ConstantSDNode>(BasePtr)) {
8634 std::swap(BasePtr, Offset);
8638 // Don't create a indexed load / store with zero offset.
8639 if (isa<ConstantSDNode>(Offset) &&
8640 cast<ConstantSDNode>(Offset)->isNullValue())
8643 // Try turning it into a pre-indexed load / store except when:
8644 // 1) The new base ptr is a frame index.
8645 // 2) If N is a store and the new base ptr is either the same as or is a
8646 // predecessor of the value being stored.
8647 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
8648 // that would create a cycle.
8649 // 4) All uses are load / store ops that use it as old base ptr.
8651 // Check #1. Preinc'ing a frame index would require copying the stack pointer
8652 // (plus the implicit offset) to a register to preinc anyway.
8653 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8658 SDValue Val = cast<StoreSDNode>(N)->getValue();
8659 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
8663 // If the offset is a constant, there may be other adds of constants that
8664 // can be folded with this one. We should do this to avoid having to keep
8665 // a copy of the original base pointer.
8666 SmallVector<SDNode *, 16> OtherUses;
8667 if (isa<ConstantSDNode>(Offset))
8668 for (SDNode *Use : BasePtr.getNode()->uses()) {
8669 if (Use == Ptr.getNode())
8672 if (Use->isPredecessorOf(N))
8675 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
8680 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
8681 if (Op1.getNode() == BasePtr.getNode())
8682 std::swap(Op0, Op1);
8683 assert(Op0.getNode() == BasePtr.getNode() &&
8684 "Use of ADD/SUB but not an operand");
8686 if (!isa<ConstantSDNode>(Op1)) {
8691 // FIXME: In some cases, we can be smarter about this.
8692 if (Op1.getValueType() != Offset.getValueType()) {
8697 OtherUses.push_back(Use);
8701 std::swap(BasePtr, Offset);
8703 // Now check for #3 and #4.
8704 bool RealUse = false;
8706 // Caches for hasPredecessorHelper
8707 SmallPtrSet<const SDNode *, 32> Visited;
8708 SmallVector<const SDNode *, 16> Worklist;
8710 for (SDNode *Use : Ptr.getNode()->uses()) {
8713 if (N->hasPredecessorHelper(Use, Visited, Worklist))
8716 // If Ptr may be folded in addressing mode of other use, then it's
8717 // not profitable to do this transformation.
8718 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
8727 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8728 BasePtr, Offset, AM);
8730 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8731 BasePtr, Offset, AM);
8734 DEBUG(dbgs() << "\nReplacing.4 ";
8736 dbgs() << "\nWith: ";
8737 Result.getNode()->dump(&DAG);
8739 WorklistRemover DeadNodes(*this);
8741 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8742 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8744 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8747 // Finally, since the node is now dead, remove it from the graph.
8748 deleteAndRecombine(N);
8751 std::swap(BasePtr, Offset);
8753 // Replace other uses of BasePtr that can be updated to use Ptr
8754 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
8755 unsigned OffsetIdx = 1;
8756 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
8758 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
8759 BasePtr.getNode() && "Expected BasePtr operand");
8761 // We need to replace ptr0 in the following expression:
8762 // x0 * offset0 + y0 * ptr0 = t0
8764 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
8766 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
8767 // indexed load/store and the expresion that needs to be re-written.
8769 // Therefore, we have:
8770 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
8772 ConstantSDNode *CN =
8773 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
8775 APInt Offset0 = CN->getAPIntValue();
8776 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
8778 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
8779 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
8780 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
8781 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
8783 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
8785 APInt CNV = Offset0;
8786 if (X0 < 0) CNV = -CNV;
8787 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
8788 else CNV = CNV - Offset1;
8790 // We can now generate the new expression.
8791 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
8792 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
8794 SDValue NewUse = DAG.getNode(Opcode,
8795 SDLoc(OtherUses[i]),
8796 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
8797 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
8798 deleteAndRecombine(OtherUses[i]);
8801 // Replace the uses of Ptr with uses of the updated base value.
8802 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
8803 deleteAndRecombine(Ptr.getNode());
8808 /// Try to combine a load/store with a add/sub of the base pointer node into a
8809 /// post-indexed load/store. The transformation folded the add/subtract into the
8810 /// new indexed load/store effectively and all of its uses are redirected to the
8812 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
8813 if (Level < AfterLegalizeDAG)
8819 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8820 if (LD->isIndexed())
8822 VT = LD->getMemoryVT();
8823 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
8824 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
8826 Ptr = LD->getBasePtr();
8827 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8828 if (ST->isIndexed())
8830 VT = ST->getMemoryVT();
8831 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
8832 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
8834 Ptr = ST->getBasePtr();
8840 if (Ptr.getNode()->hasOneUse())
8843 for (SDNode *Op : Ptr.getNode()->uses()) {
8845 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
8850 ISD::MemIndexedMode AM = ISD::UNINDEXED;
8851 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
8852 // Don't create a indexed load / store with zero offset.
8853 if (isa<ConstantSDNode>(Offset) &&
8854 cast<ConstantSDNode>(Offset)->isNullValue())
8857 // Try turning it into a post-indexed load / store except when
8858 // 1) All uses are load / store ops that use it as base ptr (and
8859 // it may be folded as addressing mmode).
8860 // 2) Op must be independent of N, i.e. Op is neither a predecessor
8861 // nor a successor of N. Otherwise, if Op is folded that would
8864 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8868 bool TryNext = false;
8869 for (SDNode *Use : BasePtr.getNode()->uses()) {
8870 if (Use == Ptr.getNode())
8873 // If all the uses are load / store addresses, then don't do the
8875 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
8876 bool RealUse = false;
8877 for (SDNode *UseUse : Use->uses()) {
8878 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
8893 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
8894 SDValue Result = isLoad
8895 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8896 BasePtr, Offset, AM)
8897 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8898 BasePtr, Offset, AM);
8901 DEBUG(dbgs() << "\nReplacing.5 ";
8903 dbgs() << "\nWith: ";
8904 Result.getNode()->dump(&DAG);
8906 WorklistRemover DeadNodes(*this);
8908 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8909 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8911 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8914 // Finally, since the node is now dead, remove it from the graph.
8915 deleteAndRecombine(N);
8917 // Replace the uses of Use with uses of the updated base value.
8918 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8919 Result.getValue(isLoad ? 1 : 0));
8920 deleteAndRecombine(Op);
8929 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
8930 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8931 ISD::MemIndexedMode AM = LD->getAddressingMode();
8932 assert(AM != ISD::UNINDEXED);
8933 SDValue BP = LD->getOperand(1);
8934 SDValue Inc = LD->getOperand(2);
8936 // Some backends use TargetConstants for load offsets, but don't expect
8937 // TargetConstants in general ADD nodes. We can convert these constants into
8938 // regular Constants (if the constant is not opaque).
8939 assert((Inc.getOpcode() != ISD::TargetConstant ||
8940 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8941 "Cannot split out indexing using opaque target constants");
8942 if (Inc.getOpcode() == ISD::TargetConstant) {
8943 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8944 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8945 ConstInc->getValueType(0));
8949 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8950 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8953 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8954 LoadSDNode *LD = cast<LoadSDNode>(N);
8955 SDValue Chain = LD->getChain();
8956 SDValue Ptr = LD->getBasePtr();
8958 // If load is not volatile and there are no uses of the loaded value (and
8959 // the updated indexed value in case of indexed loads), change uses of the
8960 // chain value into uses of the chain input (i.e. delete the dead load).
8961 if (!LD->isVolatile()) {
8962 if (N->getValueType(1) == MVT::Other) {
8964 if (!N->hasAnyUseOfValue(0)) {
8965 // It's not safe to use the two value CombineTo variant here. e.g.
8966 // v1, chain2 = load chain1, loc
8967 // v2, chain3 = load chain2, loc
8969 // Now we replace use of chain2 with chain1. This makes the second load
8970 // isomorphic to the one we are deleting, and thus makes this load live.
8971 DEBUG(dbgs() << "\nReplacing.6 ";
8973 dbgs() << "\nWith chain: ";
8974 Chain.getNode()->dump(&DAG);
8976 WorklistRemover DeadNodes(*this);
8977 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8980 deleteAndRecombine(N);
8982 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8986 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8988 // If this load has an opaque TargetConstant offset, then we cannot split
8989 // the indexing into an add/sub directly (that TargetConstant may not be
8990 // valid for a different type of node, and we cannot convert an opaque
8991 // target constant into a regular constant).
8992 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
8993 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
8995 if (!N->hasAnyUseOfValue(0) &&
8996 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
8997 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8999 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9000 Index = SplitIndexingFromLoad(LD);
9001 // Try to fold the base pointer arithmetic into subsequent loads and
9003 AddUsersToWorklist(N);
9005 Index = DAG.getUNDEF(N->getValueType(1));
9006 DEBUG(dbgs() << "\nReplacing.7 ";
9008 dbgs() << "\nWith: ";
9009 Undef.getNode()->dump(&DAG);
9010 dbgs() << " and 2 other values\n");
9011 WorklistRemover DeadNodes(*this);
9012 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9013 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9014 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9015 deleteAndRecombine(N);
9016 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9021 // If this load is directly stored, replace the load value with the stored
9023 // TODO: Handle store large -> read small portion.
9024 // TODO: Handle TRUNCSTORE/LOADEXT
9025 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9026 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9027 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9028 if (PrevST->getBasePtr() == Ptr &&
9029 PrevST->getValue().getValueType() == N->getValueType(0))
9030 return CombineTo(N, Chain.getOperand(1), Chain);
9034 // Try to infer better alignment information than the load already has.
9035 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9036 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9037 if (Align > LD->getMemOperand()->getBaseAlignment()) {
9039 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9040 LD->getValueType(0),
9041 Chain, Ptr, LD->getPointerInfo(),
9043 LD->isVolatile(), LD->isNonTemporal(),
9044 LD->isInvariant(), Align, LD->getAAInfo());
9045 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9050 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9051 : DAG.getSubtarget().useAA();
9053 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9054 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9057 if (UseAA && LD->isUnindexed()) {
9058 // Walk up chain skipping non-aliasing memory nodes.
9059 SDValue BetterChain = FindBetterChain(N, Chain);
9061 // If there is a better chain.
9062 if (Chain != BetterChain) {
9065 // Replace the chain to void dependency.
9066 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9067 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9068 BetterChain, Ptr, LD->getMemOperand());
9070 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9071 LD->getValueType(0),
9072 BetterChain, Ptr, LD->getMemoryVT(),
9073 LD->getMemOperand());
9076 // Create token factor to keep old chain connected.
9077 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9078 MVT::Other, Chain, ReplLoad.getValue(1));
9080 // Make sure the new and old chains are cleaned up.
9081 AddToWorklist(Token.getNode());
9083 // Replace uses with load result and token factor. Don't add users
9085 return CombineTo(N, ReplLoad.getValue(0), Token, false);
9089 // Try transforming N to an indexed load.
9090 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9091 return SDValue(N, 0);
9093 // Try to slice up N to more direct loads if the slices are mapped to
9094 // different register banks or pairing can take place.
9096 return SDValue(N, 0);
9102 /// \brief Helper structure used to slice a load in smaller loads.
9103 /// Basically a slice is obtained from the following sequence:
9104 /// Origin = load Ty1, Base
9105 /// Shift = srl Ty1 Origin, CstTy Amount
9106 /// Inst = trunc Shift to Ty2
9108 /// Then, it will be rewriten into:
9109 /// Slice = load SliceTy, Base + SliceOffset
9110 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9112 /// SliceTy is deduced from the number of bits that are actually used to
9114 struct LoadedSlice {
9115 /// \brief Helper structure used to compute the cost of a slice.
9117 /// Are we optimizing for code size.
9122 unsigned CrossRegisterBanksCopies;
9126 Cost(bool ForCodeSize = false)
9127 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9128 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9130 /// \brief Get the cost of one isolated slice.
9131 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9132 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9133 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9134 EVT TruncType = LS.Inst->getValueType(0);
9135 EVT LoadedType = LS.getLoadedType();
9136 if (TruncType != LoadedType &&
9137 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9141 /// \brief Account for slicing gain in the current cost.
9142 /// Slicing provide a few gains like removing a shift or a
9143 /// truncate. This method allows to grow the cost of the original
9144 /// load with the gain from this slice.
9145 void addSliceGain(const LoadedSlice &LS) {
9146 // Each slice saves a truncate.
9147 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9148 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9149 LS.Inst->getOperand(0).getValueType()))
9151 // If there is a shift amount, this slice gets rid of it.
9154 // If this slice can merge a cross register bank copy, account for it.
9155 if (LS.canMergeExpensiveCrossRegisterBankCopy())
9156 ++CrossRegisterBanksCopies;
9159 Cost &operator+=(const Cost &RHS) {
9161 Truncates += RHS.Truncates;
9162 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9168 bool operator==(const Cost &RHS) const {
9169 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9170 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9171 ZExts == RHS.ZExts && Shift == RHS.Shift;
9174 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9176 bool operator<(const Cost &RHS) const {
9177 // Assume cross register banks copies are as expensive as loads.
9178 // FIXME: Do we want some more target hooks?
9179 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9180 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9181 // Unless we are optimizing for code size, consider the
9182 // expensive operation first.
9183 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9184 return ExpensiveOpsLHS < ExpensiveOpsRHS;
9185 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9186 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9189 bool operator>(const Cost &RHS) const { return RHS < *this; }
9191 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9193 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9195 // The last instruction that represent the slice. This should be a
9196 // truncate instruction.
9198 // The original load instruction.
9200 // The right shift amount in bits from the original load.
9202 // The DAG from which Origin came from.
9203 // This is used to get some contextual information about legal types, etc.
9206 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9207 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9208 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9210 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9211 /// \return Result is \p BitWidth and has used bits set to 1 and
9212 /// not used bits set to 0.
9213 APInt getUsedBits() const {
9214 // Reproduce the trunc(lshr) sequence:
9215 // - Start from the truncated value.
9216 // - Zero extend to the desired bit width.
9218 assert(Origin && "No original load to compare against.");
9219 unsigned BitWidth = Origin->getValueSizeInBits(0);
9220 assert(Inst && "This slice is not bound to an instruction");
9221 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9222 "Extracted slice is bigger than the whole type!");
9223 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9224 UsedBits.setAllBits();
9225 UsedBits = UsedBits.zext(BitWidth);
9230 /// \brief Get the size of the slice to be loaded in bytes.
9231 unsigned getLoadedSize() const {
9232 unsigned SliceSize = getUsedBits().countPopulation();
9233 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9234 return SliceSize / 8;
9237 /// \brief Get the type that will be loaded for this slice.
9238 /// Note: This may not be the final type for the slice.
9239 EVT getLoadedType() const {
9240 assert(DAG && "Missing context");
9241 LLVMContext &Ctxt = *DAG->getContext();
9242 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9245 /// \brief Get the alignment of the load used for this slice.
9246 unsigned getAlignment() const {
9247 unsigned Alignment = Origin->getAlignment();
9248 unsigned Offset = getOffsetFromBase();
9250 Alignment = MinAlign(Alignment, Alignment + Offset);
9254 /// \brief Check if this slice can be rewritten with legal operations.
9255 bool isLegal() const {
9256 // An invalid slice is not legal.
9257 if (!Origin || !Inst || !DAG)
9260 // Offsets are for indexed load only, we do not handle that.
9261 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9264 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9266 // Check that the type is legal.
9267 EVT SliceType = getLoadedType();
9268 if (!TLI.isTypeLegal(SliceType))
9271 // Check that the load is legal for this type.
9272 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9275 // Check that the offset can be computed.
9276 // 1. Check its type.
9277 EVT PtrType = Origin->getBasePtr().getValueType();
9278 if (PtrType == MVT::Untyped || PtrType.isExtended())
9281 // 2. Check that it fits in the immediate.
9282 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9285 // 3. Check that the computation is legal.
9286 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9289 // Check that the zext is legal if it needs one.
9290 EVT TruncateType = Inst->getValueType(0);
9291 if (TruncateType != SliceType &&
9292 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9298 /// \brief Get the offset in bytes of this slice in the original chunk of
9300 /// \pre DAG != nullptr.
9301 uint64_t getOffsetFromBase() const {
9302 assert(DAG && "Missing context.");
9304 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9305 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9306 uint64_t Offset = Shift / 8;
9307 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9308 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9309 "The size of the original loaded type is not a multiple of a"
9311 // If Offset is bigger than TySizeInBytes, it means we are loading all
9312 // zeros. This should have been optimized before in the process.
9313 assert(TySizeInBytes > Offset &&
9314 "Invalid shift amount for given loaded size");
9316 Offset = TySizeInBytes - Offset - getLoadedSize();
9320 /// \brief Generate the sequence of instructions to load the slice
9321 /// represented by this object and redirect the uses of this slice to
9322 /// this new sequence of instructions.
9323 /// \pre this->Inst && this->Origin are valid Instructions and this
9324 /// object passed the legal check: LoadedSlice::isLegal returned true.
9325 /// \return The last instruction of the sequence used to load the slice.
9326 SDValue loadSlice() const {
9327 assert(Inst && Origin && "Unable to replace a non-existing slice.");
9328 const SDValue &OldBaseAddr = Origin->getBasePtr();
9329 SDValue BaseAddr = OldBaseAddr;
9330 // Get the offset in that chunk of bytes w.r.t. the endianess.
9331 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9332 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9334 // BaseAddr = BaseAddr + Offset.
9335 EVT ArithType = BaseAddr.getValueType();
9336 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
9337 DAG->getConstant(Offset, ArithType));
9340 // Create the type of the loaded slice according to its size.
9341 EVT SliceType = getLoadedType();
9343 // Create the load for the slice.
9344 SDValue LastInst = DAG->getLoad(
9345 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9346 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9347 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9348 // If the final type is not the same as the loaded type, this means that
9349 // we have to pad with zero. Create a zero extend for that.
9350 EVT FinalType = Inst->getValueType(0);
9351 if (SliceType != FinalType)
9353 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9357 /// \brief Check if this slice can be merged with an expensive cross register
9358 /// bank copy. E.g.,
9360 /// f = bitcast i32 i to float
9361 bool canMergeExpensiveCrossRegisterBankCopy() const {
9362 if (!Inst || !Inst->hasOneUse())
9364 SDNode *Use = *Inst->use_begin();
9365 if (Use->getOpcode() != ISD::BITCAST)
9367 assert(DAG && "Missing context");
9368 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9369 EVT ResVT = Use->getValueType(0);
9370 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9371 const TargetRegisterClass *ArgRC =
9372 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9373 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9376 // At this point, we know that we perform a cross-register-bank copy.
9377 // Check if it is expensive.
9378 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9379 // Assume bitcasts are cheap, unless both register classes do not
9380 // explicitly share a common sub class.
9381 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9384 // Check if it will be merged with the load.
9385 // 1. Check the alignment constraint.
9386 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9387 ResVT.getTypeForEVT(*DAG->getContext()));
9389 if (RequiredAlignment > getAlignment())
9392 // 2. Check that the load is a legal operation for that type.
9393 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9396 // 3. Check that we do not have a zext in the way.
9397 if (Inst->getValueType(0) != getLoadedType())
9405 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9406 /// \p UsedBits looks like 0..0 1..1 0..0.
9407 static bool areUsedBitsDense(const APInt &UsedBits) {
9408 // If all the bits are one, this is dense!
9409 if (UsedBits.isAllOnesValue())
9412 // Get rid of the unused bits on the right.
9413 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9414 // Get rid of the unused bits on the left.
9415 if (NarrowedUsedBits.countLeadingZeros())
9416 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9417 // Check that the chunk of bits is completely used.
9418 return NarrowedUsedBits.isAllOnesValue();
9421 /// \brief Check whether or not \p First and \p Second are next to each other
9422 /// in memory. This means that there is no hole between the bits loaded
9423 /// by \p First and the bits loaded by \p Second.
9424 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9425 const LoadedSlice &Second) {
9426 assert(First.Origin == Second.Origin && First.Origin &&
9427 "Unable to match different memory origins.");
9428 APInt UsedBits = First.getUsedBits();
9429 assert((UsedBits & Second.getUsedBits()) == 0 &&
9430 "Slices are not supposed to overlap.");
9431 UsedBits |= Second.getUsedBits();
9432 return areUsedBitsDense(UsedBits);
9435 /// \brief Adjust the \p GlobalLSCost according to the target
9436 /// paring capabilities and the layout of the slices.
9437 /// \pre \p GlobalLSCost should account for at least as many loads as
9438 /// there is in the slices in \p LoadedSlices.
9439 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9440 LoadedSlice::Cost &GlobalLSCost) {
9441 unsigned NumberOfSlices = LoadedSlices.size();
9442 // If there is less than 2 elements, no pairing is possible.
9443 if (NumberOfSlices < 2)
9446 // Sort the slices so that elements that are likely to be next to each
9447 // other in memory are next to each other in the list.
9448 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9449 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9450 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9451 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9453 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9454 // First (resp. Second) is the first (resp. Second) potentially candidate
9455 // to be placed in a paired load.
9456 const LoadedSlice *First = nullptr;
9457 const LoadedSlice *Second = nullptr;
9458 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9459 // Set the beginning of the pair.
9462 Second = &LoadedSlices[CurrSlice];
9464 // If First is NULL, it means we start a new pair.
9465 // Get to the next slice.
9469 EVT LoadedType = First->getLoadedType();
9471 // If the types of the slices are different, we cannot pair them.
9472 if (LoadedType != Second->getLoadedType())
9475 // Check if the target supplies paired loads for this type.
9476 unsigned RequiredAlignment = 0;
9477 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9478 // move to the next pair, this type is hopeless.
9482 // Check if we meet the alignment requirement.
9483 if (RequiredAlignment > First->getAlignment())
9486 // Check that both loads are next to each other in memory.
9487 if (!areSlicesNextToEachOther(*First, *Second))
9490 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9491 --GlobalLSCost.Loads;
9492 // Move to the next pair.
9497 /// \brief Check the profitability of all involved LoadedSlice.
9498 /// Currently, it is considered profitable if there is exactly two
9499 /// involved slices (1) which are (2) next to each other in memory, and
9500 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9502 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
9503 /// the elements themselves.
9505 /// FIXME: When the cost model will be mature enough, we can relax
9506 /// constraints (1) and (2).
9507 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9508 const APInt &UsedBits, bool ForCodeSize) {
9509 unsigned NumberOfSlices = LoadedSlices.size();
9510 if (StressLoadSlicing)
9511 return NumberOfSlices > 1;
9514 if (NumberOfSlices != 2)
9518 if (!areUsedBitsDense(UsedBits))
9522 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
9523 // The original code has one big load.
9525 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
9526 const LoadedSlice &LS = LoadedSlices[CurrSlice];
9527 // Accumulate the cost of all the slices.
9528 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
9529 GlobalSlicingCost += SliceCost;
9531 // Account as cost in the original configuration the gain obtained
9532 // with the current slices.
9533 OrigCost.addSliceGain(LS);
9536 // If the target supports paired load, adjust the cost accordingly.
9537 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
9538 return OrigCost > GlobalSlicingCost;
9541 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
9542 /// operations, split it in the various pieces being extracted.
9544 /// This sort of thing is introduced by SROA.
9545 /// This slicing takes care not to insert overlapping loads.
9546 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
9547 bool DAGCombiner::SliceUpLoad(SDNode *N) {
9548 if (Level < AfterLegalizeDAG)
9551 LoadSDNode *LD = cast<LoadSDNode>(N);
9552 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
9553 !LD->getValueType(0).isInteger())
9556 // Keep track of already used bits to detect overlapping values.
9557 // In that case, we will just abort the transformation.
9558 APInt UsedBits(LD->getValueSizeInBits(0), 0);
9560 SmallVector<LoadedSlice, 4> LoadedSlices;
9562 // Check if this load is used as several smaller chunks of bits.
9563 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
9564 // of computation for each trunc.
9565 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
9566 UI != UIEnd; ++UI) {
9567 // Skip the uses of the chain.
9568 if (UI.getUse().getResNo() != 0)
9574 // Check if this is a trunc(lshr).
9575 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
9576 isa<ConstantSDNode>(User->getOperand(1))) {
9577 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
9578 User = *User->use_begin();
9581 // At this point, User is a Truncate, iff we encountered, trunc or
9583 if (User->getOpcode() != ISD::TRUNCATE)
9586 // The width of the type must be a power of 2 and greater than 8-bits.
9587 // Otherwise the load cannot be represented in LLVM IR.
9588 // Moreover, if we shifted with a non-8-bits multiple, the slice
9589 // will be across several bytes. We do not support that.
9590 unsigned Width = User->getValueSizeInBits(0);
9591 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
9594 // Build the slice for this chain of computations.
9595 LoadedSlice LS(User, LD, Shift, &DAG);
9596 APInt CurrentUsedBits = LS.getUsedBits();
9598 // Check if this slice overlaps with another.
9599 if ((CurrentUsedBits & UsedBits) != 0)
9601 // Update the bits used globally.
9602 UsedBits |= CurrentUsedBits;
9604 // Check if the new slice would be legal.
9608 // Record the slice.
9609 LoadedSlices.push_back(LS);
9612 // Abort slicing if it does not seem to be profitable.
9613 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
9618 // Rewrite each chain to use an independent load.
9619 // By construction, each chain can be represented by a unique load.
9621 // Prepare the argument for the new token factor for all the slices.
9622 SmallVector<SDValue, 8> ArgChains;
9623 for (SmallVectorImpl<LoadedSlice>::const_iterator
9624 LSIt = LoadedSlices.begin(),
9625 LSItEnd = LoadedSlices.end();
9626 LSIt != LSItEnd; ++LSIt) {
9627 SDValue SliceInst = LSIt->loadSlice();
9628 CombineTo(LSIt->Inst, SliceInst, true);
9629 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
9630 SliceInst = SliceInst.getOperand(0);
9631 assert(SliceInst->getOpcode() == ISD::LOAD &&
9632 "It takes more than a zext to get to the loaded slice!!");
9633 ArgChains.push_back(SliceInst.getValue(1));
9636 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
9638 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9642 /// Check to see if V is (and load (ptr), imm), where the load is having
9643 /// specific bytes cleared out. If so, return the byte size being masked out
9644 /// and the shift amount.
9645 static std::pair<unsigned, unsigned>
9646 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
9647 std::pair<unsigned, unsigned> Result(0, 0);
9649 // Check for the structure we're looking for.
9650 if (V->getOpcode() != ISD::AND ||
9651 !isa<ConstantSDNode>(V->getOperand(1)) ||
9652 !ISD::isNormalLoad(V->getOperand(0).getNode()))
9655 // Check the chain and pointer.
9656 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
9657 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
9659 // The store should be chained directly to the load or be an operand of a
9661 if (LD == Chain.getNode())
9663 else if (Chain->getOpcode() != ISD::TokenFactor)
9664 return Result; // Fail.
9667 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
9668 if (Chain->getOperand(i).getNode() == LD) {
9672 if (!isOk) return Result;
9675 // This only handles simple types.
9676 if (V.getValueType() != MVT::i16 &&
9677 V.getValueType() != MVT::i32 &&
9678 V.getValueType() != MVT::i64)
9681 // Check the constant mask. Invert it so that the bits being masked out are
9682 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
9683 // follow the sign bit for uniformity.
9684 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
9685 unsigned NotMaskLZ = countLeadingZeros(NotMask);
9686 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
9687 unsigned NotMaskTZ = countTrailingZeros(NotMask);
9688 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
9689 if (NotMaskLZ == 64) return Result; // All zero mask.
9691 // See if we have a continuous run of bits. If so, we have 0*1+0*
9692 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
9695 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
9696 if (V.getValueType() != MVT::i64 && NotMaskLZ)
9697 NotMaskLZ -= 64-V.getValueSizeInBits();
9699 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
9700 switch (MaskedBytes) {
9704 default: return Result; // All one mask, or 5-byte mask.
9707 // Verify that the first bit starts at a multiple of mask so that the access
9708 // is aligned the same as the access width.
9709 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
9711 Result.first = MaskedBytes;
9712 Result.second = NotMaskTZ/8;
9717 /// Check to see if IVal is something that provides a value as specified by
9718 /// MaskInfo. If so, replace the specified store with a narrower store of
9721 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
9722 SDValue IVal, StoreSDNode *St,
9724 unsigned NumBytes = MaskInfo.first;
9725 unsigned ByteShift = MaskInfo.second;
9726 SelectionDAG &DAG = DC->getDAG();
9728 // Check to see if IVal is all zeros in the part being masked in by the 'or'
9729 // that uses this. If not, this is not a replacement.
9730 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
9731 ByteShift*8, (ByteShift+NumBytes)*8);
9732 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
9734 // Check that it is legal on the target to do this. It is legal if the new
9735 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
9737 MVT VT = MVT::getIntegerVT(NumBytes*8);
9738 if (!DC->isTypeLegal(VT))
9741 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
9742 // shifted by ByteShift and truncated down to NumBytes.
9744 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
9745 DAG.getConstant(ByteShift*8,
9746 DC->getShiftAmountTy(IVal.getValueType())));
9748 // Figure out the offset for the store and the alignment of the access.
9750 unsigned NewAlign = St->getAlignment();
9752 if (DAG.getTargetLoweringInfo().isLittleEndian())
9753 StOffset = ByteShift;
9755 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
9757 SDValue Ptr = St->getBasePtr();
9759 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
9760 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
9761 NewAlign = MinAlign(NewAlign, StOffset);
9764 // Truncate down to the new size.
9765 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
9768 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
9769 St->getPointerInfo().getWithOffset(StOffset),
9770 false, false, NewAlign).getNode();
9774 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
9775 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
9776 /// narrowing the load and store if it would end up being a win for performance
9778 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
9779 StoreSDNode *ST = cast<StoreSDNode>(N);
9780 if (ST->isVolatile())
9783 SDValue Chain = ST->getChain();
9784 SDValue Value = ST->getValue();
9785 SDValue Ptr = ST->getBasePtr();
9786 EVT VT = Value.getValueType();
9788 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
9791 unsigned Opc = Value.getOpcode();
9793 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
9794 // is a byte mask indicating a consecutive number of bytes, check to see if
9795 // Y is known to provide just those bytes. If so, we try to replace the
9796 // load + replace + store sequence with a single (narrower) store, which makes
9798 if (Opc == ISD::OR) {
9799 std::pair<unsigned, unsigned> MaskedLoad;
9800 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
9801 if (MaskedLoad.first)
9802 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9803 Value.getOperand(1), ST,this))
9804 return SDValue(NewST, 0);
9806 // Or is commutative, so try swapping X and Y.
9807 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
9808 if (MaskedLoad.first)
9809 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9810 Value.getOperand(0), ST,this))
9811 return SDValue(NewST, 0);
9814 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
9815 Value.getOperand(1).getOpcode() != ISD::Constant)
9818 SDValue N0 = Value.getOperand(0);
9819 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9820 Chain == SDValue(N0.getNode(), 1)) {
9821 LoadSDNode *LD = cast<LoadSDNode>(N0);
9822 if (LD->getBasePtr() != Ptr ||
9823 LD->getPointerInfo().getAddrSpace() !=
9824 ST->getPointerInfo().getAddrSpace())
9827 // Find the type to narrow it the load / op / store to.
9828 SDValue N1 = Value.getOperand(1);
9829 unsigned BitWidth = N1.getValueSizeInBits();
9830 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
9831 if (Opc == ISD::AND)
9832 Imm ^= APInt::getAllOnesValue(BitWidth);
9833 if (Imm == 0 || Imm.isAllOnesValue())
9835 unsigned ShAmt = Imm.countTrailingZeros();
9836 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
9837 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
9838 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9839 // The narrowing should be profitable, the load/store operation should be
9840 // legal (or custom) and the store size should be equal to the NewVT width.
9841 while (NewBW < BitWidth &&
9842 (NewVT.getStoreSizeInBits() != NewBW ||
9843 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
9844 !TLI.isNarrowingProfitable(VT, NewVT))) {
9845 NewBW = NextPowerOf2(NewBW);
9846 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9848 if (NewBW >= BitWidth)
9851 // If the lsb changed does not start at the type bitwidth boundary,
9852 // start at the previous one.
9854 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
9855 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
9856 std::min(BitWidth, ShAmt + NewBW));
9857 if ((Imm & Mask) == Imm) {
9858 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
9859 if (Opc == ISD::AND)
9860 NewImm ^= APInt::getAllOnesValue(NewBW);
9861 uint64_t PtrOff = ShAmt / 8;
9862 // For big endian targets, we need to adjust the offset to the pointer to
9863 // load the correct bytes.
9864 if (TLI.isBigEndian())
9865 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
9867 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
9868 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
9869 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
9872 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
9873 Ptr.getValueType(), Ptr,
9874 DAG.getConstant(PtrOff, Ptr.getValueType()));
9875 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
9876 LD->getChain(), NewPtr,
9877 LD->getPointerInfo().getWithOffset(PtrOff),
9878 LD->isVolatile(), LD->isNonTemporal(),
9879 LD->isInvariant(), NewAlign,
9881 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
9882 DAG.getConstant(NewImm, NewVT));
9883 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
9885 ST->getPointerInfo().getWithOffset(PtrOff),
9886 false, false, NewAlign);
9888 AddToWorklist(NewPtr.getNode());
9889 AddToWorklist(NewLD.getNode());
9890 AddToWorklist(NewVal.getNode());
9891 WorklistRemover DeadNodes(*this);
9892 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
9901 /// For a given floating point load / store pair, if the load value isn't used
9902 /// by any other operations, then consider transforming the pair to integer
9903 /// load / store operations if the target deems the transformation profitable.
9904 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9905 StoreSDNode *ST = cast<StoreSDNode>(N);
9906 SDValue Chain = ST->getChain();
9907 SDValue Value = ST->getValue();
9908 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9909 Value.hasOneUse() &&
9910 Chain == SDValue(Value.getNode(), 1)) {
9911 LoadSDNode *LD = cast<LoadSDNode>(Value);
9912 EVT VT = LD->getMemoryVT();
9913 if (!VT.isFloatingPoint() ||
9914 VT != ST->getMemoryVT() ||
9915 LD->isNonTemporal() ||
9916 ST->isNonTemporal() ||
9917 LD->getPointerInfo().getAddrSpace() != 0 ||
9918 ST->getPointerInfo().getAddrSpace() != 0)
9921 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9922 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9923 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9924 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9925 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9928 unsigned LDAlign = LD->getAlignment();
9929 unsigned STAlign = ST->getAlignment();
9930 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
9931 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
9932 if (LDAlign < ABIAlign || STAlign < ABIAlign)
9935 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9936 LD->getChain(), LD->getBasePtr(),
9937 LD->getPointerInfo(),
9938 false, false, false, LDAlign);
9940 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9941 NewLD, ST->getBasePtr(),
9942 ST->getPointerInfo(),
9943 false, false, STAlign);
9945 AddToWorklist(NewLD.getNode());
9946 AddToWorklist(NewST.getNode());
9947 WorklistRemover DeadNodes(*this);
9948 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9956 /// Helper struct to parse and store a memory address as base + index + offset.
9957 /// We ignore sign extensions when it is safe to do so.
9958 /// The following two expressions are not equivalent. To differentiate we need
9959 /// to store whether there was a sign extension involved in the index
9961 /// (load (i64 add (i64 copyfromreg %c)
9962 /// (i64 signextend (add (i8 load %index)
9966 /// (load (i64 add (i64 copyfromreg %c)
9967 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
9969 struct BaseIndexOffset {
9973 bool IsIndexSignExt;
9975 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9977 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9978 bool IsIndexSignExt) :
9979 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9981 bool equalBaseIndex(const BaseIndexOffset &Other) {
9982 return Other.Base == Base && Other.Index == Index &&
9983 Other.IsIndexSignExt == IsIndexSignExt;
9986 /// Parses tree in Ptr for base, index, offset addresses.
9987 static BaseIndexOffset match(SDValue Ptr) {
9988 bool IsIndexSignExt = false;
9990 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9991 // instruction, then it could be just the BASE or everything else we don't
9992 // know how to handle. Just use Ptr as BASE and give up.
9993 if (Ptr->getOpcode() != ISD::ADD)
9994 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9996 // We know that we have at least an ADD instruction. Try to pattern match
9997 // the simple case of BASE + OFFSET.
9998 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9999 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10000 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10004 // Inside a loop the current BASE pointer is calculated using an ADD and a
10005 // MUL instruction. In this case Ptr is the actual BASE pointer.
10006 // (i64 add (i64 %array_ptr)
10007 // (i64 mul (i64 %induction_var)
10008 // (i64 %element_size)))
10009 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10010 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10012 // Look at Base + Index + Offset cases.
10013 SDValue Base = Ptr->getOperand(0);
10014 SDValue IndexOffset = Ptr->getOperand(1);
10016 // Skip signextends.
10017 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10018 IndexOffset = IndexOffset->getOperand(0);
10019 IsIndexSignExt = true;
10022 // Either the case of Base + Index (no offset) or something else.
10023 if (IndexOffset->getOpcode() != ISD::ADD)
10024 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10026 // Now we have the case of Base + Index + offset.
10027 SDValue Index = IndexOffset->getOperand(0);
10028 SDValue Offset = IndexOffset->getOperand(1);
10030 if (!isa<ConstantSDNode>(Offset))
10031 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10033 // Ignore signextends.
10034 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10035 Index = Index->getOperand(0);
10036 IsIndexSignExt = true;
10037 } else IsIndexSignExt = false;
10039 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10040 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10044 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10045 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10046 unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10047 // Make sure we have something to merge.
10051 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10052 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10053 unsigned EarliestNodeUsed = 0;
10055 for (unsigned i=0; i < NumElem; ++i) {
10056 // Find a chain for the new wide-store operand. Notice that some
10057 // of the store nodes that we found may not be selected for inclusion
10058 // in the wide store. The chain we use needs to be the chain of the
10059 // earliest store node which is *used* and replaced by the wide store.
10060 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
10061 EarliestNodeUsed = i;
10064 // The earliest Node in the DAG.
10065 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
10066 SDLoc DL(StoreNodes[0].MemNode);
10070 // Find a legal type for the vector store.
10071 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10072 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10073 if (IsConstantSrc) {
10074 // A vector store with a constant source implies that the constant is
10075 // zero; we only handle merging stores of constant zeros because the zero
10076 // can be materialized without a load.
10077 // It may be beneficial to loosen this restriction to allow non-zero
10079 StoredVal = DAG.getConstant(0, Ty);
10081 SmallVector<SDValue, 8> Ops;
10082 for (unsigned i = 0; i < NumElem ; ++i) {
10083 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10084 SDValue Val = St->getValue();
10085 // All of the operands of a BUILD_VECTOR must have the same type.
10086 if (Val.getValueType() != MemVT)
10088 Ops.push_back(Val);
10091 // Build the extracted vector elements back into a vector.
10092 StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10095 // We should always use a vector store when merging extracted vector
10096 // elements, so this path implies a store of constants.
10097 assert(IsConstantSrc && "Merged vector elements should use vector store");
10099 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10100 APInt StoreInt(StoreBW, 0);
10102 // Construct a single integer constant which is made of the smaller
10103 // constant inputs.
10104 bool IsLE = TLI.isLittleEndian();
10105 for (unsigned i = 0; i < NumElem ; ++i) {
10106 unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10107 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10108 SDValue Val = St->getValue();
10109 StoreInt <<= ElementSizeBytes*8;
10110 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10111 StoreInt |= C->getAPIntValue().zext(StoreBW);
10112 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10113 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
10115 llvm_unreachable("Invalid constant element type");
10119 // Create the new Load and Store operations.
10120 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10121 StoredVal = DAG.getConstant(StoreInt, StoreTy);
10124 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
10125 FirstInChain->getBasePtr(),
10126 FirstInChain->getPointerInfo(),
10128 FirstInChain->getAlignment());
10130 // Replace the first store with the new store
10131 CombineTo(EarliestOp, NewStore);
10132 // Erase all other stores.
10133 for (unsigned i = 0; i < NumElem ; ++i) {
10134 if (StoreNodes[i].MemNode == EarliestOp)
10136 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10137 // ReplaceAllUsesWith will replace all uses that existed when it was
10138 // called, but graph optimizations may cause new ones to appear. For
10139 // example, the case in pr14333 looks like
10141 // St's chain -> St -> another store -> X
10143 // And the only difference from St to the other store is the chain.
10144 // When we change it's chain to be St's chain they become identical,
10145 // get CSEed and the net result is that X is now a use of St.
10146 // Since we know that St is redundant, just iterate.
10147 while (!St->use_empty())
10148 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10149 deleteAndRecombine(St);
10155 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10156 if (OptLevel == CodeGenOpt::None)
10159 EVT MemVT = St->getMemoryVT();
10160 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
10161 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10162 Attribute::NoImplicitFloat);
10164 // Don't merge vectors into wider inputs.
10165 if (MemVT.isVector() || !MemVT.isSimple())
10168 // Perform an early exit check. Do not bother looking at stored values that
10169 // are not constants, loads, or extracted vector elements.
10170 SDValue StoredVal = St->getValue();
10171 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10172 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10173 isa<ConstantFPSDNode>(StoredVal);
10174 bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10176 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10179 // Only look at ends of store sequences.
10180 SDValue Chain = SDValue(St, 0);
10181 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10184 // This holds the base pointer, index, and the offset in bytes from the base
10186 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10188 // We must have a base and an offset.
10189 if (!BasePtr.Base.getNode())
10192 // Do not handle stores to undef base pointers.
10193 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10196 // Save the LoadSDNodes that we find in the chain.
10197 // We need to make sure that these nodes do not interfere with
10198 // any of the store nodes.
10199 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10201 // Save the StoreSDNodes that we find in the chain.
10202 SmallVector<MemOpLink, 8> StoreNodes;
10204 // Walk up the chain and look for nodes with offsets from the same
10205 // base pointer. Stop when reaching an instruction with a different kind
10206 // or instruction which has a different base pointer.
10208 StoreSDNode *Index = St;
10210 // If the chain has more than one use, then we can't reorder the mem ops.
10211 if (Index != St && !SDValue(Index, 0)->hasOneUse())
10214 // Find the base pointer and offset for this memory node.
10215 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10217 // Check that the base pointer is the same as the original one.
10218 if (!Ptr.equalBaseIndex(BasePtr))
10221 // Check that the alignment is the same.
10222 if (Index->getAlignment() != St->getAlignment())
10225 // The memory operands must not be volatile.
10226 if (Index->isVolatile() || Index->isIndexed())
10230 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10231 if (St->isTruncatingStore())
10234 // The stored memory type must be the same.
10235 if (Index->getMemoryVT() != MemVT)
10238 // We do not allow unaligned stores because we want to prevent overriding
10240 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
10243 // We found a potential memory operand to merge.
10244 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10246 // Find the next memory operand in the chain. If the next operand in the
10247 // chain is a store then move up and continue the scan with the next
10248 // memory operand. If the next operand is a load save it and use alias
10249 // information to check if it interferes with anything.
10250 SDNode *NextInChain = Index->getChain().getNode();
10252 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10253 // We found a store node. Use it for the next iteration.
10256 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10257 if (Ldn->isVolatile()) {
10262 // Save the load node for later. Continue the scan.
10263 AliasLoadNodes.push_back(Ldn);
10264 NextInChain = Ldn->getChain().getNode();
10273 // Check if there is anything to merge.
10274 if (StoreNodes.size() < 2)
10277 // Sort the memory operands according to their distance from the base pointer.
10278 std::sort(StoreNodes.begin(), StoreNodes.end(),
10279 [](MemOpLink LHS, MemOpLink RHS) {
10280 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10281 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10282 LHS.SequenceNum > RHS.SequenceNum);
10285 // Scan the memory operations on the chain and find the first non-consecutive
10286 // store memory address.
10287 unsigned LastConsecutiveStore = 0;
10288 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10289 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10291 // Check that the addresses are consecutive starting from the second
10292 // element in the list of stores.
10294 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10295 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10299 bool Alias = false;
10300 // Check if this store interferes with any of the loads that we found.
10301 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10302 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10306 // We found a load that alias with this store. Stop the sequence.
10310 // Mark this node as useful.
10311 LastConsecutiveStore = i;
10314 // The node with the lowest store address.
10315 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10317 // Store the constants into memory as one consecutive store.
10318 if (IsConstantSrc) {
10319 unsigned LastLegalType = 0;
10320 unsigned LastLegalVectorType = 0;
10321 bool NonZero = false;
10322 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10323 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10324 SDValue StoredVal = St->getValue();
10326 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10327 NonZero |= !C->isNullValue();
10328 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10329 NonZero |= !C->getConstantFPValue()->isNullValue();
10335 // Find a legal type for the constant store.
10336 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10337 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10338 if (TLI.isTypeLegal(StoreTy))
10339 LastLegalType = i+1;
10340 // Or check whether a truncstore is legal.
10341 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10342 TargetLowering::TypePromoteInteger) {
10343 EVT LegalizedStoredValueTy =
10344 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10345 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
10346 LastLegalType = i+1;
10349 // Find a legal type for the vector store.
10350 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10351 if (TLI.isTypeLegal(Ty))
10352 LastLegalVectorType = i + 1;
10355 // We only use vectors if the constant is known to be zero and the
10356 // function is not marked with the noimplicitfloat attribute.
10357 if (NonZero || NoVectors)
10358 LastLegalVectorType = 0;
10360 // Check if we found a legal integer type to store.
10361 if (LastLegalType == 0 && LastLegalVectorType == 0)
10364 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10365 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10367 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10371 // When extracting multiple vector elements, try to store them
10372 // in one vector store rather than a sequence of scalar stores.
10373 if (IsExtractVecEltSrc) {
10374 unsigned NumElem = 0;
10375 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10376 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10377 SDValue StoredVal = St->getValue();
10378 // This restriction could be loosened.
10379 // Bail out if any stored values are not elements extracted from a vector.
10380 // It should be possible to handle mixed sources, but load sources need
10381 // more careful handling (see the block of code below that handles
10382 // consecutive loads).
10383 if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10386 // Find a legal type for the vector store.
10387 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10388 if (TLI.isTypeLegal(Ty))
10392 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10396 // Below we handle the case of multiple consecutive stores that
10397 // come from multiple consecutive loads. We merge them into a single
10398 // wide load and a single wide store.
10400 // Look for load nodes which are used by the stored values.
10401 SmallVector<MemOpLink, 8> LoadNodes;
10403 // Find acceptable loads. Loads need to have the same chain (token factor),
10404 // must not be zext, volatile, indexed, and they must be consecutive.
10405 BaseIndexOffset LdBasePtr;
10406 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10407 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10408 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10411 // Loads must only have one use.
10412 if (!Ld->hasNUsesOfValue(1, 0))
10415 // Check that the alignment is the same as the stores.
10416 if (Ld->getAlignment() != St->getAlignment())
10419 // The memory operands must not be volatile.
10420 if (Ld->isVolatile() || Ld->isIndexed())
10423 // We do not accept ext loads.
10424 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10427 // The stored memory type must be the same.
10428 if (Ld->getMemoryVT() != MemVT)
10431 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
10432 // If this is not the first ptr that we check.
10433 if (LdBasePtr.Base.getNode()) {
10434 // The base ptr must be the same.
10435 if (!LdPtr.equalBaseIndex(LdBasePtr))
10438 // Check that all other base pointers are the same as this one.
10442 // We found a potential memory operand to merge.
10443 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
10446 if (LoadNodes.size() < 2)
10449 // If we have load/store pair instructions and we only have two values,
10451 unsigned RequiredAlignment;
10452 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10453 St->getAlignment() >= RequiredAlignment)
10456 // Scan the memory operations on the chain and find the first non-consecutive
10457 // load memory address. These variables hold the index in the store node
10459 unsigned LastConsecutiveLoad = 0;
10460 // This variable refers to the size and not index in the array.
10461 unsigned LastLegalVectorType = 0;
10462 unsigned LastLegalIntegerType = 0;
10463 StartAddress = LoadNodes[0].OffsetFromBase;
10464 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
10465 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10466 // All loads much share the same chain.
10467 if (LoadNodes[i].MemNode->getChain() != FirstChain)
10470 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10471 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10473 LastConsecutiveLoad = i;
10475 // Find a legal type for the vector store.
10476 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10477 if (TLI.isTypeLegal(StoreTy))
10478 LastLegalVectorType = i + 1;
10480 // Find a legal type for the integer store.
10481 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10482 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10483 if (TLI.isTypeLegal(StoreTy))
10484 LastLegalIntegerType = i + 1;
10485 // Or check whether a truncstore and extload is legal.
10486 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10487 TargetLowering::TypePromoteInteger) {
10488 EVT LegalizedStoredValueTy =
10489 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
10490 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10491 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10492 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10493 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy))
10494 LastLegalIntegerType = i+1;
10498 // Only use vector types if the vector type is larger than the integer type.
10499 // If they are the same, use integers.
10500 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
10501 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
10503 // We add +1 here because the LastXXX variables refer to location while
10504 // the NumElem refers to array/index size.
10505 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
10506 NumElem = std::min(LastLegalType, NumElem);
10511 // The earliest Node in the DAG.
10512 unsigned EarliestNodeUsed = 0;
10513 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
10514 for (unsigned i=1; i<NumElem; ++i) {
10515 // Find a chain for the new wide-store operand. Notice that some
10516 // of the store nodes that we found may not be selected for inclusion
10517 // in the wide store. The chain we use needs to be the chain of the
10518 // earliest store node which is *used* and replaced by the wide store.
10519 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
10520 EarliestNodeUsed = i;
10523 // Find if it is better to use vectors or integers to load and store
10527 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10529 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10530 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10533 SDLoc LoadDL(LoadNodes[0].MemNode);
10534 SDLoc StoreDL(StoreNodes[0].MemNode);
10536 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
10537 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
10538 FirstLoad->getChain(),
10539 FirstLoad->getBasePtr(),
10540 FirstLoad->getPointerInfo(),
10541 false, false, false,
10542 FirstLoad->getAlignment());
10544 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
10545 FirstInChain->getBasePtr(),
10546 FirstInChain->getPointerInfo(), false, false,
10547 FirstInChain->getAlignment());
10549 // Replace one of the loads with the new load.
10550 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
10551 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
10552 SDValue(NewLoad.getNode(), 1));
10554 // Remove the rest of the load chains.
10555 for (unsigned i = 1; i < NumElem ; ++i) {
10556 // Replace all chain users of the old load nodes with the chain of the new
10558 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
10559 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
10562 // Replace the first store with the new store.
10563 CombineTo(EarliestOp, NewStore);
10564 // Erase all other stores.
10565 for (unsigned i = 0; i < NumElem ; ++i) {
10566 // Remove all Store nodes.
10567 if (StoreNodes[i].MemNode == EarliestOp)
10569 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10570 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
10571 deleteAndRecombine(St);
10577 SDValue DAGCombiner::visitSTORE(SDNode *N) {
10578 StoreSDNode *ST = cast<StoreSDNode>(N);
10579 SDValue Chain = ST->getChain();
10580 SDValue Value = ST->getValue();
10581 SDValue Ptr = ST->getBasePtr();
10583 // If this is a store of a bit convert, store the input value if the
10584 // resultant store does not need a higher alignment than the original.
10585 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
10586 ST->isUnindexed()) {
10587 unsigned OrigAlign = ST->getAlignment();
10588 EVT SVT = Value.getOperand(0).getValueType();
10589 unsigned Align = TLI.getDataLayout()->
10590 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
10591 if (Align <= OrigAlign &&
10592 ((!LegalOperations && !ST->isVolatile()) ||
10593 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
10594 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
10595 Ptr, ST->getPointerInfo(), ST->isVolatile(),
10596 ST->isNonTemporal(), OrigAlign,
10600 // Turn 'store undef, Ptr' -> nothing.
10601 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
10604 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
10605 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
10606 // NOTE: If the original store is volatile, this transform must not increase
10607 // the number of stores. For example, on x86-32 an f64 can be stored in one
10608 // processor operation but an i64 (which is not legal) requires two. So the
10609 // transform should not be done in this case.
10610 if (Value.getOpcode() != ISD::TargetConstantFP) {
10612 switch (CFP->getSimpleValueType(0).SimpleTy) {
10613 default: llvm_unreachable("Unknown FP type");
10614 case MVT::f16: // We don't do this for these yet.
10620 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
10621 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10622 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
10623 bitcastToAPInt().getZExtValue(), MVT::i32);
10624 return DAG.getStore(Chain, SDLoc(N), Tmp,
10625 Ptr, ST->getMemOperand());
10629 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
10630 !ST->isVolatile()) ||
10631 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
10632 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
10633 getZExtValue(), MVT::i64);
10634 return DAG.getStore(Chain, SDLoc(N), Tmp,
10635 Ptr, ST->getMemOperand());
10638 if (!ST->isVolatile() &&
10639 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10640 // Many FP stores are not made apparent until after legalize, e.g. for
10641 // argument passing. Since this is so common, custom legalize the
10642 // 64-bit integer store into two 32-bit stores.
10643 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
10644 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
10645 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
10646 if (TLI.isBigEndian()) std::swap(Lo, Hi);
10648 unsigned Alignment = ST->getAlignment();
10649 bool isVolatile = ST->isVolatile();
10650 bool isNonTemporal = ST->isNonTemporal();
10651 AAMDNodes AAInfo = ST->getAAInfo();
10653 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
10654 Ptr, ST->getPointerInfo(),
10655 isVolatile, isNonTemporal,
10656 ST->getAlignment(), AAInfo);
10657 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
10658 DAG.getConstant(4, Ptr.getValueType()));
10659 Alignment = MinAlign(Alignment, 4U);
10660 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
10661 Ptr, ST->getPointerInfo().getWithOffset(4),
10662 isVolatile, isNonTemporal,
10663 Alignment, AAInfo);
10664 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
10673 // Try to infer better alignment information than the store already has.
10674 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
10675 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10676 if (Align > ST->getAlignment())
10677 return DAG.getTruncStore(Chain, SDLoc(N), Value,
10678 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
10679 ST->isVolatile(), ST->isNonTemporal(), Align,
10684 // Try transforming a pair floating point load / store ops to integer
10685 // load / store ops.
10686 SDValue NewST = TransformFPLoadStorePair(N);
10687 if (NewST.getNode())
10690 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10691 : DAG.getSubtarget().useAA();
10693 if (CombinerAAOnlyFunc.getNumOccurrences() &&
10694 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10697 if (UseAA && ST->isUnindexed()) {
10698 // Walk up chain skipping non-aliasing memory nodes.
10699 SDValue BetterChain = FindBetterChain(N, Chain);
10701 // If there is a better chain.
10702 if (Chain != BetterChain) {
10705 // Replace the chain to avoid dependency.
10706 if (ST->isTruncatingStore()) {
10707 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
10708 ST->getMemoryVT(), ST->getMemOperand());
10710 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
10711 ST->getMemOperand());
10714 // Create token to keep both nodes around.
10715 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10716 MVT::Other, Chain, ReplStore);
10718 // Make sure the new and old chains are cleaned up.
10719 AddToWorklist(Token.getNode());
10721 // Don't add users to work list.
10722 return CombineTo(N, Token, false);
10726 // Try transforming N to an indexed store.
10727 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10728 return SDValue(N, 0);
10730 // FIXME: is there such a thing as a truncating indexed store?
10731 if (ST->isTruncatingStore() && ST->isUnindexed() &&
10732 Value.getValueType().isInteger()) {
10733 // See if we can simplify the input to this truncstore with knowledge that
10734 // only the low bits are being used. For example:
10735 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
10737 GetDemandedBits(Value,
10738 APInt::getLowBitsSet(
10739 Value.getValueType().getScalarType().getSizeInBits(),
10740 ST->getMemoryVT().getScalarType().getSizeInBits()));
10741 AddToWorklist(Value.getNode());
10742 if (Shorter.getNode())
10743 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
10744 Ptr, ST->getMemoryVT(), ST->getMemOperand());
10746 // Otherwise, see if we can simplify the operation with
10747 // SimplifyDemandedBits, which only works if the value has a single use.
10748 if (SimplifyDemandedBits(Value,
10749 APInt::getLowBitsSet(
10750 Value.getValueType().getScalarType().getSizeInBits(),
10751 ST->getMemoryVT().getScalarType().getSizeInBits())))
10752 return SDValue(N, 0);
10755 // If this is a load followed by a store to the same location, then the store
10757 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
10758 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
10759 ST->isUnindexed() && !ST->isVolatile() &&
10760 // There can't be any side effects between the load and store, such as
10761 // a call or store.
10762 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
10763 // The store is dead, remove it.
10768 // If this is a store followed by a store with the same value to the same
10769 // location, then the store is dead/noop.
10770 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
10771 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
10772 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
10773 ST1->isUnindexed() && !ST1->isVolatile()) {
10774 // The store is dead, remove it.
10779 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
10780 // truncating store. We can do this even if this is already a truncstore.
10781 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
10782 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
10783 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
10784 ST->getMemoryVT())) {
10785 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
10786 Ptr, ST->getMemoryVT(), ST->getMemOperand());
10789 // Only perform this optimization before the types are legal, because we
10790 // don't want to perform this optimization on every DAGCombine invocation.
10792 bool EverChanged = false;
10795 // There can be multiple store sequences on the same chain.
10796 // Keep trying to merge store sequences until we are unable to do so
10797 // or until we merge the last store on the chain.
10798 bool Changed = MergeConsecutiveStores(ST);
10799 EverChanged |= Changed;
10800 if (!Changed) break;
10801 } while (ST->getOpcode() != ISD::DELETED_NODE);
10804 return SDValue(N, 0);
10807 return ReduceLoadOpStoreWidth(N);
10810 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
10811 SDValue InVec = N->getOperand(0);
10812 SDValue InVal = N->getOperand(1);
10813 SDValue EltNo = N->getOperand(2);
10816 // If the inserted element is an UNDEF, just use the input vector.
10817 if (InVal.getOpcode() == ISD::UNDEF)
10820 EVT VT = InVec.getValueType();
10822 // If we can't generate a legal BUILD_VECTOR, exit
10823 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
10826 // Check that we know which element is being inserted
10827 if (!isa<ConstantSDNode>(EltNo))
10829 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10831 // Canonicalize insert_vector_elt dag nodes.
10833 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
10834 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
10836 // Do this only if the child insert_vector node has one use; also
10837 // do this only if indices are both constants and Idx1 < Idx0.
10838 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
10839 && isa<ConstantSDNode>(InVec.getOperand(2))) {
10840 unsigned OtherElt =
10841 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
10842 if (Elt < OtherElt) {
10844 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
10845 InVec.getOperand(0), InVal, EltNo);
10846 AddToWorklist(NewOp.getNode());
10847 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
10848 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
10852 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
10853 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
10854 // vector elements.
10855 SmallVector<SDValue, 8> Ops;
10856 // Do not combine these two vectors if the output vector will not replace
10857 // the input vector.
10858 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
10859 Ops.append(InVec.getNode()->op_begin(),
10860 InVec.getNode()->op_end());
10861 } else if (InVec.getOpcode() == ISD::UNDEF) {
10862 unsigned NElts = VT.getVectorNumElements();
10863 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
10868 // Insert the element
10869 if (Elt < Ops.size()) {
10870 // All the operands of BUILD_VECTOR must have the same type;
10871 // we enforce that here.
10872 EVT OpVT = Ops[0].getValueType();
10873 if (InVal.getValueType() != OpVT)
10874 InVal = OpVT.bitsGT(InVal.getValueType()) ?
10875 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
10876 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
10880 // Return the new vector
10881 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
10884 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
10885 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
10886 EVT ResultVT = EVE->getValueType(0);
10887 EVT VecEltVT = InVecVT.getVectorElementType();
10888 unsigned Align = OriginalLoad->getAlignment();
10889 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
10890 VecEltVT.getTypeForEVT(*DAG.getContext()));
10892 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
10897 SDValue NewPtr = OriginalLoad->getBasePtr();
10899 EVT PtrType = NewPtr.getValueType();
10900 MachinePointerInfo MPI;
10901 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
10902 int Elt = ConstEltNo->getZExtValue();
10903 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
10904 if (TLI.isBigEndian())
10905 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
10906 Offset = DAG.getConstant(PtrOff, PtrType);
10907 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
10909 Offset = DAG.getNode(
10910 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
10911 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
10912 if (TLI.isBigEndian())
10913 Offset = DAG.getNode(
10914 ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
10915 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
10916 MPI = OriginalLoad->getPointerInfo();
10918 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
10920 // The replacement we need to do here is a little tricky: we need to
10921 // replace an extractelement of a load with a load.
10922 // Use ReplaceAllUsesOfValuesWith to do the replacement.
10923 // Note that this replacement assumes that the extractvalue is the only
10924 // use of the load; that's okay because we don't want to perform this
10925 // transformation in other cases anyway.
10928 if (ResultVT.bitsGT(VecEltVT)) {
10929 // If the result type of vextract is wider than the load, then issue an
10930 // extending load instead.
10931 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
10935 Load = DAG.getExtLoad(
10936 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
10937 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10938 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10939 Chain = Load.getValue(1);
10941 Load = DAG.getLoad(
10942 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
10943 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10944 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10945 Chain = Load.getValue(1);
10946 if (ResultVT.bitsLT(VecEltVT))
10947 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
10949 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
10951 WorklistRemover DeadNodes(*this);
10952 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
10953 SDValue To[] = { Load, Chain };
10954 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10955 // Since we're explicitly calling ReplaceAllUses, add the new node to the
10956 // worklist explicitly as well.
10957 AddToWorklist(Load.getNode());
10958 AddUsersToWorklist(Load.getNode()); // Add users too
10959 // Make sure to revisit this node to clean it up; it will usually be dead.
10960 AddToWorklist(EVE);
10962 return SDValue(EVE, 0);
10965 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
10966 // (vextract (scalar_to_vector val, 0) -> val
10967 SDValue InVec = N->getOperand(0);
10968 EVT VT = InVec.getValueType();
10969 EVT NVT = N->getValueType(0);
10971 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
10972 // Check if the result type doesn't match the inserted element type. A
10973 // SCALAR_TO_VECTOR may truncate the inserted element and the
10974 // EXTRACT_VECTOR_ELT may widen the extracted vector.
10975 SDValue InOp = InVec.getOperand(0);
10976 if (InOp.getValueType() != NVT) {
10977 assert(InOp.getValueType().isInteger() && NVT.isInteger());
10978 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
10983 SDValue EltNo = N->getOperand(1);
10984 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10986 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
10987 // We only perform this optimization before the op legalization phase because
10988 // we may introduce new vector instructions which are not backed by TD
10989 // patterns. For example on AVX, extracting elements from a wide vector
10990 // without using extract_subvector. However, if we can find an underlying
10991 // scalar value, then we can always use that.
10992 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
10994 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10995 int NumElem = VT.getVectorNumElements();
10996 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10997 // Find the new index to extract from.
10998 int OrigElt = SVOp->getMaskElt(Elt);
11000 // Extracting an undef index is undef.
11002 return DAG.getUNDEF(NVT);
11004 // Select the right vector half to extract from.
11006 if (OrigElt < NumElem) {
11007 SVInVec = InVec->getOperand(0);
11009 SVInVec = InVec->getOperand(1);
11010 OrigElt -= NumElem;
11013 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11014 SDValue InOp = SVInVec.getOperand(OrigElt);
11015 if (InOp.getValueType() != NVT) {
11016 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11017 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11023 // FIXME: We should handle recursing on other vector shuffles and
11024 // scalar_to_vector here as well.
11026 if (!LegalOperations) {
11027 EVT IndexTy = TLI.getVectorIdxTy();
11028 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
11029 SVInVec, DAG.getConstant(OrigElt, IndexTy));
11033 bool BCNumEltsChanged = false;
11034 EVT ExtVT = VT.getVectorElementType();
11037 // If the result of load has to be truncated, then it's not necessarily
11039 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11042 if (InVec.getOpcode() == ISD::BITCAST) {
11043 // Don't duplicate a load with other uses.
11044 if (!InVec.hasOneUse())
11047 EVT BCVT = InVec.getOperand(0).getValueType();
11048 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11050 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11051 BCNumEltsChanged = true;
11052 InVec = InVec.getOperand(0);
11053 ExtVT = BCVT.getVectorElementType();
11056 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11057 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11058 ISD::isNormalLoad(InVec.getNode()) &&
11059 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11060 SDValue Index = N->getOperand(1);
11061 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11062 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11066 // Perform only after legalization to ensure build_vector / vector_shuffle
11067 // optimizations have already been done.
11068 if (!LegalOperations) return SDValue();
11070 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11071 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11072 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11075 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11077 LoadSDNode *LN0 = nullptr;
11078 const ShuffleVectorSDNode *SVN = nullptr;
11079 if (ISD::isNormalLoad(InVec.getNode())) {
11080 LN0 = cast<LoadSDNode>(InVec);
11081 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11082 InVec.getOperand(0).getValueType() == ExtVT &&
11083 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11084 // Don't duplicate a load with other uses.
11085 if (!InVec.hasOneUse())
11088 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11089 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11090 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11092 // (load $addr+1*size)
11094 // Don't duplicate a load with other uses.
11095 if (!InVec.hasOneUse())
11098 // If the bit convert changed the number of elements, it is unsafe
11099 // to examine the mask.
11100 if (BCNumEltsChanged)
11103 // Select the input vector, guarding against out of range extract vector.
11104 unsigned NumElems = VT.getVectorNumElements();
11105 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11106 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11108 if (InVec.getOpcode() == ISD::BITCAST) {
11109 // Don't duplicate a load with other uses.
11110 if (!InVec.hasOneUse())
11113 InVec = InVec.getOperand(0);
11115 if (ISD::isNormalLoad(InVec.getNode())) {
11116 LN0 = cast<LoadSDNode>(InVec);
11117 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11118 EltNo = DAG.getConstant(Elt, EltNo.getValueType());
11122 // Make sure we found a non-volatile load and the extractelement is
11124 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11127 // If Idx was -1 above, Elt is going to be -1, so just return undef.
11129 return DAG.getUNDEF(LVT);
11131 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11137 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11138 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11139 // We perform this optimization post type-legalization because
11140 // the type-legalizer often scalarizes integer-promoted vectors.
11141 // Performing this optimization before may create bit-casts which
11142 // will be type-legalized to complex code sequences.
11143 // We perform this optimization only before the operation legalizer because we
11144 // may introduce illegal operations.
11145 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11148 unsigned NumInScalars = N->getNumOperands();
11150 EVT VT = N->getValueType(0);
11152 // Check to see if this is a BUILD_VECTOR of a bunch of values
11153 // which come from any_extend or zero_extend nodes. If so, we can create
11154 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11155 // optimizations. We do not handle sign-extend because we can't fill the sign
11157 EVT SourceType = MVT::Other;
11158 bool AllAnyExt = true;
11160 for (unsigned i = 0; i != NumInScalars; ++i) {
11161 SDValue In = N->getOperand(i);
11162 // Ignore undef inputs.
11163 if (In.getOpcode() == ISD::UNDEF) continue;
11165 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
11166 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11168 // Abort if the element is not an extension.
11169 if (!ZeroExt && !AnyExt) {
11170 SourceType = MVT::Other;
11174 // The input is a ZeroExt or AnyExt. Check the original type.
11175 EVT InTy = In.getOperand(0).getValueType();
11177 // Check that all of the widened source types are the same.
11178 if (SourceType == MVT::Other)
11181 else if (InTy != SourceType) {
11182 // Multiple income types. Abort.
11183 SourceType = MVT::Other;
11187 // Check if all of the extends are ANY_EXTENDs.
11188 AllAnyExt &= AnyExt;
11191 // In order to have valid types, all of the inputs must be extended from the
11192 // same source type and all of the inputs must be any or zero extend.
11193 // Scalar sizes must be a power of two.
11194 EVT OutScalarTy = VT.getScalarType();
11195 bool ValidTypes = SourceType != MVT::Other &&
11196 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11197 isPowerOf2_32(SourceType.getSizeInBits());
11199 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11200 // turn into a single shuffle instruction.
11204 bool isLE = TLI.isLittleEndian();
11205 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11206 assert(ElemRatio > 1 && "Invalid element size ratio");
11207 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11208 DAG.getConstant(0, SourceType);
11210 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11211 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11213 // Populate the new build_vector
11214 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11215 SDValue Cast = N->getOperand(i);
11216 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11217 Cast.getOpcode() == ISD::ZERO_EXTEND ||
11218 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11220 if (Cast.getOpcode() == ISD::UNDEF)
11221 In = DAG.getUNDEF(SourceType);
11223 In = Cast->getOperand(0);
11224 unsigned Index = isLE ? (i * ElemRatio) :
11225 (i * ElemRatio + (ElemRatio - 1));
11227 assert(Index < Ops.size() && "Invalid index");
11231 // The type of the new BUILD_VECTOR node.
11232 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11233 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11234 "Invalid vector size");
11235 // Check if the new vector type is legal.
11236 if (!isTypeLegal(VecVT)) return SDValue();
11238 // Make the new BUILD_VECTOR.
11239 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11241 // The new BUILD_VECTOR node has the potential to be further optimized.
11242 AddToWorklist(BV.getNode());
11243 // Bitcast to the desired type.
11244 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11247 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11248 EVT VT = N->getValueType(0);
11250 unsigned NumInScalars = N->getNumOperands();
11253 EVT SrcVT = MVT::Other;
11254 unsigned Opcode = ISD::DELETED_NODE;
11255 unsigned NumDefs = 0;
11257 for (unsigned i = 0; i != NumInScalars; ++i) {
11258 SDValue In = N->getOperand(i);
11259 unsigned Opc = In.getOpcode();
11261 if (Opc == ISD::UNDEF)
11264 // If all scalar values are floats and converted from integers.
11265 if (Opcode == ISD::DELETED_NODE &&
11266 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11273 EVT InVT = In.getOperand(0).getValueType();
11275 // If all scalar values are typed differently, bail out. It's chosen to
11276 // simplify BUILD_VECTOR of integer types.
11277 if (SrcVT == MVT::Other)
11284 // If the vector has just one element defined, it's not worth to fold it into
11285 // a vectorized one.
11289 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11290 && "Should only handle conversion from integer to float.");
11291 assert(SrcVT != MVT::Other && "Cannot determine source type!");
11293 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11295 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11298 // Just because the floating-point vector type is legal does not necessarily
11299 // mean that the corresponding integer vector type is.
11300 if (!isTypeLegal(NVT))
11303 SmallVector<SDValue, 8> Opnds;
11304 for (unsigned i = 0; i != NumInScalars; ++i) {
11305 SDValue In = N->getOperand(i);
11307 if (In.getOpcode() == ISD::UNDEF)
11308 Opnds.push_back(DAG.getUNDEF(SrcVT));
11310 Opnds.push_back(In.getOperand(0));
11312 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11313 AddToWorklist(BV.getNode());
11315 return DAG.getNode(Opcode, dl, VT, BV);
11318 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11319 unsigned NumInScalars = N->getNumOperands();
11321 EVT VT = N->getValueType(0);
11323 // A vector built entirely of undefs is undef.
11324 if (ISD::allOperandsUndef(N))
11325 return DAG.getUNDEF(VT);
11327 SDValue V = reduceBuildVecExtToExtBuildVec(N);
11331 V = reduceBuildVecConvertToConvertBuildVec(N);
11335 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11336 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11337 // at most two distinct vectors, turn this into a shuffle node.
11339 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11340 if (!isTypeLegal(VT))
11343 // May only combine to shuffle after legalize if shuffle is legal.
11344 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11347 SDValue VecIn1, VecIn2;
11348 bool UsesZeroVector = false;
11349 for (unsigned i = 0; i != NumInScalars; ++i) {
11350 SDValue Op = N->getOperand(i);
11351 // Ignore undef inputs.
11352 if (Op.getOpcode() == ISD::UNDEF) continue;
11354 // See if we can combine this build_vector into a blend with a zero vector.
11355 if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
11356 cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
11357 (Op.getOpcode() == ISD::ConstantFP &&
11358 cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
11359 UsesZeroVector = true;
11363 // If this input is something other than a EXTRACT_VECTOR_ELT with a
11364 // constant index, bail out.
11365 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11366 !isa<ConstantSDNode>(Op.getOperand(1))) {
11367 VecIn1 = VecIn2 = SDValue(nullptr, 0);
11371 // We allow up to two distinct input vectors.
11372 SDValue ExtractedFromVec = Op.getOperand(0);
11373 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11376 if (!VecIn1.getNode()) {
11377 VecIn1 = ExtractedFromVec;
11378 } else if (!VecIn2.getNode() && !UsesZeroVector) {
11379 VecIn2 = ExtractedFromVec;
11381 // Too many inputs.
11382 VecIn1 = VecIn2 = SDValue(nullptr, 0);
11387 // If everything is good, we can make a shuffle operation.
11388 if (VecIn1.getNode()) {
11389 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
11390 SmallVector<int, 8> Mask;
11391 for (unsigned i = 0; i != NumInScalars; ++i) {
11392 unsigned Opcode = N->getOperand(i).getOpcode();
11393 if (Opcode == ISD::UNDEF) {
11394 Mask.push_back(-1);
11398 // Operands can also be zero.
11399 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11400 assert(UsesZeroVector &&
11401 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11402 "Unexpected node found!");
11403 Mask.push_back(NumInScalars+i);
11407 // If extracting from the first vector, just use the index directly.
11408 SDValue Extract = N->getOperand(i);
11409 SDValue ExtVal = Extract.getOperand(1);
11410 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
11411 if (Extract.getOperand(0) == VecIn1) {
11412 Mask.push_back(ExtIndex);
11416 // Otherwise, use InIdx + InputVecSize
11417 Mask.push_back(InNumElements + ExtIndex);
11420 // Avoid introducing illegal shuffles with zero.
11421 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11424 // We can't generate a shuffle node with mismatched input and output types.
11425 // Attempt to transform a single input vector to the correct type.
11426 if ((VT != VecIn1.getValueType())) {
11427 // If the input vector type has a different base type to the output
11428 // vector type, bail out.
11429 EVT VTElemType = VT.getVectorElementType();
11430 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11431 (VecIn2.getNode() &&
11432 (VecIn2.getValueType().getVectorElementType() != VTElemType)))
11435 // If the input vector is too small, widen it.
11436 // We only support widening of vectors which are half the size of the
11437 // output registers. For example XMM->YMM widening on X86 with AVX.
11438 EVT VecInT = VecIn1.getValueType();
11439 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
11440 // If we only have one small input, widen it by adding undef values.
11441 if (!VecIn2.getNode())
11442 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11443 DAG.getUNDEF(VecIn1.getValueType()));
11444 else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11445 // If we have two small inputs of the same type, try to concat them.
11446 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11447 VecIn2 = SDValue(nullptr, 0);
11450 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11451 // If the input vector is too large, try to split it.
11452 // We don't support having two input vectors that are too large.
11453 // If the zero vector was used, we can not split the vector,
11454 // since we'd need 3 inputs.
11455 if (UsesZeroVector || VecIn2.getNode())
11458 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11461 // Try to replace VecIn1 with two extract_subvectors
11462 // No need to update the masks, they should still be correct.
11463 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11464 DAG.getConstant(VT.getVectorNumElements(), TLI.getVectorIdxTy()));
11465 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11466 DAG.getConstant(0, TLI.getVectorIdxTy()));
11471 if (UsesZeroVector)
11472 VecIn2 = VT.isInteger() ? DAG.getConstant(0, VT) :
11473 DAG.getConstantFP(0.0, VT);
11475 // If VecIn2 is unused then change it to undef.
11476 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
11478 // Check that we were able to transform all incoming values to the same
11480 if (VecIn2.getValueType() != VecIn1.getValueType() ||
11481 VecIn1.getValueType() != VT)
11484 // Return the new VECTOR_SHUFFLE node.
11488 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
11494 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
11495 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
11496 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
11497 // inputs come from at most two distinct vectors, turn this into a shuffle
11500 // If we only have one input vector, we don't need to do any concatenation.
11501 if (N->getNumOperands() == 1)
11502 return N->getOperand(0);
11504 // Check if all of the operands are undefs.
11505 EVT VT = N->getValueType(0);
11506 if (ISD::allOperandsUndef(N))
11507 return DAG.getUNDEF(VT);
11509 // Optimize concat_vectors where one of the vectors is undef.
11510 if (N->getNumOperands() == 2 &&
11511 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
11512 SDValue In = N->getOperand(0);
11513 assert(In.getValueType().isVector() && "Must concat vectors");
11515 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
11516 if (In->getOpcode() == ISD::BITCAST &&
11517 !In->getOperand(0)->getValueType(0).isVector()) {
11518 SDValue Scalar = In->getOperand(0);
11519 EVT SclTy = Scalar->getValueType(0);
11521 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
11524 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
11525 VT.getSizeInBits() / SclTy.getSizeInBits());
11526 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
11529 SDLoc dl = SDLoc(N);
11530 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
11531 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
11535 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
11536 // We have already tested above for an UNDEF only concatenation.
11537 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
11538 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
11539 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
11540 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
11542 bool AllBuildVectorsOrUndefs =
11543 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
11544 if (AllBuildVectorsOrUndefs) {
11545 SmallVector<SDValue, 8> Opnds;
11546 EVT SVT = VT.getScalarType();
11549 if (!SVT.isFloatingPoint()) {
11550 // If BUILD_VECTOR are from built from integer, they may have different
11551 // operand types. Get the smallest type and truncate all operands to it.
11552 bool FoundMinVT = false;
11553 for (const SDValue &Op : N->ops())
11554 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
11555 EVT OpSVT = Op.getOperand(0)->getValueType(0);
11556 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
11559 assert(FoundMinVT && "Concat vector type mismatch");
11562 for (const SDValue &Op : N->ops()) {
11563 EVT OpVT = Op.getValueType();
11564 unsigned NumElts = OpVT.getVectorNumElements();
11566 if (ISD::UNDEF == Op.getOpcode())
11567 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
11569 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
11570 if (SVT.isFloatingPoint()) {
11571 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
11572 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
11574 for (unsigned i = 0; i != NumElts; ++i)
11576 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
11581 assert(VT.getVectorNumElements() == Opnds.size() &&
11582 "Concat vector type mismatch");
11583 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
11586 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
11587 // nodes often generate nop CONCAT_VECTOR nodes.
11588 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
11589 // place the incoming vectors at the exact same location.
11590 SDValue SingleSource = SDValue();
11591 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
11593 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11594 SDValue Op = N->getOperand(i);
11596 if (Op.getOpcode() == ISD::UNDEF)
11599 // Check if this is the identity extract:
11600 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
11603 // Find the single incoming vector for the extract_subvector.
11604 if (SingleSource.getNode()) {
11605 if (Op.getOperand(0) != SingleSource)
11608 SingleSource = Op.getOperand(0);
11610 // Check the source type is the same as the type of the result.
11611 // If not, this concat may extend the vector, so we can not
11612 // optimize it away.
11613 if (SingleSource.getValueType() != N->getValueType(0))
11617 unsigned IdentityIndex = i * PartNumElem;
11618 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11619 // The extract index must be constant.
11623 // Check that we are reading from the identity index.
11624 if (CS->getZExtValue() != IdentityIndex)
11628 if (SingleSource.getNode())
11629 return SingleSource;
11634 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
11635 EVT NVT = N->getValueType(0);
11636 SDValue V = N->getOperand(0);
11638 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
11640 // (extract_subvec (concat V1, V2, ...), i)
11643 // Only operand 0 is checked as 'concat' assumes all inputs of the same
11645 if (V->getOperand(0).getValueType() != NVT)
11647 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11648 unsigned NumElems = NVT.getVectorNumElements();
11649 assert((Idx % NumElems) == 0 &&
11650 "IDX in concat is not a multiple of the result vector length.");
11651 return V->getOperand(Idx / NumElems);
11655 if (V->getOpcode() == ISD::BITCAST)
11656 V = V.getOperand(0);
11658 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
11660 // Handle only simple case where vector being inserted and vector
11661 // being extracted are of same type, and are half size of larger vectors.
11662 EVT BigVT = V->getOperand(0).getValueType();
11663 EVT SmallVT = V->getOperand(1).getValueType();
11664 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
11667 // Only handle cases where both indexes are constants with the same type.
11668 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
11669 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
11671 if (InsIdx && ExtIdx &&
11672 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
11673 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
11675 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
11677 // indices are equal or bit offsets are equal => V1
11678 // otherwise => (extract_subvec V1, ExtIdx)
11679 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
11680 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
11681 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
11682 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
11683 DAG.getNode(ISD::BITCAST, dl,
11684 N->getOperand(0).getValueType(),
11685 V->getOperand(0)), N->getOperand(1));
11692 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
11693 SDValue V, SelectionDAG &DAG) {
11695 EVT VT = V.getValueType();
11697 switch (V.getOpcode()) {
11701 case ISD::CONCAT_VECTORS: {
11702 EVT OpVT = V->getOperand(0).getValueType();
11703 int OpSize = OpVT.getVectorNumElements();
11704 SmallBitVector OpUsedElements(OpSize, false);
11705 bool FoundSimplification = false;
11706 SmallVector<SDValue, 4> NewOps;
11707 NewOps.reserve(V->getNumOperands());
11708 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
11709 SDValue Op = V->getOperand(i);
11710 bool OpUsed = false;
11711 for (int j = 0; j < OpSize; ++j)
11712 if (UsedElements[i * OpSize + j]) {
11713 OpUsedElements[j] = true;
11717 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
11718 : DAG.getUNDEF(OpVT));
11719 FoundSimplification |= Op == NewOps.back();
11720 OpUsedElements.reset();
11722 if (FoundSimplification)
11723 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
11727 case ISD::INSERT_SUBVECTOR: {
11728 SDValue BaseV = V->getOperand(0);
11729 SDValue SubV = V->getOperand(1);
11730 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
11734 int SubSize = SubV.getValueType().getVectorNumElements();
11735 int Idx = IdxN->getZExtValue();
11736 bool SubVectorUsed = false;
11737 SmallBitVector SubUsedElements(SubSize, false);
11738 for (int i = 0; i < SubSize; ++i)
11739 if (UsedElements[i + Idx]) {
11740 SubVectorUsed = true;
11741 SubUsedElements[i] = true;
11742 UsedElements[i + Idx] = false;
11745 // Now recurse on both the base and sub vectors.
11746 SDValue SimplifiedSubV =
11748 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
11749 : DAG.getUNDEF(SubV.getValueType());
11750 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
11751 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
11752 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
11753 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
11759 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
11760 SDValue N1, SelectionDAG &DAG) {
11761 EVT VT = SVN->getValueType(0);
11762 int NumElts = VT.getVectorNumElements();
11763 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
11764 for (int M : SVN->getMask())
11765 if (M >= 0 && M < NumElts)
11766 N0UsedElements[M] = true;
11767 else if (M >= NumElts)
11768 N1UsedElements[M - NumElts] = true;
11770 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
11771 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
11772 if (S0 == N0 && S1 == N1)
11775 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
11778 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
11779 // or turn a shuffle of a single concat into simpler shuffle then concat.
11780 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
11781 EVT VT = N->getValueType(0);
11782 unsigned NumElts = VT.getVectorNumElements();
11784 SDValue N0 = N->getOperand(0);
11785 SDValue N1 = N->getOperand(1);
11786 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11788 SmallVector<SDValue, 4> Ops;
11789 EVT ConcatVT = N0.getOperand(0).getValueType();
11790 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
11791 unsigned NumConcats = NumElts / NumElemsPerConcat;
11793 // Special case: shuffle(concat(A,B)) can be more efficiently represented
11794 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
11795 // half vector elements.
11796 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
11797 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
11798 SVN->getMask().end(), [](int i) { return i == -1; })) {
11799 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
11800 ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
11801 N1 = DAG.getUNDEF(ConcatVT);
11802 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
11805 // Look at every vector that's inserted. We're looking for exact
11806 // subvector-sized copies from a concatenated vector
11807 for (unsigned I = 0; I != NumConcats; ++I) {
11808 // Make sure we're dealing with a copy.
11809 unsigned Begin = I * NumElemsPerConcat;
11810 bool AllUndef = true, NoUndef = true;
11811 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
11812 if (SVN->getMaskElt(J) >= 0)
11819 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
11822 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
11823 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
11826 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
11827 if (FirstElt < N0.getNumOperands())
11828 Ops.push_back(N0.getOperand(FirstElt));
11830 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
11832 } else if (AllUndef) {
11833 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
11834 } else { // Mixed with general masks and undefs, can't do optimization.
11839 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
11842 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
11843 EVT VT = N->getValueType(0);
11844 unsigned NumElts = VT.getVectorNumElements();
11846 SDValue N0 = N->getOperand(0);
11847 SDValue N1 = N->getOperand(1);
11849 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
11851 // Canonicalize shuffle undef, undef -> undef
11852 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
11853 return DAG.getUNDEF(VT);
11855 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11857 // Canonicalize shuffle v, v -> v, undef
11859 SmallVector<int, 8> NewMask;
11860 for (unsigned i = 0; i != NumElts; ++i) {
11861 int Idx = SVN->getMaskElt(i);
11862 if (Idx >= (int)NumElts) Idx -= NumElts;
11863 NewMask.push_back(Idx);
11865 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
11869 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
11870 if (N0.getOpcode() == ISD::UNDEF) {
11871 SmallVector<int, 8> NewMask;
11872 for (unsigned i = 0; i != NumElts; ++i) {
11873 int Idx = SVN->getMaskElt(i);
11875 if (Idx >= (int)NumElts)
11878 Idx = -1; // remove reference to lhs
11880 NewMask.push_back(Idx);
11882 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
11886 // Remove references to rhs if it is undef
11887 if (N1.getOpcode() == ISD::UNDEF) {
11888 bool Changed = false;
11889 SmallVector<int, 8> NewMask;
11890 for (unsigned i = 0; i != NumElts; ++i) {
11891 int Idx = SVN->getMaskElt(i);
11892 if (Idx >= (int)NumElts) {
11896 NewMask.push_back(Idx);
11899 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
11902 // If it is a splat, check if the argument vector is another splat or a
11904 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
11905 SDNode *V = N0.getNode();
11907 // If this is a bit convert that changes the element type of the vector but
11908 // not the number of vector elements, look through it. Be careful not to
11909 // look though conversions that change things like v4f32 to v2f64.
11910 if (V->getOpcode() == ISD::BITCAST) {
11911 SDValue ConvInput = V->getOperand(0);
11912 if (ConvInput.getValueType().isVector() &&
11913 ConvInput.getValueType().getVectorNumElements() == NumElts)
11914 V = ConvInput.getNode();
11917 if (V->getOpcode() == ISD::BUILD_VECTOR) {
11918 assert(V->getNumOperands() == NumElts &&
11919 "BUILD_VECTOR has wrong number of operands");
11921 bool AllSame = true;
11922 for (unsigned i = 0; i != NumElts; ++i) {
11923 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
11924 Base = V->getOperand(i);
11928 // Splat of <u, u, u, u>, return <u, u, u, u>
11929 if (!Base.getNode())
11931 for (unsigned i = 0; i != NumElts; ++i) {
11932 if (V->getOperand(i) != Base) {
11937 // Splat of <x, x, x, x>, return <x, x, x, x>
11941 // Canonicalize any other splat as a build_vector.
11942 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
11943 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
11944 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
11945 V->getValueType(0), Ops);
11947 // We may have jumped through bitcasts, so the type of the
11948 // BUILD_VECTOR may not match the type of the shuffle.
11949 if (V->getValueType(0) != VT)
11950 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
11955 // There are various patterns used to build up a vector from smaller vectors,
11956 // subvectors, or elements. Scan chains of these and replace unused insertions
11957 // or components with undef.
11958 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
11961 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11962 Level < AfterLegalizeVectorOps &&
11963 (N1.getOpcode() == ISD::UNDEF ||
11964 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
11965 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
11966 SDValue V = partitionShuffleOfConcats(N, DAG);
11972 // If this shuffle only has a single input that is a bitcasted shuffle,
11973 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
11974 // back to their original types.
11975 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
11976 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
11977 TLI.isTypeLegal(VT)) {
11979 // Peek through the bitcast only if there is one user.
11981 while (BC0.getOpcode() == ISD::BITCAST) {
11982 if (!BC0.hasOneUse())
11984 BC0 = BC0.getOperand(0);
11987 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
11989 return SmallVector<int, 8>(Mask.begin(), Mask.end());
11991 SmallVector<int, 8> NewMask;
11993 for (int s = 0; s != Scale; ++s)
11994 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
11998 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
11999 EVT SVT = VT.getScalarType();
12000 EVT InnerVT = BC0->getValueType(0);
12001 EVT InnerSVT = InnerVT.getScalarType();
12003 // Determine which shuffle works with the smaller scalar type.
12004 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12005 EVT ScaleSVT = ScaleVT.getScalarType();
12007 if (TLI.isTypeLegal(ScaleVT) &&
12008 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12009 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12011 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12012 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12014 // Scale the shuffle masks to the smaller scalar type.
12015 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12016 SmallVector<int, 8> InnerMask =
12017 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12018 SmallVector<int, 8> OuterMask =
12019 ScaleShuffleMask(SVN->getMask(), OuterScale);
12021 // Merge the shuffle masks.
12022 SmallVector<int, 8> NewMask;
12023 for (int M : OuterMask)
12024 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12026 // Test for shuffle mask legality over both commutations.
12027 SDValue SV0 = BC0->getOperand(0);
12028 SDValue SV1 = BC0->getOperand(1);
12029 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12031 for (int i = 0, e = (int)NewMask.size(); i != e; ++i) {
12032 int idx = NewMask[i];
12036 NewMask[i] = idx + e;
12038 NewMask[i] = idx - e;
12040 std::swap(SV0, SV1);
12041 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12045 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12046 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12047 return DAG.getNode(
12048 ISD::BITCAST, SDLoc(N), VT,
12049 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12055 // Canonicalize shuffles according to rules:
12056 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12057 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12058 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12059 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12060 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12061 TLI.isTypeLegal(VT)) {
12062 // The incoming shuffle must be of the same type as the result of the
12063 // current shuffle.
12064 assert(N1->getOperand(0).getValueType() == VT &&
12065 "Shuffle types don't match");
12067 SDValue SV0 = N1->getOperand(0);
12068 SDValue SV1 = N1->getOperand(1);
12069 bool HasSameOp0 = N0 == SV0;
12070 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12071 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12072 // Commute the operands of this shuffle so that next rule
12074 return DAG.getCommutedVectorShuffle(*SVN);
12077 // Try to fold according to rules:
12078 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12079 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12080 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12081 // Don't try to fold shuffles with illegal type.
12082 // Only fold if this shuffle is the only user of the other shuffle.
12083 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12084 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12085 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12087 // The incoming shuffle must be of the same type as the result of the
12088 // current shuffle.
12089 assert(OtherSV->getOperand(0).getValueType() == VT &&
12090 "Shuffle types don't match");
12093 SmallVector<int, 4> Mask;
12094 // Compute the combined shuffle mask for a shuffle with SV0 as the first
12095 // operand, and SV1 as the second operand.
12096 for (unsigned i = 0; i != NumElts; ++i) {
12097 int Idx = SVN->getMaskElt(i);
12099 // Propagate Undef.
12100 Mask.push_back(Idx);
12104 SDValue CurrentVec;
12105 if (Idx < (int)NumElts) {
12106 // This shuffle index refers to the inner shuffle N0. Lookup the inner
12107 // shuffle mask to identify which vector is actually referenced.
12108 Idx = OtherSV->getMaskElt(Idx);
12110 // Propagate Undef.
12111 Mask.push_back(Idx);
12115 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12116 : OtherSV->getOperand(1);
12118 // This shuffle index references an element within N1.
12122 // Simple case where 'CurrentVec' is UNDEF.
12123 if (CurrentVec.getOpcode() == ISD::UNDEF) {
12124 Mask.push_back(-1);
12128 // Canonicalize the shuffle index. We don't know yet if CurrentVec
12129 // will be the first or second operand of the combined shuffle.
12130 Idx = Idx % NumElts;
12131 if (!SV0.getNode() || SV0 == CurrentVec) {
12132 // Ok. CurrentVec is the left hand side.
12133 // Update the mask accordingly.
12135 Mask.push_back(Idx);
12139 // Bail out if we cannot convert the shuffle pair into a single shuffle.
12140 if (SV1.getNode() && SV1 != CurrentVec)
12143 // Ok. CurrentVec is the right hand side.
12144 // Update the mask accordingly.
12146 Mask.push_back(Idx + NumElts);
12149 // Check if all indices in Mask are Undef. In case, propagate Undef.
12150 bool isUndefMask = true;
12151 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12152 isUndefMask &= Mask[i] < 0;
12155 return DAG.getUNDEF(VT);
12157 if (!SV0.getNode())
12158 SV0 = DAG.getUNDEF(VT);
12159 if (!SV1.getNode())
12160 SV1 = DAG.getUNDEF(VT);
12162 // Avoid introducing shuffles with illegal mask.
12163 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
12164 // Compute the commuted shuffle mask and test again.
12165 for (unsigned i = 0; i != NumElts; ++i) {
12169 else if (idx < (int)NumElts)
12170 Mask[i] = idx + NumElts;
12172 Mask[i] = idx - NumElts;
12175 if (!TLI.isShuffleMaskLegal(Mask, VT))
12178 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12179 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12180 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12181 std::swap(SV0, SV1);
12184 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12185 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12186 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12187 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
12193 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12194 SDValue InVal = N->getOperand(0);
12195 EVT VT = N->getValueType(0);
12197 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12198 // with a VECTOR_SHUFFLE.
12199 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12200 SDValue InVec = InVal->getOperand(0);
12201 SDValue EltNo = InVal->getOperand(1);
12203 // FIXME: We could support implicit truncation if the shuffle can be
12204 // scaled to a smaller vector scalar type.
12205 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12206 if (C0 && VT == InVec.getValueType() &&
12207 VT.getScalarType() == InVal.getValueType()) {
12208 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12209 int Elt = C0->getZExtValue();
12212 if (TLI.isShuffleMaskLegal(NewMask, VT))
12213 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12221 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12222 SDValue N0 = N->getOperand(0);
12223 SDValue N2 = N->getOperand(2);
12225 // If the input vector is a concatenation, and the insert replaces
12226 // one of the halves, we can optimize into a single concat_vectors.
12227 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12228 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12229 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12230 EVT VT = N->getValueType(0);
12232 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12233 // (concat_vectors Z, Y)
12235 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12236 N->getOperand(1), N0.getOperand(1));
12238 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12239 // (concat_vectors X, Z)
12240 if (InsIdx == VT.getVectorNumElements()/2)
12241 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12242 N0.getOperand(0), N->getOperand(1));
12248 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12249 /// with the destination vector and a zero vector.
12250 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
12251 /// vector_shuffle V, Zero, <0, 4, 2, 4>
12252 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
12253 EVT VT = N->getValueType(0);
12255 SDValue LHS = N->getOperand(0);
12256 SDValue RHS = N->getOperand(1);
12257 if (N->getOpcode() == ISD::AND) {
12258 if (RHS.getOpcode() == ISD::BITCAST)
12259 RHS = RHS.getOperand(0);
12260 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12261 SmallVector<int, 8> Indices;
12262 unsigned NumElts = RHS.getNumOperands();
12263 for (unsigned i = 0; i != NumElts; ++i) {
12264 SDValue Elt = RHS.getOperand(i);
12265 if (!isa<ConstantSDNode>(Elt))
12268 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
12269 Indices.push_back(i);
12270 else if (cast<ConstantSDNode>(Elt)->isNullValue())
12271 Indices.push_back(NumElts+i);
12276 // Let's see if the target supports this vector_shuffle and make sure
12277 // we're not running after operation legalization where it may have
12278 // custom lowered the vector shuffles.
12279 EVT RVT = RHS.getValueType();
12280 if (LegalOperations || !TLI.isVectorClearMaskLegal(Indices, RVT))
12283 // Return the new VECTOR_SHUFFLE node.
12284 EVT EltVT = RVT.getVectorElementType();
12285 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
12286 DAG.getConstant(0, EltVT));
12287 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
12288 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
12289 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
12290 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
12297 /// Visit a binary vector operation, like ADD.
12298 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
12299 assert(N->getValueType(0).isVector() &&
12300 "SimplifyVBinOp only works on vectors!");
12302 SDValue LHS = N->getOperand(0);
12303 SDValue RHS = N->getOperand(1);
12304 SDValue Shuffle = XformToShuffleWithZero(N);
12305 if (Shuffle.getNode()) return Shuffle;
12307 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
12309 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
12310 RHS.getOpcode() == ISD::BUILD_VECTOR) {
12311 // Check if both vectors are constants. If not bail out.
12312 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
12313 cast<BuildVectorSDNode>(RHS)->isConstant()))
12316 SmallVector<SDValue, 8> Ops;
12317 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
12318 SDValue LHSOp = LHS.getOperand(i);
12319 SDValue RHSOp = RHS.getOperand(i);
12321 // Can't fold divide by zero.
12322 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
12323 N->getOpcode() == ISD::FDIV) {
12324 if ((RHSOp.getOpcode() == ISD::Constant &&
12325 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
12326 (RHSOp.getOpcode() == ISD::ConstantFP &&
12327 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
12331 EVT VT = LHSOp.getValueType();
12332 EVT RVT = RHSOp.getValueType();
12334 // Integer BUILD_VECTOR operands may have types larger than the element
12335 // size (e.g., when the element type is not legal). Prior to type
12336 // legalization, the types may not match between the two BUILD_VECTORS.
12337 // Truncate one of the operands to make them match.
12338 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
12339 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
12341 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
12345 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
12347 if (FoldOp.getOpcode() != ISD::UNDEF &&
12348 FoldOp.getOpcode() != ISD::Constant &&
12349 FoldOp.getOpcode() != ISD::ConstantFP)
12351 Ops.push_back(FoldOp);
12352 AddToWorklist(FoldOp.getNode());
12355 if (Ops.size() == LHS.getNumOperands())
12356 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
12359 // Type legalization might introduce new shuffles in the DAG.
12360 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
12361 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
12362 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
12363 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
12364 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
12365 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
12366 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
12367 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
12369 if (SVN0->getMask().equals(SVN1->getMask())) {
12370 EVT VT = N->getValueType(0);
12371 SDValue UndefVector = LHS.getOperand(1);
12372 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
12373 LHS.getOperand(0), RHS.getOperand(0));
12374 AddUsersToWorklist(N);
12375 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
12376 &SVN0->getMask()[0]);
12383 /// Visit a binary vector operation, like FABS/FNEG.
12384 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
12385 assert(N->getValueType(0).isVector() &&
12386 "SimplifyVUnaryOp only works on vectors!");
12388 SDValue N0 = N->getOperand(0);
12390 if (N0.getOpcode() != ISD::BUILD_VECTOR)
12393 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
12394 SmallVector<SDValue, 8> Ops;
12395 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
12396 SDValue Op = N0.getOperand(i);
12397 if (Op.getOpcode() != ISD::UNDEF &&
12398 Op.getOpcode() != ISD::ConstantFP)
12400 EVT EltVT = Op.getValueType();
12401 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
12402 if (FoldOp.getOpcode() != ISD::UNDEF &&
12403 FoldOp.getOpcode() != ISD::ConstantFP)
12405 Ops.push_back(FoldOp);
12406 AddToWorklist(FoldOp.getNode());
12409 if (Ops.size() != N0.getNumOperands())
12412 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
12415 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
12416 SDValue N1, SDValue N2){
12417 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
12419 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
12420 cast<CondCodeSDNode>(N0.getOperand(2))->get());
12422 // If we got a simplified select_cc node back from SimplifySelectCC, then
12423 // break it down into a new SETCC node, and a new SELECT node, and then return
12424 // the SELECT node, since we were called with a SELECT node.
12425 if (SCC.getNode()) {
12426 // Check to see if we got a select_cc back (to turn into setcc/select).
12427 // Otherwise, just return whatever node we got back, like fabs.
12428 if (SCC.getOpcode() == ISD::SELECT_CC) {
12429 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
12431 SCC.getOperand(0), SCC.getOperand(1),
12432 SCC.getOperand(4));
12433 AddToWorklist(SETCC.getNode());
12434 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
12435 SCC.getOperand(2), SCC.getOperand(3));
12443 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
12444 /// being selected between, see if we can simplify the select. Callers of this
12445 /// should assume that TheSelect is deleted if this returns true. As such, they
12446 /// should return the appropriate thing (e.g. the node) back to the top-level of
12447 /// the DAG combiner loop to avoid it being looked at.
12448 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
12451 // Cannot simplify select with vector condition
12452 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
12454 // If this is a select from two identical things, try to pull the operation
12455 // through the select.
12456 if (LHS.getOpcode() != RHS.getOpcode() ||
12457 !LHS.hasOneUse() || !RHS.hasOneUse())
12460 // If this is a load and the token chain is identical, replace the select
12461 // of two loads with a load through a select of the address to load from.
12462 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
12463 // constants have been dropped into the constant pool.
12464 if (LHS.getOpcode() == ISD::LOAD) {
12465 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
12466 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
12468 // Token chains must be identical.
12469 if (LHS.getOperand(0) != RHS.getOperand(0) ||
12470 // Do not let this transformation reduce the number of volatile loads.
12471 LLD->isVolatile() || RLD->isVolatile() ||
12472 // If this is an EXTLOAD, the VT's must match.
12473 LLD->getMemoryVT() != RLD->getMemoryVT() ||
12474 // If this is an EXTLOAD, the kind of extension must match.
12475 (LLD->getExtensionType() != RLD->getExtensionType() &&
12476 // The only exception is if one of the extensions is anyext.
12477 LLD->getExtensionType() != ISD::EXTLOAD &&
12478 RLD->getExtensionType() != ISD::EXTLOAD) ||
12479 // FIXME: this discards src value information. This is
12480 // over-conservative. It would be beneficial to be able to remember
12481 // both potential memory locations. Since we are discarding
12482 // src value info, don't do the transformation if the memory
12483 // locations are not in the default address space.
12484 LLD->getPointerInfo().getAddrSpace() != 0 ||
12485 RLD->getPointerInfo().getAddrSpace() != 0 ||
12486 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
12487 LLD->getBasePtr().getValueType()))
12490 // Check that the select condition doesn't reach either load. If so,
12491 // folding this will induce a cycle into the DAG. If not, this is safe to
12492 // xform, so create a select of the addresses.
12494 if (TheSelect->getOpcode() == ISD::SELECT) {
12495 SDNode *CondNode = TheSelect->getOperand(0).getNode();
12496 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
12497 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
12499 // The loads must not depend on one another.
12500 if (LLD->isPredecessorOf(RLD) ||
12501 RLD->isPredecessorOf(LLD))
12503 Addr = DAG.getSelect(SDLoc(TheSelect),
12504 LLD->getBasePtr().getValueType(),
12505 TheSelect->getOperand(0), LLD->getBasePtr(),
12506 RLD->getBasePtr());
12507 } else { // Otherwise SELECT_CC
12508 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
12509 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
12511 if ((LLD->hasAnyUseOfValue(1) &&
12512 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
12513 (RLD->hasAnyUseOfValue(1) &&
12514 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
12517 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
12518 LLD->getBasePtr().getValueType(),
12519 TheSelect->getOperand(0),
12520 TheSelect->getOperand(1),
12521 LLD->getBasePtr(), RLD->getBasePtr(),
12522 TheSelect->getOperand(4));
12526 // It is safe to replace the two loads if they have different alignments,
12527 // but the new load must be the minimum (most restrictive) alignment of the
12529 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
12530 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
12531 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
12532 Load = DAG.getLoad(TheSelect->getValueType(0),
12534 // FIXME: Discards pointer and AA info.
12535 LLD->getChain(), Addr, MachinePointerInfo(),
12536 LLD->isVolatile(), LLD->isNonTemporal(),
12537 isInvariant, Alignment);
12539 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
12540 RLD->getExtensionType() : LLD->getExtensionType(),
12542 TheSelect->getValueType(0),
12543 // FIXME: Discards pointer and AA info.
12544 LLD->getChain(), Addr, MachinePointerInfo(),
12545 LLD->getMemoryVT(), LLD->isVolatile(),
12546 LLD->isNonTemporal(), isInvariant, Alignment);
12549 // Users of the select now use the result of the load.
12550 CombineTo(TheSelect, Load);
12552 // Users of the old loads now use the new load's chain. We know the
12553 // old-load value is dead now.
12554 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
12555 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
12562 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
12563 /// where 'cond' is the comparison specified by CC.
12564 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
12565 SDValue N2, SDValue N3,
12566 ISD::CondCode CC, bool NotExtCompare) {
12567 // (x ? y : y) -> y.
12568 if (N2 == N3) return N2;
12570 EVT VT = N2.getValueType();
12571 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
12572 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
12573 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
12575 // Determine if the condition we're dealing with is constant
12576 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
12577 N0, N1, CC, DL, false);
12578 if (SCC.getNode()) AddToWorklist(SCC.getNode());
12579 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
12581 // fold select_cc true, x, y -> x
12582 if (SCCC && !SCCC->isNullValue())
12584 // fold select_cc false, x, y -> y
12585 if (SCCC && SCCC->isNullValue())
12588 // Check to see if we can simplify the select into an fabs node
12589 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
12590 // Allow either -0.0 or 0.0
12591 if (CFP->getValueAPF().isZero()) {
12592 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
12593 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
12594 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
12595 N2 == N3.getOperand(0))
12596 return DAG.getNode(ISD::FABS, DL, VT, N0);
12598 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
12599 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
12600 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
12601 N2.getOperand(0) == N3)
12602 return DAG.getNode(ISD::FABS, DL, VT, N3);
12606 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
12607 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
12608 // in it. This is a win when the constant is not otherwise available because
12609 // it replaces two constant pool loads with one. We only do this if the FP
12610 // type is known to be legal, because if it isn't, then we are before legalize
12611 // types an we want the other legalization to happen first (e.g. to avoid
12612 // messing with soft float) and if the ConstantFP is not legal, because if
12613 // it is legal, we may not need to store the FP constant in a constant pool.
12614 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
12615 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
12616 if (TLI.isTypeLegal(N2.getValueType()) &&
12617 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
12618 TargetLowering::Legal &&
12619 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
12620 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
12621 // If both constants have multiple uses, then we won't need to do an
12622 // extra load, they are likely around in registers for other users.
12623 (TV->hasOneUse() || FV->hasOneUse())) {
12624 Constant *Elts[] = {
12625 const_cast<ConstantFP*>(FV->getConstantFPValue()),
12626 const_cast<ConstantFP*>(TV->getConstantFPValue())
12628 Type *FPTy = Elts[0]->getType();
12629 const DataLayout &TD = *TLI.getDataLayout();
12631 // Create a ConstantArray of the two constants.
12632 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
12633 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
12634 TD.getPrefTypeAlignment(FPTy));
12635 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12637 // Get the offsets to the 0 and 1 element of the array so that we can
12638 // select between them.
12639 SDValue Zero = DAG.getIntPtrConstant(0);
12640 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
12641 SDValue One = DAG.getIntPtrConstant(EltSize);
12643 SDValue Cond = DAG.getSetCC(DL,
12644 getSetCCResultType(N0.getValueType()),
12646 AddToWorklist(Cond.getNode());
12647 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
12649 AddToWorklist(CstOffset.getNode());
12650 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
12652 AddToWorklist(CPIdx.getNode());
12653 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
12654 MachinePointerInfo::getConstantPool(), false,
12655 false, false, Alignment);
12660 // Check to see if we can perform the "gzip trick", transforming
12661 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
12662 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
12663 (N1C->isNullValue() || // (a < 0) ? b : 0
12664 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
12665 EVT XType = N0.getValueType();
12666 EVT AType = N2.getValueType();
12667 if (XType.bitsGE(AType)) {
12668 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
12669 // single-bit constant.
12670 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
12671 unsigned ShCtV = N2C->getAPIntValue().logBase2();
12672 ShCtV = XType.getSizeInBits()-ShCtV-1;
12673 SDValue ShCt = DAG.getConstant(ShCtV,
12674 getShiftAmountTy(N0.getValueType()));
12675 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
12677 AddToWorklist(Shift.getNode());
12679 if (XType.bitsGT(AType)) {
12680 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
12681 AddToWorklist(Shift.getNode());
12684 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
12687 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
12689 DAG.getConstant(XType.getSizeInBits()-1,
12690 getShiftAmountTy(N0.getValueType())));
12691 AddToWorklist(Shift.getNode());
12693 if (XType.bitsGT(AType)) {
12694 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
12695 AddToWorklist(Shift.getNode());
12698 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
12702 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
12703 // where y is has a single bit set.
12704 // A plaintext description would be, we can turn the SELECT_CC into an AND
12705 // when the condition can be materialized as an all-ones register. Any
12706 // single bit-test can be materialized as an all-ones register with
12707 // shift-left and shift-right-arith.
12708 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
12709 N0->getValueType(0) == VT &&
12710 N1C && N1C->isNullValue() &&
12711 N2C && N2C->isNullValue()) {
12712 SDValue AndLHS = N0->getOperand(0);
12713 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
12714 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
12715 // Shift the tested bit over the sign bit.
12716 APInt AndMask = ConstAndRHS->getAPIntValue();
12718 DAG.getConstant(AndMask.countLeadingZeros(),
12719 getShiftAmountTy(AndLHS.getValueType()));
12720 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
12722 // Now arithmetic right shift it all the way over, so the result is either
12723 // all-ones, or zero.
12725 DAG.getConstant(AndMask.getBitWidth()-1,
12726 getShiftAmountTy(Shl.getValueType()));
12727 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
12729 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
12733 // fold select C, 16, 0 -> shl C, 4
12734 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
12735 TLI.getBooleanContents(N0.getValueType()) ==
12736 TargetLowering::ZeroOrOneBooleanContent) {
12738 // If the caller doesn't want us to simplify this into a zext of a compare,
12740 if (NotExtCompare && N2C->getAPIntValue() == 1)
12743 // Get a SetCC of the condition
12744 // NOTE: Don't create a SETCC if it's not legal on this target.
12745 if (!LegalOperations ||
12746 TLI.isOperationLegal(ISD::SETCC,
12747 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
12749 // cast from setcc result type to select result type
12751 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
12753 if (N2.getValueType().bitsLT(SCC.getValueType()))
12754 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
12755 N2.getValueType());
12757 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
12758 N2.getValueType(), SCC);
12760 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
12761 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
12762 N2.getValueType(), SCC);
12765 AddToWorklist(SCC.getNode());
12766 AddToWorklist(Temp.getNode());
12768 if (N2C->getAPIntValue() == 1)
12771 // shl setcc result by log2 n2c
12772 return DAG.getNode(
12773 ISD::SHL, DL, N2.getValueType(), Temp,
12774 DAG.getConstant(N2C->getAPIntValue().logBase2(),
12775 getShiftAmountTy(Temp.getValueType())));
12779 // Check to see if this is the equivalent of setcc
12780 // FIXME: Turn all of these into setcc if setcc if setcc is legal
12781 // otherwise, go ahead with the folds.
12782 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
12783 EVT XType = N0.getValueType();
12784 if (!LegalOperations ||
12785 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
12786 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
12787 if (Res.getValueType() != VT)
12788 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
12792 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
12793 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
12794 (!LegalOperations ||
12795 TLI.isOperationLegal(ISD::CTLZ, XType))) {
12796 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
12797 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
12798 DAG.getConstant(Log2_32(XType.getSizeInBits()),
12799 getShiftAmountTy(Ctlz.getValueType())));
12801 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
12802 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
12803 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
12804 XType, DAG.getConstant(0, XType), N0);
12805 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
12806 return DAG.getNode(ISD::SRL, DL, XType,
12807 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
12808 DAG.getConstant(XType.getSizeInBits()-1,
12809 getShiftAmountTy(XType)));
12811 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
12812 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
12813 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
12814 DAG.getConstant(XType.getSizeInBits()-1,
12815 getShiftAmountTy(N0.getValueType())));
12816 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
12820 // Check to see if this is an integer abs.
12821 // select_cc setg[te] X, 0, X, -X ->
12822 // select_cc setgt X, -1, X, -X ->
12823 // select_cc setl[te] X, 0, -X, X ->
12824 // select_cc setlt X, 1, -X, X ->
12825 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
12827 ConstantSDNode *SubC = nullptr;
12828 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
12829 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
12830 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
12831 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
12832 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
12833 (N1C->isOne() && CC == ISD::SETLT)) &&
12834 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
12835 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
12837 EVT XType = N0.getValueType();
12838 if (SubC && SubC->isNullValue() && XType.isInteger()) {
12839 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
12841 DAG.getConstant(XType.getSizeInBits()-1,
12842 getShiftAmountTy(N0.getValueType())));
12843 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
12845 AddToWorklist(Shift.getNode());
12846 AddToWorklist(Add.getNode());
12847 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
12854 /// This is a stub for TargetLowering::SimplifySetCC.
12855 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
12856 SDValue N1, ISD::CondCode Cond,
12857 SDLoc DL, bool foldBooleans) {
12858 TargetLowering::DAGCombinerInfo
12859 DagCombineInfo(DAG, Level, false, this);
12860 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
12863 /// Given an ISD::SDIV node expressing a divide by constant, return
12864 /// a DAG expression to select that will generate the same value by multiplying
12865 /// by a magic number.
12866 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12867 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
12868 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12872 // Avoid division by zero.
12873 if (!C->getAPIntValue())
12876 std::vector<SDNode*> Built;
12878 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12880 for (SDNode *N : Built)
12885 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
12886 /// DAG expression that will generate the same value by right shifting.
12887 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
12888 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12892 // Avoid division by zero.
12893 if (!C->getAPIntValue())
12896 std::vector<SDNode *> Built;
12897 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
12899 for (SDNode *N : Built)
12904 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
12905 /// expression that will generate the same value by multiplying by a magic
12907 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12908 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
12909 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12913 // Avoid division by zero.
12914 if (!C->getAPIntValue())
12917 std::vector<SDNode*> Built;
12919 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12921 for (SDNode *N : Built)
12926 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
12927 if (Level >= AfterLegalizeDAG)
12930 // Expose the DAG combiner to the target combiner implementations.
12931 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12933 unsigned Iterations = 0;
12934 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
12936 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12937 // For the reciprocal, we need to find the zero of the function:
12938 // F(X) = A X - 1 [which has a zero at X = 1/A]
12940 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
12941 // does not require additional intermediate precision]
12942 EVT VT = Op.getValueType();
12944 SDValue FPOne = DAG.getConstantFP(1.0, VT);
12946 AddToWorklist(Est.getNode());
12948 // Newton iterations: Est = Est + Est (1 - Arg * Est)
12949 for (unsigned i = 0; i < Iterations; ++i) {
12950 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
12951 AddToWorklist(NewEst.getNode());
12953 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
12954 AddToWorklist(NewEst.getNode());
12956 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12957 AddToWorklist(NewEst.getNode());
12959 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
12960 AddToWorklist(Est.getNode());
12969 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12970 /// For the reciprocal sqrt, we need to find the zero of the function:
12971 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12973 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
12974 /// As a result, we precompute A/2 prior to the iteration loop.
12975 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
12976 unsigned Iterations) {
12977 EVT VT = Arg.getValueType();
12979 SDValue ThreeHalves = DAG.getConstantFP(1.5, VT);
12981 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
12982 // this entire sequence requires only one FP constant.
12983 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
12984 AddToWorklist(HalfArg.getNode());
12986 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
12987 AddToWorklist(HalfArg.getNode());
12989 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
12990 for (unsigned i = 0; i < Iterations; ++i) {
12991 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12992 AddToWorklist(NewEst.getNode());
12994 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
12995 AddToWorklist(NewEst.getNode());
12997 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
12998 AddToWorklist(NewEst.getNode());
13000 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13001 AddToWorklist(Est.getNode());
13006 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13007 /// For the reciprocal sqrt, we need to find the zero of the function:
13008 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13010 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13011 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13012 unsigned Iterations) {
13013 EVT VT = Arg.getValueType();
13015 SDValue MinusThree = DAG.getConstantFP(-3.0, VT);
13016 SDValue MinusHalf = DAG.getConstantFP(-0.5, VT);
13018 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13019 for (unsigned i = 0; i < Iterations; ++i) {
13020 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13021 AddToWorklist(HalfEst.getNode());
13023 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13024 AddToWorklist(Est.getNode());
13026 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13027 AddToWorklist(Est.getNode());
13029 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13030 AddToWorklist(Est.getNode());
13032 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13033 AddToWorklist(Est.getNode());
13038 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13039 if (Level >= AfterLegalizeDAG)
13042 // Expose the DAG combiner to the target combiner implementations.
13043 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13044 unsigned Iterations = 0;
13045 bool UseOneConstNR = false;
13046 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13047 AddToWorklist(Est.getNode());
13049 Est = UseOneConstNR ?
13050 BuildRsqrtNROneConst(Op, Est, Iterations) :
13051 BuildRsqrtNRTwoConst(Op, Est, Iterations);
13059 /// Return true if base is a frame index, which is known not to alias with
13060 /// anything but itself. Provides base object and offset as results.
13061 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
13062 const GlobalValue *&GV, const void *&CV) {
13063 // Assume it is a primitive operation.
13064 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
13066 // If it's an adding a simple constant then integrate the offset.
13067 if (Base.getOpcode() == ISD::ADD) {
13068 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13069 Base = Base.getOperand(0);
13070 Offset += C->getZExtValue();
13074 // Return the underlying GlobalValue, and update the Offset. Return false
13075 // for GlobalAddressSDNode since the same GlobalAddress may be represented
13076 // by multiple nodes with different offsets.
13077 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13078 GV = G->getGlobal();
13079 Offset += G->getOffset();
13083 // Return the underlying Constant value, and update the Offset. Return false
13084 // for ConstantSDNodes since the same constant pool entry may be represented
13085 // by multiple nodes with different offsets.
13086 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
13087 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13088 : (const void *)C->getConstVal();
13089 Offset += C->getOffset();
13092 // If it's any of the following then it can't alias with anything but itself.
13093 return isa<FrameIndexSDNode>(Base);
13096 /// Return true if there is any possibility that the two addresses overlap.
13097 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
13098 // If they are the same then they must be aliases.
13099 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
13101 // If they are both volatile then they cannot be reordered.
13102 if (Op0->isVolatile() && Op1->isVolatile()) return true;
13104 // Gather base node and offset information.
13105 SDValue Base1, Base2;
13106 int64_t Offset1, Offset2;
13107 const GlobalValue *GV1, *GV2;
13108 const void *CV1, *CV2;
13109 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13110 Base1, Offset1, GV1, CV1);
13111 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13112 Base2, Offset2, GV2, CV2);
13114 // If they have a same base address then check to see if they overlap.
13115 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
13116 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13117 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13119 // It is possible for different frame indices to alias each other, mostly
13120 // when tail call optimization reuses return address slots for arguments.
13121 // To catch this case, look up the actual index of frame indices to compute
13122 // the real alias relationship.
13123 if (isFrameIndex1 && isFrameIndex2) {
13124 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13125 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13126 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
13127 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13128 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13131 // Otherwise, if we know what the bases are, and they aren't identical, then
13132 // we know they cannot alias.
13133 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13136 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13137 // compared to the size and offset of the access, we may be able to prove they
13138 // do not alias. This check is conservative for now to catch cases created by
13139 // splitting vector types.
13140 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13141 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13142 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13143 Op1->getMemoryVT().getSizeInBits() >> 3) &&
13144 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13145 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13146 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
13148 // There is no overlap between these relatively aligned accesses of similar
13149 // size, return no alias.
13150 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13151 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
13155 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13157 : DAG.getSubtarget().useAA();
13159 if (CombinerAAOnlyFunc.getNumOccurrences() &&
13160 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13164 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
13165 // Use alias analysis information.
13166 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13167 Op1->getSrcValueOffset());
13168 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13169 Op0->getSrcValueOffset() - MinOffset;
13170 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13171 Op1->getSrcValueOffset() - MinOffset;
13172 AliasAnalysis::AliasResult AAResult =
13173 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
13175 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
13176 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
13178 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
13179 if (AAResult == AliasAnalysis::NoAlias)
13183 // Otherwise we have to assume they alias.
13187 /// Walk up chain skipping non-aliasing memory nodes,
13188 /// looking for aliasing nodes and adding them to the Aliases vector.
13189 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
13190 SmallVectorImpl<SDValue> &Aliases) {
13191 SmallVector<SDValue, 8> Chains; // List of chains to visit.
13192 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
13194 // Get alias information for node.
13195 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
13198 Chains.push_back(OriginalChain);
13199 unsigned Depth = 0;
13201 // Look at each chain and determine if it is an alias. If so, add it to the
13202 // aliases list. If not, then continue up the chain looking for the next
13204 while (!Chains.empty()) {
13205 SDValue Chain = Chains.back();
13208 // For TokenFactor nodes, look at each operand and only continue up the
13209 // chain until we find two aliases. If we've seen two aliases, assume we'll
13210 // find more and revert to original chain since the xform is unlikely to be
13213 // FIXME: The depth check could be made to return the last non-aliasing
13214 // chain we found before we hit a tokenfactor rather than the original
13216 if (Depth > 6 || Aliases.size() == 2) {
13218 Aliases.push_back(OriginalChain);
13222 // Don't bother if we've been before.
13223 if (!Visited.insert(Chain.getNode()).second)
13226 switch (Chain.getOpcode()) {
13227 case ISD::EntryToken:
13228 // Entry token is ideal chain operand, but handled in FindBetterChain.
13233 // Get alias information for Chain.
13234 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13235 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
13237 // If chain is alias then stop here.
13238 if (!(IsLoad && IsOpLoad) &&
13239 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
13240 Aliases.push_back(Chain);
13242 // Look further up the chain.
13243 Chains.push_back(Chain.getOperand(0));
13249 case ISD::TokenFactor:
13250 // We have to check each of the operands of the token factor for "small"
13251 // token factors, so we queue them up. Adding the operands to the queue
13252 // (stack) in reverse order maintains the original order and increases the
13253 // likelihood that getNode will find a matching token factor (CSE.)
13254 if (Chain.getNumOperands() > 16) {
13255 Aliases.push_back(Chain);
13258 for (unsigned n = Chain.getNumOperands(); n;)
13259 Chains.push_back(Chain.getOperand(--n));
13264 // For all other instructions we will just have to take what we can get.
13265 Aliases.push_back(Chain);
13270 // We need to be careful here to also search for aliases through the
13271 // value operand of a store, etc. Consider the following situation:
13273 // L1 = load Token1, %52
13274 // S1 = store Token1, L1, %51
13275 // L2 = load Token1, %52+8
13276 // S2 = store Token1, L2, %51+8
13277 // Token2 = Token(S1, S2)
13278 // L3 = load Token2, %53
13279 // S3 = store Token2, L3, %52
13280 // L4 = load Token2, %53+8
13281 // S4 = store Token2, L4, %52+8
13282 // If we search for aliases of S3 (which loads address %52), and we look
13283 // only through the chain, then we'll miss the trivial dependence on L1
13284 // (which also loads from %52). We then might change all loads and
13285 // stores to use Token1 as their chain operand, which could result in
13286 // copying %53 into %52 before copying %52 into %51 (which should
13289 // The problem is, however, that searching for such data dependencies
13290 // can become expensive, and the cost is not directly related to the
13291 // chain depth. Instead, we'll rule out such configurations here by
13292 // insisting that we've visited all chain users (except for users
13293 // of the original chain, which is not necessary). When doing this,
13294 // we need to look through nodes we don't care about (otherwise, things
13295 // like register copies will interfere with trivial cases).
13297 SmallVector<const SDNode *, 16> Worklist;
13298 for (const SDNode *N : Visited)
13299 if (N != OriginalChain.getNode())
13300 Worklist.push_back(N);
13302 while (!Worklist.empty()) {
13303 const SDNode *M = Worklist.pop_back_val();
13305 // We have already visited M, and want to make sure we've visited any uses
13306 // of M that we care about. For uses that we've not visisted, and don't
13307 // care about, queue them to the worklist.
13309 for (SDNode::use_iterator UI = M->use_begin(),
13310 UIE = M->use_end(); UI != UIE; ++UI)
13311 if (UI.getUse().getValueType() == MVT::Other &&
13312 Visited.insert(*UI).second) {
13313 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
13314 // We've not visited this use, and we care about it (it could have an
13315 // ordering dependency with the original node).
13317 Aliases.push_back(OriginalChain);
13321 // We've not visited this use, but we don't care about it. Mark it as
13322 // visited and enqueue it to the worklist.
13323 Worklist.push_back(*UI);
13328 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
13329 /// (aliasing node.)
13330 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
13331 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
13333 // Accumulate all the aliases to this node.
13334 GatherAllAliases(N, OldChain, Aliases);
13336 // If no operands then chain to entry token.
13337 if (Aliases.size() == 0)
13338 return DAG.getEntryNode();
13340 // If a single operand then chain to it. We don't need to revisit it.
13341 if (Aliases.size() == 1)
13344 // Construct a custom tailored token factor.
13345 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
13348 /// This is the entry point for the file.
13349 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
13350 CodeGenOpt::Level OptLevel) {
13351 /// This is the main entry point to this class.
13352 DAGCombiner(*this, AA, OptLevel).Run(Level);