Make sure we emit a section for pubnames even if that section is
[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, then
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 RHSShiftArg = RHSShift.getOperand(0);
3345   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3346
3347   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3348   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3349   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3350       RHSShiftAmt.getOpcode() == ISD::Constant) {
3351     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3352     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3353     if ((LShVal + RShVal) != OpSizeInBits)
3354       return 0;
3355
3356     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3357                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3358
3359     // If there is an AND of either shifted operand, apply it to the result.
3360     if (LHSMask.getNode() || RHSMask.getNode()) {
3361       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3362
3363       if (LHSMask.getNode()) {
3364         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3365         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3366       }
3367       if (RHSMask.getNode()) {
3368         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3369         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3370       }
3371
3372       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3373     }
3374
3375     return Rot.getNode();
3376   }
3377
3378   // If there is a mask here, and we have a variable shift, we can't be sure
3379   // that we're masking out the right stuff.
3380   if (LHSMask.getNode() || RHSMask.getNode())
3381     return 0;
3382
3383   // If the shift amount is sign/zext/any-extended just peel it off.
3384   SDValue LExtOp0 = LHSShiftAmt;
3385   SDValue RExtOp0 = RHSShiftAmt;
3386   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3387        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3388        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3389        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3390       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3391        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3392        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3393        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3394     LExtOp0 = LHSShiftAmt.getOperand(0);
3395     RExtOp0 = RHSShiftAmt.getOperand(0);
3396   }
3397
3398   if (RExtOp0.getOpcode() == ISD::SUB && RExtOp0.getOperand(1) == LExtOp0) {
3399     // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3400     //   (rotl x, y)
3401     // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3402     //   (rotr x, (sub 32, y))
3403     if (ConstantSDNode *SUBC =
3404             dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
3405       if (SUBC->getAPIntValue() == OpSizeInBits) {
3406         return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, LHSShiftArg,
3407                            HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
3408       } else if (LHSShiftArg.getOpcode() == ISD::ZERO_EXTEND ||
3409                  LHSShiftArg.getOpcode() == ISD::ANY_EXTEND) {
3410         // fold (or (shl (*ext x), (*ext y)),
3411         //          (srl (*ext x), (*ext (sub 32, y)))) ->
3412         //   (*ext (rotl x, y))
3413         // fold (or (shl (*ext x), (*ext y)),
3414         //          (srl (*ext x), (*ext (sub 32, y)))) ->
3415         //   (*ext (rotr x, (sub 32, y)))
3416         SDValue LArgExtOp0 = LHSShiftArg.getOperand(0);
3417         EVT LArgVT = LArgExtOp0.getValueType();
3418         bool HasROTRWithLArg = TLI.isOperationLegalOrCustom(ISD::ROTR, LArgVT);
3419         bool HasROTLWithLArg = TLI.isOperationLegalOrCustom(ISD::ROTL, LArgVT);
3420         if (HasROTRWithLArg || HasROTLWithLArg) {
3421           if (LArgVT.getSizeInBits() == SUBC->getAPIntValue()) {
3422             SDValue V =
3423                 DAG.getNode(HasROTLWithLArg ? ISD::ROTL : ISD::ROTR, DL, LArgVT,
3424                             LArgExtOp0, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3425             return DAG.getNode(LHSShiftArg.getOpcode(), DL, VT, V).getNode();
3426           }     
3427         }     
3428       }
3429     }
3430   } else if (LExtOp0.getOpcode() == ISD::SUB &&
3431              RExtOp0 == LExtOp0.getOperand(1)) {
3432     // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3433     //   (rotr x, y)
3434     // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3435     //   (rotl x, (sub 32, y))
3436     if (ConstantSDNode *SUBC =
3437             dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
3438       if (SUBC->getAPIntValue() == OpSizeInBits) {
3439         return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT, LHSShiftArg,
3440                            HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
3441       } else if (RHSShiftArg.getOpcode() == ISD::ZERO_EXTEND ||
3442                  RHSShiftArg.getOpcode() == ISD::ANY_EXTEND) {
3443         // fold (or (shl (*ext x), (*ext (sub 32, y))),
3444         //          (srl (*ext x), (*ext y))) ->
3445         //   (*ext (rotl x, y))
3446         // fold (or (shl (*ext x), (*ext (sub 32, y))),
3447         //          (srl (*ext x), (*ext y))) ->
3448         //   (*ext (rotr x, (sub 32, y)))
3449         SDValue RArgExtOp0 = RHSShiftArg.getOperand(0);
3450         EVT RArgVT = RArgExtOp0.getValueType();
3451         bool HasROTRWithRArg = TLI.isOperationLegalOrCustom(ISD::ROTR, RArgVT);
3452         bool HasROTLWithRArg = TLI.isOperationLegalOrCustom(ISD::ROTL, RArgVT);
3453         if (HasROTRWithRArg || HasROTLWithRArg) {
3454           if (RArgVT.getSizeInBits() == SUBC->getAPIntValue()) {
3455             SDValue V =
3456                 DAG.getNode(HasROTRWithRArg ? ISD::ROTR : ISD::ROTL, DL, RArgVT,
3457                             RArgExtOp0, HasROTR ? RHSShiftAmt : LHSShiftAmt);
3458             return DAG.getNode(RHSShiftArg.getOpcode(), DL, VT, V).getNode();
3459           }
3460         }
3461       }
3462     }
3463   }
3464
3465   return 0;
3466 }
3467
3468 SDValue DAGCombiner::visitXOR(SDNode *N) {
3469   SDValue N0 = N->getOperand(0);
3470   SDValue N1 = N->getOperand(1);
3471   SDValue LHS, RHS, CC;
3472   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3473   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3474   EVT VT = N0.getValueType();
3475
3476   // fold vector ops
3477   if (VT.isVector()) {
3478     SDValue FoldedVOp = SimplifyVBinOp(N);
3479     if (FoldedVOp.getNode()) return FoldedVOp;
3480
3481     // fold (xor x, 0) -> x, vector edition
3482     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3483       return N1;
3484     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3485       return N0;
3486   }
3487
3488   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3489   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3490     return DAG.getConstant(0, VT);
3491   // fold (xor x, undef) -> undef
3492   if (N0.getOpcode() == ISD::UNDEF)
3493     return N0;
3494   if (N1.getOpcode() == ISD::UNDEF)
3495     return N1;
3496   // fold (xor c1, c2) -> c1^c2
3497   if (N0C && N1C)
3498     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3499   // canonicalize constant to RHS
3500   if (N0C && !N1C)
3501     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3502   // fold (xor x, 0) -> x
3503   if (N1C && N1C->isNullValue())
3504     return N0;
3505   // reassociate xor
3506   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3507   if (RXOR.getNode() != 0)
3508     return RXOR;
3509
3510   // fold !(x cc y) -> (x !cc y)
3511   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3512     bool isInt = LHS.getValueType().isInteger();
3513     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3514                                                isInt);
3515
3516     if (!LegalOperations ||
3517         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3518       switch (N0.getOpcode()) {
3519       default:
3520         llvm_unreachable("Unhandled SetCC Equivalent!");
3521       case ISD::SETCC:
3522         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3523       case ISD::SELECT_CC:
3524         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3525                                N0.getOperand(3), NotCC);
3526       }
3527     }
3528   }
3529
3530   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3531   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3532       N0.getNode()->hasOneUse() &&
3533       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3534     SDValue V = N0.getOperand(0);
3535     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3536                     DAG.getConstant(1, V.getValueType()));
3537     AddToWorkList(V.getNode());
3538     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3539   }
3540
3541   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3542   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3543       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3544     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3545     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3546       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3547       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3548       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3549       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3550       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3551     }
3552   }
3553   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3554   if (N1C && N1C->isAllOnesValue() &&
3555       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3556     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3557     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3558       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3559       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3560       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3561       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3562       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3563     }
3564   }
3565   // fold (xor (and x, y), y) -> (and (not x), y)
3566   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3567       N0->getOperand(1) == N1) {
3568     SDValue X = N0->getOperand(0);
3569     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3570     AddToWorkList(NotX.getNode());
3571     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3572   }
3573   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3574   if (N1C && N0.getOpcode() == ISD::XOR) {
3575     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3576     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3577     if (N00C)
3578       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3579                          DAG.getConstant(N1C->getAPIntValue() ^
3580                                          N00C->getAPIntValue(), VT));
3581     if (N01C)
3582       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3583                          DAG.getConstant(N1C->getAPIntValue() ^
3584                                          N01C->getAPIntValue(), VT));
3585   }
3586   // fold (xor x, x) -> 0
3587   if (N0 == N1)
3588     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3589
3590   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3591   if (N0.getOpcode() == N1.getOpcode()) {
3592     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3593     if (Tmp.getNode()) return Tmp;
3594   }
3595
3596   // Simplify the expression using non-local knowledge.
3597   if (!VT.isVector() &&
3598       SimplifyDemandedBits(SDValue(N, 0)))
3599     return SDValue(N, 0);
3600
3601   return SDValue();
3602 }
3603
3604 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3605 /// the shift amount is a constant.
3606 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
3607   SDNode *LHS = N->getOperand(0).getNode();
3608   if (!LHS->hasOneUse()) return SDValue();
3609
3610   // We want to pull some binops through shifts, so that we have (and (shift))
3611   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3612   // thing happens with address calculations, so it's important to canonicalize
3613   // it.
3614   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3615
3616   switch (LHS->getOpcode()) {
3617   default: return SDValue();
3618   case ISD::OR:
3619   case ISD::XOR:
3620     HighBitSet = false; // We can only transform sra if the high bit is clear.
3621     break;
3622   case ISD::AND:
3623     HighBitSet = true;  // We can only transform sra if the high bit is set.
3624     break;
3625   case ISD::ADD:
3626     if (N->getOpcode() != ISD::SHL)
3627       return SDValue(); // only shl(add) not sr[al](add).
3628     HighBitSet = false; // We can only transform sra if the high bit is clear.
3629     break;
3630   }
3631
3632   // We require the RHS of the binop to be a constant as well.
3633   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3634   if (!BinOpCst) return SDValue();
3635
3636   // FIXME: disable this unless the input to the binop is a shift by a constant.
3637   // If it is not a shift, it pessimizes some common cases like:
3638   //
3639   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3640   //    int bar(int *X, int i) { return X[i & 255]; }
3641   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3642   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3643        BinOpLHSVal->getOpcode() != ISD::SRA &&
3644        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3645       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3646     return SDValue();
3647
3648   EVT VT = N->getValueType(0);
3649
3650   // If this is a signed shift right, and the high bit is modified by the
3651   // logical operation, do not perform the transformation. The highBitSet
3652   // boolean indicates the value of the high bit of the constant which would
3653   // cause it to be modified for this operation.
3654   if (N->getOpcode() == ISD::SRA) {
3655     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3656     if (BinOpRHSSignSet != HighBitSet)
3657       return SDValue();
3658   }
3659
3660   // Fold the constants, shifting the binop RHS by the shift amount.
3661   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3662                                N->getValueType(0),
3663                                LHS->getOperand(1), N->getOperand(1));
3664
3665   // Create the new shift.
3666   SDValue NewShift = DAG.getNode(N->getOpcode(),
3667                                  SDLoc(LHS->getOperand(0)),
3668                                  VT, LHS->getOperand(0), N->getOperand(1));
3669
3670   // Create the new binop.
3671   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3672 }
3673
3674 SDValue DAGCombiner::visitSHL(SDNode *N) {
3675   SDValue N0 = N->getOperand(0);
3676   SDValue N1 = N->getOperand(1);
3677   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3678   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3679   EVT VT = N0.getValueType();
3680   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3681
3682   // fold (shl c1, c2) -> c1<<c2
3683   if (N0C && N1C)
3684     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3685   // fold (shl 0, x) -> 0
3686   if (N0C && N0C->isNullValue())
3687     return N0;
3688   // fold (shl x, c >= size(x)) -> undef
3689   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3690     return DAG.getUNDEF(VT);
3691   // fold (shl x, 0) -> x
3692   if (N1C && N1C->isNullValue())
3693     return N0;
3694   // fold (shl undef, x) -> 0
3695   if (N0.getOpcode() == ISD::UNDEF)
3696     return DAG.getConstant(0, VT);
3697   // if (shl x, c) is known to be zero, return 0
3698   if (DAG.MaskedValueIsZero(SDValue(N, 0),
3699                             APInt::getAllOnesValue(OpSizeInBits)))
3700     return DAG.getConstant(0, VT);
3701   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3702   if (N1.getOpcode() == ISD::TRUNCATE &&
3703       N1.getOperand(0).getOpcode() == ISD::AND &&
3704       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3705     SDValue N101 = N1.getOperand(0).getOperand(1);
3706     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3707       EVT TruncVT = N1.getValueType();
3708       SDValue N100 = N1.getOperand(0).getOperand(0);
3709       APInt TruncC = N101C->getAPIntValue();
3710       TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3711       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
3712                          DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3713                                      DAG.getNode(ISD::TRUNCATE,
3714                                                  SDLoc(N),
3715                                                  TruncVT, N100),
3716                                      DAG.getConstant(TruncC, TruncVT)));
3717     }
3718   }
3719
3720   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3721     return SDValue(N, 0);
3722
3723   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3724   if (N1C && N0.getOpcode() == ISD::SHL &&
3725       N0.getOperand(1).getOpcode() == ISD::Constant) {
3726     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3727     uint64_t c2 = N1C->getZExtValue();
3728     if (c1 + c2 >= OpSizeInBits)
3729       return DAG.getConstant(0, VT);
3730     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3731                        DAG.getConstant(c1 + c2, N1.getValueType()));
3732   }
3733
3734   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3735   // For this to be valid, the second form must not preserve any of the bits
3736   // that are shifted out by the inner shift in the first form.  This means
3737   // the outer shift size must be >= the number of bits added by the ext.
3738   // As a corollary, we don't care what kind of ext it is.
3739   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3740               N0.getOpcode() == ISD::ANY_EXTEND ||
3741               N0.getOpcode() == ISD::SIGN_EXTEND) &&
3742       N0.getOperand(0).getOpcode() == ISD::SHL &&
3743       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3744     uint64_t c1 =
3745       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3746     uint64_t c2 = N1C->getZExtValue();
3747     EVT InnerShiftVT = N0.getOperand(0).getValueType();
3748     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3749     if (c2 >= OpSizeInBits - InnerShiftSize) {
3750       if (c1 + c2 >= OpSizeInBits)
3751         return DAG.getConstant(0, VT);
3752       return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
3753                          DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
3754                                      N0.getOperand(0)->getOperand(0)),
3755                          DAG.getConstant(c1 + c2, N1.getValueType()));
3756     }
3757   }
3758
3759   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
3760   // Only fold this if the inner zext has no other uses to avoid increasing
3761   // the total number of instructions.
3762   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
3763       N0.getOperand(0).getOpcode() == ISD::SRL &&
3764       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3765     uint64_t c1 =
3766       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3767     if (c1 < VT.getSizeInBits()) {
3768       uint64_t c2 = N1C->getZExtValue();
3769       if (c1 == c2) {
3770         SDValue NewOp0 = N0.getOperand(0);
3771         EVT CountVT = NewOp0.getOperand(1).getValueType();
3772         SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
3773                                      NewOp0, DAG.getConstant(c2, CountVT));
3774         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
3775       }
3776     }
3777   }
3778
3779   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
3780   //                               (and (srl x, (sub c1, c2), MASK)
3781   // Only fold this if the inner shift has no other uses -- if it does, folding
3782   // this will increase the total number of instructions.
3783   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
3784       N0.getOperand(1).getOpcode() == ISD::Constant) {
3785     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3786     if (c1 < VT.getSizeInBits()) {
3787       uint64_t c2 = N1C->getZExtValue();
3788       APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3789                                          VT.getSizeInBits() - c1);
3790       SDValue Shift;
3791       if (c2 > c1) {
3792         Mask = Mask.shl(c2-c1);
3793         Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3794                             DAG.getConstant(c2-c1, N1.getValueType()));
3795       } else {
3796         Mask = Mask.lshr(c1-c2);
3797         Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
3798                             DAG.getConstant(c1-c2, N1.getValueType()));
3799       }
3800       return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
3801                          DAG.getConstant(Mask, VT));
3802     }
3803   }
3804   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
3805   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3806     SDValue HiBitsMask =
3807       DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3808                                             VT.getSizeInBits() -
3809                                               N1C->getZExtValue()),
3810                       VT);
3811     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
3812                        HiBitsMask);
3813   }
3814
3815   if (N1C) {
3816     SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3817     if (NewSHL.getNode())
3818       return NewSHL;
3819   }
3820
3821   return SDValue();
3822 }
3823
3824 SDValue DAGCombiner::visitSRA(SDNode *N) {
3825   SDValue N0 = N->getOperand(0);
3826   SDValue N1 = N->getOperand(1);
3827   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3828   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3829   EVT VT = N0.getValueType();
3830   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3831
3832   // fold (sra c1, c2) -> (sra c1, c2)
3833   if (N0C && N1C)
3834     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
3835   // fold (sra 0, x) -> 0
3836   if (N0C && N0C->isNullValue())
3837     return N0;
3838   // fold (sra -1, x) -> -1
3839   if (N0C && N0C->isAllOnesValue())
3840     return N0;
3841   // fold (sra x, (setge c, size(x))) -> undef
3842   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3843     return DAG.getUNDEF(VT);
3844   // fold (sra x, 0) -> x
3845   if (N1C && N1C->isNullValue())
3846     return N0;
3847   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3848   // sext_inreg.
3849   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
3850     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
3851     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
3852     if (VT.isVector())
3853       ExtVT = EVT::getVectorVT(*DAG.getContext(),
3854                                ExtVT, VT.getVectorNumElements());
3855     if ((!LegalOperations ||
3856          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
3857       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
3858                          N0.getOperand(0), DAG.getValueType(ExtVT));
3859   }
3860
3861   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
3862   if (N1C && N0.getOpcode() == ISD::SRA) {
3863     if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3864       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
3865       if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
3866       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
3867                          DAG.getConstant(Sum, N1C->getValueType(0)));
3868     }
3869   }
3870
3871   // fold (sra (shl X, m), (sub result_size, n))
3872   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
3873   // result_size - n != m.
3874   // If truncate is free for the target sext(shl) is likely to result in better
3875   // code.
3876   if (N0.getOpcode() == ISD::SHL) {
3877     // Get the two constanst of the shifts, CN0 = m, CN = n.
3878     const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3879     if (N01C && N1C) {
3880       // Determine what the truncate's result bitsize and type would be.
3881       EVT TruncVT =
3882         EVT::getIntegerVT(*DAG.getContext(),
3883                           OpSizeInBits - N1C->getZExtValue());
3884       // Determine the residual right-shift amount.
3885       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
3886
3887       // If the shift is not a no-op (in which case this should be just a sign
3888       // extend already), the truncated to type is legal, sign_extend is legal
3889       // on that type, and the truncate to that type is both legal and free,
3890       // perform the transform.
3891       if ((ShiftAmt > 0) &&
3892           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
3893           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
3894           TLI.isTruncateFree(VT, TruncVT)) {
3895
3896           SDValue Amt = DAG.getConstant(ShiftAmt,
3897               getShiftAmountTy(N0.getOperand(0).getValueType()));
3898           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
3899                                       N0.getOperand(0), Amt);
3900           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
3901                                       Shift);
3902           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
3903                              N->getValueType(0), Trunc);
3904       }
3905     }
3906   }
3907
3908   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
3909   if (N1.getOpcode() == ISD::TRUNCATE &&
3910       N1.getOperand(0).getOpcode() == ISD::AND &&
3911       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3912     SDValue N101 = N1.getOperand(0).getOperand(1);
3913     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3914       EVT TruncVT = N1.getValueType();
3915       SDValue N100 = N1.getOperand(0).getOperand(0);
3916       APInt TruncC = N101C->getAPIntValue();
3917       TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
3918       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
3919                          DAG.getNode(ISD::AND, SDLoc(N),
3920                                      TruncVT,
3921                                      DAG.getNode(ISD::TRUNCATE,
3922                                                  SDLoc(N),
3923                                                  TruncVT, N100),
3924                                      DAG.getConstant(TruncC, TruncVT)));
3925     }
3926   }
3927
3928   // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
3929   //      if c1 is equal to the number of bits the trunc removes
3930   if (N0.getOpcode() == ISD::TRUNCATE &&
3931       (N0.getOperand(0).getOpcode() == ISD::SRL ||
3932        N0.getOperand(0).getOpcode() == ISD::SRA) &&
3933       N0.getOperand(0).hasOneUse() &&
3934       N0.getOperand(0).getOperand(1).hasOneUse() &&
3935       N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
3936     EVT LargeVT = N0.getOperand(0).getValueType();
3937     ConstantSDNode *LargeShiftAmt =
3938       cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
3939
3940     if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
3941         LargeShiftAmt->getZExtValue()) {
3942       SDValue Amt =
3943         DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
3944               getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
3945       SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
3946                                 N0.getOperand(0).getOperand(0), Amt);
3947       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
3948     }
3949   }
3950
3951   // Simplify, based on bits shifted out of the LHS.
3952   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3953     return SDValue(N, 0);
3954
3955
3956   // If the sign bit is known to be zero, switch this to a SRL.
3957   if (DAG.SignBitIsZero(N0))
3958     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
3959
3960   if (N1C) {
3961     SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
3962     if (NewSRA.getNode())
3963       return NewSRA;
3964   }
3965
3966   return SDValue();
3967 }
3968
3969 SDValue DAGCombiner::visitSRL(SDNode *N) {
3970   SDValue N0 = N->getOperand(0);
3971   SDValue N1 = N->getOperand(1);
3972   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3973   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3974   EVT VT = N0.getValueType();
3975   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3976
3977   // fold (srl c1, c2) -> c1 >>u c2
3978   if (N0C && N1C)
3979     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
3980   // fold (srl 0, x) -> 0
3981   if (N0C && N0C->isNullValue())
3982     return N0;
3983   // fold (srl x, c >= size(x)) -> undef
3984   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3985     return DAG.getUNDEF(VT);
3986   // fold (srl x, 0) -> x
3987   if (N1C && N1C->isNullValue())
3988     return N0;
3989   // if (srl x, c) is known to be zero, return 0
3990   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3991                                    APInt::getAllOnesValue(OpSizeInBits)))
3992     return DAG.getConstant(0, VT);
3993
3994   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
3995   if (N1C && N0.getOpcode() == ISD::SRL &&
3996       N0.getOperand(1).getOpcode() == ISD::Constant) {
3997     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3998     uint64_t c2 = N1C->getZExtValue();
3999     if (c1 + c2 >= OpSizeInBits)
4000       return DAG.getConstant(0, VT);
4001     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4002                        DAG.getConstant(c1 + c2, N1.getValueType()));
4003   }
4004
4005   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4006   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4007       N0.getOperand(0).getOpcode() == ISD::SRL &&
4008       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4009     uint64_t c1 =
4010       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4011     uint64_t c2 = N1C->getZExtValue();
4012     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4013     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4014     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4015     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4016     if (c1 + OpSizeInBits == InnerShiftSize) {
4017       if (c1 + c2 >= InnerShiftSize)
4018         return DAG.getConstant(0, VT);
4019       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4020                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4021                                      N0.getOperand(0)->getOperand(0),
4022                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4023     }
4024   }
4025
4026   // fold (srl (shl x, c), c) -> (and x, cst2)
4027   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
4028       N0.getValueSizeInBits() <= 64) {
4029     uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
4030     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4031                        DAG.getConstant(~0ULL >> ShAmt, VT));
4032   }
4033
4034   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4035   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4036     // Shifting in all undef bits?
4037     EVT SmallVT = N0.getOperand(0).getValueType();
4038     if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
4039       return DAG.getUNDEF(VT);
4040
4041     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4042       uint64_t ShiftAmt = N1C->getZExtValue();
4043       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4044                                        N0.getOperand(0),
4045                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4046       AddToWorkList(SmallShift.getNode());
4047       APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits()).lshr(ShiftAmt);
4048       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4049                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4050                          DAG.getConstant(Mask, VT));
4051     }
4052   }
4053
4054   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4055   // bit, which is unmodified by sra.
4056   if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
4057     if (N0.getOpcode() == ISD::SRA)
4058       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4059   }
4060
4061   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4062   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4063       N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
4064     APInt KnownZero, KnownOne;
4065     DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
4066
4067     // If any of the input bits are KnownOne, then the input couldn't be all
4068     // zeros, thus the result of the srl will always be zero.
4069     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4070
4071     // If all of the bits input the to ctlz node are known to be zero, then
4072     // the result of the ctlz is "32" and the result of the shift is one.
4073     APInt UnknownBits = ~KnownZero;
4074     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4075
4076     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4077     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4078       // Okay, we know that only that the single bit specified by UnknownBits
4079       // could be set on input to the CTLZ node. If this bit is set, the SRL
4080       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4081       // to an SRL/XOR pair, which is likely to simplify more.
4082       unsigned ShAmt = UnknownBits.countTrailingZeros();
4083       SDValue Op = N0.getOperand(0);
4084
4085       if (ShAmt) {
4086         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4087                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4088         AddToWorkList(Op.getNode());
4089       }
4090
4091       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4092                          Op, DAG.getConstant(1, VT));
4093     }
4094   }
4095
4096   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4097   if (N1.getOpcode() == ISD::TRUNCATE &&
4098       N1.getOperand(0).getOpcode() == ISD::AND &&
4099       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
4100     SDValue N101 = N1.getOperand(0).getOperand(1);
4101     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
4102       EVT TruncVT = N1.getValueType();
4103       SDValue N100 = N1.getOperand(0).getOperand(0);
4104       APInt TruncC = N101C->getAPIntValue();
4105       TruncC = TruncC.trunc(TruncVT.getSizeInBits());
4106       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
4107                          DAG.getNode(ISD::AND, SDLoc(N),
4108                                      TruncVT,
4109                                      DAG.getNode(ISD::TRUNCATE,
4110                                                  SDLoc(N),
4111                                                  TruncVT, N100),
4112                                      DAG.getConstant(TruncC, TruncVT)));
4113     }
4114   }
4115
4116   // fold operands of srl based on knowledge that the low bits are not
4117   // demanded.
4118   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4119     return SDValue(N, 0);
4120
4121   if (N1C) {
4122     SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
4123     if (NewSRL.getNode())
4124       return NewSRL;
4125   }
4126
4127   // Attempt to convert a srl of a load into a narrower zero-extending load.
4128   SDValue NarrowLoad = ReduceLoadWidth(N);
4129   if (NarrowLoad.getNode())
4130     return NarrowLoad;
4131
4132   // Here is a common situation. We want to optimize:
4133   //
4134   //   %a = ...
4135   //   %b = and i32 %a, 2
4136   //   %c = srl i32 %b, 1
4137   //   brcond i32 %c ...
4138   //
4139   // into
4140   //
4141   //   %a = ...
4142   //   %b = and %a, 2
4143   //   %c = setcc eq %b, 0
4144   //   brcond %c ...
4145   //
4146   // However when after the source operand of SRL is optimized into AND, the SRL
4147   // itself may not be optimized further. Look for it and add the BRCOND into
4148   // the worklist.
4149   if (N->hasOneUse()) {
4150     SDNode *Use = *N->use_begin();
4151     if (Use->getOpcode() == ISD::BRCOND)
4152       AddToWorkList(Use);
4153     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4154       // Also look pass the truncate.
4155       Use = *Use->use_begin();
4156       if (Use->getOpcode() == ISD::BRCOND)
4157         AddToWorkList(Use);
4158     }
4159   }
4160
4161   return SDValue();
4162 }
4163
4164 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4165   SDValue N0 = N->getOperand(0);
4166   EVT VT = N->getValueType(0);
4167
4168   // fold (ctlz c1) -> c2
4169   if (isa<ConstantSDNode>(N0))
4170     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4171   return SDValue();
4172 }
4173
4174 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4175   SDValue N0 = N->getOperand(0);
4176   EVT VT = N->getValueType(0);
4177
4178   // fold (ctlz_zero_undef c1) -> c2
4179   if (isa<ConstantSDNode>(N0))
4180     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4181   return SDValue();
4182 }
4183
4184 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4185   SDValue N0 = N->getOperand(0);
4186   EVT VT = N->getValueType(0);
4187
4188   // fold (cttz c1) -> c2
4189   if (isa<ConstantSDNode>(N0))
4190     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4191   return SDValue();
4192 }
4193
4194 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4195   SDValue N0 = N->getOperand(0);
4196   EVT VT = N->getValueType(0);
4197
4198   // fold (cttz_zero_undef c1) -> c2
4199   if (isa<ConstantSDNode>(N0))
4200     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4201   return SDValue();
4202 }
4203
4204 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4205   SDValue N0 = N->getOperand(0);
4206   EVT VT = N->getValueType(0);
4207
4208   // fold (ctpop c1) -> c2
4209   if (isa<ConstantSDNode>(N0))
4210     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4211   return SDValue();
4212 }
4213
4214 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4215   SDValue N0 = N->getOperand(0);
4216   SDValue N1 = N->getOperand(1);
4217   SDValue N2 = N->getOperand(2);
4218   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4219   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4220   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4221   EVT VT = N->getValueType(0);
4222   EVT VT0 = N0.getValueType();
4223
4224   // fold (select C, X, X) -> X
4225   if (N1 == N2)
4226     return N1;
4227   // fold (select true, X, Y) -> X
4228   if (N0C && !N0C->isNullValue())
4229     return N1;
4230   // fold (select false, X, Y) -> Y
4231   if (N0C && N0C->isNullValue())
4232     return N2;
4233   // fold (select C, 1, X) -> (or C, X)
4234   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4235     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4236   // fold (select C, 0, 1) -> (xor C, 1)
4237   if (VT.isInteger() &&
4238       (VT0 == MVT::i1 ||
4239        (VT0.isInteger() &&
4240         TLI.getBooleanContents(false) ==
4241         TargetLowering::ZeroOrOneBooleanContent)) &&
4242       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4243     SDValue XORNode;
4244     if (VT == VT0)
4245       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4246                          N0, DAG.getConstant(1, VT0));
4247     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4248                           N0, DAG.getConstant(1, VT0));
4249     AddToWorkList(XORNode.getNode());
4250     if (VT.bitsGT(VT0))
4251       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4252     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4253   }
4254   // fold (select C, 0, X) -> (and (not C), X)
4255   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4256     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4257     AddToWorkList(NOTNode.getNode());
4258     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4259   }
4260   // fold (select C, X, 1) -> (or (not C), X)
4261   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4262     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4263     AddToWorkList(NOTNode.getNode());
4264     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4265   }
4266   // fold (select C, X, 0) -> (and C, X)
4267   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4268     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4269   // fold (select X, X, Y) -> (or X, Y)
4270   // fold (select X, 1, Y) -> (or X, Y)
4271   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4272     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4273   // fold (select X, Y, X) -> (and X, Y)
4274   // fold (select X, Y, 0) -> (and X, Y)
4275   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4276     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4277
4278   // If we can fold this based on the true/false value, do so.
4279   if (SimplifySelectOps(N, N1, N2))
4280     return SDValue(N, 0);  // Don't revisit N.
4281
4282   // fold selects based on a setcc into other things, such as min/max/abs
4283   if (N0.getOpcode() == ISD::SETCC) {
4284     // FIXME:
4285     // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4286     // having to say they don't support SELECT_CC on every type the DAG knows
4287     // about, since there is no way to mark an opcode illegal at all value types
4288     if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4289         TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4290       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4291                          N0.getOperand(0), N0.getOperand(1),
4292                          N1, N2, N0.getOperand(2));
4293     return SimplifySelect(SDLoc(N), N0, N1, N2);
4294   }
4295
4296   return SDValue();
4297 }
4298
4299 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4300   SDValue N0 = N->getOperand(0);
4301   SDValue N1 = N->getOperand(1);
4302   SDValue N2 = N->getOperand(2);
4303   SDLoc DL(N);
4304
4305   // Canonicalize integer abs.
4306   // vselect (setg[te] X,  0),  X, -X ->
4307   // vselect (setgt    X, -1),  X, -X ->
4308   // vselect (setl[te] X,  0), -X,  X ->
4309   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4310   if (N0.getOpcode() == ISD::SETCC) {
4311     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4312     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4313     bool isAbs = false;
4314     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4315
4316     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4317          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4318         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4319       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4320     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4321              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4322       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4323
4324     if (isAbs) {
4325       EVT VT = LHS.getValueType();
4326       SDValue Shift = DAG.getNode(
4327           ISD::SRA, DL, VT, LHS,
4328           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4329       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4330       AddToWorkList(Shift.getNode());
4331       AddToWorkList(Add.getNode());
4332       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4333     }
4334   }
4335
4336   return SDValue();
4337 }
4338
4339 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4340   SDValue N0 = N->getOperand(0);
4341   SDValue N1 = N->getOperand(1);
4342   SDValue N2 = N->getOperand(2);
4343   SDValue N3 = N->getOperand(3);
4344   SDValue N4 = N->getOperand(4);
4345   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4346
4347   // fold select_cc lhs, rhs, x, x, cc -> x
4348   if (N2 == N3)
4349     return N2;
4350
4351   // Determine if the condition we're dealing with is constant
4352   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4353                               N0, N1, CC, SDLoc(N), false);
4354   if (SCC.getNode()) {
4355     AddToWorkList(SCC.getNode());
4356
4357     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4358       if (!SCCC->isNullValue())
4359         return N2;    // cond always true -> true val
4360       else
4361         return N3;    // cond always false -> false val
4362     }
4363
4364     // Fold to a simpler select_cc
4365     if (SCC.getOpcode() == ISD::SETCC)
4366       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4367                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4368                          SCC.getOperand(2));
4369   }
4370
4371   // If we can fold this based on the true/false value, do so.
4372   if (SimplifySelectOps(N, N2, N3))
4373     return SDValue(N, 0);  // Don't revisit N.
4374
4375   // fold select_cc into other things, such as min/max/abs
4376   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4377 }
4378
4379 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4380   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4381                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4382                        SDLoc(N));
4383 }
4384
4385 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4386 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4387 // transformation. Returns true if extension are possible and the above
4388 // mentioned transformation is profitable.
4389 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4390                                     unsigned ExtOpc,
4391                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4392                                     const TargetLowering &TLI) {
4393   bool HasCopyToRegUses = false;
4394   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4395   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4396                             UE = N0.getNode()->use_end();
4397        UI != UE; ++UI) {
4398     SDNode *User = *UI;
4399     if (User == N)
4400       continue;
4401     if (UI.getUse().getResNo() != N0.getResNo())
4402       continue;
4403     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4404     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4405       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4406       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4407         // Sign bits will be lost after a zext.
4408         return false;
4409       bool Add = false;
4410       for (unsigned i = 0; i != 2; ++i) {
4411         SDValue UseOp = User->getOperand(i);
4412         if (UseOp == N0)
4413           continue;
4414         if (!isa<ConstantSDNode>(UseOp))
4415           return false;
4416         Add = true;
4417       }
4418       if (Add)
4419         ExtendNodes.push_back(User);
4420       continue;
4421     }
4422     // If truncates aren't free and there are users we can't
4423     // extend, it isn't worthwhile.
4424     if (!isTruncFree)
4425       return false;
4426     // Remember if this value is live-out.
4427     if (User->getOpcode() == ISD::CopyToReg)
4428       HasCopyToRegUses = true;
4429   }
4430
4431   if (HasCopyToRegUses) {
4432     bool BothLiveOut = false;
4433     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4434          UI != UE; ++UI) {
4435       SDUse &Use = UI.getUse();
4436       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4437         BothLiveOut = true;
4438         break;
4439       }
4440     }
4441     if (BothLiveOut)
4442       // Both unextended and extended values are live out. There had better be
4443       // a good reason for the transformation.
4444       return ExtendNodes.size();
4445   }
4446   return true;
4447 }
4448
4449 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4450                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4451                                   ISD::NodeType ExtType) {
4452   // Extend SetCC uses if necessary.
4453   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4454     SDNode *SetCC = SetCCs[i];
4455     SmallVector<SDValue, 4> Ops;
4456
4457     for (unsigned j = 0; j != 2; ++j) {
4458       SDValue SOp = SetCC->getOperand(j);
4459       if (SOp == Trunc)
4460         Ops.push_back(ExtLoad);
4461       else
4462         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4463     }
4464
4465     Ops.push_back(SetCC->getOperand(2));
4466     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4467                                  &Ops[0], Ops.size()));
4468   }
4469 }
4470
4471 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4472   SDValue N0 = N->getOperand(0);
4473   EVT VT = N->getValueType(0);
4474
4475   // fold (sext c1) -> c1
4476   if (isa<ConstantSDNode>(N0))
4477     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N0);
4478
4479   // fold (sext (sext x)) -> (sext x)
4480   // fold (sext (aext x)) -> (sext x)
4481   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4482     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4483                        N0.getOperand(0));
4484
4485   if (N0.getOpcode() == ISD::TRUNCATE) {
4486     // fold (sext (truncate (load x))) -> (sext (smaller load x))
4487     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4488     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4489     if (NarrowLoad.getNode()) {
4490       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4491       if (NarrowLoad.getNode() != N0.getNode()) {
4492         CombineTo(N0.getNode(), NarrowLoad);
4493         // CombineTo deleted the truncate, if needed, but not what's under it.
4494         AddToWorkList(oye);
4495       }
4496       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4497     }
4498
4499     // See if the value being truncated is already sign extended.  If so, just
4500     // eliminate the trunc/sext pair.
4501     SDValue Op = N0.getOperand(0);
4502     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
4503     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
4504     unsigned DestBits = VT.getScalarType().getSizeInBits();
4505     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4506
4507     if (OpBits == DestBits) {
4508       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
4509       // bits, it is already ready.
4510       if (NumSignBits > DestBits-MidBits)
4511         return Op;
4512     } else if (OpBits < DestBits) {
4513       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
4514       // bits, just sext from i32.
4515       if (NumSignBits > OpBits-MidBits)
4516         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4517     } else {
4518       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
4519       // bits, just truncate to i32.
4520       if (NumSignBits > OpBits-MidBits)
4521         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4522     }
4523
4524     // fold (sext (truncate x)) -> (sextinreg x).
4525     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4526                                                  N0.getValueType())) {
4527       if (OpBits < DestBits)
4528         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4529       else if (OpBits > DestBits)
4530         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4531       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4532                          DAG.getValueType(N0.getValueType()));
4533     }
4534   }
4535
4536   // fold (sext (load x)) -> (sext (truncate (sextload x)))
4537   // None of the supported targets knows how to perform load and sign extend
4538   // on vectors in one instruction.  We only perform this transformation on
4539   // scalars.
4540   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4541       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4542        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4543     bool DoXform = true;
4544     SmallVector<SDNode*, 4> SetCCs;
4545     if (!N0.hasOneUse())
4546       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4547     if (DoXform) {
4548       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4549       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4550                                        LN0->getChain(),
4551                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4552                                        N0.getValueType(),
4553                                        LN0->isVolatile(), LN0->isNonTemporal(),
4554                                        LN0->getAlignment());
4555       CombineTo(N, ExtLoad);
4556       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4557                                   N0.getValueType(), ExtLoad);
4558       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4559       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4560                       ISD::SIGN_EXTEND);
4561       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4562     }
4563   }
4564
4565   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4566   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4567   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4568       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4569     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4570     EVT MemVT = LN0->getMemoryVT();
4571     if ((!LegalOperations && !LN0->isVolatile()) ||
4572         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4573       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4574                                        LN0->getChain(),
4575                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4576                                        MemVT,
4577                                        LN0->isVolatile(), LN0->isNonTemporal(),
4578                                        LN0->getAlignment());
4579       CombineTo(N, ExtLoad);
4580       CombineTo(N0.getNode(),
4581                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4582                             N0.getValueType(), ExtLoad),
4583                 ExtLoad.getValue(1));
4584       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4585     }
4586   }
4587
4588   // fold (sext (and/or/xor (load x), cst)) ->
4589   //      (and/or/xor (sextload x), (sext cst))
4590   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4591        N0.getOpcode() == ISD::XOR) &&
4592       isa<LoadSDNode>(N0.getOperand(0)) &&
4593       N0.getOperand(1).getOpcode() == ISD::Constant &&
4594       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4595       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4596     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4597     if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4598       bool DoXform = true;
4599       SmallVector<SDNode*, 4> SetCCs;
4600       if (!N0.hasOneUse())
4601         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4602                                           SetCCs, TLI);
4603       if (DoXform) {
4604         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
4605                                          LN0->getChain(), LN0->getBasePtr(),
4606                                          LN0->getPointerInfo(),
4607                                          LN0->getMemoryVT(),
4608                                          LN0->isVolatile(),
4609                                          LN0->isNonTemporal(),
4610                                          LN0->getAlignment());
4611         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4612         Mask = Mask.sext(VT.getSizeInBits());
4613         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4614                                   ExtLoad, DAG.getConstant(Mask, VT));
4615         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4616                                     SDLoc(N0.getOperand(0)),
4617                                     N0.getOperand(0).getValueType(), ExtLoad);
4618         CombineTo(N, And);
4619         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4620         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4621                         ISD::SIGN_EXTEND);
4622         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4623       }
4624     }
4625   }
4626
4627   if (N0.getOpcode() == ISD::SETCC) {
4628     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
4629     // Only do this before legalize for now.
4630     if (VT.isVector() && !LegalOperations &&
4631         TLI.getBooleanContents(true) ==
4632           TargetLowering::ZeroOrNegativeOneBooleanContent) {
4633       EVT N0VT = N0.getOperand(0).getValueType();
4634       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
4635       // of the same size as the compared operands. Only optimize sext(setcc())
4636       // if this is the case.
4637       EVT SVT = getSetCCResultType(N0VT);
4638
4639       // We know that the # elements of the results is the same as the
4640       // # elements of the compare (and the # elements of the compare result
4641       // for that matter).  Check to see that they are the same size.  If so,
4642       // we know that the element size of the sext'd result matches the
4643       // element size of the compare operands.
4644       if (VT.getSizeInBits() == SVT.getSizeInBits())
4645         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4646                              N0.getOperand(1),
4647                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
4648
4649       // If the desired elements are smaller or larger than the source
4650       // elements we can use a matching integer vector type and then
4651       // truncate/sign extend
4652       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
4653       if (SVT == MatchingVectorType) {
4654         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
4655                                N0.getOperand(0), N0.getOperand(1),
4656                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
4657         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
4658       }
4659     }
4660
4661     // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
4662     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
4663     SDValue NegOne =
4664       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
4665     SDValue SCC =
4666       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
4667                        NegOne, DAG.getConstant(0, VT),
4668                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4669     if (SCC.getNode()) return SCC;
4670     if (!VT.isVector() &&
4671         (!LegalOperations ||
4672          TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(VT)))) {
4673       return DAG.getSelect(SDLoc(N), VT,
4674                            DAG.getSetCC(SDLoc(N),
4675                                         getSetCCResultType(VT),
4676                                         N0.getOperand(0), N0.getOperand(1),
4677                                         cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4678                            NegOne, DAG.getConstant(0, VT));
4679     }
4680   }
4681
4682   // fold (sext x) -> (zext x) if the sign bit is known zero.
4683   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
4684       DAG.SignBitIsZero(N0))
4685     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4686
4687   return SDValue();
4688 }
4689
4690 // isTruncateOf - If N is a truncate of some other value, return true, record
4691 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
4692 // This function computes KnownZero to avoid a duplicated call to
4693 // ComputeMaskedBits in the caller.
4694 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
4695                          APInt &KnownZero) {
4696   APInt KnownOne;
4697   if (N->getOpcode() == ISD::TRUNCATE) {
4698     Op = N->getOperand(0);
4699     DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4700     return true;
4701   }
4702
4703   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
4704       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
4705     return false;
4706
4707   SDValue Op0 = N->getOperand(0);
4708   SDValue Op1 = N->getOperand(1);
4709   assert(Op0.getValueType() == Op1.getValueType());
4710
4711   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
4712   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
4713   if (COp0 && COp0->isNullValue())
4714     Op = Op1;
4715   else if (COp1 && COp1->isNullValue())
4716     Op = Op0;
4717   else
4718     return false;
4719
4720   DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4721
4722   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
4723     return false;
4724
4725   return true;
4726 }
4727
4728 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
4729   SDValue N0 = N->getOperand(0);
4730   EVT VT = N->getValueType(0);
4731
4732   // fold (zext c1) -> c1
4733   if (isa<ConstantSDNode>(N0))
4734     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4735   // fold (zext (zext x)) -> (zext x)
4736   // fold (zext (aext x)) -> (zext x)
4737   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4738     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
4739                        N0.getOperand(0));
4740
4741   // fold (zext (truncate x)) -> (zext x) or
4742   //      (zext (truncate x)) -> (truncate x)
4743   // This is valid when the truncated bits of x are already zero.
4744   // FIXME: We should extend this to work for vectors too.
4745   SDValue Op;
4746   APInt KnownZero;
4747   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
4748     APInt TruncatedBits =
4749       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
4750       APInt(Op.getValueSizeInBits(), 0) :
4751       APInt::getBitsSet(Op.getValueSizeInBits(),
4752                         N0.getValueSizeInBits(),
4753                         std::min(Op.getValueSizeInBits(),
4754                                  VT.getSizeInBits()));
4755     if (TruncatedBits == (KnownZero & TruncatedBits)) {
4756       if (VT.bitsGT(Op.getValueType()))
4757         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
4758       if (VT.bitsLT(Op.getValueType()))
4759         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4760
4761       return Op;
4762     }
4763   }
4764
4765   // fold (zext (truncate (load x))) -> (zext (smaller load x))
4766   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
4767   if (N0.getOpcode() == ISD::TRUNCATE) {
4768     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4769     if (NarrowLoad.getNode()) {
4770       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4771       if (NarrowLoad.getNode() != N0.getNode()) {
4772         CombineTo(N0.getNode(), NarrowLoad);
4773         // CombineTo deleted the truncate, if needed, but not what's under it.
4774         AddToWorkList(oye);
4775       }
4776       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4777     }
4778   }
4779
4780   // fold (zext (truncate x)) -> (and x, mask)
4781   if (N0.getOpcode() == ISD::TRUNCATE &&
4782       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
4783
4784     // fold (zext (truncate (load x))) -> (zext (smaller load x))
4785     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
4786     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4787     if (NarrowLoad.getNode()) {
4788       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4789       if (NarrowLoad.getNode() != N0.getNode()) {
4790         CombineTo(N0.getNode(), NarrowLoad);
4791         // CombineTo deleted the truncate, if needed, but not what's under it.
4792         AddToWorkList(oye);
4793       }
4794       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4795     }
4796
4797     SDValue Op = N0.getOperand(0);
4798     if (Op.getValueType().bitsLT(VT)) {
4799       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
4800       AddToWorkList(Op.getNode());
4801     } else if (Op.getValueType().bitsGT(VT)) {
4802       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4803       AddToWorkList(Op.getNode());
4804     }
4805     return DAG.getZeroExtendInReg(Op, SDLoc(N),
4806                                   N0.getValueType().getScalarType());
4807   }
4808
4809   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
4810   // if either of the casts is not free.
4811   if (N0.getOpcode() == ISD::AND &&
4812       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4813       N0.getOperand(1).getOpcode() == ISD::Constant &&
4814       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4815                            N0.getValueType()) ||
4816        !TLI.isZExtFree(N0.getValueType(), VT))) {
4817     SDValue X = N0.getOperand(0).getOperand(0);
4818     if (X.getValueType().bitsLT(VT)) {
4819       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
4820     } else if (X.getValueType().bitsGT(VT)) {
4821       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
4822     }
4823     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4824     Mask = Mask.zext(VT.getSizeInBits());
4825     return DAG.getNode(ISD::AND, SDLoc(N), VT,
4826                        X, DAG.getConstant(Mask, VT));
4827   }
4828
4829   // fold (zext (load x)) -> (zext (truncate (zextload x)))
4830   // None of the supported targets knows how to perform load and vector_zext
4831   // on vectors in one instruction.  We only perform this transformation on
4832   // scalars.
4833   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4834       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4835        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
4836     bool DoXform = true;
4837     SmallVector<SDNode*, 4> SetCCs;
4838     if (!N0.hasOneUse())
4839       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
4840     if (DoXform) {
4841       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4842       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
4843                                        LN0->getChain(),
4844                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4845                                        N0.getValueType(),
4846                                        LN0->isVolatile(), LN0->isNonTemporal(),
4847                                        LN0->getAlignment());
4848       CombineTo(N, ExtLoad);
4849       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4850                                   N0.getValueType(), ExtLoad);
4851       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4852
4853       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4854                       ISD::ZERO_EXTEND);
4855       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4856     }
4857   }
4858
4859   // fold (zext (and/or/xor (load x), cst)) ->
4860   //      (and/or/xor (zextload x), (zext cst))
4861   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4862        N0.getOpcode() == ISD::XOR) &&
4863       isa<LoadSDNode>(N0.getOperand(0)) &&
4864       N0.getOperand(1).getOpcode() == ISD::Constant &&
4865       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
4866       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4867     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4868     if (LN0->getExtensionType() != ISD::SEXTLOAD) {
4869       bool DoXform = true;
4870       SmallVector<SDNode*, 4> SetCCs;
4871       if (!N0.hasOneUse())
4872         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
4873                                           SetCCs, TLI);
4874       if (DoXform) {
4875         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
4876                                          LN0->getChain(), LN0->getBasePtr(),
4877                                          LN0->getPointerInfo(),
4878                                          LN0->getMemoryVT(),
4879                                          LN0->isVolatile(),
4880                                          LN0->isNonTemporal(),
4881                                          LN0->getAlignment());
4882         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4883         Mask = Mask.zext(VT.getSizeInBits());
4884         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4885                                   ExtLoad, DAG.getConstant(Mask, VT));
4886         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4887                                     SDLoc(N0.getOperand(0)),
4888                                     N0.getOperand(0).getValueType(), ExtLoad);
4889         CombineTo(N, And);
4890         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4891         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4892                         ISD::ZERO_EXTEND);
4893         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4894       }
4895     }
4896   }
4897
4898   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
4899   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
4900   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4901       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4902     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4903     EVT MemVT = LN0->getMemoryVT();
4904     if ((!LegalOperations && !LN0->isVolatile()) ||
4905         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
4906       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
4907                                        LN0->getChain(),
4908                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4909                                        MemVT,
4910                                        LN0->isVolatile(), LN0->isNonTemporal(),
4911                                        LN0->getAlignment());
4912       CombineTo(N, ExtLoad);
4913       CombineTo(N0.getNode(),
4914                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
4915                             ExtLoad),
4916                 ExtLoad.getValue(1));
4917       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4918     }
4919   }
4920
4921   if (N0.getOpcode() == ISD::SETCC) {
4922     if (!LegalOperations && VT.isVector()) {
4923       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
4924       // Only do this before legalize for now.
4925       EVT N0VT = N0.getOperand(0).getValueType();
4926       EVT EltVT = VT.getVectorElementType();
4927       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
4928                                     DAG.getConstant(1, EltVT));
4929       if (VT.getSizeInBits() == N0VT.getSizeInBits())
4930         // We know that the # elements of the results is the same as the
4931         // # elements of the compare (and the # elements of the compare result
4932         // for that matter).  Check to see that they are the same size.  If so,
4933         // we know that the element size of the sext'd result matches the
4934         // element size of the compare operands.
4935         return DAG.getNode(ISD::AND, SDLoc(N), VT,
4936                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4937                                          N0.getOperand(1),
4938                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4939                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
4940                                        &OneOps[0], OneOps.size()));
4941
4942       // If the desired elements are smaller or larger than the source
4943       // elements we can use a matching integer vector type and then
4944       // truncate/sign extend
4945       EVT MatchingElementType =
4946         EVT::getIntegerVT(*DAG.getContext(),
4947                           N0VT.getScalarType().getSizeInBits());
4948       EVT MatchingVectorType =
4949         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4950                          N0VT.getVectorNumElements());
4951       SDValue VsetCC =
4952         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
4953                       N0.getOperand(1),
4954                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
4955       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4956                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
4957                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
4958                                      &OneOps[0], OneOps.size()));
4959     }
4960
4961     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4962     SDValue SCC =
4963       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
4964                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4965                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4966     if (SCC.getNode()) return SCC;
4967   }
4968
4969   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
4970   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
4971       isa<ConstantSDNode>(N0.getOperand(1)) &&
4972       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
4973       N0.hasOneUse()) {
4974     SDValue ShAmt = N0.getOperand(1);
4975     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
4976     if (N0.getOpcode() == ISD::SHL) {
4977       SDValue InnerZExt = N0.getOperand(0);
4978       // If the original shl may be shifting out bits, do not perform this
4979       // transformation.
4980       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
4981         InnerZExt.getOperand(0).getValueType().getSizeInBits();
4982       if (ShAmtVal > KnownZeroBits)
4983         return SDValue();
4984     }
4985
4986     SDLoc DL(N);
4987
4988     // Ensure that the shift amount is wide enough for the shifted value.
4989     if (VT.getSizeInBits() >= 256)
4990       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
4991
4992     return DAG.getNode(N0.getOpcode(), DL, VT,
4993                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
4994                        ShAmt);
4995   }
4996
4997   return SDValue();
4998 }
4999
5000 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5001   SDValue N0 = N->getOperand(0);
5002   EVT VT = N->getValueType(0);
5003
5004   // fold (aext c1) -> c1
5005   if (isa<ConstantSDNode>(N0))
5006     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, N0);
5007   // fold (aext (aext x)) -> (aext x)
5008   // fold (aext (zext x)) -> (zext x)
5009   // fold (aext (sext x)) -> (sext x)
5010   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5011       N0.getOpcode() == ISD::ZERO_EXTEND ||
5012       N0.getOpcode() == ISD::SIGN_EXTEND)
5013     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5014
5015   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5016   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5017   if (N0.getOpcode() == ISD::TRUNCATE) {
5018     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5019     if (NarrowLoad.getNode()) {
5020       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5021       if (NarrowLoad.getNode() != N0.getNode()) {
5022         CombineTo(N0.getNode(), NarrowLoad);
5023         // CombineTo deleted the truncate, if needed, but not what's under it.
5024         AddToWorkList(oye);
5025       }
5026       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5027     }
5028   }
5029
5030   // fold (aext (truncate x))
5031   if (N0.getOpcode() == ISD::TRUNCATE) {
5032     SDValue TruncOp = N0.getOperand(0);
5033     if (TruncOp.getValueType() == VT)
5034       return TruncOp; // x iff x size == zext size.
5035     if (TruncOp.getValueType().bitsGT(VT))
5036       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5037     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5038   }
5039
5040   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5041   // if the trunc is not free.
5042   if (N0.getOpcode() == ISD::AND &&
5043       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5044       N0.getOperand(1).getOpcode() == ISD::Constant &&
5045       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5046                           N0.getValueType())) {
5047     SDValue X = N0.getOperand(0).getOperand(0);
5048     if (X.getValueType().bitsLT(VT)) {
5049       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5050     } else if (X.getValueType().bitsGT(VT)) {
5051       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5052     }
5053     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5054     Mask = Mask.zext(VT.getSizeInBits());
5055     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5056                        X, DAG.getConstant(Mask, VT));
5057   }
5058
5059   // fold (aext (load x)) -> (aext (truncate (extload x)))
5060   // None of the supported targets knows how to perform load and any_ext
5061   // on vectors in one instruction.  We only perform this transformation on
5062   // scalars.
5063   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5064       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5065        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5066     bool DoXform = true;
5067     SmallVector<SDNode*, 4> SetCCs;
5068     if (!N0.hasOneUse())
5069       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5070     if (DoXform) {
5071       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5072       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5073                                        LN0->getChain(),
5074                                        LN0->getBasePtr(), LN0->getPointerInfo(),
5075                                        N0.getValueType(),
5076                                        LN0->isVolatile(), LN0->isNonTemporal(),
5077                                        LN0->getAlignment());
5078       CombineTo(N, ExtLoad);
5079       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5080                                   N0.getValueType(), ExtLoad);
5081       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5082       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5083                       ISD::ANY_EXTEND);
5084       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5085     }
5086   }
5087
5088   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5089   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5090   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5091   if (N0.getOpcode() == ISD::LOAD &&
5092       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5093       N0.hasOneUse()) {
5094     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5095     EVT MemVT = LN0->getMemoryVT();
5096     SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N),
5097                                      VT, LN0->getChain(), LN0->getBasePtr(),
5098                                      LN0->getPointerInfo(), MemVT,
5099                                      LN0->isVolatile(), LN0->isNonTemporal(),
5100                                      LN0->getAlignment());
5101     CombineTo(N, ExtLoad);
5102     CombineTo(N0.getNode(),
5103               DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5104                           N0.getValueType(), ExtLoad),
5105               ExtLoad.getValue(1));
5106     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5107   }
5108
5109   if (N0.getOpcode() == ISD::SETCC) {
5110     // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5111     // Only do this before legalize for now.
5112     if (VT.isVector() && !LegalOperations) {
5113       EVT N0VT = N0.getOperand(0).getValueType();
5114         // We know that the # elements of the results is the same as the
5115         // # elements of the compare (and the # elements of the compare result
5116         // for that matter).  Check to see that they are the same size.  If so,
5117         // we know that the element size of the sext'd result matches the
5118         // element size of the compare operands.
5119       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5120         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5121                              N0.getOperand(1),
5122                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5123       // If the desired elements are smaller or larger than the source
5124       // elements we can use a matching integer vector type and then
5125       // truncate/sign extend
5126       else {
5127         EVT MatchingElementType =
5128           EVT::getIntegerVT(*DAG.getContext(),
5129                             N0VT.getScalarType().getSizeInBits());
5130         EVT MatchingVectorType =
5131           EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5132                            N0VT.getVectorNumElements());
5133         SDValue VsetCC =
5134           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5135                         N0.getOperand(1),
5136                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5137         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5138       }
5139     }
5140
5141     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5142     SDValue SCC =
5143       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5144                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5145                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5146     if (SCC.getNode())
5147       return SCC;
5148   }
5149
5150   return SDValue();
5151 }
5152
5153 /// GetDemandedBits - See if the specified operand can be simplified with the
5154 /// knowledge that only the bits specified by Mask are used.  If so, return the
5155 /// simpler operand, otherwise return a null SDValue.
5156 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5157   switch (V.getOpcode()) {
5158   default: break;
5159   case ISD::Constant: {
5160     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5161     assert(CV != 0 && "Const value should be ConstSDNode.");
5162     const APInt &CVal = CV->getAPIntValue();
5163     APInt NewVal = CVal & Mask;
5164     if (NewVal != CVal)
5165       return DAG.getConstant(NewVal, V.getValueType());
5166     break;
5167   }
5168   case ISD::OR:
5169   case ISD::XOR:
5170     // If the LHS or RHS don't contribute bits to the or, drop them.
5171     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5172       return V.getOperand(1);
5173     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5174       return V.getOperand(0);
5175     break;
5176   case ISD::SRL:
5177     // Only look at single-use SRLs.
5178     if (!V.getNode()->hasOneUse())
5179       break;
5180     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5181       // See if we can recursively simplify the LHS.
5182       unsigned Amt = RHSC->getZExtValue();
5183
5184       // Watch out for shift count overflow though.
5185       if (Amt >= Mask.getBitWidth()) break;
5186       APInt NewMask = Mask << Amt;
5187       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5188       if (SimplifyLHS.getNode())
5189         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5190                            SimplifyLHS, V.getOperand(1));
5191     }
5192   }
5193   return SDValue();
5194 }
5195
5196 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5197 /// bits and then truncated to a narrower type and where N is a multiple
5198 /// of number of bits of the narrower type, transform it to a narrower load
5199 /// from address + N / num of bits of new type. If the result is to be
5200 /// extended, also fold the extension to form a extending load.
5201 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5202   unsigned Opc = N->getOpcode();
5203
5204   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5205   SDValue N0 = N->getOperand(0);
5206   EVT VT = N->getValueType(0);
5207   EVT ExtVT = VT;
5208
5209   // This transformation isn't valid for vector loads.
5210   if (VT.isVector())
5211     return SDValue();
5212
5213   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5214   // extended to VT.
5215   if (Opc == ISD::SIGN_EXTEND_INREG) {
5216     ExtType = ISD::SEXTLOAD;
5217     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5218   } else if (Opc == ISD::SRL) {
5219     // Another special-case: SRL is basically zero-extending a narrower value.
5220     ExtType = ISD::ZEXTLOAD;
5221     N0 = SDValue(N, 0);
5222     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5223     if (!N01) return SDValue();
5224     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5225                               VT.getSizeInBits() - N01->getZExtValue());
5226   }
5227   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5228     return SDValue();
5229
5230   unsigned EVTBits = ExtVT.getSizeInBits();
5231
5232   // Do not generate loads of non-round integer types since these can
5233   // be expensive (and would be wrong if the type is not byte sized).
5234   if (!ExtVT.isRound())
5235     return SDValue();
5236
5237   unsigned ShAmt = 0;
5238   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5239     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5240       ShAmt = N01->getZExtValue();
5241       // Is the shift amount a multiple of size of VT?
5242       if ((ShAmt & (EVTBits-1)) == 0) {
5243         N0 = N0.getOperand(0);
5244         // Is the load width a multiple of size of VT?
5245         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5246           return SDValue();
5247       }
5248
5249       // At this point, we must have a load or else we can't do the transform.
5250       if (!isa<LoadSDNode>(N0)) return SDValue();
5251
5252       // Because a SRL must be assumed to *need* to zero-extend the high bits
5253       // (as opposed to anyext the high bits), we can't combine the zextload
5254       // lowering of SRL and an sextload.
5255       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5256         return SDValue();
5257
5258       // If the shift amount is larger than the input type then we're not
5259       // accessing any of the loaded bytes.  If the load was a zextload/extload
5260       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5261       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5262         return SDValue();
5263     }
5264   }
5265
5266   // If the load is shifted left (and the result isn't shifted back right),
5267   // we can fold the truncate through the shift.
5268   unsigned ShLeftAmt = 0;
5269   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5270       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5271     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5272       ShLeftAmt = N01->getZExtValue();
5273       N0 = N0.getOperand(0);
5274     }
5275   }
5276
5277   // If we haven't found a load, we can't narrow it.  Don't transform one with
5278   // multiple uses, this would require adding a new load.
5279   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5280     return SDValue();
5281
5282   // Don't change the width of a volatile load.
5283   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5284   if (LN0->isVolatile())
5285     return SDValue();
5286
5287   // Verify that we are actually reducing a load width here.
5288   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5289     return SDValue();
5290
5291   // For the transform to be legal, the load must produce only two values
5292   // (the value loaded and the chain).  Don't transform a pre-increment
5293   // load, for example, which produces an extra value.  Otherwise the
5294   // transformation is not equivalent, and the downstream logic to replace
5295   // uses gets things wrong.
5296   if (LN0->getNumValues() > 2)
5297     return SDValue();
5298
5299   // If the load that we're shrinking is an extload and we're not just
5300   // discarding the extension we can't simply shrink the load. Bail.
5301   // TODO: It would be possible to merge the extensions in some cases.
5302   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5303       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5304     return SDValue();
5305
5306   EVT PtrType = N0.getOperand(1).getValueType();
5307
5308   if (PtrType == MVT::Untyped || PtrType.isExtended())
5309     // It's not possible to generate a constant of extended or untyped type.
5310     return SDValue();
5311
5312   // For big endian targets, we need to adjust the offset to the pointer to
5313   // load the correct bytes.
5314   if (TLI.isBigEndian()) {
5315     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5316     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5317     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5318   }
5319
5320   uint64_t PtrOff = ShAmt / 8;
5321   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5322   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5323                                PtrType, LN0->getBasePtr(),
5324                                DAG.getConstant(PtrOff, PtrType));
5325   AddToWorkList(NewPtr.getNode());
5326
5327   SDValue Load;
5328   if (ExtType == ISD::NON_EXTLOAD)
5329     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5330                         LN0->getPointerInfo().getWithOffset(PtrOff),
5331                         LN0->isVolatile(), LN0->isNonTemporal(),
5332                         LN0->isInvariant(), NewAlign);
5333   else
5334     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5335                           LN0->getPointerInfo().getWithOffset(PtrOff),
5336                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5337                           NewAlign);
5338
5339   // Replace the old load's chain with the new load's chain.
5340   WorkListRemover DeadNodes(*this);
5341   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5342
5343   // Shift the result left, if we've swallowed a left shift.
5344   SDValue Result = Load;
5345   if (ShLeftAmt != 0) {
5346     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5347     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5348       ShImmTy = VT;
5349     // If the shift amount is as large as the result size (but, presumably,
5350     // no larger than the source) then the useful bits of the result are
5351     // zero; we can't simply return the shortened shift, because the result
5352     // of that operation is undefined.
5353     if (ShLeftAmt >= VT.getSizeInBits())
5354       Result = DAG.getConstant(0, VT);
5355     else
5356       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5357                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5358   }
5359
5360   // Return the new loaded value.
5361   return Result;
5362 }
5363
5364 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5365   SDValue N0 = N->getOperand(0);
5366   SDValue N1 = N->getOperand(1);
5367   EVT VT = N->getValueType(0);
5368   EVT EVT = cast<VTSDNode>(N1)->getVT();
5369   unsigned VTBits = VT.getScalarType().getSizeInBits();
5370   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5371
5372   // fold (sext_in_reg c1) -> c1
5373   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5374     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5375
5376   // If the input is already sign extended, just drop the extension.
5377   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5378     return N0;
5379
5380   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5381   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5382       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5383     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5384                        N0.getOperand(0), N1);
5385
5386   // fold (sext_in_reg (sext x)) -> (sext x)
5387   // fold (sext_in_reg (aext x)) -> (sext x)
5388   // if x is small enough.
5389   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5390     SDValue N00 = N0.getOperand(0);
5391     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5392         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5393       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5394   }
5395
5396   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5397   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5398     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5399
5400   // fold operands of sext_in_reg based on knowledge that the top bits are not
5401   // demanded.
5402   if (SimplifyDemandedBits(SDValue(N, 0)))
5403     return SDValue(N, 0);
5404
5405   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5406   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5407   SDValue NarrowLoad = ReduceLoadWidth(N);
5408   if (NarrowLoad.getNode())
5409     return NarrowLoad;
5410
5411   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5412   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5413   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5414   if (N0.getOpcode() == ISD::SRL) {
5415     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5416       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5417         // We can turn this into an SRA iff the input to the SRL is already sign
5418         // extended enough.
5419         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5420         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5421           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5422                              N0.getOperand(0), N0.getOperand(1));
5423       }
5424   }
5425
5426   // fold (sext_inreg (extload x)) -> (sextload x)
5427   if (ISD::isEXTLoad(N0.getNode()) &&
5428       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5429       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5430       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5431        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5432     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5433     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5434                                      LN0->getChain(),
5435                                      LN0->getBasePtr(), LN0->getPointerInfo(),
5436                                      EVT,
5437                                      LN0->isVolatile(), LN0->isNonTemporal(),
5438                                      LN0->getAlignment());
5439     CombineTo(N, ExtLoad);
5440     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5441     AddToWorkList(ExtLoad.getNode());
5442     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5443   }
5444   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5445   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5446       N0.hasOneUse() &&
5447       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5448       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5449        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5450     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5451     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5452                                      LN0->getChain(),
5453                                      LN0->getBasePtr(), LN0->getPointerInfo(),
5454                                      EVT,
5455                                      LN0->isVolatile(), LN0->isNonTemporal(),
5456                                      LN0->getAlignment());
5457     CombineTo(N, ExtLoad);
5458     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5459     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5460   }
5461
5462   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5463   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5464     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5465                                        N0.getOperand(1), false);
5466     if (BSwap.getNode() != 0)
5467       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5468                          BSwap, N1);
5469   }
5470
5471   return SDValue();
5472 }
5473
5474 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5475   SDValue N0 = N->getOperand(0);
5476   EVT VT = N->getValueType(0);
5477   bool isLE = TLI.isLittleEndian();
5478
5479   // noop truncate
5480   if (N0.getValueType() == N->getValueType(0))
5481     return N0;
5482   // fold (truncate c1) -> c1
5483   if (isa<ConstantSDNode>(N0))
5484     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5485   // fold (truncate (truncate x)) -> (truncate x)
5486   if (N0.getOpcode() == ISD::TRUNCATE)
5487     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5488   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5489   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5490       N0.getOpcode() == ISD::SIGN_EXTEND ||
5491       N0.getOpcode() == ISD::ANY_EXTEND) {
5492     if (N0.getOperand(0).getValueType().bitsLT(VT))
5493       // if the source is smaller than the dest, we still need an extend
5494       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5495                          N0.getOperand(0));
5496     if (N0.getOperand(0).getValueType().bitsGT(VT))
5497       // if the source is larger than the dest, than we just need the truncate
5498       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5499     // if the source and dest are the same type, we can drop both the extend
5500     // and the truncate.
5501     return N0.getOperand(0);
5502   }
5503
5504   // Fold extract-and-trunc into a narrow extract. For example:
5505   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5506   //   i32 y = TRUNCATE(i64 x)
5507   //        -- becomes --
5508   //   v16i8 b = BITCAST (v2i64 val)
5509   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5510   //
5511   // Note: We only run this optimization after type legalization (which often
5512   // creates this pattern) and before operation legalization after which
5513   // we need to be more careful about the vector instructions that we generate.
5514   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5515       LegalTypes && !LegalOperations && N0->hasOneUse()) {
5516
5517     EVT VecTy = N0.getOperand(0).getValueType();
5518     EVT ExTy = N0.getValueType();
5519     EVT TrTy = N->getValueType(0);
5520
5521     unsigned NumElem = VecTy.getVectorNumElements();
5522     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5523
5524     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5525     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5526
5527     SDValue EltNo = N0->getOperand(1);
5528     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5529       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5530       EVT IndexTy = TLI.getVectorIdxTy();
5531       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5532
5533       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5534                               NVT, N0.getOperand(0));
5535
5536       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5537                          SDLoc(N), TrTy, V,
5538                          DAG.getConstant(Index, IndexTy));
5539     }
5540   }
5541
5542   // Fold a series of buildvector, bitcast, and truncate if possible.
5543   // For example fold
5544   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5545   //   (2xi32 (buildvector x, y)).
5546   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5547       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5548       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5549       N0.getOperand(0).hasOneUse()) {
5550
5551     SDValue BuildVect = N0.getOperand(0);
5552     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5553     EVT TruncVecEltTy = VT.getVectorElementType();
5554
5555     // Check that the element types match.
5556     if (BuildVectEltTy == TruncVecEltTy) {
5557       // Now we only need to compute the offset of the truncated elements.
5558       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
5559       unsigned TruncVecNumElts = VT.getVectorNumElements();
5560       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5561
5562       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5563              "Invalid number of elements");
5564
5565       SmallVector<SDValue, 8> Opnds;
5566       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5567         Opnds.push_back(BuildVect.getOperand(i));
5568
5569       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
5570                          Opnds.size());
5571     }
5572   }
5573
5574   // See if we can simplify the input to this truncate through knowledge that
5575   // only the low bits are being used.
5576   // For example "trunc (or (shl x, 8), y)" // -> trunc y
5577   // Currently we only perform this optimization on scalars because vectors
5578   // may have different active low bits.
5579   if (!VT.isVector()) {
5580     SDValue Shorter =
5581       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5582                                                VT.getSizeInBits()));
5583     if (Shorter.getNode())
5584       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
5585   }
5586   // fold (truncate (load x)) -> (smaller load x)
5587   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5588   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5589     SDValue Reduced = ReduceLoadWidth(N);
5590     if (Reduced.getNode())
5591       return Reduced;
5592   }
5593   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
5594   // where ... are all 'undef'.
5595   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
5596     SmallVector<EVT, 8> VTs;
5597     SDValue V;
5598     unsigned Idx = 0;
5599     unsigned NumDefs = 0;
5600
5601     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
5602       SDValue X = N0.getOperand(i);
5603       if (X.getOpcode() != ISD::UNDEF) {
5604         V = X;
5605         Idx = i;
5606         NumDefs++;
5607       }
5608       // Stop if more than one members are non-undef.
5609       if (NumDefs > 1)
5610         break;
5611       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
5612                                      VT.getVectorElementType(),
5613                                      X.getValueType().getVectorNumElements()));
5614     }
5615
5616     if (NumDefs == 0)
5617       return DAG.getUNDEF(VT);
5618
5619     if (NumDefs == 1) {
5620       assert(V.getNode() && "The single defined operand is empty!");
5621       SmallVector<SDValue, 8> Opnds;
5622       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
5623         if (i != Idx) {
5624           Opnds.push_back(DAG.getUNDEF(VTs[i]));
5625           continue;
5626         }
5627         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
5628         AddToWorkList(NV.getNode());
5629         Opnds.push_back(NV);
5630       }
5631       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
5632                          &Opnds[0], Opnds.size());
5633     }
5634   }
5635
5636   // Simplify the operands using demanded-bits information.
5637   if (!VT.isVector() &&
5638       SimplifyDemandedBits(SDValue(N, 0)))
5639     return SDValue(N, 0);
5640
5641   return SDValue();
5642 }
5643
5644 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
5645   SDValue Elt = N->getOperand(i);
5646   if (Elt.getOpcode() != ISD::MERGE_VALUES)
5647     return Elt.getNode();
5648   return Elt.getOperand(Elt.getResNo()).getNode();
5649 }
5650
5651 /// CombineConsecutiveLoads - build_pair (load, load) -> load
5652 /// if load locations are consecutive.
5653 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
5654   assert(N->getOpcode() == ISD::BUILD_PAIR);
5655
5656   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
5657   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
5658   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
5659       LD1->getPointerInfo().getAddrSpace() !=
5660          LD2->getPointerInfo().getAddrSpace())
5661     return SDValue();
5662   EVT LD1VT = LD1->getValueType(0);
5663
5664   if (ISD::isNON_EXTLoad(LD2) &&
5665       LD2->hasOneUse() &&
5666       // If both are volatile this would reduce the number of volatile loads.
5667       // If one is volatile it might be ok, but play conservative and bail out.
5668       !LD1->isVolatile() &&
5669       !LD2->isVolatile() &&
5670       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
5671     unsigned Align = LD1->getAlignment();
5672     unsigned NewAlign = TLI.getDataLayout()->
5673       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5674
5675     if (NewAlign <= Align &&
5676         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
5677       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
5678                          LD1->getBasePtr(), LD1->getPointerInfo(),
5679                          false, false, false, Align);
5680   }
5681
5682   return SDValue();
5683 }
5684
5685 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
5686   SDValue N0 = N->getOperand(0);
5687   EVT VT = N->getValueType(0);
5688
5689   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
5690   // Only do this before legalize, since afterward the target may be depending
5691   // on the bitconvert.
5692   // First check to see if this is all constant.
5693   if (!LegalTypes &&
5694       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
5695       VT.isVector()) {
5696     bool isSimple = true;
5697     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
5698       if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
5699           N0.getOperand(i).getOpcode() != ISD::Constant &&
5700           N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
5701         isSimple = false;
5702         break;
5703       }
5704
5705     EVT DestEltVT = N->getValueType(0).getVectorElementType();
5706     assert(!DestEltVT.isVector() &&
5707            "Element type of vector ValueType must not be vector!");
5708     if (isSimple)
5709       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
5710   }
5711
5712   // If the input is a constant, let getNode fold it.
5713   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
5714     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
5715     if (Res.getNode() != N) {
5716       if (!LegalOperations ||
5717           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
5718         return Res;
5719
5720       // Folding it resulted in an illegal node, and it's too late to
5721       // do that. Clean up the old node and forego the transformation.
5722       // Ideally this won't happen very often, because instcombine
5723       // and the earlier dagcombine runs (where illegal nodes are
5724       // permitted) should have folded most of them already.
5725       DAG.DeleteNode(Res.getNode());
5726     }
5727   }
5728
5729   // (conv (conv x, t1), t2) -> (conv x, t2)
5730   if (N0.getOpcode() == ISD::BITCAST)
5731     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
5732                        N0.getOperand(0));
5733
5734   // fold (conv (load x)) -> (load (conv*)x)
5735   // If the resultant load doesn't need a higher alignment than the original!
5736   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
5737       // Do not change the width of a volatile load.
5738       !cast<LoadSDNode>(N0)->isVolatile() &&
5739       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
5740     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5741     unsigned Align = TLI.getDataLayout()->
5742       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5743     unsigned OrigAlign = LN0->getAlignment();
5744
5745     if (Align <= OrigAlign) {
5746       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
5747                                  LN0->getBasePtr(), LN0->getPointerInfo(),
5748                                  LN0->isVolatile(), LN0->isNonTemporal(),
5749                                  LN0->isInvariant(), OrigAlign);
5750       AddToWorkList(N);
5751       CombineTo(N0.getNode(),
5752                 DAG.getNode(ISD::BITCAST, SDLoc(N0),
5753                             N0.getValueType(), Load),
5754                 Load.getValue(1));
5755       return Load;
5756     }
5757   }
5758
5759   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
5760   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
5761   // This often reduces constant pool loads.
5762   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
5763        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
5764       N0.getNode()->hasOneUse() && VT.isInteger() &&
5765       !VT.isVector() && !N0.getValueType().isVector()) {
5766     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
5767                                   N0.getOperand(0));
5768     AddToWorkList(NewConv.getNode());
5769
5770     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5771     if (N0.getOpcode() == ISD::FNEG)
5772       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
5773                          NewConv, DAG.getConstant(SignBit, VT));
5774     assert(N0.getOpcode() == ISD::FABS);
5775     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5776                        NewConv, DAG.getConstant(~SignBit, VT));
5777   }
5778
5779   // fold (bitconvert (fcopysign cst, x)) ->
5780   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
5781   // Note that we don't handle (copysign x, cst) because this can always be
5782   // folded to an fneg or fabs.
5783   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
5784       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
5785       VT.isInteger() && !VT.isVector()) {
5786     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
5787     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
5788     if (isTypeLegal(IntXVT)) {
5789       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5790                               IntXVT, N0.getOperand(1));
5791       AddToWorkList(X.getNode());
5792
5793       // If X has a different width than the result/lhs, sext it or truncate it.
5794       unsigned VTWidth = VT.getSizeInBits();
5795       if (OrigXWidth < VTWidth) {
5796         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
5797         AddToWorkList(X.getNode());
5798       } else if (OrigXWidth > VTWidth) {
5799         // To get the sign bit in the right place, we have to shift it right
5800         // before truncating.
5801         X = DAG.getNode(ISD::SRL, SDLoc(X),
5802                         X.getValueType(), X,
5803                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
5804         AddToWorkList(X.getNode());
5805         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5806         AddToWorkList(X.getNode());
5807       }
5808
5809       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5810       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
5811                       X, DAG.getConstant(SignBit, VT));
5812       AddToWorkList(X.getNode());
5813
5814       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5815                                 VT, N0.getOperand(0));
5816       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
5817                         Cst, DAG.getConstant(~SignBit, VT));
5818       AddToWorkList(Cst.getNode());
5819
5820       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
5821     }
5822   }
5823
5824   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
5825   if (N0.getOpcode() == ISD::BUILD_PAIR) {
5826     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
5827     if (CombineLD.getNode())
5828       return CombineLD;
5829   }
5830
5831   return SDValue();
5832 }
5833
5834 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
5835   EVT VT = N->getValueType(0);
5836   return CombineConsecutiveLoads(N, VT);
5837 }
5838
5839 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
5840 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
5841 /// destination element value type.
5842 SDValue DAGCombiner::
5843 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
5844   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
5845
5846   // If this is already the right type, we're done.
5847   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
5848
5849   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
5850   unsigned DstBitSize = DstEltVT.getSizeInBits();
5851
5852   // If this is a conversion of N elements of one type to N elements of another
5853   // type, convert each element.  This handles FP<->INT cases.
5854   if (SrcBitSize == DstBitSize) {
5855     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5856                               BV->getValueType(0).getVectorNumElements());
5857
5858     // Due to the FP element handling below calling this routine recursively,
5859     // we can end up with a scalar-to-vector node here.
5860     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
5861       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
5862                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
5863                                      DstEltVT, BV->getOperand(0)));
5864
5865     SmallVector<SDValue, 8> Ops;
5866     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5867       SDValue Op = BV->getOperand(i);
5868       // If the vector element type is not legal, the BUILD_VECTOR operands
5869       // are promoted and implicitly truncated.  Make that explicit here.
5870       if (Op.getValueType() != SrcEltVT)
5871         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
5872       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
5873                                 DstEltVT, Op));
5874       AddToWorkList(Ops.back().getNode());
5875     }
5876     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5877                        &Ops[0], Ops.size());
5878   }
5879
5880   // Otherwise, we're growing or shrinking the elements.  To avoid having to
5881   // handle annoying details of growing/shrinking FP values, we convert them to
5882   // int first.
5883   if (SrcEltVT.isFloatingPoint()) {
5884     // Convert the input float vector to a int vector where the elements are the
5885     // same sizes.
5886     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
5887     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
5888     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
5889     SrcEltVT = IntVT;
5890   }
5891
5892   // Now we know the input is an integer vector.  If the output is a FP type,
5893   // convert to integer first, then to FP of the right size.
5894   if (DstEltVT.isFloatingPoint()) {
5895     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
5896     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
5897     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
5898
5899     // Next, convert to FP elements of the same size.
5900     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
5901   }
5902
5903   // Okay, we know the src/dst types are both integers of differing types.
5904   // Handling growing first.
5905   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
5906   if (SrcBitSize < DstBitSize) {
5907     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
5908
5909     SmallVector<SDValue, 8> Ops;
5910     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
5911          i += NumInputsPerOutput) {
5912       bool isLE = TLI.isLittleEndian();
5913       APInt NewBits = APInt(DstBitSize, 0);
5914       bool EltIsUndef = true;
5915       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
5916         // Shift the previously computed bits over.
5917         NewBits <<= SrcBitSize;
5918         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
5919         if (Op.getOpcode() == ISD::UNDEF) continue;
5920         EltIsUndef = false;
5921
5922         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
5923                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
5924       }
5925
5926       if (EltIsUndef)
5927         Ops.push_back(DAG.getUNDEF(DstEltVT));
5928       else
5929         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
5930     }
5931
5932     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
5933     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5934                        &Ops[0], Ops.size());
5935   }
5936
5937   // Finally, this must be the case where we are shrinking elements: each input
5938   // turns into multiple outputs.
5939   bool isS2V = ISD::isScalarToVector(BV);
5940   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
5941   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5942                             NumOutputsPerInput*BV->getNumOperands());
5943   SmallVector<SDValue, 8> Ops;
5944
5945   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5946     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
5947       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
5948         Ops.push_back(DAG.getUNDEF(DstEltVT));
5949       continue;
5950     }
5951
5952     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
5953                   getAPIntValue().zextOrTrunc(SrcBitSize);
5954
5955     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
5956       APInt ThisVal = OpVal.trunc(DstBitSize);
5957       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
5958       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
5959         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
5960         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
5961                            Ops[0]);
5962       OpVal = OpVal.lshr(DstBitSize);
5963     }
5964
5965     // For big endian targets, swap the order of the pieces of each element.
5966     if (TLI.isBigEndian())
5967       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
5968   }
5969
5970   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5971                      &Ops[0], Ops.size());
5972 }
5973
5974 SDValue DAGCombiner::visitFADD(SDNode *N) {
5975   SDValue N0 = N->getOperand(0);
5976   SDValue N1 = N->getOperand(1);
5977   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5978   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5979   EVT VT = N->getValueType(0);
5980
5981   // fold vector ops
5982   if (VT.isVector()) {
5983     SDValue FoldedVOp = SimplifyVBinOp(N);
5984     if (FoldedVOp.getNode()) return FoldedVOp;
5985   }
5986
5987   // fold (fadd c1, c2) -> c1 + c2
5988   if (N0CFP && N1CFP)
5989     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
5990   // canonicalize constant to RHS
5991   if (N0CFP && !N1CFP)
5992     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
5993   // fold (fadd A, 0) -> A
5994   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
5995       N1CFP->getValueAPF().isZero())
5996     return N0;
5997   // fold (fadd A, (fneg B)) -> (fsub A, B)
5998   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
5999     isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6000     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6001                        GetNegatedExpression(N1, DAG, LegalOperations));
6002   // fold (fadd (fneg A), B) -> (fsub B, A)
6003   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6004     isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6005     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6006                        GetNegatedExpression(N0, DAG, LegalOperations));
6007
6008   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6009   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6010       N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6011       isa<ConstantFPSDNode>(N0.getOperand(1)))
6012     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6013                        DAG.getNode(ISD::FADD, SDLoc(N), VT,
6014                                    N0.getOperand(1), N1));
6015
6016   // No FP constant should be created after legalization as Instruction
6017   // Selection pass has hard time in dealing with FP constant.
6018   //
6019   // We don't need test this condition for transformation like following, as
6020   // the DAG being transformed implies it is legal to take FP constant as
6021   // operand.
6022   //
6023   //  (fadd (fmul c, x), x) -> (fmul c+1, x)
6024   //
6025   bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6026
6027   // If allow, fold (fadd (fneg x), x) -> 0.0
6028   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6029       N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6030     return DAG.getConstantFP(0.0, VT);
6031
6032     // If allow, fold (fadd x, (fneg x)) -> 0.0
6033   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6034       N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6035     return DAG.getConstantFP(0.0, VT);
6036
6037   // In unsafe math mode, we can fold chains of FADD's of the same value
6038   // into multiplications.  This transform is not safe in general because
6039   // we are reducing the number of rounding steps.
6040   if (DAG.getTarget().Options.UnsafeFPMath &&
6041       TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6042       !N0CFP && !N1CFP) {
6043     if (N0.getOpcode() == ISD::FMUL) {
6044       ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6045       ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6046
6047       // (fadd (fmul c, x), x) -> (fmul x, c+1)
6048       if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6049         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6050                                      SDValue(CFP00, 0),
6051                                      DAG.getConstantFP(1.0, VT));
6052         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6053                            N1, NewCFP);
6054       }
6055
6056       // (fadd (fmul x, c), x) -> (fmul x, c+1)
6057       if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6058         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6059                                      SDValue(CFP01, 0),
6060                                      DAG.getConstantFP(1.0, VT));
6061         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6062                            N1, NewCFP);
6063       }
6064
6065       // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6066       if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6067           N1.getOperand(0) == N1.getOperand(1) &&
6068           N0.getOperand(1) == N1.getOperand(0)) {
6069         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6070                                      SDValue(CFP00, 0),
6071                                      DAG.getConstantFP(2.0, VT));
6072         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6073                            N0.getOperand(1), NewCFP);
6074       }
6075
6076       // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6077       if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6078           N1.getOperand(0) == N1.getOperand(1) &&
6079           N0.getOperand(0) == N1.getOperand(0)) {
6080         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6081                                      SDValue(CFP01, 0),
6082                                      DAG.getConstantFP(2.0, VT));
6083         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6084                            N0.getOperand(0), NewCFP);
6085       }
6086     }
6087
6088     if (N1.getOpcode() == ISD::FMUL) {
6089       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6090       ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6091
6092       // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6093       if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6094         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6095                                      SDValue(CFP10, 0),
6096                                      DAG.getConstantFP(1.0, VT));
6097         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6098                            N0, NewCFP);
6099       }
6100
6101       // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6102       if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6103         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6104                                      SDValue(CFP11, 0),
6105                                      DAG.getConstantFP(1.0, VT));
6106         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6107                            N0, NewCFP);
6108       }
6109
6110
6111       // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6112       if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6113           N0.getOperand(0) == N0.getOperand(1) &&
6114           N1.getOperand(1) == N0.getOperand(0)) {
6115         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6116                                      SDValue(CFP10, 0),
6117                                      DAG.getConstantFP(2.0, VT));
6118         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6119                            N1.getOperand(1), NewCFP);
6120       }
6121
6122       // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6123       if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6124           N0.getOperand(0) == N0.getOperand(1) &&
6125           N1.getOperand(0) == N0.getOperand(0)) {
6126         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6127                                      SDValue(CFP11, 0),
6128                                      DAG.getConstantFP(2.0, VT));
6129         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6130                            N1.getOperand(0), NewCFP);
6131       }
6132     }
6133
6134     if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6135       ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6136       // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6137       if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6138           (N0.getOperand(0) == N1))
6139         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6140                            N1, DAG.getConstantFP(3.0, VT));
6141     }
6142
6143     if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6144       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6145       // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6146       if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6147           N1.getOperand(0) == N0)
6148         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6149                            N0, DAG.getConstantFP(3.0, VT));
6150     }
6151
6152     // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6153     if (AllowNewFpConst &&
6154         N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6155         N0.getOperand(0) == N0.getOperand(1) &&
6156         N1.getOperand(0) == N1.getOperand(1) &&
6157         N0.getOperand(0) == N1.getOperand(0))
6158       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6159                          N0.getOperand(0),
6160                          DAG.getConstantFP(4.0, VT));
6161   }
6162
6163   // FADD -> FMA combines:
6164   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6165        DAG.getTarget().Options.UnsafeFPMath) &&
6166       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6167       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6168
6169     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6170     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6171       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6172                          N0.getOperand(0), N0.getOperand(1), N1);
6173
6174     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6175     // Note: Commutes FADD operands.
6176     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6177       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6178                          N1.getOperand(0), N1.getOperand(1), N0);
6179   }
6180
6181   return SDValue();
6182 }
6183
6184 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6185   SDValue N0 = N->getOperand(0);
6186   SDValue N1 = N->getOperand(1);
6187   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6188   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6189   EVT VT = N->getValueType(0);
6190   SDLoc dl(N);
6191
6192   // fold vector ops
6193   if (VT.isVector()) {
6194     SDValue FoldedVOp = SimplifyVBinOp(N);
6195     if (FoldedVOp.getNode()) return FoldedVOp;
6196   }
6197
6198   // fold (fsub c1, c2) -> c1-c2
6199   if (N0CFP && N1CFP)
6200     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6201   // fold (fsub A, 0) -> A
6202   if (DAG.getTarget().Options.UnsafeFPMath &&
6203       N1CFP && N1CFP->getValueAPF().isZero())
6204     return N0;
6205   // fold (fsub 0, B) -> -B
6206   if (DAG.getTarget().Options.UnsafeFPMath &&
6207       N0CFP && N0CFP->getValueAPF().isZero()) {
6208     if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6209       return GetNegatedExpression(N1, DAG, LegalOperations);
6210     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6211       return DAG.getNode(ISD::FNEG, dl, VT, N1);
6212   }
6213   // fold (fsub A, (fneg B)) -> (fadd A, B)
6214   if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6215     return DAG.getNode(ISD::FADD, dl, VT, N0,
6216                        GetNegatedExpression(N1, DAG, LegalOperations));
6217
6218   // If 'unsafe math' is enabled, fold
6219   //    (fsub x, x) -> 0.0 &
6220   //    (fsub x, (fadd x, y)) -> (fneg y) &
6221   //    (fsub x, (fadd y, x)) -> (fneg y)
6222   if (DAG.getTarget().Options.UnsafeFPMath) {
6223     if (N0 == N1)
6224       return DAG.getConstantFP(0.0f, VT);
6225
6226     if (N1.getOpcode() == ISD::FADD) {
6227       SDValue N10 = N1->getOperand(0);
6228       SDValue N11 = N1->getOperand(1);
6229
6230       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6231                                           &DAG.getTarget().Options))
6232         return GetNegatedExpression(N11, DAG, LegalOperations);
6233
6234       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6235                                           &DAG.getTarget().Options))
6236         return GetNegatedExpression(N10, DAG, LegalOperations);
6237     }
6238   }
6239
6240   // FSUB -> FMA combines:
6241   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6242        DAG.getTarget().Options.UnsafeFPMath) &&
6243       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6244       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6245
6246     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6247     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6248       return DAG.getNode(ISD::FMA, dl, VT,
6249                          N0.getOperand(0), N0.getOperand(1),
6250                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6251
6252     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6253     // Note: Commutes FSUB operands.
6254     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6255       return DAG.getNode(ISD::FMA, dl, VT,
6256                          DAG.getNode(ISD::FNEG, dl, VT,
6257                          N1.getOperand(0)),
6258                          N1.getOperand(1), N0);
6259
6260     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6261     if (N0.getOpcode() == ISD::FNEG &&
6262         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6263         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6264       SDValue N00 = N0.getOperand(0).getOperand(0);
6265       SDValue N01 = N0.getOperand(0).getOperand(1);
6266       return DAG.getNode(ISD::FMA, dl, VT,
6267                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6268                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6269     }
6270   }
6271
6272   return SDValue();
6273 }
6274
6275 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6276   SDValue N0 = N->getOperand(0);
6277   SDValue N1 = N->getOperand(1);
6278   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6279   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6280   EVT VT = N->getValueType(0);
6281   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6282
6283   // fold vector ops
6284   if (VT.isVector()) {
6285     SDValue FoldedVOp = SimplifyVBinOp(N);
6286     if (FoldedVOp.getNode()) return FoldedVOp;
6287   }
6288
6289   // fold (fmul c1, c2) -> c1*c2
6290   if (N0CFP && N1CFP)
6291     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6292   // canonicalize constant to RHS
6293   if (N0CFP && !N1CFP)
6294     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6295   // fold (fmul A, 0) -> 0
6296   if (DAG.getTarget().Options.UnsafeFPMath &&
6297       N1CFP && N1CFP->getValueAPF().isZero())
6298     return N1;
6299   // fold (fmul A, 0) -> 0, vector edition.
6300   if (DAG.getTarget().Options.UnsafeFPMath &&
6301       ISD::isBuildVectorAllZeros(N1.getNode()))
6302     return N1;
6303   // fold (fmul A, 1.0) -> A
6304   if (N1CFP && N1CFP->isExactlyValue(1.0))
6305     return N0;
6306   // fold (fmul X, 2.0) -> (fadd X, X)
6307   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6308     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6309   // fold (fmul X, -1.0) -> (fneg X)
6310   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6311     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6312       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6313
6314   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6315   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6316                                        &DAG.getTarget().Options)) {
6317     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6318                                          &DAG.getTarget().Options)) {
6319       // Both can be negated for free, check to see if at least one is cheaper
6320       // negated.
6321       if (LHSNeg == 2 || RHSNeg == 2)
6322         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6323                            GetNegatedExpression(N0, DAG, LegalOperations),
6324                            GetNegatedExpression(N1, DAG, LegalOperations));
6325     }
6326   }
6327
6328   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6329   if (DAG.getTarget().Options.UnsafeFPMath &&
6330       N1CFP && N0.getOpcode() == ISD::FMUL &&
6331       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6332     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6333                        DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6334                                    N0.getOperand(1), N1));
6335
6336   return SDValue();
6337 }
6338
6339 SDValue DAGCombiner::visitFMA(SDNode *N) {
6340   SDValue N0 = N->getOperand(0);
6341   SDValue N1 = N->getOperand(1);
6342   SDValue N2 = N->getOperand(2);
6343   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6344   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6345   EVT VT = N->getValueType(0);
6346   SDLoc dl(N);
6347
6348   if (DAG.getTarget().Options.UnsafeFPMath) {
6349     if (N0CFP && N0CFP->isZero())
6350       return N2;
6351     if (N1CFP && N1CFP->isZero())
6352       return N2;
6353   }
6354   if (N0CFP && N0CFP->isExactlyValue(1.0))
6355     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6356   if (N1CFP && N1CFP->isExactlyValue(1.0))
6357     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6358
6359   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6360   if (N0CFP && !N1CFP)
6361     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6362
6363   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6364   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6365       N2.getOpcode() == ISD::FMUL &&
6366       N0 == N2.getOperand(0) &&
6367       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6368     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6369                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6370   }
6371
6372
6373   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6374   if (DAG.getTarget().Options.UnsafeFPMath &&
6375       N0.getOpcode() == ISD::FMUL && N1CFP &&
6376       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6377     return DAG.getNode(ISD::FMA, dl, VT,
6378                        N0.getOperand(0),
6379                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6380                        N2);
6381   }
6382
6383   // (fma x, 1, y) -> (fadd x, y)
6384   // (fma x, -1, y) -> (fadd (fneg x), y)
6385   if (N1CFP) {
6386     if (N1CFP->isExactlyValue(1.0))
6387       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6388
6389     if (N1CFP->isExactlyValue(-1.0) &&
6390         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6391       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6392       AddToWorkList(RHSNeg.getNode());
6393       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6394     }
6395   }
6396
6397   // (fma x, c, x) -> (fmul x, (c+1))
6398   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6399     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6400                        DAG.getNode(ISD::FADD, dl, VT,
6401                                    N1, DAG.getConstantFP(1.0, VT)));
6402
6403   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6404   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6405       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6406     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6407                        DAG.getNode(ISD::FADD, dl, VT,
6408                                    N1, DAG.getConstantFP(-1.0, VT)));
6409
6410
6411   return SDValue();
6412 }
6413
6414 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6415   SDValue N0 = N->getOperand(0);
6416   SDValue N1 = N->getOperand(1);
6417   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6418   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6419   EVT VT = N->getValueType(0);
6420   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6421
6422   // fold vector ops
6423   if (VT.isVector()) {
6424     SDValue FoldedVOp = SimplifyVBinOp(N);
6425     if (FoldedVOp.getNode()) return FoldedVOp;
6426   }
6427
6428   // fold (fdiv c1, c2) -> c1/c2
6429   if (N0CFP && N1CFP)
6430     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6431
6432   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6433   if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6434     // Compute the reciprocal 1.0 / c2.
6435     APFloat N1APF = N1CFP->getValueAPF();
6436     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6437     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6438     // Only do the transform if the reciprocal is a legal fp immediate that
6439     // isn't too nasty (eg NaN, denormal, ...).
6440     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6441         (!LegalOperations ||
6442          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6443          // backend)... we should handle this gracefully after Legalize.
6444          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6445          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6446          TLI.isFPImmLegal(Recip, VT)))
6447       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6448                          DAG.getConstantFP(Recip, VT));
6449   }
6450
6451   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6452   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6453                                        &DAG.getTarget().Options)) {
6454     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6455                                          &DAG.getTarget().Options)) {
6456       // Both can be negated for free, check to see if at least one is cheaper
6457       // negated.
6458       if (LHSNeg == 2 || RHSNeg == 2)
6459         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6460                            GetNegatedExpression(N0, DAG, LegalOperations),
6461                            GetNegatedExpression(N1, DAG, LegalOperations));
6462     }
6463   }
6464
6465   return SDValue();
6466 }
6467
6468 SDValue DAGCombiner::visitFREM(SDNode *N) {
6469   SDValue N0 = N->getOperand(0);
6470   SDValue N1 = N->getOperand(1);
6471   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6472   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6473   EVT VT = N->getValueType(0);
6474
6475   // fold (frem c1, c2) -> fmod(c1,c2)
6476   if (N0CFP && N1CFP)
6477     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6478
6479   return SDValue();
6480 }
6481
6482 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6483   SDValue N0 = N->getOperand(0);
6484   SDValue N1 = N->getOperand(1);
6485   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6486   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6487   EVT VT = N->getValueType(0);
6488
6489   if (N0CFP && N1CFP)  // Constant fold
6490     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6491
6492   if (N1CFP) {
6493     const APFloat& V = N1CFP->getValueAPF();
6494     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
6495     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6496     if (!V.isNegative()) {
6497       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6498         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6499     } else {
6500       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6501         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6502                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6503     }
6504   }
6505
6506   // copysign(fabs(x), y) -> copysign(x, y)
6507   // copysign(fneg(x), y) -> copysign(x, y)
6508   // copysign(copysign(x,z), y) -> copysign(x, y)
6509   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6510       N0.getOpcode() == ISD::FCOPYSIGN)
6511     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6512                        N0.getOperand(0), N1);
6513
6514   // copysign(x, abs(y)) -> abs(x)
6515   if (N1.getOpcode() == ISD::FABS)
6516     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6517
6518   // copysign(x, copysign(y,z)) -> copysign(x, z)
6519   if (N1.getOpcode() == ISD::FCOPYSIGN)
6520     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6521                        N0, N1.getOperand(1));
6522
6523   // copysign(x, fp_extend(y)) -> copysign(x, y)
6524   // copysign(x, fp_round(y)) -> copysign(x, y)
6525   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6526     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6527                        N0, N1.getOperand(0));
6528
6529   return SDValue();
6530 }
6531
6532 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6533   SDValue N0 = N->getOperand(0);
6534   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6535   EVT VT = N->getValueType(0);
6536   EVT OpVT = N0.getValueType();
6537
6538   // fold (sint_to_fp c1) -> c1fp
6539   if (N0C &&
6540       // ...but only if the target supports immediate floating-point values
6541       (!LegalOperations ||
6542        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6543     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6544
6545   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6546   // but UINT_TO_FP is legal on this target, try to convert.
6547   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6548       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6549     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6550     if (DAG.SignBitIsZero(N0))
6551       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6552   }
6553
6554   // The next optimizations are desireable only if SELECT_CC can be lowered.
6555   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6556   // having to say they don't support SELECT_CC on every type the DAG knows
6557   // about, since there is no way to mark an opcode illegal at all value types
6558   // (See also visitSELECT)
6559   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6560     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6561     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6562         !VT.isVector() &&
6563         (!LegalOperations ||
6564          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6565       SDValue Ops[] =
6566         { N0.getOperand(0), N0.getOperand(1),
6567           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6568           N0.getOperand(2) };
6569       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6570     }
6571
6572     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6573     //      (select_cc x, y, 1.0, 0.0,, cc)
6574     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6575         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6576         (!LegalOperations ||
6577          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6578       SDValue Ops[] =
6579         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6580           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6581           N0.getOperand(0).getOperand(2) };
6582       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6583     }
6584   }
6585
6586   return SDValue();
6587 }
6588
6589 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6590   SDValue N0 = N->getOperand(0);
6591   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6592   EVT VT = N->getValueType(0);
6593   EVT OpVT = N0.getValueType();
6594
6595   // fold (uint_to_fp c1) -> c1fp
6596   if (N0C &&
6597       // ...but only if the target supports immediate floating-point values
6598       (!LegalOperations ||
6599        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6600     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6601
6602   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6603   // but SINT_TO_FP is legal on this target, try to convert.
6604   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
6605       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
6606     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
6607     if (DAG.SignBitIsZero(N0))
6608       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6609   }
6610
6611   // The next optimizations are desireable only if SELECT_CC can be lowered.
6612   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6613   // having to say they don't support SELECT_CC on every type the DAG knows
6614   // about, since there is no way to mark an opcode illegal at all value types
6615   // (See also visitSELECT)
6616   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6617     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6618
6619     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
6620         (!LegalOperations ||
6621          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6622       SDValue Ops[] =
6623         { N0.getOperand(0), N0.getOperand(1),
6624           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
6625           N0.getOperand(2) };
6626       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6627     }
6628   }
6629
6630   return SDValue();
6631 }
6632
6633 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
6634   SDValue N0 = N->getOperand(0);
6635   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6636   EVT VT = N->getValueType(0);
6637
6638   // fold (fp_to_sint c1fp) -> c1
6639   if (N0CFP)
6640     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
6641
6642   return SDValue();
6643 }
6644
6645 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
6646   SDValue N0 = N->getOperand(0);
6647   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6648   EVT VT = N->getValueType(0);
6649
6650   // fold (fp_to_uint c1fp) -> c1
6651   if (N0CFP)
6652     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
6653
6654   return SDValue();
6655 }
6656
6657 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
6658   SDValue N0 = N->getOperand(0);
6659   SDValue N1 = N->getOperand(1);
6660   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6661   EVT VT = N->getValueType(0);
6662
6663   // fold (fp_round c1fp) -> c1fp
6664   if (N0CFP)
6665     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
6666
6667   // fold (fp_round (fp_extend x)) -> x
6668   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
6669     return N0.getOperand(0);
6670
6671   // fold (fp_round (fp_round x)) -> (fp_round x)
6672   if (N0.getOpcode() == ISD::FP_ROUND) {
6673     // This is a value preserving truncation if both round's are.
6674     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
6675                    N0.getNode()->getConstantOperandVal(1) == 1;
6676     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
6677                        DAG.getIntPtrConstant(IsTrunc));
6678   }
6679
6680   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
6681   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
6682     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
6683                               N0.getOperand(0), N1);
6684     AddToWorkList(Tmp.getNode());
6685     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6686                        Tmp, N0.getOperand(1));
6687   }
6688
6689   return SDValue();
6690 }
6691
6692 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
6693   SDValue N0 = N->getOperand(0);
6694   EVT VT = N->getValueType(0);
6695   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6696   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6697
6698   // fold (fp_round_inreg c1fp) -> c1fp
6699   if (N0CFP && isTypeLegal(EVT)) {
6700     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
6701     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
6702   }
6703
6704   return SDValue();
6705 }
6706
6707 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
6708   SDValue N0 = N->getOperand(0);
6709   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6710   EVT VT = N->getValueType(0);
6711
6712   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
6713   if (N->hasOneUse() &&
6714       N->use_begin()->getOpcode() == ISD::FP_ROUND)
6715     return SDValue();
6716
6717   // fold (fp_extend c1fp) -> c1fp
6718   if (N0CFP)
6719     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
6720
6721   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
6722   // value of X.
6723   if (N0.getOpcode() == ISD::FP_ROUND
6724       && N0.getNode()->getConstantOperandVal(1) == 1) {
6725     SDValue In = N0.getOperand(0);
6726     if (In.getValueType() == VT) return In;
6727     if (VT.bitsLT(In.getValueType()))
6728       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
6729                          In, N0.getOperand(1));
6730     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
6731   }
6732
6733   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
6734   if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
6735       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6736        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
6737     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6738     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6739                                      LN0->getChain(),
6740                                      LN0->getBasePtr(), LN0->getPointerInfo(),
6741                                      N0.getValueType(),
6742                                      LN0->isVolatile(), LN0->isNonTemporal(),
6743                                      LN0->getAlignment());
6744     CombineTo(N, ExtLoad);
6745     CombineTo(N0.getNode(),
6746               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
6747                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
6748               ExtLoad.getValue(1));
6749     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6750   }
6751
6752   return SDValue();
6753 }
6754
6755 SDValue DAGCombiner::visitFNEG(SDNode *N) {
6756   SDValue N0 = N->getOperand(0);
6757   EVT VT = N->getValueType(0);
6758
6759   if (VT.isVector()) {
6760     SDValue FoldedVOp = SimplifyVUnaryOp(N);
6761     if (FoldedVOp.getNode()) return FoldedVOp;
6762   }
6763
6764   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
6765                          &DAG.getTarget().Options))
6766     return GetNegatedExpression(N0, DAG, LegalOperations);
6767
6768   // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
6769   // constant pool values.
6770   if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
6771       !VT.isVector() &&
6772       N0.getNode()->hasOneUse() &&
6773       N0.getOperand(0).getValueType().isInteger()) {
6774     SDValue Int = N0.getOperand(0);
6775     EVT IntVT = Int.getValueType();
6776     if (IntVT.isInteger() && !IntVT.isVector()) {
6777       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
6778               DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6779       AddToWorkList(Int.getNode());
6780       return DAG.getNode(ISD::BITCAST, SDLoc(N),
6781                          VT, Int);
6782     }
6783   }
6784
6785   // (fneg (fmul c, x)) -> (fmul -c, x)
6786   if (N0.getOpcode() == ISD::FMUL) {
6787     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6788     if (CFP1)
6789       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6790                          N0.getOperand(0),
6791                          DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6792                                      N0.getOperand(1)));
6793   }
6794
6795   return SDValue();
6796 }
6797
6798 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
6799   SDValue N0 = N->getOperand(0);
6800   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6801   EVT VT = N->getValueType(0);
6802
6803   // fold (fceil c1) -> fceil(c1)
6804   if (N0CFP)
6805     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
6806
6807   return SDValue();
6808 }
6809
6810 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
6811   SDValue N0 = N->getOperand(0);
6812   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6813   EVT VT = N->getValueType(0);
6814
6815   // fold (ftrunc c1) -> ftrunc(c1)
6816   if (N0CFP)
6817     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
6818
6819   return SDValue();
6820 }
6821
6822 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
6823   SDValue N0 = N->getOperand(0);
6824   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6825   EVT VT = N->getValueType(0);
6826
6827   // fold (ffloor c1) -> ffloor(c1)
6828   if (N0CFP)
6829     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
6830
6831   return SDValue();
6832 }
6833
6834 SDValue DAGCombiner::visitFABS(SDNode *N) {
6835   SDValue N0 = N->getOperand(0);
6836   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6837   EVT VT = N->getValueType(0);
6838
6839   if (VT.isVector()) {
6840     SDValue FoldedVOp = SimplifyVUnaryOp(N);
6841     if (FoldedVOp.getNode()) return FoldedVOp;
6842   }
6843
6844   // fold (fabs c1) -> fabs(c1)
6845   if (N0CFP)
6846     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6847   // fold (fabs (fabs x)) -> (fabs x)
6848   if (N0.getOpcode() == ISD::FABS)
6849     return N->getOperand(0);
6850   // fold (fabs (fneg x)) -> (fabs x)
6851   // fold (fabs (fcopysign x, y)) -> (fabs x)
6852   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
6853     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
6854
6855   // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
6856   // constant pool values.
6857   if (!TLI.isFAbsFree(VT) &&
6858       N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
6859       N0.getOperand(0).getValueType().isInteger() &&
6860       !N0.getOperand(0).getValueType().isVector()) {
6861     SDValue Int = N0.getOperand(0);
6862     EVT IntVT = Int.getValueType();
6863     if (IntVT.isInteger() && !IntVT.isVector()) {
6864       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
6865              DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6866       AddToWorkList(Int.getNode());
6867       return DAG.getNode(ISD::BITCAST, SDLoc(N),
6868                          N->getValueType(0), Int);
6869     }
6870   }
6871
6872   return SDValue();
6873 }
6874
6875 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
6876   SDValue Chain = N->getOperand(0);
6877   SDValue N1 = N->getOperand(1);
6878   SDValue N2 = N->getOperand(2);
6879
6880   // If N is a constant we could fold this into a fallthrough or unconditional
6881   // branch. However that doesn't happen very often in normal code, because
6882   // Instcombine/SimplifyCFG should have handled the available opportunities.
6883   // If we did this folding here, it would be necessary to update the
6884   // MachineBasicBlock CFG, which is awkward.
6885
6886   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
6887   // on the target.
6888   if (N1.getOpcode() == ISD::SETCC &&
6889       TLI.isOperationLegalOrCustom(ISD::BR_CC,
6890                                    N1.getOperand(0).getValueType())) {
6891     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
6892                        Chain, N1.getOperand(2),
6893                        N1.getOperand(0), N1.getOperand(1), N2);
6894   }
6895
6896   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
6897       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
6898        (N1.getOperand(0).hasOneUse() &&
6899         N1.getOperand(0).getOpcode() == ISD::SRL))) {
6900     SDNode *Trunc = 0;
6901     if (N1.getOpcode() == ISD::TRUNCATE) {
6902       // Look pass the truncate.
6903       Trunc = N1.getNode();
6904       N1 = N1.getOperand(0);
6905     }
6906
6907     // Match this pattern so that we can generate simpler code:
6908     //
6909     //   %a = ...
6910     //   %b = and i32 %a, 2
6911     //   %c = srl i32 %b, 1
6912     //   brcond i32 %c ...
6913     //
6914     // into
6915     //
6916     //   %a = ...
6917     //   %b = and i32 %a, 2
6918     //   %c = setcc eq %b, 0
6919     //   brcond %c ...
6920     //
6921     // This applies only when the AND constant value has one bit set and the
6922     // SRL constant is equal to the log2 of the AND constant. The back-end is
6923     // smart enough to convert the result into a TEST/JMP sequence.
6924     SDValue Op0 = N1.getOperand(0);
6925     SDValue Op1 = N1.getOperand(1);
6926
6927     if (Op0.getOpcode() == ISD::AND &&
6928         Op1.getOpcode() == ISD::Constant) {
6929       SDValue AndOp1 = Op0.getOperand(1);
6930
6931       if (AndOp1.getOpcode() == ISD::Constant) {
6932         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
6933
6934         if (AndConst.isPowerOf2() &&
6935             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
6936           SDValue SetCC =
6937             DAG.getSetCC(SDLoc(N),
6938                          getSetCCResultType(Op0.getValueType()),
6939                          Op0, DAG.getConstant(0, Op0.getValueType()),
6940                          ISD::SETNE);
6941
6942           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
6943                                           MVT::Other, Chain, SetCC, N2);
6944           // Don't add the new BRCond into the worklist or else SimplifySelectCC
6945           // will convert it back to (X & C1) >> C2.
6946           CombineTo(N, NewBRCond, false);
6947           // Truncate is dead.
6948           if (Trunc) {
6949             removeFromWorkList(Trunc);
6950             DAG.DeleteNode(Trunc);
6951           }
6952           // Replace the uses of SRL with SETCC
6953           WorkListRemover DeadNodes(*this);
6954           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
6955           removeFromWorkList(N1.getNode());
6956           DAG.DeleteNode(N1.getNode());
6957           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6958         }
6959       }
6960     }
6961
6962     if (Trunc)
6963       // Restore N1 if the above transformation doesn't match.
6964       N1 = N->getOperand(1);
6965   }
6966
6967   // Transform br(xor(x, y)) -> br(x != y)
6968   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
6969   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
6970     SDNode *TheXor = N1.getNode();
6971     SDValue Op0 = TheXor->getOperand(0);
6972     SDValue Op1 = TheXor->getOperand(1);
6973     if (Op0.getOpcode() == Op1.getOpcode()) {
6974       // Avoid missing important xor optimizations.
6975       SDValue Tmp = visitXOR(TheXor);
6976       if (Tmp.getNode()) {
6977         if (Tmp.getNode() != TheXor) {
6978           DEBUG(dbgs() << "\nReplacing.8 ";
6979                 TheXor->dump(&DAG);
6980                 dbgs() << "\nWith: ";
6981                 Tmp.getNode()->dump(&DAG);
6982                 dbgs() << '\n');
6983           WorkListRemover DeadNodes(*this);
6984           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
6985           removeFromWorkList(TheXor);
6986           DAG.DeleteNode(TheXor);
6987           return DAG.getNode(ISD::BRCOND, SDLoc(N),
6988                              MVT::Other, Chain, Tmp, N2);
6989         }
6990
6991         // visitXOR has changed XOR's operands or replaced the XOR completely,
6992         // bail out.
6993         return SDValue(N, 0);
6994       }
6995     }
6996
6997     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
6998       bool Equal = false;
6999       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7000         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7001             Op0.getOpcode() == ISD::XOR) {
7002           TheXor = Op0.getNode();
7003           Equal = true;
7004         }
7005
7006       EVT SetCCVT = N1.getValueType();
7007       if (LegalTypes)
7008         SetCCVT = getSetCCResultType(SetCCVT);
7009       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7010                                    SetCCVT,
7011                                    Op0, Op1,
7012                                    Equal ? ISD::SETEQ : ISD::SETNE);
7013       // Replace the uses of XOR with SETCC
7014       WorkListRemover DeadNodes(*this);
7015       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7016       removeFromWorkList(N1.getNode());
7017       DAG.DeleteNode(N1.getNode());
7018       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7019                          MVT::Other, Chain, SetCC, N2);
7020     }
7021   }
7022
7023   return SDValue();
7024 }
7025
7026 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7027 //
7028 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7029   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7030   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7031
7032   // If N is a constant we could fold this into a fallthrough or unconditional
7033   // branch. However that doesn't happen very often in normal code, because
7034   // Instcombine/SimplifyCFG should have handled the available opportunities.
7035   // If we did this folding here, it would be necessary to update the
7036   // MachineBasicBlock CFG, which is awkward.
7037
7038   // Use SimplifySetCC to simplify SETCC's.
7039   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7040                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7041                                false);
7042   if (Simp.getNode()) AddToWorkList(Simp.getNode());
7043
7044   // fold to a simpler setcc
7045   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7046     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7047                        N->getOperand(0), Simp.getOperand(2),
7048                        Simp.getOperand(0), Simp.getOperand(1),
7049                        N->getOperand(4));
7050
7051   return SDValue();
7052 }
7053
7054 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7055 /// uses N as its base pointer and that N may be folded in the load / store
7056 /// addressing mode.
7057 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7058                                     SelectionDAG &DAG,
7059                                     const TargetLowering &TLI) {
7060   EVT VT;
7061   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7062     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7063       return false;
7064     VT = Use->getValueType(0);
7065   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7066     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7067       return false;
7068     VT = ST->getValue().getValueType();
7069   } else
7070     return false;
7071
7072   TargetLowering::AddrMode AM;
7073   if (N->getOpcode() == ISD::ADD) {
7074     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7075     if (Offset)
7076       // [reg +/- imm]
7077       AM.BaseOffs = Offset->getSExtValue();
7078     else
7079       // [reg +/- reg]
7080       AM.Scale = 1;
7081   } else if (N->getOpcode() == ISD::SUB) {
7082     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7083     if (Offset)
7084       // [reg +/- imm]
7085       AM.BaseOffs = -Offset->getSExtValue();
7086     else
7087       // [reg +/- reg]
7088       AM.Scale = 1;
7089   } else
7090     return false;
7091
7092   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7093 }
7094
7095 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7096 /// pre-indexed load / store when the base pointer is an add or subtract
7097 /// and it has other uses besides the load / store. After the
7098 /// transformation, the new indexed load / store has effectively folded
7099 /// the add / subtract in and all of its other uses are redirected to the
7100 /// new load / store.
7101 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7102   if (Level < AfterLegalizeDAG)
7103     return false;
7104
7105   bool isLoad = true;
7106   SDValue Ptr;
7107   EVT VT;
7108   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7109     if (LD->isIndexed())
7110       return false;
7111     VT = LD->getMemoryVT();
7112     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7113         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7114       return false;
7115     Ptr = LD->getBasePtr();
7116   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7117     if (ST->isIndexed())
7118       return false;
7119     VT = ST->getMemoryVT();
7120     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7121         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7122       return false;
7123     Ptr = ST->getBasePtr();
7124     isLoad = false;
7125   } else {
7126     return false;
7127   }
7128
7129   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7130   // out.  There is no reason to make this a preinc/predec.
7131   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7132       Ptr.getNode()->hasOneUse())
7133     return false;
7134
7135   // Ask the target to do addressing mode selection.
7136   SDValue BasePtr;
7137   SDValue Offset;
7138   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7139   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7140     return false;
7141
7142   // Backends without true r+i pre-indexed forms may need to pass a
7143   // constant base with a variable offset so that constant coercion
7144   // will work with the patterns in canonical form.
7145   bool Swapped = false;
7146   if (isa<ConstantSDNode>(BasePtr)) {
7147     std::swap(BasePtr, Offset);
7148     Swapped = true;
7149   }
7150
7151   // Don't create a indexed load / store with zero offset.
7152   if (isa<ConstantSDNode>(Offset) &&
7153       cast<ConstantSDNode>(Offset)->isNullValue())
7154     return false;
7155
7156   // Try turning it into a pre-indexed load / store except when:
7157   // 1) The new base ptr is a frame index.
7158   // 2) If N is a store and the new base ptr is either the same as or is a
7159   //    predecessor of the value being stored.
7160   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7161   //    that would create a cycle.
7162   // 4) All uses are load / store ops that use it as old base ptr.
7163
7164   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7165   // (plus the implicit offset) to a register to preinc anyway.
7166   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7167     return false;
7168
7169   // Check #2.
7170   if (!isLoad) {
7171     SDValue Val = cast<StoreSDNode>(N)->getValue();
7172     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7173       return false;
7174   }
7175
7176   // If the offset is a constant, there may be other adds of constants that
7177   // can be folded with this one. We should do this to avoid having to keep
7178   // a copy of the original base pointer.
7179   SmallVector<SDNode *, 16> OtherUses;
7180   if (isa<ConstantSDNode>(Offset))
7181     for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7182          E = BasePtr.getNode()->use_end(); I != E; ++I) {
7183       SDNode *Use = *I;
7184       if (Use == Ptr.getNode())
7185         continue;
7186
7187       if (Use->isPredecessorOf(N))
7188         continue;
7189
7190       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7191         OtherUses.clear();
7192         break;
7193       }
7194
7195       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7196       if (Op1.getNode() == BasePtr.getNode())
7197         std::swap(Op0, Op1);
7198       assert(Op0.getNode() == BasePtr.getNode() &&
7199              "Use of ADD/SUB but not an operand");
7200
7201       if (!isa<ConstantSDNode>(Op1)) {
7202         OtherUses.clear();
7203         break;
7204       }
7205
7206       // FIXME: In some cases, we can be smarter about this.
7207       if (Op1.getValueType() != Offset.getValueType()) {
7208         OtherUses.clear();
7209         break;
7210       }
7211
7212       OtherUses.push_back(Use);
7213     }
7214
7215   if (Swapped)
7216     std::swap(BasePtr, Offset);
7217
7218   // Now check for #3 and #4.
7219   bool RealUse = false;
7220
7221   // Caches for hasPredecessorHelper
7222   SmallPtrSet<const SDNode *, 32> Visited;
7223   SmallVector<const SDNode *, 16> Worklist;
7224
7225   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7226          E = Ptr.getNode()->use_end(); I != E; ++I) {
7227     SDNode *Use = *I;
7228     if (Use == N)
7229       continue;
7230     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7231       return false;
7232
7233     // If Ptr may be folded in addressing mode of other use, then it's
7234     // not profitable to do this transformation.
7235     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7236       RealUse = true;
7237   }
7238
7239   if (!RealUse)
7240     return false;
7241
7242   SDValue Result;
7243   if (isLoad)
7244     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7245                                 BasePtr, Offset, AM);
7246   else
7247     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7248                                  BasePtr, Offset, AM);
7249   ++PreIndexedNodes;
7250   ++NodesCombined;
7251   DEBUG(dbgs() << "\nReplacing.4 ";
7252         N->dump(&DAG);
7253         dbgs() << "\nWith: ";
7254         Result.getNode()->dump(&DAG);
7255         dbgs() << '\n');
7256   WorkListRemover DeadNodes(*this);
7257   if (isLoad) {
7258     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7259     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7260   } else {
7261     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7262   }
7263
7264   // Finally, since the node is now dead, remove it from the graph.
7265   DAG.DeleteNode(N);
7266
7267   if (Swapped)
7268     std::swap(BasePtr, Offset);
7269
7270   // Replace other uses of BasePtr that can be updated to use Ptr
7271   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7272     unsigned OffsetIdx = 1;
7273     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7274       OffsetIdx = 0;
7275     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7276            BasePtr.getNode() && "Expected BasePtr operand");
7277
7278     // We need to replace ptr0 in the following expression:
7279     //   x0 * offset0 + y0 * ptr0 = t0
7280     // knowing that
7281     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7282     //
7283     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7284     // indexed load/store and the expresion that needs to be re-written.
7285     //
7286     // Therefore, we have:
7287     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7288
7289     ConstantSDNode *CN =
7290       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7291     int X0, X1, Y0, Y1;
7292     APInt Offset0 = CN->getAPIntValue();
7293     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7294
7295     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7296     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7297     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7298     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7299
7300     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7301
7302     APInt CNV = Offset0;
7303     if (X0 < 0) CNV = -CNV;
7304     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7305     else CNV = CNV - Offset1;
7306
7307     // We can now generate the new expression.
7308     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7309     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7310
7311     SDValue NewUse = DAG.getNode(Opcode,
7312                                  SDLoc(OtherUses[i]),
7313                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7314     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7315     removeFromWorkList(OtherUses[i]);
7316     DAG.DeleteNode(OtherUses[i]);
7317   }
7318
7319   // Replace the uses of Ptr with uses of the updated base value.
7320   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7321   removeFromWorkList(Ptr.getNode());
7322   DAG.DeleteNode(Ptr.getNode());
7323
7324   return true;
7325 }
7326
7327 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7328 /// add / sub of the base pointer node into a post-indexed load / store.
7329 /// The transformation folded the add / subtract into the new indexed
7330 /// load / store effectively and all of its uses are redirected to the
7331 /// new load / store.
7332 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7333   if (Level < AfterLegalizeDAG)
7334     return false;
7335
7336   bool isLoad = true;
7337   SDValue Ptr;
7338   EVT VT;
7339   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7340     if (LD->isIndexed())
7341       return false;
7342     VT = LD->getMemoryVT();
7343     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7344         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7345       return false;
7346     Ptr = LD->getBasePtr();
7347   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7348     if (ST->isIndexed())
7349       return false;
7350     VT = ST->getMemoryVT();
7351     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7352         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7353       return false;
7354     Ptr = ST->getBasePtr();
7355     isLoad = false;
7356   } else {
7357     return false;
7358   }
7359
7360   if (Ptr.getNode()->hasOneUse())
7361     return false;
7362
7363   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7364          E = Ptr.getNode()->use_end(); I != E; ++I) {
7365     SDNode *Op = *I;
7366     if (Op == N ||
7367         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7368       continue;
7369
7370     SDValue BasePtr;
7371     SDValue Offset;
7372     ISD::MemIndexedMode AM = ISD::UNINDEXED;
7373     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7374       // Don't create a indexed load / store with zero offset.
7375       if (isa<ConstantSDNode>(Offset) &&
7376           cast<ConstantSDNode>(Offset)->isNullValue())
7377         continue;
7378
7379       // Try turning it into a post-indexed load / store except when
7380       // 1) All uses are load / store ops that use it as base ptr (and
7381       //    it may be folded as addressing mmode).
7382       // 2) Op must be independent of N, i.e. Op is neither a predecessor
7383       //    nor a successor of N. Otherwise, if Op is folded that would
7384       //    create a cycle.
7385
7386       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7387         continue;
7388
7389       // Check for #1.
7390       bool TryNext = false;
7391       for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7392              EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
7393         SDNode *Use = *II;
7394         if (Use == Ptr.getNode())
7395           continue;
7396
7397         // If all the uses are load / store addresses, then don't do the
7398         // transformation.
7399         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7400           bool RealUse = false;
7401           for (SDNode::use_iterator III = Use->use_begin(),
7402                  EEE = Use->use_end(); III != EEE; ++III) {
7403             SDNode *UseUse = *III;
7404             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7405               RealUse = true;
7406           }
7407
7408           if (!RealUse) {
7409             TryNext = true;
7410             break;
7411           }
7412         }
7413       }
7414
7415       if (TryNext)
7416         continue;
7417
7418       // Check for #2
7419       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7420         SDValue Result = isLoad
7421           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7422                                BasePtr, Offset, AM)
7423           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7424                                 BasePtr, Offset, AM);
7425         ++PostIndexedNodes;
7426         ++NodesCombined;
7427         DEBUG(dbgs() << "\nReplacing.5 ";
7428               N->dump(&DAG);
7429               dbgs() << "\nWith: ";
7430               Result.getNode()->dump(&DAG);
7431               dbgs() << '\n');
7432         WorkListRemover DeadNodes(*this);
7433         if (isLoad) {
7434           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7435           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7436         } else {
7437           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7438         }
7439
7440         // Finally, since the node is now dead, remove it from the graph.
7441         DAG.DeleteNode(N);
7442
7443         // Replace the uses of Use with uses of the updated base value.
7444         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7445                                       Result.getValue(isLoad ? 1 : 0));
7446         removeFromWorkList(Op);
7447         DAG.DeleteNode(Op);
7448         return true;
7449       }
7450     }
7451   }
7452
7453   return false;
7454 }
7455
7456 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7457   LoadSDNode *LD  = cast<LoadSDNode>(N);
7458   SDValue Chain = LD->getChain();
7459   SDValue Ptr   = LD->getBasePtr();
7460
7461   // If load is not volatile and there are no uses of the loaded value (and
7462   // the updated indexed value in case of indexed loads), change uses of the
7463   // chain value into uses of the chain input (i.e. delete the dead load).
7464   if (!LD->isVolatile()) {
7465     if (N->getValueType(1) == MVT::Other) {
7466       // Unindexed loads.
7467       if (!N->hasAnyUseOfValue(0)) {
7468         // It's not safe to use the two value CombineTo variant here. e.g.
7469         // v1, chain2 = load chain1, loc
7470         // v2, chain3 = load chain2, loc
7471         // v3         = add v2, c
7472         // Now we replace use of chain2 with chain1.  This makes the second load
7473         // isomorphic to the one we are deleting, and thus makes this load live.
7474         DEBUG(dbgs() << "\nReplacing.6 ";
7475               N->dump(&DAG);
7476               dbgs() << "\nWith chain: ";
7477               Chain.getNode()->dump(&DAG);
7478               dbgs() << "\n");
7479         WorkListRemover DeadNodes(*this);
7480         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7481
7482         if (N->use_empty()) {
7483           removeFromWorkList(N);
7484           DAG.DeleteNode(N);
7485         }
7486
7487         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7488       }
7489     } else {
7490       // Indexed loads.
7491       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7492       if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7493         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7494         DEBUG(dbgs() << "\nReplacing.7 ";
7495               N->dump(&DAG);
7496               dbgs() << "\nWith: ";
7497               Undef.getNode()->dump(&DAG);
7498               dbgs() << " and 2 other values\n");
7499         WorkListRemover DeadNodes(*this);
7500         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7501         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7502                                       DAG.getUNDEF(N->getValueType(1)));
7503         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7504         removeFromWorkList(N);
7505         DAG.DeleteNode(N);
7506         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7507       }
7508     }
7509   }
7510
7511   // If this load is directly stored, replace the load value with the stored
7512   // value.
7513   // TODO: Handle store large -> read small portion.
7514   // TODO: Handle TRUNCSTORE/LOADEXT
7515   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7516     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7517       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7518       if (PrevST->getBasePtr() == Ptr &&
7519           PrevST->getValue().getValueType() == N->getValueType(0))
7520       return CombineTo(N, Chain.getOperand(1), Chain);
7521     }
7522   }
7523
7524   // Try to infer better alignment information than the load already has.
7525   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7526     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7527       if (Align > LD->getMemOperand()->getBaseAlignment()) {
7528         SDValue NewLoad =
7529                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7530                               LD->getValueType(0),
7531                               Chain, Ptr, LD->getPointerInfo(),
7532                               LD->getMemoryVT(),
7533                               LD->isVolatile(), LD->isNonTemporal(), Align);
7534         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7535       }
7536     }
7537   }
7538
7539   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7540     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7541   if (UseAA) {
7542     // Walk up chain skipping non-aliasing memory nodes.
7543     SDValue BetterChain = FindBetterChain(N, Chain);
7544
7545     // If there is a better chain.
7546     if (Chain != BetterChain) {
7547       SDValue ReplLoad;
7548
7549       // Replace the chain to void dependency.
7550       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7551         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7552                                BetterChain, Ptr, LD->getPointerInfo(),
7553                                LD->isVolatile(), LD->isNonTemporal(),
7554                                LD->isInvariant(), LD->getAlignment());
7555       } else {
7556         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7557                                   LD->getValueType(0),
7558                                   BetterChain, Ptr, LD->getPointerInfo(),
7559                                   LD->getMemoryVT(),
7560                                   LD->isVolatile(),
7561                                   LD->isNonTemporal(),
7562                                   LD->getAlignment());
7563       }
7564
7565       // Create token factor to keep old chain connected.
7566       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7567                                   MVT::Other, Chain, ReplLoad.getValue(1));
7568
7569       // Make sure the new and old chains are cleaned up.
7570       AddToWorkList(Token.getNode());
7571
7572       // Replace uses with load result and token factor. Don't add users
7573       // to work list.
7574       return CombineTo(N, ReplLoad.getValue(0), Token, false);
7575     }
7576   }
7577
7578   // Try transforming N to an indexed load.
7579   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7580     return SDValue(N, 0);
7581
7582   return SDValue();
7583 }
7584
7585 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
7586 /// load is having specific bytes cleared out.  If so, return the byte size
7587 /// being masked out and the shift amount.
7588 static std::pair<unsigned, unsigned>
7589 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
7590   std::pair<unsigned, unsigned> Result(0, 0);
7591
7592   // Check for the structure we're looking for.
7593   if (V->getOpcode() != ISD::AND ||
7594       !isa<ConstantSDNode>(V->getOperand(1)) ||
7595       !ISD::isNormalLoad(V->getOperand(0).getNode()))
7596     return Result;
7597
7598   // Check the chain and pointer.
7599   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
7600   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
7601
7602   // The store should be chained directly to the load or be an operand of a
7603   // tokenfactor.
7604   if (LD == Chain.getNode())
7605     ; // ok.
7606   else if (Chain->getOpcode() != ISD::TokenFactor)
7607     return Result; // Fail.
7608   else {
7609     bool isOk = false;
7610     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
7611       if (Chain->getOperand(i).getNode() == LD) {
7612         isOk = true;
7613         break;
7614       }
7615     if (!isOk) return Result;
7616   }
7617
7618   // This only handles simple types.
7619   if (V.getValueType() != MVT::i16 &&
7620       V.getValueType() != MVT::i32 &&
7621       V.getValueType() != MVT::i64)
7622     return Result;
7623
7624   // Check the constant mask.  Invert it so that the bits being masked out are
7625   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
7626   // follow the sign bit for uniformity.
7627   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
7628   unsigned NotMaskLZ = countLeadingZeros(NotMask);
7629   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
7630   unsigned NotMaskTZ = countTrailingZeros(NotMask);
7631   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
7632   if (NotMaskLZ == 64) return Result;  // All zero mask.
7633
7634   // See if we have a continuous run of bits.  If so, we have 0*1+0*
7635   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
7636     return Result;
7637
7638   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
7639   if (V.getValueType() != MVT::i64 && NotMaskLZ)
7640     NotMaskLZ -= 64-V.getValueSizeInBits();
7641
7642   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
7643   switch (MaskedBytes) {
7644   case 1:
7645   case 2:
7646   case 4: break;
7647   default: return Result; // All one mask, or 5-byte mask.
7648   }
7649
7650   // Verify that the first bit starts at a multiple of mask so that the access
7651   // is aligned the same as the access width.
7652   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
7653
7654   Result.first = MaskedBytes;
7655   Result.second = NotMaskTZ/8;
7656   return Result;
7657 }
7658
7659
7660 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
7661 /// provides a value as specified by MaskInfo.  If so, replace the specified
7662 /// store with a narrower store of truncated IVal.
7663 static SDNode *
7664 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
7665                                 SDValue IVal, StoreSDNode *St,
7666                                 DAGCombiner *DC) {
7667   unsigned NumBytes = MaskInfo.first;
7668   unsigned ByteShift = MaskInfo.second;
7669   SelectionDAG &DAG = DC->getDAG();
7670
7671   // Check to see if IVal is all zeros in the part being masked in by the 'or'
7672   // that uses this.  If not, this is not a replacement.
7673   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
7674                                   ByteShift*8, (ByteShift+NumBytes)*8);
7675   if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
7676
7677   // Check that it is legal on the target to do this.  It is legal if the new
7678   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
7679   // legalization.
7680   MVT VT = MVT::getIntegerVT(NumBytes*8);
7681   if (!DC->isTypeLegal(VT))
7682     return 0;
7683
7684   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
7685   // shifted by ByteShift and truncated down to NumBytes.
7686   if (ByteShift)
7687     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
7688                        DAG.getConstant(ByteShift*8,
7689                                     DC->getShiftAmountTy(IVal.getValueType())));
7690
7691   // Figure out the offset for the store and the alignment of the access.
7692   unsigned StOffset;
7693   unsigned NewAlign = St->getAlignment();
7694
7695   if (DAG.getTargetLoweringInfo().isLittleEndian())
7696     StOffset = ByteShift;
7697   else
7698     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
7699
7700   SDValue Ptr = St->getBasePtr();
7701   if (StOffset) {
7702     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
7703                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
7704     NewAlign = MinAlign(NewAlign, StOffset);
7705   }
7706
7707   // Truncate down to the new size.
7708   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
7709
7710   ++OpsNarrowed;
7711   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
7712                       St->getPointerInfo().getWithOffset(StOffset),
7713                       false, false, NewAlign).getNode();
7714 }
7715
7716
7717 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
7718 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
7719 /// of the loaded bits, try narrowing the load and store if it would end up
7720 /// being a win for performance or code size.
7721 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
7722   StoreSDNode *ST  = cast<StoreSDNode>(N);
7723   if (ST->isVolatile())
7724     return SDValue();
7725
7726   SDValue Chain = ST->getChain();
7727   SDValue Value = ST->getValue();
7728   SDValue Ptr   = ST->getBasePtr();
7729   EVT VT = Value.getValueType();
7730
7731   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
7732     return SDValue();
7733
7734   unsigned Opc = Value.getOpcode();
7735
7736   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
7737   // is a byte mask indicating a consecutive number of bytes, check to see if
7738   // Y is known to provide just those bytes.  If so, we try to replace the
7739   // load + replace + store sequence with a single (narrower) store, which makes
7740   // the load dead.
7741   if (Opc == ISD::OR) {
7742     std::pair<unsigned, unsigned> MaskedLoad;
7743     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
7744     if (MaskedLoad.first)
7745       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
7746                                                   Value.getOperand(1), ST,this))
7747         return SDValue(NewST, 0);
7748
7749     // Or is commutative, so try swapping X and Y.
7750     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
7751     if (MaskedLoad.first)
7752       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
7753                                                   Value.getOperand(0), ST,this))
7754         return SDValue(NewST, 0);
7755   }
7756
7757   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
7758       Value.getOperand(1).getOpcode() != ISD::Constant)
7759     return SDValue();
7760
7761   SDValue N0 = Value.getOperand(0);
7762   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7763       Chain == SDValue(N0.getNode(), 1)) {
7764     LoadSDNode *LD = cast<LoadSDNode>(N0);
7765     if (LD->getBasePtr() != Ptr ||
7766         LD->getPointerInfo().getAddrSpace() !=
7767         ST->getPointerInfo().getAddrSpace())
7768       return SDValue();
7769
7770     // Find the type to narrow it the load / op / store to.
7771     SDValue N1 = Value.getOperand(1);
7772     unsigned BitWidth = N1.getValueSizeInBits();
7773     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
7774     if (Opc == ISD::AND)
7775       Imm ^= APInt::getAllOnesValue(BitWidth);
7776     if (Imm == 0 || Imm.isAllOnesValue())
7777       return SDValue();
7778     unsigned ShAmt = Imm.countTrailingZeros();
7779     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
7780     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
7781     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
7782     while (NewBW < BitWidth &&
7783            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
7784              TLI.isNarrowingProfitable(VT, NewVT))) {
7785       NewBW = NextPowerOf2(NewBW);
7786       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
7787     }
7788     if (NewBW >= BitWidth)
7789       return SDValue();
7790
7791     // If the lsb changed does not start at the type bitwidth boundary,
7792     // start at the previous one.
7793     if (ShAmt % NewBW)
7794       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
7795     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
7796                                    std::min(BitWidth, ShAmt + NewBW));
7797     if ((Imm & Mask) == Imm) {
7798       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
7799       if (Opc == ISD::AND)
7800         NewImm ^= APInt::getAllOnesValue(NewBW);
7801       uint64_t PtrOff = ShAmt / 8;
7802       // For big endian targets, we need to adjust the offset to the pointer to
7803       // load the correct bytes.
7804       if (TLI.isBigEndian())
7805         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
7806
7807       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
7808       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
7809       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
7810         return SDValue();
7811
7812       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
7813                                    Ptr.getValueType(), Ptr,
7814                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
7815       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
7816                                   LD->getChain(), NewPtr,
7817                                   LD->getPointerInfo().getWithOffset(PtrOff),
7818                                   LD->isVolatile(), LD->isNonTemporal(),
7819                                   LD->isInvariant(), NewAlign);
7820       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
7821                                    DAG.getConstant(NewImm, NewVT));
7822       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
7823                                    NewVal, NewPtr,
7824                                    ST->getPointerInfo().getWithOffset(PtrOff),
7825                                    false, false, NewAlign);
7826
7827       AddToWorkList(NewPtr.getNode());
7828       AddToWorkList(NewLD.getNode());
7829       AddToWorkList(NewVal.getNode());
7830       WorkListRemover DeadNodes(*this);
7831       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
7832       ++OpsNarrowed;
7833       return NewST;
7834     }
7835   }
7836
7837   return SDValue();
7838 }
7839
7840 /// TransformFPLoadStorePair - For a given floating point load / store pair,
7841 /// if the load value isn't used by any other operations, then consider
7842 /// transforming the pair to integer load / store operations if the target
7843 /// deems the transformation profitable.
7844 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
7845   StoreSDNode *ST  = cast<StoreSDNode>(N);
7846   SDValue Chain = ST->getChain();
7847   SDValue Value = ST->getValue();
7848   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
7849       Value.hasOneUse() &&
7850       Chain == SDValue(Value.getNode(), 1)) {
7851     LoadSDNode *LD = cast<LoadSDNode>(Value);
7852     EVT VT = LD->getMemoryVT();
7853     if (!VT.isFloatingPoint() ||
7854         VT != ST->getMemoryVT() ||
7855         LD->isNonTemporal() ||
7856         ST->isNonTemporal() ||
7857         LD->getPointerInfo().getAddrSpace() != 0 ||
7858         ST->getPointerInfo().getAddrSpace() != 0)
7859       return SDValue();
7860
7861     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7862     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
7863         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
7864         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
7865         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
7866       return SDValue();
7867
7868     unsigned LDAlign = LD->getAlignment();
7869     unsigned STAlign = ST->getAlignment();
7870     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
7871     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
7872     if (LDAlign < ABIAlign || STAlign < ABIAlign)
7873       return SDValue();
7874
7875     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
7876                                 LD->getChain(), LD->getBasePtr(),
7877                                 LD->getPointerInfo(),
7878                                 false, false, false, LDAlign);
7879
7880     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
7881                                  NewLD, ST->getBasePtr(),
7882                                  ST->getPointerInfo(),
7883                                  false, false, STAlign);
7884
7885     AddToWorkList(NewLD.getNode());
7886     AddToWorkList(NewST.getNode());
7887     WorkListRemover DeadNodes(*this);
7888     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
7889     ++LdStFP2Int;
7890     return NewST;
7891   }
7892
7893   return SDValue();
7894 }
7895
7896 /// Helper struct to parse and store a memory address as base + index + offset.
7897 /// We ignore sign extensions when it is safe to do so.
7898 /// The following two expressions are not equivalent. To differentiate we need
7899 /// to store whether there was a sign extension involved in the index
7900 /// computation.
7901 ///  (load (i64 add (i64 copyfromreg %c)
7902 ///                 (i64 signextend (add (i8 load %index)
7903 ///                                      (i8 1))))
7904 /// vs
7905 ///
7906 /// (load (i64 add (i64 copyfromreg %c)
7907 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
7908 ///                                         (i32 1)))))
7909 struct BaseIndexOffset {
7910   SDValue Base;
7911   SDValue Index;
7912   int64_t Offset;
7913   bool IsIndexSignExt;
7914
7915   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
7916
7917   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
7918                   bool IsIndexSignExt) :
7919     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
7920
7921   bool equalBaseIndex(const BaseIndexOffset &Other) {
7922     return Other.Base == Base && Other.Index == Index &&
7923       Other.IsIndexSignExt == IsIndexSignExt;
7924   }
7925
7926   /// Parses tree in Ptr for base, index, offset addresses.
7927   static BaseIndexOffset match(SDValue Ptr) {
7928     bool IsIndexSignExt = false;
7929
7930     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
7931     // instruction, then it could be just the BASE or everything else we don't
7932     // know how to handle. Just use Ptr as BASE and give up.
7933     if (Ptr->getOpcode() != ISD::ADD)
7934       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
7935
7936     // We know that we have at least an ADD instruction. Try to pattern match
7937     // the simple case of BASE + OFFSET.
7938     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
7939       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
7940       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
7941                               IsIndexSignExt);
7942     }
7943
7944     // Inside a loop the current BASE pointer is calculated using an ADD and a
7945     // MUL instruction. In this case Ptr is the actual BASE pointer.
7946     // (i64 add (i64 %array_ptr)
7947     //          (i64 mul (i64 %induction_var)
7948     //                   (i64 %element_size)))
7949     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
7950       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
7951
7952     // Look at Base + Index + Offset cases.
7953     SDValue Base = Ptr->getOperand(0);
7954     SDValue IndexOffset = Ptr->getOperand(1);
7955
7956     // Skip signextends.
7957     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
7958       IndexOffset = IndexOffset->getOperand(0);
7959       IsIndexSignExt = true;
7960     }
7961
7962     // Either the case of Base + Index (no offset) or something else.
7963     if (IndexOffset->getOpcode() != ISD::ADD)
7964       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
7965
7966     // Now we have the case of Base + Index + offset.
7967     SDValue Index = IndexOffset->getOperand(0);
7968     SDValue Offset = IndexOffset->getOperand(1);
7969
7970     if (!isa<ConstantSDNode>(Offset))
7971       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
7972
7973     // Ignore signextends.
7974     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
7975       Index = Index->getOperand(0);
7976       IsIndexSignExt = true;
7977     } else IsIndexSignExt = false;
7978
7979     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
7980     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
7981   }
7982 };
7983
7984 /// Holds a pointer to an LSBaseSDNode as well as information on where it
7985 /// is located in a sequence of memory operations connected by a chain.
7986 struct MemOpLink {
7987   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
7988     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
7989   // Ptr to the mem node.
7990   LSBaseSDNode *MemNode;
7991   // Offset from the base ptr.
7992   int64_t OffsetFromBase;
7993   // What is the sequence number of this mem node.
7994   // Lowest mem operand in the DAG starts at zero.
7995   unsigned SequenceNum;
7996 };
7997
7998 /// Sorts store nodes in a link according to their offset from a shared
7999 // base ptr.
8000 struct ConsecutiveMemoryChainSorter {
8001   bool operator()(MemOpLink LHS, MemOpLink RHS) {
8002     return LHS.OffsetFromBase < RHS.OffsetFromBase;
8003   }
8004 };
8005
8006 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8007   EVT MemVT = St->getMemoryVT();
8008   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
8009   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8010     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
8011
8012   // Don't merge vectors into wider inputs.
8013   if (MemVT.isVector() || !MemVT.isSimple())
8014     return false;
8015
8016   // Perform an early exit check. Do not bother looking at stored values that
8017   // are not constants or loads.
8018   SDValue StoredVal = St->getValue();
8019   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8020   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8021       !IsLoadSrc)
8022     return false;
8023
8024   // Only look at ends of store sequences.
8025   SDValue Chain = SDValue(St, 1);
8026   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8027     return false;
8028
8029   // This holds the base pointer, index, and the offset in bytes from the base
8030   // pointer.
8031   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
8032
8033   // We must have a base and an offset.
8034   if (!BasePtr.Base.getNode())
8035     return false;
8036
8037   // Do not handle stores to undef base pointers.
8038   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
8039     return false;
8040
8041   // Save the LoadSDNodes that we find in the chain.
8042   // We need to make sure that these nodes do not interfere with
8043   // any of the store nodes.
8044   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8045
8046   // Save the StoreSDNodes that we find in the chain.
8047   SmallVector<MemOpLink, 8> StoreNodes;
8048
8049   // Walk up the chain and look for nodes with offsets from the same
8050   // base pointer. Stop when reaching an instruction with a different kind
8051   // or instruction which has a different base pointer.
8052   unsigned Seq = 0;
8053   StoreSDNode *Index = St;
8054   while (Index) {
8055     // If the chain has more than one use, then we can't reorder the mem ops.
8056     if (Index != St && !SDValue(Index, 1)->hasOneUse())
8057       break;
8058
8059     // Find the base pointer and offset for this memory node.
8060     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
8061
8062     // Check that the base pointer is the same as the original one.
8063     if (!Ptr.equalBaseIndex(BasePtr))
8064       break;
8065
8066     // Check that the alignment is the same.
8067     if (Index->getAlignment() != St->getAlignment())
8068       break;
8069
8070     // The memory operands must not be volatile.
8071     if (Index->isVolatile() || Index->isIndexed())
8072       break;
8073
8074     // No truncation.
8075     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
8076       if (St->isTruncatingStore())
8077         break;
8078
8079     // The stored memory type must be the same.
8080     if (Index->getMemoryVT() != MemVT)
8081       break;
8082
8083     // We do not allow unaligned stores because we want to prevent overriding
8084     // stores.
8085     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
8086       break;
8087
8088     // We found a potential memory operand to merge.
8089     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
8090
8091     // Find the next memory operand in the chain. If the next operand in the
8092     // chain is a store then move up and continue the scan with the next
8093     // memory operand. If the next operand is a load save it and use alias
8094     // information to check if it interferes with anything.
8095     SDNode *NextInChain = Index->getChain().getNode();
8096     while (1) {
8097       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
8098         // We found a store node. Use it for the next iteration.
8099         Index = STn;
8100         break;
8101       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
8102         // Save the load node for later. Continue the scan.
8103         AliasLoadNodes.push_back(Ldn);
8104         NextInChain = Ldn->getChain().getNode();
8105         continue;
8106       } else {
8107         Index = NULL;
8108         break;
8109       }
8110     }
8111   }
8112
8113   // Check if there is anything to merge.
8114   if (StoreNodes.size() < 2)
8115     return false;
8116
8117   // Sort the memory operands according to their distance from the base pointer.
8118   std::sort(StoreNodes.begin(), StoreNodes.end(),
8119             ConsecutiveMemoryChainSorter());
8120
8121   // Scan the memory operations on the chain and find the first non-consecutive
8122   // store memory address.
8123   unsigned LastConsecutiveStore = 0;
8124   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
8125   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
8126
8127     // Check that the addresses are consecutive starting from the second
8128     // element in the list of stores.
8129     if (i > 0) {
8130       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
8131       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8132         break;
8133     }
8134
8135     bool Alias = false;
8136     // Check if this store interferes with any of the loads that we found.
8137     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
8138       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
8139         Alias = true;
8140         break;
8141       }
8142     // We found a load that alias with this store. Stop the sequence.
8143     if (Alias)
8144       break;
8145
8146     // Mark this node as useful.
8147     LastConsecutiveStore = i;
8148   }
8149
8150   // The node with the lowest store address.
8151   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
8152
8153   // Store the constants into memory as one consecutive store.
8154   if (!IsLoadSrc) {
8155     unsigned LastLegalType = 0;
8156     unsigned LastLegalVectorType = 0;
8157     bool NonZero = false;
8158     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8159       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
8160       SDValue StoredVal = St->getValue();
8161
8162       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
8163         NonZero |= !C->isNullValue();
8164       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
8165         NonZero |= !C->getConstantFPValue()->isNullValue();
8166       } else {
8167         // Non constant.
8168         break;
8169       }
8170
8171       // Find a legal type for the constant store.
8172       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8173       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8174       if (TLI.isTypeLegal(StoreTy))
8175         LastLegalType = i+1;
8176       // Or check whether a truncstore is legal.
8177       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8178                TargetLowering::TypePromoteInteger) {
8179         EVT LegalizedStoredValueTy =
8180           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
8181         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
8182           LastLegalType = i+1;
8183       }
8184
8185       // Find a legal type for the vector store.
8186       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8187       if (TLI.isTypeLegal(Ty))
8188         LastLegalVectorType = i + 1;
8189     }
8190
8191     // We only use vectors if the constant is known to be zero and the
8192     // function is not marked with the noimplicitfloat attribute.
8193     if (NonZero || NoVectors)
8194       LastLegalVectorType = 0;
8195
8196     // Check if we found a legal integer type to store.
8197     if (LastLegalType == 0 && LastLegalVectorType == 0)
8198       return false;
8199
8200     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
8201     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
8202
8203     // Make sure we have something to merge.
8204     if (NumElem < 2)
8205       return false;
8206
8207     unsigned EarliestNodeUsed = 0;
8208     for (unsigned i=0; i < NumElem; ++i) {
8209       // Find a chain for the new wide-store operand. Notice that some
8210       // of the store nodes that we found may not be selected for inclusion
8211       // in the wide store. The chain we use needs to be the chain of the
8212       // earliest store node which is *used* and replaced by the wide store.
8213       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8214         EarliestNodeUsed = i;
8215     }
8216
8217     // The earliest Node in the DAG.
8218     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8219     SDLoc DL(StoreNodes[0].MemNode);
8220
8221     SDValue StoredVal;
8222     if (UseVector) {
8223       // Find a legal type for the vector store.
8224       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8225       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
8226       StoredVal = DAG.getConstant(0, Ty);
8227     } else {
8228       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8229       APInt StoreInt(StoreBW, 0);
8230
8231       // Construct a single integer constant which is made of the smaller
8232       // constant inputs.
8233       bool IsLE = TLI.isLittleEndian();
8234       for (unsigned i = 0; i < NumElem ; ++i) {
8235         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
8236         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
8237         SDValue Val = St->getValue();
8238         StoreInt<<=ElementSizeBytes*8;
8239         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
8240           StoreInt|=C->getAPIntValue().zext(StoreBW);
8241         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
8242           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
8243         } else {
8244           assert(false && "Invalid constant element type");
8245         }
8246       }
8247
8248       // Create the new Load and Store operations.
8249       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8250       StoredVal = DAG.getConstant(StoreInt, StoreTy);
8251     }
8252
8253     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
8254                                     FirstInChain->getBasePtr(),
8255                                     FirstInChain->getPointerInfo(),
8256                                     false, false,
8257                                     FirstInChain->getAlignment());
8258
8259     // Replace the first store with the new store
8260     CombineTo(EarliestOp, NewStore);
8261     // Erase all other stores.
8262     for (unsigned i = 0; i < NumElem ; ++i) {
8263       if (StoreNodes[i].MemNode == EarliestOp)
8264         continue;
8265       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8266       // ReplaceAllUsesWith will replace all uses that existed when it was
8267       // called, but graph optimizations may cause new ones to appear. For
8268       // example, the case in pr14333 looks like
8269       //
8270       //  St's chain -> St -> another store -> X
8271       //
8272       // And the only difference from St to the other store is the chain.
8273       // When we change it's chain to be St's chain they become identical,
8274       // get CSEed and the net result is that X is now a use of St.
8275       // Since we know that St is redundant, just iterate.
8276       while (!St->use_empty())
8277         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
8278       removeFromWorkList(St);
8279       DAG.DeleteNode(St);
8280     }
8281
8282     return true;
8283   }
8284
8285   // Below we handle the case of multiple consecutive stores that
8286   // come from multiple consecutive loads. We merge them into a single
8287   // wide load and a single wide store.
8288
8289   // Look for load nodes which are used by the stored values.
8290   SmallVector<MemOpLink, 8> LoadNodes;
8291
8292   // Find acceptable loads. Loads need to have the same chain (token factor),
8293   // must not be zext, volatile, indexed, and they must be consecutive.
8294   BaseIndexOffset LdBasePtr;
8295   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8296     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
8297     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
8298     if (!Ld) break;
8299
8300     // Loads must only have one use.
8301     if (!Ld->hasNUsesOfValue(1, 0))
8302       break;
8303
8304     // Check that the alignment is the same as the stores.
8305     if (Ld->getAlignment() != St->getAlignment())
8306       break;
8307
8308     // The memory operands must not be volatile.
8309     if (Ld->isVolatile() || Ld->isIndexed())
8310       break;
8311
8312     // We do not accept ext loads.
8313     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
8314       break;
8315
8316     // The stored memory type must be the same.
8317     if (Ld->getMemoryVT() != MemVT)
8318       break;
8319
8320     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
8321     // If this is not the first ptr that we check.
8322     if (LdBasePtr.Base.getNode()) {
8323       // The base ptr must be the same.
8324       if (!LdPtr.equalBaseIndex(LdBasePtr))
8325         break;
8326     } else {
8327       // Check that all other base pointers are the same as this one.
8328       LdBasePtr = LdPtr;
8329     }
8330
8331     // We found a potential memory operand to merge.
8332     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
8333   }
8334
8335   if (LoadNodes.size() < 2)
8336     return false;
8337
8338   // Scan the memory operations on the chain and find the first non-consecutive
8339   // load memory address. These variables hold the index in the store node
8340   // array.
8341   unsigned LastConsecutiveLoad = 0;
8342   // This variable refers to the size and not index in the array.
8343   unsigned LastLegalVectorType = 0;
8344   unsigned LastLegalIntegerType = 0;
8345   StartAddress = LoadNodes[0].OffsetFromBase;
8346   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
8347   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
8348     // All loads much share the same chain.
8349     if (LoadNodes[i].MemNode->getChain() != FirstChain)
8350       break;
8351
8352     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
8353     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8354       break;
8355     LastConsecutiveLoad = i;
8356
8357     // Find a legal type for the vector store.
8358     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8359     if (TLI.isTypeLegal(StoreTy))
8360       LastLegalVectorType = i + 1;
8361
8362     // Find a legal type for the integer store.
8363     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8364     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8365     if (TLI.isTypeLegal(StoreTy))
8366       LastLegalIntegerType = i + 1;
8367     // Or check whether a truncstore and extload is legal.
8368     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8369              TargetLowering::TypePromoteInteger) {
8370       EVT LegalizedStoredValueTy =
8371         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
8372       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
8373           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
8374           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
8375           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
8376         LastLegalIntegerType = i+1;
8377     }
8378   }
8379
8380   // Only use vector types if the vector type is larger than the integer type.
8381   // If they are the same, use integers.
8382   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
8383   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
8384
8385   // We add +1 here because the LastXXX variables refer to location while
8386   // the NumElem refers to array/index size.
8387   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
8388   NumElem = std::min(LastLegalType, NumElem);
8389
8390   if (NumElem < 2)
8391     return false;
8392
8393   // The earliest Node in the DAG.
8394   unsigned EarliestNodeUsed = 0;
8395   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8396   for (unsigned i=1; i<NumElem; ++i) {
8397     // Find a chain for the new wide-store operand. Notice that some
8398     // of the store nodes that we found may not be selected for inclusion
8399     // in the wide store. The chain we use needs to be the chain of the
8400     // earliest store node which is *used* and replaced by the wide store.
8401     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8402       EarliestNodeUsed = i;
8403   }
8404
8405   // Find if it is better to use vectors or integers to load and store
8406   // to memory.
8407   EVT JointMemOpVT;
8408   if (UseVectorTy) {
8409     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8410   } else {
8411     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8412     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8413   }
8414
8415   SDLoc LoadDL(LoadNodes[0].MemNode);
8416   SDLoc StoreDL(StoreNodes[0].MemNode);
8417
8418   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
8419   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
8420                                 FirstLoad->getChain(),
8421                                 FirstLoad->getBasePtr(),
8422                                 FirstLoad->getPointerInfo(),
8423                                 false, false, false,
8424                                 FirstLoad->getAlignment());
8425
8426   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
8427                                   FirstInChain->getBasePtr(),
8428                                   FirstInChain->getPointerInfo(), false, false,
8429                                   FirstInChain->getAlignment());
8430
8431   // Replace one of the loads with the new load.
8432   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
8433   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
8434                                 SDValue(NewLoad.getNode(), 1));
8435
8436   // Remove the rest of the load chains.
8437   for (unsigned i = 1; i < NumElem ; ++i) {
8438     // Replace all chain users of the old load nodes with the chain of the new
8439     // load node.
8440     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
8441     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
8442   }
8443
8444   // Replace the first store with the new store.
8445   CombineTo(EarliestOp, NewStore);
8446   // Erase all other stores.
8447   for (unsigned i = 0; i < NumElem ; ++i) {
8448     // Remove all Store nodes.
8449     if (StoreNodes[i].MemNode == EarliestOp)
8450       continue;
8451     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8452     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
8453     removeFromWorkList(St);
8454     DAG.DeleteNode(St);
8455   }
8456
8457   return true;
8458 }
8459
8460 SDValue DAGCombiner::visitSTORE(SDNode *N) {
8461   StoreSDNode *ST  = cast<StoreSDNode>(N);
8462   SDValue Chain = ST->getChain();
8463   SDValue Value = ST->getValue();
8464   SDValue Ptr   = ST->getBasePtr();
8465
8466   // If this is a store of a bit convert, store the input value if the
8467   // resultant store does not need a higher alignment than the original.
8468   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
8469       ST->isUnindexed()) {
8470     unsigned OrigAlign = ST->getAlignment();
8471     EVT SVT = Value.getOperand(0).getValueType();
8472     unsigned Align = TLI.getDataLayout()->
8473       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
8474     if (Align <= OrigAlign &&
8475         ((!LegalOperations && !ST->isVolatile()) ||
8476          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
8477       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
8478                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
8479                           ST->isNonTemporal(), OrigAlign);
8480   }
8481
8482   // Turn 'store undef, Ptr' -> nothing.
8483   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
8484     return Chain;
8485
8486   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
8487   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
8488     // NOTE: If the original store is volatile, this transform must not increase
8489     // the number of stores.  For example, on x86-32 an f64 can be stored in one
8490     // processor operation but an i64 (which is not legal) requires two.  So the
8491     // transform should not be done in this case.
8492     if (Value.getOpcode() != ISD::TargetConstantFP) {
8493       SDValue Tmp;
8494       switch (CFP->getSimpleValueType(0).SimpleTy) {
8495       default: llvm_unreachable("Unknown FP type");
8496       case MVT::f16:    // We don't do this for these yet.
8497       case MVT::f80:
8498       case MVT::f128:
8499       case MVT::ppcf128:
8500         break;
8501       case MVT::f32:
8502         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
8503             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
8504           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
8505                               bitcastToAPInt().getZExtValue(), MVT::i32);
8506           return DAG.getStore(Chain, SDLoc(N), Tmp,
8507                               Ptr, ST->getPointerInfo(), ST->isVolatile(),
8508                               ST->isNonTemporal(), ST->getAlignment());
8509         }
8510         break;
8511       case MVT::f64:
8512         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
8513              !ST->isVolatile()) ||
8514             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
8515           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
8516                                 getZExtValue(), MVT::i64);
8517           return DAG.getStore(Chain, SDLoc(N), Tmp,
8518                               Ptr, ST->getPointerInfo(), ST->isVolatile(),
8519                               ST->isNonTemporal(), ST->getAlignment());
8520         }
8521
8522         if (!ST->isVolatile() &&
8523             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
8524           // Many FP stores are not made apparent until after legalize, e.g. for
8525           // argument passing.  Since this is so common, custom legalize the
8526           // 64-bit integer store into two 32-bit stores.
8527           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
8528           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
8529           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
8530           if (TLI.isBigEndian()) std::swap(Lo, Hi);
8531
8532           unsigned Alignment = ST->getAlignment();
8533           bool isVolatile = ST->isVolatile();
8534           bool isNonTemporal = ST->isNonTemporal();
8535
8536           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
8537                                      Ptr, ST->getPointerInfo(),
8538                                      isVolatile, isNonTemporal,
8539                                      ST->getAlignment());
8540           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
8541                             DAG.getConstant(4, Ptr.getValueType()));
8542           Alignment = MinAlign(Alignment, 4U);
8543           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
8544                                      Ptr, ST->getPointerInfo().getWithOffset(4),
8545                                      isVolatile, isNonTemporal,
8546                                      Alignment);
8547           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
8548                              St0, St1);
8549         }
8550
8551         break;
8552       }
8553     }
8554   }
8555
8556   // Try to infer better alignment information than the store already has.
8557   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
8558     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8559       if (Align > ST->getAlignment())
8560         return DAG.getTruncStore(Chain, SDLoc(N), Value,
8561                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
8562                                  ST->isVolatile(), ST->isNonTemporal(), Align);
8563     }
8564   }
8565
8566   // Try transforming a pair floating point load / store ops to integer
8567   // load / store ops.
8568   SDValue NewST = TransformFPLoadStorePair(N);
8569   if (NewST.getNode())
8570     return NewST;
8571
8572   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8573     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
8574   if (UseAA) {
8575     // Walk up chain skipping non-aliasing memory nodes.
8576     SDValue BetterChain = FindBetterChain(N, Chain);
8577
8578     // If there is a better chain.
8579     if (Chain != BetterChain) {
8580       SDValue ReplStore;
8581
8582       // Replace the chain to avoid dependency.
8583       if (ST->isTruncatingStore()) {
8584         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
8585                                       ST->getPointerInfo(),
8586                                       ST->getMemoryVT(), ST->isVolatile(),
8587                                       ST->isNonTemporal(), ST->getAlignment());
8588       } else {
8589         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
8590                                  ST->getPointerInfo(),
8591                                  ST->isVolatile(), ST->isNonTemporal(),
8592                                  ST->getAlignment());
8593       }
8594
8595       // Create token to keep both nodes around.
8596       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8597                                   MVT::Other, Chain, ReplStore);
8598
8599       // Make sure the new and old chains are cleaned up.
8600       AddToWorkList(Token.getNode());
8601
8602       // Don't add users to work list.
8603       return CombineTo(N, Token, false);
8604     }
8605   }
8606
8607   // Try transforming N to an indexed store.
8608   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8609     return SDValue(N, 0);
8610
8611   // FIXME: is there such a thing as a truncating indexed store?
8612   if (ST->isTruncatingStore() && ST->isUnindexed() &&
8613       Value.getValueType().isInteger()) {
8614     // See if we can simplify the input to this truncstore with knowledge that
8615     // only the low bits are being used.  For example:
8616     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
8617     SDValue Shorter =
8618       GetDemandedBits(Value,
8619                       APInt::getLowBitsSet(
8620                         Value.getValueType().getScalarType().getSizeInBits(),
8621                         ST->getMemoryVT().getScalarType().getSizeInBits()));
8622     AddToWorkList(Value.getNode());
8623     if (Shorter.getNode())
8624       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
8625                                Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
8626                                ST->isVolatile(), ST->isNonTemporal(),
8627                                ST->getAlignment());
8628
8629     // Otherwise, see if we can simplify the operation with
8630     // SimplifyDemandedBits, which only works if the value has a single use.
8631     if (SimplifyDemandedBits(Value,
8632                         APInt::getLowBitsSet(
8633                           Value.getValueType().getScalarType().getSizeInBits(),
8634                           ST->getMemoryVT().getScalarType().getSizeInBits())))
8635       return SDValue(N, 0);
8636   }
8637
8638   // If this is a load followed by a store to the same location, then the store
8639   // is dead/noop.
8640   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
8641     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
8642         ST->isUnindexed() && !ST->isVolatile() &&
8643         // There can't be any side effects between the load and store, such as
8644         // a call or store.
8645         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
8646       // The store is dead, remove it.
8647       return Chain;
8648     }
8649   }
8650
8651   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
8652   // truncating store.  We can do this even if this is already a truncstore.
8653   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
8654       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
8655       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
8656                             ST->getMemoryVT())) {
8657     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
8658                              Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
8659                              ST->isVolatile(), ST->isNonTemporal(),
8660                              ST->getAlignment());
8661   }
8662
8663   // Only perform this optimization before the types are legal, because we
8664   // don't want to perform this optimization on every DAGCombine invocation.
8665   if (!LegalTypes) {
8666     bool EverChanged = false;
8667
8668     do {
8669       // There can be multiple store sequences on the same chain.
8670       // Keep trying to merge store sequences until we are unable to do so
8671       // or until we merge the last store on the chain.
8672       bool Changed = MergeConsecutiveStores(ST);
8673       EverChanged |= Changed;
8674       if (!Changed) break;
8675     } while (ST->getOpcode() != ISD::DELETED_NODE);
8676
8677     if (EverChanged)
8678       return SDValue(N, 0);
8679   }
8680
8681   return ReduceLoadOpStoreWidth(N);
8682 }
8683
8684 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
8685   SDValue InVec = N->getOperand(0);
8686   SDValue InVal = N->getOperand(1);
8687   SDValue EltNo = N->getOperand(2);
8688   SDLoc dl(N);
8689
8690   // If the inserted element is an UNDEF, just use the input vector.
8691   if (InVal.getOpcode() == ISD::UNDEF)
8692     return InVec;
8693
8694   EVT VT = InVec.getValueType();
8695
8696   // If we can't generate a legal BUILD_VECTOR, exit
8697   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
8698     return SDValue();
8699
8700   // Check that we know which element is being inserted
8701   if (!isa<ConstantSDNode>(EltNo))
8702     return SDValue();
8703   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8704
8705   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
8706   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
8707   // vector elements.
8708   SmallVector<SDValue, 8> Ops;
8709   // Do not combine these two vectors if the output vector will not replace
8710   // the input vector.
8711   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
8712     Ops.append(InVec.getNode()->op_begin(),
8713                InVec.getNode()->op_end());
8714   } else if (InVec.getOpcode() == ISD::UNDEF) {
8715     unsigned NElts = VT.getVectorNumElements();
8716     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
8717   } else {
8718     return SDValue();
8719   }
8720
8721   // Insert the element
8722   if (Elt < Ops.size()) {
8723     // All the operands of BUILD_VECTOR must have the same type;
8724     // we enforce that here.
8725     EVT OpVT = Ops[0].getValueType();
8726     if (InVal.getValueType() != OpVT)
8727       InVal = OpVT.bitsGT(InVal.getValueType()) ?
8728                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
8729                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
8730     Ops[Elt] = InVal;
8731   }
8732
8733   // Return the new vector
8734   return DAG.getNode(ISD::BUILD_VECTOR, dl,
8735                      VT, &Ops[0], Ops.size());
8736 }
8737
8738 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
8739   // (vextract (scalar_to_vector val, 0) -> val
8740   SDValue InVec = N->getOperand(0);
8741   EVT VT = InVec.getValueType();
8742   EVT NVT = N->getValueType(0);
8743
8744   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
8745     // Check if the result type doesn't match the inserted element type. A
8746     // SCALAR_TO_VECTOR may truncate the inserted element and the
8747     // EXTRACT_VECTOR_ELT may widen the extracted vector.
8748     SDValue InOp = InVec.getOperand(0);
8749     if (InOp.getValueType() != NVT) {
8750       assert(InOp.getValueType().isInteger() && NVT.isInteger());
8751       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
8752     }
8753     return InOp;
8754   }
8755
8756   SDValue EltNo = N->getOperand(1);
8757   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
8758
8759   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
8760   // We only perform this optimization before the op legalization phase because
8761   // we may introduce new vector instructions which are not backed by TD
8762   // patterns. For example on AVX, extracting elements from a wide vector
8763   // without using extract_subvector.
8764   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
8765       && ConstEltNo && !LegalOperations) {
8766     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8767     int NumElem = VT.getVectorNumElements();
8768     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
8769     // Find the new index to extract from.
8770     int OrigElt = SVOp->getMaskElt(Elt);
8771
8772     // Extracting an undef index is undef.
8773     if (OrigElt == -1)
8774       return DAG.getUNDEF(NVT);
8775
8776     // Select the right vector half to extract from.
8777     if (OrigElt < NumElem) {
8778       InVec = InVec->getOperand(0);
8779     } else {
8780       InVec = InVec->getOperand(1);
8781       OrigElt -= NumElem;
8782     }
8783
8784     EVT IndexTy = TLI.getVectorIdxTy();
8785     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
8786                        InVec, DAG.getConstant(OrigElt, IndexTy));
8787   }
8788
8789   // Perform only after legalization to ensure build_vector / vector_shuffle
8790   // optimizations have already been done.
8791   if (!LegalOperations) return SDValue();
8792
8793   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
8794   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
8795   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
8796
8797   if (ConstEltNo) {
8798     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8799     bool NewLoad = false;
8800     bool BCNumEltsChanged = false;
8801     EVT ExtVT = VT.getVectorElementType();
8802     EVT LVT = ExtVT;
8803
8804     // If the result of load has to be truncated, then it's not necessarily
8805     // profitable.
8806     if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
8807       return SDValue();
8808
8809     if (InVec.getOpcode() == ISD::BITCAST) {
8810       // Don't duplicate a load with other uses.
8811       if (!InVec.hasOneUse())
8812         return SDValue();
8813
8814       EVT BCVT = InVec.getOperand(0).getValueType();
8815       if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
8816         return SDValue();
8817       if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
8818         BCNumEltsChanged = true;
8819       InVec = InVec.getOperand(0);
8820       ExtVT = BCVT.getVectorElementType();
8821       NewLoad = true;
8822     }
8823
8824     LoadSDNode *LN0 = NULL;
8825     const ShuffleVectorSDNode *SVN = NULL;
8826     if (ISD::isNormalLoad(InVec.getNode())) {
8827       LN0 = cast<LoadSDNode>(InVec);
8828     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8829                InVec.getOperand(0).getValueType() == ExtVT &&
8830                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
8831       // Don't duplicate a load with other uses.
8832       if (!InVec.hasOneUse())
8833         return SDValue();
8834
8835       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
8836     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
8837       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
8838       // =>
8839       // (load $addr+1*size)
8840
8841       // Don't duplicate a load with other uses.
8842       if (!InVec.hasOneUse())
8843         return SDValue();
8844
8845       // If the bit convert changed the number of elements, it is unsafe
8846       // to examine the mask.
8847       if (BCNumEltsChanged)
8848         return SDValue();
8849
8850       // Select the input vector, guarding against out of range extract vector.
8851       unsigned NumElems = VT.getVectorNumElements();
8852       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
8853       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
8854
8855       if (InVec.getOpcode() == ISD::BITCAST) {
8856         // Don't duplicate a load with other uses.
8857         if (!InVec.hasOneUse())
8858           return SDValue();
8859
8860         InVec = InVec.getOperand(0);
8861       }
8862       if (ISD::isNormalLoad(InVec.getNode())) {
8863         LN0 = cast<LoadSDNode>(InVec);
8864         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
8865       }
8866     }
8867
8868     // Make sure we found a non-volatile load and the extractelement is
8869     // the only use.
8870     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
8871       return SDValue();
8872
8873     // If Idx was -1 above, Elt is going to be -1, so just return undef.
8874     if (Elt == -1)
8875       return DAG.getUNDEF(LVT);
8876
8877     unsigned Align = LN0->getAlignment();
8878     if (NewLoad) {
8879       // Check the resultant load doesn't need a higher alignment than the
8880       // original load.
8881       unsigned NewAlign =
8882         TLI.getDataLayout()
8883             ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
8884
8885       if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
8886         return SDValue();
8887
8888       Align = NewAlign;
8889     }
8890
8891     SDValue NewPtr = LN0->getBasePtr();
8892     unsigned PtrOff = 0;
8893
8894     if (Elt) {
8895       PtrOff = LVT.getSizeInBits() * Elt / 8;
8896       EVT PtrType = NewPtr.getValueType();
8897       if (TLI.isBigEndian())
8898         PtrOff = VT.getSizeInBits() / 8 - PtrOff;
8899       NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
8900                            DAG.getConstant(PtrOff, PtrType));
8901     }
8902
8903     // The replacement we need to do here is a little tricky: we need to
8904     // replace an extractelement of a load with a load.
8905     // Use ReplaceAllUsesOfValuesWith to do the replacement.
8906     // Note that this replacement assumes that the extractvalue is the only
8907     // use of the load; that's okay because we don't want to perform this
8908     // transformation in other cases anyway.
8909     SDValue Load;
8910     SDValue Chain;
8911     if (NVT.bitsGT(LVT)) {
8912       // If the result type of vextract is wider than the load, then issue an
8913       // extending load instead.
8914       ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
8915         ? ISD::ZEXTLOAD : ISD::EXTLOAD;
8916       Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
8917                             NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
8918                             LVT, LN0->isVolatile(), LN0->isNonTemporal(),Align);
8919       Chain = Load.getValue(1);
8920     } else {
8921       Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
8922                          LN0->getPointerInfo().getWithOffset(PtrOff),
8923                          LN0->isVolatile(), LN0->isNonTemporal(),
8924                          LN0->isInvariant(), Align);
8925       Chain = Load.getValue(1);
8926       if (NVT.bitsLT(LVT))
8927         Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
8928       else
8929         Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
8930     }
8931     WorkListRemover DeadNodes(*this);
8932     SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
8933     SDValue To[] = { Load, Chain };
8934     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8935     // Since we're explcitly calling ReplaceAllUses, add the new node to the
8936     // worklist explicitly as well.
8937     AddToWorkList(Load.getNode());
8938     AddUsersToWorkList(Load.getNode()); // Add users too
8939     // Make sure to revisit this node to clean it up; it will usually be dead.
8940     AddToWorkList(N);
8941     return SDValue(N, 0);
8942   }
8943
8944   return SDValue();
8945 }
8946
8947 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
8948 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
8949   // We perform this optimization post type-legalization because
8950   // the type-legalizer often scalarizes integer-promoted vectors.
8951   // Performing this optimization before may create bit-casts which
8952   // will be type-legalized to complex code sequences.
8953   // We perform this optimization only before the operation legalizer because we
8954   // may introduce illegal operations.
8955   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
8956     return SDValue();
8957
8958   unsigned NumInScalars = N->getNumOperands();
8959   SDLoc dl(N);
8960   EVT VT = N->getValueType(0);
8961
8962   // Check to see if this is a BUILD_VECTOR of a bunch of values
8963   // which come from any_extend or zero_extend nodes. If so, we can create
8964   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
8965   // optimizations. We do not handle sign-extend because we can't fill the sign
8966   // using shuffles.
8967   EVT SourceType = MVT::Other;
8968   bool AllAnyExt = true;
8969
8970   for (unsigned i = 0; i != NumInScalars; ++i) {
8971     SDValue In = N->getOperand(i);
8972     // Ignore undef inputs.
8973     if (In.getOpcode() == ISD::UNDEF) continue;
8974
8975     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
8976     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
8977
8978     // Abort if the element is not an extension.
8979     if (!ZeroExt && !AnyExt) {
8980       SourceType = MVT::Other;
8981       break;
8982     }
8983
8984     // The input is a ZeroExt or AnyExt. Check the original type.
8985     EVT InTy = In.getOperand(0).getValueType();
8986
8987     // Check that all of the widened source types are the same.
8988     if (SourceType == MVT::Other)
8989       // First time.
8990       SourceType = InTy;
8991     else if (InTy != SourceType) {
8992       // Multiple income types. Abort.
8993       SourceType = MVT::Other;
8994       break;
8995     }
8996
8997     // Check if all of the extends are ANY_EXTENDs.
8998     AllAnyExt &= AnyExt;
8999   }
9000
9001   // In order to have valid types, all of the inputs must be extended from the
9002   // same source type and all of the inputs must be any or zero extend.
9003   // Scalar sizes must be a power of two.
9004   EVT OutScalarTy = VT.getScalarType();
9005   bool ValidTypes = SourceType != MVT::Other &&
9006                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9007                  isPowerOf2_32(SourceType.getSizeInBits());
9008
9009   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9010   // turn into a single shuffle instruction.
9011   if (!ValidTypes)
9012     return SDValue();
9013
9014   bool isLE = TLI.isLittleEndian();
9015   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
9016   assert(ElemRatio > 1 && "Invalid element size ratio");
9017   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
9018                                DAG.getConstant(0, SourceType);
9019
9020   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
9021   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
9022
9023   // Populate the new build_vector
9024   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9025     SDValue Cast = N->getOperand(i);
9026     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
9027             Cast.getOpcode() == ISD::ZERO_EXTEND ||
9028             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
9029     SDValue In;
9030     if (Cast.getOpcode() == ISD::UNDEF)
9031       In = DAG.getUNDEF(SourceType);
9032     else
9033       In = Cast->getOperand(0);
9034     unsigned Index = isLE ? (i * ElemRatio) :
9035                             (i * ElemRatio + (ElemRatio - 1));
9036
9037     assert(Index < Ops.size() && "Invalid index");
9038     Ops[Index] = In;
9039   }
9040
9041   // The type of the new BUILD_VECTOR node.
9042   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
9043   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
9044          "Invalid vector size");
9045   // Check if the new vector type is legal.
9046   if (!isTypeLegal(VecVT)) return SDValue();
9047
9048   // Make the new BUILD_VECTOR.
9049   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
9050
9051   // The new BUILD_VECTOR node has the potential to be further optimized.
9052   AddToWorkList(BV.getNode());
9053   // Bitcast to the desired type.
9054   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9055 }
9056
9057 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
9058   EVT VT = N->getValueType(0);
9059
9060   unsigned NumInScalars = N->getNumOperands();
9061   SDLoc dl(N);
9062
9063   EVT SrcVT = MVT::Other;
9064   unsigned Opcode = ISD::DELETED_NODE;
9065   unsigned NumDefs = 0;
9066
9067   for (unsigned i = 0; i != NumInScalars; ++i) {
9068     SDValue In = N->getOperand(i);
9069     unsigned Opc = In.getOpcode();
9070
9071     if (Opc == ISD::UNDEF)
9072       continue;
9073
9074     // If all scalar values are floats and converted from integers.
9075     if (Opcode == ISD::DELETED_NODE &&
9076         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
9077       Opcode = Opc;
9078     }
9079
9080     if (Opc != Opcode)
9081       return SDValue();
9082
9083     EVT InVT = In.getOperand(0).getValueType();
9084
9085     // If all scalar values are typed differently, bail out. It's chosen to
9086     // simplify BUILD_VECTOR of integer types.
9087     if (SrcVT == MVT::Other)
9088       SrcVT = InVT;
9089     if (SrcVT != InVT)
9090       return SDValue();
9091     NumDefs++;
9092   }
9093
9094   // If the vector has just one element defined, it's not worth to fold it into
9095   // a vectorized one.
9096   if (NumDefs < 2)
9097     return SDValue();
9098
9099   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
9100          && "Should only handle conversion from integer to float.");
9101   assert(SrcVT != MVT::Other && "Cannot determine source type!");
9102
9103   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
9104
9105   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
9106     return SDValue();
9107
9108   SmallVector<SDValue, 8> Opnds;
9109   for (unsigned i = 0; i != NumInScalars; ++i) {
9110     SDValue In = N->getOperand(i);
9111
9112     if (In.getOpcode() == ISD::UNDEF)
9113       Opnds.push_back(DAG.getUNDEF(SrcVT));
9114     else
9115       Opnds.push_back(In.getOperand(0));
9116   }
9117   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
9118                            &Opnds[0], Opnds.size());
9119   AddToWorkList(BV.getNode());
9120
9121   return DAG.getNode(Opcode, dl, VT, BV);
9122 }
9123
9124 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
9125   unsigned NumInScalars = N->getNumOperands();
9126   SDLoc dl(N);
9127   EVT VT = N->getValueType(0);
9128
9129   // A vector built entirely of undefs is undef.
9130   if (ISD::allOperandsUndef(N))
9131     return DAG.getUNDEF(VT);
9132
9133   SDValue V = reduceBuildVecExtToExtBuildVec(N);
9134   if (V.getNode())
9135     return V;
9136
9137   V = reduceBuildVecConvertToConvertBuildVec(N);
9138   if (V.getNode())
9139     return V;
9140
9141   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
9142   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
9143   // at most two distinct vectors, turn this into a shuffle node.
9144
9145   // May only combine to shuffle after legalize if shuffle is legal.
9146   if (LegalOperations &&
9147       !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
9148     return SDValue();
9149
9150   SDValue VecIn1, VecIn2;
9151   for (unsigned i = 0; i != NumInScalars; ++i) {
9152     // Ignore undef inputs.
9153     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
9154
9155     // If this input is something other than a EXTRACT_VECTOR_ELT with a
9156     // constant index, bail out.
9157     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9158         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
9159       VecIn1 = VecIn2 = SDValue(0, 0);
9160       break;
9161     }
9162
9163     // We allow up to two distinct input vectors.
9164     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
9165     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
9166       continue;
9167
9168     if (VecIn1.getNode() == 0) {
9169       VecIn1 = ExtractedFromVec;
9170     } else if (VecIn2.getNode() == 0) {
9171       VecIn2 = ExtractedFromVec;
9172     } else {
9173       // Too many inputs.
9174       VecIn1 = VecIn2 = SDValue(0, 0);
9175       break;
9176     }
9177   }
9178
9179     // If everything is good, we can make a shuffle operation.
9180   if (VecIn1.getNode()) {
9181     SmallVector<int, 8> Mask;
9182     for (unsigned i = 0; i != NumInScalars; ++i) {
9183       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
9184         Mask.push_back(-1);
9185         continue;
9186       }
9187
9188       // If extracting from the first vector, just use the index directly.
9189       SDValue Extract = N->getOperand(i);
9190       SDValue ExtVal = Extract.getOperand(1);
9191       if (Extract.getOperand(0) == VecIn1) {
9192         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9193         if (ExtIndex > VT.getVectorNumElements())
9194           return SDValue();
9195
9196         Mask.push_back(ExtIndex);
9197         continue;
9198       }
9199
9200       // Otherwise, use InIdx + VecSize
9201       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9202       Mask.push_back(Idx+NumInScalars);
9203     }
9204
9205     // We can't generate a shuffle node with mismatched input and output types.
9206     // Attempt to transform a single input vector to the correct type.
9207     if ((VT != VecIn1.getValueType())) {
9208       // We don't support shuffeling between TWO values of different types.
9209       if (VecIn2.getNode() != 0)
9210         return SDValue();
9211
9212       // We only support widening of vectors which are half the size of the
9213       // output registers. For example XMM->YMM widening on X86 with AVX.
9214       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
9215         return SDValue();
9216
9217       // If the input vector type has a different base type to the output
9218       // vector type, bail out.
9219       if (VecIn1.getValueType().getVectorElementType() !=
9220           VT.getVectorElementType())
9221         return SDValue();
9222
9223       // Widen the input vector by adding undef values.
9224       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9225                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
9226     }
9227
9228     // If VecIn2 is unused then change it to undef.
9229     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
9230
9231     // Check that we were able to transform all incoming values to the same
9232     // type.
9233     if (VecIn2.getValueType() != VecIn1.getValueType() ||
9234         VecIn1.getValueType() != VT)
9235           return SDValue();
9236
9237     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
9238     if (!isTypeLegal(VT))
9239       return SDValue();
9240
9241     // Return the new VECTOR_SHUFFLE node.
9242     SDValue Ops[2];
9243     Ops[0] = VecIn1;
9244     Ops[1] = VecIn2;
9245     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
9246   }
9247
9248   return SDValue();
9249 }
9250
9251 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
9252   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
9253   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
9254   // inputs come from at most two distinct vectors, turn this into a shuffle
9255   // node.
9256
9257   // If we only have one input vector, we don't need to do any concatenation.
9258   if (N->getNumOperands() == 1)
9259     return N->getOperand(0);
9260
9261   // Check if all of the operands are undefs.
9262   if (ISD::allOperandsUndef(N))
9263     return DAG.getUNDEF(N->getValueType(0));
9264
9265   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
9266   // nodes often generate nop CONCAT_VECTOR nodes.
9267   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
9268   // place the incoming vectors at the exact same location.
9269   SDValue SingleSource = SDValue();
9270   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
9271
9272   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9273     SDValue Op = N->getOperand(i);
9274
9275     if (Op.getOpcode() == ISD::UNDEF)
9276       continue;
9277
9278     // Check if this is the identity extract:
9279     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
9280       return SDValue();
9281
9282     // Find the single incoming vector for the extract_subvector.
9283     if (SingleSource.getNode()) {
9284       if (Op.getOperand(0) != SingleSource)
9285         return SDValue();
9286     } else {
9287       SingleSource = Op.getOperand(0);
9288
9289       // Check the source type is the same as the type of the result.
9290       // If not, this concat may extend the vector, so we can not
9291       // optimize it away.
9292       if (SingleSource.getValueType() != N->getValueType(0))
9293         return SDValue();
9294     }
9295
9296     unsigned IdentityIndex = i * PartNumElem;
9297     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9298     // The extract index must be constant.
9299     if (!CS)
9300       return SDValue();
9301
9302     // Check that we are reading from the identity index.
9303     if (CS->getZExtValue() != IdentityIndex)
9304       return SDValue();
9305   }
9306
9307   if (SingleSource.getNode())
9308     return SingleSource;
9309
9310   return SDValue();
9311 }
9312
9313 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
9314   EVT NVT = N->getValueType(0);
9315   SDValue V = N->getOperand(0);
9316
9317   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
9318     // Combine:
9319     //    (extract_subvec (concat V1, V2, ...), i)
9320     // Into:
9321     //    Vi if possible
9322     // Only operand 0 is checked as 'concat' assumes all inputs of the same type.
9323     if (V->getOperand(0).getValueType() != NVT)
9324       return SDValue();
9325     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9326     unsigned NumElems = NVT.getVectorNumElements();
9327     assert((Idx % NumElems) == 0 &&
9328            "IDX in concat is not a multiple of the result vector length.");
9329     return V->getOperand(Idx / NumElems);
9330   }
9331
9332   // Skip bitcasting
9333   if (V->getOpcode() == ISD::BITCAST)
9334     V = V.getOperand(0);
9335
9336   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
9337     SDLoc dl(N);
9338     // Handle only simple case where vector being inserted and vector
9339     // being extracted are of same type, and are half size of larger vectors.
9340     EVT BigVT = V->getOperand(0).getValueType();
9341     EVT SmallVT = V->getOperand(1).getValueType();
9342     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
9343       return SDValue();
9344
9345     // Only handle cases where both indexes are constants with the same type.
9346     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
9347     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
9348
9349     if (InsIdx && ExtIdx &&
9350         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
9351         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
9352       // Combine:
9353       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
9354       // Into:
9355       //    indices are equal or bit offsets are equal => V1
9356       //    otherwise => (extract_subvec V1, ExtIdx)
9357       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
9358           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
9359         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
9360       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
9361                          DAG.getNode(ISD::BITCAST, dl,
9362                                      N->getOperand(0).getValueType(),
9363                                      V->getOperand(0)), N->getOperand(1));
9364     }
9365   }
9366
9367   return SDValue();
9368 }
9369
9370 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
9371 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
9372   EVT VT = N->getValueType(0);
9373   unsigned NumElts = VT.getVectorNumElements();
9374
9375   SDValue N0 = N->getOperand(0);
9376   SDValue N1 = N->getOperand(1);
9377   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9378
9379   SmallVector<SDValue, 4> Ops;
9380   EVT ConcatVT = N0.getOperand(0).getValueType();
9381   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
9382   unsigned NumConcats = NumElts / NumElemsPerConcat;
9383
9384   // Look at every vector that's inserted. We're looking for exact
9385   // subvector-sized copies from a concatenated vector
9386   for (unsigned I = 0; I != NumConcats; ++I) {
9387     // Make sure we're dealing with a copy.
9388     unsigned Begin = I * NumElemsPerConcat;
9389     bool AllUndef = true, NoUndef = true;
9390     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
9391       if (SVN->getMaskElt(J) >= 0)
9392         AllUndef = false;
9393       else
9394         NoUndef = false;
9395     }
9396
9397     if (NoUndef) {
9398       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
9399         return SDValue();
9400
9401       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
9402         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
9403           return SDValue();
9404
9405       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
9406       if (FirstElt < N0.getNumOperands())
9407         Ops.push_back(N0.getOperand(FirstElt));
9408       else
9409         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
9410
9411     } else if (AllUndef) {
9412       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
9413     } else { // Mixed with general masks and undefs, can't do optimization.
9414       return SDValue();
9415     }
9416   }
9417
9418   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
9419                      Ops.size());
9420 }
9421
9422 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
9423   EVT VT = N->getValueType(0);
9424   unsigned NumElts = VT.getVectorNumElements();
9425
9426   SDValue N0 = N->getOperand(0);
9427   SDValue N1 = N->getOperand(1);
9428
9429   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
9430
9431   // Canonicalize shuffle undef, undef -> undef
9432   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
9433     return DAG.getUNDEF(VT);
9434
9435   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9436
9437   // Canonicalize shuffle v, v -> v, undef
9438   if (N0 == N1) {
9439     SmallVector<int, 8> NewMask;
9440     for (unsigned i = 0; i != NumElts; ++i) {
9441       int Idx = SVN->getMaskElt(i);
9442       if (Idx >= (int)NumElts) Idx -= NumElts;
9443       NewMask.push_back(Idx);
9444     }
9445     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
9446                                 &NewMask[0]);
9447   }
9448
9449   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
9450   if (N0.getOpcode() == ISD::UNDEF) {
9451     SmallVector<int, 8> NewMask;
9452     for (unsigned i = 0; i != NumElts; ++i) {
9453       int Idx = SVN->getMaskElt(i);
9454       if (Idx >= 0) {
9455         if (Idx >= (int)NumElts)
9456           Idx -= NumElts;
9457         else
9458           Idx = -1; // remove reference to lhs
9459       }
9460       NewMask.push_back(Idx);
9461     }
9462     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
9463                                 &NewMask[0]);
9464   }
9465
9466   // Remove references to rhs if it is undef
9467   if (N1.getOpcode() == ISD::UNDEF) {
9468     bool Changed = false;
9469     SmallVector<int, 8> NewMask;
9470     for (unsigned i = 0; i != NumElts; ++i) {
9471       int Idx = SVN->getMaskElt(i);
9472       if (Idx >= (int)NumElts) {
9473         Idx = -1;
9474         Changed = true;
9475       }
9476       NewMask.push_back(Idx);
9477     }
9478     if (Changed)
9479       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
9480   }
9481
9482   // If it is a splat, check if the argument vector is another splat or a
9483   // build_vector with all scalar elements the same.
9484   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
9485     SDNode *V = N0.getNode();
9486
9487     // If this is a bit convert that changes the element type of the vector but
9488     // not the number of vector elements, look through it.  Be careful not to
9489     // look though conversions that change things like v4f32 to v2f64.
9490     if (V->getOpcode() == ISD::BITCAST) {
9491       SDValue ConvInput = V->getOperand(0);
9492       if (ConvInput.getValueType().isVector() &&
9493           ConvInput.getValueType().getVectorNumElements() == NumElts)
9494         V = ConvInput.getNode();
9495     }
9496
9497     if (V->getOpcode() == ISD::BUILD_VECTOR) {
9498       assert(V->getNumOperands() == NumElts &&
9499              "BUILD_VECTOR has wrong number of operands");
9500       SDValue Base;
9501       bool AllSame = true;
9502       for (unsigned i = 0; i != NumElts; ++i) {
9503         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
9504           Base = V->getOperand(i);
9505           break;
9506         }
9507       }
9508       // Splat of <u, u, u, u>, return <u, u, u, u>
9509       if (!Base.getNode())
9510         return N0;
9511       for (unsigned i = 0; i != NumElts; ++i) {
9512         if (V->getOperand(i) != Base) {
9513           AllSame = false;
9514           break;
9515         }
9516       }
9517       // Splat of <x, x, x, x>, return <x, x, x, x>
9518       if (AllSame)
9519         return N0;
9520     }
9521   }
9522
9523   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
9524       Level < AfterLegalizeVectorOps &&
9525       (N1.getOpcode() == ISD::UNDEF ||
9526       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
9527        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
9528     SDValue V = partitionShuffleOfConcats(N, DAG);
9529
9530     if (V.getNode())
9531       return V;
9532   }
9533
9534   // If this shuffle node is simply a swizzle of another shuffle node,
9535   // and it reverses the swizzle of the previous shuffle then we can
9536   // optimize shuffle(shuffle(x, undef), undef) -> x.
9537   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
9538       N1.getOpcode() == ISD::UNDEF) {
9539
9540     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
9541
9542     // Shuffle nodes can only reverse shuffles with a single non-undef value.
9543     if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
9544       return SDValue();
9545
9546     // The incoming shuffle must be of the same type as the result of the
9547     // current shuffle.
9548     assert(OtherSV->getOperand(0).getValueType() == VT &&
9549            "Shuffle types don't match");
9550
9551     for (unsigned i = 0; i != NumElts; ++i) {
9552       int Idx = SVN->getMaskElt(i);
9553       assert(Idx < (int)NumElts && "Index references undef operand");
9554       // Next, this index comes from the first value, which is the incoming
9555       // shuffle. Adopt the incoming index.
9556       if (Idx >= 0)
9557         Idx = OtherSV->getMaskElt(Idx);
9558
9559       // The combined shuffle must map each index to itself.
9560       if (Idx >= 0 && (unsigned)Idx != i)
9561         return SDValue();
9562     }
9563
9564     return OtherSV->getOperand(0);
9565   }
9566
9567   return SDValue();
9568 }
9569
9570 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
9571 /// an AND to a vector_shuffle with the destination vector and a zero vector.
9572 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
9573 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
9574 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
9575   EVT VT = N->getValueType(0);
9576   SDLoc dl(N);
9577   SDValue LHS = N->getOperand(0);
9578   SDValue RHS = N->getOperand(1);
9579   if (N->getOpcode() == ISD::AND) {
9580     if (RHS.getOpcode() == ISD::BITCAST)
9581       RHS = RHS.getOperand(0);
9582     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
9583       SmallVector<int, 8> Indices;
9584       unsigned NumElts = RHS.getNumOperands();
9585       for (unsigned i = 0; i != NumElts; ++i) {
9586         SDValue Elt = RHS.getOperand(i);
9587         if (!isa<ConstantSDNode>(Elt))
9588           return SDValue();
9589
9590         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
9591           Indices.push_back(i);
9592         else if (cast<ConstantSDNode>(Elt)->isNullValue())
9593           Indices.push_back(NumElts);
9594         else
9595           return SDValue();
9596       }
9597
9598       // Let's see if the target supports this vector_shuffle.
9599       EVT RVT = RHS.getValueType();
9600       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
9601         return SDValue();
9602
9603       // Return the new VECTOR_SHUFFLE node.
9604       EVT EltVT = RVT.getVectorElementType();
9605       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
9606                                      DAG.getConstant(0, EltVT));
9607       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
9608                                  RVT, &ZeroOps[0], ZeroOps.size());
9609       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
9610       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
9611       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
9612     }
9613   }
9614
9615   return SDValue();
9616 }
9617
9618 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
9619 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
9620   assert(N->getValueType(0).isVector() &&
9621          "SimplifyVBinOp only works on vectors!");
9622
9623   SDValue LHS = N->getOperand(0);
9624   SDValue RHS = N->getOperand(1);
9625   SDValue Shuffle = XformToShuffleWithZero(N);
9626   if (Shuffle.getNode()) return Shuffle;
9627
9628   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
9629   // this operation.
9630   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
9631       RHS.getOpcode() == ISD::BUILD_VECTOR) {
9632     SmallVector<SDValue, 8> Ops;
9633     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
9634       SDValue LHSOp = LHS.getOperand(i);
9635       SDValue RHSOp = RHS.getOperand(i);
9636       // If these two elements can't be folded, bail out.
9637       if ((LHSOp.getOpcode() != ISD::UNDEF &&
9638            LHSOp.getOpcode() != ISD::Constant &&
9639            LHSOp.getOpcode() != ISD::ConstantFP) ||
9640           (RHSOp.getOpcode() != ISD::UNDEF &&
9641            RHSOp.getOpcode() != ISD::Constant &&
9642            RHSOp.getOpcode() != ISD::ConstantFP))
9643         break;
9644
9645       // Can't fold divide by zero.
9646       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
9647           N->getOpcode() == ISD::FDIV) {
9648         if ((RHSOp.getOpcode() == ISD::Constant &&
9649              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
9650             (RHSOp.getOpcode() == ISD::ConstantFP &&
9651              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
9652           break;
9653       }
9654
9655       EVT VT = LHSOp.getValueType();
9656       EVT RVT = RHSOp.getValueType();
9657       if (RVT != VT) {
9658         // Integer BUILD_VECTOR operands may have types larger than the element
9659         // size (e.g., when the element type is not legal).  Prior to type
9660         // legalization, the types may not match between the two BUILD_VECTORS.
9661         // Truncate one of the operands to make them match.
9662         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
9663           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
9664         } else {
9665           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
9666           VT = RVT;
9667         }
9668       }
9669       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
9670                                    LHSOp, RHSOp);
9671       if (FoldOp.getOpcode() != ISD::UNDEF &&
9672           FoldOp.getOpcode() != ISD::Constant &&
9673           FoldOp.getOpcode() != ISD::ConstantFP)
9674         break;
9675       Ops.push_back(FoldOp);
9676       AddToWorkList(FoldOp.getNode());
9677     }
9678
9679     if (Ops.size() == LHS.getNumOperands())
9680       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
9681                          LHS.getValueType(), &Ops[0], Ops.size());
9682   }
9683
9684   return SDValue();
9685 }
9686
9687 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
9688 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
9689   assert(N->getValueType(0).isVector() &&
9690          "SimplifyVUnaryOp only works on vectors!");
9691
9692   SDValue N0 = N->getOperand(0);
9693
9694   if (N0.getOpcode() != ISD::BUILD_VECTOR)
9695     return SDValue();
9696
9697   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
9698   SmallVector<SDValue, 8> Ops;
9699   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
9700     SDValue Op = N0.getOperand(i);
9701     if (Op.getOpcode() != ISD::UNDEF &&
9702         Op.getOpcode() != ISD::ConstantFP)
9703       break;
9704     EVT EltVT = Op.getValueType();
9705     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
9706     if (FoldOp.getOpcode() != ISD::UNDEF &&
9707         FoldOp.getOpcode() != ISD::ConstantFP)
9708       break;
9709     Ops.push_back(FoldOp);
9710     AddToWorkList(FoldOp.getNode());
9711   }
9712
9713   if (Ops.size() != N0.getNumOperands())
9714     return SDValue();
9715
9716   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
9717                      N0.getValueType(), &Ops[0], Ops.size());
9718 }
9719
9720 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
9721                                     SDValue N1, SDValue N2){
9722   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
9723
9724   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
9725                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
9726
9727   // If we got a simplified select_cc node back from SimplifySelectCC, then
9728   // break it down into a new SETCC node, and a new SELECT node, and then return
9729   // the SELECT node, since we were called with a SELECT node.
9730   if (SCC.getNode()) {
9731     // Check to see if we got a select_cc back (to turn into setcc/select).
9732     // Otherwise, just return whatever node we got back, like fabs.
9733     if (SCC.getOpcode() == ISD::SELECT_CC) {
9734       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
9735                                   N0.getValueType(),
9736                                   SCC.getOperand(0), SCC.getOperand(1),
9737                                   SCC.getOperand(4));
9738       AddToWorkList(SETCC.getNode());
9739       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
9740                            SCC.getOperand(2), SCC.getOperand(3), SETCC);
9741     }
9742
9743     return SCC;
9744   }
9745   return SDValue();
9746 }
9747
9748 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
9749 /// are the two values being selected between, see if we can simplify the
9750 /// select.  Callers of this should assume that TheSelect is deleted if this
9751 /// returns true.  As such, they should return the appropriate thing (e.g. the
9752 /// node) back to the top-level of the DAG combiner loop to avoid it being
9753 /// looked at.
9754 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
9755                                     SDValue RHS) {
9756
9757   // Cannot simplify select with vector condition
9758   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
9759
9760   // If this is a select from two identical things, try to pull the operation
9761   // through the select.
9762   if (LHS.getOpcode() != RHS.getOpcode() ||
9763       !LHS.hasOneUse() || !RHS.hasOneUse())
9764     return false;
9765
9766   // If this is a load and the token chain is identical, replace the select
9767   // of two loads with a load through a select of the address to load from.
9768   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
9769   // constants have been dropped into the constant pool.
9770   if (LHS.getOpcode() == ISD::LOAD) {
9771     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
9772     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
9773
9774     // Token chains must be identical.
9775     if (LHS.getOperand(0) != RHS.getOperand(0) ||
9776         // Do not let this transformation reduce the number of volatile loads.
9777         LLD->isVolatile() || RLD->isVolatile() ||
9778         // If this is an EXTLOAD, the VT's must match.
9779         LLD->getMemoryVT() != RLD->getMemoryVT() ||
9780         // If this is an EXTLOAD, the kind of extension must match.
9781         (LLD->getExtensionType() != RLD->getExtensionType() &&
9782          // The only exception is if one of the extensions is anyext.
9783          LLD->getExtensionType() != ISD::EXTLOAD &&
9784          RLD->getExtensionType() != ISD::EXTLOAD) ||
9785         // FIXME: this discards src value information.  This is
9786         // over-conservative. It would be beneficial to be able to remember
9787         // both potential memory locations.  Since we are discarding
9788         // src value info, don't do the transformation if the memory
9789         // locations are not in the default address space.
9790         LLD->getPointerInfo().getAddrSpace() != 0 ||
9791         RLD->getPointerInfo().getAddrSpace() != 0 ||
9792         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
9793                                       LLD->getBasePtr().getValueType()))
9794       return false;
9795
9796     // Check that the select condition doesn't reach either load.  If so,
9797     // folding this will induce a cycle into the DAG.  If not, this is safe to
9798     // xform, so create a select of the addresses.
9799     SDValue Addr;
9800     if (TheSelect->getOpcode() == ISD::SELECT) {
9801       SDNode *CondNode = TheSelect->getOperand(0).getNode();
9802       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
9803           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
9804         return false;
9805       // The loads must not depend on one another.
9806       if (LLD->isPredecessorOf(RLD) ||
9807           RLD->isPredecessorOf(LLD))
9808         return false;
9809       Addr = DAG.getSelect(SDLoc(TheSelect),
9810                            LLD->getBasePtr().getValueType(),
9811                            TheSelect->getOperand(0), LLD->getBasePtr(),
9812                            RLD->getBasePtr());
9813     } else {  // Otherwise SELECT_CC
9814       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
9815       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
9816
9817       if ((LLD->hasAnyUseOfValue(1) &&
9818            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
9819           (RLD->hasAnyUseOfValue(1) &&
9820            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
9821         return false;
9822
9823       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
9824                          LLD->getBasePtr().getValueType(),
9825                          TheSelect->getOperand(0),
9826                          TheSelect->getOperand(1),
9827                          LLD->getBasePtr(), RLD->getBasePtr(),
9828                          TheSelect->getOperand(4));
9829     }
9830
9831     SDValue Load;
9832     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
9833       Load = DAG.getLoad(TheSelect->getValueType(0),
9834                          SDLoc(TheSelect),
9835                          // FIXME: Discards pointer info.
9836                          LLD->getChain(), Addr, MachinePointerInfo(),
9837                          LLD->isVolatile(), LLD->isNonTemporal(),
9838                          LLD->isInvariant(), LLD->getAlignment());
9839     } else {
9840       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
9841                             RLD->getExtensionType() : LLD->getExtensionType(),
9842                             SDLoc(TheSelect),
9843                             TheSelect->getValueType(0),
9844                             // FIXME: Discards pointer info.
9845                             LLD->getChain(), Addr, MachinePointerInfo(),
9846                             LLD->getMemoryVT(), LLD->isVolatile(),
9847                             LLD->isNonTemporal(), LLD->getAlignment());
9848     }
9849
9850     // Users of the select now use the result of the load.
9851     CombineTo(TheSelect, Load);
9852
9853     // Users of the old loads now use the new load's chain.  We know the
9854     // old-load value is dead now.
9855     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
9856     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
9857     return true;
9858   }
9859
9860   return false;
9861 }
9862
9863 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
9864 /// where 'cond' is the comparison specified by CC.
9865 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
9866                                       SDValue N2, SDValue N3,
9867                                       ISD::CondCode CC, bool NotExtCompare) {
9868   // (x ? y : y) -> y.
9869   if (N2 == N3) return N2;
9870
9871   EVT VT = N2.getValueType();
9872   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
9873   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
9874   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
9875
9876   // Determine if the condition we're dealing with is constant
9877   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
9878                               N0, N1, CC, DL, false);
9879   if (SCC.getNode()) AddToWorkList(SCC.getNode());
9880   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
9881
9882   // fold select_cc true, x, y -> x
9883   if (SCCC && !SCCC->isNullValue())
9884     return N2;
9885   // fold select_cc false, x, y -> y
9886   if (SCCC && SCCC->isNullValue())
9887     return N3;
9888
9889   // Check to see if we can simplify the select into an fabs node
9890   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
9891     // Allow either -0.0 or 0.0
9892     if (CFP->getValueAPF().isZero()) {
9893       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
9894       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
9895           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
9896           N2 == N3.getOperand(0))
9897         return DAG.getNode(ISD::FABS, DL, VT, N0);
9898
9899       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
9900       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
9901           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
9902           N2.getOperand(0) == N3)
9903         return DAG.getNode(ISD::FABS, DL, VT, N3);
9904     }
9905   }
9906
9907   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
9908   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
9909   // in it.  This is a win when the constant is not otherwise available because
9910   // it replaces two constant pool loads with one.  We only do this if the FP
9911   // type is known to be legal, because if it isn't, then we are before legalize
9912   // types an we want the other legalization to happen first (e.g. to avoid
9913   // messing with soft float) and if the ConstantFP is not legal, because if
9914   // it is legal, we may not need to store the FP constant in a constant pool.
9915   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
9916     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
9917       if (TLI.isTypeLegal(N2.getValueType()) &&
9918           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
9919            TargetLowering::Legal) &&
9920           // If both constants have multiple uses, then we won't need to do an
9921           // extra load, they are likely around in registers for other users.
9922           (TV->hasOneUse() || FV->hasOneUse())) {
9923         Constant *Elts[] = {
9924           const_cast<ConstantFP*>(FV->getConstantFPValue()),
9925           const_cast<ConstantFP*>(TV->getConstantFPValue())
9926         };
9927         Type *FPTy = Elts[0]->getType();
9928         const DataLayout &TD = *TLI.getDataLayout();
9929
9930         // Create a ConstantArray of the two constants.
9931         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
9932         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
9933                                             TD.getPrefTypeAlignment(FPTy));
9934         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9935
9936         // Get the offsets to the 0 and 1 element of the array so that we can
9937         // select between them.
9938         SDValue Zero = DAG.getIntPtrConstant(0);
9939         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
9940         SDValue One = DAG.getIntPtrConstant(EltSize);
9941
9942         SDValue Cond = DAG.getSetCC(DL,
9943                                     getSetCCResultType(N0.getValueType()),
9944                                     N0, N1, CC);
9945         AddToWorkList(Cond.getNode());
9946         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
9947                                           Cond, One, Zero);
9948         AddToWorkList(CstOffset.getNode());
9949         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
9950                             CstOffset);
9951         AddToWorkList(CPIdx.getNode());
9952         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
9953                            MachinePointerInfo::getConstantPool(), false,
9954                            false, false, Alignment);
9955
9956       }
9957     }
9958
9959   // Check to see if we can perform the "gzip trick", transforming
9960   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
9961   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
9962       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
9963        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
9964     EVT XType = N0.getValueType();
9965     EVT AType = N2.getValueType();
9966     if (XType.bitsGE(AType)) {
9967       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
9968       // single-bit constant.
9969       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
9970         unsigned ShCtV = N2C->getAPIntValue().logBase2();
9971         ShCtV = XType.getSizeInBits()-ShCtV-1;
9972         SDValue ShCt = DAG.getConstant(ShCtV,
9973                                        getShiftAmountTy(N0.getValueType()));
9974         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
9975                                     XType, N0, ShCt);
9976         AddToWorkList(Shift.getNode());
9977
9978         if (XType.bitsGT(AType)) {
9979           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
9980           AddToWorkList(Shift.getNode());
9981         }
9982
9983         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
9984       }
9985
9986       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
9987                                   XType, N0,
9988                                   DAG.getConstant(XType.getSizeInBits()-1,
9989                                          getShiftAmountTy(N0.getValueType())));
9990       AddToWorkList(Shift.getNode());
9991
9992       if (XType.bitsGT(AType)) {
9993         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
9994         AddToWorkList(Shift.getNode());
9995       }
9996
9997       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
9998     }
9999   }
10000
10001   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
10002   // where y is has a single bit set.
10003   // A plaintext description would be, we can turn the SELECT_CC into an AND
10004   // when the condition can be materialized as an all-ones register.  Any
10005   // single bit-test can be materialized as an all-ones register with
10006   // shift-left and shift-right-arith.
10007   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
10008       N0->getValueType(0) == VT &&
10009       N1C && N1C->isNullValue() &&
10010       N2C && N2C->isNullValue()) {
10011     SDValue AndLHS = N0->getOperand(0);
10012     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
10013     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
10014       // Shift the tested bit over the sign bit.
10015       APInt AndMask = ConstAndRHS->getAPIntValue();
10016       SDValue ShlAmt =
10017         DAG.getConstant(AndMask.countLeadingZeros(),
10018                         getShiftAmountTy(AndLHS.getValueType()));
10019       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
10020
10021       // Now arithmetic right shift it all the way over, so the result is either
10022       // all-ones, or zero.
10023       SDValue ShrAmt =
10024         DAG.getConstant(AndMask.getBitWidth()-1,
10025                         getShiftAmountTy(Shl.getValueType()));
10026       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
10027
10028       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
10029     }
10030   }
10031
10032   // fold select C, 16, 0 -> shl C, 4
10033   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
10034     TLI.getBooleanContents(N0.getValueType().isVector()) ==
10035       TargetLowering::ZeroOrOneBooleanContent) {
10036
10037     // If the caller doesn't want us to simplify this into a zext of a compare,
10038     // don't do it.
10039     if (NotExtCompare && N2C->getAPIntValue() == 1)
10040       return SDValue();
10041
10042     // Get a SetCC of the condition
10043     // NOTE: Don't create a SETCC if it's not legal on this target.
10044     if (!LegalOperations ||
10045         TLI.isOperationLegal(ISD::SETCC,
10046           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
10047       SDValue Temp, SCC;
10048       // cast from setcc result type to select result type
10049       if (LegalTypes) {
10050         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
10051                             N0, N1, CC);
10052         if (N2.getValueType().bitsLT(SCC.getValueType()))
10053           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
10054                                         N2.getValueType());
10055         else
10056           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10057                              N2.getValueType(), SCC);
10058       } else {
10059         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
10060         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10061                            N2.getValueType(), SCC);
10062       }
10063
10064       AddToWorkList(SCC.getNode());
10065       AddToWorkList(Temp.getNode());
10066
10067       if (N2C->getAPIntValue() == 1)
10068         return Temp;
10069
10070       // shl setcc result by log2 n2c
10071       return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
10072                          DAG.getConstant(N2C->getAPIntValue().logBase2(),
10073                                          getShiftAmountTy(Temp.getValueType())));
10074     }
10075   }
10076
10077   // Check to see if this is the equivalent of setcc
10078   // FIXME: Turn all of these into setcc if setcc if setcc is legal
10079   // otherwise, go ahead with the folds.
10080   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
10081     EVT XType = N0.getValueType();
10082     if (!LegalOperations ||
10083         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
10084       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
10085       if (Res.getValueType() != VT)
10086         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
10087       return Res;
10088     }
10089
10090     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
10091     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
10092         (!LegalOperations ||
10093          TLI.isOperationLegal(ISD::CTLZ, XType))) {
10094       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
10095       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
10096                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
10097                                        getShiftAmountTy(Ctlz.getValueType())));
10098     }
10099     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
10100     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
10101       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
10102                                   XType, DAG.getConstant(0, XType), N0);
10103       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
10104       return DAG.getNode(ISD::SRL, DL, XType,
10105                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
10106                          DAG.getConstant(XType.getSizeInBits()-1,
10107                                          getShiftAmountTy(XType)));
10108     }
10109     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
10110     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
10111       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
10112                                  DAG.getConstant(XType.getSizeInBits()-1,
10113                                          getShiftAmountTy(N0.getValueType())));
10114       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
10115     }
10116   }
10117
10118   // Check to see if this is an integer abs.
10119   // select_cc setg[te] X,  0,  X, -X ->
10120   // select_cc setgt    X, -1,  X, -X ->
10121   // select_cc setl[te] X,  0, -X,  X ->
10122   // select_cc setlt    X,  1, -X,  X ->
10123   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
10124   if (N1C) {
10125     ConstantSDNode *SubC = NULL;
10126     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
10127          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
10128         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
10129       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
10130     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
10131               (N1C->isOne() && CC == ISD::SETLT)) &&
10132              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
10133       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
10134
10135     EVT XType = N0.getValueType();
10136     if (SubC && SubC->isNullValue() && XType.isInteger()) {
10137       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
10138                                   N0,
10139                                   DAG.getConstant(XType.getSizeInBits()-1,
10140                                          getShiftAmountTy(N0.getValueType())));
10141       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
10142                                 XType, N0, Shift);
10143       AddToWorkList(Shift.getNode());
10144       AddToWorkList(Add.getNode());
10145       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
10146     }
10147   }
10148
10149   return SDValue();
10150 }
10151
10152 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
10153 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
10154                                    SDValue N1, ISD::CondCode Cond,
10155                                    SDLoc DL, bool foldBooleans) {
10156   TargetLowering::DAGCombinerInfo
10157     DagCombineInfo(DAG, Level, false, this);
10158   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
10159 }
10160
10161 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
10162 /// return a DAG expression to select that will generate the same value by
10163 /// multiplying by a magic number.  See:
10164 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10165 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
10166   std::vector<SDNode*> Built;
10167   SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
10168
10169   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10170        ii != ee; ++ii)
10171     AddToWorkList(*ii);
10172   return S;
10173 }
10174
10175 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
10176 /// return a DAG expression to select that will generate the same value by
10177 /// multiplying by a magic number.  See:
10178 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10179 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
10180   std::vector<SDNode*> Built;
10181   SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
10182
10183   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10184        ii != ee; ++ii)
10185     AddToWorkList(*ii);
10186   return S;
10187 }
10188
10189 /// FindBaseOffset - Return true if base is a frame index, which is known not
10190 // to alias with anything but itself.  Provides base object and offset as
10191 // results.
10192 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
10193                            const GlobalValue *&GV, const void *&CV) {
10194   // Assume it is a primitive operation.
10195   Base = Ptr; Offset = 0; GV = 0; CV = 0;
10196
10197   // If it's an adding a simple constant then integrate the offset.
10198   if (Base.getOpcode() == ISD::ADD) {
10199     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
10200       Base = Base.getOperand(0);
10201       Offset += C->getZExtValue();
10202     }
10203   }
10204
10205   // Return the underlying GlobalValue, and update the Offset.  Return false
10206   // for GlobalAddressSDNode since the same GlobalAddress may be represented
10207   // by multiple nodes with different offsets.
10208   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
10209     GV = G->getGlobal();
10210     Offset += G->getOffset();
10211     return false;
10212   }
10213
10214   // Return the underlying Constant value, and update the Offset.  Return false
10215   // for ConstantSDNodes since the same constant pool entry may be represented
10216   // by multiple nodes with different offsets.
10217   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
10218     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
10219                                          : (const void *)C->getConstVal();
10220     Offset += C->getOffset();
10221     return false;
10222   }
10223   // If it's any of the following then it can't alias with anything but itself.
10224   return isa<FrameIndexSDNode>(Base);
10225 }
10226
10227 /// isAlias - Return true if there is any possibility that the two addresses
10228 /// overlap.
10229 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
10230                           const Value *SrcValue1, int SrcValueOffset1,
10231                           unsigned SrcValueAlign1,
10232                           const MDNode *TBAAInfo1,
10233                           SDValue Ptr2, int64_t Size2,
10234                           const Value *SrcValue2, int SrcValueOffset2,
10235                           unsigned SrcValueAlign2,
10236                           const MDNode *TBAAInfo2) const {
10237   // If they are the same then they must be aliases.
10238   if (Ptr1 == Ptr2) return true;
10239
10240   // Gather base node and offset information.
10241   SDValue Base1, Base2;
10242   int64_t Offset1, Offset2;
10243   const GlobalValue *GV1, *GV2;
10244   const void *CV1, *CV2;
10245   bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
10246   bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
10247
10248   // If they have a same base address then check to see if they overlap.
10249   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
10250     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
10251
10252   // It is possible for different frame indices to alias each other, mostly
10253   // when tail call optimization reuses return address slots for arguments.
10254   // To catch this case, look up the actual index of frame indices to compute
10255   // the real alias relationship.
10256   if (isFrameIndex1 && isFrameIndex2) {
10257     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10258     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
10259     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
10260     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
10261   }
10262
10263   // Otherwise, if we know what the bases are, and they aren't identical, then
10264   // we know they cannot alias.
10265   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
10266     return false;
10267
10268   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
10269   // compared to the size and offset of the access, we may be able to prove they
10270   // do not alias.  This check is conservative for now to catch cases created by
10271   // splitting vector types.
10272   if ((SrcValueAlign1 == SrcValueAlign2) &&
10273       (SrcValueOffset1 != SrcValueOffset2) &&
10274       (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
10275     int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
10276     int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
10277
10278     // There is no overlap between these relatively aligned accesses of similar
10279     // size, return no alias.
10280     if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
10281       return false;
10282   }
10283
10284   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
10285     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
10286   if (UseAA && SrcValue1 && SrcValue2) {
10287     // Use alias analysis information.
10288     int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
10289     int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
10290     int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
10291     AliasAnalysis::AliasResult AAResult =
10292       AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
10293                AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
10294     if (AAResult == AliasAnalysis::NoAlias)
10295       return false;
10296   }
10297
10298   // Otherwise we have to assume they alias.
10299   return true;
10300 }
10301
10302 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
10303   SDValue Ptr0, Ptr1;
10304   int64_t Size0, Size1;
10305   const Value *SrcValue0, *SrcValue1;
10306   int SrcValueOffset0, SrcValueOffset1;
10307   unsigned SrcValueAlign0, SrcValueAlign1;
10308   const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
10309   FindAliasInfo(Op0, Ptr0, Size0, SrcValue0, SrcValueOffset0,
10310                 SrcValueAlign0, SrcTBAAInfo0);
10311   FindAliasInfo(Op1, Ptr1, Size1, SrcValue1, SrcValueOffset1,
10312                 SrcValueAlign1, SrcTBAAInfo1);
10313   return isAlias(Ptr0, Size0, SrcValue0, SrcValueOffset0,
10314                  SrcValueAlign0, SrcTBAAInfo0,
10315                  Ptr1, Size1, SrcValue1, SrcValueOffset1,
10316                  SrcValueAlign1, SrcTBAAInfo1);
10317 }
10318
10319 /// FindAliasInfo - Extracts the relevant alias information from the memory
10320 /// node.  Returns true if the operand was a load.
10321 bool DAGCombiner::FindAliasInfo(SDNode *N,
10322                                 SDValue &Ptr, int64_t &Size,
10323                                 const Value *&SrcValue,
10324                                 int &SrcValueOffset,
10325                                 unsigned &SrcValueAlign,
10326                                 const MDNode *&TBAAInfo) const {
10327   LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
10328
10329   Ptr = LS->getBasePtr();
10330   Size = LS->getMemoryVT().getSizeInBits() >> 3;
10331   SrcValue = LS->getSrcValue();
10332   SrcValueOffset = LS->getSrcValueOffset();
10333   SrcValueAlign = LS->getOriginalAlignment();
10334   TBAAInfo = LS->getTBAAInfo();
10335   return isa<LoadSDNode>(LS);
10336 }
10337
10338 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
10339 /// looking for aliasing nodes and adding them to the Aliases vector.
10340 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
10341                                    SmallVectorImpl<SDValue> &Aliases) {
10342   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
10343   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
10344
10345   // Get alias information for node.
10346   SDValue Ptr;
10347   int64_t Size;
10348   const Value *SrcValue;
10349   int SrcValueOffset;
10350   unsigned SrcValueAlign;
10351   const MDNode *SrcTBAAInfo;
10352   bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset,
10353                               SrcValueAlign, SrcTBAAInfo);
10354
10355   // Starting off.
10356   Chains.push_back(OriginalChain);
10357   unsigned Depth = 0;
10358
10359   // Look at each chain and determine if it is an alias.  If so, add it to the
10360   // aliases list.  If not, then continue up the chain looking for the next
10361   // candidate.
10362   while (!Chains.empty()) {
10363     SDValue Chain = Chains.back();
10364     Chains.pop_back();
10365
10366     // For TokenFactor nodes, look at each operand and only continue up the
10367     // chain until we find two aliases.  If we've seen two aliases, assume we'll
10368     // find more and revert to original chain since the xform is unlikely to be
10369     // profitable.
10370     //
10371     // FIXME: The depth check could be made to return the last non-aliasing
10372     // chain we found before we hit a tokenfactor rather than the original
10373     // chain.
10374     if (Depth > 6 || Aliases.size() == 2) {
10375       Aliases.clear();
10376       Aliases.push_back(OriginalChain);
10377       break;
10378     }
10379
10380     // Don't bother if we've been before.
10381     if (!Visited.insert(Chain.getNode()))
10382       continue;
10383
10384     switch (Chain.getOpcode()) {
10385     case ISD::EntryToken:
10386       // Entry token is ideal chain operand, but handled in FindBetterChain.
10387       break;
10388
10389     case ISD::LOAD:
10390     case ISD::STORE: {
10391       // Get alias information for Chain.
10392       SDValue OpPtr;
10393       int64_t OpSize;
10394       const Value *OpSrcValue;
10395       int OpSrcValueOffset;
10396       unsigned OpSrcValueAlign;
10397       const MDNode *OpSrcTBAAInfo;
10398       bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
10399                                     OpSrcValue, OpSrcValueOffset,
10400                                     OpSrcValueAlign,
10401                                     OpSrcTBAAInfo);
10402
10403       // If chain is alias then stop here.
10404       if (!(IsLoad && IsOpLoad) &&
10405           isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign,
10406                   SrcTBAAInfo,
10407                   OpPtr, OpSize, OpSrcValue, OpSrcValueOffset,
10408                   OpSrcValueAlign, OpSrcTBAAInfo)) {
10409         Aliases.push_back(Chain);
10410       } else {
10411         // Look further up the chain.
10412         Chains.push_back(Chain.getOperand(0));
10413         ++Depth;
10414       }
10415       break;
10416     }
10417
10418     case ISD::TokenFactor:
10419       // We have to check each of the operands of the token factor for "small"
10420       // token factors, so we queue them up.  Adding the operands to the queue
10421       // (stack) in reverse order maintains the original order and increases the
10422       // likelihood that getNode will find a matching token factor (CSE.)
10423       if (Chain.getNumOperands() > 16) {
10424         Aliases.push_back(Chain);
10425         break;
10426       }
10427       for (unsigned n = Chain.getNumOperands(); n;)
10428         Chains.push_back(Chain.getOperand(--n));
10429       ++Depth;
10430       break;
10431
10432     default:
10433       // For all other instructions we will just have to take what we can get.
10434       Aliases.push_back(Chain);
10435       break;
10436     }
10437   }
10438 }
10439
10440 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
10441 /// for a better chain (aliasing node.)
10442 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
10443   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
10444
10445   // Accumulate all the aliases to this node.
10446   GatherAllAliases(N, OldChain, Aliases);
10447
10448   // If no operands then chain to entry token.
10449   if (Aliases.size() == 0)
10450     return DAG.getEntryNode();
10451
10452   // If a single operand then chain to it.  We don't need to revisit it.
10453   if (Aliases.size() == 1)
10454     return Aliases[0];
10455
10456   // Construct a custom tailored token factor.
10457   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
10458                      &Aliases[0], Aliases.size());
10459 }
10460
10461 // SelectionDAG::Combine - This is the entry point for the file.
10462 //
10463 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
10464                            CodeGenOpt::Level OptLevel) {
10465   /// run - This is the main entry point to this class.
10466   ///
10467   DAGCombiner(*this, AA, OptLevel).Run(Level);
10468 }