Revert PR16726: extend rol/ror matching
[oota-llvm.git] / lib / CodeGen / SelectionDAG / DAGCombiner.cpp
1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
12 //
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.
16 //
17 //===----------------------------------------------------------------------===//
18
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/TargetSubtargetInfo.h"
39 #include <algorithm>
40 using namespace llvm;
41
42 STATISTIC(NodesCombined   , "Number of dag nodes combined");
43 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
44 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
45 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
46 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
47
48 namespace {
49   static cl::opt<bool>
50     CombinerAA("combiner-alias-analysis", cl::Hidden,
51                cl::desc("Turn on alias analysis during testing"));
52
53   static cl::opt<bool>
54     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
55                cl::desc("Include global information in alias analysis"));
56
57 //------------------------------ DAGCombiner ---------------------------------//
58
59   class DAGCombiner {
60     SelectionDAG &DAG;
61     const TargetLowering &TLI;
62     CombineLevel Level;
63     CodeGenOpt::Level OptLevel;
64     bool LegalOperations;
65     bool LegalTypes;
66
67     // Worklist of all of the nodes that need to be simplified.
68     //
69     // This has the semantics that when adding to the worklist,
70     // the item added must be next to be processed. It should
71     // also only appear once. The naive approach to this takes
72     // linear time.
73     //
74     // To reduce the insert/remove time to logarithmic, we use
75     // a set and a vector to maintain our worklist.
76     //
77     // The set contains the items on the worklist, but does not
78     // maintain the order they should be visited.
79     //
80     // The vector maintains the order nodes should be visited, but may
81     // contain duplicate or removed nodes. When choosing a node to
82     // visit, we pop off the order stack until we find an item that is
83     // also in the contents set. All operations are O(log N).
84     SmallPtrSet<SDNode*, 64> WorkListContents;
85     SmallVector<SDNode*, 64> WorkListOrder;
86
87     // AA - Used for DAG load/store alias analysis.
88     AliasAnalysis &AA;
89
90     /// AddUsersToWorkList - When an instruction is simplified, add all users of
91     /// the instruction to the work lists because they might get more simplified
92     /// now.
93     ///
94     void AddUsersToWorkList(SDNode *N) {
95       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
96            UI != UE; ++UI)
97         AddToWorkList(*UI);
98     }
99
100     /// visit - call the node-specific routine that knows how to fold each
101     /// particular type of node.
102     SDValue visit(SDNode *N);
103
104   public:
105     /// AddToWorkList - Add to the work list making sure its instance is at the
106     /// back (next to be processed.)
107     void AddToWorkList(SDNode *N) {
108       WorkListContents.insert(N);
109       WorkListOrder.push_back(N);
110     }
111
112     /// removeFromWorkList - remove all instances of N from the worklist.
113     ///
114     void removeFromWorkList(SDNode *N) {
115       WorkListContents.erase(N);
116     }
117
118     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
119                       bool AddTo = true);
120
121     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
122       return CombineTo(N, &Res, 1, AddTo);
123     }
124
125     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
126                       bool AddTo = true) {
127       SDValue To[] = { Res0, Res1 };
128       return CombineTo(N, To, 2, AddTo);
129     }
130
131     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
132
133   private:
134
135     /// SimplifyDemandedBits - Check the specified integer node value to see if
136     /// it can be simplified or if things it uses can be simplified by bit
137     /// propagation.  If so, return true.
138     bool SimplifyDemandedBits(SDValue Op) {
139       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
140       APInt Demanded = APInt::getAllOnesValue(BitWidth);
141       return SimplifyDemandedBits(Op, Demanded);
142     }
143
144     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
145
146     bool CombineToPreIndexedLoadStore(SDNode *N);
147     bool CombineToPostIndexedLoadStore(SDNode *N);
148
149     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
150     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
151     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
152     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
153     SDValue PromoteIntBinOp(SDValue Op);
154     SDValue PromoteIntShiftOp(SDValue Op);
155     SDValue PromoteExtend(SDValue Op);
156     bool PromoteLoad(SDValue Op);
157
158     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
159                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
160                          ISD::NodeType ExtType);
161
162     /// combine - call the node-specific routine that knows how to fold each
163     /// particular type of node. If that doesn't do anything, try the
164     /// target-specific DAG combines.
165     SDValue combine(SDNode *N);
166
167     // Visitation implementation - Implement dag node combining for different
168     // node types.  The semantics are as follows:
169     // Return Value:
170     //   SDValue.getNode() == 0 - No change was made
171     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
172     //   otherwise              - N should be replaced by the returned Operand.
173     //
174     SDValue visitTokenFactor(SDNode *N);
175     SDValue visitMERGE_VALUES(SDNode *N);
176     SDValue visitADD(SDNode *N);
177     SDValue visitSUB(SDNode *N);
178     SDValue visitADDC(SDNode *N);
179     SDValue visitSUBC(SDNode *N);
180     SDValue visitADDE(SDNode *N);
181     SDValue visitSUBE(SDNode *N);
182     SDValue visitMUL(SDNode *N);
183     SDValue visitSDIV(SDNode *N);
184     SDValue visitUDIV(SDNode *N);
185     SDValue visitSREM(SDNode *N);
186     SDValue visitUREM(SDNode *N);
187     SDValue visitMULHU(SDNode *N);
188     SDValue visitMULHS(SDNode *N);
189     SDValue visitSMUL_LOHI(SDNode *N);
190     SDValue visitUMUL_LOHI(SDNode *N);
191     SDValue visitSMULO(SDNode *N);
192     SDValue visitUMULO(SDNode *N);
193     SDValue visitSDIVREM(SDNode *N);
194     SDValue visitUDIVREM(SDNode *N);
195     SDValue visitAND(SDNode *N);
196     SDValue visitOR(SDNode *N);
197     SDValue visitXOR(SDNode *N);
198     SDValue SimplifyVBinOp(SDNode *N);
199     SDValue SimplifyVUnaryOp(SDNode *N);
200     SDValue visitSHL(SDNode *N);
201     SDValue visitSRA(SDNode *N);
202     SDValue visitSRL(SDNode *N);
203     SDValue visitCTLZ(SDNode *N);
204     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
205     SDValue visitCTTZ(SDNode *N);
206     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
207     SDValue visitCTPOP(SDNode *N);
208     SDValue visitSELECT(SDNode *N);
209     SDValue visitVSELECT(SDNode *N);
210     SDValue visitSELECT_CC(SDNode *N);
211     SDValue visitSETCC(SDNode *N);
212     SDValue visitSIGN_EXTEND(SDNode *N);
213     SDValue visitZERO_EXTEND(SDNode *N);
214     SDValue visitANY_EXTEND(SDNode *N);
215     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
216     SDValue visitTRUNCATE(SDNode *N);
217     SDValue visitBITCAST(SDNode *N);
218     SDValue visitBUILD_PAIR(SDNode *N);
219     SDValue visitFADD(SDNode *N);
220     SDValue visitFSUB(SDNode *N);
221     SDValue visitFMUL(SDNode *N);
222     SDValue visitFMA(SDNode *N);
223     SDValue visitFDIV(SDNode *N);
224     SDValue visitFREM(SDNode *N);
225     SDValue visitFCOPYSIGN(SDNode *N);
226     SDValue visitSINT_TO_FP(SDNode *N);
227     SDValue visitUINT_TO_FP(SDNode *N);
228     SDValue visitFP_TO_SINT(SDNode *N);
229     SDValue visitFP_TO_UINT(SDNode *N);
230     SDValue visitFP_ROUND(SDNode *N);
231     SDValue visitFP_ROUND_INREG(SDNode *N);
232     SDValue visitFP_EXTEND(SDNode *N);
233     SDValue visitFNEG(SDNode *N);
234     SDValue visitFABS(SDNode *N);
235     SDValue visitFCEIL(SDNode *N);
236     SDValue visitFTRUNC(SDNode *N);
237     SDValue visitFFLOOR(SDNode *N);
238     SDValue visitBRCOND(SDNode *N);
239     SDValue visitBR_CC(SDNode *N);
240     SDValue visitLOAD(SDNode *N);
241     SDValue visitSTORE(SDNode *N);
242     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
243     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
244     SDValue visitBUILD_VECTOR(SDNode *N);
245     SDValue visitCONCAT_VECTORS(SDNode *N);
246     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
247     SDValue visitVECTOR_SHUFFLE(SDNode *N);
248
249     SDValue XformToShuffleWithZero(SDNode *N);
250     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
251
252     SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
253
254     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
255     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
256     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
257     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
258                              SDValue N3, ISD::CondCode CC,
259                              bool NotExtCompare = false);
260     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
261                           SDLoc DL, bool foldBooleans = true);
262     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
263                                          unsigned HiOp);
264     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
265     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
266     SDValue BuildSDIV(SDNode *N);
267     SDValue BuildUDIV(SDNode *N);
268     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
269                                bool DemandHighBits = true);
270     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
271     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
272     SDValue ReduceLoadWidth(SDNode *N);
273     SDValue ReduceLoadOpStoreWidth(SDNode *N);
274     SDValue TransformFPLoadStorePair(SDNode *N);
275     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
276     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
277
278     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
279
280     /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
281     /// looking for aliasing nodes and adding them to the Aliases vector.
282     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
283                           SmallVectorImpl<SDValue> &Aliases);
284
285     /// isAlias - Return true if there is any possibility that the two addresses
286     /// overlap.
287     bool isAlias(SDValue Ptr1, int64_t Size1,
288                  const Value *SrcValue1, int SrcValueOffset1,
289                  unsigned SrcValueAlign1,
290                  const MDNode *TBAAInfo1,
291                  SDValue Ptr2, int64_t Size2,
292                  const Value *SrcValue2, int SrcValueOffset2,
293                  unsigned SrcValueAlign2,
294                  const MDNode *TBAAInfo2) const;
295
296     /// isAlias - Return true if there is any possibility that the two addresses
297     /// overlap.
298     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1);
299
300     /// FindAliasInfo - Extracts the relevant alias information from the memory
301     /// node.  Returns true if the operand was a load.
302     bool FindAliasInfo(SDNode *N,
303                        SDValue &Ptr, int64_t &Size,
304                        const Value *&SrcValue, int &SrcValueOffset,
305                        unsigned &SrcValueAlignment,
306                        const MDNode *&TBAAInfo) const;
307
308     /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
309     /// looking for a better chain (aliasing node.)
310     SDValue FindBetterChain(SDNode *N, SDValue Chain);
311
312     /// Merge consecutive store operations into a wide store.
313     /// This optimization uses wide integers or vectors when possible.
314     /// \return True if some memory operations were changed.
315     bool MergeConsecutiveStores(StoreSDNode *N);
316
317   public:
318     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
319       : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
320         OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {}
321
322     /// Run - runs the dag combiner on all nodes in the work list
323     void Run(CombineLevel AtLevel);
324
325     SelectionDAG &getDAG() const { return DAG; }
326
327     /// getShiftAmountTy - Returns a type large enough to hold any valid
328     /// shift amount - before type legalization these can be huge.
329     EVT getShiftAmountTy(EVT LHSTy) {
330       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
331       if (LHSTy.isVector())
332         return LHSTy;
333       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy) : TLI.getPointerTy();
334     }
335
336     /// isTypeLegal - This method returns true if we are running before type
337     /// legalization or if the specified VT is legal.
338     bool isTypeLegal(const EVT &VT) {
339       if (!LegalTypes) return true;
340       return TLI.isTypeLegal(VT);
341     }
342
343     /// getSetCCResultType - Convenience wrapper around
344     /// TargetLowering::getSetCCResultType
345     EVT getSetCCResultType(EVT VT) const {
346       return TLI.getSetCCResultType(*DAG.getContext(), VT);
347     }
348   };
349 }
350
351
352 namespace {
353 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
354 /// nodes from the worklist.
355 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
356   DAGCombiner &DC;
357 public:
358   explicit WorkListRemover(DAGCombiner &dc)
359     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
360
361   virtual void NodeDeleted(SDNode *N, SDNode *E) {
362     DC.removeFromWorkList(N);
363   }
364 };
365 }
366
367 //===----------------------------------------------------------------------===//
368 //  TargetLowering::DAGCombinerInfo implementation
369 //===----------------------------------------------------------------------===//
370
371 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
372   ((DAGCombiner*)DC)->AddToWorkList(N);
373 }
374
375 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
376   ((DAGCombiner*)DC)->removeFromWorkList(N);
377 }
378
379 SDValue TargetLowering::DAGCombinerInfo::
380 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
381   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
382 }
383
384 SDValue TargetLowering::DAGCombinerInfo::
385 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
386   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
387 }
388
389
390 SDValue TargetLowering::DAGCombinerInfo::
391 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
392   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
393 }
394
395 void TargetLowering::DAGCombinerInfo::
396 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
397   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
398 }
399
400 //===----------------------------------------------------------------------===//
401 // Helper Functions
402 //===----------------------------------------------------------------------===//
403
404 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
405 /// specified expression for the same cost as the expression itself, or 2 if we
406 /// can compute the negated form more cheaply than the expression itself.
407 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
408                                const TargetLowering &TLI,
409                                const TargetOptions *Options,
410                                unsigned Depth = 0) {
411   // fneg is removable even if it has multiple uses.
412   if (Op.getOpcode() == ISD::FNEG) return 2;
413
414   // Don't allow anything with multiple uses.
415   if (!Op.hasOneUse()) return 0;
416
417   // Don't recurse exponentially.
418   if (Depth > 6) return 0;
419
420   switch (Op.getOpcode()) {
421   default: return false;
422   case ISD::ConstantFP:
423     // Don't invert constant FP values after legalize.  The negated constant
424     // isn't necessarily legal.
425     return LegalOperations ? 0 : 1;
426   case ISD::FADD:
427     // FIXME: determine better conditions for this xform.
428     if (!Options->UnsafeFPMath) return 0;
429
430     // After operation legalization, it might not be legal to create new FSUBs.
431     if (LegalOperations &&
432         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
433       return 0;
434
435     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
436     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
437                                     Options, Depth + 1))
438       return V;
439     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
440     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
441                               Depth + 1);
442   case ISD::FSUB:
443     // We can't turn -(A-B) into B-A when we honor signed zeros.
444     if (!Options->UnsafeFPMath) return 0;
445
446     // fold (fneg (fsub A, B)) -> (fsub B, A)
447     return 1;
448
449   case ISD::FMUL:
450   case ISD::FDIV:
451     if (Options->HonorSignDependentRoundingFPMath()) return 0;
452
453     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
454     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
455                                     Options, Depth + 1))
456       return V;
457
458     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
459                               Depth + 1);
460
461   case ISD::FP_EXTEND:
462   case ISD::FP_ROUND:
463   case ISD::FSIN:
464     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
465                               Depth + 1);
466   }
467 }
468
469 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
470 /// returns the newly negated expression.
471 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
472                                     bool LegalOperations, unsigned Depth = 0) {
473   // fneg is removable even if it has multiple uses.
474   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
475
476   // Don't allow anything with multiple uses.
477   assert(Op.hasOneUse() && "Unknown reuse!");
478
479   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
480   switch (Op.getOpcode()) {
481   default: llvm_unreachable("Unknown code");
482   case ISD::ConstantFP: {
483     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
484     V.changeSign();
485     return DAG.getConstantFP(V, Op.getValueType());
486   }
487   case ISD::FADD:
488     // FIXME: determine better conditions for this xform.
489     assert(DAG.getTarget().Options.UnsafeFPMath);
490
491     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
492     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
493                            DAG.getTargetLoweringInfo(),
494                            &DAG.getTarget().Options, Depth+1))
495       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
496                          GetNegatedExpression(Op.getOperand(0), DAG,
497                                               LegalOperations, Depth+1),
498                          Op.getOperand(1));
499     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
500     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
501                        GetNegatedExpression(Op.getOperand(1), DAG,
502                                             LegalOperations, Depth+1),
503                        Op.getOperand(0));
504   case ISD::FSUB:
505     // We can't turn -(A-B) into B-A when we honor signed zeros.
506     assert(DAG.getTarget().Options.UnsafeFPMath);
507
508     // fold (fneg (fsub 0, B)) -> B
509     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
510       if (N0CFP->getValueAPF().isZero())
511         return Op.getOperand(1);
512
513     // fold (fneg (fsub A, B)) -> (fsub B, A)
514     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
515                        Op.getOperand(1), Op.getOperand(0));
516
517   case ISD::FMUL:
518   case ISD::FDIV:
519     assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
520
521     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
522     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
523                            DAG.getTargetLoweringInfo(),
524                            &DAG.getTarget().Options, Depth+1))
525       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
526                          GetNegatedExpression(Op.getOperand(0), DAG,
527                                               LegalOperations, Depth+1),
528                          Op.getOperand(1));
529
530     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
531     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
532                        Op.getOperand(0),
533                        GetNegatedExpression(Op.getOperand(1), DAG,
534                                             LegalOperations, Depth+1));
535
536   case ISD::FP_EXTEND:
537   case ISD::FSIN:
538     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
539                        GetNegatedExpression(Op.getOperand(0), DAG,
540                                             LegalOperations, Depth+1));
541   case ISD::FP_ROUND:
542       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
543                          GetNegatedExpression(Op.getOperand(0), DAG,
544                                               LegalOperations, Depth+1),
545                          Op.getOperand(1));
546   }
547 }
548
549
550 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
551 // that selects between the values 1 and 0, making it equivalent to a setcc.
552 // Also, set the incoming LHS, RHS, and CC references to the appropriate
553 // nodes based on the type of node we are checking.  This simplifies life a
554 // bit for the callers.
555 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
556                               SDValue &CC) {
557   if (N.getOpcode() == ISD::SETCC) {
558     LHS = N.getOperand(0);
559     RHS = N.getOperand(1);
560     CC  = N.getOperand(2);
561     return true;
562   }
563   if (N.getOpcode() == ISD::SELECT_CC &&
564       N.getOperand(2).getOpcode() == ISD::Constant &&
565       N.getOperand(3).getOpcode() == ISD::Constant &&
566       cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
567       cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
568     LHS = N.getOperand(0);
569     RHS = N.getOperand(1);
570     CC  = N.getOperand(4);
571     return true;
572   }
573   return false;
574 }
575
576 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
577 // one use.  If this is true, it allows the users to invert the operation for
578 // free when it is profitable to do so.
579 static bool isOneUseSetCC(SDValue N) {
580   SDValue N0, N1, N2;
581   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
582     return true;
583   return false;
584 }
585
586 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
587                                     SDValue N0, SDValue N1) {
588   EVT VT = N0.getValueType();
589   if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
590     if (isa<ConstantSDNode>(N1)) {
591       // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
592       SDValue OpNode =
593         DAG.FoldConstantArithmetic(Opc, VT,
594                                    cast<ConstantSDNode>(N0.getOperand(1)),
595                                    cast<ConstantSDNode>(N1));
596       return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
597     }
598     if (N0.hasOneUse()) {
599       // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
600       SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT,
601                                    N0.getOperand(0), N1);
602       AddToWorkList(OpNode.getNode());
603       return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
604     }
605   }
606
607   if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
608     if (isa<ConstantSDNode>(N0)) {
609       // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
610       SDValue OpNode =
611         DAG.FoldConstantArithmetic(Opc, VT,
612                                    cast<ConstantSDNode>(N1.getOperand(1)),
613                                    cast<ConstantSDNode>(N0));
614       return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
615     }
616     if (N1.hasOneUse()) {
617       // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
618       SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT,
619                                    N1.getOperand(0), N0);
620       AddToWorkList(OpNode.getNode());
621       return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
622     }
623   }
624
625   return SDValue();
626 }
627
628 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
629                                bool AddTo) {
630   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
631   ++NodesCombined;
632   DEBUG(dbgs() << "\nReplacing.1 ";
633         N->dump(&DAG);
634         dbgs() << "\nWith: ";
635         To[0].getNode()->dump(&DAG);
636         dbgs() << " and " << NumTo-1 << " other values\n";
637         for (unsigned i = 0, e = NumTo; i != e; ++i)
638           assert((!To[i].getNode() ||
639                   N->getValueType(i) == To[i].getValueType()) &&
640                  "Cannot combine value to value of different type!"));
641   WorkListRemover DeadNodes(*this);
642   DAG.ReplaceAllUsesWith(N, To);
643   if (AddTo) {
644     // Push the new nodes and any users onto the worklist
645     for (unsigned i = 0, e = NumTo; i != e; ++i) {
646       if (To[i].getNode()) {
647         AddToWorkList(To[i].getNode());
648         AddUsersToWorkList(To[i].getNode());
649       }
650     }
651   }
652
653   // Finally, if the node is now dead, remove it from the graph.  The node
654   // may not be dead if the replacement process recursively simplified to
655   // something else needing this node.
656   if (N->use_empty()) {
657     // Nodes can be reintroduced into the worklist.  Make sure we do not
658     // process a node that has been replaced.
659     removeFromWorkList(N);
660
661     // Finally, since the node is now dead, remove it from the graph.
662     DAG.DeleteNode(N);
663   }
664   return SDValue(N, 0);
665 }
666
667 void DAGCombiner::
668 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
669   // Replace all uses.  If any nodes become isomorphic to other nodes and
670   // are deleted, make sure to remove them from our worklist.
671   WorkListRemover DeadNodes(*this);
672   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
673
674   // Push the new node and any (possibly new) users onto the worklist.
675   AddToWorkList(TLO.New.getNode());
676   AddUsersToWorkList(TLO.New.getNode());
677
678   // Finally, if the node is now dead, remove it from the graph.  The node
679   // may not be dead if the replacement process recursively simplified to
680   // something else needing this node.
681   if (TLO.Old.getNode()->use_empty()) {
682     removeFromWorkList(TLO.Old.getNode());
683
684     // If the operands of this node are only used by the node, they will now
685     // be dead.  Make sure to visit them first to delete dead nodes early.
686     for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
687       if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
688         AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
689
690     DAG.DeleteNode(TLO.Old.getNode());
691   }
692 }
693
694 /// SimplifyDemandedBits - Check the specified integer node value to see if
695 /// it can be simplified or if things it uses can be simplified by bit
696 /// propagation.  If so, return true.
697 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
698   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
699   APInt KnownZero, KnownOne;
700   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
701     return false;
702
703   // Revisit the node.
704   AddToWorkList(Op.getNode());
705
706   // Replace the old value with the new one.
707   ++NodesCombined;
708   DEBUG(dbgs() << "\nReplacing.2 ";
709         TLO.Old.getNode()->dump(&DAG);
710         dbgs() << "\nWith: ";
711         TLO.New.getNode()->dump(&DAG);
712         dbgs() << '\n');
713
714   CommitTargetLoweringOpt(TLO);
715   return true;
716 }
717
718 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
719   SDLoc dl(Load);
720   EVT VT = Load->getValueType(0);
721   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
722
723   DEBUG(dbgs() << "\nReplacing.9 ";
724         Load->dump(&DAG);
725         dbgs() << "\nWith: ";
726         Trunc.getNode()->dump(&DAG);
727         dbgs() << '\n');
728   WorkListRemover DeadNodes(*this);
729   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
730   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
731   removeFromWorkList(Load);
732   DAG.DeleteNode(Load);
733   AddToWorkList(Trunc.getNode());
734 }
735
736 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
737   Replace = false;
738   SDLoc dl(Op);
739   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
740     EVT MemVT = LD->getMemoryVT();
741     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
742       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
743                                                   : ISD::EXTLOAD)
744       : LD->getExtensionType();
745     Replace = true;
746     return DAG.getExtLoad(ExtType, dl, PVT,
747                           LD->getChain(), LD->getBasePtr(),
748                           LD->getPointerInfo(),
749                           MemVT, LD->isVolatile(),
750                           LD->isNonTemporal(), LD->getAlignment());
751   }
752
753   unsigned Opc = Op.getOpcode();
754   switch (Opc) {
755   default: break;
756   case ISD::AssertSext:
757     return DAG.getNode(ISD::AssertSext, dl, PVT,
758                        SExtPromoteOperand(Op.getOperand(0), PVT),
759                        Op.getOperand(1));
760   case ISD::AssertZext:
761     return DAG.getNode(ISD::AssertZext, dl, PVT,
762                        ZExtPromoteOperand(Op.getOperand(0), PVT),
763                        Op.getOperand(1));
764   case ISD::Constant: {
765     unsigned ExtOpc =
766       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
767     return DAG.getNode(ExtOpc, dl, PVT, Op);
768   }
769   }
770
771   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
772     return SDValue();
773   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
774 }
775
776 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
777   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
778     return SDValue();
779   EVT OldVT = Op.getValueType();
780   SDLoc dl(Op);
781   bool Replace = false;
782   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
783   if (NewOp.getNode() == 0)
784     return SDValue();
785   AddToWorkList(NewOp.getNode());
786
787   if (Replace)
788     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
789   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
790                      DAG.getValueType(OldVT));
791 }
792
793 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
794   EVT OldVT = Op.getValueType();
795   SDLoc dl(Op);
796   bool Replace = false;
797   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
798   if (NewOp.getNode() == 0)
799     return SDValue();
800   AddToWorkList(NewOp.getNode());
801
802   if (Replace)
803     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
804   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
805 }
806
807 /// PromoteIntBinOp - Promote the specified integer binary operation if the
808 /// target indicates it is beneficial. e.g. On x86, it's usually better to
809 /// promote i16 operations to i32 since i16 instructions are longer.
810 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
811   if (!LegalOperations)
812     return SDValue();
813
814   EVT VT = Op.getValueType();
815   if (VT.isVector() || !VT.isInteger())
816     return SDValue();
817
818   // If operation type is 'undesirable', e.g. i16 on x86, consider
819   // promoting it.
820   unsigned Opc = Op.getOpcode();
821   if (TLI.isTypeDesirableForOp(Opc, VT))
822     return SDValue();
823
824   EVT PVT = VT;
825   // Consult target whether it is a good idea to promote this operation and
826   // what's the right type to promote it to.
827   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
828     assert(PVT != VT && "Don't know what type to promote to!");
829
830     bool Replace0 = false;
831     SDValue N0 = Op.getOperand(0);
832     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
833     if (NN0.getNode() == 0)
834       return SDValue();
835
836     bool Replace1 = false;
837     SDValue N1 = Op.getOperand(1);
838     SDValue NN1;
839     if (N0 == N1)
840       NN1 = NN0;
841     else {
842       NN1 = PromoteOperand(N1, PVT, Replace1);
843       if (NN1.getNode() == 0)
844         return SDValue();
845     }
846
847     AddToWorkList(NN0.getNode());
848     if (NN1.getNode())
849       AddToWorkList(NN1.getNode());
850
851     if (Replace0)
852       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
853     if (Replace1)
854       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
855
856     DEBUG(dbgs() << "\nPromoting ";
857           Op.getNode()->dump(&DAG));
858     SDLoc dl(Op);
859     return DAG.getNode(ISD::TRUNCATE, dl, VT,
860                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
861   }
862   return SDValue();
863 }
864
865 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
866 /// target indicates it is beneficial. e.g. On x86, it's usually better to
867 /// promote i16 operations to i32 since i16 instructions are longer.
868 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
869   if (!LegalOperations)
870     return SDValue();
871
872   EVT VT = Op.getValueType();
873   if (VT.isVector() || !VT.isInteger())
874     return SDValue();
875
876   // If operation type is 'undesirable', e.g. i16 on x86, consider
877   // promoting it.
878   unsigned Opc = Op.getOpcode();
879   if (TLI.isTypeDesirableForOp(Opc, VT))
880     return SDValue();
881
882   EVT PVT = VT;
883   // Consult target whether it is a good idea to promote this operation and
884   // what's the right type to promote it to.
885   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
886     assert(PVT != VT && "Don't know what type to promote to!");
887
888     bool Replace = false;
889     SDValue N0 = Op.getOperand(0);
890     if (Opc == ISD::SRA)
891       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
892     else if (Opc == ISD::SRL)
893       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
894     else
895       N0 = PromoteOperand(N0, PVT, Replace);
896     if (N0.getNode() == 0)
897       return SDValue();
898
899     AddToWorkList(N0.getNode());
900     if (Replace)
901       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
902
903     DEBUG(dbgs() << "\nPromoting ";
904           Op.getNode()->dump(&DAG));
905     SDLoc dl(Op);
906     return DAG.getNode(ISD::TRUNCATE, dl, VT,
907                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
908   }
909   return SDValue();
910 }
911
912 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
913   if (!LegalOperations)
914     return SDValue();
915
916   EVT VT = Op.getValueType();
917   if (VT.isVector() || !VT.isInteger())
918     return SDValue();
919
920   // If operation type is 'undesirable', e.g. i16 on x86, consider
921   // promoting it.
922   unsigned Opc = Op.getOpcode();
923   if (TLI.isTypeDesirableForOp(Opc, VT))
924     return SDValue();
925
926   EVT PVT = VT;
927   // Consult target whether it is a good idea to promote this operation and
928   // what's the right type to promote it to.
929   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
930     assert(PVT != VT && "Don't know what type to promote to!");
931     // fold (aext (aext x)) -> (aext x)
932     // fold (aext (zext x)) -> (zext x)
933     // fold (aext (sext x)) -> (sext x)
934     DEBUG(dbgs() << "\nPromoting ";
935           Op.getNode()->dump(&DAG));
936     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
937   }
938   return SDValue();
939 }
940
941 bool DAGCombiner::PromoteLoad(SDValue Op) {
942   if (!LegalOperations)
943     return false;
944
945   EVT VT = Op.getValueType();
946   if (VT.isVector() || !VT.isInteger())
947     return false;
948
949   // If operation type is 'undesirable', e.g. i16 on x86, consider
950   // promoting it.
951   unsigned Opc = Op.getOpcode();
952   if (TLI.isTypeDesirableForOp(Opc, VT))
953     return false;
954
955   EVT PVT = VT;
956   // Consult target whether it is a good idea to promote this operation and
957   // what's the right type to promote it to.
958   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
959     assert(PVT != VT && "Don't know what type to promote to!");
960
961     SDLoc dl(Op);
962     SDNode *N = Op.getNode();
963     LoadSDNode *LD = cast<LoadSDNode>(N);
964     EVT MemVT = LD->getMemoryVT();
965     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
966       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
967                                                   : ISD::EXTLOAD)
968       : LD->getExtensionType();
969     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
970                                    LD->getChain(), LD->getBasePtr(),
971                                    LD->getPointerInfo(),
972                                    MemVT, LD->isVolatile(),
973                                    LD->isNonTemporal(), LD->getAlignment());
974     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
975
976     DEBUG(dbgs() << "\nPromoting ";
977           N->dump(&DAG);
978           dbgs() << "\nTo: ";
979           Result.getNode()->dump(&DAG);
980           dbgs() << '\n');
981     WorkListRemover DeadNodes(*this);
982     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
983     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
984     removeFromWorkList(N);
985     DAG.DeleteNode(N);
986     AddToWorkList(Result.getNode());
987     return true;
988   }
989   return false;
990 }
991
992
993 //===----------------------------------------------------------------------===//
994 //  Main DAG Combiner implementation
995 //===----------------------------------------------------------------------===//
996
997 void DAGCombiner::Run(CombineLevel AtLevel) {
998   // set the instance variables, so that the various visit routines may use it.
999   Level = AtLevel;
1000   LegalOperations = Level >= AfterLegalizeVectorOps;
1001   LegalTypes = Level >= AfterLegalizeTypes;
1002
1003   // Add all the dag nodes to the worklist.
1004   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1005        E = DAG.allnodes_end(); I != E; ++I)
1006     AddToWorkList(I);
1007
1008   // Create a dummy node (which is not added to allnodes), that adds a reference
1009   // to the root node, preventing it from being deleted, and tracking any
1010   // changes of the root.
1011   HandleSDNode Dummy(DAG.getRoot());
1012
1013   // The root of the dag may dangle to deleted nodes until the dag combiner is
1014   // done.  Set it to null to avoid confusion.
1015   DAG.setRoot(SDValue());
1016
1017   // while the worklist isn't empty, find a node and
1018   // try and combine it.
1019   while (!WorkListContents.empty()) {
1020     SDNode *N;
1021     // The WorkListOrder holds the SDNodes in order, but it may contain duplicates.
1022     // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1023     // worklist *should* contain, and check the node we want to visit is should
1024     // actually be visited.
1025     do {
1026       N = WorkListOrder.pop_back_val();
1027     } while (!WorkListContents.erase(N));
1028
1029     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1030     // N is deleted from the DAG, since they too may now be dead or may have a
1031     // reduced number of uses, allowing other xforms.
1032     if (N->use_empty() && N != &Dummy) {
1033       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1034         AddToWorkList(N->getOperand(i).getNode());
1035
1036       DAG.DeleteNode(N);
1037       continue;
1038     }
1039
1040     SDValue RV = combine(N);
1041
1042     if (RV.getNode() == 0)
1043       continue;
1044
1045     ++NodesCombined;
1046
1047     // If we get back the same node we passed in, rather than a new node or
1048     // zero, we know that the node must have defined multiple values and
1049     // CombineTo was used.  Since CombineTo takes care of the worklist
1050     // mechanics for us, we have no work to do in this case.
1051     if (RV.getNode() == N)
1052       continue;
1053
1054     assert(N->getOpcode() != ISD::DELETED_NODE &&
1055            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1056            "Node was deleted but visit returned new node!");
1057
1058     DEBUG(dbgs() << "\nReplacing.3 ";
1059           N->dump(&DAG);
1060           dbgs() << "\nWith: ";
1061           RV.getNode()->dump(&DAG);
1062           dbgs() << '\n');
1063
1064     // Transfer debug value.
1065     DAG.TransferDbgValues(SDValue(N, 0), RV);
1066     WorkListRemover DeadNodes(*this);
1067     if (N->getNumValues() == RV.getNode()->getNumValues())
1068       DAG.ReplaceAllUsesWith(N, RV.getNode());
1069     else {
1070       assert(N->getValueType(0) == RV.getValueType() &&
1071              N->getNumValues() == 1 && "Type mismatch");
1072       SDValue OpV = RV;
1073       DAG.ReplaceAllUsesWith(N, &OpV);
1074     }
1075
1076     // Push the new node and any users onto the worklist
1077     AddToWorkList(RV.getNode());
1078     AddUsersToWorkList(RV.getNode());
1079
1080     // Add any uses of the old node to the worklist in case this node is the
1081     // last one that uses them.  They may become dead after this node is
1082     // deleted.
1083     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1084       AddToWorkList(N->getOperand(i).getNode());
1085
1086     // Finally, if the node is now dead, remove it from the graph.  The node
1087     // may not be dead if the replacement process recursively simplified to
1088     // something else needing this node.
1089     if (N->use_empty()) {
1090       // Nodes can be reintroduced into the worklist.  Make sure we do not
1091       // process a node that has been replaced.
1092       removeFromWorkList(N);
1093
1094       // Finally, since the node is now dead, remove it from the graph.
1095       DAG.DeleteNode(N);
1096     }
1097   }
1098
1099   // If the root changed (e.g. it was a dead load, update the root).
1100   DAG.setRoot(Dummy.getValue());
1101   DAG.RemoveDeadNodes();
1102 }
1103
1104 SDValue DAGCombiner::visit(SDNode *N) {
1105   switch (N->getOpcode()) {
1106   default: break;
1107   case ISD::TokenFactor:        return visitTokenFactor(N);
1108   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1109   case ISD::ADD:                return visitADD(N);
1110   case ISD::SUB:                return visitSUB(N);
1111   case ISD::ADDC:               return visitADDC(N);
1112   case ISD::SUBC:               return visitSUBC(N);
1113   case ISD::ADDE:               return visitADDE(N);
1114   case ISD::SUBE:               return visitSUBE(N);
1115   case ISD::MUL:                return visitMUL(N);
1116   case ISD::SDIV:               return visitSDIV(N);
1117   case ISD::UDIV:               return visitUDIV(N);
1118   case ISD::SREM:               return visitSREM(N);
1119   case ISD::UREM:               return visitUREM(N);
1120   case ISD::MULHU:              return visitMULHU(N);
1121   case ISD::MULHS:              return visitMULHS(N);
1122   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1123   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1124   case ISD::SMULO:              return visitSMULO(N);
1125   case ISD::UMULO:              return visitUMULO(N);
1126   case ISD::SDIVREM:            return visitSDIVREM(N);
1127   case ISD::UDIVREM:            return visitUDIVREM(N);
1128   case ISD::AND:                return visitAND(N);
1129   case ISD::OR:                 return visitOR(N);
1130   case ISD::XOR:                return visitXOR(N);
1131   case ISD::SHL:                return visitSHL(N);
1132   case ISD::SRA:                return visitSRA(N);
1133   case ISD::SRL:                return visitSRL(N);
1134   case ISD::CTLZ:               return visitCTLZ(N);
1135   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1136   case ISD::CTTZ:               return visitCTTZ(N);
1137   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1138   case ISD::CTPOP:              return visitCTPOP(N);
1139   case ISD::SELECT:             return visitSELECT(N);
1140   case ISD::VSELECT:            return visitVSELECT(N);
1141   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1142   case ISD::SETCC:              return visitSETCC(N);
1143   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1144   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1145   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1146   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1147   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1148   case ISD::BITCAST:            return visitBITCAST(N);
1149   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1150   case ISD::FADD:               return visitFADD(N);
1151   case ISD::FSUB:               return visitFSUB(N);
1152   case ISD::FMUL:               return visitFMUL(N);
1153   case ISD::FMA:                return visitFMA(N);
1154   case ISD::FDIV:               return visitFDIV(N);
1155   case ISD::FREM:               return visitFREM(N);
1156   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1157   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1158   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1159   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1160   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1161   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1162   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1163   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1164   case ISD::FNEG:               return visitFNEG(N);
1165   case ISD::FABS:               return visitFABS(N);
1166   case ISD::FFLOOR:             return visitFFLOOR(N);
1167   case ISD::FCEIL:              return visitFCEIL(N);
1168   case ISD::FTRUNC:             return visitFTRUNC(N);
1169   case ISD::BRCOND:             return visitBRCOND(N);
1170   case ISD::BR_CC:              return visitBR_CC(N);
1171   case ISD::LOAD:               return visitLOAD(N);
1172   case ISD::STORE:              return visitSTORE(N);
1173   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1174   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1175   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1176   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1177   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1178   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1179   }
1180   return SDValue();
1181 }
1182
1183 SDValue DAGCombiner::combine(SDNode *N) {
1184   SDValue RV = visit(N);
1185
1186   // If nothing happened, try a target-specific DAG combine.
1187   if (RV.getNode() == 0) {
1188     assert(N->getOpcode() != ISD::DELETED_NODE &&
1189            "Node was deleted but visit returned NULL!");
1190
1191     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1192         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1193
1194       // Expose the DAG combiner to the target combiner impls.
1195       TargetLowering::DAGCombinerInfo
1196         DagCombineInfo(DAG, Level, false, this);
1197
1198       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1199     }
1200   }
1201
1202   // If nothing happened still, try promoting the operation.
1203   if (RV.getNode() == 0) {
1204     switch (N->getOpcode()) {
1205     default: break;
1206     case ISD::ADD:
1207     case ISD::SUB:
1208     case ISD::MUL:
1209     case ISD::AND:
1210     case ISD::OR:
1211     case ISD::XOR:
1212       RV = PromoteIntBinOp(SDValue(N, 0));
1213       break;
1214     case ISD::SHL:
1215     case ISD::SRA:
1216     case ISD::SRL:
1217       RV = PromoteIntShiftOp(SDValue(N, 0));
1218       break;
1219     case ISD::SIGN_EXTEND:
1220     case ISD::ZERO_EXTEND:
1221     case ISD::ANY_EXTEND:
1222       RV = PromoteExtend(SDValue(N, 0));
1223       break;
1224     case ISD::LOAD:
1225       if (PromoteLoad(SDValue(N, 0)))
1226         RV = SDValue(N, 0);
1227       break;
1228     }
1229   }
1230
1231   // If N is a commutative binary node, try commuting it to enable more
1232   // sdisel CSE.
1233   if (RV.getNode() == 0 &&
1234       SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1235       N->getNumValues() == 1) {
1236     SDValue N0 = N->getOperand(0);
1237     SDValue N1 = N->getOperand(1);
1238
1239     // Constant operands are canonicalized to RHS.
1240     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1241       SDValue Ops[] = { N1, N0 };
1242       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1243                                             Ops, 2);
1244       if (CSENode)
1245         return SDValue(CSENode, 0);
1246     }
1247   }
1248
1249   return RV;
1250 }
1251
1252 /// getInputChainForNode - Given a node, return its input chain if it has one,
1253 /// otherwise return a null sd operand.
1254 static SDValue getInputChainForNode(SDNode *N) {
1255   if (unsigned NumOps = N->getNumOperands()) {
1256     if (N->getOperand(0).getValueType() == MVT::Other)
1257       return N->getOperand(0);
1258     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1259       return N->getOperand(NumOps-1);
1260     for (unsigned i = 1; i < NumOps-1; ++i)
1261       if (N->getOperand(i).getValueType() == MVT::Other)
1262         return N->getOperand(i);
1263   }
1264   return SDValue();
1265 }
1266
1267 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1268   // If N has two operands, where one has an input chain equal to the other,
1269   // the 'other' chain is redundant.
1270   if (N->getNumOperands() == 2) {
1271     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1272       return N->getOperand(0);
1273     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1274       return N->getOperand(1);
1275   }
1276
1277   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1278   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1279   SmallPtrSet<SDNode*, 16> SeenOps;
1280   bool Changed = false;             // If we should replace this token factor.
1281
1282   // Start out with this token factor.
1283   TFs.push_back(N);
1284
1285   // Iterate through token factors.  The TFs grows when new token factors are
1286   // encountered.
1287   for (unsigned i = 0; i < TFs.size(); ++i) {
1288     SDNode *TF = TFs[i];
1289
1290     // Check each of the operands.
1291     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1292       SDValue Op = TF->getOperand(i);
1293
1294       switch (Op.getOpcode()) {
1295       case ISD::EntryToken:
1296         // Entry tokens don't need to be added to the list. They are
1297         // rededundant.
1298         Changed = true;
1299         break;
1300
1301       case ISD::TokenFactor:
1302         if (Op.hasOneUse() &&
1303             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1304           // Queue up for processing.
1305           TFs.push_back(Op.getNode());
1306           // Clean up in case the token factor is removed.
1307           AddToWorkList(Op.getNode());
1308           Changed = true;
1309           break;
1310         }
1311         // Fall thru
1312
1313       default:
1314         // Only add if it isn't already in the list.
1315         if (SeenOps.insert(Op.getNode()))
1316           Ops.push_back(Op);
1317         else
1318           Changed = true;
1319         break;
1320       }
1321     }
1322   }
1323
1324   SDValue Result;
1325
1326   // If we've change things around then replace token factor.
1327   if (Changed) {
1328     if (Ops.empty()) {
1329       // The entry token is the only possible outcome.
1330       Result = DAG.getEntryNode();
1331     } else {
1332       // New and improved token factor.
1333       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
1334                            MVT::Other, &Ops[0], Ops.size());
1335     }
1336
1337     // Don't add users to work list.
1338     return CombineTo(N, Result, false);
1339   }
1340
1341   return Result;
1342 }
1343
1344 /// MERGE_VALUES can always be eliminated.
1345 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1346   WorkListRemover DeadNodes(*this);
1347   // Replacing results may cause a different MERGE_VALUES to suddenly
1348   // be CSE'd with N, and carry its uses with it. Iterate until no
1349   // uses remain, to ensure that the node can be safely deleted.
1350   // First add the users of this node to the work list so that they
1351   // can be tried again once they have new operands.
1352   AddUsersToWorkList(N);
1353   do {
1354     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1355       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1356   } while (!N->use_empty());
1357   removeFromWorkList(N);
1358   DAG.DeleteNode(N);
1359   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1360 }
1361
1362 static
1363 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1364                               SelectionDAG &DAG) {
1365   EVT VT = N0.getValueType();
1366   SDValue N00 = N0.getOperand(0);
1367   SDValue N01 = N0.getOperand(1);
1368   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1369
1370   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1371       isa<ConstantSDNode>(N00.getOperand(1))) {
1372     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1373     N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1374                      DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1375                                  N00.getOperand(0), N01),
1376                      DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1377                                  N00.getOperand(1), N01));
1378     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1379   }
1380
1381   return SDValue();
1382 }
1383
1384 SDValue DAGCombiner::visitADD(SDNode *N) {
1385   SDValue N0 = N->getOperand(0);
1386   SDValue N1 = N->getOperand(1);
1387   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1388   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1389   EVT VT = N0.getValueType();
1390
1391   // fold vector ops
1392   if (VT.isVector()) {
1393     SDValue FoldedVOp = SimplifyVBinOp(N);
1394     if (FoldedVOp.getNode()) return FoldedVOp;
1395
1396     // fold (add x, 0) -> x, vector edition
1397     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1398       return N0;
1399     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1400       return N1;
1401   }
1402
1403   // fold (add x, undef) -> undef
1404   if (N0.getOpcode() == ISD::UNDEF)
1405     return N0;
1406   if (N1.getOpcode() == ISD::UNDEF)
1407     return N1;
1408   // fold (add c1, c2) -> c1+c2
1409   if (N0C && N1C)
1410     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1411   // canonicalize constant to RHS
1412   if (N0C && !N1C)
1413     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1414   // fold (add x, 0) -> x
1415   if (N1C && N1C->isNullValue())
1416     return N0;
1417   // fold (add Sym, c) -> Sym+c
1418   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1419     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1420         GA->getOpcode() == ISD::GlobalAddress)
1421       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1422                                   GA->getOffset() +
1423                                     (uint64_t)N1C->getSExtValue());
1424   // fold ((c1-A)+c2) -> (c1+c2)-A
1425   if (N1C && N0.getOpcode() == ISD::SUB)
1426     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1427       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1428                          DAG.getConstant(N1C->getAPIntValue()+
1429                                          N0C->getAPIntValue(), VT),
1430                          N0.getOperand(1));
1431   // reassociate add
1432   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1433   if (RADD.getNode() != 0)
1434     return RADD;
1435   // fold ((0-A) + B) -> B-A
1436   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1437       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1438     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1439   // fold (A + (0-B)) -> A-B
1440   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1441       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1442     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1443   // fold (A+(B-A)) -> B
1444   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1445     return N1.getOperand(0);
1446   // fold ((B-A)+A) -> B
1447   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1448     return N0.getOperand(0);
1449   // fold (A+(B-(A+C))) to (B-C)
1450   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1451       N0 == N1.getOperand(1).getOperand(0))
1452     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1453                        N1.getOperand(1).getOperand(1));
1454   // fold (A+(B-(C+A))) to (B-C)
1455   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1456       N0 == N1.getOperand(1).getOperand(1))
1457     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1458                        N1.getOperand(1).getOperand(0));
1459   // fold (A+((B-A)+or-C)) to (B+or-C)
1460   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1461       N1.getOperand(0).getOpcode() == ISD::SUB &&
1462       N0 == N1.getOperand(0).getOperand(1))
1463     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1464                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1465
1466   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1467   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1468     SDValue N00 = N0.getOperand(0);
1469     SDValue N01 = N0.getOperand(1);
1470     SDValue N10 = N1.getOperand(0);
1471     SDValue N11 = N1.getOperand(1);
1472
1473     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1474       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1475                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1476                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1477   }
1478
1479   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1480     return SDValue(N, 0);
1481
1482   // fold (a+b) -> (a|b) iff a and b share no bits.
1483   if (VT.isInteger() && !VT.isVector()) {
1484     APInt LHSZero, LHSOne;
1485     APInt RHSZero, RHSOne;
1486     DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1487
1488     if (LHSZero.getBoolValue()) {
1489       DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1490
1491       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1492       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1493       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1494         return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1495     }
1496   }
1497
1498   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1499   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1500     SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1501     if (Result.getNode()) return Result;
1502   }
1503   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1504     SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1505     if (Result.getNode()) return Result;
1506   }
1507
1508   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1509   if (N1.getOpcode() == ISD::SHL &&
1510       N1.getOperand(0).getOpcode() == ISD::SUB)
1511     if (ConstantSDNode *C =
1512           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1513       if (C->getAPIntValue() == 0)
1514         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1515                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1516                                        N1.getOperand(0).getOperand(1),
1517                                        N1.getOperand(1)));
1518   if (N0.getOpcode() == ISD::SHL &&
1519       N0.getOperand(0).getOpcode() == ISD::SUB)
1520     if (ConstantSDNode *C =
1521           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1522       if (C->getAPIntValue() == 0)
1523         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1524                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1525                                        N0.getOperand(0).getOperand(1),
1526                                        N0.getOperand(1)));
1527
1528   if (N1.getOpcode() == ISD::AND) {
1529     SDValue AndOp0 = N1.getOperand(0);
1530     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1531     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1532     unsigned DestBits = VT.getScalarType().getSizeInBits();
1533
1534     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1535     // and similar xforms where the inner op is either ~0 or 0.
1536     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1537       SDLoc DL(N);
1538       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1539     }
1540   }
1541
1542   // add (sext i1), X -> sub X, (zext i1)
1543   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1544       N0.getOperand(0).getValueType() == MVT::i1 &&
1545       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1546     SDLoc DL(N);
1547     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1548     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1549   }
1550
1551   return SDValue();
1552 }
1553
1554 SDValue DAGCombiner::visitADDC(SDNode *N) {
1555   SDValue N0 = N->getOperand(0);
1556   SDValue N1 = N->getOperand(1);
1557   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1558   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1559   EVT VT = N0.getValueType();
1560
1561   // If the flag result is dead, turn this into an ADD.
1562   if (!N->hasAnyUseOfValue(1))
1563     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1564                      DAG.getNode(ISD::CARRY_FALSE,
1565                                  SDLoc(N), MVT::Glue));
1566
1567   // canonicalize constant to RHS.
1568   if (N0C && !N1C)
1569     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1570
1571   // fold (addc x, 0) -> x + no carry out
1572   if (N1C && N1C->isNullValue())
1573     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1574                                         SDLoc(N), MVT::Glue));
1575
1576   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1577   APInt LHSZero, LHSOne;
1578   APInt RHSZero, RHSOne;
1579   DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1580
1581   if (LHSZero.getBoolValue()) {
1582     DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1583
1584     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1585     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1586     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1587       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1588                        DAG.getNode(ISD::CARRY_FALSE,
1589                                    SDLoc(N), MVT::Glue));
1590   }
1591
1592   return SDValue();
1593 }
1594
1595 SDValue DAGCombiner::visitADDE(SDNode *N) {
1596   SDValue N0 = N->getOperand(0);
1597   SDValue N1 = N->getOperand(1);
1598   SDValue CarryIn = N->getOperand(2);
1599   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1600   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1601
1602   // canonicalize constant to RHS
1603   if (N0C && !N1C)
1604     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1605                        N1, N0, CarryIn);
1606
1607   // fold (adde x, y, false) -> (addc x, y)
1608   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1609     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1610
1611   return SDValue();
1612 }
1613
1614 // Since it may not be valid to emit a fold to zero for vector initializers
1615 // check if we can before folding.
1616 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1617                              SelectionDAG &DAG,
1618                              bool LegalOperations, bool LegalTypes) {
1619   if (!VT.isVector())
1620     return DAG.getConstant(0, VT);
1621   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
1622     // Produce a vector of zeros.
1623     EVT ElemTy = VT.getVectorElementType();
1624     if (LegalTypes && TLI.getTypeAction(*DAG.getContext(), ElemTy) ==
1625                       TargetLowering::TypePromoteInteger)
1626       ElemTy = TLI.getTypeToTransformTo(*DAG.getContext(), ElemTy);
1627     assert((!LegalTypes || TLI.isTypeLegal(ElemTy)) &&
1628            "Type for zero vector elements is not legal");
1629     SDValue El = DAG.getConstant(0, ElemTy);
1630     std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
1631     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
1632       &Ops[0], Ops.size());
1633   }
1634   return SDValue();
1635 }
1636
1637 SDValue DAGCombiner::visitSUB(SDNode *N) {
1638   SDValue N0 = N->getOperand(0);
1639   SDValue N1 = N->getOperand(1);
1640   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1641   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1642   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1643     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1644   EVT VT = N0.getValueType();
1645
1646   // fold vector ops
1647   if (VT.isVector()) {
1648     SDValue FoldedVOp = SimplifyVBinOp(N);
1649     if (FoldedVOp.getNode()) return FoldedVOp;
1650
1651     // fold (sub x, 0) -> x, vector edition
1652     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1653       return N0;
1654   }
1655
1656   // fold (sub x, x) -> 0
1657   // FIXME: Refactor this and xor and other similar operations together.
1658   if (N0 == N1)
1659     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1660   // fold (sub c1, c2) -> c1-c2
1661   if (N0C && N1C)
1662     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1663   // fold (sub x, c) -> (add x, -c)
1664   if (N1C)
1665     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1666                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1667   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1668   if (N0C && N0C->isAllOnesValue())
1669     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1670   // fold A-(A-B) -> B
1671   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1672     return N1.getOperand(1);
1673   // fold (A+B)-A -> B
1674   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1675     return N0.getOperand(1);
1676   // fold (A+B)-B -> A
1677   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1678     return N0.getOperand(0);
1679   // fold C2-(A+C1) -> (C2-C1)-A
1680   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1681     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1682                                    VT);
1683     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1684                        N1.getOperand(0));
1685   }
1686   // fold ((A+(B+or-C))-B) -> A+or-C
1687   if (N0.getOpcode() == ISD::ADD &&
1688       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1689        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1690       N0.getOperand(1).getOperand(0) == N1)
1691     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1692                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1693   // fold ((A+(C+B))-B) -> A+C
1694   if (N0.getOpcode() == ISD::ADD &&
1695       N0.getOperand(1).getOpcode() == ISD::ADD &&
1696       N0.getOperand(1).getOperand(1) == N1)
1697     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1698                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1699   // fold ((A-(B-C))-C) -> A-B
1700   if (N0.getOpcode() == ISD::SUB &&
1701       N0.getOperand(1).getOpcode() == ISD::SUB &&
1702       N0.getOperand(1).getOperand(1) == N1)
1703     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1704                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1705
1706   // If either operand of a sub is undef, the result is undef
1707   if (N0.getOpcode() == ISD::UNDEF)
1708     return N0;
1709   if (N1.getOpcode() == ISD::UNDEF)
1710     return N1;
1711
1712   // If the relocation model supports it, consider symbol offsets.
1713   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1714     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1715       // fold (sub Sym, c) -> Sym-c
1716       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1717         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1718                                     GA->getOffset() -
1719                                       (uint64_t)N1C->getSExtValue());
1720       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1721       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1722         if (GA->getGlobal() == GB->getGlobal())
1723           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1724                                  VT);
1725     }
1726
1727   return SDValue();
1728 }
1729
1730 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1731   SDValue N0 = N->getOperand(0);
1732   SDValue N1 = N->getOperand(1);
1733   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1734   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1735   EVT VT = N0.getValueType();
1736
1737   // If the flag result is dead, turn this into an SUB.
1738   if (!N->hasAnyUseOfValue(1))
1739     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1740                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1741                                  MVT::Glue));
1742
1743   // fold (subc x, x) -> 0 + no borrow
1744   if (N0 == N1)
1745     return CombineTo(N, DAG.getConstant(0, VT),
1746                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1747                                  MVT::Glue));
1748
1749   // fold (subc x, 0) -> x + no borrow
1750   if (N1C && N1C->isNullValue())
1751     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1752                                         MVT::Glue));
1753
1754   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1755   if (N0C && N0C->isAllOnesValue())
1756     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1757                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1758                                  MVT::Glue));
1759
1760   return SDValue();
1761 }
1762
1763 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1764   SDValue N0 = N->getOperand(0);
1765   SDValue N1 = N->getOperand(1);
1766   SDValue CarryIn = N->getOperand(2);
1767
1768   // fold (sube x, y, false) -> (subc x, y)
1769   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1770     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1771
1772   return SDValue();
1773 }
1774
1775 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
1776 /// all the same constant or undefined.
1777 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
1778   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
1779   if (!C)
1780     return false;
1781
1782   APInt SplatUndef;
1783   unsigned SplatBitSize;
1784   bool HasAnyUndefs;
1785   EVT EltVT = N->getValueType(0).getVectorElementType();
1786   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
1787                              HasAnyUndefs) &&
1788           EltVT.getSizeInBits() >= SplatBitSize);
1789 }
1790
1791 SDValue DAGCombiner::visitMUL(SDNode *N) {
1792   SDValue N0 = N->getOperand(0);
1793   SDValue N1 = N->getOperand(1);
1794   EVT VT = N0.getValueType();
1795
1796   // fold (mul x, undef) -> 0
1797   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1798     return DAG.getConstant(0, VT);
1799
1800   bool N0IsConst = false;
1801   bool N1IsConst = false;
1802   APInt ConstValue0, ConstValue1;
1803   // fold vector ops
1804   if (VT.isVector()) {
1805     SDValue FoldedVOp = SimplifyVBinOp(N);
1806     if (FoldedVOp.getNode()) return FoldedVOp;
1807
1808     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1809     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1810   } else {
1811     N0IsConst = dyn_cast<ConstantSDNode>(N0) != 0;
1812     ConstValue0 = N0IsConst? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue() : APInt();
1813     N1IsConst = dyn_cast<ConstantSDNode>(N1) != 0;
1814     ConstValue1 = N1IsConst? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue() : APInt();
1815   }
1816
1817   // fold (mul c1, c2) -> c1*c2
1818   if (N0IsConst && N1IsConst)
1819     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1820
1821   // canonicalize constant to RHS
1822   if (N0IsConst && !N1IsConst)
1823     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1824   // fold (mul x, 0) -> 0
1825   if (N1IsConst && ConstValue1 == 0)
1826     return N1;
1827   // We require a splat of the entire scalar bit width for non-contiguous
1828   // bit patterns.
1829   bool IsFullSplat =
1830     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1831   // fold (mul x, 1) -> x
1832   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1833     return N0;
1834   // fold (mul x, -1) -> 0-x
1835   if (N1IsConst && ConstValue1.isAllOnesValue())
1836     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1837                        DAG.getConstant(0, VT), N0);
1838   // fold (mul x, (1 << c)) -> x << c
1839   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1840     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1841                        DAG.getConstant(ConstValue1.logBase2(),
1842                                        getShiftAmountTy(N0.getValueType())));
1843   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1844   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1845     unsigned Log2Val = (-ConstValue1).logBase2();
1846     // FIXME: If the input is something that is easily negated (e.g. a
1847     // single-use add), we should put the negate there.
1848     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1849                        DAG.getConstant(0, VT),
1850                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1851                             DAG.getConstant(Log2Val,
1852                                       getShiftAmountTy(N0.getValueType()))));
1853   }
1854
1855   APInt Val;
1856   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1857   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1858       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1859                      isa<ConstantSDNode>(N0.getOperand(1)))) {
1860     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1861                              N1, N0.getOperand(1));
1862     AddToWorkList(C3.getNode());
1863     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1864                        N0.getOperand(0), C3);
1865   }
1866
1867   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1868   // use.
1869   {
1870     SDValue Sh(0,0), Y(0,0);
1871     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1872     if (N0.getOpcode() == ISD::SHL &&
1873         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1874                        isa<ConstantSDNode>(N0.getOperand(1))) &&
1875         N0.getNode()->hasOneUse()) {
1876       Sh = N0; Y = N1;
1877     } else if (N1.getOpcode() == ISD::SHL &&
1878                isa<ConstantSDNode>(N1.getOperand(1)) &&
1879                N1.getNode()->hasOneUse()) {
1880       Sh = N1; Y = N0;
1881     }
1882
1883     if (Sh.getNode()) {
1884       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1885                                 Sh.getOperand(0), Y);
1886       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1887                          Mul, Sh.getOperand(1));
1888     }
1889   }
1890
1891   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1892   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1893       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1894                      isa<ConstantSDNode>(N0.getOperand(1))))
1895     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1896                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1897                                    N0.getOperand(0), N1),
1898                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1899                                    N0.getOperand(1), N1));
1900
1901   // reassociate mul
1902   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1903   if (RMUL.getNode() != 0)
1904     return RMUL;
1905
1906   return SDValue();
1907 }
1908
1909 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1910   SDValue N0 = N->getOperand(0);
1911   SDValue N1 = N->getOperand(1);
1912   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1913   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1914   EVT VT = N->getValueType(0);
1915
1916   // fold vector ops
1917   if (VT.isVector()) {
1918     SDValue FoldedVOp = SimplifyVBinOp(N);
1919     if (FoldedVOp.getNode()) return FoldedVOp;
1920   }
1921
1922   // fold (sdiv c1, c2) -> c1/c2
1923   if (N0C && N1C && !N1C->isNullValue())
1924     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1925   // fold (sdiv X, 1) -> X
1926   if (N1C && N1C->getAPIntValue() == 1LL)
1927     return N0;
1928   // fold (sdiv X, -1) -> 0-X
1929   if (N1C && N1C->isAllOnesValue())
1930     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1931                        DAG.getConstant(0, VT), N0);
1932   // If we know the sign bits of both operands are zero, strength reduce to a
1933   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
1934   if (!VT.isVector()) {
1935     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1936       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
1937                          N0, N1);
1938   }
1939   // fold (sdiv X, pow2) -> simple ops after legalize
1940   if (N1C && !N1C->isNullValue() &&
1941       (N1C->getAPIntValue().isPowerOf2() ||
1942        (-N1C->getAPIntValue()).isPowerOf2())) {
1943     // If dividing by powers of two is cheap, then don't perform the following
1944     // fold.
1945     if (TLI.isPow2DivCheap())
1946       return SDValue();
1947
1948     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
1949
1950     // Splat the sign bit into the register
1951     SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
1952                               DAG.getConstant(VT.getSizeInBits()-1,
1953                                        getShiftAmountTy(N0.getValueType())));
1954     AddToWorkList(SGN.getNode());
1955
1956     // Add (N0 < 0) ? abs2 - 1 : 0;
1957     SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
1958                               DAG.getConstant(VT.getSizeInBits() - lg2,
1959                                        getShiftAmountTy(SGN.getValueType())));
1960     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
1961     AddToWorkList(SRL.getNode());
1962     AddToWorkList(ADD.getNode());    // Divide by pow2
1963     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
1964                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
1965
1966     // If we're dividing by a positive value, we're done.  Otherwise, we must
1967     // negate the result.
1968     if (N1C->getAPIntValue().isNonNegative())
1969       return SRA;
1970
1971     AddToWorkList(SRA.getNode());
1972     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1973                        DAG.getConstant(0, VT), SRA);
1974   }
1975
1976   // if integer divide is expensive and we satisfy the requirements, emit an
1977   // alternate sequence.
1978   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1979     SDValue Op = BuildSDIV(N);
1980     if (Op.getNode()) return Op;
1981   }
1982
1983   // undef / X -> 0
1984   if (N0.getOpcode() == ISD::UNDEF)
1985     return DAG.getConstant(0, VT);
1986   // X / undef -> undef
1987   if (N1.getOpcode() == ISD::UNDEF)
1988     return N1;
1989
1990   return SDValue();
1991 }
1992
1993 SDValue DAGCombiner::visitUDIV(SDNode *N) {
1994   SDValue N0 = N->getOperand(0);
1995   SDValue N1 = N->getOperand(1);
1996   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1997   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1998   EVT VT = N->getValueType(0);
1999
2000   // fold vector ops
2001   if (VT.isVector()) {
2002     SDValue FoldedVOp = SimplifyVBinOp(N);
2003     if (FoldedVOp.getNode()) return FoldedVOp;
2004   }
2005
2006   // fold (udiv c1, c2) -> c1/c2
2007   if (N0C && N1C && !N1C->isNullValue())
2008     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2009   // fold (udiv x, (1 << c)) -> x >>u c
2010   if (N1C && N1C->getAPIntValue().isPowerOf2())
2011     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2012                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2013                                        getShiftAmountTy(N0.getValueType())));
2014   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2015   if (N1.getOpcode() == ISD::SHL) {
2016     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2017       if (SHC->getAPIntValue().isPowerOf2()) {
2018         EVT ADDVT = N1.getOperand(1).getValueType();
2019         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2020                                   N1.getOperand(1),
2021                                   DAG.getConstant(SHC->getAPIntValue()
2022                                                                   .logBase2(),
2023                                                   ADDVT));
2024         AddToWorkList(Add.getNode());
2025         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2026       }
2027     }
2028   }
2029   // fold (udiv x, c) -> alternate
2030   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2031     SDValue Op = BuildUDIV(N);
2032     if (Op.getNode()) return Op;
2033   }
2034
2035   // undef / X -> 0
2036   if (N0.getOpcode() == ISD::UNDEF)
2037     return DAG.getConstant(0, VT);
2038   // X / undef -> undef
2039   if (N1.getOpcode() == ISD::UNDEF)
2040     return N1;
2041
2042   return SDValue();
2043 }
2044
2045 SDValue DAGCombiner::visitSREM(SDNode *N) {
2046   SDValue N0 = N->getOperand(0);
2047   SDValue N1 = N->getOperand(1);
2048   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2049   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2050   EVT VT = N->getValueType(0);
2051
2052   // fold (srem c1, c2) -> c1%c2
2053   if (N0C && N1C && !N1C->isNullValue())
2054     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2055   // If we know the sign bits of both operands are zero, strength reduce to a
2056   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2057   if (!VT.isVector()) {
2058     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2059       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2060   }
2061
2062   // If X/C can be simplified by the division-by-constant logic, lower
2063   // X%C to the equivalent of X-X/C*C.
2064   if (N1C && !N1C->isNullValue()) {
2065     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2066     AddToWorkList(Div.getNode());
2067     SDValue OptimizedDiv = combine(Div.getNode());
2068     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2069       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2070                                 OptimizedDiv, N1);
2071       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2072       AddToWorkList(Mul.getNode());
2073       return Sub;
2074     }
2075   }
2076
2077   // undef % X -> 0
2078   if (N0.getOpcode() == ISD::UNDEF)
2079     return DAG.getConstant(0, VT);
2080   // X % undef -> undef
2081   if (N1.getOpcode() == ISD::UNDEF)
2082     return N1;
2083
2084   return SDValue();
2085 }
2086
2087 SDValue DAGCombiner::visitUREM(SDNode *N) {
2088   SDValue N0 = N->getOperand(0);
2089   SDValue N1 = N->getOperand(1);
2090   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2091   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2092   EVT VT = N->getValueType(0);
2093
2094   // fold (urem c1, c2) -> c1%c2
2095   if (N0C && N1C && !N1C->isNullValue())
2096     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2097   // fold (urem x, pow2) -> (and x, pow2-1)
2098   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2099     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2100                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2101   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2102   if (N1.getOpcode() == ISD::SHL) {
2103     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2104       if (SHC->getAPIntValue().isPowerOf2()) {
2105         SDValue Add =
2106           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2107                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2108                                  VT));
2109         AddToWorkList(Add.getNode());
2110         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2111       }
2112     }
2113   }
2114
2115   // If X/C can be simplified by the division-by-constant logic, lower
2116   // X%C to the equivalent of X-X/C*C.
2117   if (N1C && !N1C->isNullValue()) {
2118     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2119     AddToWorkList(Div.getNode());
2120     SDValue OptimizedDiv = combine(Div.getNode());
2121     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2122       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2123                                 OptimizedDiv, N1);
2124       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2125       AddToWorkList(Mul.getNode());
2126       return Sub;
2127     }
2128   }
2129
2130   // undef % X -> 0
2131   if (N0.getOpcode() == ISD::UNDEF)
2132     return DAG.getConstant(0, VT);
2133   // X % undef -> undef
2134   if (N1.getOpcode() == ISD::UNDEF)
2135     return N1;
2136
2137   return SDValue();
2138 }
2139
2140 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2141   SDValue N0 = N->getOperand(0);
2142   SDValue N1 = N->getOperand(1);
2143   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2144   EVT VT = N->getValueType(0);
2145   SDLoc DL(N);
2146
2147   // fold (mulhs x, 0) -> 0
2148   if (N1C && N1C->isNullValue())
2149     return N1;
2150   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2151   if (N1C && N1C->getAPIntValue() == 1)
2152     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2153                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2154                                        getShiftAmountTy(N0.getValueType())));
2155   // fold (mulhs x, undef) -> 0
2156   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2157     return DAG.getConstant(0, VT);
2158
2159   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2160   // plus a shift.
2161   if (VT.isSimple() && !VT.isVector()) {
2162     MVT Simple = VT.getSimpleVT();
2163     unsigned SimpleSize = Simple.getSizeInBits();
2164     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2165     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2166       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2167       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2168       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2169       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2170             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2171       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2172     }
2173   }
2174
2175   return SDValue();
2176 }
2177
2178 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2179   SDValue N0 = N->getOperand(0);
2180   SDValue N1 = N->getOperand(1);
2181   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2182   EVT VT = N->getValueType(0);
2183   SDLoc DL(N);
2184
2185   // fold (mulhu x, 0) -> 0
2186   if (N1C && N1C->isNullValue())
2187     return N1;
2188   // fold (mulhu x, 1) -> 0
2189   if (N1C && N1C->getAPIntValue() == 1)
2190     return DAG.getConstant(0, N0.getValueType());
2191   // fold (mulhu x, undef) -> 0
2192   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2193     return DAG.getConstant(0, VT);
2194
2195   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2196   // plus a shift.
2197   if (VT.isSimple() && !VT.isVector()) {
2198     MVT Simple = VT.getSimpleVT();
2199     unsigned SimpleSize = Simple.getSizeInBits();
2200     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2201     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2202       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2203       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2204       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2205       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2206             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2207       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2208     }
2209   }
2210
2211   return SDValue();
2212 }
2213
2214 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2215 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2216 /// that are being performed. Return true if a simplification was made.
2217 ///
2218 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2219                                                 unsigned HiOp) {
2220   // If the high half is not needed, just compute the low half.
2221   bool HiExists = N->hasAnyUseOfValue(1);
2222   if (!HiExists &&
2223       (!LegalOperations ||
2224        TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
2225     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2226                               N->op_begin(), N->getNumOperands());
2227     return CombineTo(N, Res, Res);
2228   }
2229
2230   // If the low half is not needed, just compute the high half.
2231   bool LoExists = N->hasAnyUseOfValue(0);
2232   if (!LoExists &&
2233       (!LegalOperations ||
2234        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2235     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2236                               N->op_begin(), N->getNumOperands());
2237     return CombineTo(N, Res, Res);
2238   }
2239
2240   // If both halves are used, return as it is.
2241   if (LoExists && HiExists)
2242     return SDValue();
2243
2244   // If the two computed results can be simplified separately, separate them.
2245   if (LoExists) {
2246     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2247                              N->op_begin(), N->getNumOperands());
2248     AddToWorkList(Lo.getNode());
2249     SDValue LoOpt = combine(Lo.getNode());
2250     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2251         (!LegalOperations ||
2252          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2253       return CombineTo(N, LoOpt, LoOpt);
2254   }
2255
2256   if (HiExists) {
2257     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2258                              N->op_begin(), N->getNumOperands());
2259     AddToWorkList(Hi.getNode());
2260     SDValue HiOpt = combine(Hi.getNode());
2261     if (HiOpt.getNode() && HiOpt != Hi &&
2262         (!LegalOperations ||
2263          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2264       return CombineTo(N, HiOpt, HiOpt);
2265   }
2266
2267   return SDValue();
2268 }
2269
2270 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2271   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2272   if (Res.getNode()) return Res;
2273
2274   EVT VT = N->getValueType(0);
2275   SDLoc DL(N);
2276
2277   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2278   // plus a shift.
2279   if (VT.isSimple() && !VT.isVector()) {
2280     MVT Simple = VT.getSimpleVT();
2281     unsigned SimpleSize = Simple.getSizeInBits();
2282     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2283     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2284       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2285       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2286       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2287       // Compute the high part as N1.
2288       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2289             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2290       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2291       // Compute the low part as N0.
2292       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2293       return CombineTo(N, Lo, Hi);
2294     }
2295   }
2296
2297   return SDValue();
2298 }
2299
2300 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2301   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2302   if (Res.getNode()) return Res;
2303
2304   EVT VT = N->getValueType(0);
2305   SDLoc DL(N);
2306
2307   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2308   // plus a shift.
2309   if (VT.isSimple() && !VT.isVector()) {
2310     MVT Simple = VT.getSimpleVT();
2311     unsigned SimpleSize = Simple.getSizeInBits();
2312     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2313     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2314       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2315       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2316       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2317       // Compute the high part as N1.
2318       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2319             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2320       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2321       // Compute the low part as N0.
2322       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2323       return CombineTo(N, Lo, Hi);
2324     }
2325   }
2326
2327   return SDValue();
2328 }
2329
2330 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2331   // (smulo x, 2) -> (saddo x, x)
2332   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2333     if (C2->getAPIntValue() == 2)
2334       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2335                          N->getOperand(0), N->getOperand(0));
2336
2337   return SDValue();
2338 }
2339
2340 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2341   // (umulo x, 2) -> (uaddo x, x)
2342   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2343     if (C2->getAPIntValue() == 2)
2344       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2345                          N->getOperand(0), N->getOperand(0));
2346
2347   return SDValue();
2348 }
2349
2350 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2351   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2352   if (Res.getNode()) return Res;
2353
2354   return SDValue();
2355 }
2356
2357 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2358   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2359   if (Res.getNode()) return Res;
2360
2361   return SDValue();
2362 }
2363
2364 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2365 /// two operands of the same opcode, try to simplify it.
2366 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2367   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2368   EVT VT = N0.getValueType();
2369   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2370
2371   // Bail early if none of these transforms apply.
2372   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2373
2374   // For each of OP in AND/OR/XOR:
2375   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2376   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2377   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2378   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2379   //
2380   // do not sink logical op inside of a vector extend, since it may combine
2381   // into a vsetcc.
2382   EVT Op0VT = N0.getOperand(0).getValueType();
2383   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2384        N0.getOpcode() == ISD::SIGN_EXTEND ||
2385        // Avoid infinite looping with PromoteIntBinOp.
2386        (N0.getOpcode() == ISD::ANY_EXTEND &&
2387         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2388        (N0.getOpcode() == ISD::TRUNCATE &&
2389         (!TLI.isZExtFree(VT, Op0VT) ||
2390          !TLI.isTruncateFree(Op0VT, VT)) &&
2391         TLI.isTypeLegal(Op0VT))) &&
2392       !VT.isVector() &&
2393       Op0VT == N1.getOperand(0).getValueType() &&
2394       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2395     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2396                                  N0.getOperand(0).getValueType(),
2397                                  N0.getOperand(0), N1.getOperand(0));
2398     AddToWorkList(ORNode.getNode());
2399     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2400   }
2401
2402   // For each of OP in SHL/SRL/SRA/AND...
2403   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2404   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2405   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2406   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2407        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2408       N0.getOperand(1) == N1.getOperand(1)) {
2409     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2410                                  N0.getOperand(0).getValueType(),
2411                                  N0.getOperand(0), N1.getOperand(0));
2412     AddToWorkList(ORNode.getNode());
2413     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2414                        ORNode, N0.getOperand(1));
2415   }
2416
2417   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2418   // Only perform this optimization after type legalization and before
2419   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2420   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2421   // we don't want to undo this promotion.
2422   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2423   // on scalars.
2424   if ((N0.getOpcode() == ISD::BITCAST ||
2425        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2426       Level == AfterLegalizeTypes) {
2427     SDValue In0 = N0.getOperand(0);
2428     SDValue In1 = N1.getOperand(0);
2429     EVT In0Ty = In0.getValueType();
2430     EVT In1Ty = In1.getValueType();
2431     SDLoc DL(N);
2432     // If both incoming values are integers, and the original types are the
2433     // same.
2434     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2435       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2436       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2437       AddToWorkList(Op.getNode());
2438       return BC;
2439     }
2440   }
2441
2442   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2443   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2444   // If both shuffles use the same mask, and both shuffle within a single
2445   // vector, then it is worthwhile to move the swizzle after the operation.
2446   // The type-legalizer generates this pattern when loading illegal
2447   // vector types from memory. In many cases this allows additional shuffle
2448   // optimizations.
2449   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
2450       N0.getOperand(1).getOpcode() == ISD::UNDEF &&
2451       N1.getOperand(1).getOpcode() == ISD::UNDEF) {
2452     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2453     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2454
2455     assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
2456            "Inputs to shuffles are not the same type");
2457
2458     unsigned NumElts = VT.getVectorNumElements();
2459
2460     // Check that both shuffles use the same mask. The masks are known to be of
2461     // the same length because the result vector type is the same.
2462     bool SameMask = true;
2463     for (unsigned i = 0; i != NumElts; ++i) {
2464       int Idx0 = SVN0->getMaskElt(i);
2465       int Idx1 = SVN1->getMaskElt(i);
2466       if (Idx0 != Idx1) {
2467         SameMask = false;
2468         break;
2469       }
2470     }
2471
2472     if (SameMask) {
2473       SDValue Op = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2474                                N0.getOperand(0), N1.getOperand(0));
2475       AddToWorkList(Op.getNode());
2476       return DAG.getVectorShuffle(VT, SDLoc(N), Op,
2477                                   DAG.getUNDEF(VT), &SVN0->getMask()[0]);
2478     }
2479   }
2480
2481   return SDValue();
2482 }
2483
2484 SDValue DAGCombiner::visitAND(SDNode *N) {
2485   SDValue N0 = N->getOperand(0);
2486   SDValue N1 = N->getOperand(1);
2487   SDValue LL, LR, RL, RR, CC0, CC1;
2488   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2489   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2490   EVT VT = N1.getValueType();
2491   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2492
2493   // fold vector ops
2494   if (VT.isVector()) {
2495     SDValue FoldedVOp = SimplifyVBinOp(N);
2496     if (FoldedVOp.getNode()) return FoldedVOp;
2497
2498     // fold (and x, 0) -> 0, vector edition
2499     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2500       return N0;
2501     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2502       return N1;
2503
2504     // fold (and x, -1) -> x, vector edition
2505     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2506       return N1;
2507     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2508       return N0;
2509   }
2510
2511   // fold (and x, undef) -> 0
2512   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2513     return DAG.getConstant(0, VT);
2514   // fold (and c1, c2) -> c1&c2
2515   if (N0C && N1C)
2516     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2517   // canonicalize constant to RHS
2518   if (N0C && !N1C)
2519     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2520   // fold (and x, -1) -> x
2521   if (N1C && N1C->isAllOnesValue())
2522     return N0;
2523   // if (and x, c) is known to be zero, return 0
2524   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2525                                    APInt::getAllOnesValue(BitWidth)))
2526     return DAG.getConstant(0, VT);
2527   // reassociate and
2528   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2529   if (RAND.getNode() != 0)
2530     return RAND;
2531   // fold (and (or x, C), D) -> D if (C & D) == D
2532   if (N1C && N0.getOpcode() == ISD::OR)
2533     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2534       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2535         return N1;
2536   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2537   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2538     SDValue N0Op0 = N0.getOperand(0);
2539     APInt Mask = ~N1C->getAPIntValue();
2540     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2541     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2542       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2543                                  N0.getValueType(), N0Op0);
2544
2545       // Replace uses of the AND with uses of the Zero extend node.
2546       CombineTo(N, Zext);
2547
2548       // We actually want to replace all uses of the any_extend with the
2549       // zero_extend, to avoid duplicating things.  This will later cause this
2550       // AND to be folded.
2551       CombineTo(N0.getNode(), Zext);
2552       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2553     }
2554   }
2555   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2556   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2557   // already be zero by virtue of the width of the base type of the load.
2558   //
2559   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2560   // more cases.
2561   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2562        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2563       N0.getOpcode() == ISD::LOAD) {
2564     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2565                                          N0 : N0.getOperand(0) );
2566
2567     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2568     // This can be a pure constant or a vector splat, in which case we treat the
2569     // vector as a scalar and use the splat value.
2570     APInt Constant = APInt::getNullValue(1);
2571     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2572       Constant = C->getAPIntValue();
2573     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2574       APInt SplatValue, SplatUndef;
2575       unsigned SplatBitSize;
2576       bool HasAnyUndefs;
2577       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2578                                              SplatBitSize, HasAnyUndefs);
2579       if (IsSplat) {
2580         // Undef bits can contribute to a possible optimisation if set, so
2581         // set them.
2582         SplatValue |= SplatUndef;
2583
2584         // The splat value may be something like "0x00FFFFFF", which means 0 for
2585         // the first vector value and FF for the rest, repeating. We need a mask
2586         // that will apply equally to all members of the vector, so AND all the
2587         // lanes of the constant together.
2588         EVT VT = Vector->getValueType(0);
2589         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2590
2591         // If the splat value has been compressed to a bitlength lower
2592         // than the size of the vector lane, we need to re-expand it to
2593         // the lane size.
2594         if (BitWidth > SplatBitSize)
2595           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2596                SplatBitSize < BitWidth;
2597                SplatBitSize = SplatBitSize * 2)
2598             SplatValue |= SplatValue.shl(SplatBitSize);
2599
2600         Constant = APInt::getAllOnesValue(BitWidth);
2601         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2602           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2603       }
2604     }
2605
2606     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2607     // actually legal and isn't going to get expanded, else this is a false
2608     // optimisation.
2609     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2610                                                     Load->getMemoryVT());
2611
2612     // Resize the constant to the same size as the original memory access before
2613     // extension. If it is still the AllOnesValue then this AND is completely
2614     // unneeded.
2615     Constant =
2616       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2617
2618     bool B;
2619     switch (Load->getExtensionType()) {
2620     default: B = false; break;
2621     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2622     case ISD::ZEXTLOAD:
2623     case ISD::NON_EXTLOAD: B = true; break;
2624     }
2625
2626     if (B && Constant.isAllOnesValue()) {
2627       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2628       // preserve semantics once we get rid of the AND.
2629       SDValue NewLoad(Load, 0);
2630       if (Load->getExtensionType() == ISD::EXTLOAD) {
2631         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2632                               Load->getValueType(0), SDLoc(Load),
2633                               Load->getChain(), Load->getBasePtr(),
2634                               Load->getOffset(), Load->getMemoryVT(),
2635                               Load->getMemOperand());
2636         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2637         if (Load->getNumValues() == 3) {
2638           // PRE/POST_INC loads have 3 values.
2639           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2640                            NewLoad.getValue(2) };
2641           CombineTo(Load, To, 3, true);
2642         } else {
2643           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2644         }
2645       }
2646
2647       // Fold the AND away, taking care not to fold to the old load node if we
2648       // replaced it.
2649       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2650
2651       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2652     }
2653   }
2654   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2655   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2656     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2657     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2658
2659     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2660         LL.getValueType().isInteger()) {
2661       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2662       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2663         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2664                                      LR.getValueType(), LL, RL);
2665         AddToWorkList(ORNode.getNode());
2666         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2667       }
2668       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2669       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2670         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2671                                       LR.getValueType(), LL, RL);
2672         AddToWorkList(ANDNode.getNode());
2673         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2674       }
2675       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2676       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2677         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2678                                      LR.getValueType(), LL, RL);
2679         AddToWorkList(ORNode.getNode());
2680         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2681       }
2682     }
2683     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2684     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2685         Op0 == Op1 && LL.getValueType().isInteger() &&
2686       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2687                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2688                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2689                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2690       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2691                                     LL, DAG.getConstant(1, LL.getValueType()));
2692       AddToWorkList(ADDNode.getNode());
2693       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2694                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2695     }
2696     // canonicalize equivalent to ll == rl
2697     if (LL == RR && LR == RL) {
2698       Op1 = ISD::getSetCCSwappedOperands(Op1);
2699       std::swap(RL, RR);
2700     }
2701     if (LL == RL && LR == RR) {
2702       bool isInteger = LL.getValueType().isInteger();
2703       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2704       if (Result != ISD::SETCC_INVALID &&
2705           (!LegalOperations ||
2706            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2707             TLI.isOperationLegal(ISD::SETCC,
2708                             getSetCCResultType(N0.getSimpleValueType())))))
2709         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2710                             LL, LR, Result);
2711     }
2712   }
2713
2714   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2715   if (N0.getOpcode() == N1.getOpcode()) {
2716     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2717     if (Tmp.getNode()) return Tmp;
2718   }
2719
2720   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2721   // fold (and (sra)) -> (and (srl)) when possible.
2722   if (!VT.isVector() &&
2723       SimplifyDemandedBits(SDValue(N, 0)))
2724     return SDValue(N, 0);
2725
2726   // fold (zext_inreg (extload x)) -> (zextload x)
2727   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2728     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2729     EVT MemVT = LN0->getMemoryVT();
2730     // If we zero all the possible extended bits, then we can turn this into
2731     // a zextload if we are running before legalize or the operation is legal.
2732     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2733     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2734                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2735         ((!LegalOperations && !LN0->isVolatile()) ||
2736          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2737       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2738                                        LN0->getChain(), LN0->getBasePtr(),
2739                                        LN0->getPointerInfo(), MemVT,
2740                                        LN0->isVolatile(), LN0->isNonTemporal(),
2741                                        LN0->getAlignment());
2742       AddToWorkList(N);
2743       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2744       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2745     }
2746   }
2747   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2748   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2749       N0.hasOneUse()) {
2750     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2751     EVT MemVT = LN0->getMemoryVT();
2752     // If we zero all the possible extended bits, then we can turn this into
2753     // a zextload if we are running before legalize or the operation is legal.
2754     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2755     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2756                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2757         ((!LegalOperations && !LN0->isVolatile()) ||
2758          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2759       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2760                                        LN0->getChain(),
2761                                        LN0->getBasePtr(), LN0->getPointerInfo(),
2762                                        MemVT,
2763                                        LN0->isVolatile(), LN0->isNonTemporal(),
2764                                        LN0->getAlignment());
2765       AddToWorkList(N);
2766       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2767       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2768     }
2769   }
2770
2771   // fold (and (load x), 255) -> (zextload x, i8)
2772   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2773   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2774   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2775               (N0.getOpcode() == ISD::ANY_EXTEND &&
2776                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2777     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2778     LoadSDNode *LN0 = HasAnyExt
2779       ? cast<LoadSDNode>(N0.getOperand(0))
2780       : cast<LoadSDNode>(N0);
2781     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2782         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2783       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2784       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2785         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2786         EVT LoadedVT = LN0->getMemoryVT();
2787
2788         if (ExtVT == LoadedVT &&
2789             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2790           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2791
2792           SDValue NewLoad =
2793             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2794                            LN0->getChain(), LN0->getBasePtr(),
2795                            LN0->getPointerInfo(),
2796                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2797                            LN0->getAlignment());
2798           AddToWorkList(N);
2799           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2800           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2801         }
2802
2803         // Do not change the width of a volatile load.
2804         // Do not generate loads of non-round integer types since these can
2805         // be expensive (and would be wrong if the type is not byte sized).
2806         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2807             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2808           EVT PtrType = LN0->getOperand(1).getValueType();
2809
2810           unsigned Alignment = LN0->getAlignment();
2811           SDValue NewPtr = LN0->getBasePtr();
2812
2813           // For big endian targets, we need to add an offset to the pointer
2814           // to load the correct bytes.  For little endian systems, we merely
2815           // need to read fewer bytes from the same pointer.
2816           if (TLI.isBigEndian()) {
2817             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2818             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2819             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2820             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2821                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2822             Alignment = MinAlign(Alignment, PtrOff);
2823           }
2824
2825           AddToWorkList(NewPtr.getNode());
2826
2827           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2828           SDValue Load =
2829             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2830                            LN0->getChain(), NewPtr,
2831                            LN0->getPointerInfo(),
2832                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2833                            Alignment);
2834           AddToWorkList(N);
2835           CombineTo(LN0, Load, Load.getValue(1));
2836           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2837         }
2838       }
2839     }
2840   }
2841
2842   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2843       VT.getSizeInBits() <= 64) {
2844     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2845       APInt ADDC = ADDI->getAPIntValue();
2846       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2847         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2848         // immediate for an add, but it is legal if its top c2 bits are set,
2849         // transform the ADD so the immediate doesn't need to be materialized
2850         // in a register.
2851         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2852           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2853                                              SRLI->getZExtValue());
2854           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2855             ADDC |= Mask;
2856             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2857               SDValue NewAdd =
2858                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2859                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
2860               CombineTo(N0.getNode(), NewAdd);
2861               return SDValue(N, 0); // Return N so it doesn't get rechecked!
2862             }
2863           }
2864         }
2865       }
2866     }
2867   }
2868
2869   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2870   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2871     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2872                                        N0.getOperand(1), false);
2873     if (BSwap.getNode())
2874       return BSwap;
2875   }
2876
2877   return SDValue();
2878 }
2879
2880 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2881 ///
2882 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2883                                         bool DemandHighBits) {
2884   if (!LegalOperations)
2885     return SDValue();
2886
2887   EVT VT = N->getValueType(0);
2888   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2889     return SDValue();
2890   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2891     return SDValue();
2892
2893   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2894   bool LookPassAnd0 = false;
2895   bool LookPassAnd1 = false;
2896   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2897       std::swap(N0, N1);
2898   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2899       std::swap(N0, N1);
2900   if (N0.getOpcode() == ISD::AND) {
2901     if (!N0.getNode()->hasOneUse())
2902       return SDValue();
2903     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2904     if (!N01C || N01C->getZExtValue() != 0xFF00)
2905       return SDValue();
2906     N0 = N0.getOperand(0);
2907     LookPassAnd0 = true;
2908   }
2909
2910   if (N1.getOpcode() == ISD::AND) {
2911     if (!N1.getNode()->hasOneUse())
2912       return SDValue();
2913     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2914     if (!N11C || N11C->getZExtValue() != 0xFF)
2915       return SDValue();
2916     N1 = N1.getOperand(0);
2917     LookPassAnd1 = true;
2918   }
2919
2920   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2921     std::swap(N0, N1);
2922   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2923     return SDValue();
2924   if (!N0.getNode()->hasOneUse() ||
2925       !N1.getNode()->hasOneUse())
2926     return SDValue();
2927
2928   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2929   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2930   if (!N01C || !N11C)
2931     return SDValue();
2932   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2933     return SDValue();
2934
2935   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
2936   SDValue N00 = N0->getOperand(0);
2937   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
2938     if (!N00.getNode()->hasOneUse())
2939       return SDValue();
2940     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
2941     if (!N001C || N001C->getZExtValue() != 0xFF)
2942       return SDValue();
2943     N00 = N00.getOperand(0);
2944     LookPassAnd0 = true;
2945   }
2946
2947   SDValue N10 = N1->getOperand(0);
2948   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
2949     if (!N10.getNode()->hasOneUse())
2950       return SDValue();
2951     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
2952     if (!N101C || N101C->getZExtValue() != 0xFF00)
2953       return SDValue();
2954     N10 = N10.getOperand(0);
2955     LookPassAnd1 = true;
2956   }
2957
2958   if (N00 != N10)
2959     return SDValue();
2960
2961   // Make sure everything beyond the low halfword gets set to zero since the SRL
2962   // 16 will clear the top bits.
2963   unsigned OpSizeInBits = VT.getSizeInBits();
2964   if (DemandHighBits && OpSizeInBits > 16) {
2965     // If the left-shift isn't masked out then the only way this is a bswap is
2966     // if all bits beyond the low 8 are 0. In that case the entire pattern
2967     // reduces to a left shift anyway: leave it for other parts of the combiner.
2968     if (!LookPassAnd0)
2969       return SDValue();
2970
2971     // However, if the right shift isn't masked out then it might be because
2972     // it's not needed. See if we can spot that too.
2973     if (!LookPassAnd1 &&
2974         !DAG.MaskedValueIsZero(
2975             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
2976       return SDValue();
2977   }
2978
2979   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
2980   if (OpSizeInBits > 16)
2981     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
2982                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
2983   return Res;
2984 }
2985
2986 /// isBSwapHWordElement - Return true if the specified node is an element
2987 /// that makes up a 32-bit packed halfword byteswap. i.e.
2988 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
2989 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
2990   if (!N.getNode()->hasOneUse())
2991     return false;
2992
2993   unsigned Opc = N.getOpcode();
2994   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
2995     return false;
2996
2997   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2998   if (!N1C)
2999     return false;
3000
3001   unsigned Num;
3002   switch (N1C->getZExtValue()) {
3003   default:
3004     return false;
3005   case 0xFF:       Num = 0; break;
3006   case 0xFF00:     Num = 1; break;
3007   case 0xFF0000:   Num = 2; break;
3008   case 0xFF000000: Num = 3; break;
3009   }
3010
3011   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3012   SDValue N0 = N.getOperand(0);
3013   if (Opc == ISD::AND) {
3014     if (Num == 0 || Num == 2) {
3015       // (x >> 8) & 0xff
3016       // (x >> 8) & 0xff0000
3017       if (N0.getOpcode() != ISD::SRL)
3018         return false;
3019       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3020       if (!C || C->getZExtValue() != 8)
3021         return false;
3022     } else {
3023       // (x << 8) & 0xff00
3024       // (x << 8) & 0xff000000
3025       if (N0.getOpcode() != ISD::SHL)
3026         return false;
3027       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3028       if (!C || C->getZExtValue() != 8)
3029         return false;
3030     }
3031   } else if (Opc == ISD::SHL) {
3032     // (x & 0xff) << 8
3033     // (x & 0xff0000) << 8
3034     if (Num != 0 && Num != 2)
3035       return false;
3036     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3037     if (!C || C->getZExtValue() != 8)
3038       return false;
3039   } else { // Opc == ISD::SRL
3040     // (x & 0xff00) >> 8
3041     // (x & 0xff000000) >> 8
3042     if (Num != 1 && Num != 3)
3043       return false;
3044     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3045     if (!C || C->getZExtValue() != 8)
3046       return false;
3047   }
3048
3049   if (Parts[Num])
3050     return false;
3051
3052   Parts[Num] = N0.getOperand(0).getNode();
3053   return true;
3054 }
3055
3056 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3057 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3058 /// => (rotl (bswap x), 16)
3059 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3060   if (!LegalOperations)
3061     return SDValue();
3062
3063   EVT VT = N->getValueType(0);
3064   if (VT != MVT::i32)
3065     return SDValue();
3066   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3067     return SDValue();
3068
3069   SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
3070   // Look for either
3071   // (or (or (and), (and)), (or (and), (and)))
3072   // (or (or (or (and), (and)), (and)), (and))
3073   if (N0.getOpcode() != ISD::OR)
3074     return SDValue();
3075   SDValue N00 = N0.getOperand(0);
3076   SDValue N01 = N0.getOperand(1);
3077
3078   if (N1.getOpcode() == ISD::OR &&
3079       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3080     // (or (or (and), (and)), (or (and), (and)))
3081     SDValue N000 = N00.getOperand(0);
3082     if (!isBSwapHWordElement(N000, Parts))
3083       return SDValue();
3084
3085     SDValue N001 = N00.getOperand(1);
3086     if (!isBSwapHWordElement(N001, Parts))
3087       return SDValue();
3088     SDValue N010 = N01.getOperand(0);
3089     if (!isBSwapHWordElement(N010, Parts))
3090       return SDValue();
3091     SDValue N011 = N01.getOperand(1);
3092     if (!isBSwapHWordElement(N011, Parts))
3093       return SDValue();
3094   } else {
3095     // (or (or (or (and), (and)), (and)), (and))
3096     if (!isBSwapHWordElement(N1, Parts))
3097       return SDValue();
3098     if (!isBSwapHWordElement(N01, Parts))
3099       return SDValue();
3100     if (N00.getOpcode() != ISD::OR)
3101       return SDValue();
3102     SDValue N000 = N00.getOperand(0);
3103     if (!isBSwapHWordElement(N000, Parts))
3104       return SDValue();
3105     SDValue N001 = N00.getOperand(1);
3106     if (!isBSwapHWordElement(N001, Parts))
3107       return SDValue();
3108   }
3109
3110   // Make sure the parts are all coming from the same node.
3111   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3112     return SDValue();
3113
3114   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3115                               SDValue(Parts[0],0));
3116
3117   // Result of the bswap should be rotated by 16. If it's not legal, than
3118   // do  (x << 16) | (x >> 16).
3119   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3120   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3121     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3122   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3123     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3124   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3125                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3126                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3127 }
3128
3129 SDValue DAGCombiner::visitOR(SDNode *N) {
3130   SDValue N0 = N->getOperand(0);
3131   SDValue N1 = N->getOperand(1);
3132   SDValue LL, LR, RL, RR, CC0, CC1;
3133   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3134   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3135   EVT VT = N1.getValueType();
3136
3137   // fold vector ops
3138   if (VT.isVector()) {
3139     SDValue FoldedVOp = SimplifyVBinOp(N);
3140     if (FoldedVOp.getNode()) return FoldedVOp;
3141
3142     // fold (or x, 0) -> x, vector edition
3143     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3144       return N1;
3145     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3146       return N0;
3147
3148     // fold (or x, -1) -> -1, vector edition
3149     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3150       return N0;
3151     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3152       return N1;
3153   }
3154
3155   // fold (or x, undef) -> -1
3156   if (!LegalOperations &&
3157       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3158     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3159     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3160   }
3161   // fold (or c1, c2) -> c1|c2
3162   if (N0C && N1C)
3163     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3164   // canonicalize constant to RHS
3165   if (N0C && !N1C)
3166     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3167   // fold (or x, 0) -> x
3168   if (N1C && N1C->isNullValue())
3169     return N0;
3170   // fold (or x, -1) -> -1
3171   if (N1C && N1C->isAllOnesValue())
3172     return N1;
3173   // fold (or x, c) -> c iff (x & ~c) == 0
3174   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3175     return N1;
3176
3177   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3178   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3179   if (BSwap.getNode() != 0)
3180     return BSwap;
3181   BSwap = MatchBSwapHWordLow(N, N0, N1);
3182   if (BSwap.getNode() != 0)
3183     return BSwap;
3184
3185   // reassociate or
3186   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3187   if (ROR.getNode() != 0)
3188     return ROR;
3189   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3190   // iff (c1 & c2) == 0.
3191   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3192              isa<ConstantSDNode>(N0.getOperand(1))) {
3193     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3194     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
3195       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3196                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3197                                      N0.getOperand(0), N1),
3198                          DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
3199   }
3200   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3201   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3202     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3203     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3204
3205     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3206         LL.getValueType().isInteger()) {
3207       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3208       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3209       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3210           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3211         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3212                                      LR.getValueType(), LL, RL);
3213         AddToWorkList(ORNode.getNode());
3214         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3215       }
3216       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3217       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3218       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3219           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3220         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3221                                       LR.getValueType(), LL, RL);
3222         AddToWorkList(ANDNode.getNode());
3223         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3224       }
3225     }
3226     // canonicalize equivalent to ll == rl
3227     if (LL == RR && LR == RL) {
3228       Op1 = ISD::getSetCCSwappedOperands(Op1);
3229       std::swap(RL, RR);
3230     }
3231     if (LL == RL && LR == RR) {
3232       bool isInteger = LL.getValueType().isInteger();
3233       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3234       if (Result != ISD::SETCC_INVALID &&
3235           (!LegalOperations ||
3236            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3237             TLI.isOperationLegal(ISD::SETCC,
3238               getSetCCResultType(N0.getValueType())))))
3239         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3240                             LL, LR, Result);
3241     }
3242   }
3243
3244   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3245   if (N0.getOpcode() == N1.getOpcode()) {
3246     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3247     if (Tmp.getNode()) return Tmp;
3248   }
3249
3250   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3251   if (N0.getOpcode() == ISD::AND &&
3252       N1.getOpcode() == ISD::AND &&
3253       N0.getOperand(1).getOpcode() == ISD::Constant &&
3254       N1.getOperand(1).getOpcode() == ISD::Constant &&
3255       // Don't increase # computations.
3256       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3257     // We can only do this xform if we know that bits from X that are set in C2
3258     // but not in C1 are already zero.  Likewise for Y.
3259     const APInt &LHSMask =
3260       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3261     const APInt &RHSMask =
3262       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3263
3264     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3265         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3266       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3267                               N0.getOperand(0), N1.getOperand(0));
3268       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3269                          DAG.getConstant(LHSMask | RHSMask, VT));
3270     }
3271   }
3272
3273   // See if this is some rotate idiom.
3274   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3275     return SDValue(Rot, 0);
3276
3277   // Simplify the operands using demanded-bits information.
3278   if (!VT.isVector() &&
3279       SimplifyDemandedBits(SDValue(N, 0)))
3280     return SDValue(N, 0);
3281
3282   return SDValue();
3283 }
3284
3285 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3286 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3287   if (Op.getOpcode() == ISD::AND) {
3288     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3289       Mask = Op.getOperand(1);
3290       Op = Op.getOperand(0);
3291     } else {
3292       return false;
3293     }
3294   }
3295
3296   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3297     Shift = Op;
3298     return true;
3299   }
3300
3301   return false;
3302 }
3303
3304 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3305 // idioms for rotate, and if the target supports rotation instructions, generate
3306 // a rot[lr].
3307 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3308   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3309   EVT VT = LHS.getValueType();
3310   if (!TLI.isTypeLegal(VT)) return 0;
3311
3312   // The target must have at least one rotate flavor.
3313   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3314   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3315   if (!HasROTL && !HasROTR) return 0;
3316
3317   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3318   SDValue LHSShift;   // The shift.
3319   SDValue LHSMask;    // AND value if any.
3320   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3321     return 0; // Not part of a rotate.
3322
3323   SDValue RHSShift;   // The shift.
3324   SDValue RHSMask;    // AND value if any.
3325   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3326     return 0; // Not part of a rotate.
3327
3328   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3329     return 0;   // Not shifting the same value.
3330
3331   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3332     return 0;   // Shifts must disagree.
3333
3334   // Canonicalize shl to left side in a shl/srl pair.
3335   if (RHSShift.getOpcode() == ISD::SHL) {
3336     std::swap(LHS, RHS);
3337     std::swap(LHSShift, RHSShift);
3338     std::swap(LHSMask , RHSMask );
3339   }
3340
3341   unsigned OpSizeInBits = VT.getSizeInBits();
3342   SDValue LHSShiftArg = LHSShift.getOperand(0);
3343   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3344   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3345
3346   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3347   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3348   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3349       RHSShiftAmt.getOpcode() == ISD::Constant) {
3350     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3351     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3352     if ((LShVal + RShVal) != OpSizeInBits)
3353       return 0;
3354
3355     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3356                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3357
3358     // If there is an AND of either shifted operand, apply it to the result.
3359     if (LHSMask.getNode() || RHSMask.getNode()) {
3360       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3361
3362       if (LHSMask.getNode()) {
3363         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3364         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3365       }
3366       if (RHSMask.getNode()) {
3367         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3368         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3369       }
3370
3371       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3372     }
3373
3374     return Rot.getNode();
3375   }
3376
3377   // If there is a mask here, and we have a variable shift, we can't be sure
3378   // that we're masking out the right stuff.
3379   if (LHSMask.getNode() || RHSMask.getNode())
3380     return 0;
3381
3382   // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
3383   // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
3384   if (RHSShiftAmt.getOpcode() == ISD::SUB &&
3385       LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
3386     if (ConstantSDNode *SUBC =
3387           dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
3388       if (SUBC->getAPIntValue() == OpSizeInBits)
3389         return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, LHSShiftArg,
3390                            HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
3391     }
3392   }
3393
3394   // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
3395   // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
3396   if (LHSShiftAmt.getOpcode() == ISD::SUB &&
3397       RHSShiftAmt == LHSShiftAmt.getOperand(1))
3398     if (ConstantSDNode *SUBC =
3399           dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0)))
3400       if (SUBC->getAPIntValue() == OpSizeInBits)
3401         return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT, LHSShiftArg,
3402                            HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
3403
3404   // Look for sign/zext/any-extended or truncate cases:
3405   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3406        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3407        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3408        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3409       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3410        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3411        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3412        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3413     SDValue LExtOp0 = LHSShiftAmt.getOperand(0);
3414     SDValue RExtOp0 = RHSShiftAmt.getOperand(0);
3415     if (RExtOp0.getOpcode() == ISD::SUB &&
3416         RExtOp0.getOperand(1) == LExtOp0) {
3417       // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3418       //   (rotl x, y)
3419       // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3420       //   (rotr x, (sub 32, y))
3421       if (ConstantSDNode *SUBC =
3422             dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0)))
3423         if (SUBC->getAPIntValue() == OpSizeInBits)
3424           return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3425                              LHSShiftArg,
3426                              HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
3427     } else if (LExtOp0.getOpcode() == ISD::SUB &&
3428                RExtOp0 == LExtOp0.getOperand(1)) {
3429       // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3430       //   (rotr x, y)
3431       // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3432       //   (rotl x, (sub 32, y))
3433       if (ConstantSDNode *SUBC =
3434             dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0)))
3435         if (SUBC->getAPIntValue() == OpSizeInBits)
3436           return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT,
3437                              LHSShiftArg,
3438                              HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
3439     }
3440   }
3441
3442   return 0;
3443 }
3444
3445 SDValue DAGCombiner::visitXOR(SDNode *N) {
3446   SDValue N0 = N->getOperand(0);
3447   SDValue N1 = N->getOperand(1);
3448   SDValue LHS, RHS, CC;
3449   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3450   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3451   EVT VT = N0.getValueType();
3452
3453   // fold vector ops
3454   if (VT.isVector()) {
3455     SDValue FoldedVOp = SimplifyVBinOp(N);
3456     if (FoldedVOp.getNode()) return FoldedVOp;
3457
3458     // fold (xor x, 0) -> x, vector edition
3459     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3460       return N1;
3461     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3462       return N0;
3463   }
3464
3465   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3466   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3467     return DAG.getConstant(0, VT);
3468   // fold (xor x, undef) -> undef
3469   if (N0.getOpcode() == ISD::UNDEF)
3470     return N0;
3471   if (N1.getOpcode() == ISD::UNDEF)
3472     return N1;
3473   // fold (xor c1, c2) -> c1^c2
3474   if (N0C && N1C)
3475     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3476   // canonicalize constant to RHS
3477   if (N0C && !N1C)
3478     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3479   // fold (xor x, 0) -> x
3480   if (N1C && N1C->isNullValue())
3481     return N0;
3482   // reassociate xor
3483   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3484   if (RXOR.getNode() != 0)
3485     return RXOR;
3486
3487   // fold !(x cc y) -> (x !cc y)
3488   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3489     bool isInt = LHS.getValueType().isInteger();
3490     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3491                                                isInt);
3492
3493     if (!LegalOperations ||
3494         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3495       switch (N0.getOpcode()) {
3496       default:
3497         llvm_unreachable("Unhandled SetCC Equivalent!");
3498       case ISD::SETCC:
3499         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3500       case ISD::SELECT_CC:
3501         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3502                                N0.getOperand(3), NotCC);
3503       }
3504     }
3505   }
3506
3507   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3508   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3509       N0.getNode()->hasOneUse() &&
3510       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3511     SDValue V = N0.getOperand(0);
3512     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3513                     DAG.getConstant(1, V.getValueType()));
3514     AddToWorkList(V.getNode());
3515     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3516   }
3517
3518   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3519   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3520       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3521     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3522     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3523       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3524       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3525       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3526       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3527       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3528     }
3529   }
3530   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3531   if (N1C && N1C->isAllOnesValue() &&
3532       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3533     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3534     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3535       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3536       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3537       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3538       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3539       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3540     }
3541   }
3542   // fold (xor (and x, y), y) -> (and (not x), y)
3543   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3544       N0->getOperand(1) == N1) {
3545     SDValue X = N0->getOperand(0);
3546     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3547     AddToWorkList(NotX.getNode());
3548     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3549   }
3550   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3551   if (N1C && N0.getOpcode() == ISD::XOR) {
3552     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3553     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3554     if (N00C)
3555       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3556                          DAG.getConstant(N1C->getAPIntValue() ^
3557                                          N00C->getAPIntValue(), VT));
3558     if (N01C)
3559       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3560                          DAG.getConstant(N1C->getAPIntValue() ^
3561                                          N01C->getAPIntValue(), VT));
3562   }
3563   // fold (xor x, x) -> 0
3564   if (N0 == N1)
3565     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3566
3567   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3568   if (N0.getOpcode() == N1.getOpcode()) {
3569     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3570     if (Tmp.getNode()) return Tmp;
3571   }
3572
3573   // Simplify the expression using non-local knowledge.
3574   if (!VT.isVector() &&
3575       SimplifyDemandedBits(SDValue(N, 0)))
3576     return SDValue(N, 0);
3577
3578   return SDValue();
3579 }
3580
3581 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3582 /// the shift amount is a constant.
3583 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
3584   SDNode *LHS = N->getOperand(0).getNode();
3585   if (!LHS->hasOneUse()) return SDValue();
3586
3587   // We want to pull some binops through shifts, so that we have (and (shift))
3588   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3589   // thing happens with address calculations, so it's important to canonicalize
3590   // it.
3591   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3592
3593   switch (LHS->getOpcode()) {
3594   default: return SDValue();
3595   case ISD::OR:
3596   case ISD::XOR:
3597     HighBitSet = false; // We can only transform sra if the high bit is clear.
3598     break;
3599   case ISD::AND:
3600     HighBitSet = true;  // We can only transform sra if the high bit is set.
3601     break;
3602   case ISD::ADD:
3603     if (N->getOpcode() != ISD::SHL)
3604       return SDValue(); // only shl(add) not sr[al](add).
3605     HighBitSet = false; // We can only transform sra if the high bit is clear.
3606     break;
3607   }
3608
3609   // We require the RHS of the binop to be a constant as well.
3610   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3611   if (!BinOpCst) return SDValue();
3612
3613   // FIXME: disable this unless the input to the binop is a shift by a constant.
3614   // If it is not a shift, it pessimizes some common cases like:
3615   //
3616   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3617   //    int bar(int *X, int i) { return X[i & 255]; }
3618   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3619   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3620        BinOpLHSVal->getOpcode() != ISD::SRA &&
3621        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3622       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3623     return SDValue();
3624
3625   EVT VT = N->getValueType(0);
3626
3627   // If this is a signed shift right, and the high bit is modified by the
3628   // logical operation, do not perform the transformation. The highBitSet
3629   // boolean indicates the value of the high bit of the constant which would
3630   // cause it to be modified for this operation.
3631   if (N->getOpcode() == ISD::SRA) {
3632     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3633     if (BinOpRHSSignSet != HighBitSet)
3634       return SDValue();
3635   }
3636
3637   // Fold the constants, shifting the binop RHS by the shift amount.
3638   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3639                                N->getValueType(0),
3640                                LHS->getOperand(1), N->getOperand(1));
3641
3642   // Create the new shift.
3643   SDValue NewShift = DAG.getNode(N->getOpcode(),
3644                                  SDLoc(LHS->getOperand(0)),
3645                                  VT, LHS->getOperand(0), N->getOperand(1));
3646
3647   // Create the new binop.
3648   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3649 }
3650
3651 SDValue DAGCombiner::visitSHL(SDNode *N) {
3652   SDValue N0 = N->getOperand(0);
3653   SDValue N1 = N->getOperand(1);
3654   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3655   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3656   EVT VT = N0.getValueType();
3657   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3658
3659   // fold (shl c1, c2) -> c1<<c2
3660   if (N0C && N1C)
3661     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3662   // fold (shl 0, x) -> 0
3663   if (N0C && N0C->isNullValue())
3664     return N0;
3665   // fold (shl x, c >= size(x)) -> undef
3666   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3667     return DAG.getUNDEF(VT);
3668   // fold (shl x, 0) -> x
3669   if (N1C && N1C->isNullValue())
3670     return N0;
3671   // fold (shl undef, x) -> 0
3672   if (N0.getOpcode() == ISD::UNDEF)
3673     return DAG.getConstant(0, VT);
3674   // if (shl x, c) is known to be zero, return 0
3675   if (DAG.MaskedValueIsZero(SDValue(N, 0),
3676                             APInt::getAllOnesValue(OpSizeInBits)))
3677     return DAG.getConstant(0, VT);
3678   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3679   if (N1.getOpcode() == ISD::TRUNCATE &&
3680       N1.getOperand(0).getOpcode() == ISD::AND &&
3681       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3682     SDValue N101 = N1.getOperand(0).getOperand(1);
3683     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3684       EVT TruncVT = N1.getValueType();
3685       SDValue N100 = N1.getOperand(0).getOperand(0);
3686       APInt TruncC = N101C->getAPIntValue();
3687       TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3688       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
3689                          DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3690                                      DAG.getNode(ISD::TRUNCATE,
3691                                                  SDLoc(N),
3692                                                  TruncVT, N100),
3693                                      DAG.getConstant(TruncC, TruncVT)));
3694     }
3695   }
3696
3697   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3698     return SDValue(N, 0);
3699
3700   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3701   if (N1C && N0.getOpcode() == ISD::SHL &&
3702       N0.getOperand(1).getOpcode() == ISD::Constant) {
3703     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3704     uint64_t c2 = N1C->getZExtValue();
3705     if (c1 + c2 >= OpSizeInBits)
3706       return DAG.getConstant(0, VT);
3707     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3708                        DAG.getConstant(c1 + c2, N1.getValueType()));
3709   }
3710
3711   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3712   // For this to be valid, the second form must not preserve any of the bits
3713   // that are shifted out by the inner shift in the first form.  This means
3714   // the outer shift size must be >= the number of bits added by the ext.
3715   // As a corollary, we don't care what kind of ext it is.
3716   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3717               N0.getOpcode() == ISD::ANY_EXTEND ||
3718               N0.getOpcode() == ISD::SIGN_EXTEND) &&
3719       N0.getOperand(0).getOpcode() == ISD::SHL &&
3720       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3721     uint64_t c1 =
3722       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3723     uint64_t c2 = N1C->getZExtValue();
3724     EVT InnerShiftVT = N0.getOperand(0).getValueType();
3725     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3726     if (c2 >= OpSizeInBits - InnerShiftSize) {
3727       if (c1 + c2 >= OpSizeInBits)
3728         return DAG.getConstant(0, VT);
3729       return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
3730                          DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
3731                                      N0.getOperand(0)->getOperand(0)),
3732                          DAG.getConstant(c1 + c2, N1.getValueType()));
3733     }
3734   }
3735
3736   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
3737   //                               (and (srl x, (sub c1, c2), MASK)
3738   // Only fold this if the inner shift has no other uses -- if it does, folding
3739   // this will increase the total number of instructions.
3740   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
3741       N0.getOperand(1).getOpcode() == ISD::Constant) {
3742     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3743     if (c1 < VT.getSizeInBits()) {
3744       uint64_t c2 = N1C->getZExtValue();
3745       APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3746                                          VT.getSizeInBits() - c1);
3747       SDValue Shift;
3748       if (c2 > c1) {
3749         Mask = Mask.shl(c2-c1);
3750         Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3751                             DAG.getConstant(c2-c1, N1.getValueType()));
3752       } else {
3753         Mask = Mask.lshr(c1-c2);
3754         Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
3755                             DAG.getConstant(c1-c2, N1.getValueType()));
3756       }
3757       return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
3758                          DAG.getConstant(Mask, VT));
3759     }
3760   }
3761   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
3762   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3763     SDValue HiBitsMask =
3764       DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3765                                             VT.getSizeInBits() -
3766                                               N1C->getZExtValue()),
3767                       VT);
3768     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
3769                        HiBitsMask);
3770   }
3771
3772   if (N1C) {
3773     SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3774     if (NewSHL.getNode())
3775       return NewSHL;
3776   }
3777
3778   return SDValue();
3779 }
3780
3781 SDValue DAGCombiner::visitSRA(SDNode *N) {
3782   SDValue N0 = N->getOperand(0);
3783   SDValue N1 = N->getOperand(1);
3784   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3785   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3786   EVT VT = N0.getValueType();
3787   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3788
3789   // fold (sra c1, c2) -> (sra c1, c2)
3790   if (N0C && N1C)
3791     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
3792   // fold (sra 0, x) -> 0
3793   if (N0C && N0C->isNullValue())
3794     return N0;
3795   // fold (sra -1, x) -> -1
3796   if (N0C && N0C->isAllOnesValue())
3797     return N0;
3798   // fold (sra x, (setge c, size(x))) -> undef
3799   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3800     return DAG.getUNDEF(VT);
3801   // fold (sra x, 0) -> x
3802   if (N1C && N1C->isNullValue())
3803     return N0;
3804   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3805   // sext_inreg.
3806   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
3807     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
3808     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
3809     if (VT.isVector())
3810       ExtVT = EVT::getVectorVT(*DAG.getContext(),
3811                                ExtVT, VT.getVectorNumElements());
3812     if ((!LegalOperations ||
3813          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
3814       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
3815                          N0.getOperand(0), DAG.getValueType(ExtVT));
3816   }
3817
3818   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
3819   if (N1C && N0.getOpcode() == ISD::SRA) {
3820     if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3821       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
3822       if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
3823       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
3824                          DAG.getConstant(Sum, N1C->getValueType(0)));
3825     }
3826   }
3827
3828   // fold (sra (shl X, m), (sub result_size, n))
3829   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
3830   // result_size - n != m.
3831   // If truncate is free for the target sext(shl) is likely to result in better
3832   // code.
3833   if (N0.getOpcode() == ISD::SHL) {
3834     // Get the two constanst of the shifts, CN0 = m, CN = n.
3835     const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3836     if (N01C && N1C) {
3837       // Determine what the truncate's result bitsize and type would be.
3838       EVT TruncVT =
3839         EVT::getIntegerVT(*DAG.getContext(),
3840                           OpSizeInBits - N1C->getZExtValue());
3841       // Determine the residual right-shift amount.
3842       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
3843
3844       // If the shift is not a no-op (in which case this should be just a sign
3845       // extend already), the truncated to type is legal, sign_extend is legal
3846       // on that type, and the truncate to that type is both legal and free,
3847       // perform the transform.
3848       if ((ShiftAmt > 0) &&
3849           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
3850           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
3851           TLI.isTruncateFree(VT, TruncVT)) {
3852
3853           SDValue Amt = DAG.getConstant(ShiftAmt,
3854               getShiftAmountTy(N0.getOperand(0).getValueType()));
3855           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
3856                                       N0.getOperand(0), Amt);
3857           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
3858                                       Shift);
3859           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
3860                              N->getValueType(0), Trunc);
3861       }
3862     }
3863   }
3864
3865   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
3866   if (N1.getOpcode() == ISD::TRUNCATE &&
3867       N1.getOperand(0).getOpcode() == ISD::AND &&
3868       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3869     SDValue N101 = N1.getOperand(0).getOperand(1);
3870     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3871       EVT TruncVT = N1.getValueType();
3872       SDValue N100 = N1.getOperand(0).getOperand(0);
3873       APInt TruncC = N101C->getAPIntValue();
3874       TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
3875       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
3876                          DAG.getNode(ISD::AND, SDLoc(N),
3877                                      TruncVT,
3878                                      DAG.getNode(ISD::TRUNCATE,
3879                                                  SDLoc(N),
3880                                                  TruncVT, N100),
3881                                      DAG.getConstant(TruncC, TruncVT)));
3882     }
3883   }
3884
3885   // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
3886   //      if c1 is equal to the number of bits the trunc removes
3887   if (N0.getOpcode() == ISD::TRUNCATE &&
3888       (N0.getOperand(0).getOpcode() == ISD::SRL ||
3889        N0.getOperand(0).getOpcode() == ISD::SRA) &&
3890       N0.getOperand(0).hasOneUse() &&
3891       N0.getOperand(0).getOperand(1).hasOneUse() &&
3892       N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
3893     EVT LargeVT = N0.getOperand(0).getValueType();
3894     ConstantSDNode *LargeShiftAmt =
3895       cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
3896
3897     if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
3898         LargeShiftAmt->getZExtValue()) {
3899       SDValue Amt =
3900         DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
3901               getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
3902       SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
3903                                 N0.getOperand(0).getOperand(0), Amt);
3904       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
3905     }
3906   }
3907
3908   // Simplify, based on bits shifted out of the LHS.
3909   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3910     return SDValue(N, 0);
3911
3912
3913   // If the sign bit is known to be zero, switch this to a SRL.
3914   if (DAG.SignBitIsZero(N0))
3915     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
3916
3917   if (N1C) {
3918     SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
3919     if (NewSRA.getNode())
3920       return NewSRA;
3921   }
3922
3923   return SDValue();
3924 }
3925
3926 SDValue DAGCombiner::visitSRL(SDNode *N) {
3927   SDValue N0 = N->getOperand(0);
3928   SDValue N1 = N->getOperand(1);
3929   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3930   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3931   EVT VT = N0.getValueType();
3932   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3933
3934   // fold (srl c1, c2) -> c1 >>u c2
3935   if (N0C && N1C)
3936     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
3937   // fold (srl 0, x) -> 0
3938   if (N0C && N0C->isNullValue())
3939     return N0;
3940   // fold (srl x, c >= size(x)) -> undef
3941   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3942     return DAG.getUNDEF(VT);
3943   // fold (srl x, 0) -> x
3944   if (N1C && N1C->isNullValue())
3945     return N0;
3946   // if (srl x, c) is known to be zero, return 0
3947   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3948                                    APInt::getAllOnesValue(OpSizeInBits)))
3949     return DAG.getConstant(0, VT);
3950
3951   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
3952   if (N1C && N0.getOpcode() == ISD::SRL &&
3953       N0.getOperand(1).getOpcode() == ISD::Constant) {
3954     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3955     uint64_t c2 = N1C->getZExtValue();
3956     if (c1 + c2 >= OpSizeInBits)
3957       return DAG.getConstant(0, VT);
3958     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
3959                        DAG.getConstant(c1 + c2, N1.getValueType()));
3960   }
3961
3962   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
3963   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
3964       N0.getOperand(0).getOpcode() == ISD::SRL &&
3965       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3966     uint64_t c1 =
3967       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3968     uint64_t c2 = N1C->getZExtValue();
3969     EVT InnerShiftVT = N0.getOperand(0).getValueType();
3970     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
3971     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3972     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
3973     if (c1 + OpSizeInBits == InnerShiftSize) {
3974       if (c1 + c2 >= InnerShiftSize)
3975         return DAG.getConstant(0, VT);
3976       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
3977                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
3978                                      N0.getOperand(0)->getOperand(0),
3979                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
3980     }
3981   }
3982
3983   // fold (srl (shl x, c), c) -> (and x, cst2)
3984   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
3985       N0.getValueSizeInBits() <= 64) {
3986     uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
3987     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
3988                        DAG.getConstant(~0ULL >> ShAmt, VT));
3989   }
3990
3991   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
3992   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3993     // Shifting in all undef bits?
3994     EVT SmallVT = N0.getOperand(0).getValueType();
3995     if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
3996       return DAG.getUNDEF(VT);
3997
3998     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
3999       uint64_t ShiftAmt = N1C->getZExtValue();
4000       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4001                                        N0.getOperand(0),
4002                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4003       AddToWorkList(SmallShift.getNode());
4004       APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits()).lshr(ShiftAmt);
4005       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4006                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4007                          DAG.getConstant(Mask, VT));
4008     }
4009   }
4010
4011   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4012   // bit, which is unmodified by sra.
4013   if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
4014     if (N0.getOpcode() == ISD::SRA)
4015       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4016   }
4017
4018   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4019   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4020       N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
4021     APInt KnownZero, KnownOne;
4022     DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
4023
4024     // If any of the input bits are KnownOne, then the input couldn't be all
4025     // zeros, thus the result of the srl will always be zero.
4026     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4027
4028     // If all of the bits input the to ctlz node are known to be zero, then
4029     // the result of the ctlz is "32" and the result of the shift is one.
4030     APInt UnknownBits = ~KnownZero;
4031     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4032
4033     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4034     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4035       // Okay, we know that only that the single bit specified by UnknownBits
4036       // could be set on input to the CTLZ node. If this bit is set, the SRL
4037       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4038       // to an SRL/XOR pair, which is likely to simplify more.
4039       unsigned ShAmt = UnknownBits.countTrailingZeros();
4040       SDValue Op = N0.getOperand(0);
4041
4042       if (ShAmt) {
4043         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4044                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4045         AddToWorkList(Op.getNode());
4046       }
4047
4048       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4049                          Op, DAG.getConstant(1, VT));
4050     }
4051   }
4052
4053   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4054   if (N1.getOpcode() == ISD::TRUNCATE &&
4055       N1.getOperand(0).getOpcode() == ISD::AND &&
4056       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
4057     SDValue N101 = N1.getOperand(0).getOperand(1);
4058     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
4059       EVT TruncVT = N1.getValueType();
4060       SDValue N100 = N1.getOperand(0).getOperand(0);
4061       APInt TruncC = N101C->getAPIntValue();
4062       TruncC = TruncC.trunc(TruncVT.getSizeInBits());
4063       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
4064                          DAG.getNode(ISD::AND, SDLoc(N),
4065                                      TruncVT,
4066                                      DAG.getNode(ISD::TRUNCATE,
4067                                                  SDLoc(N),
4068                                                  TruncVT, N100),
4069                                      DAG.getConstant(TruncC, TruncVT)));
4070     }
4071   }
4072
4073   // fold operands of srl based on knowledge that the low bits are not
4074   // demanded.
4075   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4076     return SDValue(N, 0);
4077
4078   if (N1C) {
4079     SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
4080     if (NewSRL.getNode())
4081       return NewSRL;
4082   }
4083
4084   // Attempt to convert a srl of a load into a narrower zero-extending load.
4085   SDValue NarrowLoad = ReduceLoadWidth(N);
4086   if (NarrowLoad.getNode())
4087     return NarrowLoad;
4088
4089   // Here is a common situation. We want to optimize:
4090   //
4091   //   %a = ...
4092   //   %b = and i32 %a, 2
4093   //   %c = srl i32 %b, 1
4094   //   brcond i32 %c ...
4095   //
4096   // into
4097   //
4098   //   %a = ...
4099   //   %b = and %a, 2
4100   //   %c = setcc eq %b, 0
4101   //   brcond %c ...
4102   //
4103   // However when after the source operand of SRL is optimized into AND, the SRL
4104   // itself may not be optimized further. Look for it and add the BRCOND into
4105   // the worklist.
4106   if (N->hasOneUse()) {
4107     SDNode *Use = *N->use_begin();
4108     if (Use->getOpcode() == ISD::BRCOND)
4109       AddToWorkList(Use);
4110     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4111       // Also look pass the truncate.
4112       Use = *Use->use_begin();
4113       if (Use->getOpcode() == ISD::BRCOND)
4114         AddToWorkList(Use);
4115     }
4116   }
4117
4118   return SDValue();
4119 }
4120
4121 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4122   SDValue N0 = N->getOperand(0);
4123   EVT VT = N->getValueType(0);
4124
4125   // fold (ctlz c1) -> c2
4126   if (isa<ConstantSDNode>(N0))
4127     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4128   return SDValue();
4129 }
4130
4131 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4132   SDValue N0 = N->getOperand(0);
4133   EVT VT = N->getValueType(0);
4134
4135   // fold (ctlz_zero_undef c1) -> c2
4136   if (isa<ConstantSDNode>(N0))
4137     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4138   return SDValue();
4139 }
4140
4141 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4142   SDValue N0 = N->getOperand(0);
4143   EVT VT = N->getValueType(0);
4144
4145   // fold (cttz c1) -> c2
4146   if (isa<ConstantSDNode>(N0))
4147     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4148   return SDValue();
4149 }
4150
4151 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4152   SDValue N0 = N->getOperand(0);
4153   EVT VT = N->getValueType(0);
4154
4155   // fold (cttz_zero_undef c1) -> c2
4156   if (isa<ConstantSDNode>(N0))
4157     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4158   return SDValue();
4159 }
4160
4161 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4162   SDValue N0 = N->getOperand(0);
4163   EVT VT = N->getValueType(0);
4164
4165   // fold (ctpop c1) -> c2
4166   if (isa<ConstantSDNode>(N0))
4167     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4168   return SDValue();
4169 }
4170
4171 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4172   SDValue N0 = N->getOperand(0);
4173   SDValue N1 = N->getOperand(1);
4174   SDValue N2 = N->getOperand(2);
4175   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4176   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4177   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4178   EVT VT = N->getValueType(0);
4179   EVT VT0 = N0.getValueType();
4180
4181   // fold (select C, X, X) -> X
4182   if (N1 == N2)
4183     return N1;
4184   // fold (select true, X, Y) -> X
4185   if (N0C && !N0C->isNullValue())
4186     return N1;
4187   // fold (select false, X, Y) -> Y
4188   if (N0C && N0C->isNullValue())
4189     return N2;
4190   // fold (select C, 1, X) -> (or C, X)
4191   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4192     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4193   // fold (select C, 0, 1) -> (xor C, 1)
4194   if (VT.isInteger() &&
4195       (VT0 == MVT::i1 ||
4196        (VT0.isInteger() &&
4197         TLI.getBooleanContents(false) ==
4198         TargetLowering::ZeroOrOneBooleanContent)) &&
4199       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4200     SDValue XORNode;
4201     if (VT == VT0)
4202       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4203                          N0, DAG.getConstant(1, VT0));
4204     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4205                           N0, DAG.getConstant(1, VT0));
4206     AddToWorkList(XORNode.getNode());
4207     if (VT.bitsGT(VT0))
4208       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4209     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4210   }
4211   // fold (select C, 0, X) -> (and (not C), X)
4212   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4213     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4214     AddToWorkList(NOTNode.getNode());
4215     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4216   }
4217   // fold (select C, X, 1) -> (or (not C), X)
4218   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4219     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4220     AddToWorkList(NOTNode.getNode());
4221     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4222   }
4223   // fold (select C, X, 0) -> (and C, X)
4224   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4225     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4226   // fold (select X, X, Y) -> (or X, Y)
4227   // fold (select X, 1, Y) -> (or X, Y)
4228   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4229     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4230   // fold (select X, Y, X) -> (and X, Y)
4231   // fold (select X, Y, 0) -> (and X, Y)
4232   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4233     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4234
4235   // If we can fold this based on the true/false value, do so.
4236   if (SimplifySelectOps(N, N1, N2))
4237     return SDValue(N, 0);  // Don't revisit N.
4238
4239   // fold selects based on a setcc into other things, such as min/max/abs
4240   if (N0.getOpcode() == ISD::SETCC) {
4241     // FIXME:
4242     // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4243     // having to say they don't support SELECT_CC on every type the DAG knows
4244     // about, since there is no way to mark an opcode illegal at all value types
4245     if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4246         TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4247       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4248                          N0.getOperand(0), N0.getOperand(1),
4249                          N1, N2, N0.getOperand(2));
4250     return SimplifySelect(SDLoc(N), N0, N1, N2);
4251   }
4252
4253   return SDValue();
4254 }
4255
4256 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4257   SDValue N0 = N->getOperand(0);
4258   SDValue N1 = N->getOperand(1);
4259   SDValue N2 = N->getOperand(2);
4260   SDLoc DL(N);
4261
4262   // Canonicalize integer abs.
4263   // vselect (setg[te] X,  0),  X, -X ->
4264   // vselect (setgt    X, -1),  X, -X ->
4265   // vselect (setl[te] X,  0), -X,  X ->
4266   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4267   if (N0.getOpcode() == ISD::SETCC) {
4268     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4269     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4270     bool isAbs = false;
4271     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4272
4273     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4274          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4275         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4276       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4277     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4278              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4279       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4280
4281     if (isAbs) {
4282       EVT VT = LHS.getValueType();
4283       SDValue Shift = DAG.getNode(
4284           ISD::SRA, DL, VT, LHS,
4285           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4286       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4287       AddToWorkList(Shift.getNode());
4288       AddToWorkList(Add.getNode());
4289       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4290     }
4291   }
4292
4293   return SDValue();
4294 }
4295
4296 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4297   SDValue N0 = N->getOperand(0);
4298   SDValue N1 = N->getOperand(1);
4299   SDValue N2 = N->getOperand(2);
4300   SDValue N3 = N->getOperand(3);
4301   SDValue N4 = N->getOperand(4);
4302   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4303
4304   // fold select_cc lhs, rhs, x, x, cc -> x
4305   if (N2 == N3)
4306     return N2;
4307
4308   // Determine if the condition we're dealing with is constant
4309   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4310                               N0, N1, CC, SDLoc(N), false);
4311   if (SCC.getNode()) {
4312     AddToWorkList(SCC.getNode());
4313
4314     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4315       if (!SCCC->isNullValue())
4316         return N2;    // cond always true -> true val
4317       else
4318         return N3;    // cond always false -> false val
4319     }
4320
4321     // Fold to a simpler select_cc
4322     if (SCC.getOpcode() == ISD::SETCC)
4323       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4324                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4325                          SCC.getOperand(2));
4326   }
4327
4328   // If we can fold this based on the true/false value, do so.
4329   if (SimplifySelectOps(N, N2, N3))
4330     return SDValue(N, 0);  // Don't revisit N.
4331
4332   // fold select_cc into other things, such as min/max/abs
4333   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4334 }
4335
4336 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4337   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4338                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4339                        SDLoc(N));
4340 }
4341
4342 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4343 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4344 // transformation. Returns true if extension are possible and the above
4345 // mentioned transformation is profitable.
4346 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4347                                     unsigned ExtOpc,
4348                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4349                                     const TargetLowering &TLI) {
4350   bool HasCopyToRegUses = false;
4351   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4352   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4353                             UE = N0.getNode()->use_end();
4354        UI != UE; ++UI) {
4355     SDNode *User = *UI;
4356     if (User == N)
4357       continue;
4358     if (UI.getUse().getResNo() != N0.getResNo())
4359       continue;
4360     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4361     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4362       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4363       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4364         // Sign bits will be lost after a zext.
4365         return false;
4366       bool Add = false;
4367       for (unsigned i = 0; i != 2; ++i) {
4368         SDValue UseOp = User->getOperand(i);
4369         if (UseOp == N0)
4370           continue;
4371         if (!isa<ConstantSDNode>(UseOp))
4372           return false;
4373         Add = true;
4374       }
4375       if (Add)
4376         ExtendNodes.push_back(User);
4377       continue;
4378     }
4379     // If truncates aren't free and there are users we can't
4380     // extend, it isn't worthwhile.
4381     if (!isTruncFree)
4382       return false;
4383     // Remember if this value is live-out.
4384     if (User->getOpcode() == ISD::CopyToReg)
4385       HasCopyToRegUses = true;
4386   }
4387
4388   if (HasCopyToRegUses) {
4389     bool BothLiveOut = false;
4390     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4391          UI != UE; ++UI) {
4392       SDUse &Use = UI.getUse();
4393       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4394         BothLiveOut = true;
4395         break;
4396       }
4397     }
4398     if (BothLiveOut)
4399       // Both unextended and extended values are live out. There had better be
4400       // a good reason for the transformation.
4401       return ExtendNodes.size();
4402   }
4403   return true;
4404 }
4405
4406 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4407                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4408                                   ISD::NodeType ExtType) {
4409   // Extend SetCC uses if necessary.
4410   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4411     SDNode *SetCC = SetCCs[i];
4412     SmallVector<SDValue, 4> Ops;
4413
4414     for (unsigned j = 0; j != 2; ++j) {
4415       SDValue SOp = SetCC->getOperand(j);
4416       if (SOp == Trunc)
4417         Ops.push_back(ExtLoad);
4418       else
4419         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4420     }
4421
4422     Ops.push_back(SetCC->getOperand(2));
4423     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4424                                  &Ops[0], Ops.size()));
4425   }
4426 }
4427
4428 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4429   SDValue N0 = N->getOperand(0);
4430   EVT VT = N->getValueType(0);
4431
4432   // fold (sext c1) -> c1
4433   if (isa<ConstantSDNode>(N0))
4434     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N0);
4435
4436   // fold (sext (sext x)) -> (sext x)
4437   // fold (sext (aext x)) -> (sext x)
4438   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4439     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4440                        N0.getOperand(0));
4441
4442   if (N0.getOpcode() == ISD::TRUNCATE) {
4443     // fold (sext (truncate (load x))) -> (sext (smaller load x))
4444     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4445     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4446     if (NarrowLoad.getNode()) {
4447       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4448       if (NarrowLoad.getNode() != N0.getNode()) {
4449         CombineTo(N0.getNode(), NarrowLoad);
4450         // CombineTo deleted the truncate, if needed, but not what's under it.
4451         AddToWorkList(oye);
4452       }
4453       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4454     }
4455
4456     // See if the value being truncated is already sign extended.  If so, just
4457     // eliminate the trunc/sext pair.
4458     SDValue Op = N0.getOperand(0);
4459     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
4460     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
4461     unsigned DestBits = VT.getScalarType().getSizeInBits();
4462     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4463
4464     if (OpBits == DestBits) {
4465       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
4466       // bits, it is already ready.
4467       if (NumSignBits > DestBits-MidBits)
4468         return Op;
4469     } else if (OpBits < DestBits) {
4470       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
4471       // bits, just sext from i32.
4472       if (NumSignBits > OpBits-MidBits)
4473         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4474     } else {
4475       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
4476       // bits, just truncate to i32.
4477       if (NumSignBits > OpBits-MidBits)
4478         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4479     }
4480
4481     // fold (sext (truncate x)) -> (sextinreg x).
4482     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4483                                                  N0.getValueType())) {
4484       if (OpBits < DestBits)
4485         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4486       else if (OpBits > DestBits)
4487         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4488       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4489                          DAG.getValueType(N0.getValueType()));
4490     }
4491   }
4492
4493   // fold (sext (load x)) -> (sext (truncate (sextload x)))
4494   // None of the supported targets knows how to perform load and sign extend
4495   // on vectors in one instruction.  We only perform this transformation on
4496   // scalars.
4497   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4498       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4499        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4500     bool DoXform = true;
4501     SmallVector<SDNode*, 4> SetCCs;
4502     if (!N0.hasOneUse())
4503       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4504     if (DoXform) {
4505       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4506       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4507                                        LN0->getChain(),
4508                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4509                                        N0.getValueType(),
4510                                        LN0->isVolatile(), LN0->isNonTemporal(),
4511                                        LN0->getAlignment());
4512       CombineTo(N, ExtLoad);
4513       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4514                                   N0.getValueType(), ExtLoad);
4515       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4516       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4517                       ISD::SIGN_EXTEND);
4518       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4519     }
4520   }
4521
4522   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4523   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4524   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4525       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4526     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4527     EVT MemVT = LN0->getMemoryVT();
4528     if ((!LegalOperations && !LN0->isVolatile()) ||
4529         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4530       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4531                                        LN0->getChain(),
4532                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4533                                        MemVT,
4534                                        LN0->isVolatile(), LN0->isNonTemporal(),
4535                                        LN0->getAlignment());
4536       CombineTo(N, ExtLoad);
4537       CombineTo(N0.getNode(),
4538                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4539                             N0.getValueType(), ExtLoad),
4540                 ExtLoad.getValue(1));
4541       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4542     }
4543   }
4544
4545   // fold (sext (and/or/xor (load x), cst)) ->
4546   //      (and/or/xor (sextload x), (sext cst))
4547   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4548        N0.getOpcode() == ISD::XOR) &&
4549       isa<LoadSDNode>(N0.getOperand(0)) &&
4550       N0.getOperand(1).getOpcode() == ISD::Constant &&
4551       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4552       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4553     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4554     if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4555       bool DoXform = true;
4556       SmallVector<SDNode*, 4> SetCCs;
4557       if (!N0.hasOneUse())
4558         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4559                                           SetCCs, TLI);
4560       if (DoXform) {
4561         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
4562                                          LN0->getChain(), LN0->getBasePtr(),
4563                                          LN0->getPointerInfo(),
4564                                          LN0->getMemoryVT(),
4565                                          LN0->isVolatile(),
4566                                          LN0->isNonTemporal(),
4567                                          LN0->getAlignment());
4568         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4569         Mask = Mask.sext(VT.getSizeInBits());
4570         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4571                                   ExtLoad, DAG.getConstant(Mask, VT));
4572         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4573                                     SDLoc(N0.getOperand(0)),
4574                                     N0.getOperand(0).getValueType(), ExtLoad);
4575         CombineTo(N, And);
4576         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4577         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4578                         ISD::SIGN_EXTEND);
4579         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4580       }
4581     }
4582   }
4583
4584   if (N0.getOpcode() == ISD::SETCC) {
4585     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
4586     // Only do this before legalize for now.
4587     if (VT.isVector() && !LegalOperations &&
4588         TLI.getBooleanContents(true) ==
4589           TargetLowering::ZeroOrNegativeOneBooleanContent) {
4590       EVT N0VT = N0.getOperand(0).getValueType();
4591       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
4592       // of the same size as the compared operands. Only optimize sext(setcc())
4593       // if this is the case.
4594       EVT SVT = getSetCCResultType(N0VT);
4595
4596       // We know that the # elements of the results is the same as the
4597       // # elements of the compare (and the # elements of the compare result
4598       // for that matter).  Check to see that they are the same size.  If so,
4599       // we know that the element size of the sext'd result matches the
4600       // element size of the compare operands.
4601       if (VT.getSizeInBits() == SVT.getSizeInBits())
4602         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4603                              N0.getOperand(1),
4604                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
4605
4606       // If the desired elements are smaller or larger than the source
4607       // elements we can use a matching integer vector type and then
4608       // truncate/sign extend
4609       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
4610       if (SVT == MatchingVectorType) {
4611         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
4612                                N0.getOperand(0), N0.getOperand(1),
4613                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
4614         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
4615       }
4616     }
4617
4618     // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
4619     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
4620     SDValue NegOne =
4621       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
4622     SDValue SCC =
4623       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
4624                        NegOne, DAG.getConstant(0, VT),
4625                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4626     if (SCC.getNode()) return SCC;
4627     if (!VT.isVector() &&
4628         (!LegalOperations ||
4629          TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(VT)))) {
4630       return DAG.getSelect(SDLoc(N), VT,
4631                            DAG.getSetCC(SDLoc(N),
4632                                         getSetCCResultType(VT),
4633                                         N0.getOperand(0), N0.getOperand(1),
4634                                         cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4635                            NegOne, DAG.getConstant(0, VT));
4636     }
4637   }
4638
4639   // fold (sext x) -> (zext x) if the sign bit is known zero.
4640   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
4641       DAG.SignBitIsZero(N0))
4642     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4643
4644   return SDValue();
4645 }
4646
4647 // isTruncateOf - If N is a truncate of some other value, return true, record
4648 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
4649 // This function computes KnownZero to avoid a duplicated call to
4650 // ComputeMaskedBits in the caller.
4651 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
4652                          APInt &KnownZero) {
4653   APInt KnownOne;
4654   if (N->getOpcode() == ISD::TRUNCATE) {
4655     Op = N->getOperand(0);
4656     DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4657     return true;
4658   }
4659
4660   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
4661       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
4662     return false;
4663
4664   SDValue Op0 = N->getOperand(0);
4665   SDValue Op1 = N->getOperand(1);
4666   assert(Op0.getValueType() == Op1.getValueType());
4667
4668   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
4669   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
4670   if (COp0 && COp0->isNullValue())
4671     Op = Op1;
4672   else if (COp1 && COp1->isNullValue())
4673     Op = Op0;
4674   else
4675     return false;
4676
4677   DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4678
4679   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
4680     return false;
4681
4682   return true;
4683 }
4684
4685 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
4686   SDValue N0 = N->getOperand(0);
4687   EVT VT = N->getValueType(0);
4688
4689   // fold (zext c1) -> c1
4690   if (isa<ConstantSDNode>(N0))
4691     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4692   // fold (zext (zext x)) -> (zext x)
4693   // fold (zext (aext x)) -> (zext x)
4694   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4695     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
4696                        N0.getOperand(0));
4697
4698   // fold (zext (truncate x)) -> (zext x) or
4699   //      (zext (truncate x)) -> (truncate x)
4700   // This is valid when the truncated bits of x are already zero.
4701   // FIXME: We should extend this to work for vectors too.
4702   SDValue Op;
4703   APInt KnownZero;
4704   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
4705     APInt TruncatedBits =
4706       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
4707       APInt(Op.getValueSizeInBits(), 0) :
4708       APInt::getBitsSet(Op.getValueSizeInBits(),
4709                         N0.getValueSizeInBits(),
4710                         std::min(Op.getValueSizeInBits(),
4711                                  VT.getSizeInBits()));
4712     if (TruncatedBits == (KnownZero & TruncatedBits)) {
4713       if (VT.bitsGT(Op.getValueType()))
4714         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
4715       if (VT.bitsLT(Op.getValueType()))
4716         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4717
4718       return Op;
4719     }
4720   }
4721
4722   // fold (zext (truncate (load x))) -> (zext (smaller load x))
4723   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
4724   if (N0.getOpcode() == ISD::TRUNCATE) {
4725     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4726     if (NarrowLoad.getNode()) {
4727       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4728       if (NarrowLoad.getNode() != N0.getNode()) {
4729         CombineTo(N0.getNode(), NarrowLoad);
4730         // CombineTo deleted the truncate, if needed, but not what's under it.
4731         AddToWorkList(oye);
4732       }
4733       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4734     }
4735   }
4736
4737   // fold (zext (truncate x)) -> (and x, mask)
4738   if (N0.getOpcode() == ISD::TRUNCATE &&
4739       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
4740
4741     // fold (zext (truncate (load x))) -> (zext (smaller load x))
4742     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
4743     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4744     if (NarrowLoad.getNode()) {
4745       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4746       if (NarrowLoad.getNode() != N0.getNode()) {
4747         CombineTo(N0.getNode(), NarrowLoad);
4748         // CombineTo deleted the truncate, if needed, but not what's under it.
4749         AddToWorkList(oye);
4750       }
4751       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4752     }
4753
4754     SDValue Op = N0.getOperand(0);
4755     if (Op.getValueType().bitsLT(VT)) {
4756       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
4757       AddToWorkList(Op.getNode());
4758     } else if (Op.getValueType().bitsGT(VT)) {
4759       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4760       AddToWorkList(Op.getNode());
4761     }
4762     return DAG.getZeroExtendInReg(Op, SDLoc(N),
4763                                   N0.getValueType().getScalarType());
4764   }
4765
4766   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
4767   // if either of the casts is not free.
4768   if (N0.getOpcode() == ISD::AND &&
4769       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4770       N0.getOperand(1).getOpcode() == ISD::Constant &&
4771       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4772                            N0.getValueType()) ||
4773        !TLI.isZExtFree(N0.getValueType(), VT))) {
4774     SDValue X = N0.getOperand(0).getOperand(0);
4775     if (X.getValueType().bitsLT(VT)) {
4776       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
4777     } else if (X.getValueType().bitsGT(VT)) {
4778       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
4779     }
4780     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4781     Mask = Mask.zext(VT.getSizeInBits());
4782     return DAG.getNode(ISD::AND, SDLoc(N), VT,
4783                        X, DAG.getConstant(Mask, VT));
4784   }
4785
4786   // fold (zext (load x)) -> (zext (truncate (zextload x)))
4787   // None of the supported targets knows how to perform load and vector_zext
4788   // on vectors in one instruction.  We only perform this transformation on
4789   // scalars.
4790   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4791       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4792        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
4793     bool DoXform = true;
4794     SmallVector<SDNode*, 4> SetCCs;
4795     if (!N0.hasOneUse())
4796       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
4797     if (DoXform) {
4798       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4799       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
4800                                        LN0->getChain(),
4801                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4802                                        N0.getValueType(),
4803                                        LN0->isVolatile(), LN0->isNonTemporal(),
4804                                        LN0->getAlignment());
4805       CombineTo(N, ExtLoad);
4806       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4807                                   N0.getValueType(), ExtLoad);
4808       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4809
4810       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4811                       ISD::ZERO_EXTEND);
4812       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4813     }
4814   }
4815
4816   // fold (zext (and/or/xor (load x), cst)) ->
4817   //      (and/or/xor (zextload x), (zext cst))
4818   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4819        N0.getOpcode() == ISD::XOR) &&
4820       isa<LoadSDNode>(N0.getOperand(0)) &&
4821       N0.getOperand(1).getOpcode() == ISD::Constant &&
4822       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
4823       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4824     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4825     if (LN0->getExtensionType() != ISD::SEXTLOAD) {
4826       bool DoXform = true;
4827       SmallVector<SDNode*, 4> SetCCs;
4828       if (!N0.hasOneUse())
4829         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
4830                                           SetCCs, TLI);
4831       if (DoXform) {
4832         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
4833                                          LN0->getChain(), LN0->getBasePtr(),
4834                                          LN0->getPointerInfo(),
4835                                          LN0->getMemoryVT(),
4836                                          LN0->isVolatile(),
4837                                          LN0->isNonTemporal(),
4838                                          LN0->getAlignment());
4839         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4840         Mask = Mask.zext(VT.getSizeInBits());
4841         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4842                                   ExtLoad, DAG.getConstant(Mask, VT));
4843         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4844                                     SDLoc(N0.getOperand(0)),
4845                                     N0.getOperand(0).getValueType(), ExtLoad);
4846         CombineTo(N, And);
4847         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4848         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4849                         ISD::ZERO_EXTEND);
4850         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4851       }
4852     }
4853   }
4854
4855   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
4856   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
4857   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4858       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4859     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4860     EVT MemVT = LN0->getMemoryVT();
4861     if ((!LegalOperations && !LN0->isVolatile()) ||
4862         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
4863       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
4864                                        LN0->getChain(),
4865                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4866                                        MemVT,
4867                                        LN0->isVolatile(), LN0->isNonTemporal(),
4868                                        LN0->getAlignment());
4869       CombineTo(N, ExtLoad);
4870       CombineTo(N0.getNode(),
4871                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
4872                             ExtLoad),
4873                 ExtLoad.getValue(1));
4874       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4875     }
4876   }
4877
4878   if (N0.getOpcode() == ISD::SETCC) {
4879     if (!LegalOperations && VT.isVector()) {
4880       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
4881       // Only do this before legalize for now.
4882       EVT N0VT = N0.getOperand(0).getValueType();
4883       EVT EltVT = VT.getVectorElementType();
4884       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
4885                                     DAG.getConstant(1, EltVT));
4886       if (VT.getSizeInBits() == N0VT.getSizeInBits())
4887         // We know that the # elements of the results is the same as the
4888         // # elements of the compare (and the # elements of the compare result
4889         // for that matter).  Check to see that they are the same size.  If so,
4890         // we know that the element size of the sext'd result matches the
4891         // element size of the compare operands.
4892         return DAG.getNode(ISD::AND, SDLoc(N), VT,
4893                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4894                                          N0.getOperand(1),
4895                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4896                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
4897                                        &OneOps[0], OneOps.size()));
4898
4899       // If the desired elements are smaller or larger than the source
4900       // elements we can use a matching integer vector type and then
4901       // truncate/sign extend
4902       EVT MatchingElementType =
4903         EVT::getIntegerVT(*DAG.getContext(),
4904                           N0VT.getScalarType().getSizeInBits());
4905       EVT MatchingVectorType =
4906         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4907                          N0VT.getVectorNumElements());
4908       SDValue VsetCC =
4909         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
4910                       N0.getOperand(1),
4911                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
4912       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4913                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
4914                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
4915                                      &OneOps[0], OneOps.size()));
4916     }
4917
4918     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4919     SDValue SCC =
4920       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
4921                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4922                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4923     if (SCC.getNode()) return SCC;
4924   }
4925
4926   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
4927   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
4928       isa<ConstantSDNode>(N0.getOperand(1)) &&
4929       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
4930       N0.hasOneUse()) {
4931     SDValue ShAmt = N0.getOperand(1);
4932     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
4933     if (N0.getOpcode() == ISD::SHL) {
4934       SDValue InnerZExt = N0.getOperand(0);
4935       // If the original shl may be shifting out bits, do not perform this
4936       // transformation.
4937       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
4938         InnerZExt.getOperand(0).getValueType().getSizeInBits();
4939       if (ShAmtVal > KnownZeroBits)
4940         return SDValue();
4941     }
4942
4943     SDLoc DL(N);
4944
4945     // Ensure that the shift amount is wide enough for the shifted value.
4946     if (VT.getSizeInBits() >= 256)
4947       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
4948
4949     return DAG.getNode(N0.getOpcode(), DL, VT,
4950                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
4951                        ShAmt);
4952   }
4953
4954   return SDValue();
4955 }
4956
4957 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
4958   SDValue N0 = N->getOperand(0);
4959   EVT VT = N->getValueType(0);
4960
4961   // fold (aext c1) -> c1
4962   if (isa<ConstantSDNode>(N0))
4963     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, N0);
4964   // fold (aext (aext x)) -> (aext x)
4965   // fold (aext (zext x)) -> (zext x)
4966   // fold (aext (sext x)) -> (sext x)
4967   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
4968       N0.getOpcode() == ISD::ZERO_EXTEND ||
4969       N0.getOpcode() == ISD::SIGN_EXTEND)
4970     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
4971
4972   // fold (aext (truncate (load x))) -> (aext (smaller load x))
4973   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
4974   if (N0.getOpcode() == ISD::TRUNCATE) {
4975     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4976     if (NarrowLoad.getNode()) {
4977       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4978       if (NarrowLoad.getNode() != N0.getNode()) {
4979         CombineTo(N0.getNode(), NarrowLoad);
4980         // CombineTo deleted the truncate, if needed, but not what's under it.
4981         AddToWorkList(oye);
4982       }
4983       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4984     }
4985   }
4986
4987   // fold (aext (truncate x))
4988   if (N0.getOpcode() == ISD::TRUNCATE) {
4989     SDValue TruncOp = N0.getOperand(0);
4990     if (TruncOp.getValueType() == VT)
4991       return TruncOp; // x iff x size == zext size.
4992     if (TruncOp.getValueType().bitsGT(VT))
4993       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
4994     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
4995   }
4996
4997   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
4998   // if the trunc is not free.
4999   if (N0.getOpcode() == ISD::AND &&
5000       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5001       N0.getOperand(1).getOpcode() == ISD::Constant &&
5002       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5003                           N0.getValueType())) {
5004     SDValue X = N0.getOperand(0).getOperand(0);
5005     if (X.getValueType().bitsLT(VT)) {
5006       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5007     } else if (X.getValueType().bitsGT(VT)) {
5008       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5009     }
5010     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5011     Mask = Mask.zext(VT.getSizeInBits());
5012     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5013                        X, DAG.getConstant(Mask, VT));
5014   }
5015
5016   // fold (aext (load x)) -> (aext (truncate (extload x)))
5017   // None of the supported targets knows how to perform load and any_ext
5018   // on vectors in one instruction.  We only perform this transformation on
5019   // scalars.
5020   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5021       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5022        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5023     bool DoXform = true;
5024     SmallVector<SDNode*, 4> SetCCs;
5025     if (!N0.hasOneUse())
5026       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5027     if (DoXform) {
5028       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5029       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5030                                        LN0->getChain(),
5031                                        LN0->getBasePtr(), LN0->getPointerInfo(),
5032                                        N0.getValueType(),
5033                                        LN0->isVolatile(), LN0->isNonTemporal(),
5034                                        LN0->getAlignment());
5035       CombineTo(N, ExtLoad);
5036       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5037                                   N0.getValueType(), ExtLoad);
5038       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5039       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5040                       ISD::ANY_EXTEND);
5041       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5042     }
5043   }
5044
5045   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5046   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5047   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5048   if (N0.getOpcode() == ISD::LOAD &&
5049       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5050       N0.hasOneUse()) {
5051     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5052     EVT MemVT = LN0->getMemoryVT();
5053     SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N),
5054                                      VT, LN0->getChain(), LN0->getBasePtr(),
5055                                      LN0->getPointerInfo(), MemVT,
5056                                      LN0->isVolatile(), LN0->isNonTemporal(),
5057                                      LN0->getAlignment());
5058     CombineTo(N, ExtLoad);
5059     CombineTo(N0.getNode(),
5060               DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5061                           N0.getValueType(), ExtLoad),
5062               ExtLoad.getValue(1));
5063     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5064   }
5065
5066   if (N0.getOpcode() == ISD::SETCC) {
5067     // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5068     // Only do this before legalize for now.
5069     if (VT.isVector() && !LegalOperations) {
5070       EVT N0VT = N0.getOperand(0).getValueType();
5071         // We know that the # elements of the results is the same as the
5072         // # elements of the compare (and the # elements of the compare result
5073         // for that matter).  Check to see that they are the same size.  If so,
5074         // we know that the element size of the sext'd result matches the
5075         // element size of the compare operands.
5076       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5077         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5078                              N0.getOperand(1),
5079                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5080       // If the desired elements are smaller or larger than the source
5081       // elements we can use a matching integer vector type and then
5082       // truncate/sign extend
5083       else {
5084         EVT MatchingElementType =
5085           EVT::getIntegerVT(*DAG.getContext(),
5086                             N0VT.getScalarType().getSizeInBits());
5087         EVT MatchingVectorType =
5088           EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5089                            N0VT.getVectorNumElements());
5090         SDValue VsetCC =
5091           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5092                         N0.getOperand(1),
5093                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5094         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5095       }
5096     }
5097
5098     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5099     SDValue SCC =
5100       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5101                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5102                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5103     if (SCC.getNode())
5104       return SCC;
5105   }
5106
5107   return SDValue();
5108 }
5109
5110 /// GetDemandedBits - See if the specified operand can be simplified with the
5111 /// knowledge that only the bits specified by Mask are used.  If so, return the
5112 /// simpler operand, otherwise return a null SDValue.
5113 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5114   switch (V.getOpcode()) {
5115   default: break;
5116   case ISD::Constant: {
5117     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5118     assert(CV != 0 && "Const value should be ConstSDNode.");
5119     const APInt &CVal = CV->getAPIntValue();
5120     APInt NewVal = CVal & Mask;
5121     if (NewVal != CVal)
5122       return DAG.getConstant(NewVal, V.getValueType());
5123     break;
5124   }
5125   case ISD::OR:
5126   case ISD::XOR:
5127     // If the LHS or RHS don't contribute bits to the or, drop them.
5128     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5129       return V.getOperand(1);
5130     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5131       return V.getOperand(0);
5132     break;
5133   case ISD::SRL:
5134     // Only look at single-use SRLs.
5135     if (!V.getNode()->hasOneUse())
5136       break;
5137     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5138       // See if we can recursively simplify the LHS.
5139       unsigned Amt = RHSC->getZExtValue();
5140
5141       // Watch out for shift count overflow though.
5142       if (Amt >= Mask.getBitWidth()) break;
5143       APInt NewMask = Mask << Amt;
5144       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5145       if (SimplifyLHS.getNode())
5146         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5147                            SimplifyLHS, V.getOperand(1));
5148     }
5149   }
5150   return SDValue();
5151 }
5152
5153 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5154 /// bits and then truncated to a narrower type and where N is a multiple
5155 /// of number of bits of the narrower type, transform it to a narrower load
5156 /// from address + N / num of bits of new type. If the result is to be
5157 /// extended, also fold the extension to form a extending load.
5158 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5159   unsigned Opc = N->getOpcode();
5160
5161   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5162   SDValue N0 = N->getOperand(0);
5163   EVT VT = N->getValueType(0);
5164   EVT ExtVT = VT;
5165
5166   // This transformation isn't valid for vector loads.
5167   if (VT.isVector())
5168     return SDValue();
5169
5170   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5171   // extended to VT.
5172   if (Opc == ISD::SIGN_EXTEND_INREG) {
5173     ExtType = ISD::SEXTLOAD;
5174     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5175   } else if (Opc == ISD::SRL) {
5176     // Another special-case: SRL is basically zero-extending a narrower value.
5177     ExtType = ISD::ZEXTLOAD;
5178     N0 = SDValue(N, 0);
5179     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5180     if (!N01) return SDValue();
5181     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5182                               VT.getSizeInBits() - N01->getZExtValue());
5183   }
5184   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5185     return SDValue();
5186
5187   unsigned EVTBits = ExtVT.getSizeInBits();
5188
5189   // Do not generate loads of non-round integer types since these can
5190   // be expensive (and would be wrong if the type is not byte sized).
5191   if (!ExtVT.isRound())
5192     return SDValue();
5193
5194   unsigned ShAmt = 0;
5195   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5196     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5197       ShAmt = N01->getZExtValue();
5198       // Is the shift amount a multiple of size of VT?
5199       if ((ShAmt & (EVTBits-1)) == 0) {
5200         N0 = N0.getOperand(0);
5201         // Is the load width a multiple of size of VT?
5202         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5203           return SDValue();
5204       }
5205
5206       // At this point, we must have a load or else we can't do the transform.
5207       if (!isa<LoadSDNode>(N0)) return SDValue();
5208
5209       // Because a SRL must be assumed to *need* to zero-extend the high bits
5210       // (as opposed to anyext the high bits), we can't combine the zextload
5211       // lowering of SRL and an sextload.
5212       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5213         return SDValue();
5214
5215       // If the shift amount is larger than the input type then we're not
5216       // accessing any of the loaded bytes.  If the load was a zextload/extload
5217       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5218       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5219         return SDValue();
5220     }
5221   }
5222
5223   // If the load is shifted left (and the result isn't shifted back right),
5224   // we can fold the truncate through the shift.
5225   unsigned ShLeftAmt = 0;
5226   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5227       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5228     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5229       ShLeftAmt = N01->getZExtValue();
5230       N0 = N0.getOperand(0);
5231     }
5232   }
5233
5234   // If we haven't found a load, we can't narrow it.  Don't transform one with
5235   // multiple uses, this would require adding a new load.
5236   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5237     return SDValue();
5238
5239   // Don't change the width of a volatile load.
5240   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5241   if (LN0->isVolatile())
5242     return SDValue();
5243
5244   // Verify that we are actually reducing a load width here.
5245   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5246     return SDValue();
5247
5248   // For the transform to be legal, the load must produce only two values
5249   // (the value loaded and the chain).  Don't transform a pre-increment
5250   // load, for example, which produces an extra value.  Otherwise the
5251   // transformation is not equivalent, and the downstream logic to replace
5252   // uses gets things wrong.
5253   if (LN0->getNumValues() > 2)
5254     return SDValue();
5255
5256   // If the load that we're shrinking is an extload and we're not just
5257   // discarding the extension we can't simply shrink the load. Bail.
5258   // TODO: It would be possible to merge the extensions in some cases.
5259   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5260       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5261     return SDValue();
5262
5263   EVT PtrType = N0.getOperand(1).getValueType();
5264
5265   if (PtrType == MVT::Untyped || PtrType.isExtended())
5266     // It's not possible to generate a constant of extended or untyped type.
5267     return SDValue();
5268
5269   // For big endian targets, we need to adjust the offset to the pointer to
5270   // load the correct bytes.
5271   if (TLI.isBigEndian()) {
5272     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5273     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5274     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5275   }
5276
5277   uint64_t PtrOff = ShAmt / 8;
5278   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5279   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5280                                PtrType, LN0->getBasePtr(),
5281                                DAG.getConstant(PtrOff, PtrType));
5282   AddToWorkList(NewPtr.getNode());
5283
5284   SDValue Load;
5285   if (ExtType == ISD::NON_EXTLOAD)
5286     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5287                         LN0->getPointerInfo().getWithOffset(PtrOff),
5288                         LN0->isVolatile(), LN0->isNonTemporal(),
5289                         LN0->isInvariant(), NewAlign);
5290   else
5291     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5292                           LN0->getPointerInfo().getWithOffset(PtrOff),
5293                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5294                           NewAlign);
5295
5296   // Replace the old load's chain with the new load's chain.
5297   WorkListRemover DeadNodes(*this);
5298   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5299
5300   // Shift the result left, if we've swallowed a left shift.
5301   SDValue Result = Load;
5302   if (ShLeftAmt != 0) {
5303     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5304     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5305       ShImmTy = VT;
5306     // If the shift amount is as large as the result size (but, presumably,
5307     // no larger than the source) then the useful bits of the result are
5308     // zero; we can't simply return the shortened shift, because the result
5309     // of that operation is undefined.
5310     if (ShLeftAmt >= VT.getSizeInBits())
5311       Result = DAG.getConstant(0, VT);
5312     else
5313       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5314                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5315   }
5316
5317   // Return the new loaded value.
5318   return Result;
5319 }
5320
5321 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5322   SDValue N0 = N->getOperand(0);
5323   SDValue N1 = N->getOperand(1);
5324   EVT VT = N->getValueType(0);
5325   EVT EVT = cast<VTSDNode>(N1)->getVT();
5326   unsigned VTBits = VT.getScalarType().getSizeInBits();
5327   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5328
5329   // fold (sext_in_reg c1) -> c1
5330   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5331     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5332
5333   // If the input is already sign extended, just drop the extension.
5334   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5335     return N0;
5336
5337   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5338   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5339       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5340     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5341                        N0.getOperand(0), N1);
5342
5343   // fold (sext_in_reg (sext x)) -> (sext x)
5344   // fold (sext_in_reg (aext x)) -> (sext x)
5345   // if x is small enough.
5346   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5347     SDValue N00 = N0.getOperand(0);
5348     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5349         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5350       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5351   }
5352
5353   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5354   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5355     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5356
5357   // fold operands of sext_in_reg based on knowledge that the top bits are not
5358   // demanded.
5359   if (SimplifyDemandedBits(SDValue(N, 0)))
5360     return SDValue(N, 0);
5361
5362   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5363   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5364   SDValue NarrowLoad = ReduceLoadWidth(N);
5365   if (NarrowLoad.getNode())
5366     return NarrowLoad;
5367
5368   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5369   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5370   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5371   if (N0.getOpcode() == ISD::SRL) {
5372     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5373       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5374         // We can turn this into an SRA iff the input to the SRL is already sign
5375         // extended enough.
5376         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5377         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5378           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5379                              N0.getOperand(0), N0.getOperand(1));
5380       }
5381   }
5382
5383   // fold (sext_inreg (extload x)) -> (sextload x)
5384   if (ISD::isEXTLoad(N0.getNode()) &&
5385       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5386       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5387       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5388        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5389     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5390     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5391                                      LN0->getChain(),
5392                                      LN0->getBasePtr(), LN0->getPointerInfo(),
5393                                      EVT,
5394                                      LN0->isVolatile(), LN0->isNonTemporal(),
5395                                      LN0->getAlignment());
5396     CombineTo(N, ExtLoad);
5397     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5398     AddToWorkList(ExtLoad.getNode());
5399     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5400   }
5401   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5402   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5403       N0.hasOneUse() &&
5404       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5405       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5406        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5407     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5408     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5409                                      LN0->getChain(),
5410                                      LN0->getBasePtr(), LN0->getPointerInfo(),
5411                                      EVT,
5412                                      LN0->isVolatile(), LN0->isNonTemporal(),
5413                                      LN0->getAlignment());
5414     CombineTo(N, ExtLoad);
5415     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5416     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5417   }
5418
5419   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5420   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5421     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5422                                        N0.getOperand(1), false);
5423     if (BSwap.getNode() != 0)
5424       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5425                          BSwap, N1);
5426   }
5427
5428   return SDValue();
5429 }
5430
5431 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5432   SDValue N0 = N->getOperand(0);
5433   EVT VT = N->getValueType(0);
5434   bool isLE = TLI.isLittleEndian();
5435
5436   // noop truncate
5437   if (N0.getValueType() == N->getValueType(0))
5438     return N0;
5439   // fold (truncate c1) -> c1
5440   if (isa<ConstantSDNode>(N0))
5441     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5442   // fold (truncate (truncate x)) -> (truncate x)
5443   if (N0.getOpcode() == ISD::TRUNCATE)
5444     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5445   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5446   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5447       N0.getOpcode() == ISD::SIGN_EXTEND ||
5448       N0.getOpcode() == ISD::ANY_EXTEND) {
5449     if (N0.getOperand(0).getValueType().bitsLT(VT))
5450       // if the source is smaller than the dest, we still need an extend
5451       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5452                          N0.getOperand(0));
5453     if (N0.getOperand(0).getValueType().bitsGT(VT))
5454       // if the source is larger than the dest, than we just need the truncate
5455       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5456     // if the source and dest are the same type, we can drop both the extend
5457     // and the truncate.
5458     return N0.getOperand(0);
5459   }
5460
5461   // Fold extract-and-trunc into a narrow extract. For example:
5462   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5463   //   i32 y = TRUNCATE(i64 x)
5464   //        -- becomes --
5465   //   v16i8 b = BITCAST (v2i64 val)
5466   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5467   //
5468   // Note: We only run this optimization after type legalization (which often
5469   // creates this pattern) and before operation legalization after which
5470   // we need to be more careful about the vector instructions that we generate.
5471   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5472       LegalTypes && !LegalOperations && N0->hasOneUse()) {
5473
5474     EVT VecTy = N0.getOperand(0).getValueType();
5475     EVT ExTy = N0.getValueType();
5476     EVT TrTy = N->getValueType(0);
5477
5478     unsigned NumElem = VecTy.getVectorNumElements();
5479     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5480
5481     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5482     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5483
5484     SDValue EltNo = N0->getOperand(1);
5485     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5486       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5487       EVT IndexTy = TLI.getVectorIdxTy();
5488       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5489
5490       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5491                               NVT, N0.getOperand(0));
5492
5493       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5494                          SDLoc(N), TrTy, V,
5495                          DAG.getConstant(Index, IndexTy));
5496     }
5497   }
5498
5499   // Fold a series of buildvector, bitcast, and truncate if possible.
5500   // For example fold
5501   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5502   //   (2xi32 (buildvector x, y)).
5503   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5504       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5505       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5506       N0.getOperand(0).hasOneUse()) {
5507
5508     SDValue BuildVect = N0.getOperand(0);
5509     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5510     EVT TruncVecEltTy = VT.getVectorElementType();
5511
5512     // Check that the element types match.
5513     if (BuildVectEltTy == TruncVecEltTy) {
5514       // Now we only need to compute the offset of the truncated elements.
5515       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
5516       unsigned TruncVecNumElts = VT.getVectorNumElements();
5517       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5518
5519       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5520              "Invalid number of elements");
5521
5522       SmallVector<SDValue, 8> Opnds;
5523       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5524         Opnds.push_back(BuildVect.getOperand(i));
5525
5526       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
5527                          Opnds.size());
5528     }
5529   }
5530
5531   // See if we can simplify the input to this truncate through knowledge that
5532   // only the low bits are being used.
5533   // For example "trunc (or (shl x, 8), y)" // -> trunc y
5534   // Currently we only perform this optimization on scalars because vectors
5535   // may have different active low bits.
5536   if (!VT.isVector()) {
5537     SDValue Shorter =
5538       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5539                                                VT.getSizeInBits()));
5540     if (Shorter.getNode())
5541       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
5542   }
5543   // fold (truncate (load x)) -> (smaller load x)
5544   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5545   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5546     SDValue Reduced = ReduceLoadWidth(N);
5547     if (Reduced.getNode())
5548       return Reduced;
5549   }
5550   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
5551   // where ... are all 'undef'.
5552   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
5553     SmallVector<EVT, 8> VTs;
5554     SDValue V;
5555     unsigned Idx = 0;
5556     unsigned NumDefs = 0;
5557
5558     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
5559       SDValue X = N0.getOperand(i);
5560       if (X.getOpcode() != ISD::UNDEF) {
5561         V = X;
5562         Idx = i;
5563         NumDefs++;
5564       }
5565       // Stop if more than one members are non-undef.
5566       if (NumDefs > 1)
5567         break;
5568       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
5569                                      VT.getVectorElementType(),
5570                                      X.getValueType().getVectorNumElements()));
5571     }
5572
5573     if (NumDefs == 0)
5574       return DAG.getUNDEF(VT);
5575
5576     if (NumDefs == 1) {
5577       assert(V.getNode() && "The single defined operand is empty!");
5578       SmallVector<SDValue, 8> Opnds;
5579       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
5580         if (i != Idx) {
5581           Opnds.push_back(DAG.getUNDEF(VTs[i]));
5582           continue;
5583         }
5584         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
5585         AddToWorkList(NV.getNode());
5586         Opnds.push_back(NV);
5587       }
5588       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
5589                          &Opnds[0], Opnds.size());
5590     }
5591   }
5592
5593   // Simplify the operands using demanded-bits information.
5594   if (!VT.isVector() &&
5595       SimplifyDemandedBits(SDValue(N, 0)))
5596     return SDValue(N, 0);
5597
5598   return SDValue();
5599 }
5600
5601 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
5602   SDValue Elt = N->getOperand(i);
5603   if (Elt.getOpcode() != ISD::MERGE_VALUES)
5604     return Elt.getNode();
5605   return Elt.getOperand(Elt.getResNo()).getNode();
5606 }
5607
5608 /// CombineConsecutiveLoads - build_pair (load, load) -> load
5609 /// if load locations are consecutive.
5610 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
5611   assert(N->getOpcode() == ISD::BUILD_PAIR);
5612
5613   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
5614   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
5615   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
5616       LD1->getPointerInfo().getAddrSpace() !=
5617          LD2->getPointerInfo().getAddrSpace())
5618     return SDValue();
5619   EVT LD1VT = LD1->getValueType(0);
5620
5621   if (ISD::isNON_EXTLoad(LD2) &&
5622       LD2->hasOneUse() &&
5623       // If both are volatile this would reduce the number of volatile loads.
5624       // If one is volatile it might be ok, but play conservative and bail out.
5625       !LD1->isVolatile() &&
5626       !LD2->isVolatile() &&
5627       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
5628     unsigned Align = LD1->getAlignment();
5629     unsigned NewAlign = TLI.getDataLayout()->
5630       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5631
5632     if (NewAlign <= Align &&
5633         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
5634       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
5635                          LD1->getBasePtr(), LD1->getPointerInfo(),
5636                          false, false, false, Align);
5637   }
5638
5639   return SDValue();
5640 }
5641
5642 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
5643   SDValue N0 = N->getOperand(0);
5644   EVT VT = N->getValueType(0);
5645
5646   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
5647   // Only do this before legalize, since afterward the target may be depending
5648   // on the bitconvert.
5649   // First check to see if this is all constant.
5650   if (!LegalTypes &&
5651       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
5652       VT.isVector()) {
5653     bool isSimple = true;
5654     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
5655       if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
5656           N0.getOperand(i).getOpcode() != ISD::Constant &&
5657           N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
5658         isSimple = false;
5659         break;
5660       }
5661
5662     EVT DestEltVT = N->getValueType(0).getVectorElementType();
5663     assert(!DestEltVT.isVector() &&
5664            "Element type of vector ValueType must not be vector!");
5665     if (isSimple)
5666       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
5667   }
5668
5669   // If the input is a constant, let getNode fold it.
5670   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
5671     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
5672     if (Res.getNode() != N) {
5673       if (!LegalOperations ||
5674           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
5675         return Res;
5676
5677       // Folding it resulted in an illegal node, and it's too late to
5678       // do that. Clean up the old node and forego the transformation.
5679       // Ideally this won't happen very often, because instcombine
5680       // and the earlier dagcombine runs (where illegal nodes are
5681       // permitted) should have folded most of them already.
5682       DAG.DeleteNode(Res.getNode());
5683     }
5684   }
5685
5686   // (conv (conv x, t1), t2) -> (conv x, t2)
5687   if (N0.getOpcode() == ISD::BITCAST)
5688     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
5689                        N0.getOperand(0));
5690
5691   // fold (conv (load x)) -> (load (conv*)x)
5692   // If the resultant load doesn't need a higher alignment than the original!
5693   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
5694       // Do not change the width of a volatile load.
5695       !cast<LoadSDNode>(N0)->isVolatile() &&
5696       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
5697     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5698     unsigned Align = TLI.getDataLayout()->
5699       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5700     unsigned OrigAlign = LN0->getAlignment();
5701
5702     if (Align <= OrigAlign) {
5703       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
5704                                  LN0->getBasePtr(), LN0->getPointerInfo(),
5705                                  LN0->isVolatile(), LN0->isNonTemporal(),
5706                                  LN0->isInvariant(), OrigAlign);
5707       AddToWorkList(N);
5708       CombineTo(N0.getNode(),
5709                 DAG.getNode(ISD::BITCAST, SDLoc(N0),
5710                             N0.getValueType(), Load),
5711                 Load.getValue(1));
5712       return Load;
5713     }
5714   }
5715
5716   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
5717   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
5718   // This often reduces constant pool loads.
5719   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
5720        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
5721       N0.getNode()->hasOneUse() && VT.isInteger() &&
5722       !VT.isVector() && !N0.getValueType().isVector()) {
5723     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
5724                                   N0.getOperand(0));
5725     AddToWorkList(NewConv.getNode());
5726
5727     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5728     if (N0.getOpcode() == ISD::FNEG)
5729       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
5730                          NewConv, DAG.getConstant(SignBit, VT));
5731     assert(N0.getOpcode() == ISD::FABS);
5732     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5733                        NewConv, DAG.getConstant(~SignBit, VT));
5734   }
5735
5736   // fold (bitconvert (fcopysign cst, x)) ->
5737   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
5738   // Note that we don't handle (copysign x, cst) because this can always be
5739   // folded to an fneg or fabs.
5740   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
5741       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
5742       VT.isInteger() && !VT.isVector()) {
5743     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
5744     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
5745     if (isTypeLegal(IntXVT)) {
5746       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5747                               IntXVT, N0.getOperand(1));
5748       AddToWorkList(X.getNode());
5749
5750       // If X has a different width than the result/lhs, sext it or truncate it.
5751       unsigned VTWidth = VT.getSizeInBits();
5752       if (OrigXWidth < VTWidth) {
5753         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
5754         AddToWorkList(X.getNode());
5755       } else if (OrigXWidth > VTWidth) {
5756         // To get the sign bit in the right place, we have to shift it right
5757         // before truncating.
5758         X = DAG.getNode(ISD::SRL, SDLoc(X),
5759                         X.getValueType(), X,
5760                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
5761         AddToWorkList(X.getNode());
5762         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5763         AddToWorkList(X.getNode());
5764       }
5765
5766       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5767       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
5768                       X, DAG.getConstant(SignBit, VT));
5769       AddToWorkList(X.getNode());
5770
5771       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5772                                 VT, N0.getOperand(0));
5773       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
5774                         Cst, DAG.getConstant(~SignBit, VT));
5775       AddToWorkList(Cst.getNode());
5776
5777       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
5778     }
5779   }
5780
5781   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
5782   if (N0.getOpcode() == ISD::BUILD_PAIR) {
5783     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
5784     if (CombineLD.getNode())
5785       return CombineLD;
5786   }
5787
5788   return SDValue();
5789 }
5790
5791 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
5792   EVT VT = N->getValueType(0);
5793   return CombineConsecutiveLoads(N, VT);
5794 }
5795
5796 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
5797 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
5798 /// destination element value type.
5799 SDValue DAGCombiner::
5800 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
5801   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
5802
5803   // If this is already the right type, we're done.
5804   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
5805
5806   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
5807   unsigned DstBitSize = DstEltVT.getSizeInBits();
5808
5809   // If this is a conversion of N elements of one type to N elements of another
5810   // type, convert each element.  This handles FP<->INT cases.
5811   if (SrcBitSize == DstBitSize) {
5812     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5813                               BV->getValueType(0).getVectorNumElements());
5814
5815     // Due to the FP element handling below calling this routine recursively,
5816     // we can end up with a scalar-to-vector node here.
5817     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
5818       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
5819                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
5820                                      DstEltVT, BV->getOperand(0)));
5821
5822     SmallVector<SDValue, 8> Ops;
5823     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5824       SDValue Op = BV->getOperand(i);
5825       // If the vector element type is not legal, the BUILD_VECTOR operands
5826       // are promoted and implicitly truncated.  Make that explicit here.
5827       if (Op.getValueType() != SrcEltVT)
5828         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
5829       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
5830                                 DstEltVT, Op));
5831       AddToWorkList(Ops.back().getNode());
5832     }
5833     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5834                        &Ops[0], Ops.size());
5835   }
5836
5837   // Otherwise, we're growing or shrinking the elements.  To avoid having to
5838   // handle annoying details of growing/shrinking FP values, we convert them to
5839   // int first.
5840   if (SrcEltVT.isFloatingPoint()) {
5841     // Convert the input float vector to a int vector where the elements are the
5842     // same sizes.
5843     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
5844     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
5845     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
5846     SrcEltVT = IntVT;
5847   }
5848
5849   // Now we know the input is an integer vector.  If the output is a FP type,
5850   // convert to integer first, then to FP of the right size.
5851   if (DstEltVT.isFloatingPoint()) {
5852     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
5853     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
5854     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
5855
5856     // Next, convert to FP elements of the same size.
5857     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
5858   }
5859
5860   // Okay, we know the src/dst types are both integers of differing types.
5861   // Handling growing first.
5862   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
5863   if (SrcBitSize < DstBitSize) {
5864     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
5865
5866     SmallVector<SDValue, 8> Ops;
5867     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
5868          i += NumInputsPerOutput) {
5869       bool isLE = TLI.isLittleEndian();
5870       APInt NewBits = APInt(DstBitSize, 0);
5871       bool EltIsUndef = true;
5872       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
5873         // Shift the previously computed bits over.
5874         NewBits <<= SrcBitSize;
5875         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
5876         if (Op.getOpcode() == ISD::UNDEF) continue;
5877         EltIsUndef = false;
5878
5879         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
5880                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
5881       }
5882
5883       if (EltIsUndef)
5884         Ops.push_back(DAG.getUNDEF(DstEltVT));
5885       else
5886         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
5887     }
5888
5889     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
5890     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5891                        &Ops[0], Ops.size());
5892   }
5893
5894   // Finally, this must be the case where we are shrinking elements: each input
5895   // turns into multiple outputs.
5896   bool isS2V = ISD::isScalarToVector(BV);
5897   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
5898   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5899                             NumOutputsPerInput*BV->getNumOperands());
5900   SmallVector<SDValue, 8> Ops;
5901
5902   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5903     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
5904       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
5905         Ops.push_back(DAG.getUNDEF(DstEltVT));
5906       continue;
5907     }
5908
5909     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
5910                   getAPIntValue().zextOrTrunc(SrcBitSize);
5911
5912     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
5913       APInt ThisVal = OpVal.trunc(DstBitSize);
5914       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
5915       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
5916         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
5917         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
5918                            Ops[0]);
5919       OpVal = OpVal.lshr(DstBitSize);
5920     }
5921
5922     // For big endian targets, swap the order of the pieces of each element.
5923     if (TLI.isBigEndian())
5924       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
5925   }
5926
5927   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5928                      &Ops[0], Ops.size());
5929 }
5930
5931 SDValue DAGCombiner::visitFADD(SDNode *N) {
5932   SDValue N0 = N->getOperand(0);
5933   SDValue N1 = N->getOperand(1);
5934   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5935   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5936   EVT VT = N->getValueType(0);
5937
5938   // fold vector ops
5939   if (VT.isVector()) {
5940     SDValue FoldedVOp = SimplifyVBinOp(N);
5941     if (FoldedVOp.getNode()) return FoldedVOp;
5942   }
5943
5944   // fold (fadd c1, c2) -> c1 + c2
5945   if (N0CFP && N1CFP)
5946     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
5947   // canonicalize constant to RHS
5948   if (N0CFP && !N1CFP)
5949     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
5950   // fold (fadd A, 0) -> A
5951   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
5952       N1CFP->getValueAPF().isZero())
5953     return N0;
5954   // fold (fadd A, (fneg B)) -> (fsub A, B)
5955   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
5956     isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
5957     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
5958                        GetNegatedExpression(N1, DAG, LegalOperations));
5959   // fold (fadd (fneg A), B) -> (fsub B, A)
5960   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
5961     isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
5962     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
5963                        GetNegatedExpression(N0, DAG, LegalOperations));
5964
5965   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
5966   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
5967       N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
5968       isa<ConstantFPSDNode>(N0.getOperand(1)))
5969     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
5970                        DAG.getNode(ISD::FADD, SDLoc(N), VT,
5971                                    N0.getOperand(1), N1));
5972
5973   // No FP constant should be created after legalization as Instruction
5974   // Selection pass has hard time in dealing with FP constant.
5975   //
5976   // We don't need test this condition for transformation like following, as
5977   // the DAG being transformed implies it is legal to take FP constant as
5978   // operand.
5979   //
5980   //  (fadd (fmul c, x), x) -> (fmul c+1, x)
5981   //
5982   bool AllowNewFpConst = (Level < AfterLegalizeDAG);
5983
5984   // If allow, fold (fadd (fneg x), x) -> 0.0
5985   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
5986       N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
5987     return DAG.getConstantFP(0.0, VT);
5988
5989     // If allow, fold (fadd x, (fneg x)) -> 0.0
5990   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
5991       N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
5992     return DAG.getConstantFP(0.0, VT);
5993
5994   // In unsafe math mode, we can fold chains of FADD's of the same value
5995   // into multiplications.  This transform is not safe in general because
5996   // we are reducing the number of rounding steps.
5997   if (DAG.getTarget().Options.UnsafeFPMath &&
5998       TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
5999       !N0CFP && !N1CFP) {
6000     if (N0.getOpcode() == ISD::FMUL) {
6001       ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6002       ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6003
6004       // (fadd (fmul c, x), x) -> (fmul x, c+1)
6005       if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6006         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6007                                      SDValue(CFP00, 0),
6008                                      DAG.getConstantFP(1.0, VT));
6009         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6010                            N1, NewCFP);
6011       }
6012
6013       // (fadd (fmul x, c), x) -> (fmul x, c+1)
6014       if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6015         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6016                                      SDValue(CFP01, 0),
6017                                      DAG.getConstantFP(1.0, VT));
6018         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6019                            N1, NewCFP);
6020       }
6021
6022       // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6023       if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6024           N1.getOperand(0) == N1.getOperand(1) &&
6025           N0.getOperand(1) == N1.getOperand(0)) {
6026         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6027                                      SDValue(CFP00, 0),
6028                                      DAG.getConstantFP(2.0, VT));
6029         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6030                            N0.getOperand(1), NewCFP);
6031       }
6032
6033       // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6034       if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6035           N1.getOperand(0) == N1.getOperand(1) &&
6036           N0.getOperand(0) == N1.getOperand(0)) {
6037         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6038                                      SDValue(CFP01, 0),
6039                                      DAG.getConstantFP(2.0, VT));
6040         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6041                            N0.getOperand(0), NewCFP);
6042       }
6043     }
6044
6045     if (N1.getOpcode() == ISD::FMUL) {
6046       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6047       ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6048
6049       // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6050       if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6051         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6052                                      SDValue(CFP10, 0),
6053                                      DAG.getConstantFP(1.0, VT));
6054         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6055                            N0, NewCFP);
6056       }
6057
6058       // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6059       if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6060         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6061                                      SDValue(CFP11, 0),
6062                                      DAG.getConstantFP(1.0, VT));
6063         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6064                            N0, NewCFP);
6065       }
6066
6067
6068       // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6069       if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6070           N0.getOperand(0) == N0.getOperand(1) &&
6071           N1.getOperand(1) == N0.getOperand(0)) {
6072         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6073                                      SDValue(CFP10, 0),
6074                                      DAG.getConstantFP(2.0, VT));
6075         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6076                            N1.getOperand(1), NewCFP);
6077       }
6078
6079       // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6080       if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6081           N0.getOperand(0) == N0.getOperand(1) &&
6082           N1.getOperand(0) == N0.getOperand(0)) {
6083         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6084                                      SDValue(CFP11, 0),
6085                                      DAG.getConstantFP(2.0, VT));
6086         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6087                            N1.getOperand(0), NewCFP);
6088       }
6089     }
6090
6091     if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6092       ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6093       // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6094       if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6095           (N0.getOperand(0) == N1))
6096         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6097                            N1, DAG.getConstantFP(3.0, VT));
6098     }
6099
6100     if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6101       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6102       // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6103       if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6104           N1.getOperand(0) == N0)
6105         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6106                            N0, DAG.getConstantFP(3.0, VT));
6107     }
6108
6109     // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6110     if (AllowNewFpConst &&
6111         N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6112         N0.getOperand(0) == N0.getOperand(1) &&
6113         N1.getOperand(0) == N1.getOperand(1) &&
6114         N0.getOperand(0) == N1.getOperand(0))
6115       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6116                          N0.getOperand(0),
6117                          DAG.getConstantFP(4.0, VT));
6118   }
6119
6120   // FADD -> FMA combines:
6121   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6122        DAG.getTarget().Options.UnsafeFPMath) &&
6123       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6124       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6125
6126     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6127     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6128       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6129                          N0.getOperand(0), N0.getOperand(1), N1);
6130
6131     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6132     // Note: Commutes FADD operands.
6133     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6134       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6135                          N1.getOperand(0), N1.getOperand(1), N0);
6136   }
6137
6138   return SDValue();
6139 }
6140
6141 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6142   SDValue N0 = N->getOperand(0);
6143   SDValue N1 = N->getOperand(1);
6144   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6145   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6146   EVT VT = N->getValueType(0);
6147   SDLoc dl(N);
6148
6149   // fold vector ops
6150   if (VT.isVector()) {
6151     SDValue FoldedVOp = SimplifyVBinOp(N);
6152     if (FoldedVOp.getNode()) return FoldedVOp;
6153   }
6154
6155   // fold (fsub c1, c2) -> c1-c2
6156   if (N0CFP && N1CFP)
6157     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6158   // fold (fsub A, 0) -> A
6159   if (DAG.getTarget().Options.UnsafeFPMath &&
6160       N1CFP && N1CFP->getValueAPF().isZero())
6161     return N0;
6162   // fold (fsub 0, B) -> -B
6163   if (DAG.getTarget().Options.UnsafeFPMath &&
6164       N0CFP && N0CFP->getValueAPF().isZero()) {
6165     if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6166       return GetNegatedExpression(N1, DAG, LegalOperations);
6167     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6168       return DAG.getNode(ISD::FNEG, dl, VT, N1);
6169   }
6170   // fold (fsub A, (fneg B)) -> (fadd A, B)
6171   if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6172     return DAG.getNode(ISD::FADD, dl, VT, N0,
6173                        GetNegatedExpression(N1, DAG, LegalOperations));
6174
6175   // If 'unsafe math' is enabled, fold
6176   //    (fsub x, x) -> 0.0 &
6177   //    (fsub x, (fadd x, y)) -> (fneg y) &
6178   //    (fsub x, (fadd y, x)) -> (fneg y)
6179   if (DAG.getTarget().Options.UnsafeFPMath) {
6180     if (N0 == N1)
6181       return DAG.getConstantFP(0.0f, VT);
6182
6183     if (N1.getOpcode() == ISD::FADD) {
6184       SDValue N10 = N1->getOperand(0);
6185       SDValue N11 = N1->getOperand(1);
6186
6187       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6188                                           &DAG.getTarget().Options))
6189         return GetNegatedExpression(N11, DAG, LegalOperations);
6190
6191       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6192                                           &DAG.getTarget().Options))
6193         return GetNegatedExpression(N10, DAG, LegalOperations);
6194     }
6195   }
6196
6197   // FSUB -> FMA combines:
6198   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6199        DAG.getTarget().Options.UnsafeFPMath) &&
6200       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6201       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6202
6203     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6204     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6205       return DAG.getNode(ISD::FMA, dl, VT,
6206                          N0.getOperand(0), N0.getOperand(1),
6207                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6208
6209     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6210     // Note: Commutes FSUB operands.
6211     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6212       return DAG.getNode(ISD::FMA, dl, VT,
6213                          DAG.getNode(ISD::FNEG, dl, VT,
6214                          N1.getOperand(0)),
6215                          N1.getOperand(1), N0);
6216
6217     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6218     if (N0.getOpcode() == ISD::FNEG &&
6219         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6220         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6221       SDValue N00 = N0.getOperand(0).getOperand(0);
6222       SDValue N01 = N0.getOperand(0).getOperand(1);
6223       return DAG.getNode(ISD::FMA, dl, VT,
6224                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6225                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6226     }
6227   }
6228
6229   return SDValue();
6230 }
6231
6232 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6233   SDValue N0 = N->getOperand(0);
6234   SDValue N1 = N->getOperand(1);
6235   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6236   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6237   EVT VT = N->getValueType(0);
6238   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6239
6240   // fold vector ops
6241   if (VT.isVector()) {
6242     SDValue FoldedVOp = SimplifyVBinOp(N);
6243     if (FoldedVOp.getNode()) return FoldedVOp;
6244   }
6245
6246   // fold (fmul c1, c2) -> c1*c2
6247   if (N0CFP && N1CFP)
6248     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6249   // canonicalize constant to RHS
6250   if (N0CFP && !N1CFP)
6251     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6252   // fold (fmul A, 0) -> 0
6253   if (DAG.getTarget().Options.UnsafeFPMath &&
6254       N1CFP && N1CFP->getValueAPF().isZero())
6255     return N1;
6256   // fold (fmul A, 0) -> 0, vector edition.
6257   if (DAG.getTarget().Options.UnsafeFPMath &&
6258       ISD::isBuildVectorAllZeros(N1.getNode()))
6259     return N1;
6260   // fold (fmul A, 1.0) -> A
6261   if (N1CFP && N1CFP->isExactlyValue(1.0))
6262     return N0;
6263   // fold (fmul X, 2.0) -> (fadd X, X)
6264   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6265     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6266   // fold (fmul X, -1.0) -> (fneg X)
6267   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6268     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6269       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6270
6271   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6272   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6273                                        &DAG.getTarget().Options)) {
6274     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6275                                          &DAG.getTarget().Options)) {
6276       // Both can be negated for free, check to see if at least one is cheaper
6277       // negated.
6278       if (LHSNeg == 2 || RHSNeg == 2)
6279         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6280                            GetNegatedExpression(N0, DAG, LegalOperations),
6281                            GetNegatedExpression(N1, DAG, LegalOperations));
6282     }
6283   }
6284
6285   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6286   if (DAG.getTarget().Options.UnsafeFPMath &&
6287       N1CFP && N0.getOpcode() == ISD::FMUL &&
6288       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6289     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6290                        DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6291                                    N0.getOperand(1), N1));
6292
6293   return SDValue();
6294 }
6295
6296 SDValue DAGCombiner::visitFMA(SDNode *N) {
6297   SDValue N0 = N->getOperand(0);
6298   SDValue N1 = N->getOperand(1);
6299   SDValue N2 = N->getOperand(2);
6300   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6301   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6302   EVT VT = N->getValueType(0);
6303   SDLoc dl(N);
6304
6305   if (DAG.getTarget().Options.UnsafeFPMath) {
6306     if (N0CFP && N0CFP->isZero())
6307       return N2;
6308     if (N1CFP && N1CFP->isZero())
6309       return N2;
6310   }
6311   if (N0CFP && N0CFP->isExactlyValue(1.0))
6312     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6313   if (N1CFP && N1CFP->isExactlyValue(1.0))
6314     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6315
6316   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6317   if (N0CFP && !N1CFP)
6318     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6319
6320   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6321   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6322       N2.getOpcode() == ISD::FMUL &&
6323       N0 == N2.getOperand(0) &&
6324       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6325     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6326                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6327   }
6328
6329
6330   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6331   if (DAG.getTarget().Options.UnsafeFPMath &&
6332       N0.getOpcode() == ISD::FMUL && N1CFP &&
6333       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6334     return DAG.getNode(ISD::FMA, dl, VT,
6335                        N0.getOperand(0),
6336                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6337                        N2);
6338   }
6339
6340   // (fma x, 1, y) -> (fadd x, y)
6341   // (fma x, -1, y) -> (fadd (fneg x), y)
6342   if (N1CFP) {
6343     if (N1CFP->isExactlyValue(1.0))
6344       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6345
6346     if (N1CFP->isExactlyValue(-1.0) &&
6347         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6348       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6349       AddToWorkList(RHSNeg.getNode());
6350       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6351     }
6352   }
6353
6354   // (fma x, c, x) -> (fmul x, (c+1))
6355   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6356     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6357                        DAG.getNode(ISD::FADD, dl, VT,
6358                                    N1, DAG.getConstantFP(1.0, VT)));
6359
6360   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6361   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6362       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6363     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6364                        DAG.getNode(ISD::FADD, dl, VT,
6365                                    N1, DAG.getConstantFP(-1.0, VT)));
6366
6367
6368   return SDValue();
6369 }
6370
6371 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6372   SDValue N0 = N->getOperand(0);
6373   SDValue N1 = N->getOperand(1);
6374   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6375   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6376   EVT VT = N->getValueType(0);
6377   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6378
6379   // fold vector ops
6380   if (VT.isVector()) {
6381     SDValue FoldedVOp = SimplifyVBinOp(N);
6382     if (FoldedVOp.getNode()) return FoldedVOp;
6383   }
6384
6385   // fold (fdiv c1, c2) -> c1/c2
6386   if (N0CFP && N1CFP)
6387     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6388
6389   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6390   if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6391     // Compute the reciprocal 1.0 / c2.
6392     APFloat N1APF = N1CFP->getValueAPF();
6393     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6394     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6395     // Only do the transform if the reciprocal is a legal fp immediate that
6396     // isn't too nasty (eg NaN, denormal, ...).
6397     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6398         (!LegalOperations ||
6399          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6400          // backend)... we should handle this gracefully after Legalize.
6401          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6402          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6403          TLI.isFPImmLegal(Recip, VT)))
6404       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6405                          DAG.getConstantFP(Recip, VT));
6406   }
6407
6408   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6409   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6410                                        &DAG.getTarget().Options)) {
6411     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6412                                          &DAG.getTarget().Options)) {
6413       // Both can be negated for free, check to see if at least one is cheaper
6414       // negated.
6415       if (LHSNeg == 2 || RHSNeg == 2)
6416         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6417                            GetNegatedExpression(N0, DAG, LegalOperations),
6418                            GetNegatedExpression(N1, DAG, LegalOperations));
6419     }
6420   }
6421
6422   return SDValue();
6423 }
6424
6425 SDValue DAGCombiner::visitFREM(SDNode *N) {
6426   SDValue N0 = N->getOperand(0);
6427   SDValue N1 = N->getOperand(1);
6428   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6429   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6430   EVT VT = N->getValueType(0);
6431
6432   // fold (frem c1, c2) -> fmod(c1,c2)
6433   if (N0CFP && N1CFP)
6434     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6435
6436   return SDValue();
6437 }
6438
6439 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6440   SDValue N0 = N->getOperand(0);
6441   SDValue N1 = N->getOperand(1);
6442   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6443   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6444   EVT VT = N->getValueType(0);
6445
6446   if (N0CFP && N1CFP)  // Constant fold
6447     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6448
6449   if (N1CFP) {
6450     const APFloat& V = N1CFP->getValueAPF();
6451     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
6452     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6453     if (!V.isNegative()) {
6454       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6455         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6456     } else {
6457       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6458         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6459                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6460     }
6461   }
6462
6463   // copysign(fabs(x), y) -> copysign(x, y)
6464   // copysign(fneg(x), y) -> copysign(x, y)
6465   // copysign(copysign(x,z), y) -> copysign(x, y)
6466   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6467       N0.getOpcode() == ISD::FCOPYSIGN)
6468     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6469                        N0.getOperand(0), N1);
6470
6471   // copysign(x, abs(y)) -> abs(x)
6472   if (N1.getOpcode() == ISD::FABS)
6473     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6474
6475   // copysign(x, copysign(y,z)) -> copysign(x, z)
6476   if (N1.getOpcode() == ISD::FCOPYSIGN)
6477     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6478                        N0, N1.getOperand(1));
6479
6480   // copysign(x, fp_extend(y)) -> copysign(x, y)
6481   // copysign(x, fp_round(y)) -> copysign(x, y)
6482   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6483     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6484                        N0, N1.getOperand(0));
6485
6486   return SDValue();
6487 }
6488
6489 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6490   SDValue N0 = N->getOperand(0);
6491   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6492   EVT VT = N->getValueType(0);
6493   EVT OpVT = N0.getValueType();
6494
6495   // fold (sint_to_fp c1) -> c1fp
6496   if (N0C &&
6497       // ...but only if the target supports immediate floating-point values
6498       (!LegalOperations ||
6499        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6500     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6501
6502   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6503   // but UINT_TO_FP is legal on this target, try to convert.
6504   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6505       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6506     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6507     if (DAG.SignBitIsZero(N0))
6508       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6509   }
6510
6511   // The next optimizations are desireable only if SELECT_CC can be lowered.
6512   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6513   // having to say they don't support SELECT_CC on every type the DAG knows
6514   // about, since there is no way to mark an opcode illegal at all value types
6515   // (See also visitSELECT)
6516   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6517     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6518     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6519         !VT.isVector() &&
6520         (!LegalOperations ||
6521          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6522       SDValue Ops[] =
6523         { N0.getOperand(0), N0.getOperand(1),
6524           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6525           N0.getOperand(2) };
6526       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6527     }
6528
6529     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6530     //      (select_cc x, y, 1.0, 0.0,, cc)
6531     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6532         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6533         (!LegalOperations ||
6534          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6535       SDValue Ops[] =
6536         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6537           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6538           N0.getOperand(0).getOperand(2) };
6539       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6540     }
6541   }
6542
6543   return SDValue();
6544 }
6545
6546 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6547   SDValue N0 = N->getOperand(0);
6548   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6549   EVT VT = N->getValueType(0);
6550   EVT OpVT = N0.getValueType();
6551
6552   // fold (uint_to_fp c1) -> c1fp
6553   if (N0C &&
6554       // ...but only if the target supports immediate floating-point values
6555       (!LegalOperations ||
6556        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6557     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6558
6559   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6560   // but SINT_TO_FP is legal on this target, try to convert.
6561   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
6562       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
6563     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
6564     if (DAG.SignBitIsZero(N0))
6565       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6566   }
6567
6568   // The next optimizations are desireable only if SELECT_CC can be lowered.
6569   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6570   // having to say they don't support SELECT_CC on every type the DAG knows
6571   // about, since there is no way to mark an opcode illegal at all value types
6572   // (See also visitSELECT)
6573   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6574     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6575
6576     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
6577         (!LegalOperations ||
6578          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6579       SDValue Ops[] =
6580         { N0.getOperand(0), N0.getOperand(1),
6581           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
6582           N0.getOperand(2) };
6583       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6584     }
6585   }
6586
6587   return SDValue();
6588 }
6589
6590 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
6591   SDValue N0 = N->getOperand(0);
6592   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6593   EVT VT = N->getValueType(0);
6594
6595   // fold (fp_to_sint c1fp) -> c1
6596   if (N0CFP)
6597     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
6598
6599   return SDValue();
6600 }
6601
6602 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
6603   SDValue N0 = N->getOperand(0);
6604   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6605   EVT VT = N->getValueType(0);
6606
6607   // fold (fp_to_uint c1fp) -> c1
6608   if (N0CFP)
6609     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
6610
6611   return SDValue();
6612 }
6613
6614 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
6615   SDValue N0 = N->getOperand(0);
6616   SDValue N1 = N->getOperand(1);
6617   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6618   EVT VT = N->getValueType(0);
6619
6620   // fold (fp_round c1fp) -> c1fp
6621   if (N0CFP)
6622     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
6623
6624   // fold (fp_round (fp_extend x)) -> x
6625   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
6626     return N0.getOperand(0);
6627
6628   // fold (fp_round (fp_round x)) -> (fp_round x)
6629   if (N0.getOpcode() == ISD::FP_ROUND) {
6630     // This is a value preserving truncation if both round's are.
6631     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
6632                    N0.getNode()->getConstantOperandVal(1) == 1;
6633     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
6634                        DAG.getIntPtrConstant(IsTrunc));
6635   }
6636
6637   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
6638   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
6639     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
6640                               N0.getOperand(0), N1);
6641     AddToWorkList(Tmp.getNode());
6642     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6643                        Tmp, N0.getOperand(1));
6644   }
6645
6646   return SDValue();
6647 }
6648
6649 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
6650   SDValue N0 = N->getOperand(0);
6651   EVT VT = N->getValueType(0);
6652   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6653   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6654
6655   // fold (fp_round_inreg c1fp) -> c1fp
6656   if (N0CFP && isTypeLegal(EVT)) {
6657     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
6658     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
6659   }
6660
6661   return SDValue();
6662 }
6663
6664 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
6665   SDValue N0 = N->getOperand(0);
6666   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6667   EVT VT = N->getValueType(0);
6668
6669   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
6670   if (N->hasOneUse() &&
6671       N->use_begin()->getOpcode() == ISD::FP_ROUND)
6672     return SDValue();
6673
6674   // fold (fp_extend c1fp) -> c1fp
6675   if (N0CFP)
6676     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
6677
6678   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
6679   // value of X.
6680   if (N0.getOpcode() == ISD::FP_ROUND
6681       && N0.getNode()->getConstantOperandVal(1) == 1) {
6682     SDValue In = N0.getOperand(0);
6683     if (In.getValueType() == VT) return In;
6684     if (VT.bitsLT(In.getValueType()))
6685       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
6686                          In, N0.getOperand(1));
6687     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
6688   }
6689
6690   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
6691   if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
6692       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6693        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
6694     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6695     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6696                                      LN0->getChain(),
6697                                      LN0->getBasePtr(), LN0->getPointerInfo(),
6698                                      N0.getValueType(),
6699                                      LN0->isVolatile(), LN0->isNonTemporal(),
6700                                      LN0->getAlignment());
6701     CombineTo(N, ExtLoad);
6702     CombineTo(N0.getNode(),
6703               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
6704                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
6705               ExtLoad.getValue(1));
6706     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6707   }
6708
6709   return SDValue();
6710 }
6711
6712 SDValue DAGCombiner::visitFNEG(SDNode *N) {
6713   SDValue N0 = N->getOperand(0);
6714   EVT VT = N->getValueType(0);
6715
6716   if (VT.isVector()) {
6717     SDValue FoldedVOp = SimplifyVUnaryOp(N);
6718     if (FoldedVOp.getNode()) return FoldedVOp;
6719   }
6720
6721   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
6722                          &DAG.getTarget().Options))
6723     return GetNegatedExpression(N0, DAG, LegalOperations);
6724
6725   // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
6726   // constant pool values.
6727   if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
6728       !VT.isVector() &&
6729       N0.getNode()->hasOneUse() &&
6730       N0.getOperand(0).getValueType().isInteger()) {
6731     SDValue Int = N0.getOperand(0);
6732     EVT IntVT = Int.getValueType();
6733     if (IntVT.isInteger() && !IntVT.isVector()) {
6734       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
6735               DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6736       AddToWorkList(Int.getNode());
6737       return DAG.getNode(ISD::BITCAST, SDLoc(N),
6738                          VT, Int);
6739     }
6740   }
6741
6742   // (fneg (fmul c, x)) -> (fmul -c, x)
6743   if (N0.getOpcode() == ISD::FMUL) {
6744     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6745     if (CFP1)
6746       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6747                          N0.getOperand(0),
6748                          DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6749                                      N0.getOperand(1)));
6750   }
6751
6752   return SDValue();
6753 }
6754
6755 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
6756   SDValue N0 = N->getOperand(0);
6757   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6758   EVT VT = N->getValueType(0);
6759
6760   // fold (fceil c1) -> fceil(c1)
6761   if (N0CFP)
6762     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
6763
6764   return SDValue();
6765 }
6766
6767 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
6768   SDValue N0 = N->getOperand(0);
6769   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6770   EVT VT = N->getValueType(0);
6771
6772   // fold (ftrunc c1) -> ftrunc(c1)
6773   if (N0CFP)
6774     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
6775
6776   return SDValue();
6777 }
6778
6779 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
6780   SDValue N0 = N->getOperand(0);
6781   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6782   EVT VT = N->getValueType(0);
6783
6784   // fold (ffloor c1) -> ffloor(c1)
6785   if (N0CFP)
6786     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
6787
6788   return SDValue();
6789 }
6790
6791 SDValue DAGCombiner::visitFABS(SDNode *N) {
6792   SDValue N0 = N->getOperand(0);
6793   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6794   EVT VT = N->getValueType(0);
6795
6796   if (VT.isVector()) {
6797     SDValue FoldedVOp = SimplifyVUnaryOp(N);
6798     if (FoldedVOp.getNode()) return FoldedVOp;
6799   }
6800
6801   // fold (fabs c1) -> fabs(c1)
6802   if (N0CFP)
6803     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6804   // fold (fabs (fabs x)) -> (fabs x)
6805   if (N0.getOpcode() == ISD::FABS)
6806     return N->getOperand(0);
6807   // fold (fabs (fneg x)) -> (fabs x)
6808   // fold (fabs (fcopysign x, y)) -> (fabs x)
6809   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
6810     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
6811
6812   // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
6813   // constant pool values.
6814   if (!TLI.isFAbsFree(VT) &&
6815       N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
6816       N0.getOperand(0).getValueType().isInteger() &&
6817       !N0.getOperand(0).getValueType().isVector()) {
6818     SDValue Int = N0.getOperand(0);
6819     EVT IntVT = Int.getValueType();
6820     if (IntVT.isInteger() && !IntVT.isVector()) {
6821       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
6822              DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6823       AddToWorkList(Int.getNode());
6824       return DAG.getNode(ISD::BITCAST, SDLoc(N),
6825                          N->getValueType(0), Int);
6826     }
6827   }
6828
6829   return SDValue();
6830 }
6831
6832 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
6833   SDValue Chain = N->getOperand(0);
6834   SDValue N1 = N->getOperand(1);
6835   SDValue N2 = N->getOperand(2);
6836
6837   // If N is a constant we could fold this into a fallthrough or unconditional
6838   // branch. However that doesn't happen very often in normal code, because
6839   // Instcombine/SimplifyCFG should have handled the available opportunities.
6840   // If we did this folding here, it would be necessary to update the
6841   // MachineBasicBlock CFG, which is awkward.
6842
6843   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
6844   // on the target.
6845   if (N1.getOpcode() == ISD::SETCC &&
6846       TLI.isOperationLegalOrCustom(ISD::BR_CC,
6847                                    N1.getOperand(0).getValueType())) {
6848     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
6849                        Chain, N1.getOperand(2),
6850                        N1.getOperand(0), N1.getOperand(1), N2);
6851   }
6852
6853   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
6854       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
6855        (N1.getOperand(0).hasOneUse() &&
6856         N1.getOperand(0).getOpcode() == ISD::SRL))) {
6857     SDNode *Trunc = 0;
6858     if (N1.getOpcode() == ISD::TRUNCATE) {
6859       // Look pass the truncate.
6860       Trunc = N1.getNode();
6861       N1 = N1.getOperand(0);
6862     }
6863
6864     // Match this pattern so that we can generate simpler code:
6865     //
6866     //   %a = ...
6867     //   %b = and i32 %a, 2
6868     //   %c = srl i32 %b, 1
6869     //   brcond i32 %c ...
6870     //
6871     // into
6872     //
6873     //   %a = ...
6874     //   %b = and i32 %a, 2
6875     //   %c = setcc eq %b, 0
6876     //   brcond %c ...
6877     //
6878     // This applies only when the AND constant value has one bit set and the
6879     // SRL constant is equal to the log2 of the AND constant. The back-end is
6880     // smart enough to convert the result into a TEST/JMP sequence.
6881     SDValue Op0 = N1.getOperand(0);
6882     SDValue Op1 = N1.getOperand(1);
6883
6884     if (Op0.getOpcode() == ISD::AND &&
6885         Op1.getOpcode() == ISD::Constant) {
6886       SDValue AndOp1 = Op0.getOperand(1);
6887
6888       if (AndOp1.getOpcode() == ISD::Constant) {
6889         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
6890
6891         if (AndConst.isPowerOf2() &&
6892             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
6893           SDValue SetCC =
6894             DAG.getSetCC(SDLoc(N),
6895                          getSetCCResultType(Op0.getValueType()),
6896                          Op0, DAG.getConstant(0, Op0.getValueType()),
6897                          ISD::SETNE);
6898
6899           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
6900                                           MVT::Other, Chain, SetCC, N2);
6901           // Don't add the new BRCond into the worklist or else SimplifySelectCC
6902           // will convert it back to (X & C1) >> C2.
6903           CombineTo(N, NewBRCond, false);
6904           // Truncate is dead.
6905           if (Trunc) {
6906             removeFromWorkList(Trunc);
6907             DAG.DeleteNode(Trunc);
6908           }
6909           // Replace the uses of SRL with SETCC
6910           WorkListRemover DeadNodes(*this);
6911           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
6912           removeFromWorkList(N1.getNode());
6913           DAG.DeleteNode(N1.getNode());
6914           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6915         }
6916       }
6917     }
6918
6919     if (Trunc)
6920       // Restore N1 if the above transformation doesn't match.
6921       N1 = N->getOperand(1);
6922   }
6923
6924   // Transform br(xor(x, y)) -> br(x != y)
6925   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
6926   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
6927     SDNode *TheXor = N1.getNode();
6928     SDValue Op0 = TheXor->getOperand(0);
6929     SDValue Op1 = TheXor->getOperand(1);
6930     if (Op0.getOpcode() == Op1.getOpcode()) {
6931       // Avoid missing important xor optimizations.
6932       SDValue Tmp = visitXOR(TheXor);
6933       if (Tmp.getNode()) {
6934         if (Tmp.getNode() != TheXor) {
6935           DEBUG(dbgs() << "\nReplacing.8 ";
6936                 TheXor->dump(&DAG);
6937                 dbgs() << "\nWith: ";
6938                 Tmp.getNode()->dump(&DAG);
6939                 dbgs() << '\n');
6940           WorkListRemover DeadNodes(*this);
6941           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
6942           removeFromWorkList(TheXor);
6943           DAG.DeleteNode(TheXor);
6944           return DAG.getNode(ISD::BRCOND, SDLoc(N),
6945                              MVT::Other, Chain, Tmp, N2);
6946         }
6947
6948         // visitXOR has changed XOR's operands or replaced the XOR completely,
6949         // bail out.
6950         return SDValue(N, 0);
6951       }
6952     }
6953
6954     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
6955       bool Equal = false;
6956       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
6957         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
6958             Op0.getOpcode() == ISD::XOR) {
6959           TheXor = Op0.getNode();
6960           Equal = true;
6961         }
6962
6963       EVT SetCCVT = N1.getValueType();
6964       if (LegalTypes)
6965         SetCCVT = getSetCCResultType(SetCCVT);
6966       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
6967                                    SetCCVT,
6968                                    Op0, Op1,
6969                                    Equal ? ISD::SETEQ : ISD::SETNE);
6970       // Replace the uses of XOR with SETCC
6971       WorkListRemover DeadNodes(*this);
6972       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
6973       removeFromWorkList(N1.getNode());
6974       DAG.DeleteNode(N1.getNode());
6975       return DAG.getNode(ISD::BRCOND, SDLoc(N),
6976                          MVT::Other, Chain, SetCC, N2);
6977     }
6978   }
6979
6980   return SDValue();
6981 }
6982
6983 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
6984 //
6985 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
6986   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
6987   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
6988
6989   // If N is a constant we could fold this into a fallthrough or unconditional
6990   // branch. However that doesn't happen very often in normal code, because
6991   // Instcombine/SimplifyCFG should have handled the available opportunities.
6992   // If we did this folding here, it would be necessary to update the
6993   // MachineBasicBlock CFG, which is awkward.
6994
6995   // Use SimplifySetCC to simplify SETCC's.
6996   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
6997                                CondLHS, CondRHS, CC->get(), SDLoc(N),
6998                                false);
6999   if (Simp.getNode()) AddToWorkList(Simp.getNode());
7000
7001   // fold to a simpler setcc
7002   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7003     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7004                        N->getOperand(0), Simp.getOperand(2),
7005                        Simp.getOperand(0), Simp.getOperand(1),
7006                        N->getOperand(4));
7007
7008   return SDValue();
7009 }
7010
7011 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7012 /// uses N as its base pointer and that N may be folded in the load / store
7013 /// addressing mode.
7014 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7015                                     SelectionDAG &DAG,
7016                                     const TargetLowering &TLI) {
7017   EVT VT;
7018   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7019     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7020       return false;
7021     VT = Use->getValueType(0);
7022   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7023     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7024       return false;
7025     VT = ST->getValue().getValueType();
7026   } else
7027     return false;
7028
7029   TargetLowering::AddrMode AM;
7030   if (N->getOpcode() == ISD::ADD) {
7031     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7032     if (Offset)
7033       // [reg +/- imm]
7034       AM.BaseOffs = Offset->getSExtValue();
7035     else
7036       // [reg +/- reg]
7037       AM.Scale = 1;
7038   } else if (N->getOpcode() == ISD::SUB) {
7039     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7040     if (Offset)
7041       // [reg +/- imm]
7042       AM.BaseOffs = -Offset->getSExtValue();
7043     else
7044       // [reg +/- reg]
7045       AM.Scale = 1;
7046   } else
7047     return false;
7048
7049   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7050 }
7051
7052 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7053 /// pre-indexed load / store when the base pointer is an add or subtract
7054 /// and it has other uses besides the load / store. After the
7055 /// transformation, the new indexed load / store has effectively folded
7056 /// the add / subtract in and all of its other uses are redirected to the
7057 /// new load / store.
7058 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7059   if (Level < AfterLegalizeDAG)
7060     return false;
7061
7062   bool isLoad = true;
7063   SDValue Ptr;
7064   EVT VT;
7065   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7066     if (LD->isIndexed())
7067       return false;
7068     VT = LD->getMemoryVT();
7069     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7070         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7071       return false;
7072     Ptr = LD->getBasePtr();
7073   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7074     if (ST->isIndexed())
7075       return false;
7076     VT = ST->getMemoryVT();
7077     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7078         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7079       return false;
7080     Ptr = ST->getBasePtr();
7081     isLoad = false;
7082   } else {
7083     return false;
7084   }
7085
7086   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7087   // out.  There is no reason to make this a preinc/predec.
7088   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7089       Ptr.getNode()->hasOneUse())
7090     return false;
7091
7092   // Ask the target to do addressing mode selection.
7093   SDValue BasePtr;
7094   SDValue Offset;
7095   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7096   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7097     return false;
7098
7099   // Backends without true r+i pre-indexed forms may need to pass a
7100   // constant base with a variable offset so that constant coercion
7101   // will work with the patterns in canonical form.
7102   bool Swapped = false;
7103   if (isa<ConstantSDNode>(BasePtr)) {
7104     std::swap(BasePtr, Offset);
7105     Swapped = true;
7106   }
7107
7108   // Don't create a indexed load / store with zero offset.
7109   if (isa<ConstantSDNode>(Offset) &&
7110       cast<ConstantSDNode>(Offset)->isNullValue())
7111     return false;
7112
7113   // Try turning it into a pre-indexed load / store except when:
7114   // 1) The new base ptr is a frame index.
7115   // 2) If N is a store and the new base ptr is either the same as or is a
7116   //    predecessor of the value being stored.
7117   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7118   //    that would create a cycle.
7119   // 4) All uses are load / store ops that use it as old base ptr.
7120
7121   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7122   // (plus the implicit offset) to a register to preinc anyway.
7123   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7124     return false;
7125
7126   // Check #2.
7127   if (!isLoad) {
7128     SDValue Val = cast<StoreSDNode>(N)->getValue();
7129     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7130       return false;
7131   }
7132
7133   // If the offset is a constant, there may be other adds of constants that
7134   // can be folded with this one. We should do this to avoid having to keep
7135   // a copy of the original base pointer.
7136   SmallVector<SDNode *, 16> OtherUses;
7137   if (isa<ConstantSDNode>(Offset))
7138     for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7139          E = BasePtr.getNode()->use_end(); I != E; ++I) {
7140       SDNode *Use = *I;
7141       if (Use == Ptr.getNode())
7142         continue;
7143
7144       if (Use->isPredecessorOf(N))
7145         continue;
7146
7147       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7148         OtherUses.clear();
7149         break;
7150       }
7151
7152       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7153       if (Op1.getNode() == BasePtr.getNode())
7154         std::swap(Op0, Op1);
7155       assert(Op0.getNode() == BasePtr.getNode() &&
7156              "Use of ADD/SUB but not an operand");
7157
7158       if (!isa<ConstantSDNode>(Op1)) {
7159         OtherUses.clear();
7160         break;
7161       }
7162
7163       // FIXME: In some cases, we can be smarter about this.
7164       if (Op1.getValueType() != Offset.getValueType()) {
7165         OtherUses.clear();
7166         break;
7167       }
7168
7169       OtherUses.push_back(Use);
7170     }
7171
7172   if (Swapped)
7173     std::swap(BasePtr, Offset);
7174
7175   // Now check for #3 and #4.
7176   bool RealUse = false;
7177
7178   // Caches for hasPredecessorHelper
7179   SmallPtrSet<const SDNode *, 32> Visited;
7180   SmallVector<const SDNode *, 16> Worklist;
7181
7182   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7183          E = Ptr.getNode()->use_end(); I != E; ++I) {
7184     SDNode *Use = *I;
7185     if (Use == N)
7186       continue;
7187     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7188       return false;
7189
7190     // If Ptr may be folded in addressing mode of other use, then it's
7191     // not profitable to do this transformation.
7192     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7193       RealUse = true;
7194   }
7195
7196   if (!RealUse)
7197     return false;
7198
7199   SDValue Result;
7200   if (isLoad)
7201     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7202                                 BasePtr, Offset, AM);
7203   else
7204     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7205                                  BasePtr, Offset, AM);
7206   ++PreIndexedNodes;
7207   ++NodesCombined;
7208   DEBUG(dbgs() << "\nReplacing.4 ";
7209         N->dump(&DAG);
7210         dbgs() << "\nWith: ";
7211         Result.getNode()->dump(&DAG);
7212         dbgs() << '\n');
7213   WorkListRemover DeadNodes(*this);
7214   if (isLoad) {
7215     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7216     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7217   } else {
7218     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7219   }
7220
7221   // Finally, since the node is now dead, remove it from the graph.
7222   DAG.DeleteNode(N);
7223
7224   if (Swapped)
7225     std::swap(BasePtr, Offset);
7226
7227   // Replace other uses of BasePtr that can be updated to use Ptr
7228   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7229     unsigned OffsetIdx = 1;
7230     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7231       OffsetIdx = 0;
7232     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7233            BasePtr.getNode() && "Expected BasePtr operand");
7234
7235     // We need to replace ptr0 in the following expression:
7236     //   x0 * offset0 + y0 * ptr0 = t0
7237     // knowing that
7238     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7239     //
7240     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7241     // indexed load/store and the expresion that needs to be re-written.
7242     //
7243     // Therefore, we have:
7244     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7245
7246     ConstantSDNode *CN =
7247       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7248     int X0, X1, Y0, Y1;
7249     APInt Offset0 = CN->getAPIntValue();
7250     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7251
7252     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7253     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7254     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7255     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7256
7257     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7258
7259     APInt CNV = Offset0;
7260     if (X0 < 0) CNV = -CNV;
7261     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7262     else CNV = CNV - Offset1;
7263
7264     // We can now generate the new expression.
7265     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7266     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7267
7268     SDValue NewUse = DAG.getNode(Opcode,
7269                                  SDLoc(OtherUses[i]),
7270                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7271     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7272     removeFromWorkList(OtherUses[i]);
7273     DAG.DeleteNode(OtherUses[i]);
7274   }
7275
7276   // Replace the uses of Ptr with uses of the updated base value.
7277   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7278   removeFromWorkList(Ptr.getNode());
7279   DAG.DeleteNode(Ptr.getNode());
7280
7281   return true;
7282 }
7283
7284 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7285 /// add / sub of the base pointer node into a post-indexed load / store.
7286 /// The transformation folded the add / subtract into the new indexed
7287 /// load / store effectively and all of its uses are redirected to the
7288 /// new load / store.
7289 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7290   if (Level < AfterLegalizeDAG)
7291     return false;
7292
7293   bool isLoad = true;
7294   SDValue Ptr;
7295   EVT VT;
7296   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7297     if (LD->isIndexed())
7298       return false;
7299     VT = LD->getMemoryVT();
7300     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7301         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7302       return false;
7303     Ptr = LD->getBasePtr();
7304   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7305     if (ST->isIndexed())
7306       return false;
7307     VT = ST->getMemoryVT();
7308     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7309         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7310       return false;
7311     Ptr = ST->getBasePtr();
7312     isLoad = false;
7313   } else {
7314     return false;
7315   }
7316
7317   if (Ptr.getNode()->hasOneUse())
7318     return false;
7319
7320   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7321          E = Ptr.getNode()->use_end(); I != E; ++I) {
7322     SDNode *Op = *I;
7323     if (Op == N ||
7324         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7325       continue;
7326
7327     SDValue BasePtr;
7328     SDValue Offset;
7329     ISD::MemIndexedMode AM = ISD::UNINDEXED;
7330     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7331       // Don't create a indexed load / store with zero offset.
7332       if (isa<ConstantSDNode>(Offset) &&
7333           cast<ConstantSDNode>(Offset)->isNullValue())
7334         continue;
7335
7336       // Try turning it into a post-indexed load / store except when
7337       // 1) All uses are load / store ops that use it as base ptr (and
7338       //    it may be folded as addressing mmode).
7339       // 2) Op must be independent of N, i.e. Op is neither a predecessor
7340       //    nor a successor of N. Otherwise, if Op is folded that would
7341       //    create a cycle.
7342
7343       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7344         continue;
7345
7346       // Check for #1.
7347       bool TryNext = false;
7348       for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7349              EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
7350         SDNode *Use = *II;
7351         if (Use == Ptr.getNode())
7352           continue;
7353
7354         // If all the uses are load / store addresses, then don't do the
7355         // transformation.
7356         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7357           bool RealUse = false;
7358           for (SDNode::use_iterator III = Use->use_begin(),
7359                  EEE = Use->use_end(); III != EEE; ++III) {
7360             SDNode *UseUse = *III;
7361             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7362               RealUse = true;
7363           }
7364
7365           if (!RealUse) {
7366             TryNext = true;
7367             break;
7368           }
7369         }
7370       }
7371
7372       if (TryNext)
7373         continue;
7374
7375       // Check for #2
7376       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7377         SDValue Result = isLoad
7378           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7379                                BasePtr, Offset, AM)
7380           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7381                                 BasePtr, Offset, AM);
7382         ++PostIndexedNodes;
7383         ++NodesCombined;
7384         DEBUG(dbgs() << "\nReplacing.5 ";
7385               N->dump(&DAG);
7386               dbgs() << "\nWith: ";
7387               Result.getNode()->dump(&DAG);
7388               dbgs() << '\n');
7389         WorkListRemover DeadNodes(*this);
7390         if (isLoad) {
7391           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7392           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7393         } else {
7394           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7395         }
7396
7397         // Finally, since the node is now dead, remove it from the graph.
7398         DAG.DeleteNode(N);
7399
7400         // Replace the uses of Use with uses of the updated base value.
7401         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7402                                       Result.getValue(isLoad ? 1 : 0));
7403         removeFromWorkList(Op);
7404         DAG.DeleteNode(Op);
7405         return true;
7406       }
7407     }
7408   }
7409
7410   return false;
7411 }
7412
7413 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7414   LoadSDNode *LD  = cast<LoadSDNode>(N);
7415   SDValue Chain = LD->getChain();
7416   SDValue Ptr   = LD->getBasePtr();
7417
7418   // If load is not volatile and there are no uses of the loaded value (and
7419   // the updated indexed value in case of indexed loads), change uses of the
7420   // chain value into uses of the chain input (i.e. delete the dead load).
7421   if (!LD->isVolatile()) {
7422     if (N->getValueType(1) == MVT::Other) {
7423       // Unindexed loads.
7424       if (!N->hasAnyUseOfValue(0)) {
7425         // It's not safe to use the two value CombineTo variant here. e.g.
7426         // v1, chain2 = load chain1, loc
7427         // v2, chain3 = load chain2, loc
7428         // v3         = add v2, c
7429         // Now we replace use of chain2 with chain1.  This makes the second load
7430         // isomorphic to the one we are deleting, and thus makes this load live.
7431         DEBUG(dbgs() << "\nReplacing.6 ";
7432               N->dump(&DAG);
7433               dbgs() << "\nWith chain: ";
7434               Chain.getNode()->dump(&DAG);
7435               dbgs() << "\n");
7436         WorkListRemover DeadNodes(*this);
7437         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7438
7439         if (N->use_empty()) {
7440           removeFromWorkList(N);
7441           DAG.DeleteNode(N);
7442         }
7443
7444         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7445       }
7446     } else {
7447       // Indexed loads.
7448       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7449       if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7450         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7451         DEBUG(dbgs() << "\nReplacing.7 ";
7452               N->dump(&DAG);
7453               dbgs() << "\nWith: ";
7454               Undef.getNode()->dump(&DAG);
7455               dbgs() << " and 2 other values\n");
7456         WorkListRemover DeadNodes(*this);
7457         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7458         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7459                                       DAG.getUNDEF(N->getValueType(1)));
7460         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7461         removeFromWorkList(N);
7462         DAG.DeleteNode(N);
7463         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7464       }
7465     }
7466   }
7467
7468   // If this load is directly stored, replace the load value with the stored
7469   // value.
7470   // TODO: Handle store large -> read small portion.
7471   // TODO: Handle TRUNCSTORE/LOADEXT
7472   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7473     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7474       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7475       if (PrevST->getBasePtr() == Ptr &&
7476           PrevST->getValue().getValueType() == N->getValueType(0))
7477       return CombineTo(N, Chain.getOperand(1), Chain);
7478     }
7479   }
7480
7481   // Try to infer better alignment information than the load already has.
7482   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7483     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7484       if (Align > LD->getMemOperand()->getBaseAlignment()) {
7485         SDValue NewLoad =
7486                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7487                               LD->getValueType(0),
7488                               Chain, Ptr, LD->getPointerInfo(),
7489                               LD->getMemoryVT(),
7490                               LD->isVolatile(), LD->isNonTemporal(), Align);
7491         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7492       }
7493     }
7494   }
7495
7496   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7497     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7498   if (UseAA) {
7499     // Walk up chain skipping non-aliasing memory nodes.
7500     SDValue BetterChain = FindBetterChain(N, Chain);
7501
7502     // If there is a better chain.
7503     if (Chain != BetterChain) {
7504       SDValue ReplLoad;
7505
7506       // Replace the chain to void dependency.
7507       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7508         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7509                                BetterChain, Ptr, LD->getPointerInfo(),
7510                                LD->isVolatile(), LD->isNonTemporal(),
7511                                LD->isInvariant(), LD->getAlignment());
7512       } else {
7513         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7514                                   LD->getValueType(0),
7515                                   BetterChain, Ptr, LD->getPointerInfo(),
7516                                   LD->getMemoryVT(),
7517                                   LD->isVolatile(),
7518                                   LD->isNonTemporal(),
7519                                   LD->getAlignment());
7520       }
7521
7522       // Create token factor to keep old chain connected.
7523       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7524                                   MVT::Other, Chain, ReplLoad.getValue(1));
7525
7526       // Make sure the new and old chains are cleaned up.
7527       AddToWorkList(Token.getNode());
7528
7529       // Replace uses with load result and token factor. Don't add users
7530       // to work list.
7531       return CombineTo(N, ReplLoad.getValue(0), Token, false);
7532     }
7533   }
7534
7535   // Try transforming N to an indexed load.
7536   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7537     return SDValue(N, 0);
7538
7539   return SDValue();
7540 }
7541
7542 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
7543 /// load is having specific bytes cleared out.  If so, return the byte size
7544 /// being masked out and the shift amount.
7545 static std::pair<unsigned, unsigned>
7546 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
7547   std::pair<unsigned, unsigned> Result(0, 0);
7548
7549   // Check for the structure we're looking for.
7550   if (V->getOpcode() != ISD::AND ||
7551       !isa<ConstantSDNode>(V->getOperand(1)) ||
7552       !ISD::isNormalLoad(V->getOperand(0).getNode()))
7553     return Result;
7554
7555   // Check the chain and pointer.
7556   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
7557   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
7558
7559   // The store should be chained directly to the load or be an operand of a
7560   // tokenfactor.
7561   if (LD == Chain.getNode())
7562     ; // ok.
7563   else if (Chain->getOpcode() != ISD::TokenFactor)
7564     return Result; // Fail.
7565   else {
7566     bool isOk = false;
7567     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
7568       if (Chain->getOperand(i).getNode() == LD) {
7569         isOk = true;
7570         break;
7571       }
7572     if (!isOk) return Result;
7573   }
7574
7575   // This only handles simple types.
7576   if (V.getValueType() != MVT::i16 &&
7577       V.getValueType() != MVT::i32 &&
7578       V.getValueType() != MVT::i64)
7579     return Result;
7580
7581   // Check the constant mask.  Invert it so that the bits being masked out are
7582   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
7583   // follow the sign bit for uniformity.
7584   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
7585   unsigned NotMaskLZ = countLeadingZeros(NotMask);
7586   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
7587   unsigned NotMaskTZ = countTrailingZeros(NotMask);
7588   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
7589   if (NotMaskLZ == 64) return Result;  // All zero mask.
7590
7591   // See if we have a continuous run of bits.  If so, we have 0*1+0*
7592   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
7593     return Result;
7594
7595   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
7596   if (V.getValueType() != MVT::i64 && NotMaskLZ)
7597     NotMaskLZ -= 64-V.getValueSizeInBits();
7598
7599   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
7600   switch (MaskedBytes) {
7601   case 1:
7602   case 2:
7603   case 4: break;
7604   default: return Result; // All one mask, or 5-byte mask.
7605   }
7606
7607   // Verify that the first bit starts at a multiple of mask so that the access
7608   // is aligned the same as the access width.
7609   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
7610
7611   Result.first = MaskedBytes;
7612   Result.second = NotMaskTZ/8;
7613   return Result;
7614 }
7615
7616
7617 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
7618 /// provides a value as specified by MaskInfo.  If so, replace the specified
7619 /// store with a narrower store of truncated IVal.
7620 static SDNode *
7621 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
7622                                 SDValue IVal, StoreSDNode *St,
7623                                 DAGCombiner *DC) {
7624   unsigned NumBytes = MaskInfo.first;
7625   unsigned ByteShift = MaskInfo.second;
7626   SelectionDAG &DAG = DC->getDAG();
7627
7628   // Check to see if IVal is all zeros in the part being masked in by the 'or'
7629   // that uses this.  If not, this is not a replacement.
7630   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
7631                                   ByteShift*8, (ByteShift+NumBytes)*8);
7632   if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
7633
7634   // Check that it is legal on the target to do this.  It is legal if the new
7635   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
7636   // legalization.
7637   MVT VT = MVT::getIntegerVT(NumBytes*8);
7638   if (!DC->isTypeLegal(VT))
7639     return 0;
7640
7641   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
7642   // shifted by ByteShift and truncated down to NumBytes.
7643   if (ByteShift)
7644     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
7645                        DAG.getConstant(ByteShift*8,
7646                                     DC->getShiftAmountTy(IVal.getValueType())));
7647
7648   // Figure out the offset for the store and the alignment of the access.
7649   unsigned StOffset;
7650   unsigned NewAlign = St->getAlignment();
7651
7652   if (DAG.getTargetLoweringInfo().isLittleEndian())
7653     StOffset = ByteShift;
7654   else
7655     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
7656
7657   SDValue Ptr = St->getBasePtr();
7658   if (StOffset) {
7659     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
7660                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
7661     NewAlign = MinAlign(NewAlign, StOffset);
7662   }
7663
7664   // Truncate down to the new size.
7665   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
7666
7667   ++OpsNarrowed;
7668   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
7669                       St->getPointerInfo().getWithOffset(StOffset),
7670                       false, false, NewAlign).getNode();
7671 }
7672
7673
7674 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
7675 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
7676 /// of the loaded bits, try narrowing the load and store if it would end up
7677 /// being a win for performance or code size.
7678 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
7679   StoreSDNode *ST  = cast<StoreSDNode>(N);
7680   if (ST->isVolatile())
7681     return SDValue();
7682
7683   SDValue Chain = ST->getChain();
7684   SDValue Value = ST->getValue();
7685   SDValue Ptr   = ST->getBasePtr();
7686   EVT VT = Value.getValueType();
7687
7688   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
7689     return SDValue();
7690
7691   unsigned Opc = Value.getOpcode();
7692
7693   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
7694   // is a byte mask indicating a consecutive number of bytes, check to see if
7695   // Y is known to provide just those bytes.  If so, we try to replace the
7696   // load + replace + store sequence with a single (narrower) store, which makes
7697   // the load dead.
7698   if (Opc == ISD::OR) {
7699     std::pair<unsigned, unsigned> MaskedLoad;
7700     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
7701     if (MaskedLoad.first)
7702       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
7703                                                   Value.getOperand(1), ST,this))
7704         return SDValue(NewST, 0);
7705
7706     // Or is commutative, so try swapping X and Y.
7707     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
7708     if (MaskedLoad.first)
7709       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
7710                                                   Value.getOperand(0), ST,this))
7711         return SDValue(NewST, 0);
7712   }
7713
7714   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
7715       Value.getOperand(1).getOpcode() != ISD::Constant)
7716     return SDValue();
7717
7718   SDValue N0 = Value.getOperand(0);
7719   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7720       Chain == SDValue(N0.getNode(), 1)) {
7721     LoadSDNode *LD = cast<LoadSDNode>(N0);
7722     if (LD->getBasePtr() != Ptr ||
7723         LD->getPointerInfo().getAddrSpace() !=
7724         ST->getPointerInfo().getAddrSpace())
7725       return SDValue();
7726
7727     // Find the type to narrow it the load / op / store to.
7728     SDValue N1 = Value.getOperand(1);
7729     unsigned BitWidth = N1.getValueSizeInBits();
7730     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
7731     if (Opc == ISD::AND)
7732       Imm ^= APInt::getAllOnesValue(BitWidth);
7733     if (Imm == 0 || Imm.isAllOnesValue())
7734       return SDValue();
7735     unsigned ShAmt = Imm.countTrailingZeros();
7736     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
7737     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
7738     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
7739     while (NewBW < BitWidth &&
7740            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
7741              TLI.isNarrowingProfitable(VT, NewVT))) {
7742       NewBW = NextPowerOf2(NewBW);
7743       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
7744     }
7745     if (NewBW >= BitWidth)
7746       return SDValue();
7747
7748     // If the lsb changed does not start at the type bitwidth boundary,
7749     // start at the previous one.
7750     if (ShAmt % NewBW)
7751       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
7752     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
7753                                    std::min(BitWidth, ShAmt + NewBW));
7754     if ((Imm & Mask) == Imm) {
7755       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
7756       if (Opc == ISD::AND)
7757         NewImm ^= APInt::getAllOnesValue(NewBW);
7758       uint64_t PtrOff = ShAmt / 8;
7759       // For big endian targets, we need to adjust the offset to the pointer to
7760       // load the correct bytes.
7761       if (TLI.isBigEndian())
7762         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
7763
7764       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
7765       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
7766       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
7767         return SDValue();
7768
7769       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
7770                                    Ptr.getValueType(), Ptr,
7771                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
7772       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
7773                                   LD->getChain(), NewPtr,
7774                                   LD->getPointerInfo().getWithOffset(PtrOff),
7775                                   LD->isVolatile(), LD->isNonTemporal(),
7776                                   LD->isInvariant(), NewAlign);
7777       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
7778                                    DAG.getConstant(NewImm, NewVT));
7779       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
7780                                    NewVal, NewPtr,
7781                                    ST->getPointerInfo().getWithOffset(PtrOff),
7782                                    false, false, NewAlign);
7783
7784       AddToWorkList(NewPtr.getNode());
7785       AddToWorkList(NewLD.getNode());
7786       AddToWorkList(NewVal.getNode());
7787       WorkListRemover DeadNodes(*this);
7788       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
7789       ++OpsNarrowed;
7790       return NewST;
7791     }
7792   }
7793
7794   return SDValue();
7795 }
7796
7797 /// TransformFPLoadStorePair - For a given floating point load / store pair,
7798 /// if the load value isn't used by any other operations, then consider
7799 /// transforming the pair to integer load / store operations if the target
7800 /// deems the transformation profitable.
7801 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
7802   StoreSDNode *ST  = cast<StoreSDNode>(N);
7803   SDValue Chain = ST->getChain();
7804   SDValue Value = ST->getValue();
7805   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
7806       Value.hasOneUse() &&
7807       Chain == SDValue(Value.getNode(), 1)) {
7808     LoadSDNode *LD = cast<LoadSDNode>(Value);
7809     EVT VT = LD->getMemoryVT();
7810     if (!VT.isFloatingPoint() ||
7811         VT != ST->getMemoryVT() ||
7812         LD->isNonTemporal() ||
7813         ST->isNonTemporal() ||
7814         LD->getPointerInfo().getAddrSpace() != 0 ||
7815         ST->getPointerInfo().getAddrSpace() != 0)
7816       return SDValue();
7817
7818     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7819     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
7820         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
7821         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
7822         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
7823       return SDValue();
7824
7825     unsigned LDAlign = LD->getAlignment();
7826     unsigned STAlign = ST->getAlignment();
7827     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
7828     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
7829     if (LDAlign < ABIAlign || STAlign < ABIAlign)
7830       return SDValue();
7831
7832     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
7833                                 LD->getChain(), LD->getBasePtr(),
7834                                 LD->getPointerInfo(),
7835                                 false, false, false, LDAlign);
7836
7837     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
7838                                  NewLD, ST->getBasePtr(),
7839                                  ST->getPointerInfo(),
7840                                  false, false, STAlign);
7841
7842     AddToWorkList(NewLD.getNode());
7843     AddToWorkList(NewST.getNode());
7844     WorkListRemover DeadNodes(*this);
7845     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
7846     ++LdStFP2Int;
7847     return NewST;
7848   }
7849
7850   return SDValue();
7851 }
7852
7853 /// Helper struct to parse and store a memory address as base + index + offset.
7854 /// We ignore sign extensions when it is safe to do so.
7855 /// The following two expressions are not equivalent. To differentiate we need
7856 /// to store whether there was a sign extension involved in the index
7857 /// computation.
7858 ///  (load (i64 add (i64 copyfromreg %c)
7859 ///                 (i64 signextend (add (i8 load %index)
7860 ///                                      (i8 1))))
7861 /// vs
7862 ///
7863 /// (load (i64 add (i64 copyfromreg %c)
7864 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
7865 ///                                         (i32 1)))))
7866 struct BaseIndexOffset {
7867   SDValue Base;
7868   SDValue Index;
7869   int64_t Offset;
7870   bool IsIndexSignExt;
7871
7872   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
7873
7874   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
7875                   bool IsIndexSignExt) :
7876     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
7877
7878   bool equalBaseIndex(const BaseIndexOffset &Other) {
7879     return Other.Base == Base && Other.Index == Index &&
7880       Other.IsIndexSignExt == IsIndexSignExt;
7881   }
7882
7883   /// Parses tree in Ptr for base, index, offset addresses.
7884   static BaseIndexOffset match(SDValue Ptr) {
7885     bool IsIndexSignExt = false;
7886
7887     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
7888     // instruction, then it could be just the BASE or everything else we don't
7889     // know how to handle. Just use Ptr as BASE and give up.
7890     if (Ptr->getOpcode() != ISD::ADD)
7891       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
7892
7893     // We know that we have at least an ADD instruction. Try to pattern match
7894     // the simple case of BASE + OFFSET.
7895     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
7896       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
7897       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
7898                               IsIndexSignExt);
7899     }
7900
7901     // Inside a loop the current BASE pointer is calculated using an ADD and a
7902     // MUL instruction. In this case Ptr is the actual BASE pointer.
7903     // (i64 add (i64 %array_ptr)
7904     //          (i64 mul (i64 %induction_var)
7905     //                   (i64 %element_size)))
7906     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
7907       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
7908
7909     // Look at Base + Index + Offset cases.
7910     SDValue Base = Ptr->getOperand(0);
7911     SDValue IndexOffset = Ptr->getOperand(1);
7912
7913     // Skip signextends.
7914     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
7915       IndexOffset = IndexOffset->getOperand(0);
7916       IsIndexSignExt = true;
7917     }
7918
7919     // Either the case of Base + Index (no offset) or something else.
7920     if (IndexOffset->getOpcode() != ISD::ADD)
7921       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
7922
7923     // Now we have the case of Base + Index + offset.
7924     SDValue Index = IndexOffset->getOperand(0);
7925     SDValue Offset = IndexOffset->getOperand(1);
7926
7927     if (!isa<ConstantSDNode>(Offset))
7928       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
7929
7930     // Ignore signextends.
7931     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
7932       Index = Index->getOperand(0);
7933       IsIndexSignExt = true;
7934     } else IsIndexSignExt = false;
7935
7936     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
7937     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
7938   }
7939 };
7940
7941 /// Holds a pointer to an LSBaseSDNode as well as information on where it
7942 /// is located in a sequence of memory operations connected by a chain.
7943 struct MemOpLink {
7944   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
7945     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
7946   // Ptr to the mem node.
7947   LSBaseSDNode *MemNode;
7948   // Offset from the base ptr.
7949   int64_t OffsetFromBase;
7950   // What is the sequence number of this mem node.
7951   // Lowest mem operand in the DAG starts at zero.
7952   unsigned SequenceNum;
7953 };
7954
7955 /// Sorts store nodes in a link according to their offset from a shared
7956 // base ptr.
7957 struct ConsecutiveMemoryChainSorter {
7958   bool operator()(MemOpLink LHS, MemOpLink RHS) {
7959     return LHS.OffsetFromBase < RHS.OffsetFromBase;
7960   }
7961 };
7962
7963 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
7964   EVT MemVT = St->getMemoryVT();
7965   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
7966   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
7967     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
7968
7969   // Don't merge vectors into wider inputs.
7970   if (MemVT.isVector() || !MemVT.isSimple())
7971     return false;
7972
7973   // Perform an early exit check. Do not bother looking at stored values that
7974   // are not constants or loads.
7975   SDValue StoredVal = St->getValue();
7976   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
7977   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
7978       !IsLoadSrc)
7979     return false;
7980
7981   // Only look at ends of store sequences.
7982   SDValue Chain = SDValue(St, 1);
7983   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
7984     return false;
7985
7986   // This holds the base pointer, index, and the offset in bytes from the base
7987   // pointer.
7988   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
7989
7990   // We must have a base and an offset.
7991   if (!BasePtr.Base.getNode())
7992     return false;
7993
7994   // Do not handle stores to undef base pointers.
7995   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
7996     return false;
7997
7998   // Save the LoadSDNodes that we find in the chain.
7999   // We need to make sure that these nodes do not interfere with
8000   // any of the store nodes.
8001   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8002
8003   // Save the StoreSDNodes that we find in the chain.
8004   SmallVector<MemOpLink, 8> StoreNodes;
8005
8006   // Walk up the chain and look for nodes with offsets from the same
8007   // base pointer. Stop when reaching an instruction with a different kind
8008   // or instruction which has a different base pointer.
8009   unsigned Seq = 0;
8010   StoreSDNode *Index = St;
8011   while (Index) {
8012     // If the chain has more than one use, then we can't reorder the mem ops.
8013     if (Index != St && !SDValue(Index, 1)->hasOneUse())
8014       break;
8015
8016     // Find the base pointer and offset for this memory node.
8017     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
8018
8019     // Check that the base pointer is the same as the original one.
8020     if (!Ptr.equalBaseIndex(BasePtr))
8021       break;
8022
8023     // Check that the alignment is the same.
8024     if (Index->getAlignment() != St->getAlignment())
8025       break;
8026
8027     // The memory operands must not be volatile.
8028     if (Index->isVolatile() || Index->isIndexed())
8029       break;
8030
8031     // No truncation.
8032     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
8033       if (St->isTruncatingStore())
8034         break;
8035
8036     // The stored memory type must be the same.
8037     if (Index->getMemoryVT() != MemVT)
8038       break;
8039
8040     // We do not allow unaligned stores because we want to prevent overriding
8041     // stores.
8042     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
8043       break;
8044
8045     // We found a potential memory operand to merge.
8046     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
8047
8048     // Find the next memory operand in the chain. If the next operand in the
8049     // chain is a store then move up and continue the scan with the next
8050     // memory operand. If the next operand is a load save it and use alias
8051     // information to check if it interferes with anything.
8052     SDNode *NextInChain = Index->getChain().getNode();
8053     while (1) {
8054       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
8055         // We found a store node. Use it for the next iteration.
8056         Index = STn;
8057         break;
8058       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
8059         // Save the load node for later. Continue the scan.
8060         AliasLoadNodes.push_back(Ldn);
8061         NextInChain = Ldn->getChain().getNode();
8062         continue;
8063       } else {
8064         Index = NULL;
8065         break;
8066       }
8067     }
8068   }
8069
8070   // Check if there is anything to merge.
8071   if (StoreNodes.size() < 2)
8072     return false;
8073
8074   // Sort the memory operands according to their distance from the base pointer.
8075   std::sort(StoreNodes.begin(), StoreNodes.end(),
8076             ConsecutiveMemoryChainSorter());
8077
8078   // Scan the memory operations on the chain and find the first non-consecutive
8079   // store memory address.
8080   unsigned LastConsecutiveStore = 0;
8081   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
8082   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
8083
8084     // Check that the addresses are consecutive starting from the second
8085     // element in the list of stores.
8086     if (i > 0) {
8087       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
8088       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8089         break;
8090     }
8091
8092     bool Alias = false;
8093     // Check if this store interferes with any of the loads that we found.
8094     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
8095       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
8096         Alias = true;
8097         break;
8098       }
8099     // We found a load that alias with this store. Stop the sequence.
8100     if (Alias)
8101       break;
8102
8103     // Mark this node as useful.
8104     LastConsecutiveStore = i;
8105   }
8106
8107   // The node with the lowest store address.
8108   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
8109
8110   // Store the constants into memory as one consecutive store.
8111   if (!IsLoadSrc) {
8112     unsigned LastLegalType = 0;
8113     unsigned LastLegalVectorType = 0;
8114     bool NonZero = false;
8115     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8116       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
8117       SDValue StoredVal = St->getValue();
8118
8119       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
8120         NonZero |= !C->isNullValue();
8121       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
8122         NonZero |= !C->getConstantFPValue()->isNullValue();
8123       } else {
8124         // Non constant.
8125         break;
8126       }
8127
8128       // Find a legal type for the constant store.
8129       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8130       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8131       if (TLI.isTypeLegal(StoreTy))
8132         LastLegalType = i+1;
8133       // Or check whether a truncstore is legal.
8134       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8135                TargetLowering::TypePromoteInteger) {
8136         EVT LegalizedStoredValueTy =
8137           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
8138         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
8139           LastLegalType = i+1;
8140       }
8141
8142       // Find a legal type for the vector store.
8143       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8144       if (TLI.isTypeLegal(Ty))
8145         LastLegalVectorType = i + 1;
8146     }
8147
8148     // We only use vectors if the constant is known to be zero and the
8149     // function is not marked with the noimplicitfloat attribute.
8150     if (NonZero || NoVectors)
8151       LastLegalVectorType = 0;
8152
8153     // Check if we found a legal integer type to store.
8154     if (LastLegalType == 0 && LastLegalVectorType == 0)
8155       return false;
8156
8157     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
8158     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
8159
8160     // Make sure we have something to merge.
8161     if (NumElem < 2)
8162       return false;
8163
8164     unsigned EarliestNodeUsed = 0;
8165     for (unsigned i=0; i < NumElem; ++i) {
8166       // Find a chain for the new wide-store operand. Notice that some
8167       // of the store nodes that we found may not be selected for inclusion
8168       // in the wide store. The chain we use needs to be the chain of the
8169       // earliest store node which is *used* and replaced by the wide store.
8170       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8171         EarliestNodeUsed = i;
8172     }
8173
8174     // The earliest Node in the DAG.
8175     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8176     SDLoc DL(StoreNodes[0].MemNode);
8177
8178     SDValue StoredVal;
8179     if (UseVector) {
8180       // Find a legal type for the vector store.
8181       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8182       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
8183       StoredVal = DAG.getConstant(0, Ty);
8184     } else {
8185       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8186       APInt StoreInt(StoreBW, 0);
8187
8188       // Construct a single integer constant which is made of the smaller
8189       // constant inputs.
8190       bool IsLE = TLI.isLittleEndian();
8191       for (unsigned i = 0; i < NumElem ; ++i) {
8192         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
8193         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
8194         SDValue Val = St->getValue();
8195         StoreInt<<=ElementSizeBytes*8;
8196         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
8197           StoreInt|=C->getAPIntValue().zext(StoreBW);
8198         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
8199           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
8200         } else {
8201           assert(false && "Invalid constant element type");
8202         }
8203       }
8204
8205       // Create the new Load and Store operations.
8206       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8207       StoredVal = DAG.getConstant(StoreInt, StoreTy);
8208     }
8209
8210     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
8211                                     FirstInChain->getBasePtr(),
8212                                     FirstInChain->getPointerInfo(),
8213                                     false, false,
8214                                     FirstInChain->getAlignment());
8215
8216     // Replace the first store with the new store
8217     CombineTo(EarliestOp, NewStore);
8218     // Erase all other stores.
8219     for (unsigned i = 0; i < NumElem ; ++i) {
8220       if (StoreNodes[i].MemNode == EarliestOp)
8221         continue;
8222       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8223       // ReplaceAllUsesWith will replace all uses that existed when it was
8224       // called, but graph optimizations may cause new ones to appear. For
8225       // example, the case in pr14333 looks like
8226       //
8227       //  St's chain -> St -> another store -> X
8228       //
8229       // And the only difference from St to the other store is the chain.
8230       // When we change it's chain to be St's chain they become identical,
8231       // get CSEed and the net result is that X is now a use of St.
8232       // Since we know that St is redundant, just iterate.
8233       while (!St->use_empty())
8234         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
8235       removeFromWorkList(St);
8236       DAG.DeleteNode(St);
8237     }
8238
8239     return true;
8240   }
8241
8242   // Below we handle the case of multiple consecutive stores that
8243   // come from multiple consecutive loads. We merge them into a single
8244   // wide load and a single wide store.
8245
8246   // Look for load nodes which are used by the stored values.
8247   SmallVector<MemOpLink, 8> LoadNodes;
8248
8249   // Find acceptable loads. Loads need to have the same chain (token factor),
8250   // must not be zext, volatile, indexed, and they must be consecutive.
8251   BaseIndexOffset LdBasePtr;
8252   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8253     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
8254     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
8255     if (!Ld) break;
8256
8257     // Loads must only have one use.
8258     if (!Ld->hasNUsesOfValue(1, 0))
8259       break;
8260
8261     // Check that the alignment is the same as the stores.
8262     if (Ld->getAlignment() != St->getAlignment())
8263       break;
8264
8265     // The memory operands must not be volatile.
8266     if (Ld->isVolatile() || Ld->isIndexed())
8267       break;
8268
8269     // We do not accept ext loads.
8270     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
8271       break;
8272
8273     // The stored memory type must be the same.
8274     if (Ld->getMemoryVT() != MemVT)
8275       break;
8276
8277     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
8278     // If this is not the first ptr that we check.
8279     if (LdBasePtr.Base.getNode()) {
8280       // The base ptr must be the same.
8281       if (!LdPtr.equalBaseIndex(LdBasePtr))
8282         break;
8283     } else {
8284       // Check that all other base pointers are the same as this one.
8285       LdBasePtr = LdPtr;
8286     }
8287
8288     // We found a potential memory operand to merge.
8289     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
8290   }
8291
8292   if (LoadNodes.size() < 2)
8293     return false;
8294
8295   // Scan the memory operations on the chain and find the first non-consecutive
8296   // load memory address. These variables hold the index in the store node
8297   // array.
8298   unsigned LastConsecutiveLoad = 0;
8299   // This variable refers to the size and not index in the array.
8300   unsigned LastLegalVectorType = 0;
8301   unsigned LastLegalIntegerType = 0;
8302   StartAddress = LoadNodes[0].OffsetFromBase;
8303   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
8304   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
8305     // All loads much share the same chain.
8306     if (LoadNodes[i].MemNode->getChain() != FirstChain)
8307       break;
8308
8309     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
8310     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8311       break;
8312     LastConsecutiveLoad = i;
8313
8314     // Find a legal type for the vector store.
8315     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8316     if (TLI.isTypeLegal(StoreTy))
8317       LastLegalVectorType = i + 1;
8318
8319     // Find a legal type for the integer store.
8320     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8321     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8322     if (TLI.isTypeLegal(StoreTy))
8323       LastLegalIntegerType = i + 1;
8324     // Or check whether a truncstore and extload is legal.
8325     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8326              TargetLowering::TypePromoteInteger) {
8327       EVT LegalizedStoredValueTy =
8328         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
8329       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
8330           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
8331           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
8332           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
8333         LastLegalIntegerType = i+1;
8334     }
8335   }
8336
8337   // Only use vector types if the vector type is larger than the integer type.
8338   // If they are the same, use integers.
8339   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
8340   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
8341
8342   // We add +1 here because the LastXXX variables refer to location while
8343   // the NumElem refers to array/index size.
8344   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
8345   NumElem = std::min(LastLegalType, NumElem);
8346
8347   if (NumElem < 2)
8348     return false;
8349
8350   // The earliest Node in the DAG.
8351   unsigned EarliestNodeUsed = 0;
8352   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8353   for (unsigned i=1; i<NumElem; ++i) {
8354     // Find a chain for the new wide-store operand. Notice that some
8355     // of the store nodes that we found may not be selected for inclusion
8356     // in the wide store. The chain we use needs to be the chain of the
8357     // earliest store node which is *used* and replaced by the wide store.
8358     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8359       EarliestNodeUsed = i;
8360   }
8361
8362   // Find if it is better to use vectors or integers to load and store
8363   // to memory.
8364   EVT JointMemOpVT;
8365   if (UseVectorTy) {
8366     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8367   } else {
8368     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8369     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8370   }
8371
8372   SDLoc LoadDL(LoadNodes[0].MemNode);
8373   SDLoc StoreDL(StoreNodes[0].MemNode);
8374
8375   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
8376   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
8377                                 FirstLoad->getChain(),
8378                                 FirstLoad->getBasePtr(),
8379                                 FirstLoad->getPointerInfo(),
8380                                 false, false, false,
8381                                 FirstLoad->getAlignment());
8382
8383   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
8384                                   FirstInChain->getBasePtr(),
8385                                   FirstInChain->getPointerInfo(), false, false,
8386                                   FirstInChain->getAlignment());
8387
8388   // Replace one of the loads with the new load.
8389   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
8390   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
8391                                 SDValue(NewLoad.getNode(), 1));
8392
8393   // Remove the rest of the load chains.
8394   for (unsigned i = 1; i < NumElem ; ++i) {
8395     // Replace all chain users of the old load nodes with the chain of the new
8396     // load node.
8397     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
8398     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
8399   }
8400
8401   // Replace the first store with the new store.
8402   CombineTo(EarliestOp, NewStore);
8403   // Erase all other stores.
8404   for (unsigned i = 0; i < NumElem ; ++i) {
8405     // Remove all Store nodes.
8406     if (StoreNodes[i].MemNode == EarliestOp)
8407       continue;
8408     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8409     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
8410     removeFromWorkList(St);
8411     DAG.DeleteNode(St);
8412   }
8413
8414   return true;
8415 }
8416
8417 SDValue DAGCombiner::visitSTORE(SDNode *N) {
8418   StoreSDNode *ST  = cast<StoreSDNode>(N);
8419   SDValue Chain = ST->getChain();
8420   SDValue Value = ST->getValue();
8421   SDValue Ptr   = ST->getBasePtr();
8422
8423   // If this is a store of a bit convert, store the input value if the
8424   // resultant store does not need a higher alignment than the original.
8425   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
8426       ST->isUnindexed()) {
8427     unsigned OrigAlign = ST->getAlignment();
8428     EVT SVT = Value.getOperand(0).getValueType();
8429     unsigned Align = TLI.getDataLayout()->
8430       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
8431     if (Align <= OrigAlign &&
8432         ((!LegalOperations && !ST->isVolatile()) ||
8433          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
8434       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
8435                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
8436                           ST->isNonTemporal(), OrigAlign);
8437   }
8438
8439   // Turn 'store undef, Ptr' -> nothing.
8440   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
8441     return Chain;
8442
8443   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
8444   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
8445     // NOTE: If the original store is volatile, this transform must not increase
8446     // the number of stores.  For example, on x86-32 an f64 can be stored in one
8447     // processor operation but an i64 (which is not legal) requires two.  So the
8448     // transform should not be done in this case.
8449     if (Value.getOpcode() != ISD::TargetConstantFP) {
8450       SDValue Tmp;
8451       switch (CFP->getSimpleValueType(0).SimpleTy) {
8452       default: llvm_unreachable("Unknown FP type");
8453       case MVT::f16:    // We don't do this for these yet.
8454       case MVT::f80:
8455       case MVT::f128:
8456       case MVT::ppcf128:
8457         break;
8458       case MVT::f32:
8459         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
8460             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
8461           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
8462                               bitcastToAPInt().getZExtValue(), MVT::i32);
8463           return DAG.getStore(Chain, SDLoc(N), Tmp,
8464                               Ptr, ST->getPointerInfo(), ST->isVolatile(),
8465                               ST->isNonTemporal(), ST->getAlignment());
8466         }
8467         break;
8468       case MVT::f64:
8469         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
8470              !ST->isVolatile()) ||
8471             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
8472           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
8473                                 getZExtValue(), MVT::i64);
8474           return DAG.getStore(Chain, SDLoc(N), Tmp,
8475                               Ptr, ST->getPointerInfo(), ST->isVolatile(),
8476                               ST->isNonTemporal(), ST->getAlignment());
8477         }
8478
8479         if (!ST->isVolatile() &&
8480             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
8481           // Many FP stores are not made apparent until after legalize, e.g. for
8482           // argument passing.  Since this is so common, custom legalize the
8483           // 64-bit integer store into two 32-bit stores.
8484           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
8485           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
8486           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
8487           if (TLI.isBigEndian()) std::swap(Lo, Hi);
8488
8489           unsigned Alignment = ST->getAlignment();
8490           bool isVolatile = ST->isVolatile();
8491           bool isNonTemporal = ST->isNonTemporal();
8492
8493           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
8494                                      Ptr, ST->getPointerInfo(),
8495                                      isVolatile, isNonTemporal,
8496                                      ST->getAlignment());
8497           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
8498                             DAG.getConstant(4, Ptr.getValueType()));
8499           Alignment = MinAlign(Alignment, 4U);
8500           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
8501                                      Ptr, ST->getPointerInfo().getWithOffset(4),
8502                                      isVolatile, isNonTemporal,
8503                                      Alignment);
8504           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
8505                              St0, St1);
8506         }
8507
8508         break;
8509       }
8510     }
8511   }
8512
8513   // Try to infer better alignment information than the store already has.
8514   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
8515     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8516       if (Align > ST->getAlignment())
8517         return DAG.getTruncStore(Chain, SDLoc(N), Value,
8518                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
8519                                  ST->isVolatile(), ST->isNonTemporal(), Align);
8520     }
8521   }
8522
8523   // Try transforming a pair floating point load / store ops to integer
8524   // load / store ops.
8525   SDValue NewST = TransformFPLoadStorePair(N);
8526   if (NewST.getNode())
8527     return NewST;
8528
8529   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8530     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
8531   if (UseAA) {
8532     // Walk up chain skipping non-aliasing memory nodes.
8533     SDValue BetterChain = FindBetterChain(N, Chain);
8534
8535     // If there is a better chain.
8536     if (Chain != BetterChain) {
8537       SDValue ReplStore;
8538
8539       // Replace the chain to avoid dependency.
8540       if (ST->isTruncatingStore()) {
8541         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
8542                                       ST->getPointerInfo(),
8543                                       ST->getMemoryVT(), ST->isVolatile(),
8544                                       ST->isNonTemporal(), ST->getAlignment());
8545       } else {
8546         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
8547                                  ST->getPointerInfo(),
8548                                  ST->isVolatile(), ST->isNonTemporal(),
8549                                  ST->getAlignment());
8550       }
8551
8552       // Create token to keep both nodes around.
8553       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8554                                   MVT::Other, Chain, ReplStore);
8555
8556       // Make sure the new and old chains are cleaned up.
8557       AddToWorkList(Token.getNode());
8558
8559       // Don't add users to work list.
8560       return CombineTo(N, Token, false);
8561     }
8562   }
8563
8564   // Try transforming N to an indexed store.
8565   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8566     return SDValue(N, 0);
8567
8568   // FIXME: is there such a thing as a truncating indexed store?
8569   if (ST->isTruncatingStore() && ST->isUnindexed() &&
8570       Value.getValueType().isInteger()) {
8571     // See if we can simplify the input to this truncstore with knowledge that
8572     // only the low bits are being used.  For example:
8573     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
8574     SDValue Shorter =
8575       GetDemandedBits(Value,
8576                       APInt::getLowBitsSet(
8577                         Value.getValueType().getScalarType().getSizeInBits(),
8578                         ST->getMemoryVT().getScalarType().getSizeInBits()));
8579     AddToWorkList(Value.getNode());
8580     if (Shorter.getNode())
8581       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
8582                                Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
8583                                ST->isVolatile(), ST->isNonTemporal(),
8584                                ST->getAlignment());
8585
8586     // Otherwise, see if we can simplify the operation with
8587     // SimplifyDemandedBits, which only works if the value has a single use.
8588     if (SimplifyDemandedBits(Value,
8589                         APInt::getLowBitsSet(
8590                           Value.getValueType().getScalarType().getSizeInBits(),
8591                           ST->getMemoryVT().getScalarType().getSizeInBits())))
8592       return SDValue(N, 0);
8593   }
8594
8595   // If this is a load followed by a store to the same location, then the store
8596   // is dead/noop.
8597   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
8598     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
8599         ST->isUnindexed() && !ST->isVolatile() &&
8600         // There can't be any side effects between the load and store, such as
8601         // a call or store.
8602         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
8603       // The store is dead, remove it.
8604       return Chain;
8605     }
8606   }
8607
8608   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
8609   // truncating store.  We can do this even if this is already a truncstore.
8610   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
8611       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
8612       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
8613                             ST->getMemoryVT())) {
8614     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
8615                              Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
8616                              ST->isVolatile(), ST->isNonTemporal(),
8617                              ST->getAlignment());
8618   }
8619
8620   // Only perform this optimization before the types are legal, because we
8621   // don't want to perform this optimization on every DAGCombine invocation.
8622   if (!LegalTypes) {
8623     bool EverChanged = false;
8624
8625     do {
8626       // There can be multiple store sequences on the same chain.
8627       // Keep trying to merge store sequences until we are unable to do so
8628       // or until we merge the last store on the chain.
8629       bool Changed = MergeConsecutiveStores(ST);
8630       EverChanged |= Changed;
8631       if (!Changed) break;
8632     } while (ST->getOpcode() != ISD::DELETED_NODE);
8633
8634     if (EverChanged)
8635       return SDValue(N, 0);
8636   }
8637
8638   return ReduceLoadOpStoreWidth(N);
8639 }
8640
8641 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
8642   SDValue InVec = N->getOperand(0);
8643   SDValue InVal = N->getOperand(1);
8644   SDValue EltNo = N->getOperand(2);
8645   SDLoc dl(N);
8646
8647   // If the inserted element is an UNDEF, just use the input vector.
8648   if (InVal.getOpcode() == ISD::UNDEF)
8649     return InVec;
8650
8651   EVT VT = InVec.getValueType();
8652
8653   // If we can't generate a legal BUILD_VECTOR, exit
8654   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
8655     return SDValue();
8656
8657   // Check that we know which element is being inserted
8658   if (!isa<ConstantSDNode>(EltNo))
8659     return SDValue();
8660   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8661
8662   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
8663   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
8664   // vector elements.
8665   SmallVector<SDValue, 8> Ops;
8666   // Do not combine these two vectors if the output vector will not replace
8667   // the input vector.
8668   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
8669     Ops.append(InVec.getNode()->op_begin(),
8670                InVec.getNode()->op_end());
8671   } else if (InVec.getOpcode() == ISD::UNDEF) {
8672     unsigned NElts = VT.getVectorNumElements();
8673     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
8674   } else {
8675     return SDValue();
8676   }
8677
8678   // Insert the element
8679   if (Elt < Ops.size()) {
8680     // All the operands of BUILD_VECTOR must have the same type;
8681     // we enforce that here.
8682     EVT OpVT = Ops[0].getValueType();
8683     if (InVal.getValueType() != OpVT)
8684       InVal = OpVT.bitsGT(InVal.getValueType()) ?
8685                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
8686                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
8687     Ops[Elt] = InVal;
8688   }
8689
8690   // Return the new vector
8691   return DAG.getNode(ISD::BUILD_VECTOR, dl,
8692                      VT, &Ops[0], Ops.size());
8693 }
8694
8695 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
8696   // (vextract (scalar_to_vector val, 0) -> val
8697   SDValue InVec = N->getOperand(0);
8698   EVT VT = InVec.getValueType();
8699   EVT NVT = N->getValueType(0);
8700
8701   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
8702     // Check if the result type doesn't match the inserted element type. A
8703     // SCALAR_TO_VECTOR may truncate the inserted element and the
8704     // EXTRACT_VECTOR_ELT may widen the extracted vector.
8705     SDValue InOp = InVec.getOperand(0);
8706     if (InOp.getValueType() != NVT) {
8707       assert(InOp.getValueType().isInteger() && NVT.isInteger());
8708       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
8709     }
8710     return InOp;
8711   }
8712
8713   SDValue EltNo = N->getOperand(1);
8714   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
8715
8716   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
8717   // We only perform this optimization before the op legalization phase because
8718   // we may introduce new vector instructions which are not backed by TD
8719   // patterns. For example on AVX, extracting elements from a wide vector
8720   // without using extract_subvector.
8721   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
8722       && ConstEltNo && !LegalOperations) {
8723     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8724     int NumElem = VT.getVectorNumElements();
8725     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
8726     // Find the new index to extract from.
8727     int OrigElt = SVOp->getMaskElt(Elt);
8728
8729     // Extracting an undef index is undef.
8730     if (OrigElt == -1)
8731       return DAG.getUNDEF(NVT);
8732
8733     // Select the right vector half to extract from.
8734     if (OrigElt < NumElem) {
8735       InVec = InVec->getOperand(0);
8736     } else {
8737       InVec = InVec->getOperand(1);
8738       OrigElt -= NumElem;
8739     }
8740
8741     EVT IndexTy = TLI.getVectorIdxTy();
8742     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
8743                        InVec, DAG.getConstant(OrigElt, IndexTy));
8744   }
8745
8746   // Perform only after legalization to ensure build_vector / vector_shuffle
8747   // optimizations have already been done.
8748   if (!LegalOperations) return SDValue();
8749
8750   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
8751   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
8752   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
8753
8754   if (ConstEltNo) {
8755     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8756     bool NewLoad = false;
8757     bool BCNumEltsChanged = false;
8758     EVT ExtVT = VT.getVectorElementType();
8759     EVT LVT = ExtVT;
8760
8761     // If the result of load has to be truncated, then it's not necessarily
8762     // profitable.
8763     if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
8764       return SDValue();
8765
8766     if (InVec.getOpcode() == ISD::BITCAST) {
8767       // Don't duplicate a load with other uses.
8768       if (!InVec.hasOneUse())
8769         return SDValue();
8770
8771       EVT BCVT = InVec.getOperand(0).getValueType();
8772       if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
8773         return SDValue();
8774       if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
8775         BCNumEltsChanged = true;
8776       InVec = InVec.getOperand(0);
8777       ExtVT = BCVT.getVectorElementType();
8778       NewLoad = true;
8779     }
8780
8781     LoadSDNode *LN0 = NULL;
8782     const ShuffleVectorSDNode *SVN = NULL;
8783     if (ISD::isNormalLoad(InVec.getNode())) {
8784       LN0 = cast<LoadSDNode>(InVec);
8785     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8786                InVec.getOperand(0).getValueType() == ExtVT &&
8787                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
8788       // Don't duplicate a load with other uses.
8789       if (!InVec.hasOneUse())
8790         return SDValue();
8791
8792       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
8793     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
8794       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
8795       // =>
8796       // (load $addr+1*size)
8797
8798       // Don't duplicate a load with other uses.
8799       if (!InVec.hasOneUse())
8800         return SDValue();
8801
8802       // If the bit convert changed the number of elements, it is unsafe
8803       // to examine the mask.
8804       if (BCNumEltsChanged)
8805         return SDValue();
8806
8807       // Select the input vector, guarding against out of range extract vector.
8808       unsigned NumElems = VT.getVectorNumElements();
8809       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
8810       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
8811
8812       if (InVec.getOpcode() == ISD::BITCAST) {
8813         // Don't duplicate a load with other uses.
8814         if (!InVec.hasOneUse())
8815           return SDValue();
8816
8817         InVec = InVec.getOperand(0);
8818       }
8819       if (ISD::isNormalLoad(InVec.getNode())) {
8820         LN0 = cast<LoadSDNode>(InVec);
8821         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
8822       }
8823     }
8824
8825     // Make sure we found a non-volatile load and the extractelement is
8826     // the only use.
8827     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
8828       return SDValue();
8829
8830     // If Idx was -1 above, Elt is going to be -1, so just return undef.
8831     if (Elt == -1)
8832       return DAG.getUNDEF(LVT);
8833
8834     unsigned Align = LN0->getAlignment();
8835     if (NewLoad) {
8836       // Check the resultant load doesn't need a higher alignment than the
8837       // original load.
8838       unsigned NewAlign =
8839         TLI.getDataLayout()
8840             ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
8841
8842       if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
8843         return SDValue();
8844
8845       Align = NewAlign;
8846     }
8847
8848     SDValue NewPtr = LN0->getBasePtr();
8849     unsigned PtrOff = 0;
8850
8851     if (Elt) {
8852       PtrOff = LVT.getSizeInBits() * Elt / 8;
8853       EVT PtrType = NewPtr.getValueType();
8854       if (TLI.isBigEndian())
8855         PtrOff = VT.getSizeInBits() / 8 - PtrOff;
8856       NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
8857                            DAG.getConstant(PtrOff, PtrType));
8858     }
8859
8860     // The replacement we need to do here is a little tricky: we need to
8861     // replace an extractelement of a load with a load.
8862     // Use ReplaceAllUsesOfValuesWith to do the replacement.
8863     // Note that this replacement assumes that the extractvalue is the only
8864     // use of the load; that's okay because we don't want to perform this
8865     // transformation in other cases anyway.
8866     SDValue Load;
8867     SDValue Chain;
8868     if (NVT.bitsGT(LVT)) {
8869       // If the result type of vextract is wider than the load, then issue an
8870       // extending load instead.
8871       ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
8872         ? ISD::ZEXTLOAD : ISD::EXTLOAD;
8873       Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
8874                             NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
8875                             LVT, LN0->isVolatile(), LN0->isNonTemporal(),Align);
8876       Chain = Load.getValue(1);
8877     } else {
8878       Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
8879                          LN0->getPointerInfo().getWithOffset(PtrOff),
8880                          LN0->isVolatile(), LN0->isNonTemporal(),
8881                          LN0->isInvariant(), Align);
8882       Chain = Load.getValue(1);
8883       if (NVT.bitsLT(LVT))
8884         Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
8885       else
8886         Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
8887     }
8888     WorkListRemover DeadNodes(*this);
8889     SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
8890     SDValue To[] = { Load, Chain };
8891     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8892     // Since we're explcitly calling ReplaceAllUses, add the new node to the
8893     // worklist explicitly as well.
8894     AddToWorkList(Load.getNode());
8895     AddUsersToWorkList(Load.getNode()); // Add users too
8896     // Make sure to revisit this node to clean it up; it will usually be dead.
8897     AddToWorkList(N);
8898     return SDValue(N, 0);
8899   }
8900
8901   return SDValue();
8902 }
8903
8904 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
8905 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
8906   // We perform this optimization post type-legalization because
8907   // the type-legalizer often scalarizes integer-promoted vectors.
8908   // Performing this optimization before may create bit-casts which
8909   // will be type-legalized to complex code sequences.
8910   // We perform this optimization only before the operation legalizer because we
8911   // may introduce illegal operations.
8912   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
8913     return SDValue();
8914
8915   unsigned NumInScalars = N->getNumOperands();
8916   SDLoc dl(N);
8917   EVT VT = N->getValueType(0);
8918
8919   // Check to see if this is a BUILD_VECTOR of a bunch of values
8920   // which come from any_extend or zero_extend nodes. If so, we can create
8921   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
8922   // optimizations. We do not handle sign-extend because we can't fill the sign
8923   // using shuffles.
8924   EVT SourceType = MVT::Other;
8925   bool AllAnyExt = true;
8926
8927   for (unsigned i = 0; i != NumInScalars; ++i) {
8928     SDValue In = N->getOperand(i);
8929     // Ignore undef inputs.
8930     if (In.getOpcode() == ISD::UNDEF) continue;
8931
8932     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
8933     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
8934
8935     // Abort if the element is not an extension.
8936     if (!ZeroExt && !AnyExt) {
8937       SourceType = MVT::Other;
8938       break;
8939     }
8940
8941     // The input is a ZeroExt or AnyExt. Check the original type.
8942     EVT InTy = In.getOperand(0).getValueType();
8943
8944     // Check that all of the widened source types are the same.
8945     if (SourceType == MVT::Other)
8946       // First time.
8947       SourceType = InTy;
8948     else if (InTy != SourceType) {
8949       // Multiple income types. Abort.
8950       SourceType = MVT::Other;
8951       break;
8952     }
8953
8954     // Check if all of the extends are ANY_EXTENDs.
8955     AllAnyExt &= AnyExt;
8956   }
8957
8958   // In order to have valid types, all of the inputs must be extended from the
8959   // same source type and all of the inputs must be any or zero extend.
8960   // Scalar sizes must be a power of two.
8961   EVT OutScalarTy = VT.getScalarType();
8962   bool ValidTypes = SourceType != MVT::Other &&
8963                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
8964                  isPowerOf2_32(SourceType.getSizeInBits());
8965
8966   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
8967   // turn into a single shuffle instruction.
8968   if (!ValidTypes)
8969     return SDValue();
8970
8971   bool isLE = TLI.isLittleEndian();
8972   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
8973   assert(ElemRatio > 1 && "Invalid element size ratio");
8974   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
8975                                DAG.getConstant(0, SourceType);
8976
8977   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
8978   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
8979
8980   // Populate the new build_vector
8981   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
8982     SDValue Cast = N->getOperand(i);
8983     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
8984             Cast.getOpcode() == ISD::ZERO_EXTEND ||
8985             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
8986     SDValue In;
8987     if (Cast.getOpcode() == ISD::UNDEF)
8988       In = DAG.getUNDEF(SourceType);
8989     else
8990       In = Cast->getOperand(0);
8991     unsigned Index = isLE ? (i * ElemRatio) :
8992                             (i * ElemRatio + (ElemRatio - 1));
8993
8994     assert(Index < Ops.size() && "Invalid index");
8995     Ops[Index] = In;
8996   }
8997
8998   // The type of the new BUILD_VECTOR node.
8999   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
9000   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
9001          "Invalid vector size");
9002   // Check if the new vector type is legal.
9003   if (!isTypeLegal(VecVT)) return SDValue();
9004
9005   // Make the new BUILD_VECTOR.
9006   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
9007
9008   // The new BUILD_VECTOR node has the potential to be further optimized.
9009   AddToWorkList(BV.getNode());
9010   // Bitcast to the desired type.
9011   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9012 }
9013
9014 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
9015   EVT VT = N->getValueType(0);
9016
9017   unsigned NumInScalars = N->getNumOperands();
9018   SDLoc dl(N);
9019
9020   EVT SrcVT = MVT::Other;
9021   unsigned Opcode = ISD::DELETED_NODE;
9022   unsigned NumDefs = 0;
9023
9024   for (unsigned i = 0; i != NumInScalars; ++i) {
9025     SDValue In = N->getOperand(i);
9026     unsigned Opc = In.getOpcode();
9027
9028     if (Opc == ISD::UNDEF)
9029       continue;
9030
9031     // If all scalar values are floats and converted from integers.
9032     if (Opcode == ISD::DELETED_NODE &&
9033         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
9034       Opcode = Opc;
9035     }
9036
9037     if (Opc != Opcode)
9038       return SDValue();
9039
9040     EVT InVT = In.getOperand(0).getValueType();
9041
9042     // If all scalar values are typed differently, bail out. It's chosen to
9043     // simplify BUILD_VECTOR of integer types.
9044     if (SrcVT == MVT::Other)
9045       SrcVT = InVT;
9046     if (SrcVT != InVT)
9047       return SDValue();
9048     NumDefs++;
9049   }
9050
9051   // If the vector has just one element defined, it's not worth to fold it into
9052   // a vectorized one.
9053   if (NumDefs < 2)
9054     return SDValue();
9055
9056   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
9057          && "Should only handle conversion from integer to float.");
9058   assert(SrcVT != MVT::Other && "Cannot determine source type!");
9059
9060   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
9061
9062   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
9063     return SDValue();
9064
9065   SmallVector<SDValue, 8> Opnds;
9066   for (unsigned i = 0; i != NumInScalars; ++i) {
9067     SDValue In = N->getOperand(i);
9068
9069     if (In.getOpcode() == ISD::UNDEF)
9070       Opnds.push_back(DAG.getUNDEF(SrcVT));
9071     else
9072       Opnds.push_back(In.getOperand(0));
9073   }
9074   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
9075                            &Opnds[0], Opnds.size());
9076   AddToWorkList(BV.getNode());
9077
9078   return DAG.getNode(Opcode, dl, VT, BV);
9079 }
9080
9081 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
9082   unsigned NumInScalars = N->getNumOperands();
9083   SDLoc dl(N);
9084   EVT VT = N->getValueType(0);
9085
9086   // A vector built entirely of undefs is undef.
9087   if (ISD::allOperandsUndef(N))
9088     return DAG.getUNDEF(VT);
9089
9090   SDValue V = reduceBuildVecExtToExtBuildVec(N);
9091   if (V.getNode())
9092     return V;
9093
9094   V = reduceBuildVecConvertToConvertBuildVec(N);
9095   if (V.getNode())
9096     return V;
9097
9098   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
9099   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
9100   // at most two distinct vectors, turn this into a shuffle node.
9101
9102   // May only combine to shuffle after legalize if shuffle is legal.
9103   if (LegalOperations &&
9104       !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
9105     return SDValue();
9106
9107   SDValue VecIn1, VecIn2;
9108   for (unsigned i = 0; i != NumInScalars; ++i) {
9109     // Ignore undef inputs.
9110     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
9111
9112     // If this input is something other than a EXTRACT_VECTOR_ELT with a
9113     // constant index, bail out.
9114     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9115         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
9116       VecIn1 = VecIn2 = SDValue(0, 0);
9117       break;
9118     }
9119
9120     // We allow up to two distinct input vectors.
9121     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
9122     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
9123       continue;
9124
9125     if (VecIn1.getNode() == 0) {
9126       VecIn1 = ExtractedFromVec;
9127     } else if (VecIn2.getNode() == 0) {
9128       VecIn2 = ExtractedFromVec;
9129     } else {
9130       // Too many inputs.
9131       VecIn1 = VecIn2 = SDValue(0, 0);
9132       break;
9133     }
9134   }
9135
9136     // If everything is good, we can make a shuffle operation.
9137   if (VecIn1.getNode()) {
9138     SmallVector<int, 8> Mask;
9139     for (unsigned i = 0; i != NumInScalars; ++i) {
9140       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
9141         Mask.push_back(-1);
9142         continue;
9143       }
9144
9145       // If extracting from the first vector, just use the index directly.
9146       SDValue Extract = N->getOperand(i);
9147       SDValue ExtVal = Extract.getOperand(1);
9148       if (Extract.getOperand(0) == VecIn1) {
9149         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9150         if (ExtIndex > VT.getVectorNumElements())
9151           return SDValue();
9152
9153         Mask.push_back(ExtIndex);
9154         continue;
9155       }
9156
9157       // Otherwise, use InIdx + VecSize
9158       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9159       Mask.push_back(Idx+NumInScalars);
9160     }
9161
9162     // We can't generate a shuffle node with mismatched input and output types.
9163     // Attempt to transform a single input vector to the correct type.
9164     if ((VT != VecIn1.getValueType())) {
9165       // We don't support shuffeling between TWO values of different types.
9166       if (VecIn2.getNode() != 0)
9167         return SDValue();
9168
9169       // We only support widening of vectors which are half the size of the
9170       // output registers. For example XMM->YMM widening on X86 with AVX.
9171       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
9172         return SDValue();
9173
9174       // If the input vector type has a different base type to the output
9175       // vector type, bail out.
9176       if (VecIn1.getValueType().getVectorElementType() !=
9177           VT.getVectorElementType())
9178         return SDValue();
9179
9180       // Widen the input vector by adding undef values.
9181       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9182                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
9183     }
9184
9185     // If VecIn2 is unused then change it to undef.
9186     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
9187
9188     // Check that we were able to transform all incoming values to the same
9189     // type.
9190     if (VecIn2.getValueType() != VecIn1.getValueType() ||
9191         VecIn1.getValueType() != VT)
9192           return SDValue();
9193
9194     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
9195     if (!isTypeLegal(VT))
9196       return SDValue();
9197
9198     // Return the new VECTOR_SHUFFLE node.
9199     SDValue Ops[2];
9200     Ops[0] = VecIn1;
9201     Ops[1] = VecIn2;
9202     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
9203   }
9204
9205   return SDValue();
9206 }
9207
9208 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
9209   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
9210   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
9211   // inputs come from at most two distinct vectors, turn this into a shuffle
9212   // node.
9213
9214   // If we only have one input vector, we don't need to do any concatenation.
9215   if (N->getNumOperands() == 1)
9216     return N->getOperand(0);
9217
9218   // Check if all of the operands are undefs.
9219   if (ISD::allOperandsUndef(N))
9220     return DAG.getUNDEF(N->getValueType(0));
9221
9222   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
9223   // nodes often generate nop CONCAT_VECTOR nodes.
9224   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
9225   // place the incoming vectors at the exact same location.
9226   SDValue SingleSource = SDValue();
9227   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
9228
9229   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9230     SDValue Op = N->getOperand(i);
9231
9232     if (Op.getOpcode() == ISD::UNDEF)
9233       continue;
9234
9235     // Check if this is the identity extract:
9236     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
9237       return SDValue();
9238
9239     // Find the single incoming vector for the extract_subvector.
9240     if (SingleSource.getNode()) {
9241       if (Op.getOperand(0) != SingleSource)
9242         return SDValue();
9243     } else {
9244       SingleSource = Op.getOperand(0);
9245
9246       // Check the source type is the same as the type of the result.
9247       // If not, this concat may extend the vector, so we can not
9248       // optimize it away.
9249       if (SingleSource.getValueType() != N->getValueType(0))
9250         return SDValue();
9251     }
9252
9253     unsigned IdentityIndex = i * PartNumElem;
9254     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9255     // The extract index must be constant.
9256     if (!CS)
9257       return SDValue();
9258
9259     // Check that we are reading from the identity index.
9260     if (CS->getZExtValue() != IdentityIndex)
9261       return SDValue();
9262   }
9263
9264   if (SingleSource.getNode())
9265     return SingleSource;
9266
9267   return SDValue();
9268 }
9269
9270 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
9271   EVT NVT = N->getValueType(0);
9272   SDValue V = N->getOperand(0);
9273
9274   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
9275     // Combine:
9276     //    (extract_subvec (concat V1, V2, ...), i)
9277     // Into:
9278     //    Vi if possible
9279     // Only operand 0 is checked as 'concat' assumes all inputs of the same type.
9280     if (V->getOperand(0).getValueType() != NVT)
9281       return SDValue();
9282     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9283     unsigned NumElems = NVT.getVectorNumElements();
9284     assert((Idx % NumElems) == 0 &&
9285            "IDX in concat is not a multiple of the result vector length.");
9286     return V->getOperand(Idx / NumElems);
9287   }
9288
9289   // Skip bitcasting
9290   if (V->getOpcode() == ISD::BITCAST)
9291     V = V.getOperand(0);
9292
9293   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
9294     SDLoc dl(N);
9295     // Handle only simple case where vector being inserted and vector
9296     // being extracted are of same type, and are half size of larger vectors.
9297     EVT BigVT = V->getOperand(0).getValueType();
9298     EVT SmallVT = V->getOperand(1).getValueType();
9299     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
9300       return SDValue();
9301
9302     // Only handle cases where both indexes are constants with the same type.
9303     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
9304     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
9305
9306     if (InsIdx && ExtIdx &&
9307         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
9308         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
9309       // Combine:
9310       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
9311       // Into:
9312       //    indices are equal or bit offsets are equal => V1
9313       //    otherwise => (extract_subvec V1, ExtIdx)
9314       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
9315           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
9316         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
9317       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
9318                          DAG.getNode(ISD::BITCAST, dl,
9319                                      N->getOperand(0).getValueType(),
9320                                      V->getOperand(0)), N->getOperand(1));
9321     }
9322   }
9323
9324   return SDValue();
9325 }
9326
9327 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
9328 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
9329   EVT VT = N->getValueType(0);
9330   unsigned NumElts = VT.getVectorNumElements();
9331
9332   SDValue N0 = N->getOperand(0);
9333   SDValue N1 = N->getOperand(1);
9334   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9335
9336   SmallVector<SDValue, 4> Ops;
9337   EVT ConcatVT = N0.getOperand(0).getValueType();
9338   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
9339   unsigned NumConcats = NumElts / NumElemsPerConcat;
9340
9341   // Look at every vector that's inserted. We're looking for exact
9342   // subvector-sized copies from a concatenated vector
9343   for (unsigned I = 0; I != NumConcats; ++I) {
9344     // Make sure we're dealing with a copy.
9345     unsigned Begin = I * NumElemsPerConcat;
9346     bool AllUndef = true, NoUndef = true;
9347     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
9348       if (SVN->getMaskElt(J) >= 0)
9349         AllUndef = false;
9350       else
9351         NoUndef = false;
9352     }
9353
9354     if (NoUndef) {
9355       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
9356         return SDValue();
9357
9358       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
9359         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
9360           return SDValue();
9361
9362       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
9363       if (FirstElt < N0.getNumOperands())
9364         Ops.push_back(N0.getOperand(FirstElt));
9365       else
9366         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
9367
9368     } else if (AllUndef) {
9369       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
9370     } else { // Mixed with general masks and undefs, can't do optimization.
9371       return SDValue();
9372     }
9373   }
9374
9375   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
9376                      Ops.size());
9377 }
9378
9379 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
9380   EVT VT = N->getValueType(0);
9381   unsigned NumElts = VT.getVectorNumElements();
9382
9383   SDValue N0 = N->getOperand(0);
9384   SDValue N1 = N->getOperand(1);
9385
9386   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
9387
9388   // Canonicalize shuffle undef, undef -> undef
9389   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
9390     return DAG.getUNDEF(VT);
9391
9392   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9393
9394   // Canonicalize shuffle v, v -> v, undef
9395   if (N0 == N1) {
9396     SmallVector<int, 8> NewMask;
9397     for (unsigned i = 0; i != NumElts; ++i) {
9398       int Idx = SVN->getMaskElt(i);
9399       if (Idx >= (int)NumElts) Idx -= NumElts;
9400       NewMask.push_back(Idx);
9401     }
9402     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
9403                                 &NewMask[0]);
9404   }
9405
9406   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
9407   if (N0.getOpcode() == ISD::UNDEF) {
9408     SmallVector<int, 8> NewMask;
9409     for (unsigned i = 0; i != NumElts; ++i) {
9410       int Idx = SVN->getMaskElt(i);
9411       if (Idx >= 0) {
9412         if (Idx >= (int)NumElts)
9413           Idx -= NumElts;
9414         else
9415           Idx = -1; // remove reference to lhs
9416       }
9417       NewMask.push_back(Idx);
9418     }
9419     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
9420                                 &NewMask[0]);
9421   }
9422
9423   // Remove references to rhs if it is undef
9424   if (N1.getOpcode() == ISD::UNDEF) {
9425     bool Changed = false;
9426     SmallVector<int, 8> NewMask;
9427     for (unsigned i = 0; i != NumElts; ++i) {
9428       int Idx = SVN->getMaskElt(i);
9429       if (Idx >= (int)NumElts) {
9430         Idx = -1;
9431         Changed = true;
9432       }
9433       NewMask.push_back(Idx);
9434     }
9435     if (Changed)
9436       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
9437   }
9438
9439   // If it is a splat, check if the argument vector is another splat or a
9440   // build_vector with all scalar elements the same.
9441   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
9442     SDNode *V = N0.getNode();
9443
9444     // If this is a bit convert that changes the element type of the vector but
9445     // not the number of vector elements, look through it.  Be careful not to
9446     // look though conversions that change things like v4f32 to v2f64.
9447     if (V->getOpcode() == ISD::BITCAST) {
9448       SDValue ConvInput = V->getOperand(0);
9449       if (ConvInput.getValueType().isVector() &&
9450           ConvInput.getValueType().getVectorNumElements() == NumElts)
9451         V = ConvInput.getNode();
9452     }
9453
9454     if (V->getOpcode() == ISD::BUILD_VECTOR) {
9455       assert(V->getNumOperands() == NumElts &&
9456              "BUILD_VECTOR has wrong number of operands");
9457       SDValue Base;
9458       bool AllSame = true;
9459       for (unsigned i = 0; i != NumElts; ++i) {
9460         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
9461           Base = V->getOperand(i);
9462           break;
9463         }
9464       }
9465       // Splat of <u, u, u, u>, return <u, u, u, u>
9466       if (!Base.getNode())
9467         return N0;
9468       for (unsigned i = 0; i != NumElts; ++i) {
9469         if (V->getOperand(i) != Base) {
9470           AllSame = false;
9471           break;
9472         }
9473       }
9474       // Splat of <x, x, x, x>, return <x, x, x, x>
9475       if (AllSame)
9476         return N0;
9477     }
9478   }
9479
9480   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
9481       Level < AfterLegalizeVectorOps &&
9482       (N1.getOpcode() == ISD::UNDEF ||
9483       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
9484        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
9485     SDValue V = partitionShuffleOfConcats(N, DAG);
9486
9487     if (V.getNode())
9488       return V;
9489   }
9490
9491   // If this shuffle node is simply a swizzle of another shuffle node,
9492   // and it reverses the swizzle of the previous shuffle then we can
9493   // optimize shuffle(shuffle(x, undef), undef) -> x.
9494   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
9495       N1.getOpcode() == ISD::UNDEF) {
9496
9497     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
9498
9499     // Shuffle nodes can only reverse shuffles with a single non-undef value.
9500     if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
9501       return SDValue();
9502
9503     // The incoming shuffle must be of the same type as the result of the
9504     // current shuffle.
9505     assert(OtherSV->getOperand(0).getValueType() == VT &&
9506            "Shuffle types don't match");
9507
9508     for (unsigned i = 0; i != NumElts; ++i) {
9509       int Idx = SVN->getMaskElt(i);
9510       assert(Idx < (int)NumElts && "Index references undef operand");
9511       // Next, this index comes from the first value, which is the incoming
9512       // shuffle. Adopt the incoming index.
9513       if (Idx >= 0)
9514         Idx = OtherSV->getMaskElt(Idx);
9515
9516       // The combined shuffle must map each index to itself.
9517       if (Idx >= 0 && (unsigned)Idx != i)
9518         return SDValue();
9519     }
9520
9521     return OtherSV->getOperand(0);
9522   }
9523
9524   return SDValue();
9525 }
9526
9527 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
9528 /// an AND to a vector_shuffle with the destination vector and a zero vector.
9529 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
9530 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
9531 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
9532   EVT VT = N->getValueType(0);
9533   SDLoc dl(N);
9534   SDValue LHS = N->getOperand(0);
9535   SDValue RHS = N->getOperand(1);
9536   if (N->getOpcode() == ISD::AND) {
9537     if (RHS.getOpcode() == ISD::BITCAST)
9538       RHS = RHS.getOperand(0);
9539     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
9540       SmallVector<int, 8> Indices;
9541       unsigned NumElts = RHS.getNumOperands();
9542       for (unsigned i = 0; i != NumElts; ++i) {
9543         SDValue Elt = RHS.getOperand(i);
9544         if (!isa<ConstantSDNode>(Elt))
9545           return SDValue();
9546
9547         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
9548           Indices.push_back(i);
9549         else if (cast<ConstantSDNode>(Elt)->isNullValue())
9550           Indices.push_back(NumElts);
9551         else
9552           return SDValue();
9553       }
9554
9555       // Let's see if the target supports this vector_shuffle.
9556       EVT RVT = RHS.getValueType();
9557       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
9558         return SDValue();
9559
9560       // Return the new VECTOR_SHUFFLE node.
9561       EVT EltVT = RVT.getVectorElementType();
9562       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
9563                                      DAG.getConstant(0, EltVT));
9564       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
9565                                  RVT, &ZeroOps[0], ZeroOps.size());
9566       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
9567       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
9568       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
9569     }
9570   }
9571
9572   return SDValue();
9573 }
9574
9575 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
9576 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
9577   assert(N->getValueType(0).isVector() &&
9578          "SimplifyVBinOp only works on vectors!");
9579
9580   SDValue LHS = N->getOperand(0);
9581   SDValue RHS = N->getOperand(1);
9582   SDValue Shuffle = XformToShuffleWithZero(N);
9583   if (Shuffle.getNode()) return Shuffle;
9584
9585   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
9586   // this operation.
9587   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
9588       RHS.getOpcode() == ISD::BUILD_VECTOR) {
9589     SmallVector<SDValue, 8> Ops;
9590     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
9591       SDValue LHSOp = LHS.getOperand(i);
9592       SDValue RHSOp = RHS.getOperand(i);
9593       // If these two elements can't be folded, bail out.
9594       if ((LHSOp.getOpcode() != ISD::UNDEF &&
9595            LHSOp.getOpcode() != ISD::Constant &&
9596            LHSOp.getOpcode() != ISD::ConstantFP) ||
9597           (RHSOp.getOpcode() != ISD::UNDEF &&
9598            RHSOp.getOpcode() != ISD::Constant &&
9599            RHSOp.getOpcode() != ISD::ConstantFP))
9600         break;
9601
9602       // Can't fold divide by zero.
9603       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
9604           N->getOpcode() == ISD::FDIV) {
9605         if ((RHSOp.getOpcode() == ISD::Constant &&
9606              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
9607             (RHSOp.getOpcode() == ISD::ConstantFP &&
9608              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
9609           break;
9610       }
9611
9612       EVT VT = LHSOp.getValueType();
9613       EVT RVT = RHSOp.getValueType();
9614       if (RVT != VT) {
9615         // Integer BUILD_VECTOR operands may have types larger than the element
9616         // size (e.g., when the element type is not legal).  Prior to type
9617         // legalization, the types may not match between the two BUILD_VECTORS.
9618         // Truncate one of the operands to make them match.
9619         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
9620           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
9621         } else {
9622           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
9623           VT = RVT;
9624         }
9625       }
9626       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
9627                                    LHSOp, RHSOp);
9628       if (FoldOp.getOpcode() != ISD::UNDEF &&
9629           FoldOp.getOpcode() != ISD::Constant &&
9630           FoldOp.getOpcode() != ISD::ConstantFP)
9631         break;
9632       Ops.push_back(FoldOp);
9633       AddToWorkList(FoldOp.getNode());
9634     }
9635
9636     if (Ops.size() == LHS.getNumOperands())
9637       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
9638                          LHS.getValueType(), &Ops[0], Ops.size());
9639   }
9640
9641   return SDValue();
9642 }
9643
9644 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
9645 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
9646   assert(N->getValueType(0).isVector() &&
9647          "SimplifyVUnaryOp only works on vectors!");
9648
9649   SDValue N0 = N->getOperand(0);
9650
9651   if (N0.getOpcode() != ISD::BUILD_VECTOR)
9652     return SDValue();
9653
9654   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
9655   SmallVector<SDValue, 8> Ops;
9656   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
9657     SDValue Op = N0.getOperand(i);
9658     if (Op.getOpcode() != ISD::UNDEF &&
9659         Op.getOpcode() != ISD::ConstantFP)
9660       break;
9661     EVT EltVT = Op.getValueType();
9662     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
9663     if (FoldOp.getOpcode() != ISD::UNDEF &&
9664         FoldOp.getOpcode() != ISD::ConstantFP)
9665       break;
9666     Ops.push_back(FoldOp);
9667     AddToWorkList(FoldOp.getNode());
9668   }
9669
9670   if (Ops.size() != N0.getNumOperands())
9671     return SDValue();
9672
9673   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
9674                      N0.getValueType(), &Ops[0], Ops.size());
9675 }
9676
9677 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
9678                                     SDValue N1, SDValue N2){
9679   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
9680
9681   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
9682                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
9683
9684   // If we got a simplified select_cc node back from SimplifySelectCC, then
9685   // break it down into a new SETCC node, and a new SELECT node, and then return
9686   // the SELECT node, since we were called with a SELECT node.
9687   if (SCC.getNode()) {
9688     // Check to see if we got a select_cc back (to turn into setcc/select).
9689     // Otherwise, just return whatever node we got back, like fabs.
9690     if (SCC.getOpcode() == ISD::SELECT_CC) {
9691       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
9692                                   N0.getValueType(),
9693                                   SCC.getOperand(0), SCC.getOperand(1),
9694                                   SCC.getOperand(4));
9695       AddToWorkList(SETCC.getNode());
9696       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
9697                            SCC.getOperand(2), SCC.getOperand(3), SETCC);
9698     }
9699
9700     return SCC;
9701   }
9702   return SDValue();
9703 }
9704
9705 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
9706 /// are the two values being selected between, see if we can simplify the
9707 /// select.  Callers of this should assume that TheSelect is deleted if this
9708 /// returns true.  As such, they should return the appropriate thing (e.g. the
9709 /// node) back to the top-level of the DAG combiner loop to avoid it being
9710 /// looked at.
9711 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
9712                                     SDValue RHS) {
9713
9714   // Cannot simplify select with vector condition
9715   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
9716
9717   // If this is a select from two identical things, try to pull the operation
9718   // through the select.
9719   if (LHS.getOpcode() != RHS.getOpcode() ||
9720       !LHS.hasOneUse() || !RHS.hasOneUse())
9721     return false;
9722
9723   // If this is a load and the token chain is identical, replace the select
9724   // of two loads with a load through a select of the address to load from.
9725   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
9726   // constants have been dropped into the constant pool.
9727   if (LHS.getOpcode() == ISD::LOAD) {
9728     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
9729     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
9730
9731     // Token chains must be identical.
9732     if (LHS.getOperand(0) != RHS.getOperand(0) ||
9733         // Do not let this transformation reduce the number of volatile loads.
9734         LLD->isVolatile() || RLD->isVolatile() ||
9735         // If this is an EXTLOAD, the VT's must match.
9736         LLD->getMemoryVT() != RLD->getMemoryVT() ||
9737         // If this is an EXTLOAD, the kind of extension must match.
9738         (LLD->getExtensionType() != RLD->getExtensionType() &&
9739          // The only exception is if one of the extensions is anyext.
9740          LLD->getExtensionType() != ISD::EXTLOAD &&
9741          RLD->getExtensionType() != ISD::EXTLOAD) ||
9742         // FIXME: this discards src value information.  This is
9743         // over-conservative. It would be beneficial to be able to remember
9744         // both potential memory locations.  Since we are discarding
9745         // src value info, don't do the transformation if the memory
9746         // locations are not in the default address space.
9747         LLD->getPointerInfo().getAddrSpace() != 0 ||
9748         RLD->getPointerInfo().getAddrSpace() != 0 ||
9749         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
9750                                       LLD->getBasePtr().getValueType()))
9751       return false;
9752
9753     // Check that the select condition doesn't reach either load.  If so,
9754     // folding this will induce a cycle into the DAG.  If not, this is safe to
9755     // xform, so create a select of the addresses.
9756     SDValue Addr;
9757     if (TheSelect->getOpcode() == ISD::SELECT) {
9758       SDNode *CondNode = TheSelect->getOperand(0).getNode();
9759       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
9760           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
9761         return false;
9762       // The loads must not depend on one another.
9763       if (LLD->isPredecessorOf(RLD) ||
9764           RLD->isPredecessorOf(LLD))
9765         return false;
9766       Addr = DAG.getSelect(SDLoc(TheSelect),
9767                            LLD->getBasePtr().getValueType(),
9768                            TheSelect->getOperand(0), LLD->getBasePtr(),
9769                            RLD->getBasePtr());
9770     } else {  // Otherwise SELECT_CC
9771       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
9772       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
9773
9774       if ((LLD->hasAnyUseOfValue(1) &&
9775            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
9776           (RLD->hasAnyUseOfValue(1) &&
9777            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
9778         return false;
9779
9780       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
9781                          LLD->getBasePtr().getValueType(),
9782                          TheSelect->getOperand(0),
9783                          TheSelect->getOperand(1),
9784                          LLD->getBasePtr(), RLD->getBasePtr(),
9785                          TheSelect->getOperand(4));
9786     }
9787
9788     SDValue Load;
9789     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
9790       Load = DAG.getLoad(TheSelect->getValueType(0),
9791                          SDLoc(TheSelect),
9792                          // FIXME: Discards pointer info.
9793                          LLD->getChain(), Addr, MachinePointerInfo(),
9794                          LLD->isVolatile(), LLD->isNonTemporal(),
9795                          LLD->isInvariant(), LLD->getAlignment());
9796     } else {
9797       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
9798                             RLD->getExtensionType() : LLD->getExtensionType(),
9799                             SDLoc(TheSelect),
9800                             TheSelect->getValueType(0),
9801                             // FIXME: Discards pointer info.
9802                             LLD->getChain(), Addr, MachinePointerInfo(),
9803                             LLD->getMemoryVT(), LLD->isVolatile(),
9804                             LLD->isNonTemporal(), LLD->getAlignment());
9805     }
9806
9807     // Users of the select now use the result of the load.
9808     CombineTo(TheSelect, Load);
9809
9810     // Users of the old loads now use the new load's chain.  We know the
9811     // old-load value is dead now.
9812     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
9813     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
9814     return true;
9815   }
9816
9817   return false;
9818 }
9819
9820 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
9821 /// where 'cond' is the comparison specified by CC.
9822 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
9823                                       SDValue N2, SDValue N3,
9824                                       ISD::CondCode CC, bool NotExtCompare) {
9825   // (x ? y : y) -> y.
9826   if (N2 == N3) return N2;
9827
9828   EVT VT = N2.getValueType();
9829   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
9830   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
9831   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
9832
9833   // Determine if the condition we're dealing with is constant
9834   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
9835                               N0, N1, CC, DL, false);
9836   if (SCC.getNode()) AddToWorkList(SCC.getNode());
9837   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
9838
9839   // fold select_cc true, x, y -> x
9840   if (SCCC && !SCCC->isNullValue())
9841     return N2;
9842   // fold select_cc false, x, y -> y
9843   if (SCCC && SCCC->isNullValue())
9844     return N3;
9845
9846   // Check to see if we can simplify the select into an fabs node
9847   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
9848     // Allow either -0.0 or 0.0
9849     if (CFP->getValueAPF().isZero()) {
9850       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
9851       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
9852           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
9853           N2 == N3.getOperand(0))
9854         return DAG.getNode(ISD::FABS, DL, VT, N0);
9855
9856       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
9857       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
9858           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
9859           N2.getOperand(0) == N3)
9860         return DAG.getNode(ISD::FABS, DL, VT, N3);
9861     }
9862   }
9863
9864   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
9865   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
9866   // in it.  This is a win when the constant is not otherwise available because
9867   // it replaces two constant pool loads with one.  We only do this if the FP
9868   // type is known to be legal, because if it isn't, then we are before legalize
9869   // types an we want the other legalization to happen first (e.g. to avoid
9870   // messing with soft float) and if the ConstantFP is not legal, because if
9871   // it is legal, we may not need to store the FP constant in a constant pool.
9872   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
9873     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
9874       if (TLI.isTypeLegal(N2.getValueType()) &&
9875           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
9876            TargetLowering::Legal) &&
9877           // If both constants have multiple uses, then we won't need to do an
9878           // extra load, they are likely around in registers for other users.
9879           (TV->hasOneUse() || FV->hasOneUse())) {
9880         Constant *Elts[] = {
9881           const_cast<ConstantFP*>(FV->getConstantFPValue()),
9882           const_cast<ConstantFP*>(TV->getConstantFPValue())
9883         };
9884         Type *FPTy = Elts[0]->getType();
9885         const DataLayout &TD = *TLI.getDataLayout();
9886
9887         // Create a ConstantArray of the two constants.
9888         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
9889         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
9890                                             TD.getPrefTypeAlignment(FPTy));
9891         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9892
9893         // Get the offsets to the 0 and 1 element of the array so that we can
9894         // select between them.
9895         SDValue Zero = DAG.getIntPtrConstant(0);
9896         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
9897         SDValue One = DAG.getIntPtrConstant(EltSize);
9898
9899         SDValue Cond = DAG.getSetCC(DL,
9900                                     getSetCCResultType(N0.getValueType()),
9901                                     N0, N1, CC);
9902         AddToWorkList(Cond.getNode());
9903         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
9904                                           Cond, One, Zero);
9905         AddToWorkList(CstOffset.getNode());
9906         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
9907                             CstOffset);
9908         AddToWorkList(CPIdx.getNode());
9909         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
9910                            MachinePointerInfo::getConstantPool(), false,
9911                            false, false, Alignment);
9912
9913       }
9914     }
9915
9916   // Check to see if we can perform the "gzip trick", transforming
9917   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
9918   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
9919       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
9920        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
9921     EVT XType = N0.getValueType();
9922     EVT AType = N2.getValueType();
9923     if (XType.bitsGE(AType)) {
9924       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
9925       // single-bit constant.
9926       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
9927         unsigned ShCtV = N2C->getAPIntValue().logBase2();
9928         ShCtV = XType.getSizeInBits()-ShCtV-1;
9929         SDValue ShCt = DAG.getConstant(ShCtV,
9930                                        getShiftAmountTy(N0.getValueType()));
9931         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
9932                                     XType, N0, ShCt);
9933         AddToWorkList(Shift.getNode());
9934
9935         if (XType.bitsGT(AType)) {
9936           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
9937           AddToWorkList(Shift.getNode());
9938         }
9939
9940         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
9941       }
9942
9943       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
9944                                   XType, N0,
9945                                   DAG.getConstant(XType.getSizeInBits()-1,
9946                                          getShiftAmountTy(N0.getValueType())));
9947       AddToWorkList(Shift.getNode());
9948
9949       if (XType.bitsGT(AType)) {
9950         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
9951         AddToWorkList(Shift.getNode());
9952       }
9953
9954       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
9955     }
9956   }
9957
9958   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
9959   // where y is has a single bit set.
9960   // A plaintext description would be, we can turn the SELECT_CC into an AND
9961   // when the condition can be materialized as an all-ones register.  Any
9962   // single bit-test can be materialized as an all-ones register with
9963   // shift-left and shift-right-arith.
9964   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
9965       N0->getValueType(0) == VT &&
9966       N1C && N1C->isNullValue() &&
9967       N2C && N2C->isNullValue()) {
9968     SDValue AndLHS = N0->getOperand(0);
9969     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
9970     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
9971       // Shift the tested bit over the sign bit.
9972       APInt AndMask = ConstAndRHS->getAPIntValue();
9973       SDValue ShlAmt =
9974         DAG.getConstant(AndMask.countLeadingZeros(),
9975                         getShiftAmountTy(AndLHS.getValueType()));
9976       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
9977
9978       // Now arithmetic right shift it all the way over, so the result is either
9979       // all-ones, or zero.
9980       SDValue ShrAmt =
9981         DAG.getConstant(AndMask.getBitWidth()-1,
9982                         getShiftAmountTy(Shl.getValueType()));
9983       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
9984
9985       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
9986     }
9987   }
9988
9989   // fold select C, 16, 0 -> shl C, 4
9990   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
9991     TLI.getBooleanContents(N0.getValueType().isVector()) ==
9992       TargetLowering::ZeroOrOneBooleanContent) {
9993
9994     // If the caller doesn't want us to simplify this into a zext of a compare,
9995     // don't do it.
9996     if (NotExtCompare && N2C->getAPIntValue() == 1)
9997       return SDValue();
9998
9999     // Get a SetCC of the condition
10000     // NOTE: Don't create a SETCC if it's not legal on this target.
10001     if (!LegalOperations ||
10002         TLI.isOperationLegal(ISD::SETCC,
10003           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
10004       SDValue Temp, SCC;
10005       // cast from setcc result type to select result type
10006       if (LegalTypes) {
10007         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
10008                             N0, N1, CC);
10009         if (N2.getValueType().bitsLT(SCC.getValueType()))
10010           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
10011                                         N2.getValueType());
10012         else
10013           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10014                              N2.getValueType(), SCC);
10015       } else {
10016         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
10017         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10018                            N2.getValueType(), SCC);
10019       }
10020
10021       AddToWorkList(SCC.getNode());
10022       AddToWorkList(Temp.getNode());
10023
10024       if (N2C->getAPIntValue() == 1)
10025         return Temp;
10026
10027       // shl setcc result by log2 n2c
10028       return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
10029                          DAG.getConstant(N2C->getAPIntValue().logBase2(),
10030                                          getShiftAmountTy(Temp.getValueType())));
10031     }
10032   }
10033
10034   // Check to see if this is the equivalent of setcc
10035   // FIXME: Turn all of these into setcc if setcc if setcc is legal
10036   // otherwise, go ahead with the folds.
10037   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
10038     EVT XType = N0.getValueType();
10039     if (!LegalOperations ||
10040         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
10041       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
10042       if (Res.getValueType() != VT)
10043         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
10044       return Res;
10045     }
10046
10047     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
10048     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
10049         (!LegalOperations ||
10050          TLI.isOperationLegal(ISD::CTLZ, XType))) {
10051       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
10052       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
10053                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
10054                                        getShiftAmountTy(Ctlz.getValueType())));
10055     }
10056     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
10057     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
10058       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
10059                                   XType, DAG.getConstant(0, XType), N0);
10060       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
10061       return DAG.getNode(ISD::SRL, DL, XType,
10062                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
10063                          DAG.getConstant(XType.getSizeInBits()-1,
10064                                          getShiftAmountTy(XType)));
10065     }
10066     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
10067     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
10068       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
10069                                  DAG.getConstant(XType.getSizeInBits()-1,
10070                                          getShiftAmountTy(N0.getValueType())));
10071       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
10072     }
10073   }
10074
10075   // Check to see if this is an integer abs.
10076   // select_cc setg[te] X,  0,  X, -X ->
10077   // select_cc setgt    X, -1,  X, -X ->
10078   // select_cc setl[te] X,  0, -X,  X ->
10079   // select_cc setlt    X,  1, -X,  X ->
10080   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
10081   if (N1C) {
10082     ConstantSDNode *SubC = NULL;
10083     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
10084          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
10085         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
10086       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
10087     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
10088               (N1C->isOne() && CC == ISD::SETLT)) &&
10089              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
10090       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
10091
10092     EVT XType = N0.getValueType();
10093     if (SubC && SubC->isNullValue() && XType.isInteger()) {
10094       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
10095                                   N0,
10096                                   DAG.getConstant(XType.getSizeInBits()-1,
10097                                          getShiftAmountTy(N0.getValueType())));
10098       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
10099                                 XType, N0, Shift);
10100       AddToWorkList(Shift.getNode());
10101       AddToWorkList(Add.getNode());
10102       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
10103     }
10104   }
10105
10106   return SDValue();
10107 }
10108
10109 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
10110 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
10111                                    SDValue N1, ISD::CondCode Cond,
10112                                    SDLoc DL, bool foldBooleans) {
10113   TargetLowering::DAGCombinerInfo
10114     DagCombineInfo(DAG, Level, false, this);
10115   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
10116 }
10117
10118 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
10119 /// return a DAG expression to select that will generate the same value by
10120 /// multiplying by a magic number.  See:
10121 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10122 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
10123   std::vector<SDNode*> Built;
10124   SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
10125
10126   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10127        ii != ee; ++ii)
10128     AddToWorkList(*ii);
10129   return S;
10130 }
10131
10132 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
10133 /// return a DAG expression to select that will generate the same value by
10134 /// multiplying by a magic number.  See:
10135 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10136 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
10137   std::vector<SDNode*> Built;
10138   SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
10139
10140   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10141        ii != ee; ++ii)
10142     AddToWorkList(*ii);
10143   return S;
10144 }
10145
10146 /// FindBaseOffset - Return true if base is a frame index, which is known not
10147 // to alias with anything but itself.  Provides base object and offset as
10148 // results.
10149 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
10150                            const GlobalValue *&GV, const void *&CV) {
10151   // Assume it is a primitive operation.
10152   Base = Ptr; Offset = 0; GV = 0; CV = 0;
10153
10154   // If it's an adding a simple constant then integrate the offset.
10155   if (Base.getOpcode() == ISD::ADD) {
10156     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
10157       Base = Base.getOperand(0);
10158       Offset += C->getZExtValue();
10159     }
10160   }
10161
10162   // Return the underlying GlobalValue, and update the Offset.  Return false
10163   // for GlobalAddressSDNode since the same GlobalAddress may be represented
10164   // by multiple nodes with different offsets.
10165   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
10166     GV = G->getGlobal();
10167     Offset += G->getOffset();
10168     return false;
10169   }
10170
10171   // Return the underlying Constant value, and update the Offset.  Return false
10172   // for ConstantSDNodes since the same constant pool entry may be represented
10173   // by multiple nodes with different offsets.
10174   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
10175     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
10176                                          : (const void *)C->getConstVal();
10177     Offset += C->getOffset();
10178     return false;
10179   }
10180   // If it's any of the following then it can't alias with anything but itself.
10181   return isa<FrameIndexSDNode>(Base);
10182 }
10183
10184 /// isAlias - Return true if there is any possibility that the two addresses
10185 /// overlap.
10186 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
10187                           const Value *SrcValue1, int SrcValueOffset1,
10188                           unsigned SrcValueAlign1,
10189                           const MDNode *TBAAInfo1,
10190                           SDValue Ptr2, int64_t Size2,
10191                           const Value *SrcValue2, int SrcValueOffset2,
10192                           unsigned SrcValueAlign2,
10193                           const MDNode *TBAAInfo2) const {
10194   // If they are the same then they must be aliases.
10195   if (Ptr1 == Ptr2) return true;
10196
10197   // Gather base node and offset information.
10198   SDValue Base1, Base2;
10199   int64_t Offset1, Offset2;
10200   const GlobalValue *GV1, *GV2;
10201   const void *CV1, *CV2;
10202   bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
10203   bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
10204
10205   // If they have a same base address then check to see if they overlap.
10206   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
10207     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
10208
10209   // It is possible for different frame indices to alias each other, mostly
10210   // when tail call optimization reuses return address slots for arguments.
10211   // To catch this case, look up the actual index of frame indices to compute
10212   // the real alias relationship.
10213   if (isFrameIndex1 && isFrameIndex2) {
10214     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10215     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
10216     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
10217     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
10218   }
10219
10220   // Otherwise, if we know what the bases are, and they aren't identical, then
10221   // we know they cannot alias.
10222   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
10223     return false;
10224
10225   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
10226   // compared to the size and offset of the access, we may be able to prove they
10227   // do not alias.  This check is conservative for now to catch cases created by
10228   // splitting vector types.
10229   if ((SrcValueAlign1 == SrcValueAlign2) &&
10230       (SrcValueOffset1 != SrcValueOffset2) &&
10231       (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
10232     int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
10233     int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
10234
10235     // There is no overlap between these relatively aligned accesses of similar
10236     // size, return no alias.
10237     if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
10238       return false;
10239   }
10240
10241   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
10242     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
10243   if (UseAA && SrcValue1 && SrcValue2) {
10244     // Use alias analysis information.
10245     int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
10246     int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
10247     int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
10248     AliasAnalysis::AliasResult AAResult =
10249       AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
10250                AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
10251     if (AAResult == AliasAnalysis::NoAlias)
10252       return false;
10253   }
10254
10255   // Otherwise we have to assume they alias.
10256   return true;
10257 }
10258
10259 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
10260   SDValue Ptr0, Ptr1;
10261   int64_t Size0, Size1;
10262   const Value *SrcValue0, *SrcValue1;
10263   int SrcValueOffset0, SrcValueOffset1;
10264   unsigned SrcValueAlign0, SrcValueAlign1;
10265   const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
10266   FindAliasInfo(Op0, Ptr0, Size0, SrcValue0, SrcValueOffset0,
10267                 SrcValueAlign0, SrcTBAAInfo0);
10268   FindAliasInfo(Op1, Ptr1, Size1, SrcValue1, SrcValueOffset1,
10269                 SrcValueAlign1, SrcTBAAInfo1);
10270   return isAlias(Ptr0, Size0, SrcValue0, SrcValueOffset0,
10271                  SrcValueAlign0, SrcTBAAInfo0,
10272                  Ptr1, Size1, SrcValue1, SrcValueOffset1,
10273                  SrcValueAlign1, SrcTBAAInfo1);
10274 }
10275
10276 /// FindAliasInfo - Extracts the relevant alias information from the memory
10277 /// node.  Returns true if the operand was a load.
10278 bool DAGCombiner::FindAliasInfo(SDNode *N,
10279                                 SDValue &Ptr, int64_t &Size,
10280                                 const Value *&SrcValue,
10281                                 int &SrcValueOffset,
10282                                 unsigned &SrcValueAlign,
10283                                 const MDNode *&TBAAInfo) const {
10284   LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
10285
10286   Ptr = LS->getBasePtr();
10287   Size = LS->getMemoryVT().getSizeInBits() >> 3;
10288   SrcValue = LS->getSrcValue();
10289   SrcValueOffset = LS->getSrcValueOffset();
10290   SrcValueAlign = LS->getOriginalAlignment();
10291   TBAAInfo = LS->getTBAAInfo();
10292   return isa<LoadSDNode>(LS);
10293 }
10294
10295 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
10296 /// looking for aliasing nodes and adding them to the Aliases vector.
10297 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
10298                                    SmallVectorImpl<SDValue> &Aliases) {
10299   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
10300   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
10301
10302   // Get alias information for node.
10303   SDValue Ptr;
10304   int64_t Size;
10305   const Value *SrcValue;
10306   int SrcValueOffset;
10307   unsigned SrcValueAlign;
10308   const MDNode *SrcTBAAInfo;
10309   bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset,
10310                               SrcValueAlign, SrcTBAAInfo);
10311
10312   // Starting off.
10313   Chains.push_back(OriginalChain);
10314   unsigned Depth = 0;
10315
10316   // Look at each chain and determine if it is an alias.  If so, add it to the
10317   // aliases list.  If not, then continue up the chain looking for the next
10318   // candidate.
10319   while (!Chains.empty()) {
10320     SDValue Chain = Chains.back();
10321     Chains.pop_back();
10322
10323     // For TokenFactor nodes, look at each operand and only continue up the
10324     // chain until we find two aliases.  If we've seen two aliases, assume we'll
10325     // find more and revert to original chain since the xform is unlikely to be
10326     // profitable.
10327     //
10328     // FIXME: The depth check could be made to return the last non-aliasing
10329     // chain we found before we hit a tokenfactor rather than the original
10330     // chain.
10331     if (Depth > 6 || Aliases.size() == 2) {
10332       Aliases.clear();
10333       Aliases.push_back(OriginalChain);
10334       break;
10335     }
10336
10337     // Don't bother if we've been before.
10338     if (!Visited.insert(Chain.getNode()))
10339       continue;
10340
10341     switch (Chain.getOpcode()) {
10342     case ISD::EntryToken:
10343       // Entry token is ideal chain operand, but handled in FindBetterChain.
10344       break;
10345
10346     case ISD::LOAD:
10347     case ISD::STORE: {
10348       // Get alias information for Chain.
10349       SDValue OpPtr;
10350       int64_t OpSize;
10351       const Value *OpSrcValue;
10352       int OpSrcValueOffset;
10353       unsigned OpSrcValueAlign;
10354       const MDNode *OpSrcTBAAInfo;
10355       bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
10356                                     OpSrcValue, OpSrcValueOffset,
10357                                     OpSrcValueAlign,
10358                                     OpSrcTBAAInfo);
10359
10360       // If chain is alias then stop here.
10361       if (!(IsLoad && IsOpLoad) &&
10362           isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign,
10363                   SrcTBAAInfo,
10364                   OpPtr, OpSize, OpSrcValue, OpSrcValueOffset,
10365                   OpSrcValueAlign, OpSrcTBAAInfo)) {
10366         Aliases.push_back(Chain);
10367       } else {
10368         // Look further up the chain.
10369         Chains.push_back(Chain.getOperand(0));
10370         ++Depth;
10371       }
10372       break;
10373     }
10374
10375     case ISD::TokenFactor:
10376       // We have to check each of the operands of the token factor for "small"
10377       // token factors, so we queue them up.  Adding the operands to the queue
10378       // (stack) in reverse order maintains the original order and increases the
10379       // likelihood that getNode will find a matching token factor (CSE.)
10380       if (Chain.getNumOperands() > 16) {
10381         Aliases.push_back(Chain);
10382         break;
10383       }
10384       for (unsigned n = Chain.getNumOperands(); n;)
10385         Chains.push_back(Chain.getOperand(--n));
10386       ++Depth;
10387       break;
10388
10389     default:
10390       // For all other instructions we will just have to take what we can get.
10391       Aliases.push_back(Chain);
10392       break;
10393     }
10394   }
10395 }
10396
10397 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
10398 /// for a better chain (aliasing node.)
10399 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
10400   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
10401
10402   // Accumulate all the aliases to this node.
10403   GatherAllAliases(N, OldChain, Aliases);
10404
10405   // If no operands then chain to entry token.
10406   if (Aliases.size() == 0)
10407     return DAG.getEntryNode();
10408
10409   // If a single operand then chain to it.  We don't need to revisit it.
10410   if (Aliases.size() == 1)
10411     return Aliases[0];
10412
10413   // Construct a custom tailored token factor.
10414   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
10415                      &Aliases[0], Aliases.size());
10416 }
10417
10418 // SelectionDAG::Combine - This is the entry point for the file.
10419 //
10420 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
10421                            CodeGenOpt::Level OptLevel) {
10422   /// run - This is the main entry point to this class.
10423   ///
10424   DAGCombiner(*this, AA, OptLevel).Run(Level);
10425 }