1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run
11 // both before and after the DAG is legalized.
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
17 //===----------------------------------------------------------------------===//
19 #define DEBUG_TYPE "dagcombine"
20 #include "llvm/CodeGen/SelectionDAG.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetLowering.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
43 STATISTIC(NodesCombined , "Number of dag nodes combined");
44 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
45 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
46 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
47 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
48 STATISTIC(SlicedLoads, "Number of load sliced");
52 CombinerAA("combiner-alias-analysis", cl::Hidden,
53 cl::desc("Enable DAG combiner alias-analysis heuristics"));
56 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
57 cl::desc("Enable DAG combiner's use of IR alias analysis"));
59 // FIXME: Enable the use of TBAA. There are two known issues preventing this:
60 // 1. Stack coloring does not update TBAA when merging allocas
61 // 2. CGP inserts ptrtoint/inttoptr pairs when sinking address computations.
62 // Because BasicAA does not handle inttoptr, we'll often miss basic type
63 // punning idioms that we need to catch so we don't miscompile real-world
66 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(false),
67 cl::desc("Enable DAG combiner's use of TBAA"));
70 static cl::opt<std::string>
71 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
72 cl::desc("Only use DAG-combiner alias analysis in this"
76 /// Hidden option to stress test load slicing, i.e., when this option
77 /// is enabled, load slicing bypasses most of its profitability guards.
79 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
80 cl::desc("Bypass the profitability model of load "
84 //------------------------------ DAGCombiner ---------------------------------//
88 const TargetLowering &TLI;
90 CodeGenOpt::Level OptLevel;
95 // Worklist of all of the nodes that need to be simplified.
97 // This has the semantics that when adding to the worklist,
98 // the item added must be next to be processed. It should
99 // also only appear once. The naive approach to this takes
102 // To reduce the insert/remove time to logarithmic, we use
103 // a set and a vector to maintain our worklist.
105 // The set contains the items on the worklist, but does not
106 // maintain the order they should be visited.
108 // The vector maintains the order nodes should be visited, but may
109 // contain duplicate or removed nodes. When choosing a node to
110 // visit, we pop off the order stack until we find an item that is
111 // also in the contents set. All operations are O(log N).
112 SmallPtrSet<SDNode*, 64> WorkListContents;
113 SmallVector<SDNode*, 64> WorkListOrder;
115 // AA - Used for DAG load/store alias analysis.
118 /// AddUsersToWorkList - When an instruction is simplified, add all users of
119 /// the instruction to the work lists because they might get more simplified
122 void AddUsersToWorkList(SDNode *N) {
123 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
128 /// visit - call the node-specific routine that knows how to fold each
129 /// particular type of node.
130 SDValue visit(SDNode *N);
133 /// AddToWorkList - Add to the work list making sure its instance is at the
134 /// back (next to be processed.)
135 void AddToWorkList(SDNode *N) {
136 WorkListContents.insert(N);
137 WorkListOrder.push_back(N);
140 /// removeFromWorkList - remove all instances of N from the worklist.
142 void removeFromWorkList(SDNode *N) {
143 WorkListContents.erase(N);
146 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
149 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
150 return CombineTo(N, &Res, 1, AddTo);
153 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
155 SDValue To[] = { Res0, Res1 };
156 return CombineTo(N, To, 2, AddTo);
159 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
163 /// SimplifyDemandedBits - Check the specified integer node value to see if
164 /// it can be simplified or if things it uses can be simplified by bit
165 /// propagation. If so, return true.
166 bool SimplifyDemandedBits(SDValue Op) {
167 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
168 APInt Demanded = APInt::getAllOnesValue(BitWidth);
169 return SimplifyDemandedBits(Op, Demanded);
172 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
174 bool CombineToPreIndexedLoadStore(SDNode *N);
175 bool CombineToPostIndexedLoadStore(SDNode *N);
176 bool SliceUpLoad(SDNode *N);
178 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
179 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
180 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
181 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
182 SDValue PromoteIntBinOp(SDValue Op);
183 SDValue PromoteIntShiftOp(SDValue Op);
184 SDValue PromoteExtend(SDValue Op);
185 bool PromoteLoad(SDValue Op);
187 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
188 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
189 ISD::NodeType ExtType);
191 /// combine - call the node-specific routine that knows how to fold each
192 /// particular type of node. If that doesn't do anything, try the
193 /// target-specific DAG combines.
194 SDValue combine(SDNode *N);
196 // Visitation implementation - Implement dag node combining for different
197 // node types. The semantics are as follows:
199 // SDValue.getNode() == 0 - No change was made
200 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
201 // otherwise - N should be replaced by the returned Operand.
203 SDValue visitTokenFactor(SDNode *N);
204 SDValue visitMERGE_VALUES(SDNode *N);
205 SDValue visitADD(SDNode *N);
206 SDValue visitSUB(SDNode *N);
207 SDValue visitADDC(SDNode *N);
208 SDValue visitSUBC(SDNode *N);
209 SDValue visitADDE(SDNode *N);
210 SDValue visitSUBE(SDNode *N);
211 SDValue visitMUL(SDNode *N);
212 SDValue visitSDIV(SDNode *N);
213 SDValue visitUDIV(SDNode *N);
214 SDValue visitSREM(SDNode *N);
215 SDValue visitUREM(SDNode *N);
216 SDValue visitMULHU(SDNode *N);
217 SDValue visitMULHS(SDNode *N);
218 SDValue visitSMUL_LOHI(SDNode *N);
219 SDValue visitUMUL_LOHI(SDNode *N);
220 SDValue visitSMULO(SDNode *N);
221 SDValue visitUMULO(SDNode *N);
222 SDValue visitSDIVREM(SDNode *N);
223 SDValue visitUDIVREM(SDNode *N);
224 SDValue visitAND(SDNode *N);
225 SDValue visitOR(SDNode *N);
226 SDValue visitXOR(SDNode *N);
227 SDValue SimplifyVBinOp(SDNode *N);
228 SDValue SimplifyVUnaryOp(SDNode *N);
229 SDValue visitSHL(SDNode *N);
230 SDValue visitSRA(SDNode *N);
231 SDValue visitSRL(SDNode *N);
232 SDValue visitRotate(SDNode *N);
233 SDValue visitCTLZ(SDNode *N);
234 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
235 SDValue visitCTTZ(SDNode *N);
236 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
237 SDValue visitCTPOP(SDNode *N);
238 SDValue visitSELECT(SDNode *N);
239 SDValue visitVSELECT(SDNode *N);
240 SDValue visitSELECT_CC(SDNode *N);
241 SDValue visitSETCC(SDNode *N);
242 SDValue visitSIGN_EXTEND(SDNode *N);
243 SDValue visitZERO_EXTEND(SDNode *N);
244 SDValue visitANY_EXTEND(SDNode *N);
245 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
246 SDValue visitTRUNCATE(SDNode *N);
247 SDValue visitBITCAST(SDNode *N);
248 SDValue visitBUILD_PAIR(SDNode *N);
249 SDValue visitFADD(SDNode *N);
250 SDValue visitFSUB(SDNode *N);
251 SDValue visitFMUL(SDNode *N);
252 SDValue visitFMA(SDNode *N);
253 SDValue visitFDIV(SDNode *N);
254 SDValue visitFREM(SDNode *N);
255 SDValue visitFCOPYSIGN(SDNode *N);
256 SDValue visitSINT_TO_FP(SDNode *N);
257 SDValue visitUINT_TO_FP(SDNode *N);
258 SDValue visitFP_TO_SINT(SDNode *N);
259 SDValue visitFP_TO_UINT(SDNode *N);
260 SDValue visitFP_ROUND(SDNode *N);
261 SDValue visitFP_ROUND_INREG(SDNode *N);
262 SDValue visitFP_EXTEND(SDNode *N);
263 SDValue visitFNEG(SDNode *N);
264 SDValue visitFABS(SDNode *N);
265 SDValue visitFCEIL(SDNode *N);
266 SDValue visitFTRUNC(SDNode *N);
267 SDValue visitFFLOOR(SDNode *N);
268 SDValue visitBRCOND(SDNode *N);
269 SDValue visitBR_CC(SDNode *N);
270 SDValue visitLOAD(SDNode *N);
271 SDValue visitSTORE(SDNode *N);
272 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
273 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
274 SDValue visitBUILD_VECTOR(SDNode *N);
275 SDValue visitCONCAT_VECTORS(SDNode *N);
276 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
277 SDValue visitVECTOR_SHUFFLE(SDNode *N);
278 SDValue visitINSERT_SUBVECTOR(SDNode *N);
280 SDValue XformToShuffleWithZero(SDNode *N);
281 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
283 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
285 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
286 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
287 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
288 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
289 SDValue N3, ISD::CondCode CC,
290 bool NotExtCompare = false);
291 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
292 SDLoc DL, bool foldBooleans = true);
293 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
295 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
296 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
297 SDValue BuildSDIV(SDNode *N);
298 SDValue BuildUDIV(SDNode *N);
299 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
300 bool DemandHighBits = true);
301 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
302 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
303 SDValue InnerPos, SDValue InnerNeg,
304 unsigned PosOpcode, unsigned NegOpcode,
306 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
307 SDValue ReduceLoadWidth(SDNode *N);
308 SDValue ReduceLoadOpStoreWidth(SDNode *N);
309 SDValue TransformFPLoadStorePair(SDNode *N);
310 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
311 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
313 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
315 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
316 /// looking for aliasing nodes and adding them to the Aliases vector.
317 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
318 SmallVectorImpl<SDValue> &Aliases);
320 /// isAlias - Return true if there is any possibility that the two addresses
322 bool isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
323 const Value *SrcValue1, int SrcValueOffset1,
324 unsigned SrcValueAlign1,
325 const MDNode *TBAAInfo1,
326 SDValue Ptr2, int64_t Size2, bool IsVolatile2,
327 const Value *SrcValue2, int SrcValueOffset2,
328 unsigned SrcValueAlign2,
329 const MDNode *TBAAInfo2) const;
331 /// isAlias - Return true if there is any possibility that the two addresses
333 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1);
335 /// FindAliasInfo - Extracts the relevant alias information from the memory
336 /// node. Returns true if the operand was a load.
337 bool FindAliasInfo(SDNode *N,
338 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
339 const Value *&SrcValue, int &SrcValueOffset,
340 unsigned &SrcValueAlignment,
341 const MDNode *&TBAAInfo) const;
343 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
344 /// looking for a better chain (aliasing node.)
345 SDValue FindBetterChain(SDNode *N, SDValue Chain);
347 /// Merge consecutive store operations into a wide store.
348 /// This optimization uses wide integers or vectors when possible.
349 /// \return True if some memory operations were changed.
350 bool MergeConsecutiveStores(StoreSDNode *N);
352 /// \brief Try to transform a truncation where C is a constant:
353 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
355 /// \p N needs to be a truncation and its first operand an AND. Other
356 /// requirements are checked by the function (e.g. that trunc is
357 /// single-use) and if missed an empty SDValue is returned.
358 SDValue distributeTruncateThroughAnd(SDNode *N);
361 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
362 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
363 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
364 AttributeSet FnAttrs =
365 DAG.getMachineFunction().getFunction()->getAttributes();
367 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
368 Attribute::OptimizeForSize) ||
369 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
372 /// Run - runs the dag combiner on all nodes in the work list
373 void Run(CombineLevel AtLevel);
375 SelectionDAG &getDAG() const { return DAG; }
377 /// getShiftAmountTy - Returns a type large enough to hold any valid
378 /// shift amount - before type legalization these can be huge.
379 EVT getShiftAmountTy(EVT LHSTy) {
380 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
381 if (LHSTy.isVector())
383 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
384 : TLI.getPointerTy();
387 /// isTypeLegal - This method returns true if we are running before type
388 /// legalization or if the specified VT is legal.
389 bool isTypeLegal(const EVT &VT) {
390 if (!LegalTypes) return true;
391 return TLI.isTypeLegal(VT);
394 /// getSetCCResultType - Convenience wrapper around
395 /// TargetLowering::getSetCCResultType
396 EVT getSetCCResultType(EVT VT) const {
397 return TLI.getSetCCResultType(*DAG.getContext(), VT);
404 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
405 /// nodes from the worklist.
406 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
409 explicit WorkListRemover(DAGCombiner &dc)
410 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
412 void NodeDeleted(SDNode *N, SDNode *E) override {
413 DC.removeFromWorkList(N);
418 //===----------------------------------------------------------------------===//
419 // TargetLowering::DAGCombinerInfo implementation
420 //===----------------------------------------------------------------------===//
422 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
423 ((DAGCombiner*)DC)->AddToWorkList(N);
426 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
427 ((DAGCombiner*)DC)->removeFromWorkList(N);
430 SDValue TargetLowering::DAGCombinerInfo::
431 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
432 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
435 SDValue TargetLowering::DAGCombinerInfo::
436 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
437 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
441 SDValue TargetLowering::DAGCombinerInfo::
442 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
443 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
446 void TargetLowering::DAGCombinerInfo::
447 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
448 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
451 //===----------------------------------------------------------------------===//
453 //===----------------------------------------------------------------------===//
455 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
456 /// specified expression for the same cost as the expression itself, or 2 if we
457 /// can compute the negated form more cheaply than the expression itself.
458 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
459 const TargetLowering &TLI,
460 const TargetOptions *Options,
461 unsigned Depth = 0) {
462 // fneg is removable even if it has multiple uses.
463 if (Op.getOpcode() == ISD::FNEG) return 2;
465 // Don't allow anything with multiple uses.
466 if (!Op.hasOneUse()) return 0;
468 // Don't recurse exponentially.
469 if (Depth > 6) return 0;
471 switch (Op.getOpcode()) {
472 default: return false;
473 case ISD::ConstantFP:
474 // Don't invert constant FP values after legalize. The negated constant
475 // isn't necessarily legal.
476 return LegalOperations ? 0 : 1;
478 // FIXME: determine better conditions for this xform.
479 if (!Options->UnsafeFPMath) return 0;
481 // After operation legalization, it might not be legal to create new FSUBs.
482 if (LegalOperations &&
483 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
486 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
487 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
490 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
491 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
494 // We can't turn -(A-B) into B-A when we honor signed zeros.
495 if (!Options->UnsafeFPMath) return 0;
497 // fold (fneg (fsub A, B)) -> (fsub B, A)
502 if (Options->HonorSignDependentRoundingFPMath()) return 0;
504 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
505 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
509 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
515 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
520 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
521 /// returns the newly negated expression.
522 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
523 bool LegalOperations, unsigned Depth = 0) {
524 // fneg is removable even if it has multiple uses.
525 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
527 // Don't allow anything with multiple uses.
528 assert(Op.hasOneUse() && "Unknown reuse!");
530 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
531 switch (Op.getOpcode()) {
532 default: llvm_unreachable("Unknown code");
533 case ISD::ConstantFP: {
534 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
536 return DAG.getConstantFP(V, Op.getValueType());
539 // FIXME: determine better conditions for this xform.
540 assert(DAG.getTarget().Options.UnsafeFPMath);
542 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
543 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
544 DAG.getTargetLoweringInfo(),
545 &DAG.getTarget().Options, Depth+1))
546 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
547 GetNegatedExpression(Op.getOperand(0), DAG,
548 LegalOperations, Depth+1),
550 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
551 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
552 GetNegatedExpression(Op.getOperand(1), DAG,
553 LegalOperations, Depth+1),
556 // We can't turn -(A-B) into B-A when we honor signed zeros.
557 assert(DAG.getTarget().Options.UnsafeFPMath);
559 // fold (fneg (fsub 0, B)) -> B
560 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
561 if (N0CFP->getValueAPF().isZero())
562 return Op.getOperand(1);
564 // fold (fneg (fsub A, B)) -> (fsub B, A)
565 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
566 Op.getOperand(1), Op.getOperand(0));
570 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
572 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
573 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
574 DAG.getTargetLoweringInfo(),
575 &DAG.getTarget().Options, Depth+1))
576 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
577 GetNegatedExpression(Op.getOperand(0), DAG,
578 LegalOperations, Depth+1),
581 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
582 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
584 GetNegatedExpression(Op.getOperand(1), DAG,
585 LegalOperations, Depth+1));
589 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
590 GetNegatedExpression(Op.getOperand(0), DAG,
591 LegalOperations, Depth+1));
593 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
594 GetNegatedExpression(Op.getOperand(0), DAG,
595 LegalOperations, Depth+1),
601 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
602 // that selects between the values 1 and 0, making it equivalent to a setcc.
603 // Also, set the incoming LHS, RHS, and CC references to the appropriate
604 // nodes based on the type of node we are checking. This simplifies life a
605 // bit for the callers.
606 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
608 if (N.getOpcode() == ISD::SETCC) {
609 LHS = N.getOperand(0);
610 RHS = N.getOperand(1);
611 CC = N.getOperand(2);
614 if (N.getOpcode() == ISD::SELECT_CC &&
615 N.getOperand(2).getOpcode() == ISD::Constant &&
616 N.getOperand(3).getOpcode() == ISD::Constant &&
617 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
618 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
619 LHS = N.getOperand(0);
620 RHS = N.getOperand(1);
621 CC = N.getOperand(4);
627 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
628 // one use. If this is true, it allows the users to invert the operation for
629 // free when it is profitable to do so.
630 static bool isOneUseSetCC(SDValue N) {
632 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
637 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
638 /// elements are all the same constant or undefined.
639 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
640 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
645 unsigned SplatBitSize;
647 EVT EltVT = N->getValueType(0).getVectorElementType();
648 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
650 EltVT.getSizeInBits() >= SplatBitSize);
653 // \brief Returns the SDNode if it is a constant BuildVector or constant.
654 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
655 if (isa<ConstantSDNode>(N))
657 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
658 if(BV && BV->isConstant())
663 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
665 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
666 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
669 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N))
670 return BV->getConstantSplatValue();
675 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
676 SDValue N0, SDValue N1) {
677 EVT VT = N0.getValueType();
678 if (N0.getOpcode() == Opc) {
679 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
680 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
681 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
682 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
683 if (!OpNode.getNode())
685 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
687 if (N0.hasOneUse()) {
688 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
690 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
691 if (!OpNode.getNode())
693 AddToWorkList(OpNode.getNode());
694 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
699 if (N1.getOpcode() == Opc) {
700 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
701 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
702 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
703 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
704 if (!OpNode.getNode())
706 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
708 if (N1.hasOneUse()) {
709 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
711 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
712 if (!OpNode.getNode())
714 AddToWorkList(OpNode.getNode());
715 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
723 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
725 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
727 DEBUG(dbgs() << "\nReplacing.1 ";
729 dbgs() << "\nWith: ";
730 To[0].getNode()->dump(&DAG);
731 dbgs() << " and " << NumTo-1 << " other values\n";
732 for (unsigned i = 0, e = NumTo; i != e; ++i)
733 assert((!To[i].getNode() ||
734 N->getValueType(i) == To[i].getValueType()) &&
735 "Cannot combine value to value of different type!"));
736 WorkListRemover DeadNodes(*this);
737 DAG.ReplaceAllUsesWith(N, To);
739 // Push the new nodes and any users onto the worklist
740 for (unsigned i = 0, e = NumTo; i != e; ++i) {
741 if (To[i].getNode()) {
742 AddToWorkList(To[i].getNode());
743 AddUsersToWorkList(To[i].getNode());
748 // Finally, if the node is now dead, remove it from the graph. The node
749 // may not be dead if the replacement process recursively simplified to
750 // something else needing this node.
751 if (N->use_empty()) {
752 // Nodes can be reintroduced into the worklist. Make sure we do not
753 // process a node that has been replaced.
754 removeFromWorkList(N);
756 // Finally, since the node is now dead, remove it from the graph.
759 return SDValue(N, 0);
763 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
764 // Replace all uses. If any nodes become isomorphic to other nodes and
765 // are deleted, make sure to remove them from our worklist.
766 WorkListRemover DeadNodes(*this);
767 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
769 // Push the new node and any (possibly new) users onto the worklist.
770 AddToWorkList(TLO.New.getNode());
771 AddUsersToWorkList(TLO.New.getNode());
773 // Finally, if the node is now dead, remove it from the graph. The node
774 // may not be dead if the replacement process recursively simplified to
775 // something else needing this node.
776 if (TLO.Old.getNode()->use_empty()) {
777 removeFromWorkList(TLO.Old.getNode());
779 // If the operands of this node are only used by the node, they will now
780 // be dead. Make sure to visit them first to delete dead nodes early.
781 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
782 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
783 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
785 DAG.DeleteNode(TLO.Old.getNode());
789 /// SimplifyDemandedBits - Check the specified integer node value to see if
790 /// it can be simplified or if things it uses can be simplified by bit
791 /// propagation. If so, return true.
792 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
793 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
794 APInt KnownZero, KnownOne;
795 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
799 AddToWorkList(Op.getNode());
801 // Replace the old value with the new one.
803 DEBUG(dbgs() << "\nReplacing.2 ";
804 TLO.Old.getNode()->dump(&DAG);
805 dbgs() << "\nWith: ";
806 TLO.New.getNode()->dump(&DAG);
809 CommitTargetLoweringOpt(TLO);
813 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
815 EVT VT = Load->getValueType(0);
816 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
818 DEBUG(dbgs() << "\nReplacing.9 ";
820 dbgs() << "\nWith: ";
821 Trunc.getNode()->dump(&DAG);
823 WorkListRemover DeadNodes(*this);
824 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
825 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
826 removeFromWorkList(Load);
827 DAG.DeleteNode(Load);
828 AddToWorkList(Trunc.getNode());
831 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
834 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
835 EVT MemVT = LD->getMemoryVT();
836 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
837 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
839 : LD->getExtensionType();
841 return DAG.getExtLoad(ExtType, dl, PVT,
842 LD->getChain(), LD->getBasePtr(),
843 MemVT, LD->getMemOperand());
846 unsigned Opc = Op.getOpcode();
849 case ISD::AssertSext:
850 return DAG.getNode(ISD::AssertSext, dl, PVT,
851 SExtPromoteOperand(Op.getOperand(0), PVT),
853 case ISD::AssertZext:
854 return DAG.getNode(ISD::AssertZext, dl, PVT,
855 ZExtPromoteOperand(Op.getOperand(0), PVT),
857 case ISD::Constant: {
859 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
860 return DAG.getNode(ExtOpc, dl, PVT, Op);
864 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
866 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
869 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
870 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
872 EVT OldVT = Op.getValueType();
874 bool Replace = false;
875 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
876 if (NewOp.getNode() == 0)
878 AddToWorkList(NewOp.getNode());
881 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
882 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
883 DAG.getValueType(OldVT));
886 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
887 EVT OldVT = Op.getValueType();
889 bool Replace = false;
890 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
891 if (NewOp.getNode() == 0)
893 AddToWorkList(NewOp.getNode());
896 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
897 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
900 /// PromoteIntBinOp - Promote the specified integer binary operation if the
901 /// target indicates it is beneficial. e.g. On x86, it's usually better to
902 /// promote i16 operations to i32 since i16 instructions are longer.
903 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
904 if (!LegalOperations)
907 EVT VT = Op.getValueType();
908 if (VT.isVector() || !VT.isInteger())
911 // If operation type is 'undesirable', e.g. i16 on x86, consider
913 unsigned Opc = Op.getOpcode();
914 if (TLI.isTypeDesirableForOp(Opc, VT))
918 // Consult target whether it is a good idea to promote this operation and
919 // what's the right type to promote it to.
920 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
921 assert(PVT != VT && "Don't know what type to promote to!");
923 bool Replace0 = false;
924 SDValue N0 = Op.getOperand(0);
925 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
926 if (NN0.getNode() == 0)
929 bool Replace1 = false;
930 SDValue N1 = Op.getOperand(1);
935 NN1 = PromoteOperand(N1, PVT, Replace1);
936 if (NN1.getNode() == 0)
940 AddToWorkList(NN0.getNode());
942 AddToWorkList(NN1.getNode());
945 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
947 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
949 DEBUG(dbgs() << "\nPromoting ";
950 Op.getNode()->dump(&DAG));
952 return DAG.getNode(ISD::TRUNCATE, dl, VT,
953 DAG.getNode(Opc, dl, PVT, NN0, NN1));
958 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
959 /// target indicates it is beneficial. e.g. On x86, it's usually better to
960 /// promote i16 operations to i32 since i16 instructions are longer.
961 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
962 if (!LegalOperations)
965 EVT VT = Op.getValueType();
966 if (VT.isVector() || !VT.isInteger())
969 // If operation type is 'undesirable', e.g. i16 on x86, consider
971 unsigned Opc = Op.getOpcode();
972 if (TLI.isTypeDesirableForOp(Opc, VT))
976 // Consult target whether it is a good idea to promote this operation and
977 // what's the right type to promote it to.
978 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
979 assert(PVT != VT && "Don't know what type to promote to!");
981 bool Replace = false;
982 SDValue N0 = Op.getOperand(0);
984 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
985 else if (Opc == ISD::SRL)
986 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
988 N0 = PromoteOperand(N0, PVT, Replace);
989 if (N0.getNode() == 0)
992 AddToWorkList(N0.getNode());
994 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
996 DEBUG(dbgs() << "\nPromoting ";
997 Op.getNode()->dump(&DAG));
999 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1000 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1005 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1006 if (!LegalOperations)
1009 EVT VT = Op.getValueType();
1010 if (VT.isVector() || !VT.isInteger())
1013 // If operation type is 'undesirable', e.g. i16 on x86, consider
1015 unsigned Opc = Op.getOpcode();
1016 if (TLI.isTypeDesirableForOp(Opc, VT))
1020 // Consult target whether it is a good idea to promote this operation and
1021 // what's the right type to promote it to.
1022 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1023 assert(PVT != VT && "Don't know what type to promote to!");
1024 // fold (aext (aext x)) -> (aext x)
1025 // fold (aext (zext x)) -> (zext x)
1026 // fold (aext (sext x)) -> (sext x)
1027 DEBUG(dbgs() << "\nPromoting ";
1028 Op.getNode()->dump(&DAG));
1029 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1034 bool DAGCombiner::PromoteLoad(SDValue Op) {
1035 if (!LegalOperations)
1038 EVT VT = Op.getValueType();
1039 if (VT.isVector() || !VT.isInteger())
1042 // If operation type is 'undesirable', e.g. i16 on x86, consider
1044 unsigned Opc = Op.getOpcode();
1045 if (TLI.isTypeDesirableForOp(Opc, VT))
1049 // Consult target whether it is a good idea to promote this operation and
1050 // what's the right type to promote it to.
1051 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1052 assert(PVT != VT && "Don't know what type to promote to!");
1055 SDNode *N = Op.getNode();
1056 LoadSDNode *LD = cast<LoadSDNode>(N);
1057 EVT MemVT = LD->getMemoryVT();
1058 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1059 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1061 : LD->getExtensionType();
1062 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1063 LD->getChain(), LD->getBasePtr(),
1064 MemVT, LD->getMemOperand());
1065 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1067 DEBUG(dbgs() << "\nPromoting ";
1070 Result.getNode()->dump(&DAG);
1072 WorkListRemover DeadNodes(*this);
1073 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1074 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1075 removeFromWorkList(N);
1077 AddToWorkList(Result.getNode());
1084 //===----------------------------------------------------------------------===//
1085 // Main DAG Combiner implementation
1086 //===----------------------------------------------------------------------===//
1088 void DAGCombiner::Run(CombineLevel AtLevel) {
1089 // set the instance variables, so that the various visit routines may use it.
1091 LegalOperations = Level >= AfterLegalizeVectorOps;
1092 LegalTypes = Level >= AfterLegalizeTypes;
1094 // Add all the dag nodes to the worklist.
1095 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1096 E = DAG.allnodes_end(); I != E; ++I)
1099 // Create a dummy node (which is not added to allnodes), that adds a reference
1100 // to the root node, preventing it from being deleted, and tracking any
1101 // changes of the root.
1102 HandleSDNode Dummy(DAG.getRoot());
1104 // The root of the dag may dangle to deleted nodes until the dag combiner is
1105 // done. Set it to null to avoid confusion.
1106 DAG.setRoot(SDValue());
1108 // while the worklist isn't empty, find a node and
1109 // try and combine it.
1110 while (!WorkListContents.empty()) {
1112 // The WorkListOrder holds the SDNodes in order, but it may contain
1114 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1115 // worklist *should* contain, and check the node we want to visit is should
1116 // actually be visited.
1118 N = WorkListOrder.pop_back_val();
1119 } while (!WorkListContents.erase(N));
1121 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1122 // N is deleted from the DAG, since they too may now be dead or may have a
1123 // reduced number of uses, allowing other xforms.
1124 if (N->use_empty() && N != &Dummy) {
1125 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1126 AddToWorkList(N->getOperand(i).getNode());
1132 SDValue RV = combine(N);
1134 if (RV.getNode() == 0)
1139 // If we get back the same node we passed in, rather than a new node or
1140 // zero, we know that the node must have defined multiple values and
1141 // CombineTo was used. Since CombineTo takes care of the worklist
1142 // mechanics for us, we have no work to do in this case.
1143 if (RV.getNode() == N)
1146 assert(N->getOpcode() != ISD::DELETED_NODE &&
1147 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1148 "Node was deleted but visit returned new node!");
1150 DEBUG(dbgs() << "\nReplacing.3 ";
1152 dbgs() << "\nWith: ";
1153 RV.getNode()->dump(&DAG);
1156 // Transfer debug value.
1157 DAG.TransferDbgValues(SDValue(N, 0), RV);
1158 WorkListRemover DeadNodes(*this);
1159 if (N->getNumValues() == RV.getNode()->getNumValues())
1160 DAG.ReplaceAllUsesWith(N, RV.getNode());
1162 assert(N->getValueType(0) == RV.getValueType() &&
1163 N->getNumValues() == 1 && "Type mismatch");
1165 DAG.ReplaceAllUsesWith(N, &OpV);
1168 // Push the new node and any users onto the worklist
1169 AddToWorkList(RV.getNode());
1170 AddUsersToWorkList(RV.getNode());
1172 // Add any uses of the old node to the worklist in case this node is the
1173 // last one that uses them. They may become dead after this node is
1175 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1176 AddToWorkList(N->getOperand(i).getNode());
1178 // Finally, if the node is now dead, remove it from the graph. The node
1179 // may not be dead if the replacement process recursively simplified to
1180 // something else needing this node.
1181 if (N->use_empty()) {
1182 // Nodes can be reintroduced into the worklist. Make sure we do not
1183 // process a node that has been replaced.
1184 removeFromWorkList(N);
1186 // Finally, since the node is now dead, remove it from the graph.
1191 // If the root changed (e.g. it was a dead load, update the root).
1192 DAG.setRoot(Dummy.getValue());
1193 DAG.RemoveDeadNodes();
1196 SDValue DAGCombiner::visit(SDNode *N) {
1197 switch (N->getOpcode()) {
1199 case ISD::TokenFactor: return visitTokenFactor(N);
1200 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1201 case ISD::ADD: return visitADD(N);
1202 case ISD::SUB: return visitSUB(N);
1203 case ISD::ADDC: return visitADDC(N);
1204 case ISD::SUBC: return visitSUBC(N);
1205 case ISD::ADDE: return visitADDE(N);
1206 case ISD::SUBE: return visitSUBE(N);
1207 case ISD::MUL: return visitMUL(N);
1208 case ISD::SDIV: return visitSDIV(N);
1209 case ISD::UDIV: return visitUDIV(N);
1210 case ISD::SREM: return visitSREM(N);
1211 case ISD::UREM: return visitUREM(N);
1212 case ISD::MULHU: return visitMULHU(N);
1213 case ISD::MULHS: return visitMULHS(N);
1214 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1215 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1216 case ISD::SMULO: return visitSMULO(N);
1217 case ISD::UMULO: return visitUMULO(N);
1218 case ISD::SDIVREM: return visitSDIVREM(N);
1219 case ISD::UDIVREM: return visitUDIVREM(N);
1220 case ISD::AND: return visitAND(N);
1221 case ISD::OR: return visitOR(N);
1222 case ISD::XOR: return visitXOR(N);
1223 case ISD::SHL: return visitSHL(N);
1224 case ISD::SRA: return visitSRA(N);
1225 case ISD::SRL: return visitSRL(N);
1227 case ISD::ROTL: return visitRotate(N);
1228 case ISD::CTLZ: return visitCTLZ(N);
1229 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1230 case ISD::CTTZ: return visitCTTZ(N);
1231 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1232 case ISD::CTPOP: return visitCTPOP(N);
1233 case ISD::SELECT: return visitSELECT(N);
1234 case ISD::VSELECT: return visitVSELECT(N);
1235 case ISD::SELECT_CC: return visitSELECT_CC(N);
1236 case ISD::SETCC: return visitSETCC(N);
1237 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1238 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1239 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1240 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1241 case ISD::TRUNCATE: return visitTRUNCATE(N);
1242 case ISD::BITCAST: return visitBITCAST(N);
1243 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1244 case ISD::FADD: return visitFADD(N);
1245 case ISD::FSUB: return visitFSUB(N);
1246 case ISD::FMUL: return visitFMUL(N);
1247 case ISD::FMA: return visitFMA(N);
1248 case ISD::FDIV: return visitFDIV(N);
1249 case ISD::FREM: return visitFREM(N);
1250 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1251 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1252 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1253 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1254 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1255 case ISD::FP_ROUND: return visitFP_ROUND(N);
1256 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1257 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1258 case ISD::FNEG: return visitFNEG(N);
1259 case ISD::FABS: return visitFABS(N);
1260 case ISD::FFLOOR: return visitFFLOOR(N);
1261 case ISD::FCEIL: return visitFCEIL(N);
1262 case ISD::FTRUNC: return visitFTRUNC(N);
1263 case ISD::BRCOND: return visitBRCOND(N);
1264 case ISD::BR_CC: return visitBR_CC(N);
1265 case ISD::LOAD: return visitLOAD(N);
1266 case ISD::STORE: return visitSTORE(N);
1267 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1268 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1269 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1270 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1271 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1272 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1273 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1278 SDValue DAGCombiner::combine(SDNode *N) {
1279 SDValue RV = visit(N);
1281 // If nothing happened, try a target-specific DAG combine.
1282 if (RV.getNode() == 0) {
1283 assert(N->getOpcode() != ISD::DELETED_NODE &&
1284 "Node was deleted but visit returned NULL!");
1286 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1287 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1289 // Expose the DAG combiner to the target combiner impls.
1290 TargetLowering::DAGCombinerInfo
1291 DagCombineInfo(DAG, Level, false, this);
1293 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1297 // If nothing happened still, try promoting the operation.
1298 if (RV.getNode() == 0) {
1299 switch (N->getOpcode()) {
1307 RV = PromoteIntBinOp(SDValue(N, 0));
1312 RV = PromoteIntShiftOp(SDValue(N, 0));
1314 case ISD::SIGN_EXTEND:
1315 case ISD::ZERO_EXTEND:
1316 case ISD::ANY_EXTEND:
1317 RV = PromoteExtend(SDValue(N, 0));
1320 if (PromoteLoad(SDValue(N, 0)))
1326 // If N is a commutative binary node, try commuting it to enable more
1328 if (RV.getNode() == 0 &&
1329 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1330 N->getNumValues() == 1) {
1331 SDValue N0 = N->getOperand(0);
1332 SDValue N1 = N->getOperand(1);
1334 // Constant operands are canonicalized to RHS.
1335 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1336 SDValue Ops[] = { N1, N0 };
1337 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1340 return SDValue(CSENode, 0);
1347 /// getInputChainForNode - Given a node, return its input chain if it has one,
1348 /// otherwise return a null sd operand.
1349 static SDValue getInputChainForNode(SDNode *N) {
1350 if (unsigned NumOps = N->getNumOperands()) {
1351 if (N->getOperand(0).getValueType() == MVT::Other)
1352 return N->getOperand(0);
1353 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1354 return N->getOperand(NumOps-1);
1355 for (unsigned i = 1; i < NumOps-1; ++i)
1356 if (N->getOperand(i).getValueType() == MVT::Other)
1357 return N->getOperand(i);
1362 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1363 // If N has two operands, where one has an input chain equal to the other,
1364 // the 'other' chain is redundant.
1365 if (N->getNumOperands() == 2) {
1366 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1367 return N->getOperand(0);
1368 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1369 return N->getOperand(1);
1372 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1373 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1374 SmallPtrSet<SDNode*, 16> SeenOps;
1375 bool Changed = false; // If we should replace this token factor.
1377 // Start out with this token factor.
1380 // Iterate through token factors. The TFs grows when new token factors are
1382 for (unsigned i = 0; i < TFs.size(); ++i) {
1383 SDNode *TF = TFs[i];
1385 // Check each of the operands.
1386 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1387 SDValue Op = TF->getOperand(i);
1389 switch (Op.getOpcode()) {
1390 case ISD::EntryToken:
1391 // Entry tokens don't need to be added to the list. They are
1396 case ISD::TokenFactor:
1397 if (Op.hasOneUse() &&
1398 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1399 // Queue up for processing.
1400 TFs.push_back(Op.getNode());
1401 // Clean up in case the token factor is removed.
1402 AddToWorkList(Op.getNode());
1409 // Only add if it isn't already in the list.
1410 if (SeenOps.insert(Op.getNode()))
1421 // If we've change things around then replace token factor.
1424 // The entry token is the only possible outcome.
1425 Result = DAG.getEntryNode();
1427 // New and improved token factor.
1428 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
1429 MVT::Other, &Ops[0], Ops.size());
1432 // Don't add users to work list.
1433 return CombineTo(N, Result, false);
1439 /// MERGE_VALUES can always be eliminated.
1440 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1441 WorkListRemover DeadNodes(*this);
1442 // Replacing results may cause a different MERGE_VALUES to suddenly
1443 // be CSE'd with N, and carry its uses with it. Iterate until no
1444 // uses remain, to ensure that the node can be safely deleted.
1445 // First add the users of this node to the work list so that they
1446 // can be tried again once they have new operands.
1447 AddUsersToWorkList(N);
1449 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1450 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1451 } while (!N->use_empty());
1452 removeFromWorkList(N);
1454 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1458 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1459 SelectionDAG &DAG) {
1460 EVT VT = N0.getValueType();
1461 SDValue N00 = N0.getOperand(0);
1462 SDValue N01 = N0.getOperand(1);
1463 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1465 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1466 isa<ConstantSDNode>(N00.getOperand(1))) {
1467 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1468 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1469 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1470 N00.getOperand(0), N01),
1471 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1472 N00.getOperand(1), N01));
1473 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1479 SDValue DAGCombiner::visitADD(SDNode *N) {
1480 SDValue N0 = N->getOperand(0);
1481 SDValue N1 = N->getOperand(1);
1482 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1483 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1484 EVT VT = N0.getValueType();
1487 if (VT.isVector()) {
1488 SDValue FoldedVOp = SimplifyVBinOp(N);
1489 if (FoldedVOp.getNode()) return FoldedVOp;
1491 // fold (add x, 0) -> x, vector edition
1492 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1494 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1498 // fold (add x, undef) -> undef
1499 if (N0.getOpcode() == ISD::UNDEF)
1501 if (N1.getOpcode() == ISD::UNDEF)
1503 // fold (add c1, c2) -> c1+c2
1505 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1506 // canonicalize constant to RHS
1508 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1509 // fold (add x, 0) -> x
1510 if (N1C && N1C->isNullValue())
1512 // fold (add Sym, c) -> Sym+c
1513 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1514 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1515 GA->getOpcode() == ISD::GlobalAddress)
1516 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1518 (uint64_t)N1C->getSExtValue());
1519 // fold ((c1-A)+c2) -> (c1+c2)-A
1520 if (N1C && N0.getOpcode() == ISD::SUB)
1521 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1522 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1523 DAG.getConstant(N1C->getAPIntValue()+
1524 N0C->getAPIntValue(), VT),
1527 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1528 if (RADD.getNode() != 0)
1530 // fold ((0-A) + B) -> B-A
1531 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1532 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1533 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1534 // fold (A + (0-B)) -> A-B
1535 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1536 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1537 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1538 // fold (A+(B-A)) -> B
1539 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1540 return N1.getOperand(0);
1541 // fold ((B-A)+A) -> B
1542 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1543 return N0.getOperand(0);
1544 // fold (A+(B-(A+C))) to (B-C)
1545 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1546 N0 == N1.getOperand(1).getOperand(0))
1547 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1548 N1.getOperand(1).getOperand(1));
1549 // fold (A+(B-(C+A))) to (B-C)
1550 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1551 N0 == N1.getOperand(1).getOperand(1))
1552 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1553 N1.getOperand(1).getOperand(0));
1554 // fold (A+((B-A)+or-C)) to (B+or-C)
1555 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1556 N1.getOperand(0).getOpcode() == ISD::SUB &&
1557 N0 == N1.getOperand(0).getOperand(1))
1558 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1559 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1561 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1562 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1563 SDValue N00 = N0.getOperand(0);
1564 SDValue N01 = N0.getOperand(1);
1565 SDValue N10 = N1.getOperand(0);
1566 SDValue N11 = N1.getOperand(1);
1568 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1569 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1570 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1571 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1574 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1575 return SDValue(N, 0);
1577 // fold (a+b) -> (a|b) iff a and b share no bits.
1578 if (VT.isInteger() && !VT.isVector()) {
1579 APInt LHSZero, LHSOne;
1580 APInt RHSZero, RHSOne;
1581 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1583 if (LHSZero.getBoolValue()) {
1584 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1586 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1587 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1588 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1589 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1590 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1595 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1596 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1597 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1598 if (Result.getNode()) return Result;
1600 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1601 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1602 if (Result.getNode()) return Result;
1605 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1606 if (N1.getOpcode() == ISD::SHL &&
1607 N1.getOperand(0).getOpcode() == ISD::SUB)
1608 if (ConstantSDNode *C =
1609 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1610 if (C->getAPIntValue() == 0)
1611 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1612 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1613 N1.getOperand(0).getOperand(1),
1615 if (N0.getOpcode() == ISD::SHL &&
1616 N0.getOperand(0).getOpcode() == ISD::SUB)
1617 if (ConstantSDNode *C =
1618 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1619 if (C->getAPIntValue() == 0)
1620 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1621 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1622 N0.getOperand(0).getOperand(1),
1625 if (N1.getOpcode() == ISD::AND) {
1626 SDValue AndOp0 = N1.getOperand(0);
1627 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1628 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1629 unsigned DestBits = VT.getScalarType().getSizeInBits();
1631 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1632 // and similar xforms where the inner op is either ~0 or 0.
1633 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1635 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1639 // add (sext i1), X -> sub X, (zext i1)
1640 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1641 N0.getOperand(0).getValueType() == MVT::i1 &&
1642 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1644 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1645 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1651 SDValue DAGCombiner::visitADDC(SDNode *N) {
1652 SDValue N0 = N->getOperand(0);
1653 SDValue N1 = N->getOperand(1);
1654 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1655 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1656 EVT VT = N0.getValueType();
1658 // If the flag result is dead, turn this into an ADD.
1659 if (!N->hasAnyUseOfValue(1))
1660 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1661 DAG.getNode(ISD::CARRY_FALSE,
1662 SDLoc(N), MVT::Glue));
1664 // canonicalize constant to RHS.
1666 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1668 // fold (addc x, 0) -> x + no carry out
1669 if (N1C && N1C->isNullValue())
1670 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1671 SDLoc(N), MVT::Glue));
1673 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1674 APInt LHSZero, LHSOne;
1675 APInt RHSZero, RHSOne;
1676 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1678 if (LHSZero.getBoolValue()) {
1679 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1681 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1682 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1683 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1684 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1685 DAG.getNode(ISD::CARRY_FALSE,
1686 SDLoc(N), MVT::Glue));
1692 SDValue DAGCombiner::visitADDE(SDNode *N) {
1693 SDValue N0 = N->getOperand(0);
1694 SDValue N1 = N->getOperand(1);
1695 SDValue CarryIn = N->getOperand(2);
1696 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1697 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1699 // canonicalize constant to RHS
1701 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1704 // fold (adde x, y, false) -> (addc x, y)
1705 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1706 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1711 // Since it may not be valid to emit a fold to zero for vector initializers
1712 // check if we can before folding.
1713 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1715 bool LegalOperations, bool LegalTypes) {
1717 return DAG.getConstant(0, VT);
1718 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1719 return DAG.getConstant(0, VT);
1723 SDValue DAGCombiner::visitSUB(SDNode *N) {
1724 SDValue N0 = N->getOperand(0);
1725 SDValue N1 = N->getOperand(1);
1726 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1727 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1728 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1729 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1730 EVT VT = N0.getValueType();
1733 if (VT.isVector()) {
1734 SDValue FoldedVOp = SimplifyVBinOp(N);
1735 if (FoldedVOp.getNode()) return FoldedVOp;
1737 // fold (sub x, 0) -> x, vector edition
1738 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1742 // fold (sub x, x) -> 0
1743 // FIXME: Refactor this and xor and other similar operations together.
1745 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1746 // fold (sub c1, c2) -> c1-c2
1748 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1749 // fold (sub x, c) -> (add x, -c)
1751 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1752 DAG.getConstant(-N1C->getAPIntValue(), VT));
1753 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1754 if (N0C && N0C->isAllOnesValue())
1755 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1756 // fold A-(A-B) -> B
1757 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1758 return N1.getOperand(1);
1759 // fold (A+B)-A -> B
1760 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1761 return N0.getOperand(1);
1762 // fold (A+B)-B -> A
1763 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1764 return N0.getOperand(0);
1765 // fold C2-(A+C1) -> (C2-C1)-A
1766 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1767 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1769 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1772 // fold ((A+(B+or-C))-B) -> A+or-C
1773 if (N0.getOpcode() == ISD::ADD &&
1774 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1775 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1776 N0.getOperand(1).getOperand(0) == N1)
1777 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1778 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1779 // fold ((A+(C+B))-B) -> A+C
1780 if (N0.getOpcode() == ISD::ADD &&
1781 N0.getOperand(1).getOpcode() == ISD::ADD &&
1782 N0.getOperand(1).getOperand(1) == N1)
1783 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1784 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1785 // fold ((A-(B-C))-C) -> A-B
1786 if (N0.getOpcode() == ISD::SUB &&
1787 N0.getOperand(1).getOpcode() == ISD::SUB &&
1788 N0.getOperand(1).getOperand(1) == N1)
1789 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1790 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1792 // If either operand of a sub is undef, the result is undef
1793 if (N0.getOpcode() == ISD::UNDEF)
1795 if (N1.getOpcode() == ISD::UNDEF)
1798 // If the relocation model supports it, consider symbol offsets.
1799 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1800 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1801 // fold (sub Sym, c) -> Sym-c
1802 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1803 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1805 (uint64_t)N1C->getSExtValue());
1806 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1807 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1808 if (GA->getGlobal() == GB->getGlobal())
1809 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1816 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1817 SDValue N0 = N->getOperand(0);
1818 SDValue N1 = N->getOperand(1);
1819 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1820 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1821 EVT VT = N0.getValueType();
1823 // If the flag result is dead, turn this into an SUB.
1824 if (!N->hasAnyUseOfValue(1))
1825 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1826 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1829 // fold (subc x, x) -> 0 + no borrow
1831 return CombineTo(N, DAG.getConstant(0, VT),
1832 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1835 // fold (subc x, 0) -> x + no borrow
1836 if (N1C && N1C->isNullValue())
1837 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1840 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1841 if (N0C && N0C->isAllOnesValue())
1842 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1843 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1849 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1850 SDValue N0 = N->getOperand(0);
1851 SDValue N1 = N->getOperand(1);
1852 SDValue CarryIn = N->getOperand(2);
1854 // fold (sube x, y, false) -> (subc x, y)
1855 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1856 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1861 SDValue DAGCombiner::visitMUL(SDNode *N) {
1862 SDValue N0 = N->getOperand(0);
1863 SDValue N1 = N->getOperand(1);
1864 EVT VT = N0.getValueType();
1866 // fold (mul x, undef) -> 0
1867 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1868 return DAG.getConstant(0, VT);
1870 bool N0IsConst = false;
1871 bool N1IsConst = false;
1872 APInt ConstValue0, ConstValue1;
1874 if (VT.isVector()) {
1875 SDValue FoldedVOp = SimplifyVBinOp(N);
1876 if (FoldedVOp.getNode()) return FoldedVOp;
1878 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1879 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1881 N0IsConst = dyn_cast<ConstantSDNode>(N0) != 0;
1882 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1884 N1IsConst = dyn_cast<ConstantSDNode>(N1) != 0;
1885 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1889 // fold (mul c1, c2) -> c1*c2
1890 if (N0IsConst && N1IsConst)
1891 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1893 // canonicalize constant to RHS
1894 if (N0IsConst && !N1IsConst)
1895 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1896 // fold (mul x, 0) -> 0
1897 if (N1IsConst && ConstValue1 == 0)
1899 // We require a splat of the entire scalar bit width for non-contiguous
1902 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1903 // fold (mul x, 1) -> x
1904 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1906 // fold (mul x, -1) -> 0-x
1907 if (N1IsConst && ConstValue1.isAllOnesValue())
1908 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1909 DAG.getConstant(0, VT), N0);
1910 // fold (mul x, (1 << c)) -> x << c
1911 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1912 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1913 DAG.getConstant(ConstValue1.logBase2(),
1914 getShiftAmountTy(N0.getValueType())));
1915 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1916 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1917 unsigned Log2Val = (-ConstValue1).logBase2();
1918 // FIXME: If the input is something that is easily negated (e.g. a
1919 // single-use add), we should put the negate there.
1920 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1921 DAG.getConstant(0, VT),
1922 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1923 DAG.getConstant(Log2Val,
1924 getShiftAmountTy(N0.getValueType()))));
1928 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1929 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1930 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1931 isa<ConstantSDNode>(N0.getOperand(1)))) {
1932 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1933 N1, N0.getOperand(1));
1934 AddToWorkList(C3.getNode());
1935 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1936 N0.getOperand(0), C3);
1939 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1942 SDValue Sh(0,0), Y(0,0);
1943 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1944 if (N0.getOpcode() == ISD::SHL &&
1945 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1946 isa<ConstantSDNode>(N0.getOperand(1))) &&
1947 N0.getNode()->hasOneUse()) {
1949 } else if (N1.getOpcode() == ISD::SHL &&
1950 isa<ConstantSDNode>(N1.getOperand(1)) &&
1951 N1.getNode()->hasOneUse()) {
1956 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1957 Sh.getOperand(0), Y);
1958 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1959 Mul, Sh.getOperand(1));
1963 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1964 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1965 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1966 isa<ConstantSDNode>(N0.getOperand(1))))
1967 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1968 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1969 N0.getOperand(0), N1),
1970 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1971 N0.getOperand(1), N1));
1974 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1975 if (RMUL.getNode() != 0)
1981 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1982 SDValue N0 = N->getOperand(0);
1983 SDValue N1 = N->getOperand(1);
1984 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1985 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1986 EVT VT = N->getValueType(0);
1989 if (VT.isVector()) {
1990 SDValue FoldedVOp = SimplifyVBinOp(N);
1991 if (FoldedVOp.getNode()) return FoldedVOp;
1994 // fold (sdiv c1, c2) -> c1/c2
1995 if (N0C && N1C && !N1C->isNullValue())
1996 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1997 // fold (sdiv X, 1) -> X
1998 if (N1C && N1C->getAPIntValue() == 1LL)
2000 // fold (sdiv X, -1) -> 0-X
2001 if (N1C && N1C->isAllOnesValue())
2002 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2003 DAG.getConstant(0, VT), N0);
2004 // If we know the sign bits of both operands are zero, strength reduce to a
2005 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2006 if (!VT.isVector()) {
2007 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2008 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2011 // fold (sdiv X, pow2) -> simple ops after legalize
2012 if (N1C && !N1C->isNullValue() &&
2013 (N1C->getAPIntValue().isPowerOf2() ||
2014 (-N1C->getAPIntValue()).isPowerOf2())) {
2015 // If dividing by powers of two is cheap, then don't perform the following
2017 if (TLI.isPow2DivCheap())
2020 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2022 // Splat the sign bit into the register
2023 SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2024 DAG.getConstant(VT.getSizeInBits()-1,
2025 getShiftAmountTy(N0.getValueType())));
2026 AddToWorkList(SGN.getNode());
2028 // Add (N0 < 0) ? abs2 - 1 : 0;
2029 SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2030 DAG.getConstant(VT.getSizeInBits() - lg2,
2031 getShiftAmountTy(SGN.getValueType())));
2032 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2033 AddToWorkList(SRL.getNode());
2034 AddToWorkList(ADD.getNode()); // Divide by pow2
2035 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2036 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2038 // If we're dividing by a positive value, we're done. Otherwise, we must
2039 // negate the result.
2040 if (N1C->getAPIntValue().isNonNegative())
2043 AddToWorkList(SRA.getNode());
2044 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2045 DAG.getConstant(0, VT), SRA);
2048 // if integer divide is expensive and we satisfy the requirements, emit an
2049 // alternate sequence.
2050 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2051 SDValue Op = BuildSDIV(N);
2052 if (Op.getNode()) return Op;
2056 if (N0.getOpcode() == ISD::UNDEF)
2057 return DAG.getConstant(0, VT);
2058 // X / undef -> undef
2059 if (N1.getOpcode() == ISD::UNDEF)
2065 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2066 SDValue N0 = N->getOperand(0);
2067 SDValue N1 = N->getOperand(1);
2068 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
2069 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2070 EVT VT = N->getValueType(0);
2073 if (VT.isVector()) {
2074 SDValue FoldedVOp = SimplifyVBinOp(N);
2075 if (FoldedVOp.getNode()) return FoldedVOp;
2078 // fold (udiv c1, c2) -> c1/c2
2079 if (N0C && N1C && !N1C->isNullValue())
2080 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2081 // fold (udiv x, (1 << c)) -> x >>u c
2082 if (N1C && N1C->getAPIntValue().isPowerOf2())
2083 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2084 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2085 getShiftAmountTy(N0.getValueType())));
2086 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2087 if (N1.getOpcode() == ISD::SHL) {
2088 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2089 if (SHC->getAPIntValue().isPowerOf2()) {
2090 EVT ADDVT = N1.getOperand(1).getValueType();
2091 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2093 DAG.getConstant(SHC->getAPIntValue()
2096 AddToWorkList(Add.getNode());
2097 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2101 // fold (udiv x, c) -> alternate
2102 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2103 SDValue Op = BuildUDIV(N);
2104 if (Op.getNode()) return Op;
2108 if (N0.getOpcode() == ISD::UNDEF)
2109 return DAG.getConstant(0, VT);
2110 // X / undef -> undef
2111 if (N1.getOpcode() == ISD::UNDEF)
2117 SDValue DAGCombiner::visitSREM(SDNode *N) {
2118 SDValue N0 = N->getOperand(0);
2119 SDValue N1 = N->getOperand(1);
2120 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2121 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2122 EVT VT = N->getValueType(0);
2124 // fold (srem c1, c2) -> c1%c2
2125 if (N0C && N1C && !N1C->isNullValue())
2126 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2127 // If we know the sign bits of both operands are zero, strength reduce to a
2128 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2129 if (!VT.isVector()) {
2130 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2131 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2134 // If X/C can be simplified by the division-by-constant logic, lower
2135 // X%C to the equivalent of X-X/C*C.
2136 if (N1C && !N1C->isNullValue()) {
2137 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2138 AddToWorkList(Div.getNode());
2139 SDValue OptimizedDiv = combine(Div.getNode());
2140 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2141 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2143 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2144 AddToWorkList(Mul.getNode());
2150 if (N0.getOpcode() == ISD::UNDEF)
2151 return DAG.getConstant(0, VT);
2152 // X % undef -> undef
2153 if (N1.getOpcode() == ISD::UNDEF)
2159 SDValue DAGCombiner::visitUREM(SDNode *N) {
2160 SDValue N0 = N->getOperand(0);
2161 SDValue N1 = N->getOperand(1);
2162 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2163 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2164 EVT VT = N->getValueType(0);
2166 // fold (urem c1, c2) -> c1%c2
2167 if (N0C && N1C && !N1C->isNullValue())
2168 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2169 // fold (urem x, pow2) -> (and x, pow2-1)
2170 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2171 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2172 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2173 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2174 if (N1.getOpcode() == ISD::SHL) {
2175 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2176 if (SHC->getAPIntValue().isPowerOf2()) {
2178 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2179 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2181 AddToWorkList(Add.getNode());
2182 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2187 // If X/C can be simplified by the division-by-constant logic, lower
2188 // X%C to the equivalent of X-X/C*C.
2189 if (N1C && !N1C->isNullValue()) {
2190 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2191 AddToWorkList(Div.getNode());
2192 SDValue OptimizedDiv = combine(Div.getNode());
2193 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2194 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2196 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2197 AddToWorkList(Mul.getNode());
2203 if (N0.getOpcode() == ISD::UNDEF)
2204 return DAG.getConstant(0, VT);
2205 // X % undef -> undef
2206 if (N1.getOpcode() == ISD::UNDEF)
2212 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2213 SDValue N0 = N->getOperand(0);
2214 SDValue N1 = N->getOperand(1);
2215 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2216 EVT VT = N->getValueType(0);
2219 // fold (mulhs x, 0) -> 0
2220 if (N1C && N1C->isNullValue())
2222 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2223 if (N1C && N1C->getAPIntValue() == 1)
2224 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2225 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2226 getShiftAmountTy(N0.getValueType())));
2227 // fold (mulhs x, undef) -> 0
2228 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2229 return DAG.getConstant(0, VT);
2231 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2233 if (VT.isSimple() && !VT.isVector()) {
2234 MVT Simple = VT.getSimpleVT();
2235 unsigned SimpleSize = Simple.getSizeInBits();
2236 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2237 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2238 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2239 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2240 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2241 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2242 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2243 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2250 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2251 SDValue N0 = N->getOperand(0);
2252 SDValue N1 = N->getOperand(1);
2253 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2254 EVT VT = N->getValueType(0);
2257 // fold (mulhu x, 0) -> 0
2258 if (N1C && N1C->isNullValue())
2260 // fold (mulhu x, 1) -> 0
2261 if (N1C && N1C->getAPIntValue() == 1)
2262 return DAG.getConstant(0, N0.getValueType());
2263 // fold (mulhu x, undef) -> 0
2264 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2265 return DAG.getConstant(0, VT);
2267 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2269 if (VT.isSimple() && !VT.isVector()) {
2270 MVT Simple = VT.getSimpleVT();
2271 unsigned SimpleSize = Simple.getSizeInBits();
2272 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2273 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2274 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2275 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2276 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2277 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2278 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2279 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2286 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2287 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2288 /// that are being performed. Return true if a simplification was made.
2290 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2292 // If the high half is not needed, just compute the low half.
2293 bool HiExists = N->hasAnyUseOfValue(1);
2295 (!LegalOperations ||
2296 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2297 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2298 N->op_begin(), N->getNumOperands());
2299 return CombineTo(N, Res, Res);
2302 // If the low half is not needed, just compute the high half.
2303 bool LoExists = N->hasAnyUseOfValue(0);
2305 (!LegalOperations ||
2306 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2307 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2308 N->op_begin(), N->getNumOperands());
2309 return CombineTo(N, Res, Res);
2312 // If both halves are used, return as it is.
2313 if (LoExists && HiExists)
2316 // If the two computed results can be simplified separately, separate them.
2318 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2319 N->op_begin(), N->getNumOperands());
2320 AddToWorkList(Lo.getNode());
2321 SDValue LoOpt = combine(Lo.getNode());
2322 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2323 (!LegalOperations ||
2324 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2325 return CombineTo(N, LoOpt, LoOpt);
2329 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2330 N->op_begin(), N->getNumOperands());
2331 AddToWorkList(Hi.getNode());
2332 SDValue HiOpt = combine(Hi.getNode());
2333 if (HiOpt.getNode() && HiOpt != Hi &&
2334 (!LegalOperations ||
2335 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2336 return CombineTo(N, HiOpt, HiOpt);
2342 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2343 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2344 if (Res.getNode()) return Res;
2346 EVT VT = N->getValueType(0);
2349 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2351 if (VT.isSimple() && !VT.isVector()) {
2352 MVT Simple = VT.getSimpleVT();
2353 unsigned SimpleSize = Simple.getSizeInBits();
2354 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2355 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2356 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2357 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2358 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2359 // Compute the high part as N1.
2360 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2361 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2362 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2363 // Compute the low part as N0.
2364 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2365 return CombineTo(N, Lo, Hi);
2372 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2373 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2374 if (Res.getNode()) return Res;
2376 EVT VT = N->getValueType(0);
2379 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2381 if (VT.isSimple() && !VT.isVector()) {
2382 MVT Simple = VT.getSimpleVT();
2383 unsigned SimpleSize = Simple.getSizeInBits();
2384 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2385 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2386 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2387 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2388 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2389 // Compute the high part as N1.
2390 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2391 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2392 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2393 // Compute the low part as N0.
2394 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2395 return CombineTo(N, Lo, Hi);
2402 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2403 // (smulo x, 2) -> (saddo x, x)
2404 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2405 if (C2->getAPIntValue() == 2)
2406 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2407 N->getOperand(0), N->getOperand(0));
2412 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2413 // (umulo x, 2) -> (uaddo x, x)
2414 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2415 if (C2->getAPIntValue() == 2)
2416 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2417 N->getOperand(0), N->getOperand(0));
2422 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2423 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2424 if (Res.getNode()) return Res;
2429 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2430 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2431 if (Res.getNode()) return Res;
2436 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2437 /// two operands of the same opcode, try to simplify it.
2438 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2439 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2440 EVT VT = N0.getValueType();
2441 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2443 // Bail early if none of these transforms apply.
2444 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2446 // For each of OP in AND/OR/XOR:
2447 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2448 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2449 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2450 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2452 // do not sink logical op inside of a vector extend, since it may combine
2454 EVT Op0VT = N0.getOperand(0).getValueType();
2455 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2456 N0.getOpcode() == ISD::SIGN_EXTEND ||
2457 // Avoid infinite looping with PromoteIntBinOp.
2458 (N0.getOpcode() == ISD::ANY_EXTEND &&
2459 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2460 (N0.getOpcode() == ISD::TRUNCATE &&
2461 (!TLI.isZExtFree(VT, Op0VT) ||
2462 !TLI.isTruncateFree(Op0VT, VT)) &&
2463 TLI.isTypeLegal(Op0VT))) &&
2465 Op0VT == N1.getOperand(0).getValueType() &&
2466 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2467 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2468 N0.getOperand(0).getValueType(),
2469 N0.getOperand(0), N1.getOperand(0));
2470 AddToWorkList(ORNode.getNode());
2471 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2474 // For each of OP in SHL/SRL/SRA/AND...
2475 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2476 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2477 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2478 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2479 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2480 N0.getOperand(1) == N1.getOperand(1)) {
2481 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2482 N0.getOperand(0).getValueType(),
2483 N0.getOperand(0), N1.getOperand(0));
2484 AddToWorkList(ORNode.getNode());
2485 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2486 ORNode, N0.getOperand(1));
2489 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2490 // Only perform this optimization after type legalization and before
2491 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2492 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2493 // we don't want to undo this promotion.
2494 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2496 if ((N0.getOpcode() == ISD::BITCAST ||
2497 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2498 Level == AfterLegalizeTypes) {
2499 SDValue In0 = N0.getOperand(0);
2500 SDValue In1 = N1.getOperand(0);
2501 EVT In0Ty = In0.getValueType();
2502 EVT In1Ty = In1.getValueType();
2504 // If both incoming values are integers, and the original types are the
2506 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2507 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2508 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2509 AddToWorkList(Op.getNode());
2514 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2515 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2516 // If both shuffles use the same mask, and both shuffle within a single
2517 // vector, then it is worthwhile to move the swizzle after the operation.
2518 // The type-legalizer generates this pattern when loading illegal
2519 // vector types from memory. In many cases this allows additional shuffle
2521 // There are other cases where moving the shuffle after the xor/and/or
2522 // is profitable even if shuffles don't perform a swizzle.
2523 // If both shuffles use the same mask, and both shuffles have the same first
2524 // or second operand, then it might still be profitable to move the shuffle
2525 // after the xor/and/or operation.
2526 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2527 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2528 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2530 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2531 "Inputs to shuffles are not the same type");
2533 // Check that both shuffles use the same mask. The masks are known to be of
2534 // the same length because the result vector type is the same.
2535 // Check also that shuffles have only one use to avoid introducing extra
2537 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2538 SVN0->getMask().equals(SVN1->getMask())) {
2539 SDValue ShOp = N0->getOperand(1);
2541 // Don't try to fold this node if it requires introducing a
2542 // build vector of all zeros that might be illegal at this stage.
2543 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2545 ShOp = DAG.getConstant(0, VT);
2550 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2551 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2552 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2553 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2554 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2555 N0->getOperand(0), N1->getOperand(0));
2556 AddToWorkList(NewNode.getNode());
2557 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2558 &SVN0->getMask()[0]);
2561 // Don't try to fold this node if it requires introducing a
2562 // build vector of all zeros that might be illegal at this stage.
2563 ShOp = N0->getOperand(0);
2564 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2566 ShOp = DAG.getConstant(0, VT);
2571 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2572 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2573 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2574 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2575 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2576 N0->getOperand(1), N1->getOperand(1));
2577 AddToWorkList(NewNode.getNode());
2578 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2579 &SVN0->getMask()[0]);
2587 SDValue DAGCombiner::visitAND(SDNode *N) {
2588 SDValue N0 = N->getOperand(0);
2589 SDValue N1 = N->getOperand(1);
2590 SDValue LL, LR, RL, RR, CC0, CC1;
2591 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2592 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2593 EVT VT = N1.getValueType();
2594 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2597 if (VT.isVector()) {
2598 SDValue FoldedVOp = SimplifyVBinOp(N);
2599 if (FoldedVOp.getNode()) return FoldedVOp;
2601 // fold (and x, 0) -> 0, vector edition
2602 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2604 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2607 // fold (and x, -1) -> x, vector edition
2608 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2610 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2614 // fold (and x, undef) -> 0
2615 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2616 return DAG.getConstant(0, VT);
2617 // fold (and c1, c2) -> c1&c2
2619 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2620 // canonicalize constant to RHS
2622 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2623 // fold (and x, -1) -> x
2624 if (N1C && N1C->isAllOnesValue())
2626 // if (and x, c) is known to be zero, return 0
2627 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2628 APInt::getAllOnesValue(BitWidth)))
2629 return DAG.getConstant(0, VT);
2631 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2632 if (RAND.getNode() != 0)
2634 // fold (and (or x, C), D) -> D if (C & D) == D
2635 if (N1C && N0.getOpcode() == ISD::OR)
2636 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2637 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2639 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2640 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2641 SDValue N0Op0 = N0.getOperand(0);
2642 APInt Mask = ~N1C->getAPIntValue();
2643 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2644 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2645 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2646 N0.getValueType(), N0Op0);
2648 // Replace uses of the AND with uses of the Zero extend node.
2651 // We actually want to replace all uses of the any_extend with the
2652 // zero_extend, to avoid duplicating things. This will later cause this
2653 // AND to be folded.
2654 CombineTo(N0.getNode(), Zext);
2655 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2658 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2659 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2660 // already be zero by virtue of the width of the base type of the load.
2662 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2664 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2665 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2666 N0.getOpcode() == ISD::LOAD) {
2667 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2668 N0 : N0.getOperand(0) );
2670 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2671 // This can be a pure constant or a vector splat, in which case we treat the
2672 // vector as a scalar and use the splat value.
2673 APInt Constant = APInt::getNullValue(1);
2674 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2675 Constant = C->getAPIntValue();
2676 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2677 APInt SplatValue, SplatUndef;
2678 unsigned SplatBitSize;
2680 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2681 SplatBitSize, HasAnyUndefs);
2683 // Undef bits can contribute to a possible optimisation if set, so
2685 SplatValue |= SplatUndef;
2687 // The splat value may be something like "0x00FFFFFF", which means 0 for
2688 // the first vector value and FF for the rest, repeating. We need a mask
2689 // that will apply equally to all members of the vector, so AND all the
2690 // lanes of the constant together.
2691 EVT VT = Vector->getValueType(0);
2692 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2694 // If the splat value has been compressed to a bitlength lower
2695 // than the size of the vector lane, we need to re-expand it to
2697 if (BitWidth > SplatBitSize)
2698 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2699 SplatBitSize < BitWidth;
2700 SplatBitSize = SplatBitSize * 2)
2701 SplatValue |= SplatValue.shl(SplatBitSize);
2703 Constant = APInt::getAllOnesValue(BitWidth);
2704 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2705 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2709 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2710 // actually legal and isn't going to get expanded, else this is a false
2712 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2713 Load->getMemoryVT());
2715 // Resize the constant to the same size as the original memory access before
2716 // extension. If it is still the AllOnesValue then this AND is completely
2719 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2722 switch (Load->getExtensionType()) {
2723 default: B = false; break;
2724 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2726 case ISD::NON_EXTLOAD: B = true; break;
2729 if (B && Constant.isAllOnesValue()) {
2730 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2731 // preserve semantics once we get rid of the AND.
2732 SDValue NewLoad(Load, 0);
2733 if (Load->getExtensionType() == ISD::EXTLOAD) {
2734 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2735 Load->getValueType(0), SDLoc(Load),
2736 Load->getChain(), Load->getBasePtr(),
2737 Load->getOffset(), Load->getMemoryVT(),
2738 Load->getMemOperand());
2739 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2740 if (Load->getNumValues() == 3) {
2741 // PRE/POST_INC loads have 3 values.
2742 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2743 NewLoad.getValue(2) };
2744 CombineTo(Load, To, 3, true);
2746 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2750 // Fold the AND away, taking care not to fold to the old load node if we
2752 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2754 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2757 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2758 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2759 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2760 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2762 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2763 LL.getValueType().isInteger()) {
2764 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2765 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2766 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2767 LR.getValueType(), LL, RL);
2768 AddToWorkList(ORNode.getNode());
2769 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2771 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2772 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2773 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2774 LR.getValueType(), LL, RL);
2775 AddToWorkList(ANDNode.getNode());
2776 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2778 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2779 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2780 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2781 LR.getValueType(), LL, RL);
2782 AddToWorkList(ORNode.getNode());
2783 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2786 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2787 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2788 Op0 == Op1 && LL.getValueType().isInteger() &&
2789 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2790 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2791 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2792 cast<ConstantSDNode>(RR)->isNullValue()))) {
2793 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2794 LL, DAG.getConstant(1, LL.getValueType()));
2795 AddToWorkList(ADDNode.getNode());
2796 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2797 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2799 // canonicalize equivalent to ll == rl
2800 if (LL == RR && LR == RL) {
2801 Op1 = ISD::getSetCCSwappedOperands(Op1);
2804 if (LL == RL && LR == RR) {
2805 bool isInteger = LL.getValueType().isInteger();
2806 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2807 if (Result != ISD::SETCC_INVALID &&
2808 (!LegalOperations ||
2809 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2810 TLI.isOperationLegal(ISD::SETCC,
2811 getSetCCResultType(N0.getSimpleValueType())))))
2812 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2817 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2818 if (N0.getOpcode() == N1.getOpcode()) {
2819 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2820 if (Tmp.getNode()) return Tmp;
2823 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2824 // fold (and (sra)) -> (and (srl)) when possible.
2825 if (!VT.isVector() &&
2826 SimplifyDemandedBits(SDValue(N, 0)))
2827 return SDValue(N, 0);
2829 // fold (zext_inreg (extload x)) -> (zextload x)
2830 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2831 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2832 EVT MemVT = LN0->getMemoryVT();
2833 // If we zero all the possible extended bits, then we can turn this into
2834 // a zextload if we are running before legalize or the operation is legal.
2835 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2836 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2837 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2838 ((!LegalOperations && !LN0->isVolatile()) ||
2839 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2840 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2841 LN0->getChain(), LN0->getBasePtr(),
2842 MemVT, LN0->getMemOperand());
2844 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2845 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2848 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2849 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2851 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2852 EVT MemVT = LN0->getMemoryVT();
2853 // If we zero all the possible extended bits, then we can turn this into
2854 // a zextload if we are running before legalize or the operation is legal.
2855 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2856 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2857 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2858 ((!LegalOperations && !LN0->isVolatile()) ||
2859 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2860 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2861 LN0->getChain(), LN0->getBasePtr(),
2862 MemVT, LN0->getMemOperand());
2864 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2865 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2869 // fold (and (load x), 255) -> (zextload x, i8)
2870 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2871 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2872 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2873 (N0.getOpcode() == ISD::ANY_EXTEND &&
2874 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2875 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2876 LoadSDNode *LN0 = HasAnyExt
2877 ? cast<LoadSDNode>(N0.getOperand(0))
2878 : cast<LoadSDNode>(N0);
2879 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2880 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2881 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2882 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2883 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2884 EVT LoadedVT = LN0->getMemoryVT();
2886 if (ExtVT == LoadedVT &&
2887 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2888 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2891 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2892 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2893 LN0->getMemOperand());
2895 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2896 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2899 // Do not change the width of a volatile load.
2900 // Do not generate loads of non-round integer types since these can
2901 // be expensive (and would be wrong if the type is not byte sized).
2902 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2903 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2904 EVT PtrType = LN0->getOperand(1).getValueType();
2906 unsigned Alignment = LN0->getAlignment();
2907 SDValue NewPtr = LN0->getBasePtr();
2909 // For big endian targets, we need to add an offset to the pointer
2910 // to load the correct bytes. For little endian systems, we merely
2911 // need to read fewer bytes from the same pointer.
2912 if (TLI.isBigEndian()) {
2913 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2914 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2915 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2916 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2917 NewPtr, DAG.getConstant(PtrOff, PtrType));
2918 Alignment = MinAlign(Alignment, PtrOff);
2921 AddToWorkList(NewPtr.getNode());
2923 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2925 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2926 LN0->getChain(), NewPtr,
2927 LN0->getPointerInfo(),
2928 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2929 Alignment, LN0->getTBAAInfo());
2931 CombineTo(LN0, Load, Load.getValue(1));
2932 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2938 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2939 VT.getSizeInBits() <= 64) {
2940 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2941 APInt ADDC = ADDI->getAPIntValue();
2942 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2943 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2944 // immediate for an add, but it is legal if its top c2 bits are set,
2945 // transform the ADD so the immediate doesn't need to be materialized
2947 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2948 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2949 SRLI->getZExtValue());
2950 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2952 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2954 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2955 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2956 CombineTo(N0.getNode(), NewAdd);
2957 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2965 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2966 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2967 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2968 N0.getOperand(1), false);
2969 if (BSwap.getNode())
2976 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2978 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2979 bool DemandHighBits) {
2980 if (!LegalOperations)
2983 EVT VT = N->getValueType(0);
2984 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2986 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2989 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2990 bool LookPassAnd0 = false;
2991 bool LookPassAnd1 = false;
2992 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2994 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2996 if (N0.getOpcode() == ISD::AND) {
2997 if (!N0.getNode()->hasOneUse())
2999 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3000 if (!N01C || N01C->getZExtValue() != 0xFF00)
3002 N0 = N0.getOperand(0);
3003 LookPassAnd0 = true;
3006 if (N1.getOpcode() == ISD::AND) {
3007 if (!N1.getNode()->hasOneUse())
3009 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3010 if (!N11C || N11C->getZExtValue() != 0xFF)
3012 N1 = N1.getOperand(0);
3013 LookPassAnd1 = true;
3016 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3018 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3020 if (!N0.getNode()->hasOneUse() ||
3021 !N1.getNode()->hasOneUse())
3024 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3025 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3028 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3031 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3032 SDValue N00 = N0->getOperand(0);
3033 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3034 if (!N00.getNode()->hasOneUse())
3036 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3037 if (!N001C || N001C->getZExtValue() != 0xFF)
3039 N00 = N00.getOperand(0);
3040 LookPassAnd0 = true;
3043 SDValue N10 = N1->getOperand(0);
3044 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3045 if (!N10.getNode()->hasOneUse())
3047 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3048 if (!N101C || N101C->getZExtValue() != 0xFF00)
3050 N10 = N10.getOperand(0);
3051 LookPassAnd1 = true;
3057 // Make sure everything beyond the low halfword gets set to zero since the SRL
3058 // 16 will clear the top bits.
3059 unsigned OpSizeInBits = VT.getSizeInBits();
3060 if (DemandHighBits && OpSizeInBits > 16) {
3061 // If the left-shift isn't masked out then the only way this is a bswap is
3062 // if all bits beyond the low 8 are 0. In that case the entire pattern
3063 // reduces to a left shift anyway: leave it for other parts of the combiner.
3067 // However, if the right shift isn't masked out then it might be because
3068 // it's not needed. See if we can spot that too.
3069 if (!LookPassAnd1 &&
3070 !DAG.MaskedValueIsZero(
3071 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3075 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3076 if (OpSizeInBits > 16)
3077 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3078 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3082 /// isBSwapHWordElement - Return true if the specified node is an element
3083 /// that makes up a 32-bit packed halfword byteswap. i.e.
3084 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3085 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3086 if (!N.getNode()->hasOneUse())
3089 unsigned Opc = N.getOpcode();
3090 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3093 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3098 switch (N1C->getZExtValue()) {
3101 case 0xFF: Num = 0; break;
3102 case 0xFF00: Num = 1; break;
3103 case 0xFF0000: Num = 2; break;
3104 case 0xFF000000: Num = 3; break;
3107 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3108 SDValue N0 = N.getOperand(0);
3109 if (Opc == ISD::AND) {
3110 if (Num == 0 || Num == 2) {
3112 // (x >> 8) & 0xff0000
3113 if (N0.getOpcode() != ISD::SRL)
3115 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3116 if (!C || C->getZExtValue() != 8)
3119 // (x << 8) & 0xff00
3120 // (x << 8) & 0xff000000
3121 if (N0.getOpcode() != ISD::SHL)
3123 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3124 if (!C || C->getZExtValue() != 8)
3127 } else if (Opc == ISD::SHL) {
3129 // (x & 0xff0000) << 8
3130 if (Num != 0 && Num != 2)
3132 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3133 if (!C || C->getZExtValue() != 8)
3135 } else { // Opc == ISD::SRL
3136 // (x & 0xff00) >> 8
3137 // (x & 0xff000000) >> 8
3138 if (Num != 1 && Num != 3)
3140 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3141 if (!C || C->getZExtValue() != 8)
3148 Parts[Num] = N0.getOperand(0).getNode();
3152 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3153 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3154 /// => (rotl (bswap x), 16)
3155 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3156 if (!LegalOperations)
3159 EVT VT = N->getValueType(0);
3162 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3165 SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
3167 // (or (or (and), (and)), (or (and), (and)))
3168 // (or (or (or (and), (and)), (and)), (and))
3169 if (N0.getOpcode() != ISD::OR)
3171 SDValue N00 = N0.getOperand(0);
3172 SDValue N01 = N0.getOperand(1);
3174 if (N1.getOpcode() == ISD::OR &&
3175 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3176 // (or (or (and), (and)), (or (and), (and)))
3177 SDValue N000 = N00.getOperand(0);
3178 if (!isBSwapHWordElement(N000, Parts))
3181 SDValue N001 = N00.getOperand(1);
3182 if (!isBSwapHWordElement(N001, Parts))
3184 SDValue N010 = N01.getOperand(0);
3185 if (!isBSwapHWordElement(N010, Parts))
3187 SDValue N011 = N01.getOperand(1);
3188 if (!isBSwapHWordElement(N011, Parts))
3191 // (or (or (or (and), (and)), (and)), (and))
3192 if (!isBSwapHWordElement(N1, Parts))
3194 if (!isBSwapHWordElement(N01, Parts))
3196 if (N00.getOpcode() != ISD::OR)
3198 SDValue N000 = N00.getOperand(0);
3199 if (!isBSwapHWordElement(N000, Parts))
3201 SDValue N001 = N00.getOperand(1);
3202 if (!isBSwapHWordElement(N001, Parts))
3206 // Make sure the parts are all coming from the same node.
3207 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3210 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3211 SDValue(Parts[0],0));
3213 // Result of the bswap should be rotated by 16. If it's not legal, then
3214 // do (x << 16) | (x >> 16).
3215 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3216 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3217 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3218 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3219 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3220 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3221 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3222 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3225 SDValue DAGCombiner::visitOR(SDNode *N) {
3226 SDValue N0 = N->getOperand(0);
3227 SDValue N1 = N->getOperand(1);
3228 SDValue LL, LR, RL, RR, CC0, CC1;
3229 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3230 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3231 EVT VT = N1.getValueType();
3234 if (VT.isVector()) {
3235 SDValue FoldedVOp = SimplifyVBinOp(N);
3236 if (FoldedVOp.getNode()) return FoldedVOp;
3238 // fold (or x, 0) -> x, vector edition
3239 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3241 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3244 // fold (or x, -1) -> -1, vector edition
3245 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3247 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3250 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3251 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3252 // Do this only if the resulting shuffle is legal.
3253 if (isa<ShuffleVectorSDNode>(N0) &&
3254 isa<ShuffleVectorSDNode>(N1) &&
3255 N0->getOperand(1) == N1->getOperand(1) &&
3256 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3257 bool CanFold = true;
3258 unsigned NumElts = VT.getVectorNumElements();
3259 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3260 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3261 // We construct two shuffle masks:
3262 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3263 // and N1 as the second operand.
3264 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3265 // and N0 as the second operand.
3266 // We do this because OR is commutable and therefore there might be
3267 // two ways to fold this node into a shuffle.
3268 SmallVector<int,4> Mask1;
3269 SmallVector<int,4> Mask2;
3271 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3272 int M0 = SV0->getMaskElt(i);
3273 int M1 = SV1->getMaskElt(i);
3275 // Both shuffle indexes are undef. Propagate Undef.
3276 if (M0 < 0 && M1 < 0) {
3277 Mask1.push_back(M0);
3278 Mask2.push_back(M0);
3282 if (M0 < 0 || M1 < 0 ||
3283 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3284 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3289 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3290 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3294 // Fold this sequence only if the resulting shuffle is 'legal'.
3295 if (TLI.isShuffleMaskLegal(Mask1, VT))
3296 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3297 N1->getOperand(0), &Mask1[0]);
3298 if (TLI.isShuffleMaskLegal(Mask2, VT))
3299 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3300 N0->getOperand(0), &Mask2[0]);
3305 // fold (or x, undef) -> -1
3306 if (!LegalOperations &&
3307 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3308 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3309 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3311 // fold (or c1, c2) -> c1|c2
3313 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3314 // canonicalize constant to RHS
3316 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3317 // fold (or x, 0) -> x
3318 if (N1C && N1C->isNullValue())
3320 // fold (or x, -1) -> -1
3321 if (N1C && N1C->isAllOnesValue())
3323 // fold (or x, c) -> c iff (x & ~c) == 0
3324 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3327 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3328 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3329 if (BSwap.getNode() != 0)
3331 BSwap = MatchBSwapHWordLow(N, N0, N1);
3332 if (BSwap.getNode() != 0)
3336 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3337 if (ROR.getNode() != 0)
3339 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3340 // iff (c1 & c2) == 0.
3341 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3342 isa<ConstantSDNode>(N0.getOperand(1))) {
3343 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3344 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3345 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3348 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3349 DAG.getNode(ISD::OR, SDLoc(N0), VT,
3350 N0.getOperand(0), N1), COR);
3353 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3354 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3355 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3356 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3358 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3359 LL.getValueType().isInteger()) {
3360 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3361 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3362 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3363 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3364 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3365 LR.getValueType(), LL, RL);
3366 AddToWorkList(ORNode.getNode());
3367 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3369 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3370 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3371 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3372 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3373 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3374 LR.getValueType(), LL, RL);
3375 AddToWorkList(ANDNode.getNode());
3376 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3379 // canonicalize equivalent to ll == rl
3380 if (LL == RR && LR == RL) {
3381 Op1 = ISD::getSetCCSwappedOperands(Op1);
3384 if (LL == RL && LR == RR) {
3385 bool isInteger = LL.getValueType().isInteger();
3386 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3387 if (Result != ISD::SETCC_INVALID &&
3388 (!LegalOperations ||
3389 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3390 TLI.isOperationLegal(ISD::SETCC,
3391 getSetCCResultType(N0.getValueType())))))
3392 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3397 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3398 if (N0.getOpcode() == N1.getOpcode()) {
3399 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3400 if (Tmp.getNode()) return Tmp;
3403 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3404 if (N0.getOpcode() == ISD::AND &&
3405 N1.getOpcode() == ISD::AND &&
3406 N0.getOperand(1).getOpcode() == ISD::Constant &&
3407 N1.getOperand(1).getOpcode() == ISD::Constant &&
3408 // Don't increase # computations.
3409 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3410 // We can only do this xform if we know that bits from X that are set in C2
3411 // but not in C1 are already zero. Likewise for Y.
3412 const APInt &LHSMask =
3413 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3414 const APInt &RHSMask =
3415 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3417 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3418 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3419 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3420 N0.getOperand(0), N1.getOperand(0));
3421 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3422 DAG.getConstant(LHSMask | RHSMask, VT));
3426 // See if this is some rotate idiom.
3427 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3428 return SDValue(Rot, 0);
3430 // Simplify the operands using demanded-bits information.
3431 if (!VT.isVector() &&
3432 SimplifyDemandedBits(SDValue(N, 0)))
3433 return SDValue(N, 0);
3438 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3439 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3440 if (Op.getOpcode() == ISD::AND) {
3441 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3442 Mask = Op.getOperand(1);
3443 Op = Op.getOperand(0);
3449 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3457 // Return true if we can prove that, whenever Neg and Pos are both in the
3458 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3459 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3461 // (or (shift1 X, Neg), (shift2 X, Pos))
3463 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3464 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3465 // to consider shift amounts with defined behavior.
3466 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3467 // If OpSize is a power of 2 then:
3469 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3470 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3472 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3473 // for the stronger condition:
3475 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3477 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3478 // we can just replace Neg with Neg' for the rest of the function.
3480 // In other cases we check for the even stronger condition:
3482 // Neg == OpSize - Pos [B]
3484 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3485 // behavior if Pos == 0 (and consequently Neg == OpSize).
3487 // We could actually use [A] whenever OpSize is a power of 2, but the
3488 // only extra cases that it would match are those uninteresting ones
3489 // where Neg and Pos are never in range at the same time. E.g. for
3490 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3491 // as well as (sub 32, Pos), but:
3493 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3495 // always invokes undefined behavior for 32-bit X.
3497 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3498 unsigned MaskLoBits = 0;
3499 if (Neg.getOpcode() == ISD::AND &&
3500 isPowerOf2_64(OpSize) &&
3501 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3502 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3503 Neg = Neg.getOperand(0);
3504 MaskLoBits = Log2_64(OpSize);
3507 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3508 if (Neg.getOpcode() != ISD::SUB)
3510 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3513 SDValue NegOp1 = Neg.getOperand(1);
3515 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3516 // Pos'. The truncation is redundant for the purpose of the equality.
3518 Pos.getOpcode() == ISD::AND &&
3519 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3520 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3521 Pos = Pos.getOperand(0);
3523 // The condition we need is now:
3525 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3527 // If NegOp1 == Pos then we need:
3529 // OpSize & Mask == NegC & Mask
3531 // (because "x & Mask" is a truncation and distributes through subtraction).
3534 Width = NegC->getAPIntValue();
3535 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3536 // Then the condition we want to prove becomes:
3538 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3540 // which, again because "x & Mask" is a truncation, becomes:
3542 // NegC & Mask == (OpSize - PosC) & Mask
3543 // OpSize & Mask == (NegC + PosC) & Mask
3544 else if (Pos.getOpcode() == ISD::ADD &&
3545 Pos.getOperand(0) == NegOp1 &&
3546 Pos.getOperand(1).getOpcode() == ISD::Constant)
3547 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3548 NegC->getAPIntValue());
3552 // Now we just need to check that OpSize & Mask == Width & Mask.
3554 // Opsize & Mask is 0 since Mask is Opsize - 1.
3555 return Width.getLoBits(MaskLoBits) == 0;
3556 return Width == OpSize;
3559 // A subroutine of MatchRotate used once we have found an OR of two opposite
3560 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3561 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3562 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3563 // Neg with outer conversions stripped away.
3564 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3565 SDValue Neg, SDValue InnerPos,
3566 SDValue InnerNeg, unsigned PosOpcode,
3567 unsigned NegOpcode, SDLoc DL) {
3568 // fold (or (shl x, (*ext y)),
3569 // (srl x, (*ext (sub 32, y)))) ->
3570 // (rotl x, y) or (rotr x, (sub 32, y))
3572 // fold (or (shl x, (*ext (sub 32, y))),
3573 // (srl x, (*ext y))) ->
3574 // (rotr x, y) or (rotl x, (sub 32, y))
3575 EVT VT = Shifted.getValueType();
3576 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3577 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3578 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3579 HasPos ? Pos : Neg).getNode();
3582 // fold (or (shl (*ext x), (*ext y)),
3583 // (srl (*ext x), (*ext (sub 32, y)))) ->
3584 // (*ext (rotl x, y)) or (*ext (rotr x, (sub 32, y)))
3586 // fold (or (shl (*ext x), (*ext (sub 32, y))),
3587 // (srl (*ext x), (*ext y))) ->
3588 // (*ext (rotr x, y)) or (*ext (rotl x, (sub 32, y)))
3589 if (Shifted.getOpcode() == ISD::ZERO_EXTEND ||
3590 Shifted.getOpcode() == ISD::ANY_EXTEND) {
3591 SDValue InnerShifted = Shifted.getOperand(0);
3592 EVT InnerVT = InnerShifted.getValueType();
3593 bool HasPosInner = TLI.isOperationLegalOrCustom(PosOpcode, InnerVT);
3594 if (HasPosInner || TLI.isOperationLegalOrCustom(NegOpcode, InnerVT)) {
3595 if (matchRotateSub(InnerPos, InnerNeg, InnerVT.getSizeInBits())) {
3596 SDValue V = DAG.getNode(HasPosInner ? PosOpcode : NegOpcode, DL,
3597 InnerVT, InnerShifted, HasPosInner ? Pos : Neg);
3598 return DAG.getNode(Shifted.getOpcode(), DL, VT, V).getNode();
3606 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3607 // idioms for rotate, and if the target supports rotation instructions, generate
3609 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3610 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3611 EVT VT = LHS.getValueType();
3612 if (!TLI.isTypeLegal(VT)) return 0;
3614 // The target must have at least one rotate flavor.
3615 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3616 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3617 if (!HasROTL && !HasROTR) return 0;
3619 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3620 SDValue LHSShift; // The shift.
3621 SDValue LHSMask; // AND value if any.
3622 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3623 return 0; // Not part of a rotate.
3625 SDValue RHSShift; // The shift.
3626 SDValue RHSMask; // AND value if any.
3627 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3628 return 0; // Not part of a rotate.
3630 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3631 return 0; // Not shifting the same value.
3633 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3634 return 0; // Shifts must disagree.
3636 // Canonicalize shl to left side in a shl/srl pair.
3637 if (RHSShift.getOpcode() == ISD::SHL) {
3638 std::swap(LHS, RHS);
3639 std::swap(LHSShift, RHSShift);
3640 std::swap(LHSMask , RHSMask );
3643 unsigned OpSizeInBits = VT.getSizeInBits();
3644 SDValue LHSShiftArg = LHSShift.getOperand(0);
3645 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3646 SDValue RHSShiftArg = RHSShift.getOperand(0);
3647 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3649 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3650 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3651 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3652 RHSShiftAmt.getOpcode() == ISD::Constant) {
3653 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3654 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3655 if ((LShVal + RShVal) != OpSizeInBits)
3658 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3659 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3661 // If there is an AND of either shifted operand, apply it to the result.
3662 if (LHSMask.getNode() || RHSMask.getNode()) {
3663 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3665 if (LHSMask.getNode()) {
3666 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3667 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3669 if (RHSMask.getNode()) {
3670 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3671 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3674 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3677 return Rot.getNode();
3680 // If there is a mask here, and we have a variable shift, we can't be sure
3681 // that we're masking out the right stuff.
3682 if (LHSMask.getNode() || RHSMask.getNode())
3685 // If the shift amount is sign/zext/any-extended just peel it off.
3686 SDValue LExtOp0 = LHSShiftAmt;
3687 SDValue RExtOp0 = RHSShiftAmt;
3688 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3689 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3690 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3691 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3692 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3693 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3694 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3695 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3696 LExtOp0 = LHSShiftAmt.getOperand(0);
3697 RExtOp0 = RHSShiftAmt.getOperand(0);
3700 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3701 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3705 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3706 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3713 SDValue DAGCombiner::visitXOR(SDNode *N) {
3714 SDValue N0 = N->getOperand(0);
3715 SDValue N1 = N->getOperand(1);
3716 SDValue LHS, RHS, CC;
3717 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3718 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3719 EVT VT = N0.getValueType();
3722 if (VT.isVector()) {
3723 SDValue FoldedVOp = SimplifyVBinOp(N);
3724 if (FoldedVOp.getNode()) return FoldedVOp;
3726 // fold (xor x, 0) -> x, vector edition
3727 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3729 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3733 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3734 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3735 return DAG.getConstant(0, VT);
3736 // fold (xor x, undef) -> undef
3737 if (N0.getOpcode() == ISD::UNDEF)
3739 if (N1.getOpcode() == ISD::UNDEF)
3741 // fold (xor c1, c2) -> c1^c2
3743 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3744 // canonicalize constant to RHS
3746 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3747 // fold (xor x, 0) -> x
3748 if (N1C && N1C->isNullValue())
3751 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3752 if (RXOR.getNode() != 0)
3755 // fold !(x cc y) -> (x !cc y)
3756 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3757 bool isInt = LHS.getValueType().isInteger();
3758 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3761 if (!LegalOperations ||
3762 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3763 switch (N0.getOpcode()) {
3765 llvm_unreachable("Unhandled SetCC Equivalent!");
3767 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3768 case ISD::SELECT_CC:
3769 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3770 N0.getOperand(3), NotCC);
3775 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3776 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3777 N0.getNode()->hasOneUse() &&
3778 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3779 SDValue V = N0.getOperand(0);
3780 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3781 DAG.getConstant(1, V.getValueType()));
3782 AddToWorkList(V.getNode());
3783 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3786 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3787 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3788 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3789 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3790 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3791 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3792 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3793 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3794 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3795 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3798 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3799 if (N1C && N1C->isAllOnesValue() &&
3800 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3801 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3802 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3803 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3804 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3805 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3806 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3807 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3810 // fold (xor (and x, y), y) -> (and (not x), y)
3811 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3812 N0->getOperand(1) == N1) {
3813 SDValue X = N0->getOperand(0);
3814 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3815 AddToWorkList(NotX.getNode());
3816 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3818 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3819 if (N1C && N0.getOpcode() == ISD::XOR) {
3820 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3821 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3823 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3824 DAG.getConstant(N1C->getAPIntValue() ^
3825 N00C->getAPIntValue(), VT));
3827 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3828 DAG.getConstant(N1C->getAPIntValue() ^
3829 N01C->getAPIntValue(), VT));
3831 // fold (xor x, x) -> 0
3833 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3835 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3836 if (N0.getOpcode() == N1.getOpcode()) {
3837 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3838 if (Tmp.getNode()) return Tmp;
3841 // Simplify the expression using non-local knowledge.
3842 if (!VT.isVector() &&
3843 SimplifyDemandedBits(SDValue(N, 0)))
3844 return SDValue(N, 0);
3849 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3850 /// the shift amount is a constant.
3851 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3852 // We can't and shouldn't fold opaque constants.
3853 if (Amt->isOpaque())
3856 SDNode *LHS = N->getOperand(0).getNode();
3857 if (!LHS->hasOneUse()) return SDValue();
3859 // We want to pull some binops through shifts, so that we have (and (shift))
3860 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3861 // thing happens with address calculations, so it's important to canonicalize
3863 bool HighBitSet = false; // Can we transform this if the high bit is set?
3865 switch (LHS->getOpcode()) {
3866 default: return SDValue();
3869 HighBitSet = false; // We can only transform sra if the high bit is clear.
3872 HighBitSet = true; // We can only transform sra if the high bit is set.
3875 if (N->getOpcode() != ISD::SHL)
3876 return SDValue(); // only shl(add) not sr[al](add).
3877 HighBitSet = false; // We can only transform sra if the high bit is clear.
3881 // We require the RHS of the binop to be a constant and not opaque as well.
3882 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3883 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3885 // FIXME: disable this unless the input to the binop is a shift by a constant.
3886 // If it is not a shift, it pessimizes some common cases like:
3888 // void foo(int *X, int i) { X[i & 1235] = 1; }
3889 // int bar(int *X, int i) { return X[i & 255]; }
3890 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3891 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3892 BinOpLHSVal->getOpcode() != ISD::SRA &&
3893 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3894 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3897 EVT VT = N->getValueType(0);
3899 // If this is a signed shift right, and the high bit is modified by the
3900 // logical operation, do not perform the transformation. The highBitSet
3901 // boolean indicates the value of the high bit of the constant which would
3902 // cause it to be modified for this operation.
3903 if (N->getOpcode() == ISD::SRA) {
3904 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3905 if (BinOpRHSSignSet != HighBitSet)
3909 // Fold the constants, shifting the binop RHS by the shift amount.
3910 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3912 LHS->getOperand(1), N->getOperand(1));
3913 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3915 // Create the new shift.
3916 SDValue NewShift = DAG.getNode(N->getOpcode(),
3917 SDLoc(LHS->getOperand(0)),
3918 VT, LHS->getOperand(0), N->getOperand(1));
3920 // Create the new binop.
3921 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3924 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3925 assert(N->getOpcode() == ISD::TRUNCATE);
3926 assert(N->getOperand(0).getOpcode() == ISD::AND);
3928 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3929 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3930 SDValue N01 = N->getOperand(0).getOperand(1);
3932 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3933 EVT TruncVT = N->getValueType(0);
3934 SDValue N00 = N->getOperand(0).getOperand(0);
3935 APInt TruncC = N01C->getAPIntValue();
3936 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3938 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3939 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3940 DAG.getConstant(TruncC, TruncVT));
3947 SDValue DAGCombiner::visitRotate(SDNode *N) {
3948 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3949 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3950 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3951 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3952 if (NewOp1.getNode())
3953 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3954 N->getOperand(0), NewOp1);
3959 SDValue DAGCombiner::visitSHL(SDNode *N) {
3960 SDValue N0 = N->getOperand(0);
3961 SDValue N1 = N->getOperand(1);
3962 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3963 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3964 EVT VT = N0.getValueType();
3965 unsigned OpSizeInBits = VT.getScalarSizeInBits();
3968 if (VT.isVector()) {
3969 SDValue FoldedVOp = SimplifyVBinOp(N);
3970 if (FoldedVOp.getNode()) return FoldedVOp;
3972 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3973 // If setcc produces all-one true value then:
3974 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
3975 if (N1CV && N1CV->isConstant()) {
3976 if (N0.getOpcode() == ISD::AND &&
3977 TLI.getBooleanContents(true) ==
3978 TargetLowering::ZeroOrNegativeOneBooleanContent) {
3979 SDValue N00 = N0->getOperand(0);
3980 SDValue N01 = N0->getOperand(1);
3981 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
3983 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC) {
3984 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3986 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3989 N1C = isConstOrConstSplat(N1);
3994 // fold (shl c1, c2) -> c1<<c2
3996 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3997 // fold (shl 0, x) -> 0
3998 if (N0C && N0C->isNullValue())
4000 // fold (shl x, c >= size(x)) -> undef
4001 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4002 return DAG.getUNDEF(VT);
4003 // fold (shl x, 0) -> x
4004 if (N1C && N1C->isNullValue())
4006 // fold (shl undef, x) -> 0
4007 if (N0.getOpcode() == ISD::UNDEF)
4008 return DAG.getConstant(0, VT);
4009 // if (shl x, c) is known to be zero, return 0
4010 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4011 APInt::getAllOnesValue(OpSizeInBits)))
4012 return DAG.getConstant(0, VT);
4013 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4014 if (N1.getOpcode() == ISD::TRUNCATE &&
4015 N1.getOperand(0).getOpcode() == ISD::AND) {
4016 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4017 if (NewOp1.getNode())
4018 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4021 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4022 return SDValue(N, 0);
4024 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4025 if (N1C && N0.getOpcode() == ISD::SHL) {
4026 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4027 uint64_t c1 = N0C1->getZExtValue();
4028 uint64_t c2 = N1C->getZExtValue();
4029 if (c1 + c2 >= OpSizeInBits)
4030 return DAG.getConstant(0, VT);
4031 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4032 DAG.getConstant(c1 + c2, N1.getValueType()));
4036 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4037 // For this to be valid, the second form must not preserve any of the bits
4038 // that are shifted out by the inner shift in the first form. This means
4039 // the outer shift size must be >= the number of bits added by the ext.
4040 // As a corollary, we don't care what kind of ext it is.
4041 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4042 N0.getOpcode() == ISD::ANY_EXTEND ||
4043 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4044 N0.getOperand(0).getOpcode() == ISD::SHL) {
4045 SDValue N0Op0 = N0.getOperand(0);
4046 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4047 uint64_t c1 = N0Op0C1->getZExtValue();
4048 uint64_t c2 = N1C->getZExtValue();
4049 EVT InnerShiftVT = N0Op0.getValueType();
4050 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4051 if (c2 >= OpSizeInBits - InnerShiftSize) {
4052 if (c1 + c2 >= OpSizeInBits)
4053 return DAG.getConstant(0, VT);
4054 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4055 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4056 N0Op0->getOperand(0)),
4057 DAG.getConstant(c1 + c2, N1.getValueType()));
4062 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4063 // Only fold this if the inner zext has no other uses to avoid increasing
4064 // the total number of instructions.
4065 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4066 N0.getOperand(0).getOpcode() == ISD::SRL) {
4067 SDValue N0Op0 = N0.getOperand(0);
4068 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4069 uint64_t c1 = N0Op0C1->getZExtValue();
4070 if (c1 < VT.getScalarSizeInBits()) {
4071 uint64_t c2 = N1C->getZExtValue();
4073 SDValue NewOp0 = N0.getOperand(0);
4074 EVT CountVT = NewOp0.getOperand(1).getValueType();
4075 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4076 NewOp0, DAG.getConstant(c2, CountVT));
4077 AddToWorkList(NewSHL.getNode());
4078 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4084 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4085 // (and (srl x, (sub c1, c2), MASK)
4086 // Only fold this if the inner shift has no other uses -- if it does, folding
4087 // this will increase the total number of instructions.
4088 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4089 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4090 uint64_t c1 = N0C1->getZExtValue();
4091 if (c1 < OpSizeInBits) {
4092 uint64_t c2 = N1C->getZExtValue();
4093 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4096 Mask = Mask.shl(c2 - c1);
4097 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4098 DAG.getConstant(c2 - c1, N1.getValueType()));
4100 Mask = Mask.lshr(c1 - c2);
4101 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4102 DAG.getConstant(c1 - c2, N1.getValueType()));
4104 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4105 DAG.getConstant(Mask, VT));
4109 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4110 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4111 unsigned BitSize = VT.getScalarSizeInBits();
4112 SDValue HiBitsMask =
4113 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4114 BitSize - N1C->getZExtValue()), VT);
4115 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4120 SDValue NewSHL = visitShiftByConstant(N, N1C);
4121 if (NewSHL.getNode())
4128 SDValue DAGCombiner::visitSRA(SDNode *N) {
4129 SDValue N0 = N->getOperand(0);
4130 SDValue N1 = N->getOperand(1);
4131 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4132 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4133 EVT VT = N0.getValueType();
4134 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4137 if (VT.isVector()) {
4138 SDValue FoldedVOp = SimplifyVBinOp(N);
4139 if (FoldedVOp.getNode()) return FoldedVOp;
4141 N1C = isConstOrConstSplat(N1);
4144 // fold (sra c1, c2) -> (sra c1, c2)
4146 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4147 // fold (sra 0, x) -> 0
4148 if (N0C && N0C->isNullValue())
4150 // fold (sra -1, x) -> -1
4151 if (N0C && N0C->isAllOnesValue())
4153 // fold (sra x, (setge c, size(x))) -> undef
4154 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4155 return DAG.getUNDEF(VT);
4156 // fold (sra x, 0) -> x
4157 if (N1C && N1C->isNullValue())
4159 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4161 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4162 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4163 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4165 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4166 ExtVT, VT.getVectorNumElements());
4167 if ((!LegalOperations ||
4168 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4169 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4170 N0.getOperand(0), DAG.getValueType(ExtVT));
4173 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4174 if (N1C && N0.getOpcode() == ISD::SRA) {
4175 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4176 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4177 if (Sum >= OpSizeInBits)
4178 Sum = OpSizeInBits - 1;
4179 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4180 DAG.getConstant(Sum, N1.getValueType()));
4184 // fold (sra (shl X, m), (sub result_size, n))
4185 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4186 // result_size - n != m.
4187 // If truncate is free for the target sext(shl) is likely to result in better
4189 if (N0.getOpcode() == ISD::SHL && N1C) {
4190 // Get the two constanst of the shifts, CN0 = m, CN = n.
4191 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4193 LLVMContext &Ctx = *DAG.getContext();
4194 // Determine what the truncate's result bitsize and type would be.
4195 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4198 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4200 // Determine the residual right-shift amount.
4201 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4203 // If the shift is not a no-op (in which case this should be just a sign
4204 // extend already), the truncated to type is legal, sign_extend is legal
4205 // on that type, and the truncate to that type is both legal and free,
4206 // perform the transform.
4207 if ((ShiftAmt > 0) &&
4208 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4209 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4210 TLI.isTruncateFree(VT, TruncVT)) {
4212 SDValue Amt = DAG.getConstant(ShiftAmt,
4213 getShiftAmountTy(N0.getOperand(0).getValueType()));
4214 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4215 N0.getOperand(0), Amt);
4216 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4218 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4219 N->getValueType(0), Trunc);
4224 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4225 if (N1.getOpcode() == ISD::TRUNCATE &&
4226 N1.getOperand(0).getOpcode() == ISD::AND) {
4227 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4228 if (NewOp1.getNode())
4229 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4232 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4233 // if c1 is equal to the number of bits the trunc removes
4234 if (N0.getOpcode() == ISD::TRUNCATE &&
4235 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4236 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4237 N0.getOperand(0).hasOneUse() &&
4238 N0.getOperand(0).getOperand(1).hasOneUse() &&
4240 SDValue N0Op0 = N0.getOperand(0);
4241 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4242 unsigned LargeShiftVal = LargeShift->getZExtValue();
4243 EVT LargeVT = N0Op0.getValueType();
4245 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4247 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4248 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4249 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4250 N0Op0.getOperand(0), Amt);
4251 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4256 // Simplify, based on bits shifted out of the LHS.
4257 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4258 return SDValue(N, 0);
4261 // If the sign bit is known to be zero, switch this to a SRL.
4262 if (DAG.SignBitIsZero(N0))
4263 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4266 SDValue NewSRA = visitShiftByConstant(N, N1C);
4267 if (NewSRA.getNode())
4274 SDValue DAGCombiner::visitSRL(SDNode *N) {
4275 SDValue N0 = N->getOperand(0);
4276 SDValue N1 = N->getOperand(1);
4277 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4278 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4279 EVT VT = N0.getValueType();
4280 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4283 if (VT.isVector()) {
4284 SDValue FoldedVOp = SimplifyVBinOp(N);
4285 if (FoldedVOp.getNode()) return FoldedVOp;
4287 N1C = isConstOrConstSplat(N1);
4290 // fold (srl c1, c2) -> c1 >>u c2
4292 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4293 // fold (srl 0, x) -> 0
4294 if (N0C && N0C->isNullValue())
4296 // fold (srl x, c >= size(x)) -> undef
4297 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4298 return DAG.getUNDEF(VT);
4299 // fold (srl x, 0) -> x
4300 if (N1C && N1C->isNullValue())
4302 // if (srl x, c) is known to be zero, return 0
4303 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4304 APInt::getAllOnesValue(OpSizeInBits)))
4305 return DAG.getConstant(0, VT);
4307 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4308 if (N1C && N0.getOpcode() == ISD::SRL) {
4309 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4310 uint64_t c1 = N01C->getZExtValue();
4311 uint64_t c2 = N1C->getZExtValue();
4312 if (c1 + c2 >= OpSizeInBits)
4313 return DAG.getConstant(0, VT);
4314 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4315 DAG.getConstant(c1 + c2, N1.getValueType()));
4319 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4320 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4321 N0.getOperand(0).getOpcode() == ISD::SRL &&
4322 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4324 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4325 uint64_t c2 = N1C->getZExtValue();
4326 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4327 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4328 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4329 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4330 if (c1 + OpSizeInBits == InnerShiftSize) {
4331 if (c1 + c2 >= InnerShiftSize)
4332 return DAG.getConstant(0, VT);
4333 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4334 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4335 N0.getOperand(0)->getOperand(0),
4336 DAG.getConstant(c1 + c2, ShiftCountVT)));
4340 // fold (srl (shl x, c), c) -> (and x, cst2)
4341 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4342 unsigned BitSize = N0.getScalarValueSizeInBits();
4343 if (BitSize <= 64) {
4344 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4345 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4346 DAG.getConstant(~0ULL >> ShAmt, VT));
4350 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4351 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4352 // Shifting in all undef bits?
4353 EVT SmallVT = N0.getOperand(0).getValueType();
4354 unsigned BitSize = SmallVT.getScalarSizeInBits();
4355 if (N1C->getZExtValue() >= BitSize)
4356 return DAG.getUNDEF(VT);
4358 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4359 uint64_t ShiftAmt = N1C->getZExtValue();
4360 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4362 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4363 AddToWorkList(SmallShift.getNode());
4364 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4365 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4366 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4367 DAG.getConstant(Mask, VT));
4371 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4372 // bit, which is unmodified by sra.
4373 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4374 if (N0.getOpcode() == ISD::SRA)
4375 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4378 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4379 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4380 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4381 APInt KnownZero, KnownOne;
4382 DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
4384 // If any of the input bits are KnownOne, then the input couldn't be all
4385 // zeros, thus the result of the srl will always be zero.
4386 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4388 // If all of the bits input the to ctlz node are known to be zero, then
4389 // the result of the ctlz is "32" and the result of the shift is one.
4390 APInt UnknownBits = ~KnownZero;
4391 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4393 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4394 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4395 // Okay, we know that only that the single bit specified by UnknownBits
4396 // could be set on input to the CTLZ node. If this bit is set, the SRL
4397 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4398 // to an SRL/XOR pair, which is likely to simplify more.
4399 unsigned ShAmt = UnknownBits.countTrailingZeros();
4400 SDValue Op = N0.getOperand(0);
4403 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4404 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4405 AddToWorkList(Op.getNode());
4408 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4409 Op, DAG.getConstant(1, VT));
4413 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4414 if (N1.getOpcode() == ISD::TRUNCATE &&
4415 N1.getOperand(0).getOpcode() == ISD::AND) {
4416 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4417 if (NewOp1.getNode())
4418 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4421 // fold operands of srl based on knowledge that the low bits are not
4423 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4424 return SDValue(N, 0);
4427 SDValue NewSRL = visitShiftByConstant(N, N1C);
4428 if (NewSRL.getNode())
4432 // Attempt to convert a srl of a load into a narrower zero-extending load.
4433 SDValue NarrowLoad = ReduceLoadWidth(N);
4434 if (NarrowLoad.getNode())
4437 // Here is a common situation. We want to optimize:
4440 // %b = and i32 %a, 2
4441 // %c = srl i32 %b, 1
4442 // brcond i32 %c ...
4448 // %c = setcc eq %b, 0
4451 // However when after the source operand of SRL is optimized into AND, the SRL
4452 // itself may not be optimized further. Look for it and add the BRCOND into
4454 if (N->hasOneUse()) {
4455 SDNode *Use = *N->use_begin();
4456 if (Use->getOpcode() == ISD::BRCOND)
4458 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4459 // Also look pass the truncate.
4460 Use = *Use->use_begin();
4461 if (Use->getOpcode() == ISD::BRCOND)
4469 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4470 SDValue N0 = N->getOperand(0);
4471 EVT VT = N->getValueType(0);
4473 // fold (ctlz c1) -> c2
4474 if (isa<ConstantSDNode>(N0))
4475 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4479 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4480 SDValue N0 = N->getOperand(0);
4481 EVT VT = N->getValueType(0);
4483 // fold (ctlz_zero_undef c1) -> c2
4484 if (isa<ConstantSDNode>(N0))
4485 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4489 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4490 SDValue N0 = N->getOperand(0);
4491 EVT VT = N->getValueType(0);
4493 // fold (cttz c1) -> c2
4494 if (isa<ConstantSDNode>(N0))
4495 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4499 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4500 SDValue N0 = N->getOperand(0);
4501 EVT VT = N->getValueType(0);
4503 // fold (cttz_zero_undef c1) -> c2
4504 if (isa<ConstantSDNode>(N0))
4505 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4509 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4510 SDValue N0 = N->getOperand(0);
4511 EVT VT = N->getValueType(0);
4513 // fold (ctpop c1) -> c2
4514 if (isa<ConstantSDNode>(N0))
4515 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4519 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4520 SDValue N0 = N->getOperand(0);
4521 SDValue N1 = N->getOperand(1);
4522 SDValue N2 = N->getOperand(2);
4523 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4524 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4525 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4526 EVT VT = N->getValueType(0);
4527 EVT VT0 = N0.getValueType();
4529 // fold (select C, X, X) -> X
4532 // fold (select true, X, Y) -> X
4533 if (N0C && !N0C->isNullValue())
4535 // fold (select false, X, Y) -> Y
4536 if (N0C && N0C->isNullValue())
4538 // fold (select C, 1, X) -> (or C, X)
4539 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4540 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4541 // fold (select C, 0, 1) -> (xor C, 1)
4542 if (VT.isInteger() &&
4545 TLI.getBooleanContents(false) ==
4546 TargetLowering::ZeroOrOneBooleanContent)) &&
4547 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4550 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4551 N0, DAG.getConstant(1, VT0));
4552 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4553 N0, DAG.getConstant(1, VT0));
4554 AddToWorkList(XORNode.getNode());
4556 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4557 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4559 // fold (select C, 0, X) -> (and (not C), X)
4560 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4561 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4562 AddToWorkList(NOTNode.getNode());
4563 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4565 // fold (select C, X, 1) -> (or (not C), X)
4566 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4567 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4568 AddToWorkList(NOTNode.getNode());
4569 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4571 // fold (select C, X, 0) -> (and C, X)
4572 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4573 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4574 // fold (select X, X, Y) -> (or X, Y)
4575 // fold (select X, 1, Y) -> (or X, Y)
4576 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4577 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4578 // fold (select X, Y, X) -> (and X, Y)
4579 // fold (select X, Y, 0) -> (and X, Y)
4580 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4581 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4583 // If we can fold this based on the true/false value, do so.
4584 if (SimplifySelectOps(N, N1, N2))
4585 return SDValue(N, 0); // Don't revisit N.
4587 // fold selects based on a setcc into other things, such as min/max/abs
4588 if (N0.getOpcode() == ISD::SETCC) {
4590 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4591 // having to say they don't support SELECT_CC on every type the DAG knows
4592 // about, since there is no way to mark an opcode illegal at all value types
4593 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4594 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4595 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4596 N0.getOperand(0), N0.getOperand(1),
4597 N1, N2, N0.getOperand(2));
4598 return SimplifySelect(SDLoc(N), N0, N1, N2);
4605 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4608 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4610 // Split the inputs.
4611 SDValue Lo, Hi, LL, LH, RL, RH;
4612 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4613 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4615 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4616 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4618 return std::make_pair(Lo, Hi);
4621 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4622 SDValue N0 = N->getOperand(0);
4623 SDValue N1 = N->getOperand(1);
4624 SDValue N2 = N->getOperand(2);
4627 // Canonicalize integer abs.
4628 // vselect (setg[te] X, 0), X, -X ->
4629 // vselect (setgt X, -1), X, -X ->
4630 // vselect (setl[te] X, 0), -X, X ->
4631 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4632 if (N0.getOpcode() == ISD::SETCC) {
4633 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4634 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4636 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4638 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4639 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4640 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4641 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4642 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4643 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4644 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4647 EVT VT = LHS.getValueType();
4648 SDValue Shift = DAG.getNode(
4649 ISD::SRA, DL, VT, LHS,
4650 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4651 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4652 AddToWorkList(Shift.getNode());
4653 AddToWorkList(Add.getNode());
4654 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4658 // If the VSELECT result requires splitting and the mask is provided by a
4659 // SETCC, then split both nodes and its operands before legalization. This
4660 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4661 // and enables future optimizations (e.g. min/max pattern matching on X86).
4662 if (N0.getOpcode() == ISD::SETCC) {
4663 EVT VT = N->getValueType(0);
4665 // Check if any splitting is required.
4666 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4667 TargetLowering::TypeSplitVector)
4670 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4671 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4672 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4673 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4675 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4676 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4678 // Add the new VSELECT nodes to the work list in case they need to be split
4680 AddToWorkList(Lo.getNode());
4681 AddToWorkList(Hi.getNode());
4683 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4686 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4687 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4689 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4690 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4696 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4697 SDValue N0 = N->getOperand(0);
4698 SDValue N1 = N->getOperand(1);
4699 SDValue N2 = N->getOperand(2);
4700 SDValue N3 = N->getOperand(3);
4701 SDValue N4 = N->getOperand(4);
4702 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4704 // fold select_cc lhs, rhs, x, x, cc -> x
4708 // Determine if the condition we're dealing with is constant
4709 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4710 N0, N1, CC, SDLoc(N), false);
4711 if (SCC.getNode()) {
4712 AddToWorkList(SCC.getNode());
4714 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4715 if (!SCCC->isNullValue())
4716 return N2; // cond always true -> true val
4718 return N3; // cond always false -> false val
4721 // Fold to a simpler select_cc
4722 if (SCC.getOpcode() == ISD::SETCC)
4723 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4724 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4728 // If we can fold this based on the true/false value, do so.
4729 if (SimplifySelectOps(N, N2, N3))
4730 return SDValue(N, 0); // Don't revisit N.
4732 // fold select_cc into other things, such as min/max/abs
4733 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4736 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4737 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4738 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4742 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4743 // dag node into a ConstantSDNode or a build_vector of constants.
4744 // This function is called by the DAGCombiner when visiting sext/zext/aext
4745 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4746 // Vector extends are not folded if operations are legal; this is to
4747 // avoid introducing illegal build_vector dag nodes.
4748 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4749 SelectionDAG &DAG, bool LegalTypes,
4750 bool LegalOperations) {
4751 unsigned Opcode = N->getOpcode();
4752 SDValue N0 = N->getOperand(0);
4753 EVT VT = N->getValueType(0);
4755 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4756 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4758 // fold (sext c1) -> c1
4759 // fold (zext c1) -> c1
4760 // fold (aext c1) -> c1
4761 if (isa<ConstantSDNode>(N0))
4762 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4764 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4765 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4766 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4767 EVT SVT = VT.getScalarType();
4768 if (!(VT.isVector() &&
4769 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4770 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4773 // We can fold this node into a build_vector.
4774 unsigned VTBits = SVT.getSizeInBits();
4775 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4776 unsigned ShAmt = VTBits - EVTBits;
4777 SmallVector<SDValue, 8> Elts;
4778 unsigned NumElts = N0->getNumOperands();
4781 for (unsigned i=0; i != NumElts; ++i) {
4782 SDValue Op = N0->getOperand(i);
4783 if (Op->getOpcode() == ISD::UNDEF) {
4784 Elts.push_back(DAG.getUNDEF(SVT));
4788 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4789 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4790 if (Opcode == ISD::SIGN_EXTEND)
4791 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4794 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4798 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], NumElts).getNode();
4801 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4802 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4803 // transformation. Returns true if extension are possible and the above
4804 // mentioned transformation is profitable.
4805 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4807 SmallVectorImpl<SDNode *> &ExtendNodes,
4808 const TargetLowering &TLI) {
4809 bool HasCopyToRegUses = false;
4810 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4811 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4812 UE = N0.getNode()->use_end();
4817 if (UI.getUse().getResNo() != N0.getResNo())
4819 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4820 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4821 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4822 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4823 // Sign bits will be lost after a zext.
4826 for (unsigned i = 0; i != 2; ++i) {
4827 SDValue UseOp = User->getOperand(i);
4830 if (!isa<ConstantSDNode>(UseOp))
4835 ExtendNodes.push_back(User);
4838 // If truncates aren't free and there are users we can't
4839 // extend, it isn't worthwhile.
4842 // Remember if this value is live-out.
4843 if (User->getOpcode() == ISD::CopyToReg)
4844 HasCopyToRegUses = true;
4847 if (HasCopyToRegUses) {
4848 bool BothLiveOut = false;
4849 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4851 SDUse &Use = UI.getUse();
4852 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4858 // Both unextended and extended values are live out. There had better be
4859 // a good reason for the transformation.
4860 return ExtendNodes.size();
4865 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4866 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4867 ISD::NodeType ExtType) {
4868 // Extend SetCC uses if necessary.
4869 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4870 SDNode *SetCC = SetCCs[i];
4871 SmallVector<SDValue, 4> Ops;
4873 for (unsigned j = 0; j != 2; ++j) {
4874 SDValue SOp = SetCC->getOperand(j);
4876 Ops.push_back(ExtLoad);
4878 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4881 Ops.push_back(SetCC->getOperand(2));
4882 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4883 &Ops[0], Ops.size()));
4887 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4888 SDValue N0 = N->getOperand(0);
4889 EVT VT = N->getValueType(0);
4891 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4893 return SDValue(Res, 0);
4895 // fold (sext (sext x)) -> (sext x)
4896 // fold (sext (aext x)) -> (sext x)
4897 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4898 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4901 if (N0.getOpcode() == ISD::TRUNCATE) {
4902 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4903 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4904 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4905 if (NarrowLoad.getNode()) {
4906 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4907 if (NarrowLoad.getNode() != N0.getNode()) {
4908 CombineTo(N0.getNode(), NarrowLoad);
4909 // CombineTo deleted the truncate, if needed, but not what's under it.
4912 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4915 // See if the value being truncated is already sign extended. If so, just
4916 // eliminate the trunc/sext pair.
4917 SDValue Op = N0.getOperand(0);
4918 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4919 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4920 unsigned DestBits = VT.getScalarType().getSizeInBits();
4921 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4923 if (OpBits == DestBits) {
4924 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4925 // bits, it is already ready.
4926 if (NumSignBits > DestBits-MidBits)
4928 } else if (OpBits < DestBits) {
4929 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4930 // bits, just sext from i32.
4931 if (NumSignBits > OpBits-MidBits)
4932 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4934 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4935 // bits, just truncate to i32.
4936 if (NumSignBits > OpBits-MidBits)
4937 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4940 // fold (sext (truncate x)) -> (sextinreg x).
4941 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4942 N0.getValueType())) {
4943 if (OpBits < DestBits)
4944 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4945 else if (OpBits > DestBits)
4946 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4947 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4948 DAG.getValueType(N0.getValueType()));
4952 // fold (sext (load x)) -> (sext (truncate (sextload x)))
4953 // None of the supported targets knows how to perform load and sign extend
4954 // on vectors in one instruction. We only perform this transformation on
4956 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4957 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4958 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4959 bool DoXform = true;
4960 SmallVector<SDNode*, 4> SetCCs;
4961 if (!N0.hasOneUse())
4962 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4964 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4965 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4967 LN0->getBasePtr(), N0.getValueType(),
4968 LN0->getMemOperand());
4969 CombineTo(N, ExtLoad);
4970 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4971 N0.getValueType(), ExtLoad);
4972 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4973 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4975 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4979 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4980 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4981 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4982 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4983 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4984 EVT MemVT = LN0->getMemoryVT();
4985 if ((!LegalOperations && !LN0->isVolatile()) ||
4986 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4987 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4989 LN0->getBasePtr(), MemVT,
4990 LN0->getMemOperand());
4991 CombineTo(N, ExtLoad);
4992 CombineTo(N0.getNode(),
4993 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4994 N0.getValueType(), ExtLoad),
4995 ExtLoad.getValue(1));
4996 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5000 // fold (sext (and/or/xor (load x), cst)) ->
5001 // (and/or/xor (sextload x), (sext cst))
5002 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5003 N0.getOpcode() == ISD::XOR) &&
5004 isa<LoadSDNode>(N0.getOperand(0)) &&
5005 N0.getOperand(1).getOpcode() == ISD::Constant &&
5006 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5007 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5008 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5009 if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
5010 bool DoXform = true;
5011 SmallVector<SDNode*, 4> SetCCs;
5012 if (!N0.hasOneUse())
5013 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5016 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5017 LN0->getChain(), LN0->getBasePtr(),
5019 LN0->getMemOperand());
5020 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5021 Mask = Mask.sext(VT.getSizeInBits());
5022 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5023 ExtLoad, DAG.getConstant(Mask, VT));
5024 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5025 SDLoc(N0.getOperand(0)),
5026 N0.getOperand(0).getValueType(), ExtLoad);
5028 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5029 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5031 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5036 if (N0.getOpcode() == ISD::SETCC) {
5037 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5038 // Only do this before legalize for now.
5039 if (VT.isVector() && !LegalOperations &&
5040 TLI.getBooleanContents(true) ==
5041 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5042 EVT N0VT = N0.getOperand(0).getValueType();
5043 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5044 // of the same size as the compared operands. Only optimize sext(setcc())
5045 // if this is the case.
5046 EVT SVT = getSetCCResultType(N0VT);
5048 // We know that the # elements of the results is the same as the
5049 // # elements of the compare (and the # elements of the compare result
5050 // for that matter). Check to see that they are the same size. If so,
5051 // we know that the element size of the sext'd result matches the
5052 // element size of the compare operands.
5053 if (VT.getSizeInBits() == SVT.getSizeInBits())
5054 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5056 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5058 // If the desired elements are smaller or larger than the source
5059 // elements we can use a matching integer vector type and then
5060 // truncate/sign extend
5061 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5062 if (SVT == MatchingVectorType) {
5063 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5064 N0.getOperand(0), N0.getOperand(1),
5065 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5066 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5070 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5071 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5073 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5075 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5076 NegOne, DAG.getConstant(0, VT),
5077 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5078 if (SCC.getNode()) return SCC;
5080 if (!VT.isVector()) {
5081 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5082 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5084 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5085 SDValue SetCC = DAG.getSetCC(DL,
5087 N0.getOperand(0), N0.getOperand(1), CC);
5088 EVT SelectVT = getSetCCResultType(VT);
5089 return DAG.getSelect(DL, VT,
5090 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5091 NegOne, DAG.getConstant(0, VT));
5097 // fold (sext x) -> (zext x) if the sign bit is known zero.
5098 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5099 DAG.SignBitIsZero(N0))
5100 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5105 // isTruncateOf - If N is a truncate of some other value, return true, record
5106 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5107 // This function computes KnownZero to avoid a duplicated call to
5108 // ComputeMaskedBits in the caller.
5109 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5112 if (N->getOpcode() == ISD::TRUNCATE) {
5113 Op = N->getOperand(0);
5114 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5118 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5119 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5122 SDValue Op0 = N->getOperand(0);
5123 SDValue Op1 = N->getOperand(1);
5124 assert(Op0.getValueType() == Op1.getValueType());
5126 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5127 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5128 if (COp0 && COp0->isNullValue())
5130 else if (COp1 && COp1->isNullValue())
5135 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5137 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5143 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5144 SDValue N0 = N->getOperand(0);
5145 EVT VT = N->getValueType(0);
5147 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5149 return SDValue(Res, 0);
5151 // fold (zext (zext x)) -> (zext x)
5152 // fold (zext (aext x)) -> (zext x)
5153 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5154 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5157 // fold (zext (truncate x)) -> (zext x) or
5158 // (zext (truncate x)) -> (truncate x)
5159 // This is valid when the truncated bits of x are already zero.
5160 // FIXME: We should extend this to work for vectors too.
5163 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5164 APInt TruncatedBits =
5165 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5166 APInt(Op.getValueSizeInBits(), 0) :
5167 APInt::getBitsSet(Op.getValueSizeInBits(),
5168 N0.getValueSizeInBits(),
5169 std::min(Op.getValueSizeInBits(),
5170 VT.getSizeInBits()));
5171 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5172 if (VT.bitsGT(Op.getValueType()))
5173 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5174 if (VT.bitsLT(Op.getValueType()))
5175 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5181 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5182 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5183 if (N0.getOpcode() == ISD::TRUNCATE) {
5184 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5185 if (NarrowLoad.getNode()) {
5186 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5187 if (NarrowLoad.getNode() != N0.getNode()) {
5188 CombineTo(N0.getNode(), NarrowLoad);
5189 // CombineTo deleted the truncate, if needed, but not what's under it.
5192 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5196 // fold (zext (truncate x)) -> (and x, mask)
5197 if (N0.getOpcode() == ISD::TRUNCATE &&
5198 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5200 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5201 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5202 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5203 if (NarrowLoad.getNode()) {
5204 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5205 if (NarrowLoad.getNode() != N0.getNode()) {
5206 CombineTo(N0.getNode(), NarrowLoad);
5207 // CombineTo deleted the truncate, if needed, but not what's under it.
5210 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5213 SDValue Op = N0.getOperand(0);
5214 if (Op.getValueType().bitsLT(VT)) {
5215 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5216 AddToWorkList(Op.getNode());
5217 } else if (Op.getValueType().bitsGT(VT)) {
5218 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5219 AddToWorkList(Op.getNode());
5221 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5222 N0.getValueType().getScalarType());
5225 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5226 // if either of the casts is not free.
5227 if (N0.getOpcode() == ISD::AND &&
5228 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5229 N0.getOperand(1).getOpcode() == ISD::Constant &&
5230 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5231 N0.getValueType()) ||
5232 !TLI.isZExtFree(N0.getValueType(), VT))) {
5233 SDValue X = N0.getOperand(0).getOperand(0);
5234 if (X.getValueType().bitsLT(VT)) {
5235 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5236 } else if (X.getValueType().bitsGT(VT)) {
5237 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5239 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5240 Mask = Mask.zext(VT.getSizeInBits());
5241 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5242 X, DAG.getConstant(Mask, VT));
5245 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5246 // None of the supported targets knows how to perform load and vector_zext
5247 // on vectors in one instruction. We only perform this transformation on
5249 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5250 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5251 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5252 bool DoXform = true;
5253 SmallVector<SDNode*, 4> SetCCs;
5254 if (!N0.hasOneUse())
5255 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5257 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5258 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5260 LN0->getBasePtr(), N0.getValueType(),
5261 LN0->getMemOperand());
5262 CombineTo(N, ExtLoad);
5263 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5264 N0.getValueType(), ExtLoad);
5265 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5267 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5269 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5273 // fold (zext (and/or/xor (load x), cst)) ->
5274 // (and/or/xor (zextload x), (zext cst))
5275 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5276 N0.getOpcode() == ISD::XOR) &&
5277 isa<LoadSDNode>(N0.getOperand(0)) &&
5278 N0.getOperand(1).getOpcode() == ISD::Constant &&
5279 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5280 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5281 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5282 if (LN0->getExtensionType() != ISD::SEXTLOAD) {
5283 bool DoXform = true;
5284 SmallVector<SDNode*, 4> SetCCs;
5285 if (!N0.hasOneUse())
5286 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5289 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5290 LN0->getChain(), LN0->getBasePtr(),
5292 LN0->getMemOperand());
5293 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5294 Mask = Mask.zext(VT.getSizeInBits());
5295 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5296 ExtLoad, DAG.getConstant(Mask, VT));
5297 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5298 SDLoc(N0.getOperand(0)),
5299 N0.getOperand(0).getValueType(), ExtLoad);
5301 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5302 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5304 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5309 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5310 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5311 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5312 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5313 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5314 EVT MemVT = LN0->getMemoryVT();
5315 if ((!LegalOperations && !LN0->isVolatile()) ||
5316 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5317 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5319 LN0->getBasePtr(), MemVT,
5320 LN0->getMemOperand());
5321 CombineTo(N, ExtLoad);
5322 CombineTo(N0.getNode(),
5323 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5325 ExtLoad.getValue(1));
5326 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5330 if (N0.getOpcode() == ISD::SETCC) {
5331 if (!LegalOperations && VT.isVector() &&
5332 N0.getValueType().getVectorElementType() == MVT::i1) {
5333 EVT N0VT = N0.getOperand(0).getValueType();
5334 if (getSetCCResultType(N0VT) == N0.getValueType())
5337 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5338 // Only do this before legalize for now.
5339 EVT EltVT = VT.getVectorElementType();
5340 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5341 DAG.getConstant(1, EltVT));
5342 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5343 // We know that the # elements of the results is the same as the
5344 // # elements of the compare (and the # elements of the compare result
5345 // for that matter). Check to see that they are the same size. If so,
5346 // we know that the element size of the sext'd result matches the
5347 // element size of the compare operands.
5348 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5349 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5351 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5352 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5353 &OneOps[0], OneOps.size()));
5355 // If the desired elements are smaller or larger than the source
5356 // elements we can use a matching integer vector type and then
5357 // truncate/sign extend
5358 EVT MatchingElementType =
5359 EVT::getIntegerVT(*DAG.getContext(),
5360 N0VT.getScalarType().getSizeInBits());
5361 EVT MatchingVectorType =
5362 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5363 N0VT.getVectorNumElements());
5365 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5367 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5368 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5369 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5370 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5371 &OneOps[0], OneOps.size()));
5374 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5376 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5377 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5378 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5379 if (SCC.getNode()) return SCC;
5382 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5383 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5384 isa<ConstantSDNode>(N0.getOperand(1)) &&
5385 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5387 SDValue ShAmt = N0.getOperand(1);
5388 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5389 if (N0.getOpcode() == ISD::SHL) {
5390 SDValue InnerZExt = N0.getOperand(0);
5391 // If the original shl may be shifting out bits, do not perform this
5393 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5394 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5395 if (ShAmtVal > KnownZeroBits)
5401 // Ensure that the shift amount is wide enough for the shifted value.
5402 if (VT.getSizeInBits() >= 256)
5403 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5405 return DAG.getNode(N0.getOpcode(), DL, VT,
5406 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5413 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5414 SDValue N0 = N->getOperand(0);
5415 EVT VT = N->getValueType(0);
5417 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5419 return SDValue(Res, 0);
5421 // fold (aext (aext x)) -> (aext x)
5422 // fold (aext (zext x)) -> (zext x)
5423 // fold (aext (sext x)) -> (sext x)
5424 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5425 N0.getOpcode() == ISD::ZERO_EXTEND ||
5426 N0.getOpcode() == ISD::SIGN_EXTEND)
5427 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5429 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5430 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5431 if (N0.getOpcode() == ISD::TRUNCATE) {
5432 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5433 if (NarrowLoad.getNode()) {
5434 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5435 if (NarrowLoad.getNode() != N0.getNode()) {
5436 CombineTo(N0.getNode(), NarrowLoad);
5437 // CombineTo deleted the truncate, if needed, but not what's under it.
5440 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5444 // fold (aext (truncate x))
5445 if (N0.getOpcode() == ISD::TRUNCATE) {
5446 SDValue TruncOp = N0.getOperand(0);
5447 if (TruncOp.getValueType() == VT)
5448 return TruncOp; // x iff x size == zext size.
5449 if (TruncOp.getValueType().bitsGT(VT))
5450 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5451 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5454 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5455 // if the trunc is not free.
5456 if (N0.getOpcode() == ISD::AND &&
5457 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5458 N0.getOperand(1).getOpcode() == ISD::Constant &&
5459 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5460 N0.getValueType())) {
5461 SDValue X = N0.getOperand(0).getOperand(0);
5462 if (X.getValueType().bitsLT(VT)) {
5463 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5464 } else if (X.getValueType().bitsGT(VT)) {
5465 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5467 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5468 Mask = Mask.zext(VT.getSizeInBits());
5469 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5470 X, DAG.getConstant(Mask, VT));
5473 // fold (aext (load x)) -> (aext (truncate (extload x)))
5474 // None of the supported targets knows how to perform load and any_ext
5475 // on vectors in one instruction. We only perform this transformation on
5477 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5478 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5479 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5480 bool DoXform = true;
5481 SmallVector<SDNode*, 4> SetCCs;
5482 if (!N0.hasOneUse())
5483 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5485 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5486 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5488 LN0->getBasePtr(), N0.getValueType(),
5489 LN0->getMemOperand());
5490 CombineTo(N, ExtLoad);
5491 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5492 N0.getValueType(), ExtLoad);
5493 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5494 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5496 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5500 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5501 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5502 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5503 if (N0.getOpcode() == ISD::LOAD &&
5504 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5506 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5507 EVT MemVT = LN0->getMemoryVT();
5508 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N),
5509 VT, LN0->getChain(), LN0->getBasePtr(),
5510 MemVT, LN0->getMemOperand());
5511 CombineTo(N, ExtLoad);
5512 CombineTo(N0.getNode(),
5513 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5514 N0.getValueType(), ExtLoad),
5515 ExtLoad.getValue(1));
5516 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5519 if (N0.getOpcode() == ISD::SETCC) {
5520 // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5521 // Only do this before legalize for now.
5522 if (VT.isVector() && !LegalOperations) {
5523 EVT N0VT = N0.getOperand(0).getValueType();
5524 // We know that the # elements of the results is the same as the
5525 // # elements of the compare (and the # elements of the compare result
5526 // for that matter). Check to see that they are the same size. If so,
5527 // we know that the element size of the sext'd result matches the
5528 // element size of the compare operands.
5529 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5530 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5532 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5533 // If the desired elements are smaller or larger than the source
5534 // elements we can use a matching integer vector type and then
5535 // truncate/sign extend
5537 EVT MatchingElementType =
5538 EVT::getIntegerVT(*DAG.getContext(),
5539 N0VT.getScalarType().getSizeInBits());
5540 EVT MatchingVectorType =
5541 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5542 N0VT.getVectorNumElements());
5544 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5546 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5547 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5551 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5553 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5554 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5555 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5563 /// GetDemandedBits - See if the specified operand can be simplified with the
5564 /// knowledge that only the bits specified by Mask are used. If so, return the
5565 /// simpler operand, otherwise return a null SDValue.
5566 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5567 switch (V.getOpcode()) {
5569 case ISD::Constant: {
5570 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5571 assert(CV != 0 && "Const value should be ConstSDNode.");
5572 const APInt &CVal = CV->getAPIntValue();
5573 APInt NewVal = CVal & Mask;
5575 return DAG.getConstant(NewVal, V.getValueType());
5580 // If the LHS or RHS don't contribute bits to the or, drop them.
5581 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5582 return V.getOperand(1);
5583 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5584 return V.getOperand(0);
5587 // Only look at single-use SRLs.
5588 if (!V.getNode()->hasOneUse())
5590 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5591 // See if we can recursively simplify the LHS.
5592 unsigned Amt = RHSC->getZExtValue();
5594 // Watch out for shift count overflow though.
5595 if (Amt >= Mask.getBitWidth()) break;
5596 APInt NewMask = Mask << Amt;
5597 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5598 if (SimplifyLHS.getNode())
5599 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5600 SimplifyLHS, V.getOperand(1));
5606 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5607 /// bits and then truncated to a narrower type and where N is a multiple
5608 /// of number of bits of the narrower type, transform it to a narrower load
5609 /// from address + N / num of bits of new type. If the result is to be
5610 /// extended, also fold the extension to form a extending load.
5611 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5612 unsigned Opc = N->getOpcode();
5614 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5615 SDValue N0 = N->getOperand(0);
5616 EVT VT = N->getValueType(0);
5619 // This transformation isn't valid for vector loads.
5623 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5625 if (Opc == ISD::SIGN_EXTEND_INREG) {
5626 ExtType = ISD::SEXTLOAD;
5627 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5628 } else if (Opc == ISD::SRL) {
5629 // Another special-case: SRL is basically zero-extending a narrower value.
5630 ExtType = ISD::ZEXTLOAD;
5632 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5633 if (!N01) return SDValue();
5634 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5635 VT.getSizeInBits() - N01->getZExtValue());
5637 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5640 unsigned EVTBits = ExtVT.getSizeInBits();
5642 // Do not generate loads of non-round integer types since these can
5643 // be expensive (and would be wrong if the type is not byte sized).
5644 if (!ExtVT.isRound())
5648 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5649 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5650 ShAmt = N01->getZExtValue();
5651 // Is the shift amount a multiple of size of VT?
5652 if ((ShAmt & (EVTBits-1)) == 0) {
5653 N0 = N0.getOperand(0);
5654 // Is the load width a multiple of size of VT?
5655 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5659 // At this point, we must have a load or else we can't do the transform.
5660 if (!isa<LoadSDNode>(N0)) return SDValue();
5662 // Because a SRL must be assumed to *need* to zero-extend the high bits
5663 // (as opposed to anyext the high bits), we can't combine the zextload
5664 // lowering of SRL and an sextload.
5665 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5668 // If the shift amount is larger than the input type then we're not
5669 // accessing any of the loaded bytes. If the load was a zextload/extload
5670 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5671 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5676 // If the load is shifted left (and the result isn't shifted back right),
5677 // we can fold the truncate through the shift.
5678 unsigned ShLeftAmt = 0;
5679 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5680 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5681 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5682 ShLeftAmt = N01->getZExtValue();
5683 N0 = N0.getOperand(0);
5687 // If we haven't found a load, we can't narrow it. Don't transform one with
5688 // multiple uses, this would require adding a new load.
5689 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5692 // Don't change the width of a volatile load.
5693 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5694 if (LN0->isVolatile())
5697 // Verify that we are actually reducing a load width here.
5698 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5701 // For the transform to be legal, the load must produce only two values
5702 // (the value loaded and the chain). Don't transform a pre-increment
5703 // load, for example, which produces an extra value. Otherwise the
5704 // transformation is not equivalent, and the downstream logic to replace
5705 // uses gets things wrong.
5706 if (LN0->getNumValues() > 2)
5709 // If the load that we're shrinking is an extload and we're not just
5710 // discarding the extension we can't simply shrink the load. Bail.
5711 // TODO: It would be possible to merge the extensions in some cases.
5712 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5713 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5716 EVT PtrType = N0.getOperand(1).getValueType();
5718 if (PtrType == MVT::Untyped || PtrType.isExtended())
5719 // It's not possible to generate a constant of extended or untyped type.
5722 // For big endian targets, we need to adjust the offset to the pointer to
5723 // load the correct bytes.
5724 if (TLI.isBigEndian()) {
5725 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5726 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5727 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5730 uint64_t PtrOff = ShAmt / 8;
5731 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5732 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5733 PtrType, LN0->getBasePtr(),
5734 DAG.getConstant(PtrOff, PtrType));
5735 AddToWorkList(NewPtr.getNode());
5738 if (ExtType == ISD::NON_EXTLOAD)
5739 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5740 LN0->getPointerInfo().getWithOffset(PtrOff),
5741 LN0->isVolatile(), LN0->isNonTemporal(),
5742 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5744 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5745 LN0->getPointerInfo().getWithOffset(PtrOff),
5746 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5747 NewAlign, LN0->getTBAAInfo());
5749 // Replace the old load's chain with the new load's chain.
5750 WorkListRemover DeadNodes(*this);
5751 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5753 // Shift the result left, if we've swallowed a left shift.
5754 SDValue Result = Load;
5755 if (ShLeftAmt != 0) {
5756 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5757 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5759 // If the shift amount is as large as the result size (but, presumably,
5760 // no larger than the source) then the useful bits of the result are
5761 // zero; we can't simply return the shortened shift, because the result
5762 // of that operation is undefined.
5763 if (ShLeftAmt >= VT.getSizeInBits())
5764 Result = DAG.getConstant(0, VT);
5766 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5767 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5770 // Return the new loaded value.
5774 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5775 SDValue N0 = N->getOperand(0);
5776 SDValue N1 = N->getOperand(1);
5777 EVT VT = N->getValueType(0);
5778 EVT EVT = cast<VTSDNode>(N1)->getVT();
5779 unsigned VTBits = VT.getScalarType().getSizeInBits();
5780 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5782 // fold (sext_in_reg c1) -> c1
5783 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5784 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5786 // If the input is already sign extended, just drop the extension.
5787 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5790 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5791 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5792 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5793 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5794 N0.getOperand(0), N1);
5796 // fold (sext_in_reg (sext x)) -> (sext x)
5797 // fold (sext_in_reg (aext x)) -> (sext x)
5798 // if x is small enough.
5799 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5800 SDValue N00 = N0.getOperand(0);
5801 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5802 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5803 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5806 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5807 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5808 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5810 // fold operands of sext_in_reg based on knowledge that the top bits are not
5812 if (SimplifyDemandedBits(SDValue(N, 0)))
5813 return SDValue(N, 0);
5815 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5816 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5817 SDValue NarrowLoad = ReduceLoadWidth(N);
5818 if (NarrowLoad.getNode())
5821 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5822 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5823 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5824 if (N0.getOpcode() == ISD::SRL) {
5825 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5826 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5827 // We can turn this into an SRA iff the input to the SRL is already sign
5829 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5830 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5831 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5832 N0.getOperand(0), N0.getOperand(1));
5836 // fold (sext_inreg (extload x)) -> (sextload x)
5837 if (ISD::isEXTLoad(N0.getNode()) &&
5838 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5839 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5840 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5841 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5842 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5843 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5845 LN0->getBasePtr(), EVT,
5846 LN0->getMemOperand());
5847 CombineTo(N, ExtLoad);
5848 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5849 AddToWorkList(ExtLoad.getNode());
5850 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5852 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5853 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5855 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5856 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5857 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5858 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5859 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5861 LN0->getBasePtr(), EVT,
5862 LN0->getMemOperand());
5863 CombineTo(N, ExtLoad);
5864 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5865 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5868 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5869 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5870 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5871 N0.getOperand(1), false);
5872 if (BSwap.getNode() != 0)
5873 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5877 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5878 // into a build_vector.
5879 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5880 SmallVector<SDValue, 8> Elts;
5881 unsigned NumElts = N0->getNumOperands();
5882 unsigned ShAmt = VTBits - EVTBits;
5884 for (unsigned i = 0; i != NumElts; ++i) {
5885 SDValue Op = N0->getOperand(i);
5886 if (Op->getOpcode() == ISD::UNDEF) {
5891 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5892 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5893 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5894 Op.getValueType()));
5897 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Elts[0], NumElts);
5903 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5904 SDValue N0 = N->getOperand(0);
5905 EVT VT = N->getValueType(0);
5906 bool isLE = TLI.isLittleEndian();
5909 if (N0.getValueType() == N->getValueType(0))
5911 // fold (truncate c1) -> c1
5912 if (isa<ConstantSDNode>(N0))
5913 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5914 // fold (truncate (truncate x)) -> (truncate x)
5915 if (N0.getOpcode() == ISD::TRUNCATE)
5916 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5917 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5918 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5919 N0.getOpcode() == ISD::SIGN_EXTEND ||
5920 N0.getOpcode() == ISD::ANY_EXTEND) {
5921 if (N0.getOperand(0).getValueType().bitsLT(VT))
5922 // if the source is smaller than the dest, we still need an extend
5923 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5925 if (N0.getOperand(0).getValueType().bitsGT(VT))
5926 // if the source is larger than the dest, than we just need the truncate
5927 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5928 // if the source and dest are the same type, we can drop both the extend
5929 // and the truncate.
5930 return N0.getOperand(0);
5933 // Fold extract-and-trunc into a narrow extract. For example:
5934 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5935 // i32 y = TRUNCATE(i64 x)
5937 // v16i8 b = BITCAST (v2i64 val)
5938 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5940 // Note: We only run this optimization after type legalization (which often
5941 // creates this pattern) and before operation legalization after which
5942 // we need to be more careful about the vector instructions that we generate.
5943 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5944 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
5946 EVT VecTy = N0.getOperand(0).getValueType();
5947 EVT ExTy = N0.getValueType();
5948 EVT TrTy = N->getValueType(0);
5950 unsigned NumElem = VecTy.getVectorNumElements();
5951 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5953 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5954 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5956 SDValue EltNo = N0->getOperand(1);
5957 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5958 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5959 EVT IndexTy = TLI.getVectorIdxTy();
5960 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5962 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5963 NVT, N0.getOperand(0));
5965 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5967 DAG.getConstant(Index, IndexTy));
5971 // Fold a series of buildvector, bitcast, and truncate if possible.
5973 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5974 // (2xi32 (buildvector x, y)).
5975 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5976 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5977 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5978 N0.getOperand(0).hasOneUse()) {
5980 SDValue BuildVect = N0.getOperand(0);
5981 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5982 EVT TruncVecEltTy = VT.getVectorElementType();
5984 // Check that the element types match.
5985 if (BuildVectEltTy == TruncVecEltTy) {
5986 // Now we only need to compute the offset of the truncated elements.
5987 unsigned BuildVecNumElts = BuildVect.getNumOperands();
5988 unsigned TruncVecNumElts = VT.getVectorNumElements();
5989 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5991 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5992 "Invalid number of elements");
5994 SmallVector<SDValue, 8> Opnds;
5995 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5996 Opnds.push_back(BuildVect.getOperand(i));
5998 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
6003 // See if we can simplify the input to this truncate through knowledge that
6004 // only the low bits are being used.
6005 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6006 // Currently we only perform this optimization on scalars because vectors
6007 // may have different active low bits.
6008 if (!VT.isVector()) {
6010 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6011 VT.getSizeInBits()));
6012 if (Shorter.getNode())
6013 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6015 // fold (truncate (load x)) -> (smaller load x)
6016 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6017 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6018 SDValue Reduced = ReduceLoadWidth(N);
6019 if (Reduced.getNode())
6021 // Handle the case where the load remains an extending load even
6022 // after truncation.
6023 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6024 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6025 if (!LN0->isVolatile() &&
6026 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6027 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6028 VT, LN0->getChain(), LN0->getBasePtr(),
6030 LN0->getMemOperand());
6031 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6036 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6037 // where ... are all 'undef'.
6038 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6039 SmallVector<EVT, 8> VTs;
6042 unsigned NumDefs = 0;
6044 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6045 SDValue X = N0.getOperand(i);
6046 if (X.getOpcode() != ISD::UNDEF) {
6051 // Stop if more than one members are non-undef.
6054 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6055 VT.getVectorElementType(),
6056 X.getValueType().getVectorNumElements()));
6060 return DAG.getUNDEF(VT);
6063 assert(V.getNode() && "The single defined operand is empty!");
6064 SmallVector<SDValue, 8> Opnds;
6065 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6067 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6070 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6071 AddToWorkList(NV.getNode());
6072 Opnds.push_back(NV);
6074 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
6075 &Opnds[0], Opnds.size());
6079 // Simplify the operands using demanded-bits information.
6080 if (!VT.isVector() &&
6081 SimplifyDemandedBits(SDValue(N, 0)))
6082 return SDValue(N, 0);
6087 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6088 SDValue Elt = N->getOperand(i);
6089 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6090 return Elt.getNode();
6091 return Elt.getOperand(Elt.getResNo()).getNode();
6094 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6095 /// if load locations are consecutive.
6096 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6097 assert(N->getOpcode() == ISD::BUILD_PAIR);
6099 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6100 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6101 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6102 LD1->getAddressSpace() != LD2->getAddressSpace())
6104 EVT LD1VT = LD1->getValueType(0);
6106 if (ISD::isNON_EXTLoad(LD2) &&
6108 // If both are volatile this would reduce the number of volatile loads.
6109 // If one is volatile it might be ok, but play conservative and bail out.
6110 !LD1->isVolatile() &&
6111 !LD2->isVolatile() &&
6112 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6113 unsigned Align = LD1->getAlignment();
6114 unsigned NewAlign = TLI.getDataLayout()->
6115 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6117 if (NewAlign <= Align &&
6118 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6119 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6120 LD1->getBasePtr(), LD1->getPointerInfo(),
6121 false, false, false, Align);
6127 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6128 SDValue N0 = N->getOperand(0);
6129 EVT VT = N->getValueType(0);
6131 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6132 // Only do this before legalize, since afterward the target may be depending
6133 // on the bitconvert.
6134 // First check to see if this is all constant.
6136 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6138 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6140 EVT DestEltVT = N->getValueType(0).getVectorElementType();
6141 assert(!DestEltVT.isVector() &&
6142 "Element type of vector ValueType must not be vector!");
6144 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6147 // If the input is a constant, let getNode fold it.
6148 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6149 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6150 if (Res.getNode() != N) {
6151 if (!LegalOperations ||
6152 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6155 // Folding it resulted in an illegal node, and it's too late to
6156 // do that. Clean up the old node and forego the transformation.
6157 // Ideally this won't happen very often, because instcombine
6158 // and the earlier dagcombine runs (where illegal nodes are
6159 // permitted) should have folded most of them already.
6160 DAG.DeleteNode(Res.getNode());
6164 // (conv (conv x, t1), t2) -> (conv x, t2)
6165 if (N0.getOpcode() == ISD::BITCAST)
6166 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6169 // fold (conv (load x)) -> (load (conv*)x)
6170 // If the resultant load doesn't need a higher alignment than the original!
6171 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6172 // Do not change the width of a volatile load.
6173 !cast<LoadSDNode>(N0)->isVolatile() &&
6174 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6175 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6176 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6177 unsigned Align = TLI.getDataLayout()->
6178 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6179 unsigned OrigAlign = LN0->getAlignment();
6181 if (Align <= OrigAlign) {
6182 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6183 LN0->getBasePtr(), LN0->getPointerInfo(),
6184 LN0->isVolatile(), LN0->isNonTemporal(),
6185 LN0->isInvariant(), OrigAlign,
6186 LN0->getTBAAInfo());
6188 CombineTo(N0.getNode(),
6189 DAG.getNode(ISD::BITCAST, SDLoc(N0),
6190 N0.getValueType(), Load),
6196 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6197 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6198 // This often reduces constant pool loads.
6199 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6200 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6201 N0.getNode()->hasOneUse() && VT.isInteger() &&
6202 !VT.isVector() && !N0.getValueType().isVector()) {
6203 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6205 AddToWorkList(NewConv.getNode());
6207 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6208 if (N0.getOpcode() == ISD::FNEG)
6209 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6210 NewConv, DAG.getConstant(SignBit, VT));
6211 assert(N0.getOpcode() == ISD::FABS);
6212 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6213 NewConv, DAG.getConstant(~SignBit, VT));
6216 // fold (bitconvert (fcopysign cst, x)) ->
6217 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6218 // Note that we don't handle (copysign x, cst) because this can always be
6219 // folded to an fneg or fabs.
6220 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6221 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6222 VT.isInteger() && !VT.isVector()) {
6223 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6224 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6225 if (isTypeLegal(IntXVT)) {
6226 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6227 IntXVT, N0.getOperand(1));
6228 AddToWorkList(X.getNode());
6230 // If X has a different width than the result/lhs, sext it or truncate it.
6231 unsigned VTWidth = VT.getSizeInBits();
6232 if (OrigXWidth < VTWidth) {
6233 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6234 AddToWorkList(X.getNode());
6235 } else if (OrigXWidth > VTWidth) {
6236 // To get the sign bit in the right place, we have to shift it right
6237 // before truncating.
6238 X = DAG.getNode(ISD::SRL, SDLoc(X),
6239 X.getValueType(), X,
6240 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6241 AddToWorkList(X.getNode());
6242 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6243 AddToWorkList(X.getNode());
6246 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6247 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6248 X, DAG.getConstant(SignBit, VT));
6249 AddToWorkList(X.getNode());
6251 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6252 VT, N0.getOperand(0));
6253 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6254 Cst, DAG.getConstant(~SignBit, VT));
6255 AddToWorkList(Cst.getNode());
6257 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6261 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6262 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6263 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6264 if (CombineLD.getNode())
6271 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6272 EVT VT = N->getValueType(0);
6273 return CombineConsecutiveLoads(N, VT);
6276 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6277 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
6278 /// destination element value type.
6279 SDValue DAGCombiner::
6280 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6281 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6283 // If this is already the right type, we're done.
6284 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6286 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6287 unsigned DstBitSize = DstEltVT.getSizeInBits();
6289 // If this is a conversion of N elements of one type to N elements of another
6290 // type, convert each element. This handles FP<->INT cases.
6291 if (SrcBitSize == DstBitSize) {
6292 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6293 BV->getValueType(0).getVectorNumElements());
6295 // Due to the FP element handling below calling this routine recursively,
6296 // we can end up with a scalar-to-vector node here.
6297 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6298 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6299 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6300 DstEltVT, BV->getOperand(0)));
6302 SmallVector<SDValue, 8> Ops;
6303 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6304 SDValue Op = BV->getOperand(i);
6305 // If the vector element type is not legal, the BUILD_VECTOR operands
6306 // are promoted and implicitly truncated. Make that explicit here.
6307 if (Op.getValueType() != SrcEltVT)
6308 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6309 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6311 AddToWorkList(Ops.back().getNode());
6313 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6314 &Ops[0], Ops.size());
6317 // Otherwise, we're growing or shrinking the elements. To avoid having to
6318 // handle annoying details of growing/shrinking FP values, we convert them to
6320 if (SrcEltVT.isFloatingPoint()) {
6321 // Convert the input float vector to a int vector where the elements are the
6323 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6324 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6325 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6329 // Now we know the input is an integer vector. If the output is a FP type,
6330 // convert to integer first, then to FP of the right size.
6331 if (DstEltVT.isFloatingPoint()) {
6332 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6333 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6334 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6336 // Next, convert to FP elements of the same size.
6337 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6340 // Okay, we know the src/dst types are both integers of differing types.
6341 // Handling growing first.
6342 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6343 if (SrcBitSize < DstBitSize) {
6344 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6346 SmallVector<SDValue, 8> Ops;
6347 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6348 i += NumInputsPerOutput) {
6349 bool isLE = TLI.isLittleEndian();
6350 APInt NewBits = APInt(DstBitSize, 0);
6351 bool EltIsUndef = true;
6352 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6353 // Shift the previously computed bits over.
6354 NewBits <<= SrcBitSize;
6355 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6356 if (Op.getOpcode() == ISD::UNDEF) continue;
6359 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6360 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6364 Ops.push_back(DAG.getUNDEF(DstEltVT));
6366 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6369 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6370 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6371 &Ops[0], Ops.size());
6374 // Finally, this must be the case where we are shrinking elements: each input
6375 // turns into multiple outputs.
6376 bool isS2V = ISD::isScalarToVector(BV);
6377 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6378 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6379 NumOutputsPerInput*BV->getNumOperands());
6380 SmallVector<SDValue, 8> Ops;
6382 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6383 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6384 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6385 Ops.push_back(DAG.getUNDEF(DstEltVT));
6389 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6390 getAPIntValue().zextOrTrunc(SrcBitSize);
6392 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6393 APInt ThisVal = OpVal.trunc(DstBitSize);
6394 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6395 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6396 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6397 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6399 OpVal = OpVal.lshr(DstBitSize);
6402 // For big endian targets, swap the order of the pieces of each element.
6403 if (TLI.isBigEndian())
6404 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6407 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6408 &Ops[0], Ops.size());
6411 SDValue DAGCombiner::visitFADD(SDNode *N) {
6412 SDValue N0 = N->getOperand(0);
6413 SDValue N1 = N->getOperand(1);
6414 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6415 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6416 EVT VT = N->getValueType(0);
6419 if (VT.isVector()) {
6420 SDValue FoldedVOp = SimplifyVBinOp(N);
6421 if (FoldedVOp.getNode()) return FoldedVOp;
6424 // fold (fadd c1, c2) -> c1 + c2
6426 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6427 // canonicalize constant to RHS
6428 if (N0CFP && !N1CFP)
6429 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6430 // fold (fadd A, 0) -> A
6431 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6432 N1CFP->getValueAPF().isZero())
6434 // fold (fadd A, (fneg B)) -> (fsub A, B)
6435 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6436 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6437 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6438 GetNegatedExpression(N1, DAG, LegalOperations));
6439 // fold (fadd (fneg A), B) -> (fsub B, A)
6440 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6441 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6442 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6443 GetNegatedExpression(N0, DAG, LegalOperations));
6445 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6446 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6447 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6448 isa<ConstantFPSDNode>(N0.getOperand(1)))
6449 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6450 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6451 N0.getOperand(1), N1));
6453 // No FP constant should be created after legalization as Instruction
6454 // Selection pass has hard time in dealing with FP constant.
6456 // We don't need test this condition for transformation like following, as
6457 // the DAG being transformed implies it is legal to take FP constant as
6460 // (fadd (fmul c, x), x) -> (fmul c+1, x)
6462 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6464 // If allow, fold (fadd (fneg x), x) -> 0.0
6465 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6466 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6467 return DAG.getConstantFP(0.0, VT);
6469 // If allow, fold (fadd x, (fneg x)) -> 0.0
6470 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6471 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6472 return DAG.getConstantFP(0.0, VT);
6474 // In unsafe math mode, we can fold chains of FADD's of the same value
6475 // into multiplications. This transform is not safe in general because
6476 // we are reducing the number of rounding steps.
6477 if (DAG.getTarget().Options.UnsafeFPMath &&
6478 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6480 if (N0.getOpcode() == ISD::FMUL) {
6481 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6482 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6484 // (fadd (fmul c, x), x) -> (fmul x, c+1)
6485 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6486 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6488 DAG.getConstantFP(1.0, VT));
6489 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6493 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6494 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6495 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6497 DAG.getConstantFP(1.0, VT));
6498 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6502 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6503 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6504 N1.getOperand(0) == N1.getOperand(1) &&
6505 N0.getOperand(1) == N1.getOperand(0)) {
6506 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6508 DAG.getConstantFP(2.0, VT));
6509 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6510 N0.getOperand(1), NewCFP);
6513 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6514 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6515 N1.getOperand(0) == N1.getOperand(1) &&
6516 N0.getOperand(0) == N1.getOperand(0)) {
6517 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6519 DAG.getConstantFP(2.0, VT));
6520 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6521 N0.getOperand(0), NewCFP);
6525 if (N1.getOpcode() == ISD::FMUL) {
6526 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6527 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6529 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6530 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6531 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6533 DAG.getConstantFP(1.0, VT));
6534 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6538 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6539 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6540 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6542 DAG.getConstantFP(1.0, VT));
6543 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6548 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6549 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6550 N0.getOperand(0) == N0.getOperand(1) &&
6551 N1.getOperand(1) == N0.getOperand(0)) {
6552 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6554 DAG.getConstantFP(2.0, VT));
6555 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6556 N1.getOperand(1), NewCFP);
6559 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6560 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6561 N0.getOperand(0) == N0.getOperand(1) &&
6562 N1.getOperand(0) == N0.getOperand(0)) {
6563 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6565 DAG.getConstantFP(2.0, VT));
6566 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6567 N1.getOperand(0), NewCFP);
6571 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6572 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6573 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6574 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6575 (N0.getOperand(0) == N1))
6576 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6577 N1, DAG.getConstantFP(3.0, VT));
6580 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6581 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6582 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6583 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6584 N1.getOperand(0) == N0)
6585 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6586 N0, DAG.getConstantFP(3.0, VT));
6589 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6590 if (AllowNewFpConst &&
6591 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6592 N0.getOperand(0) == N0.getOperand(1) &&
6593 N1.getOperand(0) == N1.getOperand(1) &&
6594 N0.getOperand(0) == N1.getOperand(0))
6595 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6597 DAG.getConstantFP(4.0, VT));
6600 // FADD -> FMA combines:
6601 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6602 DAG.getTarget().Options.UnsafeFPMath) &&
6603 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6604 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6606 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6607 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6608 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6609 N0.getOperand(0), N0.getOperand(1), N1);
6611 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6612 // Note: Commutes FADD operands.
6613 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6614 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6615 N1.getOperand(0), N1.getOperand(1), N0);
6621 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6622 SDValue N0 = N->getOperand(0);
6623 SDValue N1 = N->getOperand(1);
6624 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6625 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6626 EVT VT = N->getValueType(0);
6630 if (VT.isVector()) {
6631 SDValue FoldedVOp = SimplifyVBinOp(N);
6632 if (FoldedVOp.getNode()) return FoldedVOp;
6635 // fold (fsub c1, c2) -> c1-c2
6637 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6638 // fold (fsub A, 0) -> A
6639 if (DAG.getTarget().Options.UnsafeFPMath &&
6640 N1CFP && N1CFP->getValueAPF().isZero())
6642 // fold (fsub 0, B) -> -B
6643 if (DAG.getTarget().Options.UnsafeFPMath &&
6644 N0CFP && N0CFP->getValueAPF().isZero()) {
6645 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6646 return GetNegatedExpression(N1, DAG, LegalOperations);
6647 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6648 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6650 // fold (fsub A, (fneg B)) -> (fadd A, B)
6651 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6652 return DAG.getNode(ISD::FADD, dl, VT, N0,
6653 GetNegatedExpression(N1, DAG, LegalOperations));
6655 // If 'unsafe math' is enabled, fold
6656 // (fsub x, x) -> 0.0 &
6657 // (fsub x, (fadd x, y)) -> (fneg y) &
6658 // (fsub x, (fadd y, x)) -> (fneg y)
6659 if (DAG.getTarget().Options.UnsafeFPMath) {
6661 return DAG.getConstantFP(0.0f, VT);
6663 if (N1.getOpcode() == ISD::FADD) {
6664 SDValue N10 = N1->getOperand(0);
6665 SDValue N11 = N1->getOperand(1);
6667 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6668 &DAG.getTarget().Options))
6669 return GetNegatedExpression(N11, DAG, LegalOperations);
6671 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6672 &DAG.getTarget().Options))
6673 return GetNegatedExpression(N10, DAG, LegalOperations);
6677 // FSUB -> FMA combines:
6678 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6679 DAG.getTarget().Options.UnsafeFPMath) &&
6680 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6681 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6683 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6684 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6685 return DAG.getNode(ISD::FMA, dl, VT,
6686 N0.getOperand(0), N0.getOperand(1),
6687 DAG.getNode(ISD::FNEG, dl, VT, N1));
6689 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6690 // Note: Commutes FSUB operands.
6691 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6692 return DAG.getNode(ISD::FMA, dl, VT,
6693 DAG.getNode(ISD::FNEG, dl, VT,
6695 N1.getOperand(1), N0);
6697 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6698 if (N0.getOpcode() == ISD::FNEG &&
6699 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6700 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6701 SDValue N00 = N0.getOperand(0).getOperand(0);
6702 SDValue N01 = N0.getOperand(0).getOperand(1);
6703 return DAG.getNode(ISD::FMA, dl, VT,
6704 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6705 DAG.getNode(ISD::FNEG, dl, VT, N1));
6712 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6713 SDValue N0 = N->getOperand(0);
6714 SDValue N1 = N->getOperand(1);
6715 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6716 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6717 EVT VT = N->getValueType(0);
6718 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6721 if (VT.isVector()) {
6722 SDValue FoldedVOp = SimplifyVBinOp(N);
6723 if (FoldedVOp.getNode()) return FoldedVOp;
6726 // fold (fmul c1, c2) -> c1*c2
6728 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6729 // canonicalize constant to RHS
6730 if (N0CFP && !N1CFP)
6731 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6732 // fold (fmul A, 0) -> 0
6733 if (DAG.getTarget().Options.UnsafeFPMath &&
6734 N1CFP && N1CFP->getValueAPF().isZero())
6736 // fold (fmul A, 0) -> 0, vector edition.
6737 if (DAG.getTarget().Options.UnsafeFPMath &&
6738 ISD::isBuildVectorAllZeros(N1.getNode()))
6740 // fold (fmul A, 1.0) -> A
6741 if (N1CFP && N1CFP->isExactlyValue(1.0))
6743 // fold (fmul X, 2.0) -> (fadd X, X)
6744 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6745 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6746 // fold (fmul X, -1.0) -> (fneg X)
6747 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6748 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6749 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6751 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6752 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6753 &DAG.getTarget().Options)) {
6754 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6755 &DAG.getTarget().Options)) {
6756 // Both can be negated for free, check to see if at least one is cheaper
6758 if (LHSNeg == 2 || RHSNeg == 2)
6759 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6760 GetNegatedExpression(N0, DAG, LegalOperations),
6761 GetNegatedExpression(N1, DAG, LegalOperations));
6765 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6766 if (DAG.getTarget().Options.UnsafeFPMath &&
6767 N1CFP && N0.getOpcode() == ISD::FMUL &&
6768 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6769 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6770 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6771 N0.getOperand(1), N1));
6776 SDValue DAGCombiner::visitFMA(SDNode *N) {
6777 SDValue N0 = N->getOperand(0);
6778 SDValue N1 = N->getOperand(1);
6779 SDValue N2 = N->getOperand(2);
6780 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6781 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6782 EVT VT = N->getValueType(0);
6785 if (DAG.getTarget().Options.UnsafeFPMath) {
6786 if (N0CFP && N0CFP->isZero())
6788 if (N1CFP && N1CFP->isZero())
6791 if (N0CFP && N0CFP->isExactlyValue(1.0))
6792 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6793 if (N1CFP && N1CFP->isExactlyValue(1.0))
6794 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6796 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6797 if (N0CFP && !N1CFP)
6798 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6800 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6801 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6802 N2.getOpcode() == ISD::FMUL &&
6803 N0 == N2.getOperand(0) &&
6804 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6805 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6806 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6810 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6811 if (DAG.getTarget().Options.UnsafeFPMath &&
6812 N0.getOpcode() == ISD::FMUL && N1CFP &&
6813 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6814 return DAG.getNode(ISD::FMA, dl, VT,
6816 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6820 // (fma x, 1, y) -> (fadd x, y)
6821 // (fma x, -1, y) -> (fadd (fneg x), y)
6823 if (N1CFP->isExactlyValue(1.0))
6824 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6826 if (N1CFP->isExactlyValue(-1.0) &&
6827 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6828 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6829 AddToWorkList(RHSNeg.getNode());
6830 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6834 // (fma x, c, x) -> (fmul x, (c+1))
6835 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6836 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6837 DAG.getNode(ISD::FADD, dl, VT,
6838 N1, DAG.getConstantFP(1.0, VT)));
6840 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6841 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6842 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6843 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6844 DAG.getNode(ISD::FADD, dl, VT,
6845 N1, DAG.getConstantFP(-1.0, VT)));
6851 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6852 SDValue N0 = N->getOperand(0);
6853 SDValue N1 = N->getOperand(1);
6854 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6855 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6856 EVT VT = N->getValueType(0);
6857 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6860 if (VT.isVector()) {
6861 SDValue FoldedVOp = SimplifyVBinOp(N);
6862 if (FoldedVOp.getNode()) return FoldedVOp;
6865 // fold (fdiv c1, c2) -> c1/c2
6867 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6869 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6870 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6871 // Compute the reciprocal 1.0 / c2.
6872 APFloat N1APF = N1CFP->getValueAPF();
6873 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6874 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6875 // Only do the transform if the reciprocal is a legal fp immediate that
6876 // isn't too nasty (eg NaN, denormal, ...).
6877 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6878 (!LegalOperations ||
6879 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6880 // backend)... we should handle this gracefully after Legalize.
6881 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6882 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6883 TLI.isFPImmLegal(Recip, VT)))
6884 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6885 DAG.getConstantFP(Recip, VT));
6888 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6889 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6890 &DAG.getTarget().Options)) {
6891 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6892 &DAG.getTarget().Options)) {
6893 // Both can be negated for free, check to see if at least one is cheaper
6895 if (LHSNeg == 2 || RHSNeg == 2)
6896 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6897 GetNegatedExpression(N0, DAG, LegalOperations),
6898 GetNegatedExpression(N1, DAG, LegalOperations));
6905 SDValue DAGCombiner::visitFREM(SDNode *N) {
6906 SDValue N0 = N->getOperand(0);
6907 SDValue N1 = N->getOperand(1);
6908 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6909 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6910 EVT VT = N->getValueType(0);
6912 // fold (frem c1, c2) -> fmod(c1,c2)
6914 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6919 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6920 SDValue N0 = N->getOperand(0);
6921 SDValue N1 = N->getOperand(1);
6922 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6923 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6924 EVT VT = N->getValueType(0);
6926 if (N0CFP && N1CFP) // Constant fold
6927 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6930 const APFloat& V = N1CFP->getValueAPF();
6931 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6932 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6933 if (!V.isNegative()) {
6934 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6935 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6937 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6938 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6939 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6943 // copysign(fabs(x), y) -> copysign(x, y)
6944 // copysign(fneg(x), y) -> copysign(x, y)
6945 // copysign(copysign(x,z), y) -> copysign(x, y)
6946 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6947 N0.getOpcode() == ISD::FCOPYSIGN)
6948 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6949 N0.getOperand(0), N1);
6951 // copysign(x, abs(y)) -> abs(x)
6952 if (N1.getOpcode() == ISD::FABS)
6953 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6955 // copysign(x, copysign(y,z)) -> copysign(x, z)
6956 if (N1.getOpcode() == ISD::FCOPYSIGN)
6957 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6958 N0, N1.getOperand(1));
6960 // copysign(x, fp_extend(y)) -> copysign(x, y)
6961 // copysign(x, fp_round(y)) -> copysign(x, y)
6962 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6963 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6964 N0, N1.getOperand(0));
6969 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6970 SDValue N0 = N->getOperand(0);
6971 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6972 EVT VT = N->getValueType(0);
6973 EVT OpVT = N0.getValueType();
6975 // fold (sint_to_fp c1) -> c1fp
6977 // ...but only if the target supports immediate floating-point values
6978 (!LegalOperations ||
6979 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6980 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6982 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6983 // but UINT_TO_FP is legal on this target, try to convert.
6984 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6985 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6986 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6987 if (DAG.SignBitIsZero(N0))
6988 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6991 // The next optimizations are desirable only if SELECT_CC can be lowered.
6992 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6993 // having to say they don't support SELECT_CC on every type the DAG knows
6994 // about, since there is no way to mark an opcode illegal at all value types
6995 // (See also visitSELECT)
6996 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6997 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6998 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7000 (!LegalOperations ||
7001 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7003 { N0.getOperand(0), N0.getOperand(1),
7004 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7006 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
7009 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7010 // (select_cc x, y, 1.0, 0.0,, cc)
7011 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7012 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7013 (!LegalOperations ||
7014 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7016 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7017 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7018 N0.getOperand(0).getOperand(2) };
7019 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
7026 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7027 SDValue N0 = N->getOperand(0);
7028 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7029 EVT VT = N->getValueType(0);
7030 EVT OpVT = N0.getValueType();
7032 // fold (uint_to_fp c1) -> c1fp
7034 // ...but only if the target supports immediate floating-point values
7035 (!LegalOperations ||
7036 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7037 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7039 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7040 // but SINT_TO_FP is legal on this target, try to convert.
7041 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7042 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7043 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7044 if (DAG.SignBitIsZero(N0))
7045 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7048 // The next optimizations are desirable only if SELECT_CC can be lowered.
7049 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
7050 // having to say they don't support SELECT_CC on every type the DAG knows
7051 // about, since there is no way to mark an opcode illegal at all value types
7052 // (See also visitSELECT)
7053 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
7054 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7056 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7057 (!LegalOperations ||
7058 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7060 { N0.getOperand(0), N0.getOperand(1),
7061 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7063 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
7070 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7071 SDValue N0 = N->getOperand(0);
7072 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7073 EVT VT = N->getValueType(0);
7075 // fold (fp_to_sint c1fp) -> c1
7077 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7082 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7083 SDValue N0 = N->getOperand(0);
7084 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7085 EVT VT = N->getValueType(0);
7087 // fold (fp_to_uint c1fp) -> c1
7089 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7094 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7095 SDValue N0 = N->getOperand(0);
7096 SDValue N1 = N->getOperand(1);
7097 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7098 EVT VT = N->getValueType(0);
7100 // fold (fp_round c1fp) -> c1fp
7102 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7104 // fold (fp_round (fp_extend x)) -> x
7105 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7106 return N0.getOperand(0);
7108 // fold (fp_round (fp_round x)) -> (fp_round x)
7109 if (N0.getOpcode() == ISD::FP_ROUND) {
7110 // This is a value preserving truncation if both round's are.
7111 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7112 N0.getNode()->getConstantOperandVal(1) == 1;
7113 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7114 DAG.getIntPtrConstant(IsTrunc));
7117 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7118 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7119 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7120 N0.getOperand(0), N1);
7121 AddToWorkList(Tmp.getNode());
7122 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7123 Tmp, N0.getOperand(1));
7129 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7130 SDValue N0 = N->getOperand(0);
7131 EVT VT = N->getValueType(0);
7132 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7133 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7135 // fold (fp_round_inreg c1fp) -> c1fp
7136 if (N0CFP && isTypeLegal(EVT)) {
7137 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7138 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7144 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7145 SDValue N0 = N->getOperand(0);
7146 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7147 EVT VT = N->getValueType(0);
7149 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7150 if (N->hasOneUse() &&
7151 N->use_begin()->getOpcode() == ISD::FP_ROUND)
7154 // fold (fp_extend c1fp) -> c1fp
7156 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7158 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7160 if (N0.getOpcode() == ISD::FP_ROUND
7161 && N0.getNode()->getConstantOperandVal(1) == 1) {
7162 SDValue In = N0.getOperand(0);
7163 if (In.getValueType() == VT) return In;
7164 if (VT.bitsLT(In.getValueType()))
7165 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7166 In, N0.getOperand(1));
7167 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7170 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7171 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7172 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7173 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
7174 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7175 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7177 LN0->getBasePtr(), N0.getValueType(),
7178 LN0->getMemOperand());
7179 CombineTo(N, ExtLoad);
7180 CombineTo(N0.getNode(),
7181 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7182 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7183 ExtLoad.getValue(1));
7184 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7190 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7191 SDValue N0 = N->getOperand(0);
7192 EVT VT = N->getValueType(0);
7194 if (VT.isVector()) {
7195 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7196 if (FoldedVOp.getNode()) return FoldedVOp;
7199 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7200 &DAG.getTarget().Options))
7201 return GetNegatedExpression(N0, DAG, LegalOperations);
7203 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7204 // constant pool values.
7205 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7207 N0.getNode()->hasOneUse() &&
7208 N0.getOperand(0).getValueType().isInteger()) {
7209 SDValue Int = N0.getOperand(0);
7210 EVT IntVT = Int.getValueType();
7211 if (IntVT.isInteger() && !IntVT.isVector()) {
7212 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7213 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7214 AddToWorkList(Int.getNode());
7215 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7220 // (fneg (fmul c, x)) -> (fmul -c, x)
7221 if (N0.getOpcode() == ISD::FMUL) {
7222 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7224 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7226 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7233 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7234 SDValue N0 = N->getOperand(0);
7235 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7236 EVT VT = N->getValueType(0);
7238 // fold (fceil c1) -> fceil(c1)
7240 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7245 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7246 SDValue N0 = N->getOperand(0);
7247 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7248 EVT VT = N->getValueType(0);
7250 // fold (ftrunc c1) -> ftrunc(c1)
7252 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7257 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7258 SDValue N0 = N->getOperand(0);
7259 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7260 EVT VT = N->getValueType(0);
7262 // fold (ffloor c1) -> ffloor(c1)
7264 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7269 SDValue DAGCombiner::visitFABS(SDNode *N) {
7270 SDValue N0 = N->getOperand(0);
7271 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7272 EVT VT = N->getValueType(0);
7274 if (VT.isVector()) {
7275 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7276 if (FoldedVOp.getNode()) return FoldedVOp;
7279 // fold (fabs c1) -> fabs(c1)
7281 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7282 // fold (fabs (fabs x)) -> (fabs x)
7283 if (N0.getOpcode() == ISD::FABS)
7284 return N->getOperand(0);
7285 // fold (fabs (fneg x)) -> (fabs x)
7286 // fold (fabs (fcopysign x, y)) -> (fabs x)
7287 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7288 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7290 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7291 // constant pool values.
7292 if (!TLI.isFAbsFree(VT) &&
7293 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7294 N0.getOperand(0).getValueType().isInteger() &&
7295 !N0.getOperand(0).getValueType().isVector()) {
7296 SDValue Int = N0.getOperand(0);
7297 EVT IntVT = Int.getValueType();
7298 if (IntVT.isInteger() && !IntVT.isVector()) {
7299 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7300 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7301 AddToWorkList(Int.getNode());
7302 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7303 N->getValueType(0), Int);
7310 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7311 SDValue Chain = N->getOperand(0);
7312 SDValue N1 = N->getOperand(1);
7313 SDValue N2 = N->getOperand(2);
7315 // If N is a constant we could fold this into a fallthrough or unconditional
7316 // branch. However that doesn't happen very often in normal code, because
7317 // Instcombine/SimplifyCFG should have handled the available opportunities.
7318 // If we did this folding here, it would be necessary to update the
7319 // MachineBasicBlock CFG, which is awkward.
7321 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7323 if (N1.getOpcode() == ISD::SETCC &&
7324 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7325 N1.getOperand(0).getValueType())) {
7326 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7327 Chain, N1.getOperand(2),
7328 N1.getOperand(0), N1.getOperand(1), N2);
7331 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7332 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7333 (N1.getOperand(0).hasOneUse() &&
7334 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7336 if (N1.getOpcode() == ISD::TRUNCATE) {
7337 // Look pass the truncate.
7338 Trunc = N1.getNode();
7339 N1 = N1.getOperand(0);
7342 // Match this pattern so that we can generate simpler code:
7345 // %b = and i32 %a, 2
7346 // %c = srl i32 %b, 1
7347 // brcond i32 %c ...
7352 // %b = and i32 %a, 2
7353 // %c = setcc eq %b, 0
7356 // This applies only when the AND constant value has one bit set and the
7357 // SRL constant is equal to the log2 of the AND constant. The back-end is
7358 // smart enough to convert the result into a TEST/JMP sequence.
7359 SDValue Op0 = N1.getOperand(0);
7360 SDValue Op1 = N1.getOperand(1);
7362 if (Op0.getOpcode() == ISD::AND &&
7363 Op1.getOpcode() == ISD::Constant) {
7364 SDValue AndOp1 = Op0.getOperand(1);
7366 if (AndOp1.getOpcode() == ISD::Constant) {
7367 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7369 if (AndConst.isPowerOf2() &&
7370 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7372 DAG.getSetCC(SDLoc(N),
7373 getSetCCResultType(Op0.getValueType()),
7374 Op0, DAG.getConstant(0, Op0.getValueType()),
7377 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7378 MVT::Other, Chain, SetCC, N2);
7379 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7380 // will convert it back to (X & C1) >> C2.
7381 CombineTo(N, NewBRCond, false);
7382 // Truncate is dead.
7384 removeFromWorkList(Trunc);
7385 DAG.DeleteNode(Trunc);
7387 // Replace the uses of SRL with SETCC
7388 WorkListRemover DeadNodes(*this);
7389 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7390 removeFromWorkList(N1.getNode());
7391 DAG.DeleteNode(N1.getNode());
7392 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7398 // Restore N1 if the above transformation doesn't match.
7399 N1 = N->getOperand(1);
7402 // Transform br(xor(x, y)) -> br(x != y)
7403 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7404 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7405 SDNode *TheXor = N1.getNode();
7406 SDValue Op0 = TheXor->getOperand(0);
7407 SDValue Op1 = TheXor->getOperand(1);
7408 if (Op0.getOpcode() == Op1.getOpcode()) {
7409 // Avoid missing important xor optimizations.
7410 SDValue Tmp = visitXOR(TheXor);
7411 if (Tmp.getNode()) {
7412 if (Tmp.getNode() != TheXor) {
7413 DEBUG(dbgs() << "\nReplacing.8 ";
7415 dbgs() << "\nWith: ";
7416 Tmp.getNode()->dump(&DAG);
7418 WorkListRemover DeadNodes(*this);
7419 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7420 removeFromWorkList(TheXor);
7421 DAG.DeleteNode(TheXor);
7422 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7423 MVT::Other, Chain, Tmp, N2);
7426 // visitXOR has changed XOR's operands or replaced the XOR completely,
7428 return SDValue(N, 0);
7432 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7434 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7435 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7436 Op0.getOpcode() == ISD::XOR) {
7437 TheXor = Op0.getNode();
7441 EVT SetCCVT = N1.getValueType();
7443 SetCCVT = getSetCCResultType(SetCCVT);
7444 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7447 Equal ? ISD::SETEQ : ISD::SETNE);
7448 // Replace the uses of XOR with SETCC
7449 WorkListRemover DeadNodes(*this);
7450 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7451 removeFromWorkList(N1.getNode());
7452 DAG.DeleteNode(N1.getNode());
7453 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7454 MVT::Other, Chain, SetCC, N2);
7461 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7463 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7464 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7465 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7467 // If N is a constant we could fold this into a fallthrough or unconditional
7468 // branch. However that doesn't happen very often in normal code, because
7469 // Instcombine/SimplifyCFG should have handled the available opportunities.
7470 // If we did this folding here, it would be necessary to update the
7471 // MachineBasicBlock CFG, which is awkward.
7473 // Use SimplifySetCC to simplify SETCC's.
7474 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7475 CondLHS, CondRHS, CC->get(), SDLoc(N),
7477 if (Simp.getNode()) AddToWorkList(Simp.getNode());
7479 // fold to a simpler setcc
7480 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7481 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7482 N->getOperand(0), Simp.getOperand(2),
7483 Simp.getOperand(0), Simp.getOperand(1),
7489 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7490 /// uses N as its base pointer and that N may be folded in the load / store
7491 /// addressing mode.
7492 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7494 const TargetLowering &TLI) {
7496 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7497 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7499 VT = Use->getValueType(0);
7500 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7501 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7503 VT = ST->getValue().getValueType();
7507 TargetLowering::AddrMode AM;
7508 if (N->getOpcode() == ISD::ADD) {
7509 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7512 AM.BaseOffs = Offset->getSExtValue();
7516 } else if (N->getOpcode() == ISD::SUB) {
7517 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7520 AM.BaseOffs = -Offset->getSExtValue();
7527 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7530 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7531 /// pre-indexed load / store when the base pointer is an add or subtract
7532 /// and it has other uses besides the load / store. After the
7533 /// transformation, the new indexed load / store has effectively folded
7534 /// the add / subtract in and all of its other uses are redirected to the
7535 /// new load / store.
7536 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7537 if (Level < AfterLegalizeDAG)
7543 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7544 if (LD->isIndexed())
7546 VT = LD->getMemoryVT();
7547 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7548 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7550 Ptr = LD->getBasePtr();
7551 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7552 if (ST->isIndexed())
7554 VT = ST->getMemoryVT();
7555 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7556 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7558 Ptr = ST->getBasePtr();
7564 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7565 // out. There is no reason to make this a preinc/predec.
7566 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7567 Ptr.getNode()->hasOneUse())
7570 // Ask the target to do addressing mode selection.
7573 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7574 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7577 // Backends without true r+i pre-indexed forms may need to pass a
7578 // constant base with a variable offset so that constant coercion
7579 // will work with the patterns in canonical form.
7580 bool Swapped = false;
7581 if (isa<ConstantSDNode>(BasePtr)) {
7582 std::swap(BasePtr, Offset);
7586 // Don't create a indexed load / store with zero offset.
7587 if (isa<ConstantSDNode>(Offset) &&
7588 cast<ConstantSDNode>(Offset)->isNullValue())
7591 // Try turning it into a pre-indexed load / store except when:
7592 // 1) The new base ptr is a frame index.
7593 // 2) If N is a store and the new base ptr is either the same as or is a
7594 // predecessor of the value being stored.
7595 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7596 // that would create a cycle.
7597 // 4) All uses are load / store ops that use it as old base ptr.
7599 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7600 // (plus the implicit offset) to a register to preinc anyway.
7601 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7606 SDValue Val = cast<StoreSDNode>(N)->getValue();
7607 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7611 // If the offset is a constant, there may be other adds of constants that
7612 // can be folded with this one. We should do this to avoid having to keep
7613 // a copy of the original base pointer.
7614 SmallVector<SDNode *, 16> OtherUses;
7615 if (isa<ConstantSDNode>(Offset))
7616 for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7617 E = BasePtr.getNode()->use_end(); I != E; ++I) {
7619 if (Use == Ptr.getNode())
7622 if (Use->isPredecessorOf(N))
7625 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7630 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7631 if (Op1.getNode() == BasePtr.getNode())
7632 std::swap(Op0, Op1);
7633 assert(Op0.getNode() == BasePtr.getNode() &&
7634 "Use of ADD/SUB but not an operand");
7636 if (!isa<ConstantSDNode>(Op1)) {
7641 // FIXME: In some cases, we can be smarter about this.
7642 if (Op1.getValueType() != Offset.getValueType()) {
7647 OtherUses.push_back(Use);
7651 std::swap(BasePtr, Offset);
7653 // Now check for #3 and #4.
7654 bool RealUse = false;
7656 // Caches for hasPredecessorHelper
7657 SmallPtrSet<const SDNode *, 32> Visited;
7658 SmallVector<const SDNode *, 16> Worklist;
7660 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7661 E = Ptr.getNode()->use_end(); I != E; ++I) {
7665 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7668 // If Ptr may be folded in addressing mode of other use, then it's
7669 // not profitable to do this transformation.
7670 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7679 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7680 BasePtr, Offset, AM);
7682 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7683 BasePtr, Offset, AM);
7686 DEBUG(dbgs() << "\nReplacing.4 ";
7688 dbgs() << "\nWith: ";
7689 Result.getNode()->dump(&DAG);
7691 WorkListRemover DeadNodes(*this);
7693 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7694 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7696 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7699 // Finally, since the node is now dead, remove it from the graph.
7703 std::swap(BasePtr, Offset);
7705 // Replace other uses of BasePtr that can be updated to use Ptr
7706 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7707 unsigned OffsetIdx = 1;
7708 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7710 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7711 BasePtr.getNode() && "Expected BasePtr operand");
7713 // We need to replace ptr0 in the following expression:
7714 // x0 * offset0 + y0 * ptr0 = t0
7716 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7718 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7719 // indexed load/store and the expresion that needs to be re-written.
7721 // Therefore, we have:
7722 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7724 ConstantSDNode *CN =
7725 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7727 APInt Offset0 = CN->getAPIntValue();
7728 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7730 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7731 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7732 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7733 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7735 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7737 APInt CNV = Offset0;
7738 if (X0 < 0) CNV = -CNV;
7739 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7740 else CNV = CNV - Offset1;
7742 // We can now generate the new expression.
7743 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7744 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7746 SDValue NewUse = DAG.getNode(Opcode,
7747 SDLoc(OtherUses[i]),
7748 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7749 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7750 removeFromWorkList(OtherUses[i]);
7751 DAG.DeleteNode(OtherUses[i]);
7754 // Replace the uses of Ptr with uses of the updated base value.
7755 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7756 removeFromWorkList(Ptr.getNode());
7757 DAG.DeleteNode(Ptr.getNode());
7762 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7763 /// add / sub of the base pointer node into a post-indexed load / store.
7764 /// The transformation folded the add / subtract into the new indexed
7765 /// load / store effectively and all of its uses are redirected to the
7766 /// new load / store.
7767 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7768 if (Level < AfterLegalizeDAG)
7774 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7775 if (LD->isIndexed())
7777 VT = LD->getMemoryVT();
7778 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7779 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7781 Ptr = LD->getBasePtr();
7782 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7783 if (ST->isIndexed())
7785 VT = ST->getMemoryVT();
7786 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7787 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7789 Ptr = ST->getBasePtr();
7795 if (Ptr.getNode()->hasOneUse())
7798 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7799 E = Ptr.getNode()->use_end(); I != E; ++I) {
7802 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7807 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7808 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7809 // Don't create a indexed load / store with zero offset.
7810 if (isa<ConstantSDNode>(Offset) &&
7811 cast<ConstantSDNode>(Offset)->isNullValue())
7814 // Try turning it into a post-indexed load / store except when
7815 // 1) All uses are load / store ops that use it as base ptr (and
7816 // it may be folded as addressing mmode).
7817 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7818 // nor a successor of N. Otherwise, if Op is folded that would
7821 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7825 bool TryNext = false;
7826 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7827 EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
7829 if (Use == Ptr.getNode())
7832 // If all the uses are load / store addresses, then don't do the
7834 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7835 bool RealUse = false;
7836 for (SDNode::use_iterator III = Use->use_begin(),
7837 EEE = Use->use_end(); III != EEE; ++III) {
7838 SDNode *UseUse = *III;
7839 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7854 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7855 SDValue Result = isLoad
7856 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7857 BasePtr, Offset, AM)
7858 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7859 BasePtr, Offset, AM);
7862 DEBUG(dbgs() << "\nReplacing.5 ";
7864 dbgs() << "\nWith: ";
7865 Result.getNode()->dump(&DAG);
7867 WorkListRemover DeadNodes(*this);
7869 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7870 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7872 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7875 // Finally, since the node is now dead, remove it from the graph.
7878 // Replace the uses of Use with uses of the updated base value.
7879 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7880 Result.getValue(isLoad ? 1 : 0));
7881 removeFromWorkList(Op);
7891 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7892 LoadSDNode *LD = cast<LoadSDNode>(N);
7893 SDValue Chain = LD->getChain();
7894 SDValue Ptr = LD->getBasePtr();
7896 // If load is not volatile and there are no uses of the loaded value (and
7897 // the updated indexed value in case of indexed loads), change uses of the
7898 // chain value into uses of the chain input (i.e. delete the dead load).
7899 if (!LD->isVolatile()) {
7900 if (N->getValueType(1) == MVT::Other) {
7902 if (!N->hasAnyUseOfValue(0)) {
7903 // It's not safe to use the two value CombineTo variant here. e.g.
7904 // v1, chain2 = load chain1, loc
7905 // v2, chain3 = load chain2, loc
7907 // Now we replace use of chain2 with chain1. This makes the second load
7908 // isomorphic to the one we are deleting, and thus makes this load live.
7909 DEBUG(dbgs() << "\nReplacing.6 ";
7911 dbgs() << "\nWith chain: ";
7912 Chain.getNode()->dump(&DAG);
7914 WorkListRemover DeadNodes(*this);
7915 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7917 if (N->use_empty()) {
7918 removeFromWorkList(N);
7922 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7926 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7927 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7928 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7929 DEBUG(dbgs() << "\nReplacing.7 ";
7931 dbgs() << "\nWith: ";
7932 Undef.getNode()->dump(&DAG);
7933 dbgs() << " and 2 other values\n");
7934 WorkListRemover DeadNodes(*this);
7935 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7936 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7937 DAG.getUNDEF(N->getValueType(1)));
7938 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7939 removeFromWorkList(N);
7941 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7946 // If this load is directly stored, replace the load value with the stored
7948 // TODO: Handle store large -> read small portion.
7949 // TODO: Handle TRUNCSTORE/LOADEXT
7950 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7951 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7952 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7953 if (PrevST->getBasePtr() == Ptr &&
7954 PrevST->getValue().getValueType() == N->getValueType(0))
7955 return CombineTo(N, Chain.getOperand(1), Chain);
7959 // Try to infer better alignment information than the load already has.
7960 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7961 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7962 if (Align > LD->getMemOperand()->getBaseAlignment()) {
7964 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7965 LD->getValueType(0),
7966 Chain, Ptr, LD->getPointerInfo(),
7968 LD->isVolatile(), LD->isNonTemporal(), Align,
7970 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7975 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7976 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7978 if (CombinerAAOnlyFunc.getNumOccurrences() &&
7979 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
7982 if (UseAA && LD->isUnindexed()) {
7983 // Walk up chain skipping non-aliasing memory nodes.
7984 SDValue BetterChain = FindBetterChain(N, Chain);
7986 // If there is a better chain.
7987 if (Chain != BetterChain) {
7990 // Replace the chain to void dependency.
7991 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7992 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7993 BetterChain, Ptr, LD->getMemOperand());
7995 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7996 LD->getValueType(0),
7997 BetterChain, Ptr, LD->getMemoryVT(),
7998 LD->getMemOperand());
8001 // Create token factor to keep old chain connected.
8002 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8003 MVT::Other, Chain, ReplLoad.getValue(1));
8005 // Make sure the new and old chains are cleaned up.
8006 AddToWorkList(Token.getNode());
8008 // Replace uses with load result and token factor. Don't add users
8010 return CombineTo(N, ReplLoad.getValue(0), Token, false);
8014 // Try transforming N to an indexed load.
8015 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8016 return SDValue(N, 0);
8018 // Try to slice up N to more direct loads if the slices are mapped to
8019 // different register banks or pairing can take place.
8021 return SDValue(N, 0);
8027 /// \brief Helper structure used to slice a load in smaller loads.
8028 /// Basically a slice is obtained from the following sequence:
8029 /// Origin = load Ty1, Base
8030 /// Shift = srl Ty1 Origin, CstTy Amount
8031 /// Inst = trunc Shift to Ty2
8033 /// Then, it will be rewriten into:
8034 /// Slice = load SliceTy, Base + SliceOffset
8035 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8037 /// SliceTy is deduced from the number of bits that are actually used to
8039 struct LoadedSlice {
8040 /// \brief Helper structure used to compute the cost of a slice.
8042 /// Are we optimizing for code size.
8047 unsigned CrossRegisterBanksCopies;
8051 Cost(bool ForCodeSize = false)
8052 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8053 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8055 /// \brief Get the cost of one isolated slice.
8056 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8057 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8058 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8059 EVT TruncType = LS.Inst->getValueType(0);
8060 EVT LoadedType = LS.getLoadedType();
8061 if (TruncType != LoadedType &&
8062 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8066 /// \brief Account for slicing gain in the current cost.
8067 /// Slicing provide a few gains like removing a shift or a
8068 /// truncate. This method allows to grow the cost of the original
8069 /// load with the gain from this slice.
8070 void addSliceGain(const LoadedSlice &LS) {
8071 // Each slice saves a truncate.
8072 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8073 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8074 LS.Inst->getOperand(0).getValueType()))
8076 // If there is a shift amount, this slice gets rid of it.
8079 // If this slice can merge a cross register bank copy, account for it.
8080 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8081 ++CrossRegisterBanksCopies;
8084 Cost &operator+=(const Cost &RHS) {
8086 Truncates += RHS.Truncates;
8087 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8093 bool operator==(const Cost &RHS) const {
8094 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8095 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8096 ZExts == RHS.ZExts && Shift == RHS.Shift;
8099 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8101 bool operator<(const Cost &RHS) const {
8102 // Assume cross register banks copies are as expensive as loads.
8103 // FIXME: Do we want some more target hooks?
8104 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8105 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8106 // Unless we are optimizing for code size, consider the
8107 // expensive operation first.
8108 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8109 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8110 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8111 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8114 bool operator>(const Cost &RHS) const { return RHS < *this; }
8116 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8118 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8120 // The last instruction that represent the slice. This should be a
8121 // truncate instruction.
8123 // The original load instruction.
8125 // The right shift amount in bits from the original load.
8127 // The DAG from which Origin came from.
8128 // This is used to get some contextual information about legal types, etc.
8131 LoadedSlice(SDNode *Inst = NULL, LoadSDNode *Origin = NULL,
8132 unsigned Shift = 0, SelectionDAG *DAG = NULL)
8133 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8135 LoadedSlice(const LoadedSlice &LS)
8136 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8138 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8139 /// \return Result is \p BitWidth and has used bits set to 1 and
8140 /// not used bits set to 0.
8141 APInt getUsedBits() const {
8142 // Reproduce the trunc(lshr) sequence:
8143 // - Start from the truncated value.
8144 // - Zero extend to the desired bit width.
8146 assert(Origin && "No original load to compare against.");
8147 unsigned BitWidth = Origin->getValueSizeInBits(0);
8148 assert(Inst && "This slice is not bound to an instruction");
8149 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8150 "Extracted slice is bigger than the whole type!");
8151 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8152 UsedBits.setAllBits();
8153 UsedBits = UsedBits.zext(BitWidth);
8158 /// \brief Get the size of the slice to be loaded in bytes.
8159 unsigned getLoadedSize() const {
8160 unsigned SliceSize = getUsedBits().countPopulation();
8161 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8162 return SliceSize / 8;
8165 /// \brief Get the type that will be loaded for this slice.
8166 /// Note: This may not be the final type for the slice.
8167 EVT getLoadedType() const {
8168 assert(DAG && "Missing context");
8169 LLVMContext &Ctxt = *DAG->getContext();
8170 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8173 /// \brief Get the alignment of the load used for this slice.
8174 unsigned getAlignment() const {
8175 unsigned Alignment = Origin->getAlignment();
8176 unsigned Offset = getOffsetFromBase();
8178 Alignment = MinAlign(Alignment, Alignment + Offset);
8182 /// \brief Check if this slice can be rewritten with legal operations.
8183 bool isLegal() const {
8184 // An invalid slice is not legal.
8185 if (!Origin || !Inst || !DAG)
8188 // Offsets are for indexed load only, we do not handle that.
8189 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8192 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8194 // Check that the type is legal.
8195 EVT SliceType = getLoadedType();
8196 if (!TLI.isTypeLegal(SliceType))
8199 // Check that the load is legal for this type.
8200 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8203 // Check that the offset can be computed.
8204 // 1. Check its type.
8205 EVT PtrType = Origin->getBasePtr().getValueType();
8206 if (PtrType == MVT::Untyped || PtrType.isExtended())
8209 // 2. Check that it fits in the immediate.
8210 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8213 // 3. Check that the computation is legal.
8214 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8217 // Check that the zext is legal if it needs one.
8218 EVT TruncateType = Inst->getValueType(0);
8219 if (TruncateType != SliceType &&
8220 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8226 /// \brief Get the offset in bytes of this slice in the original chunk of
8228 /// \pre DAG != NULL.
8229 uint64_t getOffsetFromBase() const {
8230 assert(DAG && "Missing context.");
8232 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8233 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8234 uint64_t Offset = Shift / 8;
8235 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8236 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8237 "The size of the original loaded type is not a multiple of a"
8239 // If Offset is bigger than TySizeInBytes, it means we are loading all
8240 // zeros. This should have been optimized before in the process.
8241 assert(TySizeInBytes > Offset &&
8242 "Invalid shift amount for given loaded size");
8244 Offset = TySizeInBytes - Offset - getLoadedSize();
8248 /// \brief Generate the sequence of instructions to load the slice
8249 /// represented by this object and redirect the uses of this slice to
8250 /// this new sequence of instructions.
8251 /// \pre this->Inst && this->Origin are valid Instructions and this
8252 /// object passed the legal check: LoadedSlice::isLegal returned true.
8253 /// \return The last instruction of the sequence used to load the slice.
8254 SDValue loadSlice() const {
8255 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8256 const SDValue &OldBaseAddr = Origin->getBasePtr();
8257 SDValue BaseAddr = OldBaseAddr;
8258 // Get the offset in that chunk of bytes w.r.t. the endianess.
8259 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8260 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8262 // BaseAddr = BaseAddr + Offset.
8263 EVT ArithType = BaseAddr.getValueType();
8264 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8265 DAG->getConstant(Offset, ArithType));
8268 // Create the type of the loaded slice according to its size.
8269 EVT SliceType = getLoadedType();
8271 // Create the load for the slice.
8272 SDValue LastInst = DAG->getLoad(
8273 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8274 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8275 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8276 // If the final type is not the same as the loaded type, this means that
8277 // we have to pad with zero. Create a zero extend for that.
8278 EVT FinalType = Inst->getValueType(0);
8279 if (SliceType != FinalType)
8281 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8285 /// \brief Check if this slice can be merged with an expensive cross register
8286 /// bank copy. E.g.,
8288 /// f = bitcast i32 i to float
8289 bool canMergeExpensiveCrossRegisterBankCopy() const {
8290 if (!Inst || !Inst->hasOneUse())
8292 SDNode *Use = *Inst->use_begin();
8293 if (Use->getOpcode() != ISD::BITCAST)
8295 assert(DAG && "Missing context");
8296 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8297 EVT ResVT = Use->getValueType(0);
8298 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8299 const TargetRegisterClass *ArgRC =
8300 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8301 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8304 // At this point, we know that we perform a cross-register-bank copy.
8305 // Check if it is expensive.
8306 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8307 // Assume bitcasts are cheap, unless both register classes do not
8308 // explicitly share a common sub class.
8309 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8312 // Check if it will be merged with the load.
8313 // 1. Check the alignment constraint.
8314 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8315 ResVT.getTypeForEVT(*DAG->getContext()));
8317 if (RequiredAlignment > getAlignment())
8320 // 2. Check that the load is a legal operation for that type.
8321 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8324 // 3. Check that we do not have a zext in the way.
8325 if (Inst->getValueType(0) != getLoadedType())
8333 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8334 /// \p UsedBits looks like 0..0 1..1 0..0.
8335 static bool areUsedBitsDense(const APInt &UsedBits) {
8336 // If all the bits are one, this is dense!
8337 if (UsedBits.isAllOnesValue())
8340 // Get rid of the unused bits on the right.
8341 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8342 // Get rid of the unused bits on the left.
8343 if (NarrowedUsedBits.countLeadingZeros())
8344 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8345 // Check that the chunk of bits is completely used.
8346 return NarrowedUsedBits.isAllOnesValue();
8349 /// \brief Check whether or not \p First and \p Second are next to each other
8350 /// in memory. This means that there is no hole between the bits loaded
8351 /// by \p First and the bits loaded by \p Second.
8352 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8353 const LoadedSlice &Second) {
8354 assert(First.Origin == Second.Origin && First.Origin &&
8355 "Unable to match different memory origins.");
8356 APInt UsedBits = First.getUsedBits();
8357 assert((UsedBits & Second.getUsedBits()) == 0 &&
8358 "Slices are not supposed to overlap.");
8359 UsedBits |= Second.getUsedBits();
8360 return areUsedBitsDense(UsedBits);
8363 /// \brief Adjust the \p GlobalLSCost according to the target
8364 /// paring capabilities and the layout of the slices.
8365 /// \pre \p GlobalLSCost should account for at least as many loads as
8366 /// there is in the slices in \p LoadedSlices.
8367 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8368 LoadedSlice::Cost &GlobalLSCost) {
8369 unsigned NumberOfSlices = LoadedSlices.size();
8370 // If there is less than 2 elements, no pairing is possible.
8371 if (NumberOfSlices < 2)
8374 // Sort the slices so that elements that are likely to be next to each
8375 // other in memory are next to each other in the list.
8376 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8377 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8378 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8379 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8381 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8382 // First (resp. Second) is the first (resp. Second) potentially candidate
8383 // to be placed in a paired load.
8384 const LoadedSlice *First = NULL;
8385 const LoadedSlice *Second = NULL;
8386 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8387 // Set the beginning of the pair.
8390 Second = &LoadedSlices[CurrSlice];
8392 // If First is NULL, it means we start a new pair.
8393 // Get to the next slice.
8397 EVT LoadedType = First->getLoadedType();
8399 // If the types of the slices are different, we cannot pair them.
8400 if (LoadedType != Second->getLoadedType())
8403 // Check if the target supplies paired loads for this type.
8404 unsigned RequiredAlignment = 0;
8405 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8406 // move to the next pair, this type is hopeless.
8410 // Check if we meet the alignment requirement.
8411 if (RequiredAlignment > First->getAlignment())
8414 // Check that both loads are next to each other in memory.
8415 if (!areSlicesNextToEachOther(*First, *Second))
8418 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8419 --GlobalLSCost.Loads;
8420 // Move to the next pair.
8425 /// \brief Check the profitability of all involved LoadedSlice.
8426 /// Currently, it is considered profitable if there is exactly two
8427 /// involved slices (1) which are (2) next to each other in memory, and
8428 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8430 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8431 /// the elements themselves.
8433 /// FIXME: When the cost model will be mature enough, we can relax
8434 /// constraints (1) and (2).
8435 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8436 const APInt &UsedBits, bool ForCodeSize) {
8437 unsigned NumberOfSlices = LoadedSlices.size();
8438 if (StressLoadSlicing)
8439 return NumberOfSlices > 1;
8442 if (NumberOfSlices != 2)
8446 if (!areUsedBitsDense(UsedBits))
8450 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8451 // The original code has one big load.
8453 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8454 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8455 // Accumulate the cost of all the slices.
8456 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8457 GlobalSlicingCost += SliceCost;
8459 // Account as cost in the original configuration the gain obtained
8460 // with the current slices.
8461 OrigCost.addSliceGain(LS);
8464 // If the target supports paired load, adjust the cost accordingly.
8465 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8466 return OrigCost > GlobalSlicingCost;
8469 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8470 /// operations, split it in the various pieces being extracted.
8472 /// This sort of thing is introduced by SROA.
8473 /// This slicing takes care not to insert overlapping loads.
8474 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8475 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8476 if (Level < AfterLegalizeDAG)
8479 LoadSDNode *LD = cast<LoadSDNode>(N);
8480 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8481 !LD->getValueType(0).isInteger())
8484 // Keep track of already used bits to detect overlapping values.
8485 // In that case, we will just abort the transformation.
8486 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8488 SmallVector<LoadedSlice, 4> LoadedSlices;
8490 // Check if this load is used as several smaller chunks of bits.
8491 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8492 // of computation for each trunc.
8493 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8494 UI != UIEnd; ++UI) {
8495 // Skip the uses of the chain.
8496 if (UI.getUse().getResNo() != 0)
8502 // Check if this is a trunc(lshr).
8503 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8504 isa<ConstantSDNode>(User->getOperand(1))) {
8505 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8506 User = *User->use_begin();
8509 // At this point, User is a Truncate, iff we encountered, trunc or
8511 if (User->getOpcode() != ISD::TRUNCATE)
8514 // The width of the type must be a power of 2 and greater than 8-bits.
8515 // Otherwise the load cannot be represented in LLVM IR.
8516 // Moreover, if we shifted with a non-8-bits multiple, the slice
8517 // will be across several bytes. We do not support that.
8518 unsigned Width = User->getValueSizeInBits(0);
8519 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8522 // Build the slice for this chain of computations.
8523 LoadedSlice LS(User, LD, Shift, &DAG);
8524 APInt CurrentUsedBits = LS.getUsedBits();
8526 // Check if this slice overlaps with another.
8527 if ((CurrentUsedBits & UsedBits) != 0)
8529 // Update the bits used globally.
8530 UsedBits |= CurrentUsedBits;
8532 // Check if the new slice would be legal.
8536 // Record the slice.
8537 LoadedSlices.push_back(LS);
8540 // Abort slicing if it does not seem to be profitable.
8541 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8546 // Rewrite each chain to use an independent load.
8547 // By construction, each chain can be represented by a unique load.
8549 // Prepare the argument for the new token factor for all the slices.
8550 SmallVector<SDValue, 8> ArgChains;
8551 for (SmallVectorImpl<LoadedSlice>::const_iterator
8552 LSIt = LoadedSlices.begin(),
8553 LSItEnd = LoadedSlices.end();
8554 LSIt != LSItEnd; ++LSIt) {
8555 SDValue SliceInst = LSIt->loadSlice();
8556 CombineTo(LSIt->Inst, SliceInst, true);
8557 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8558 SliceInst = SliceInst.getOperand(0);
8559 assert(SliceInst->getOpcode() == ISD::LOAD &&
8560 "It takes more than a zext to get to the loaded slice!!");
8561 ArgChains.push_back(SliceInst.getValue(1));
8564 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8565 &ArgChains[0], ArgChains.size());
8566 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8570 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8571 /// load is having specific bytes cleared out. If so, return the byte size
8572 /// being masked out and the shift amount.
8573 static std::pair<unsigned, unsigned>
8574 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8575 std::pair<unsigned, unsigned> Result(0, 0);
8577 // Check for the structure we're looking for.
8578 if (V->getOpcode() != ISD::AND ||
8579 !isa<ConstantSDNode>(V->getOperand(1)) ||
8580 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8583 // Check the chain and pointer.
8584 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8585 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
8587 // The store should be chained directly to the load or be an operand of a
8589 if (LD == Chain.getNode())
8591 else if (Chain->getOpcode() != ISD::TokenFactor)
8592 return Result; // Fail.
8595 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8596 if (Chain->getOperand(i).getNode() == LD) {
8600 if (!isOk) return Result;
8603 // This only handles simple types.
8604 if (V.getValueType() != MVT::i16 &&
8605 V.getValueType() != MVT::i32 &&
8606 V.getValueType() != MVT::i64)
8609 // Check the constant mask. Invert it so that the bits being masked out are
8610 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8611 // follow the sign bit for uniformity.
8612 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8613 unsigned NotMaskLZ = countLeadingZeros(NotMask);
8614 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
8615 unsigned NotMaskTZ = countTrailingZeros(NotMask);
8616 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8617 if (NotMaskLZ == 64) return Result; // All zero mask.
8619 // See if we have a continuous run of bits. If so, we have 0*1+0*
8620 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8623 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8624 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8625 NotMaskLZ -= 64-V.getValueSizeInBits();
8627 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8628 switch (MaskedBytes) {
8632 default: return Result; // All one mask, or 5-byte mask.
8635 // Verify that the first bit starts at a multiple of mask so that the access
8636 // is aligned the same as the access width.
8637 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8639 Result.first = MaskedBytes;
8640 Result.second = NotMaskTZ/8;
8645 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8646 /// provides a value as specified by MaskInfo. If so, replace the specified
8647 /// store with a narrower store of truncated IVal.
8649 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8650 SDValue IVal, StoreSDNode *St,
8652 unsigned NumBytes = MaskInfo.first;
8653 unsigned ByteShift = MaskInfo.second;
8654 SelectionDAG &DAG = DC->getDAG();
8656 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8657 // that uses this. If not, this is not a replacement.
8658 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8659 ByteShift*8, (ByteShift+NumBytes)*8);
8660 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
8662 // Check that it is legal on the target to do this. It is legal if the new
8663 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8665 MVT VT = MVT::getIntegerVT(NumBytes*8);
8666 if (!DC->isTypeLegal(VT))
8669 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8670 // shifted by ByteShift and truncated down to NumBytes.
8672 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8673 DAG.getConstant(ByteShift*8,
8674 DC->getShiftAmountTy(IVal.getValueType())));
8676 // Figure out the offset for the store and the alignment of the access.
8678 unsigned NewAlign = St->getAlignment();
8680 if (DAG.getTargetLoweringInfo().isLittleEndian())
8681 StOffset = ByteShift;
8683 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8685 SDValue Ptr = St->getBasePtr();
8687 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8688 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8689 NewAlign = MinAlign(NewAlign, StOffset);
8692 // Truncate down to the new size.
8693 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8696 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8697 St->getPointerInfo().getWithOffset(StOffset),
8698 false, false, NewAlign).getNode();
8702 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8703 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8704 /// of the loaded bits, try narrowing the load and store if it would end up
8705 /// being a win for performance or code size.
8706 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8707 StoreSDNode *ST = cast<StoreSDNode>(N);
8708 if (ST->isVolatile())
8711 SDValue Chain = ST->getChain();
8712 SDValue Value = ST->getValue();
8713 SDValue Ptr = ST->getBasePtr();
8714 EVT VT = Value.getValueType();
8716 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8719 unsigned Opc = Value.getOpcode();
8721 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8722 // is a byte mask indicating a consecutive number of bytes, check to see if
8723 // Y is known to provide just those bytes. If so, we try to replace the
8724 // load + replace + store sequence with a single (narrower) store, which makes
8726 if (Opc == ISD::OR) {
8727 std::pair<unsigned, unsigned> MaskedLoad;
8728 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8729 if (MaskedLoad.first)
8730 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8731 Value.getOperand(1), ST,this))
8732 return SDValue(NewST, 0);
8734 // Or is commutative, so try swapping X and Y.
8735 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8736 if (MaskedLoad.first)
8737 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8738 Value.getOperand(0), ST,this))
8739 return SDValue(NewST, 0);
8742 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8743 Value.getOperand(1).getOpcode() != ISD::Constant)
8746 SDValue N0 = Value.getOperand(0);
8747 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8748 Chain == SDValue(N0.getNode(), 1)) {
8749 LoadSDNode *LD = cast<LoadSDNode>(N0);
8750 if (LD->getBasePtr() != Ptr ||
8751 LD->getPointerInfo().getAddrSpace() !=
8752 ST->getPointerInfo().getAddrSpace())
8755 // Find the type to narrow it the load / op / store to.
8756 SDValue N1 = Value.getOperand(1);
8757 unsigned BitWidth = N1.getValueSizeInBits();
8758 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8759 if (Opc == ISD::AND)
8760 Imm ^= APInt::getAllOnesValue(BitWidth);
8761 if (Imm == 0 || Imm.isAllOnesValue())
8763 unsigned ShAmt = Imm.countTrailingZeros();
8764 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8765 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8766 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8767 while (NewBW < BitWidth &&
8768 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8769 TLI.isNarrowingProfitable(VT, NewVT))) {
8770 NewBW = NextPowerOf2(NewBW);
8771 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8773 if (NewBW >= BitWidth)
8776 // If the lsb changed does not start at the type bitwidth boundary,
8777 // start at the previous one.
8779 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8780 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8781 std::min(BitWidth, ShAmt + NewBW));
8782 if ((Imm & Mask) == Imm) {
8783 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8784 if (Opc == ISD::AND)
8785 NewImm ^= APInt::getAllOnesValue(NewBW);
8786 uint64_t PtrOff = ShAmt / 8;
8787 // For big endian targets, we need to adjust the offset to the pointer to
8788 // load the correct bytes.
8789 if (TLI.isBigEndian())
8790 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8792 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8793 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8794 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8797 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8798 Ptr.getValueType(), Ptr,
8799 DAG.getConstant(PtrOff, Ptr.getValueType()));
8800 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8801 LD->getChain(), NewPtr,
8802 LD->getPointerInfo().getWithOffset(PtrOff),
8803 LD->isVolatile(), LD->isNonTemporal(),
8804 LD->isInvariant(), NewAlign,
8806 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8807 DAG.getConstant(NewImm, NewVT));
8808 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8810 ST->getPointerInfo().getWithOffset(PtrOff),
8811 false, false, NewAlign);
8813 AddToWorkList(NewPtr.getNode());
8814 AddToWorkList(NewLD.getNode());
8815 AddToWorkList(NewVal.getNode());
8816 WorkListRemover DeadNodes(*this);
8817 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8826 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8827 /// if the load value isn't used by any other operations, then consider
8828 /// transforming the pair to integer load / store operations if the target
8829 /// deems the transformation profitable.
8830 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8831 StoreSDNode *ST = cast<StoreSDNode>(N);
8832 SDValue Chain = ST->getChain();
8833 SDValue Value = ST->getValue();
8834 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8835 Value.hasOneUse() &&
8836 Chain == SDValue(Value.getNode(), 1)) {
8837 LoadSDNode *LD = cast<LoadSDNode>(Value);
8838 EVT VT = LD->getMemoryVT();
8839 if (!VT.isFloatingPoint() ||
8840 VT != ST->getMemoryVT() ||
8841 LD->isNonTemporal() ||
8842 ST->isNonTemporal() ||
8843 LD->getPointerInfo().getAddrSpace() != 0 ||
8844 ST->getPointerInfo().getAddrSpace() != 0)
8847 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8848 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8849 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8850 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8851 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8854 unsigned LDAlign = LD->getAlignment();
8855 unsigned STAlign = ST->getAlignment();
8856 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8857 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8858 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8861 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8862 LD->getChain(), LD->getBasePtr(),
8863 LD->getPointerInfo(),
8864 false, false, false, LDAlign);
8866 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8867 NewLD, ST->getBasePtr(),
8868 ST->getPointerInfo(),
8869 false, false, STAlign);
8871 AddToWorkList(NewLD.getNode());
8872 AddToWorkList(NewST.getNode());
8873 WorkListRemover DeadNodes(*this);
8874 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8882 /// Helper struct to parse and store a memory address as base + index + offset.
8883 /// We ignore sign extensions when it is safe to do so.
8884 /// The following two expressions are not equivalent. To differentiate we need
8885 /// to store whether there was a sign extension involved in the index
8887 /// (load (i64 add (i64 copyfromreg %c)
8888 /// (i64 signextend (add (i8 load %index)
8892 /// (load (i64 add (i64 copyfromreg %c)
8893 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8895 struct BaseIndexOffset {
8899 bool IsIndexSignExt;
8901 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8903 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8904 bool IsIndexSignExt) :
8905 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8907 bool equalBaseIndex(const BaseIndexOffset &Other) {
8908 return Other.Base == Base && Other.Index == Index &&
8909 Other.IsIndexSignExt == IsIndexSignExt;
8912 /// Parses tree in Ptr for base, index, offset addresses.
8913 static BaseIndexOffset match(SDValue Ptr) {
8914 bool IsIndexSignExt = false;
8916 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8917 // instruction, then it could be just the BASE or everything else we don't
8918 // know how to handle. Just use Ptr as BASE and give up.
8919 if (Ptr->getOpcode() != ISD::ADD)
8920 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8922 // We know that we have at least an ADD instruction. Try to pattern match
8923 // the simple case of BASE + OFFSET.
8924 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8925 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8926 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8930 // Inside a loop the current BASE pointer is calculated using an ADD and a
8931 // MUL instruction. In this case Ptr is the actual BASE pointer.
8932 // (i64 add (i64 %array_ptr)
8933 // (i64 mul (i64 %induction_var)
8934 // (i64 %element_size)))
8935 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8936 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8938 // Look at Base + Index + Offset cases.
8939 SDValue Base = Ptr->getOperand(0);
8940 SDValue IndexOffset = Ptr->getOperand(1);
8942 // Skip signextends.
8943 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8944 IndexOffset = IndexOffset->getOperand(0);
8945 IsIndexSignExt = true;
8948 // Either the case of Base + Index (no offset) or something else.
8949 if (IndexOffset->getOpcode() != ISD::ADD)
8950 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8952 // Now we have the case of Base + Index + offset.
8953 SDValue Index = IndexOffset->getOperand(0);
8954 SDValue Offset = IndexOffset->getOperand(1);
8956 if (!isa<ConstantSDNode>(Offset))
8957 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8959 // Ignore signextends.
8960 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8961 Index = Index->getOperand(0);
8962 IsIndexSignExt = true;
8963 } else IsIndexSignExt = false;
8965 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8966 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8970 /// Holds a pointer to an LSBaseSDNode as well as information on where it
8971 /// is located in a sequence of memory operations connected by a chain.
8973 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8974 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8975 // Ptr to the mem node.
8976 LSBaseSDNode *MemNode;
8977 // Offset from the base ptr.
8978 int64_t OffsetFromBase;
8979 // What is the sequence number of this mem node.
8980 // Lowest mem operand in the DAG starts at zero.
8981 unsigned SequenceNum;
8984 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8985 EVT MemVT = St->getMemoryVT();
8986 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
8987 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8988 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
8990 // Don't merge vectors into wider inputs.
8991 if (MemVT.isVector() || !MemVT.isSimple())
8994 // Perform an early exit check. Do not bother looking at stored values that
8995 // are not constants or loads.
8996 SDValue StoredVal = St->getValue();
8997 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8998 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9002 // Only look at ends of store sequences.
9003 SDValue Chain = SDValue(St, 1);
9004 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9007 // This holds the base pointer, index, and the offset in bytes from the base
9009 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9011 // We must have a base and an offset.
9012 if (!BasePtr.Base.getNode())
9015 // Do not handle stores to undef base pointers.
9016 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9019 // Save the LoadSDNodes that we find in the chain.
9020 // We need to make sure that these nodes do not interfere with
9021 // any of the store nodes.
9022 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9024 // Save the StoreSDNodes that we find in the chain.
9025 SmallVector<MemOpLink, 8> StoreNodes;
9027 // Walk up the chain and look for nodes with offsets from the same
9028 // base pointer. Stop when reaching an instruction with a different kind
9029 // or instruction which has a different base pointer.
9031 StoreSDNode *Index = St;
9033 // If the chain has more than one use, then we can't reorder the mem ops.
9034 if (Index != St && !SDValue(Index, 1)->hasOneUse())
9037 // Find the base pointer and offset for this memory node.
9038 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9040 // Check that the base pointer is the same as the original one.
9041 if (!Ptr.equalBaseIndex(BasePtr))
9044 // Check that the alignment is the same.
9045 if (Index->getAlignment() != St->getAlignment())
9048 // The memory operands must not be volatile.
9049 if (Index->isVolatile() || Index->isIndexed())
9053 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9054 if (St->isTruncatingStore())
9057 // The stored memory type must be the same.
9058 if (Index->getMemoryVT() != MemVT)
9061 // We do not allow unaligned stores because we want to prevent overriding
9063 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9066 // We found a potential memory operand to merge.
9067 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9069 // Find the next memory operand in the chain. If the next operand in the
9070 // chain is a store then move up and continue the scan with the next
9071 // memory operand. If the next operand is a load save it and use alias
9072 // information to check if it interferes with anything.
9073 SDNode *NextInChain = Index->getChain().getNode();
9075 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9076 // We found a store node. Use it for the next iteration.
9079 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9080 if (Ldn->isVolatile()) {
9085 // Save the load node for later. Continue the scan.
9086 AliasLoadNodes.push_back(Ldn);
9087 NextInChain = Ldn->getChain().getNode();
9096 // Check if there is anything to merge.
9097 if (StoreNodes.size() < 2)
9100 // Sort the memory operands according to their distance from the base pointer.
9101 std::sort(StoreNodes.begin(), StoreNodes.end(),
9102 [](MemOpLink LHS, MemOpLink RHS) {
9103 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9104 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9105 LHS.SequenceNum > RHS.SequenceNum);
9108 // Scan the memory operations on the chain and find the first non-consecutive
9109 // store memory address.
9110 unsigned LastConsecutiveStore = 0;
9111 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9112 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9114 // Check that the addresses are consecutive starting from the second
9115 // element in the list of stores.
9117 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9118 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9123 // Check if this store interferes with any of the loads that we found.
9124 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9125 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9129 // We found a load that alias with this store. Stop the sequence.
9133 // Mark this node as useful.
9134 LastConsecutiveStore = i;
9137 // The node with the lowest store address.
9138 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9140 // Store the constants into memory as one consecutive store.
9142 unsigned LastLegalType = 0;
9143 unsigned LastLegalVectorType = 0;
9144 bool NonZero = false;
9145 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9146 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9147 SDValue StoredVal = St->getValue();
9149 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9150 NonZero |= !C->isNullValue();
9151 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9152 NonZero |= !C->getConstantFPValue()->isNullValue();
9158 // Find a legal type for the constant store.
9159 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9160 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9161 if (TLI.isTypeLegal(StoreTy))
9162 LastLegalType = i+1;
9163 // Or check whether a truncstore is legal.
9164 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9165 TargetLowering::TypePromoteInteger) {
9166 EVT LegalizedStoredValueTy =
9167 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9168 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9169 LastLegalType = i+1;
9172 // Find a legal type for the vector store.
9173 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9174 if (TLI.isTypeLegal(Ty))
9175 LastLegalVectorType = i + 1;
9178 // We only use vectors if the constant is known to be zero and the
9179 // function is not marked with the noimplicitfloat attribute.
9180 if (NonZero || NoVectors)
9181 LastLegalVectorType = 0;
9183 // Check if we found a legal integer type to store.
9184 if (LastLegalType == 0 && LastLegalVectorType == 0)
9187 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9188 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9190 // Make sure we have something to merge.
9194 unsigned EarliestNodeUsed = 0;
9195 for (unsigned i=0; i < NumElem; ++i) {
9196 // Find a chain for the new wide-store operand. Notice that some
9197 // of the store nodes that we found may not be selected for inclusion
9198 // in the wide store. The chain we use needs to be the chain of the
9199 // earliest store node which is *used* and replaced by the wide store.
9200 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9201 EarliestNodeUsed = i;
9204 // The earliest Node in the DAG.
9205 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9206 SDLoc DL(StoreNodes[0].MemNode);
9210 // Find a legal type for the vector store.
9211 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9212 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9213 StoredVal = DAG.getConstant(0, Ty);
9215 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9216 APInt StoreInt(StoreBW, 0);
9218 // Construct a single integer constant which is made of the smaller
9220 bool IsLE = TLI.isLittleEndian();
9221 for (unsigned i = 0; i < NumElem ; ++i) {
9222 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9223 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9224 SDValue Val = St->getValue();
9225 StoreInt<<=ElementSizeBytes*8;
9226 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9227 StoreInt|=C->getAPIntValue().zext(StoreBW);
9228 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9229 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9231 assert(false && "Invalid constant element type");
9235 // Create the new Load and Store operations.
9236 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9237 StoredVal = DAG.getConstant(StoreInt, StoreTy);
9240 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9241 FirstInChain->getBasePtr(),
9242 FirstInChain->getPointerInfo(),
9244 FirstInChain->getAlignment());
9246 // Replace the first store with the new store
9247 CombineTo(EarliestOp, NewStore);
9248 // Erase all other stores.
9249 for (unsigned i = 0; i < NumElem ; ++i) {
9250 if (StoreNodes[i].MemNode == EarliestOp)
9252 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9253 // ReplaceAllUsesWith will replace all uses that existed when it was
9254 // called, but graph optimizations may cause new ones to appear. For
9255 // example, the case in pr14333 looks like
9257 // St's chain -> St -> another store -> X
9259 // And the only difference from St to the other store is the chain.
9260 // When we change it's chain to be St's chain they become identical,
9261 // get CSEed and the net result is that X is now a use of St.
9262 // Since we know that St is redundant, just iterate.
9263 while (!St->use_empty())
9264 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9265 removeFromWorkList(St);
9272 // Below we handle the case of multiple consecutive stores that
9273 // come from multiple consecutive loads. We merge them into a single
9274 // wide load and a single wide store.
9276 // Look for load nodes which are used by the stored values.
9277 SmallVector<MemOpLink, 8> LoadNodes;
9279 // Find acceptable loads. Loads need to have the same chain (token factor),
9280 // must not be zext, volatile, indexed, and they must be consecutive.
9281 BaseIndexOffset LdBasePtr;
9282 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9283 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9284 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9287 // Loads must only have one use.
9288 if (!Ld->hasNUsesOfValue(1, 0))
9291 // Check that the alignment is the same as the stores.
9292 if (Ld->getAlignment() != St->getAlignment())
9295 // The memory operands must not be volatile.
9296 if (Ld->isVolatile() || Ld->isIndexed())
9299 // We do not accept ext loads.
9300 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9303 // The stored memory type must be the same.
9304 if (Ld->getMemoryVT() != MemVT)
9307 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9308 // If this is not the first ptr that we check.
9309 if (LdBasePtr.Base.getNode()) {
9310 // The base ptr must be the same.
9311 if (!LdPtr.equalBaseIndex(LdBasePtr))
9314 // Check that all other base pointers are the same as this one.
9318 // We found a potential memory operand to merge.
9319 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9322 if (LoadNodes.size() < 2)
9325 // Scan the memory operations on the chain and find the first non-consecutive
9326 // load memory address. These variables hold the index in the store node
9328 unsigned LastConsecutiveLoad = 0;
9329 // This variable refers to the size and not index in the array.
9330 unsigned LastLegalVectorType = 0;
9331 unsigned LastLegalIntegerType = 0;
9332 StartAddress = LoadNodes[0].OffsetFromBase;
9333 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9334 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9335 // All loads much share the same chain.
9336 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9339 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9340 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9342 LastConsecutiveLoad = i;
9344 // Find a legal type for the vector store.
9345 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9346 if (TLI.isTypeLegal(StoreTy))
9347 LastLegalVectorType = i + 1;
9349 // Find a legal type for the integer store.
9350 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9351 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9352 if (TLI.isTypeLegal(StoreTy))
9353 LastLegalIntegerType = i + 1;
9354 // Or check whether a truncstore and extload is legal.
9355 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9356 TargetLowering::TypePromoteInteger) {
9357 EVT LegalizedStoredValueTy =
9358 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9359 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9360 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9361 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9362 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9363 LastLegalIntegerType = i+1;
9367 // Only use vector types if the vector type is larger than the integer type.
9368 // If they are the same, use integers.
9369 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9370 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9372 // We add +1 here because the LastXXX variables refer to location while
9373 // the NumElem refers to array/index size.
9374 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9375 NumElem = std::min(LastLegalType, NumElem);
9380 // The earliest Node in the DAG.
9381 unsigned EarliestNodeUsed = 0;
9382 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9383 for (unsigned i=1; i<NumElem; ++i) {
9384 // Find a chain for the new wide-store operand. Notice that some
9385 // of the store nodes that we found may not be selected for inclusion
9386 // in the wide store. The chain we use needs to be the chain of the
9387 // earliest store node which is *used* and replaced by the wide store.
9388 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9389 EarliestNodeUsed = i;
9392 // Find if it is better to use vectors or integers to load and store
9396 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9398 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9399 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9402 SDLoc LoadDL(LoadNodes[0].MemNode);
9403 SDLoc StoreDL(StoreNodes[0].MemNode);
9405 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9406 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9407 FirstLoad->getChain(),
9408 FirstLoad->getBasePtr(),
9409 FirstLoad->getPointerInfo(),
9410 false, false, false,
9411 FirstLoad->getAlignment());
9413 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9414 FirstInChain->getBasePtr(),
9415 FirstInChain->getPointerInfo(), false, false,
9416 FirstInChain->getAlignment());
9418 // Replace one of the loads with the new load.
9419 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9420 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9421 SDValue(NewLoad.getNode(), 1));
9423 // Remove the rest of the load chains.
9424 for (unsigned i = 1; i < NumElem ; ++i) {
9425 // Replace all chain users of the old load nodes with the chain of the new
9427 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9428 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9431 // Replace the first store with the new store.
9432 CombineTo(EarliestOp, NewStore);
9433 // Erase all other stores.
9434 for (unsigned i = 0; i < NumElem ; ++i) {
9435 // Remove all Store nodes.
9436 if (StoreNodes[i].MemNode == EarliestOp)
9438 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9439 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9440 removeFromWorkList(St);
9447 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9448 StoreSDNode *ST = cast<StoreSDNode>(N);
9449 SDValue Chain = ST->getChain();
9450 SDValue Value = ST->getValue();
9451 SDValue Ptr = ST->getBasePtr();
9453 // If this is a store of a bit convert, store the input value if the
9454 // resultant store does not need a higher alignment than the original.
9455 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9456 ST->isUnindexed()) {
9457 unsigned OrigAlign = ST->getAlignment();
9458 EVT SVT = Value.getOperand(0).getValueType();
9459 unsigned Align = TLI.getDataLayout()->
9460 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9461 if (Align <= OrigAlign &&
9462 ((!LegalOperations && !ST->isVolatile()) ||
9463 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9464 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9465 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9466 ST->isNonTemporal(), OrigAlign,
9470 // Turn 'store undef, Ptr' -> nothing.
9471 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9474 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9475 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9476 // NOTE: If the original store is volatile, this transform must not increase
9477 // the number of stores. For example, on x86-32 an f64 can be stored in one
9478 // processor operation but an i64 (which is not legal) requires two. So the
9479 // transform should not be done in this case.
9480 if (Value.getOpcode() != ISD::TargetConstantFP) {
9482 switch (CFP->getSimpleValueType(0).SimpleTy) {
9483 default: llvm_unreachable("Unknown FP type");
9484 case MVT::f16: // We don't do this for these yet.
9490 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9491 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9492 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9493 bitcastToAPInt().getZExtValue(), MVT::i32);
9494 return DAG.getStore(Chain, SDLoc(N), Tmp,
9495 Ptr, ST->getMemOperand());
9499 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9500 !ST->isVolatile()) ||
9501 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9502 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9503 getZExtValue(), MVT::i64);
9504 return DAG.getStore(Chain, SDLoc(N), Tmp,
9505 Ptr, ST->getMemOperand());
9508 if (!ST->isVolatile() &&
9509 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9510 // Many FP stores are not made apparent until after legalize, e.g. for
9511 // argument passing. Since this is so common, custom legalize the
9512 // 64-bit integer store into two 32-bit stores.
9513 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9514 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9515 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9516 if (TLI.isBigEndian()) std::swap(Lo, Hi);
9518 unsigned Alignment = ST->getAlignment();
9519 bool isVolatile = ST->isVolatile();
9520 bool isNonTemporal = ST->isNonTemporal();
9521 const MDNode *TBAAInfo = ST->getTBAAInfo();
9523 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9524 Ptr, ST->getPointerInfo(),
9525 isVolatile, isNonTemporal,
9526 ST->getAlignment(), TBAAInfo);
9527 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9528 DAG.getConstant(4, Ptr.getValueType()));
9529 Alignment = MinAlign(Alignment, 4U);
9530 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9531 Ptr, ST->getPointerInfo().getWithOffset(4),
9532 isVolatile, isNonTemporal,
9533 Alignment, TBAAInfo);
9534 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9543 // Try to infer better alignment information than the store already has.
9544 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9545 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9546 if (Align > ST->getAlignment())
9547 return DAG.getTruncStore(Chain, SDLoc(N), Value,
9548 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9549 ST->isVolatile(), ST->isNonTemporal(), Align,
9554 // Try transforming a pair floating point load / store ops to integer
9555 // load / store ops.
9556 SDValue NewST = TransformFPLoadStorePair(N);
9557 if (NewST.getNode())
9560 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9561 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9563 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9564 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9567 if (UseAA && ST->isUnindexed()) {
9568 // Walk up chain skipping non-aliasing memory nodes.
9569 SDValue BetterChain = FindBetterChain(N, Chain);
9571 // If there is a better chain.
9572 if (Chain != BetterChain) {
9575 // Replace the chain to avoid dependency.
9576 if (ST->isTruncatingStore()) {
9577 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9578 ST->getMemoryVT(), ST->getMemOperand());
9580 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9581 ST->getMemOperand());
9584 // Create token to keep both nodes around.
9585 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9586 MVT::Other, Chain, ReplStore);
9588 // Make sure the new and old chains are cleaned up.
9589 AddToWorkList(Token.getNode());
9591 // Don't add users to work list.
9592 return CombineTo(N, Token, false);
9596 // Try transforming N to an indexed store.
9597 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9598 return SDValue(N, 0);
9600 // FIXME: is there such a thing as a truncating indexed store?
9601 if (ST->isTruncatingStore() && ST->isUnindexed() &&
9602 Value.getValueType().isInteger()) {
9603 // See if we can simplify the input to this truncstore with knowledge that
9604 // only the low bits are being used. For example:
9605 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
9607 GetDemandedBits(Value,
9608 APInt::getLowBitsSet(
9609 Value.getValueType().getScalarType().getSizeInBits(),
9610 ST->getMemoryVT().getScalarType().getSizeInBits()));
9611 AddToWorkList(Value.getNode());
9612 if (Shorter.getNode())
9613 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9614 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9616 // Otherwise, see if we can simplify the operation with
9617 // SimplifyDemandedBits, which only works if the value has a single use.
9618 if (SimplifyDemandedBits(Value,
9619 APInt::getLowBitsSet(
9620 Value.getValueType().getScalarType().getSizeInBits(),
9621 ST->getMemoryVT().getScalarType().getSizeInBits())))
9622 return SDValue(N, 0);
9625 // If this is a load followed by a store to the same location, then the store
9627 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9628 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9629 ST->isUnindexed() && !ST->isVolatile() &&
9630 // There can't be any side effects between the load and store, such as
9632 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9633 // The store is dead, remove it.
9638 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9639 // truncating store. We can do this even if this is already a truncstore.
9640 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9641 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9642 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9643 ST->getMemoryVT())) {
9644 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9645 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9648 // Only perform this optimization before the types are legal, because we
9649 // don't want to perform this optimization on every DAGCombine invocation.
9651 bool EverChanged = false;
9654 // There can be multiple store sequences on the same chain.
9655 // Keep trying to merge store sequences until we are unable to do so
9656 // or until we merge the last store on the chain.
9657 bool Changed = MergeConsecutiveStores(ST);
9658 EverChanged |= Changed;
9659 if (!Changed) break;
9660 } while (ST->getOpcode() != ISD::DELETED_NODE);
9663 return SDValue(N, 0);
9666 return ReduceLoadOpStoreWidth(N);
9669 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9670 SDValue InVec = N->getOperand(0);
9671 SDValue InVal = N->getOperand(1);
9672 SDValue EltNo = N->getOperand(2);
9675 // If the inserted element is an UNDEF, just use the input vector.
9676 if (InVal.getOpcode() == ISD::UNDEF)
9679 EVT VT = InVec.getValueType();
9681 // If we can't generate a legal BUILD_VECTOR, exit
9682 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9685 // Check that we know which element is being inserted
9686 if (!isa<ConstantSDNode>(EltNo))
9688 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9690 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9691 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9693 SmallVector<SDValue, 8> Ops;
9694 // Do not combine these two vectors if the output vector will not replace
9695 // the input vector.
9696 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9697 Ops.append(InVec.getNode()->op_begin(),
9698 InVec.getNode()->op_end());
9699 } else if (InVec.getOpcode() == ISD::UNDEF) {
9700 unsigned NElts = VT.getVectorNumElements();
9701 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9706 // Insert the element
9707 if (Elt < Ops.size()) {
9708 // All the operands of BUILD_VECTOR must have the same type;
9709 // we enforce that here.
9710 EVT OpVT = Ops[0].getValueType();
9711 if (InVal.getValueType() != OpVT)
9712 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9713 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9714 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9718 // Return the new vector
9719 return DAG.getNode(ISD::BUILD_VECTOR, dl,
9720 VT, &Ops[0], Ops.size());
9723 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9724 // (vextract (scalar_to_vector val, 0) -> val
9725 SDValue InVec = N->getOperand(0);
9726 EVT VT = InVec.getValueType();
9727 EVT NVT = N->getValueType(0);
9729 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9730 // Check if the result type doesn't match the inserted element type. A
9731 // SCALAR_TO_VECTOR may truncate the inserted element and the
9732 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9733 SDValue InOp = InVec.getOperand(0);
9734 if (InOp.getValueType() != NVT) {
9735 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9736 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9741 SDValue EltNo = N->getOperand(1);
9742 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9744 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9745 // We only perform this optimization before the op legalization phase because
9746 // we may introduce new vector instructions which are not backed by TD
9747 // patterns. For example on AVX, extracting elements from a wide vector
9748 // without using extract_subvector. However, if we can find an underlying
9749 // scalar value, then we can always use that.
9750 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9752 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9753 int NumElem = VT.getVectorNumElements();
9754 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9755 // Find the new index to extract from.
9756 int OrigElt = SVOp->getMaskElt(Elt);
9758 // Extracting an undef index is undef.
9760 return DAG.getUNDEF(NVT);
9762 // Select the right vector half to extract from.
9764 if (OrigElt < NumElem) {
9765 SVInVec = InVec->getOperand(0);
9767 SVInVec = InVec->getOperand(1);
9771 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9772 SDValue InOp = SVInVec.getOperand(OrigElt);
9773 if (InOp.getValueType() != NVT) {
9774 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9775 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9781 // FIXME: We should handle recursing on other vector shuffles and
9782 // scalar_to_vector here as well.
9784 if (!LegalOperations) {
9785 EVT IndexTy = TLI.getVectorIdxTy();
9786 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9787 SVInVec, DAG.getConstant(OrigElt, IndexTy));
9791 // Perform only after legalization to ensure build_vector / vector_shuffle
9792 // optimizations have already been done.
9793 if (!LegalOperations) return SDValue();
9795 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9796 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9797 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9800 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9801 bool NewLoad = false;
9802 bool BCNumEltsChanged = false;
9803 EVT ExtVT = VT.getVectorElementType();
9806 // If the result of load has to be truncated, then it's not necessarily
9808 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9811 if (InVec.getOpcode() == ISD::BITCAST) {
9812 // Don't duplicate a load with other uses.
9813 if (!InVec.hasOneUse())
9816 EVT BCVT = InVec.getOperand(0).getValueType();
9817 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9819 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9820 BCNumEltsChanged = true;
9821 InVec = InVec.getOperand(0);
9822 ExtVT = BCVT.getVectorElementType();
9826 LoadSDNode *LN0 = NULL;
9827 const ShuffleVectorSDNode *SVN = NULL;
9828 if (ISD::isNormalLoad(InVec.getNode())) {
9829 LN0 = cast<LoadSDNode>(InVec);
9830 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9831 InVec.getOperand(0).getValueType() == ExtVT &&
9832 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9833 // Don't duplicate a load with other uses.
9834 if (!InVec.hasOneUse())
9837 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9838 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9839 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9841 // (load $addr+1*size)
9843 // Don't duplicate a load with other uses.
9844 if (!InVec.hasOneUse())
9847 // If the bit convert changed the number of elements, it is unsafe
9848 // to examine the mask.
9849 if (BCNumEltsChanged)
9852 // Select the input vector, guarding against out of range extract vector.
9853 unsigned NumElems = VT.getVectorNumElements();
9854 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9855 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9857 if (InVec.getOpcode() == ISD::BITCAST) {
9858 // Don't duplicate a load with other uses.
9859 if (!InVec.hasOneUse())
9862 InVec = InVec.getOperand(0);
9864 if (ISD::isNormalLoad(InVec.getNode())) {
9865 LN0 = cast<LoadSDNode>(InVec);
9866 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9870 // Make sure we found a non-volatile load and the extractelement is
9872 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9875 // If Idx was -1 above, Elt is going to be -1, so just return undef.
9877 return DAG.getUNDEF(LVT);
9879 unsigned Align = LN0->getAlignment();
9881 // Check the resultant load doesn't need a higher alignment than the
9885 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9887 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9893 SDValue NewPtr = LN0->getBasePtr();
9894 unsigned PtrOff = 0;
9897 PtrOff = LVT.getSizeInBits() * Elt / 8;
9898 EVT PtrType = NewPtr.getValueType();
9899 if (TLI.isBigEndian())
9900 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9901 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9902 DAG.getConstant(PtrOff, PtrType));
9905 // The replacement we need to do here is a little tricky: we need to
9906 // replace an extractelement of a load with a load.
9907 // Use ReplaceAllUsesOfValuesWith to do the replacement.
9908 // Note that this replacement assumes that the extractvalue is the only
9909 // use of the load; that's okay because we don't want to perform this
9910 // transformation in other cases anyway.
9913 if (NVT.bitsGT(LVT)) {
9914 // If the result type of vextract is wider than the load, then issue an
9915 // extending load instead.
9916 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9917 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9918 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9919 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9920 LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9921 Align, LN0->getTBAAInfo());
9922 Chain = Load.getValue(1);
9924 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9925 LN0->getPointerInfo().getWithOffset(PtrOff),
9926 LN0->isVolatile(), LN0->isNonTemporal(),
9927 LN0->isInvariant(), Align, LN0->getTBAAInfo());
9928 Chain = Load.getValue(1);
9929 if (NVT.bitsLT(LVT))
9930 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
9932 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
9934 WorkListRemover DeadNodes(*this);
9935 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
9936 SDValue To[] = { Load, Chain };
9937 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9938 // Since we're explcitly calling ReplaceAllUses, add the new node to the
9939 // worklist explicitly as well.
9940 AddToWorkList(Load.getNode());
9941 AddUsersToWorkList(Load.getNode()); // Add users too
9942 // Make sure to revisit this node to clean it up; it will usually be dead.
9944 return SDValue(N, 0);
9950 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
9951 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9952 // We perform this optimization post type-legalization because
9953 // the type-legalizer often scalarizes integer-promoted vectors.
9954 // Performing this optimization before may create bit-casts which
9955 // will be type-legalized to complex code sequences.
9956 // We perform this optimization only before the operation legalizer because we
9957 // may introduce illegal operations.
9958 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9961 unsigned NumInScalars = N->getNumOperands();
9963 EVT VT = N->getValueType(0);
9965 // Check to see if this is a BUILD_VECTOR of a bunch of values
9966 // which come from any_extend or zero_extend nodes. If so, we can create
9967 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
9968 // optimizations. We do not handle sign-extend because we can't fill the sign
9970 EVT SourceType = MVT::Other;
9971 bool AllAnyExt = true;
9973 for (unsigned i = 0; i != NumInScalars; ++i) {
9974 SDValue In = N->getOperand(i);
9975 // Ignore undef inputs.
9976 if (In.getOpcode() == ISD::UNDEF) continue;
9978 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
9979 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9981 // Abort if the element is not an extension.
9982 if (!ZeroExt && !AnyExt) {
9983 SourceType = MVT::Other;
9987 // The input is a ZeroExt or AnyExt. Check the original type.
9988 EVT InTy = In.getOperand(0).getValueType();
9990 // Check that all of the widened source types are the same.
9991 if (SourceType == MVT::Other)
9994 else if (InTy != SourceType) {
9995 // Multiple income types. Abort.
9996 SourceType = MVT::Other;
10000 // Check if all of the extends are ANY_EXTENDs.
10001 AllAnyExt &= AnyExt;
10004 // In order to have valid types, all of the inputs must be extended from the
10005 // same source type and all of the inputs must be any or zero extend.
10006 // Scalar sizes must be a power of two.
10007 EVT OutScalarTy = VT.getScalarType();
10008 bool ValidTypes = SourceType != MVT::Other &&
10009 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10010 isPowerOf2_32(SourceType.getSizeInBits());
10012 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10013 // turn into a single shuffle instruction.
10017 bool isLE = TLI.isLittleEndian();
10018 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10019 assert(ElemRatio > 1 && "Invalid element size ratio");
10020 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10021 DAG.getConstant(0, SourceType);
10023 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10024 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10026 // Populate the new build_vector
10027 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10028 SDValue Cast = N->getOperand(i);
10029 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10030 Cast.getOpcode() == ISD::ZERO_EXTEND ||
10031 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10033 if (Cast.getOpcode() == ISD::UNDEF)
10034 In = DAG.getUNDEF(SourceType);
10036 In = Cast->getOperand(0);
10037 unsigned Index = isLE ? (i * ElemRatio) :
10038 (i * ElemRatio + (ElemRatio - 1));
10040 assert(Index < Ops.size() && "Invalid index");
10044 // The type of the new BUILD_VECTOR node.
10045 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10046 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10047 "Invalid vector size");
10048 // Check if the new vector type is legal.
10049 if (!isTypeLegal(VecVT)) return SDValue();
10051 // Make the new BUILD_VECTOR.
10052 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
10054 // The new BUILD_VECTOR node has the potential to be further optimized.
10055 AddToWorkList(BV.getNode());
10056 // Bitcast to the desired type.
10057 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10060 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10061 EVT VT = N->getValueType(0);
10063 unsigned NumInScalars = N->getNumOperands();
10066 EVT SrcVT = MVT::Other;
10067 unsigned Opcode = ISD::DELETED_NODE;
10068 unsigned NumDefs = 0;
10070 for (unsigned i = 0; i != NumInScalars; ++i) {
10071 SDValue In = N->getOperand(i);
10072 unsigned Opc = In.getOpcode();
10074 if (Opc == ISD::UNDEF)
10077 // If all scalar values are floats and converted from integers.
10078 if (Opcode == ISD::DELETED_NODE &&
10079 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10086 EVT InVT = In.getOperand(0).getValueType();
10088 // If all scalar values are typed differently, bail out. It's chosen to
10089 // simplify BUILD_VECTOR of integer types.
10090 if (SrcVT == MVT::Other)
10097 // If the vector has just one element defined, it's not worth to fold it into
10098 // a vectorized one.
10102 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10103 && "Should only handle conversion from integer to float.");
10104 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10106 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10108 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10111 SmallVector<SDValue, 8> Opnds;
10112 for (unsigned i = 0; i != NumInScalars; ++i) {
10113 SDValue In = N->getOperand(i);
10115 if (In.getOpcode() == ISD::UNDEF)
10116 Opnds.push_back(DAG.getUNDEF(SrcVT));
10118 Opnds.push_back(In.getOperand(0));
10120 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
10121 &Opnds[0], Opnds.size());
10122 AddToWorkList(BV.getNode());
10124 return DAG.getNode(Opcode, dl, VT, BV);
10127 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10128 unsigned NumInScalars = N->getNumOperands();
10130 EVT VT = N->getValueType(0);
10132 // A vector built entirely of undefs is undef.
10133 if (ISD::allOperandsUndef(N))
10134 return DAG.getUNDEF(VT);
10136 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10140 V = reduceBuildVecConvertToConvertBuildVec(N);
10144 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10145 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10146 // at most two distinct vectors, turn this into a shuffle node.
10148 // May only combine to shuffle after legalize if shuffle is legal.
10149 if (LegalOperations &&
10150 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10153 SDValue VecIn1, VecIn2;
10154 for (unsigned i = 0; i != NumInScalars; ++i) {
10155 // Ignore undef inputs.
10156 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10158 // If this input is something other than a EXTRACT_VECTOR_ELT with a
10159 // constant index, bail out.
10160 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10161 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10162 VecIn1 = VecIn2 = SDValue(0, 0);
10166 // We allow up to two distinct input vectors.
10167 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10168 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10171 if (VecIn1.getNode() == 0) {
10172 VecIn1 = ExtractedFromVec;
10173 } else if (VecIn2.getNode() == 0) {
10174 VecIn2 = ExtractedFromVec;
10176 // Too many inputs.
10177 VecIn1 = VecIn2 = SDValue(0, 0);
10182 // If everything is good, we can make a shuffle operation.
10183 if (VecIn1.getNode()) {
10184 SmallVector<int, 8> Mask;
10185 for (unsigned i = 0; i != NumInScalars; ++i) {
10186 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10187 Mask.push_back(-1);
10191 // If extracting from the first vector, just use the index directly.
10192 SDValue Extract = N->getOperand(i);
10193 SDValue ExtVal = Extract.getOperand(1);
10194 if (Extract.getOperand(0) == VecIn1) {
10195 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10196 if (ExtIndex > VT.getVectorNumElements())
10199 Mask.push_back(ExtIndex);
10203 // Otherwise, use InIdx + VecSize
10204 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10205 Mask.push_back(Idx+NumInScalars);
10208 // We can't generate a shuffle node with mismatched input and output types.
10209 // Attempt to transform a single input vector to the correct type.
10210 if ((VT != VecIn1.getValueType())) {
10211 // We don't support shuffeling between TWO values of different types.
10212 if (VecIn2.getNode() != 0)
10215 // We only support widening of vectors which are half the size of the
10216 // output registers. For example XMM->YMM widening on X86 with AVX.
10217 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10220 // If the input vector type has a different base type to the output
10221 // vector type, bail out.
10222 if (VecIn1.getValueType().getVectorElementType() !=
10223 VT.getVectorElementType())
10226 // Widen the input vector by adding undef values.
10227 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10228 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10231 // If VecIn2 is unused then change it to undef.
10232 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10234 // Check that we were able to transform all incoming values to the same
10236 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10237 VecIn1.getValueType() != VT)
10240 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10241 if (!isTypeLegal(VT))
10244 // Return the new VECTOR_SHUFFLE node.
10248 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10254 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10255 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10256 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10257 // inputs come from at most two distinct vectors, turn this into a shuffle
10260 // If we only have one input vector, we don't need to do any concatenation.
10261 if (N->getNumOperands() == 1)
10262 return N->getOperand(0);
10264 // Check if all of the operands are undefs.
10265 EVT VT = N->getValueType(0);
10266 if (ISD::allOperandsUndef(N))
10267 return DAG.getUNDEF(VT);
10269 // Optimize concat_vectors where one of the vectors is undef.
10270 if (N->getNumOperands() == 2 &&
10271 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10272 SDValue In = N->getOperand(0);
10273 assert(In.getValueType().isVector() && "Must concat vectors");
10275 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10276 if (In->getOpcode() == ISD::BITCAST &&
10277 !In->getOperand(0)->getValueType(0).isVector()) {
10278 SDValue Scalar = In->getOperand(0);
10279 EVT SclTy = Scalar->getValueType(0);
10281 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10284 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10285 VT.getSizeInBits() / SclTy.getSizeInBits());
10286 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10289 SDLoc dl = SDLoc(N);
10290 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10291 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10295 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10296 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10297 if (N->getNumOperands() == 2 &&
10298 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10299 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10300 EVT VT = N->getValueType(0);
10301 SDValue N0 = N->getOperand(0);
10302 SDValue N1 = N->getOperand(1);
10303 SmallVector<SDValue, 8> Opnds;
10304 unsigned BuildVecNumElts = N0.getNumOperands();
10306 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10307 Opnds.push_back(N0.getOperand(i));
10308 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10309 Opnds.push_back(N1.getOperand(i));
10311 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
10315 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10316 // nodes often generate nop CONCAT_VECTOR nodes.
10317 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10318 // place the incoming vectors at the exact same location.
10319 SDValue SingleSource = SDValue();
10320 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10322 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10323 SDValue Op = N->getOperand(i);
10325 if (Op.getOpcode() == ISD::UNDEF)
10328 // Check if this is the identity extract:
10329 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10332 // Find the single incoming vector for the extract_subvector.
10333 if (SingleSource.getNode()) {
10334 if (Op.getOperand(0) != SingleSource)
10337 SingleSource = Op.getOperand(0);
10339 // Check the source type is the same as the type of the result.
10340 // If not, this concat may extend the vector, so we can not
10341 // optimize it away.
10342 if (SingleSource.getValueType() != N->getValueType(0))
10346 unsigned IdentityIndex = i * PartNumElem;
10347 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10348 // The extract index must be constant.
10352 // Check that we are reading from the identity index.
10353 if (CS->getZExtValue() != IdentityIndex)
10357 if (SingleSource.getNode())
10358 return SingleSource;
10363 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10364 EVT NVT = N->getValueType(0);
10365 SDValue V = N->getOperand(0);
10367 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10369 // (extract_subvec (concat V1, V2, ...), i)
10372 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10374 if (V->getOperand(0).getValueType() != NVT)
10376 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10377 unsigned NumElems = NVT.getVectorNumElements();
10378 assert((Idx % NumElems) == 0 &&
10379 "IDX in concat is not a multiple of the result vector length.");
10380 return V->getOperand(Idx / NumElems);
10384 if (V->getOpcode() == ISD::BITCAST)
10385 V = V.getOperand(0);
10387 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10389 // Handle only simple case where vector being inserted and vector
10390 // being extracted are of same type, and are half size of larger vectors.
10391 EVT BigVT = V->getOperand(0).getValueType();
10392 EVT SmallVT = V->getOperand(1).getValueType();
10393 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10396 // Only handle cases where both indexes are constants with the same type.
10397 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10398 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10400 if (InsIdx && ExtIdx &&
10401 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10402 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10404 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10406 // indices are equal or bit offsets are equal => V1
10407 // otherwise => (extract_subvec V1, ExtIdx)
10408 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10409 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10410 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10411 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10412 DAG.getNode(ISD::BITCAST, dl,
10413 N->getOperand(0).getValueType(),
10414 V->getOperand(0)), N->getOperand(1));
10421 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10422 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10423 EVT VT = N->getValueType(0);
10424 unsigned NumElts = VT.getVectorNumElements();
10426 SDValue N0 = N->getOperand(0);
10427 SDValue N1 = N->getOperand(1);
10428 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10430 SmallVector<SDValue, 4> Ops;
10431 EVT ConcatVT = N0.getOperand(0).getValueType();
10432 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10433 unsigned NumConcats = NumElts / NumElemsPerConcat;
10435 // Look at every vector that's inserted. We're looking for exact
10436 // subvector-sized copies from a concatenated vector
10437 for (unsigned I = 0; I != NumConcats; ++I) {
10438 // Make sure we're dealing with a copy.
10439 unsigned Begin = I * NumElemsPerConcat;
10440 bool AllUndef = true, NoUndef = true;
10441 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10442 if (SVN->getMaskElt(J) >= 0)
10449 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10452 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10453 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10456 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10457 if (FirstElt < N0.getNumOperands())
10458 Ops.push_back(N0.getOperand(FirstElt));
10460 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10462 } else if (AllUndef) {
10463 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10464 } else { // Mixed with general masks and undefs, can't do optimization.
10469 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
10473 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10474 EVT VT = N->getValueType(0);
10475 unsigned NumElts = VT.getVectorNumElements();
10477 SDValue N0 = N->getOperand(0);
10478 SDValue N1 = N->getOperand(1);
10480 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10482 // Canonicalize shuffle undef, undef -> undef
10483 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10484 return DAG.getUNDEF(VT);
10486 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10488 // Canonicalize shuffle v, v -> v, undef
10490 SmallVector<int, 8> NewMask;
10491 for (unsigned i = 0; i != NumElts; ++i) {
10492 int Idx = SVN->getMaskElt(i);
10493 if (Idx >= (int)NumElts) Idx -= NumElts;
10494 NewMask.push_back(Idx);
10496 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10500 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10501 if (N0.getOpcode() == ISD::UNDEF) {
10502 SmallVector<int, 8> NewMask;
10503 for (unsigned i = 0; i != NumElts; ++i) {
10504 int Idx = SVN->getMaskElt(i);
10506 if (Idx >= (int)NumElts)
10509 Idx = -1; // remove reference to lhs
10511 NewMask.push_back(Idx);
10513 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10517 // Remove references to rhs if it is undef
10518 if (N1.getOpcode() == ISD::UNDEF) {
10519 bool Changed = false;
10520 SmallVector<int, 8> NewMask;
10521 for (unsigned i = 0; i != NumElts; ++i) {
10522 int Idx = SVN->getMaskElt(i);
10523 if (Idx >= (int)NumElts) {
10527 NewMask.push_back(Idx);
10530 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10533 // If it is a splat, check if the argument vector is another splat or a
10534 // build_vector with all scalar elements the same.
10535 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10536 SDNode *V = N0.getNode();
10538 // If this is a bit convert that changes the element type of the vector but
10539 // not the number of vector elements, look through it. Be careful not to
10540 // look though conversions that change things like v4f32 to v2f64.
10541 if (V->getOpcode() == ISD::BITCAST) {
10542 SDValue ConvInput = V->getOperand(0);
10543 if (ConvInput.getValueType().isVector() &&
10544 ConvInput.getValueType().getVectorNumElements() == NumElts)
10545 V = ConvInput.getNode();
10548 if (V->getOpcode() == ISD::BUILD_VECTOR) {
10549 assert(V->getNumOperands() == NumElts &&
10550 "BUILD_VECTOR has wrong number of operands");
10552 bool AllSame = true;
10553 for (unsigned i = 0; i != NumElts; ++i) {
10554 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10555 Base = V->getOperand(i);
10559 // Splat of <u, u, u, u>, return <u, u, u, u>
10560 if (!Base.getNode())
10562 for (unsigned i = 0; i != NumElts; ++i) {
10563 if (V->getOperand(i) != Base) {
10568 // Splat of <x, x, x, x>, return <x, x, x, x>
10574 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10575 Level < AfterLegalizeVectorOps &&
10576 (N1.getOpcode() == ISD::UNDEF ||
10577 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10578 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10579 SDValue V = partitionShuffleOfConcats(N, DAG);
10585 // If this shuffle node is simply a swizzle of another shuffle node,
10586 // and it reverses the swizzle of the previous shuffle then we can
10587 // optimize shuffle(shuffle(x, undef), undef) -> x.
10588 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10589 N1.getOpcode() == ISD::UNDEF) {
10591 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10593 // Shuffle nodes can only reverse shuffles with a single non-undef value.
10594 if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10597 // The incoming shuffle must be of the same type as the result of the
10598 // current shuffle.
10599 assert(OtherSV->getOperand(0).getValueType() == VT &&
10600 "Shuffle types don't match");
10602 for (unsigned i = 0; i != NumElts; ++i) {
10603 int Idx = SVN->getMaskElt(i);
10604 assert(Idx < (int)NumElts && "Index references undef operand");
10605 // Next, this index comes from the first value, which is the incoming
10606 // shuffle. Adopt the incoming index.
10608 Idx = OtherSV->getMaskElt(Idx);
10610 // The combined shuffle must map each index to itself.
10611 if (Idx >= 0 && (unsigned)Idx != i)
10615 return OtherSV->getOperand(0);
10621 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10622 SDValue N0 = N->getOperand(0);
10623 SDValue N2 = N->getOperand(2);
10625 // If the input vector is a concatenation, and the insert replaces
10626 // one of the halves, we can optimize into a single concat_vectors.
10627 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10628 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10629 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10630 EVT VT = N->getValueType(0);
10632 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10633 // (concat_vectors Z, Y)
10635 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10636 N->getOperand(1), N0.getOperand(1));
10638 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10639 // (concat_vectors X, Z)
10640 if (InsIdx == VT.getVectorNumElements()/2)
10641 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10642 N0.getOperand(0), N->getOperand(1));
10648 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10649 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10650 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10651 /// vector_shuffle V, Zero, <0, 4, 2, 4>
10652 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10653 EVT VT = N->getValueType(0);
10655 SDValue LHS = N->getOperand(0);
10656 SDValue RHS = N->getOperand(1);
10657 if (N->getOpcode() == ISD::AND) {
10658 if (RHS.getOpcode() == ISD::BITCAST)
10659 RHS = RHS.getOperand(0);
10660 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10661 SmallVector<int, 8> Indices;
10662 unsigned NumElts = RHS.getNumOperands();
10663 for (unsigned i = 0; i != NumElts; ++i) {
10664 SDValue Elt = RHS.getOperand(i);
10665 if (!isa<ConstantSDNode>(Elt))
10668 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10669 Indices.push_back(i);
10670 else if (cast<ConstantSDNode>(Elt)->isNullValue())
10671 Indices.push_back(NumElts);
10676 // Let's see if the target supports this vector_shuffle.
10677 EVT RVT = RHS.getValueType();
10678 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10681 // Return the new VECTOR_SHUFFLE node.
10682 EVT EltVT = RVT.getVectorElementType();
10683 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10684 DAG.getConstant(0, EltVT));
10685 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10686 RVT, &ZeroOps[0], ZeroOps.size());
10687 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10688 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10689 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10696 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10697 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10698 assert(N->getValueType(0).isVector() &&
10699 "SimplifyVBinOp only works on vectors!");
10701 SDValue LHS = N->getOperand(0);
10702 SDValue RHS = N->getOperand(1);
10703 SDValue Shuffle = XformToShuffleWithZero(N);
10704 if (Shuffle.getNode()) return Shuffle;
10706 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10708 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10709 RHS.getOpcode() == ISD::BUILD_VECTOR) {
10710 // Check if both vectors are constants. If not bail out.
10711 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10712 cast<BuildVectorSDNode>(RHS)->isConstant()))
10715 SmallVector<SDValue, 8> Ops;
10716 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10717 SDValue LHSOp = LHS.getOperand(i);
10718 SDValue RHSOp = RHS.getOperand(i);
10720 // Can't fold divide by zero.
10721 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10722 N->getOpcode() == ISD::FDIV) {
10723 if ((RHSOp.getOpcode() == ISD::Constant &&
10724 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10725 (RHSOp.getOpcode() == ISD::ConstantFP &&
10726 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10730 EVT VT = LHSOp.getValueType();
10731 EVT RVT = RHSOp.getValueType();
10733 // Integer BUILD_VECTOR operands may have types larger than the element
10734 // size (e.g., when the element type is not legal). Prior to type
10735 // legalization, the types may not match between the two BUILD_VECTORS.
10736 // Truncate one of the operands to make them match.
10737 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10738 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10740 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10744 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10746 if (FoldOp.getOpcode() != ISD::UNDEF &&
10747 FoldOp.getOpcode() != ISD::Constant &&
10748 FoldOp.getOpcode() != ISD::ConstantFP)
10750 Ops.push_back(FoldOp);
10751 AddToWorkList(FoldOp.getNode());
10754 if (Ops.size() == LHS.getNumOperands())
10755 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10756 LHS.getValueType(), &Ops[0], Ops.size());
10762 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10763 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10764 assert(N->getValueType(0).isVector() &&
10765 "SimplifyVUnaryOp only works on vectors!");
10767 SDValue N0 = N->getOperand(0);
10769 if (N0.getOpcode() != ISD::BUILD_VECTOR)
10772 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10773 SmallVector<SDValue, 8> Ops;
10774 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10775 SDValue Op = N0.getOperand(i);
10776 if (Op.getOpcode() != ISD::UNDEF &&
10777 Op.getOpcode() != ISD::ConstantFP)
10779 EVT EltVT = Op.getValueType();
10780 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
10781 if (FoldOp.getOpcode() != ISD::UNDEF &&
10782 FoldOp.getOpcode() != ISD::ConstantFP)
10784 Ops.push_back(FoldOp);
10785 AddToWorkList(FoldOp.getNode());
10788 if (Ops.size() != N0.getNumOperands())
10791 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10792 N0.getValueType(), &Ops[0], Ops.size());
10795 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10796 SDValue N1, SDValue N2){
10797 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10799 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
10800 cast<CondCodeSDNode>(N0.getOperand(2))->get());
10802 // If we got a simplified select_cc node back from SimplifySelectCC, then
10803 // break it down into a new SETCC node, and a new SELECT node, and then return
10804 // the SELECT node, since we were called with a SELECT node.
10805 if (SCC.getNode()) {
10806 // Check to see if we got a select_cc back (to turn into setcc/select).
10807 // Otherwise, just return whatever node we got back, like fabs.
10808 if (SCC.getOpcode() == ISD::SELECT_CC) {
10809 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
10811 SCC.getOperand(0), SCC.getOperand(1),
10812 SCC.getOperand(4));
10813 AddToWorkList(SETCC.getNode());
10814 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10815 SCC.getOperand(2), SCC.getOperand(3), SETCC);
10823 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10824 /// are the two values being selected between, see if we can simplify the
10825 /// select. Callers of this should assume that TheSelect is deleted if this
10826 /// returns true. As such, they should return the appropriate thing (e.g. the
10827 /// node) back to the top-level of the DAG combiner loop to avoid it being
10829 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
10832 // Cannot simplify select with vector condition
10833 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10835 // If this is a select from two identical things, try to pull the operation
10836 // through the select.
10837 if (LHS.getOpcode() != RHS.getOpcode() ||
10838 !LHS.hasOneUse() || !RHS.hasOneUse())
10841 // If this is a load and the token chain is identical, replace the select
10842 // of two loads with a load through a select of the address to load from.
10843 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10844 // constants have been dropped into the constant pool.
10845 if (LHS.getOpcode() == ISD::LOAD) {
10846 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10847 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
10849 // Token chains must be identical.
10850 if (LHS.getOperand(0) != RHS.getOperand(0) ||
10851 // Do not let this transformation reduce the number of volatile loads.
10852 LLD->isVolatile() || RLD->isVolatile() ||
10853 // If this is an EXTLOAD, the VT's must match.
10854 LLD->getMemoryVT() != RLD->getMemoryVT() ||
10855 // If this is an EXTLOAD, the kind of extension must match.
10856 (LLD->getExtensionType() != RLD->getExtensionType() &&
10857 // The only exception is if one of the extensions is anyext.
10858 LLD->getExtensionType() != ISD::EXTLOAD &&
10859 RLD->getExtensionType() != ISD::EXTLOAD) ||
10860 // FIXME: this discards src value information. This is
10861 // over-conservative. It would be beneficial to be able to remember
10862 // both potential memory locations. Since we are discarding
10863 // src value info, don't do the transformation if the memory
10864 // locations are not in the default address space.
10865 LLD->getPointerInfo().getAddrSpace() != 0 ||
10866 RLD->getPointerInfo().getAddrSpace() != 0 ||
10867 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10868 LLD->getBasePtr().getValueType()))
10871 // Check that the select condition doesn't reach either load. If so,
10872 // folding this will induce a cycle into the DAG. If not, this is safe to
10873 // xform, so create a select of the addresses.
10875 if (TheSelect->getOpcode() == ISD::SELECT) {
10876 SDNode *CondNode = TheSelect->getOperand(0).getNode();
10877 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10878 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10880 // The loads must not depend on one another.
10881 if (LLD->isPredecessorOf(RLD) ||
10882 RLD->isPredecessorOf(LLD))
10884 Addr = DAG.getSelect(SDLoc(TheSelect),
10885 LLD->getBasePtr().getValueType(),
10886 TheSelect->getOperand(0), LLD->getBasePtr(),
10887 RLD->getBasePtr());
10888 } else { // Otherwise SELECT_CC
10889 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10890 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10892 if ((LLD->hasAnyUseOfValue(1) &&
10893 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
10894 (RLD->hasAnyUseOfValue(1) &&
10895 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
10898 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
10899 LLD->getBasePtr().getValueType(),
10900 TheSelect->getOperand(0),
10901 TheSelect->getOperand(1),
10902 LLD->getBasePtr(), RLD->getBasePtr(),
10903 TheSelect->getOperand(4));
10907 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10908 Load = DAG.getLoad(TheSelect->getValueType(0),
10910 // FIXME: Discards pointer and TBAA info.
10911 LLD->getChain(), Addr, MachinePointerInfo(),
10912 LLD->isVolatile(), LLD->isNonTemporal(),
10913 LLD->isInvariant(), LLD->getAlignment());
10915 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10916 RLD->getExtensionType() : LLD->getExtensionType(),
10918 TheSelect->getValueType(0),
10919 // FIXME: Discards pointer and TBAA info.
10920 LLD->getChain(), Addr, MachinePointerInfo(),
10921 LLD->getMemoryVT(), LLD->isVolatile(),
10922 LLD->isNonTemporal(), LLD->getAlignment());
10925 // Users of the select now use the result of the load.
10926 CombineTo(TheSelect, Load);
10928 // Users of the old loads now use the new load's chain. We know the
10929 // old-load value is dead now.
10930 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10931 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10938 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10939 /// where 'cond' is the comparison specified by CC.
10940 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
10941 SDValue N2, SDValue N3,
10942 ISD::CondCode CC, bool NotExtCompare) {
10943 // (x ? y : y) -> y.
10944 if (N2 == N3) return N2;
10946 EVT VT = N2.getValueType();
10947 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10948 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10949 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
10951 // Determine if the condition we're dealing with is constant
10952 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
10953 N0, N1, CC, DL, false);
10954 if (SCC.getNode()) AddToWorkList(SCC.getNode());
10955 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
10957 // fold select_cc true, x, y -> x
10958 if (SCCC && !SCCC->isNullValue())
10960 // fold select_cc false, x, y -> y
10961 if (SCCC && SCCC->isNullValue())
10964 // Check to see if we can simplify the select into an fabs node
10965 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10966 // Allow either -0.0 or 0.0
10967 if (CFP->getValueAPF().isZero()) {
10968 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10969 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10970 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10971 N2 == N3.getOperand(0))
10972 return DAG.getNode(ISD::FABS, DL, VT, N0);
10974 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10975 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10976 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10977 N2.getOperand(0) == N3)
10978 return DAG.getNode(ISD::FABS, DL, VT, N3);
10982 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10983 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10984 // in it. This is a win when the constant is not otherwise available because
10985 // it replaces two constant pool loads with one. We only do this if the FP
10986 // type is known to be legal, because if it isn't, then we are before legalize
10987 // types an we want the other legalization to happen first (e.g. to avoid
10988 // messing with soft float) and if the ConstantFP is not legal, because if
10989 // it is legal, we may not need to store the FP constant in a constant pool.
10990 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10991 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10992 if (TLI.isTypeLegal(N2.getValueType()) &&
10993 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10994 TargetLowering::Legal) &&
10995 // If both constants have multiple uses, then we won't need to do an
10996 // extra load, they are likely around in registers for other users.
10997 (TV->hasOneUse() || FV->hasOneUse())) {
10998 Constant *Elts[] = {
10999 const_cast<ConstantFP*>(FV->getConstantFPValue()),
11000 const_cast<ConstantFP*>(TV->getConstantFPValue())
11002 Type *FPTy = Elts[0]->getType();
11003 const DataLayout &TD = *TLI.getDataLayout();
11005 // Create a ConstantArray of the two constants.
11006 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11007 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11008 TD.getPrefTypeAlignment(FPTy));
11009 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11011 // Get the offsets to the 0 and 1 element of the array so that we can
11012 // select between them.
11013 SDValue Zero = DAG.getIntPtrConstant(0);
11014 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11015 SDValue One = DAG.getIntPtrConstant(EltSize);
11017 SDValue Cond = DAG.getSetCC(DL,
11018 getSetCCResultType(N0.getValueType()),
11020 AddToWorkList(Cond.getNode());
11021 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11023 AddToWorkList(CstOffset.getNode());
11024 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11026 AddToWorkList(CPIdx.getNode());
11027 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11028 MachinePointerInfo::getConstantPool(), false,
11029 false, false, Alignment);
11034 // Check to see if we can perform the "gzip trick", transforming
11035 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11036 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11037 (N1C->isNullValue() || // (a < 0) ? b : 0
11038 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
11039 EVT XType = N0.getValueType();
11040 EVT AType = N2.getValueType();
11041 if (XType.bitsGE(AType)) {
11042 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11043 // single-bit constant.
11044 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11045 unsigned ShCtV = N2C->getAPIntValue().logBase2();
11046 ShCtV = XType.getSizeInBits()-ShCtV-1;
11047 SDValue ShCt = DAG.getConstant(ShCtV,
11048 getShiftAmountTy(N0.getValueType()));
11049 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11051 AddToWorkList(Shift.getNode());
11053 if (XType.bitsGT(AType)) {
11054 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11055 AddToWorkList(Shift.getNode());
11058 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11061 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11063 DAG.getConstant(XType.getSizeInBits()-1,
11064 getShiftAmountTy(N0.getValueType())));
11065 AddToWorkList(Shift.getNode());
11067 if (XType.bitsGT(AType)) {
11068 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11069 AddToWorkList(Shift.getNode());
11072 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11076 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11077 // where y is has a single bit set.
11078 // A plaintext description would be, we can turn the SELECT_CC into an AND
11079 // when the condition can be materialized as an all-ones register. Any
11080 // single bit-test can be materialized as an all-ones register with
11081 // shift-left and shift-right-arith.
11082 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11083 N0->getValueType(0) == VT &&
11084 N1C && N1C->isNullValue() &&
11085 N2C && N2C->isNullValue()) {
11086 SDValue AndLHS = N0->getOperand(0);
11087 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11088 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11089 // Shift the tested bit over the sign bit.
11090 APInt AndMask = ConstAndRHS->getAPIntValue();
11092 DAG.getConstant(AndMask.countLeadingZeros(),
11093 getShiftAmountTy(AndLHS.getValueType()));
11094 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11096 // Now arithmetic right shift it all the way over, so the result is either
11097 // all-ones, or zero.
11099 DAG.getConstant(AndMask.getBitWidth()-1,
11100 getShiftAmountTy(Shl.getValueType()));
11101 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11103 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11107 // fold select C, 16, 0 -> shl C, 4
11108 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11109 TLI.getBooleanContents(N0.getValueType().isVector()) ==
11110 TargetLowering::ZeroOrOneBooleanContent) {
11112 // If the caller doesn't want us to simplify this into a zext of a compare,
11114 if (NotExtCompare && N2C->getAPIntValue() == 1)
11117 // Get a SetCC of the condition
11118 // NOTE: Don't create a SETCC if it's not legal on this target.
11119 if (!LegalOperations ||
11120 TLI.isOperationLegal(ISD::SETCC,
11121 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11123 // cast from setcc result type to select result type
11125 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11127 if (N2.getValueType().bitsLT(SCC.getValueType()))
11128 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11129 N2.getValueType());
11131 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11132 N2.getValueType(), SCC);
11134 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11135 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11136 N2.getValueType(), SCC);
11139 AddToWorkList(SCC.getNode());
11140 AddToWorkList(Temp.getNode());
11142 if (N2C->getAPIntValue() == 1)
11145 // shl setcc result by log2 n2c
11146 return DAG.getNode(
11147 ISD::SHL, DL, N2.getValueType(), Temp,
11148 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11149 getShiftAmountTy(Temp.getValueType())));
11153 // Check to see if this is the equivalent of setcc
11154 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11155 // otherwise, go ahead with the folds.
11156 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11157 EVT XType = N0.getValueType();
11158 if (!LegalOperations ||
11159 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11160 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11161 if (Res.getValueType() != VT)
11162 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11166 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11167 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11168 (!LegalOperations ||
11169 TLI.isOperationLegal(ISD::CTLZ, XType))) {
11170 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11171 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11172 DAG.getConstant(Log2_32(XType.getSizeInBits()),
11173 getShiftAmountTy(Ctlz.getValueType())));
11175 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11176 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11177 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11178 XType, DAG.getConstant(0, XType), N0);
11179 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11180 return DAG.getNode(ISD::SRL, DL, XType,
11181 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11182 DAG.getConstant(XType.getSizeInBits()-1,
11183 getShiftAmountTy(XType)));
11185 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11186 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11187 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11188 DAG.getConstant(XType.getSizeInBits()-1,
11189 getShiftAmountTy(N0.getValueType())));
11190 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11194 // Check to see if this is an integer abs.
11195 // select_cc setg[te] X, 0, X, -X ->
11196 // select_cc setgt X, -1, X, -X ->
11197 // select_cc setl[te] X, 0, -X, X ->
11198 // select_cc setlt X, 1, -X, X ->
11199 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11201 ConstantSDNode *SubC = NULL;
11202 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11203 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11204 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11205 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11206 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11207 (N1C->isOne() && CC == ISD::SETLT)) &&
11208 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11209 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11211 EVT XType = N0.getValueType();
11212 if (SubC && SubC->isNullValue() && XType.isInteger()) {
11213 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11215 DAG.getConstant(XType.getSizeInBits()-1,
11216 getShiftAmountTy(N0.getValueType())));
11217 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11219 AddToWorkList(Shift.getNode());
11220 AddToWorkList(Add.getNode());
11221 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11228 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11229 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11230 SDValue N1, ISD::CondCode Cond,
11231 SDLoc DL, bool foldBooleans) {
11232 TargetLowering::DAGCombinerInfo
11233 DagCombineInfo(DAG, Level, false, this);
11234 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11237 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11238 /// return a DAG expression to select that will generate the same value by
11239 /// multiplying by a magic number. See:
11240 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11241 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11242 std::vector<SDNode*> Built;
11243 SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
11245 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
11247 AddToWorkList(*ii);
11251 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
11252 /// return a DAG expression to select that will generate the same value by
11253 /// multiplying by a magic number. See:
11254 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11255 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11256 std::vector<SDNode*> Built;
11257 SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
11259 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
11261 AddToWorkList(*ii);
11265 /// FindBaseOffset - Return true if base is a frame index, which is known not
11266 // to alias with anything but itself. Provides base object and offset as
11268 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11269 const GlobalValue *&GV, const void *&CV) {
11270 // Assume it is a primitive operation.
11271 Base = Ptr; Offset = 0; GV = 0; CV = 0;
11273 // If it's an adding a simple constant then integrate the offset.
11274 if (Base.getOpcode() == ISD::ADD) {
11275 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11276 Base = Base.getOperand(0);
11277 Offset += C->getZExtValue();
11281 // Return the underlying GlobalValue, and update the Offset. Return false
11282 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11283 // by multiple nodes with different offsets.
11284 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11285 GV = G->getGlobal();
11286 Offset += G->getOffset();
11290 // Return the underlying Constant value, and update the Offset. Return false
11291 // for ConstantSDNodes since the same constant pool entry may be represented
11292 // by multiple nodes with different offsets.
11293 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11294 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11295 : (const void *)C->getConstVal();
11296 Offset += C->getOffset();
11299 // If it's any of the following then it can't alias with anything but itself.
11300 return isa<FrameIndexSDNode>(Base);
11303 /// isAlias - Return true if there is any possibility that the two addresses
11305 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
11306 const Value *SrcValue1, int SrcValueOffset1,
11307 unsigned SrcValueAlign1,
11308 const MDNode *TBAAInfo1,
11309 SDValue Ptr2, int64_t Size2, bool IsVolatile2,
11310 const Value *SrcValue2, int SrcValueOffset2,
11311 unsigned SrcValueAlign2,
11312 const MDNode *TBAAInfo2) const {
11313 // If they are the same then they must be aliases.
11314 if (Ptr1 == Ptr2) return true;
11316 // If they are both volatile then they cannot be reordered.
11317 if (IsVolatile1 && IsVolatile2) return true;
11319 // Gather base node and offset information.
11320 SDValue Base1, Base2;
11321 int64_t Offset1, Offset2;
11322 const GlobalValue *GV1, *GV2;
11323 const void *CV1, *CV2;
11324 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
11325 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
11327 // If they have a same base address then check to see if they overlap.
11328 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11329 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11331 // It is possible for different frame indices to alias each other, mostly
11332 // when tail call optimization reuses return address slots for arguments.
11333 // To catch this case, look up the actual index of frame indices to compute
11334 // the real alias relationship.
11335 if (isFrameIndex1 && isFrameIndex2) {
11336 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11337 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11338 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11339 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11342 // Otherwise, if we know what the bases are, and they aren't identical, then
11343 // we know they cannot alias.
11344 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11347 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11348 // compared to the size and offset of the access, we may be able to prove they
11349 // do not alias. This check is conservative for now to catch cases created by
11350 // splitting vector types.
11351 if ((SrcValueAlign1 == SrcValueAlign2) &&
11352 (SrcValueOffset1 != SrcValueOffset2) &&
11353 (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
11354 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
11355 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
11357 // There is no overlap between these relatively aligned accesses of similar
11358 // size, return no alias.
11359 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
11363 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11364 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11366 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11367 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11370 if (UseAA && SrcValue1 && SrcValue2) {
11371 // Use alias analysis information.
11372 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
11373 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
11374 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
11375 AliasAnalysis::AliasResult AAResult =
11376 AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1,
11377 UseTBAA ? TBAAInfo1 : 0),
11378 AliasAnalysis::Location(SrcValue2, Overlap2,
11379 UseTBAA ? TBAAInfo2 : 0));
11380 if (AAResult == AliasAnalysis::NoAlias)
11384 // Otherwise we have to assume they alias.
11388 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
11389 SDValue Ptr0, Ptr1;
11390 int64_t Size0, Size1;
11391 bool IsVolatile0, IsVolatile1;
11392 const Value *SrcValue0, *SrcValue1;
11393 int SrcValueOffset0, SrcValueOffset1;
11394 unsigned SrcValueAlign0, SrcValueAlign1;
11395 const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
11396 FindAliasInfo(Op0, Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
11397 SrcValueAlign0, SrcTBAAInfo0);
11398 FindAliasInfo(Op1, Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
11399 SrcValueAlign1, SrcTBAAInfo1);
11400 return isAlias(Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
11401 SrcValueAlign0, SrcTBAAInfo0,
11402 Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
11403 SrcValueAlign1, SrcTBAAInfo1);
11406 /// FindAliasInfo - Extracts the relevant alias information from the memory
11407 /// node. Returns true if the operand was a nonvolatile load.
11408 bool DAGCombiner::FindAliasInfo(SDNode *N,
11409 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
11410 const Value *&SrcValue,
11411 int &SrcValueOffset,
11412 unsigned &SrcValueAlign,
11413 const MDNode *&TBAAInfo) const {
11414 LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
11416 Ptr = LS->getBasePtr();
11417 Size = LS->getMemoryVT().getSizeInBits() >> 3;
11418 IsVolatile = LS->isVolatile();
11419 SrcValue = LS->getSrcValue();
11420 SrcValueOffset = LS->getSrcValueOffset();
11421 SrcValueAlign = LS->getOriginalAlignment();
11422 TBAAInfo = LS->getTBAAInfo();
11423 return isa<LoadSDNode>(LS) && !IsVolatile;
11426 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11427 /// looking for aliasing nodes and adding them to the Aliases vector.
11428 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11429 SmallVectorImpl<SDValue> &Aliases) {
11430 SmallVector<SDValue, 8> Chains; // List of chains to visit.
11431 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
11433 // Get alias information for node.
11437 const Value *SrcValue;
11438 int SrcValueOffset;
11439 unsigned SrcValueAlign;
11440 const MDNode *SrcTBAAInfo;
11441 bool IsLoad = FindAliasInfo(N, Ptr, Size, IsVolatile, SrcValue,
11442 SrcValueOffset, SrcValueAlign, SrcTBAAInfo);
11445 Chains.push_back(OriginalChain);
11446 unsigned Depth = 0;
11448 // Look at each chain and determine if it is an alias. If so, add it to the
11449 // aliases list. If not, then continue up the chain looking for the next
11451 while (!Chains.empty()) {
11452 SDValue Chain = Chains.back();
11455 // For TokenFactor nodes, look at each operand and only continue up the
11456 // chain until we find two aliases. If we've seen two aliases, assume we'll
11457 // find more and revert to original chain since the xform is unlikely to be
11460 // FIXME: The depth check could be made to return the last non-aliasing
11461 // chain we found before we hit a tokenfactor rather than the original
11463 if (Depth > 6 || Aliases.size() == 2) {
11465 Aliases.push_back(OriginalChain);
11469 // Don't bother if we've been before.
11470 if (!Visited.insert(Chain.getNode()))
11473 switch (Chain.getOpcode()) {
11474 case ISD::EntryToken:
11475 // Entry token is ideal chain operand, but handled in FindBetterChain.
11480 // Get alias information for Chain.
11484 const Value *OpSrcValue;
11485 int OpSrcValueOffset;
11486 unsigned OpSrcValueAlign;
11487 const MDNode *OpSrcTBAAInfo;
11488 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
11489 OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11493 // If chain is alias then stop here.
11494 if (!(IsLoad && IsOpLoad) &&
11495 isAlias(Ptr, Size, IsVolatile, SrcValue, SrcValueOffset,
11496 SrcValueAlign, SrcTBAAInfo,
11497 OpPtr, OpSize, OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11498 OpSrcValueAlign, OpSrcTBAAInfo)) {
11499 Aliases.push_back(Chain);
11501 // Look further up the chain.
11502 Chains.push_back(Chain.getOperand(0));
11508 case ISD::TokenFactor:
11509 // We have to check each of the operands of the token factor for "small"
11510 // token factors, so we queue them up. Adding the operands to the queue
11511 // (stack) in reverse order maintains the original order and increases the
11512 // likelihood that getNode will find a matching token factor (CSE.)
11513 if (Chain.getNumOperands() > 16) {
11514 Aliases.push_back(Chain);
11517 for (unsigned n = Chain.getNumOperands(); n;)
11518 Chains.push_back(Chain.getOperand(--n));
11523 // For all other instructions we will just have to take what we can get.
11524 Aliases.push_back(Chain);
11529 // We need to be careful here to also search for aliases through the
11530 // value operand of a store, etc. Consider the following situation:
11532 // L1 = load Token1, %52
11533 // S1 = store Token1, L1, %51
11534 // L2 = load Token1, %52+8
11535 // S2 = store Token1, L2, %51+8
11536 // Token2 = Token(S1, S2)
11537 // L3 = load Token2, %53
11538 // S3 = store Token2, L3, %52
11539 // L4 = load Token2, %53+8
11540 // S4 = store Token2, L4, %52+8
11541 // If we search for aliases of S3 (which loads address %52), and we look
11542 // only through the chain, then we'll miss the trivial dependence on L1
11543 // (which also loads from %52). We then might change all loads and
11544 // stores to use Token1 as their chain operand, which could result in
11545 // copying %53 into %52 before copying %52 into %51 (which should
11548 // The problem is, however, that searching for such data dependencies
11549 // can become expensive, and the cost is not directly related to the
11550 // chain depth. Instead, we'll rule out such configurations here by
11551 // insisting that we've visited all chain users (except for users
11552 // of the original chain, which is not necessary). When doing this,
11553 // we need to look through nodes we don't care about (otherwise, things
11554 // like register copies will interfere with trivial cases).
11556 SmallVector<const SDNode *, 16> Worklist;
11557 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11558 IE = Visited.end(); I != IE; ++I)
11559 if (*I != OriginalChain.getNode())
11560 Worklist.push_back(*I);
11562 while (!Worklist.empty()) {
11563 const SDNode *M = Worklist.pop_back_val();
11565 // We have already visited M, and want to make sure we've visited any uses
11566 // of M that we care about. For uses that we've not visisted, and don't
11567 // care about, queue them to the worklist.
11569 for (SDNode::use_iterator UI = M->use_begin(),
11570 UIE = M->use_end(); UI != UIE; ++UI)
11571 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11572 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11573 // We've not visited this use, and we care about it (it could have an
11574 // ordering dependency with the original node).
11576 Aliases.push_back(OriginalChain);
11580 // We've not visited this use, but we don't care about it. Mark it as
11581 // visited and enqueue it to the worklist.
11582 Worklist.push_back(*UI);
11587 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11588 /// for a better chain (aliasing node.)
11589 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11590 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
11592 // Accumulate all the aliases to this node.
11593 GatherAllAliases(N, OldChain, Aliases);
11595 // If no operands then chain to entry token.
11596 if (Aliases.size() == 0)
11597 return DAG.getEntryNode();
11599 // If a single operand then chain to it. We don't need to revisit it.
11600 if (Aliases.size() == 1)
11603 // Construct a custom tailored token factor.
11604 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
11605 &Aliases[0], Aliases.size());
11608 // SelectionDAG::Combine - This is the entry point for the file.
11610 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11611 CodeGenOpt::Level OptLevel) {
11612 /// run - This is the main entry point to this class.
11614 DAGCombiner(*this, AA, OptLevel).Run(Level);