SLPVectorizer: add a second limit for the number of alias checks.
[oota-llvm.git] / lib / Transforms / Vectorize / SLPVectorizer.cpp
1 //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
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 // This pass implements the Bottom Up SLP vectorizer. It detects consecutive
10 // stores that can be put together into vector-stores. Next, it attempts to
11 // construct vectorizable tree using the use-def chains. If a profitable tree
12 // was found, the SLP vectorizer performs vectorization on the tree.
13 //
14 // The pass is inspired by the work described in the paper:
15 //  "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks.
16 //
17 //===----------------------------------------------------------------------===//
18 #include "llvm/Transforms/Vectorize.h"
19 #include "llvm/ADT/MapVector.h"
20 #include "llvm/ADT/PostOrderIterator.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/Analysis/AssumptionCache.h"
26 #include "llvm/Analysis/CodeMetrics.h"
27 #include "llvm/Analysis/LoopInfo.h"
28 #include "llvm/Analysis/ScalarEvolution.h"
29 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
30 #include "llvm/Analysis/TargetTransformInfo.h"
31 #include "llvm/Analysis/ValueTracking.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/Dominators.h"
34 #include "llvm/IR/IRBuilder.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/IntrinsicInst.h"
37 #include "llvm/IR/Module.h"
38 #include "llvm/IR/NoFolder.h"
39 #include "llvm/IR/Type.h"
40 #include "llvm/IR/Value.h"
41 #include "llvm/IR/Verifier.h"
42 #include "llvm/Pass.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/raw_ostream.h"
46 #include "llvm/Transforms/Utils/VectorUtils.h"
47 #include <algorithm>
48 #include <map>
49 #include <memory>
50
51 using namespace llvm;
52
53 #define SV_NAME "slp-vectorizer"
54 #define DEBUG_TYPE "SLP"
55
56 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
57
58 static cl::opt<int>
59     SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
60                      cl::desc("Only vectorize if you gain more than this "
61                               "number "));
62
63 static cl::opt<bool>
64 ShouldVectorizeHor("slp-vectorize-hor", cl::init(false), cl::Hidden,
65                    cl::desc("Attempt to vectorize horizontal reductions"));
66
67 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
68     "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
69     cl::desc(
70         "Attempt to vectorize horizontal reductions feeding into a store"));
71
72 namespace {
73
74 static const unsigned MinVecRegSize = 128;
75
76 static const unsigned RecursionMaxDepth = 12;
77
78 // Limit the number of alias checks. The limit is chosen so that
79 // it has no negative effect on the llvm benchmarks.
80 static const unsigned AliasedCheckLimit = 10;
81
82 // Another limit for the alias checks: The maximum distance between load/store
83 // instructions where alias checks are done.
84 // This limit is useful for very large basic blocks.
85 static const int MaxMemDepDistance = 160;
86
87 /// \returns the parent basic block if all of the instructions in \p VL
88 /// are in the same block or null otherwise.
89 static BasicBlock *getSameBlock(ArrayRef<Value *> VL) {
90   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
91   if (!I0)
92     return nullptr;
93   BasicBlock *BB = I0->getParent();
94   for (int i = 1, e = VL.size(); i < e; i++) {
95     Instruction *I = dyn_cast<Instruction>(VL[i]);
96     if (!I)
97       return nullptr;
98
99     if (BB != I->getParent())
100       return nullptr;
101   }
102   return BB;
103 }
104
105 /// \returns True if all of the values in \p VL are constants.
106 static bool allConstant(ArrayRef<Value *> VL) {
107   for (unsigned i = 0, e = VL.size(); i < e; ++i)
108     if (!isa<Constant>(VL[i]))
109       return false;
110   return true;
111 }
112
113 /// \returns True if all of the values in \p VL are identical.
114 static bool isSplat(ArrayRef<Value *> VL) {
115   for (unsigned i = 1, e = VL.size(); i < e; ++i)
116     if (VL[i] != VL[0])
117       return false;
118   return true;
119 }
120
121 ///\returns Opcode that can be clubbed with \p Op to create an alternate
122 /// sequence which can later be merged as a ShuffleVector instruction.
123 static unsigned getAltOpcode(unsigned Op) {
124   switch (Op) {
125   case Instruction::FAdd:
126     return Instruction::FSub;
127   case Instruction::FSub:
128     return Instruction::FAdd;
129   case Instruction::Add:
130     return Instruction::Sub;
131   case Instruction::Sub:
132     return Instruction::Add;
133   default:
134     return 0;
135   }
136 }
137
138 ///\returns bool representing if Opcode \p Op can be part
139 /// of an alternate sequence which can later be merged as
140 /// a ShuffleVector instruction.
141 static bool canCombineAsAltInst(unsigned Op) {
142   if (Op == Instruction::FAdd || Op == Instruction::FSub ||
143       Op == Instruction::Sub || Op == Instruction::Add)
144     return true;
145   return false;
146 }
147
148 /// \returns ShuffleVector instruction if intructions in \p VL have
149 ///  alternate fadd,fsub / fsub,fadd/add,sub/sub,add sequence.
150 /// (i.e. e.g. opcodes of fadd,fsub,fadd,fsub...)
151 static unsigned isAltInst(ArrayRef<Value *> VL) {
152   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
153   unsigned Opcode = I0->getOpcode();
154   unsigned AltOpcode = getAltOpcode(Opcode);
155   for (int i = 1, e = VL.size(); i < e; i++) {
156     Instruction *I = dyn_cast<Instruction>(VL[i]);
157     if (!I || I->getOpcode() != ((i & 1) ? AltOpcode : Opcode))
158       return 0;
159   }
160   return Instruction::ShuffleVector;
161 }
162
163 /// \returns The opcode if all of the Instructions in \p VL have the same
164 /// opcode, or zero.
165 static unsigned getSameOpcode(ArrayRef<Value *> VL) {
166   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
167   if (!I0)
168     return 0;
169   unsigned Opcode = I0->getOpcode();
170   for (int i = 1, e = VL.size(); i < e; i++) {
171     Instruction *I = dyn_cast<Instruction>(VL[i]);
172     if (!I || Opcode != I->getOpcode()) {
173       if (canCombineAsAltInst(Opcode) && i == 1)
174         return isAltInst(VL);
175       return 0;
176     }
177   }
178   return Opcode;
179 }
180
181 /// Get the intersection (logical and) of all of the potential IR flags
182 /// of each scalar operation (VL) that will be converted into a vector (I).
183 /// Flag set: NSW, NUW, exact, and all of fast-math.
184 static void propagateIRFlags(Value *I, ArrayRef<Value *> VL) {
185   if (auto *VecOp = dyn_cast<BinaryOperator>(I)) {
186     if (auto *Intersection = dyn_cast<BinaryOperator>(VL[0])) {
187       // Intersection is initialized to the 0th scalar,
188       // so start counting from index '1'.
189       for (int i = 1, e = VL.size(); i < e; ++i) {
190         if (auto *Scalar = dyn_cast<BinaryOperator>(VL[i]))
191           Intersection->andIRFlags(Scalar);
192       }
193       VecOp->copyIRFlags(Intersection);
194     }
195   }
196 }
197   
198 /// \returns \p I after propagating metadata from \p VL.
199 static Instruction *propagateMetadata(Instruction *I, ArrayRef<Value *> VL) {
200   Instruction *I0 = cast<Instruction>(VL[0]);
201   SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
202   I0->getAllMetadataOtherThanDebugLoc(Metadata);
203
204   for (unsigned i = 0, n = Metadata.size(); i != n; ++i) {
205     unsigned Kind = Metadata[i].first;
206     MDNode *MD = Metadata[i].second;
207
208     for (int i = 1, e = VL.size(); MD && i != e; i++) {
209       Instruction *I = cast<Instruction>(VL[i]);
210       MDNode *IMD = I->getMetadata(Kind);
211
212       switch (Kind) {
213       default:
214         MD = nullptr; // Remove unknown metadata
215         break;
216       case LLVMContext::MD_tbaa:
217         MD = MDNode::getMostGenericTBAA(MD, IMD);
218         break;
219       case LLVMContext::MD_alias_scope:
220       case LLVMContext::MD_noalias:
221         MD = MDNode::intersect(MD, IMD);
222         break;
223       case LLVMContext::MD_fpmath:
224         MD = MDNode::getMostGenericFPMath(MD, IMD);
225         break;
226       }
227     }
228     I->setMetadata(Kind, MD);
229   }
230   return I;
231 }
232
233 /// \returns The type that all of the values in \p VL have or null if there
234 /// are different types.
235 static Type* getSameType(ArrayRef<Value *> VL) {
236   Type *Ty = VL[0]->getType();
237   for (int i = 1, e = VL.size(); i < e; i++)
238     if (VL[i]->getType() != Ty)
239       return nullptr;
240
241   return Ty;
242 }
243
244 /// \returns True if the ExtractElement instructions in VL can be vectorized
245 /// to use the original vector.
246 static bool CanReuseExtract(ArrayRef<Value *> VL) {
247   assert(Instruction::ExtractElement == getSameOpcode(VL) && "Invalid opcode");
248   // Check if all of the extracts come from the same vector and from the
249   // correct offset.
250   Value *VL0 = VL[0];
251   ExtractElementInst *E0 = cast<ExtractElementInst>(VL0);
252   Value *Vec = E0->getOperand(0);
253
254   // We have to extract from the same vector type.
255   unsigned NElts = Vec->getType()->getVectorNumElements();
256
257   if (NElts != VL.size())
258     return false;
259
260   // Check that all of the indices extract from the correct offset.
261   ConstantInt *CI = dyn_cast<ConstantInt>(E0->getOperand(1));
262   if (!CI || CI->getZExtValue())
263     return false;
264
265   for (unsigned i = 1, e = VL.size(); i < e; ++i) {
266     ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
267     ConstantInt *CI = dyn_cast<ConstantInt>(E->getOperand(1));
268
269     if (!CI || CI->getZExtValue() != i || E->getOperand(0) != Vec)
270       return false;
271   }
272
273   return true;
274 }
275
276 /// \returns True if in-tree use also needs extract. This refers to
277 /// possible scalar operand in vectorized instruction.
278 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
279                                     TargetLibraryInfo *TLI) {
280
281   unsigned Opcode = UserInst->getOpcode();
282   switch (Opcode) {
283   case Instruction::Load: {
284     LoadInst *LI = cast<LoadInst>(UserInst);
285     return (LI->getPointerOperand() == Scalar);
286   }
287   case Instruction::Store: {
288     StoreInst *SI = cast<StoreInst>(UserInst);
289     return (SI->getPointerOperand() == Scalar);
290   }
291   case Instruction::Call: {
292     CallInst *CI = cast<CallInst>(UserInst);
293     Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
294     if (hasVectorInstrinsicScalarOpd(ID, 1)) {
295       return (CI->getArgOperand(1) == Scalar);
296     }
297   }
298   default:
299     return false;
300   }
301 }
302
303 /// \returns the AA location that is being access by the instruction.
304 static AliasAnalysis::Location getLocation(Instruction *I, AliasAnalysis *AA) {
305   if (StoreInst *SI = dyn_cast<StoreInst>(I))
306     return AA->getLocation(SI);
307   if (LoadInst *LI = dyn_cast<LoadInst>(I))
308     return AA->getLocation(LI);
309   return AliasAnalysis::Location();
310 }
311
312 /// Bottom Up SLP Vectorizer.
313 class BoUpSLP {
314 public:
315   typedef SmallVector<Value *, 8> ValueList;
316   typedef SmallVector<Instruction *, 16> InstrList;
317   typedef SmallPtrSet<Value *, 16> ValueSet;
318   typedef SmallVector<StoreInst *, 8> StoreList;
319
320   BoUpSLP(Function *Func, ScalarEvolution *Se, const DataLayout *Dl,
321           TargetTransformInfo *Tti, TargetLibraryInfo *TLi, AliasAnalysis *Aa,
322           LoopInfo *Li, DominatorTree *Dt, AssumptionCache *AC)
323       : NumLoadsWantToKeepOrder(0), NumLoadsWantToChangeOrder(0), F(Func),
324         SE(Se), DL(Dl), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt),
325         Builder(Se->getContext()) {
326     CodeMetrics::collectEphemeralValues(F, AC, EphValues);
327   }
328
329   /// \brief Vectorize the tree that starts with the elements in \p VL.
330   /// Returns the vectorized root.
331   Value *vectorizeTree();
332
333   /// \returns the cost incurred by unwanted spills and fills, caused by
334   /// holding live values over call sites.
335   int getSpillCost();
336
337   /// \returns the vectorization cost of the subtree that starts at \p VL.
338   /// A negative number means that this is profitable.
339   int getTreeCost();
340
341   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
342   /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
343   void buildTree(ArrayRef<Value *> Roots,
344                  ArrayRef<Value *> UserIgnoreLst = None);
345
346   /// Clear the internal data structures that are created by 'buildTree'.
347   void deleteTree() {
348     VectorizableTree.clear();
349     ScalarToTreeEntry.clear();
350     MustGather.clear();
351     ExternalUses.clear();
352     NumLoadsWantToKeepOrder = 0;
353     NumLoadsWantToChangeOrder = 0;
354     for (auto &Iter : BlocksSchedules) {
355       BlockScheduling *BS = Iter.second.get();
356       BS->clear();
357     }
358   }
359
360   /// \returns true if the memory operations A and B are consecutive.
361   bool isConsecutiveAccess(Value *A, Value *B);
362
363   /// \brief Perform LICM and CSE on the newly generated gather sequences.
364   void optimizeGatherSequence();
365
366   /// \returns true if it is benefitial to reverse the vector order.
367   bool shouldReorder() const {
368     return NumLoadsWantToChangeOrder > NumLoadsWantToKeepOrder;
369   }
370
371 private:
372   struct TreeEntry;
373
374   /// \returns the cost of the vectorizable entry.
375   int getEntryCost(TreeEntry *E);
376
377   /// This is the recursive part of buildTree.
378   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth);
379
380   /// Vectorize a single entry in the tree.
381   Value *vectorizeTree(TreeEntry *E);
382
383   /// Vectorize a single entry in the tree, starting in \p VL.
384   Value *vectorizeTree(ArrayRef<Value *> VL);
385
386   /// \returns the pointer to the vectorized value if \p VL is already
387   /// vectorized, or NULL. They may happen in cycles.
388   Value *alreadyVectorized(ArrayRef<Value *> VL) const;
389
390   /// \brief Take the pointer operand from the Load/Store instruction.
391   /// \returns NULL if this is not a valid Load/Store instruction.
392   static Value *getPointerOperand(Value *I);
393
394   /// \brief Take the address space operand from the Load/Store instruction.
395   /// \returns -1 if this is not a valid Load/Store instruction.
396   static unsigned getAddressSpaceOperand(Value *I);
397
398   /// \returns the scalarization cost for this type. Scalarization in this
399   /// context means the creation of vectors from a group of scalars.
400   int getGatherCost(Type *Ty);
401
402   /// \returns the scalarization cost for this list of values. Assuming that
403   /// this subtree gets vectorized, we may need to extract the values from the
404   /// roots. This method calculates the cost of extracting the values.
405   int getGatherCost(ArrayRef<Value *> VL);
406
407   /// \brief Set the Builder insert point to one after the last instruction in
408   /// the bundle
409   void setInsertPointAfterBundle(ArrayRef<Value *> VL);
410
411   /// \returns a vector from a collection of scalars in \p VL.
412   Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
413
414   /// \returns whether the VectorizableTree is fully vectoriable and will
415   /// be beneficial even the tree height is tiny.
416   bool isFullyVectorizableTinyTree();
417
418   /// \reorder commutative operands in alt shuffle if they result in
419   ///  vectorized code.
420   void reorderAltShuffleOperands(ArrayRef<Value *> VL,
421                                  SmallVectorImpl<Value *> &Left,
422                                  SmallVectorImpl<Value *> &Right);
423   /// \reorder commutative operands to get better probability of
424   /// generating vectorized code.
425   void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
426                                       SmallVectorImpl<Value *> &Left,
427                                       SmallVectorImpl<Value *> &Right);
428   struct TreeEntry {
429     TreeEntry() : Scalars(), VectorizedValue(nullptr),
430     NeedToGather(0) {}
431
432     /// \returns true if the scalars in VL are equal to this entry.
433     bool isSame(ArrayRef<Value *> VL) const {
434       assert(VL.size() == Scalars.size() && "Invalid size");
435       return std::equal(VL.begin(), VL.end(), Scalars.begin());
436     }
437
438     /// A vector of scalars.
439     ValueList Scalars;
440
441     /// The Scalars are vectorized into this value. It is initialized to Null.
442     Value *VectorizedValue;
443
444     /// Do we need to gather this sequence ?
445     bool NeedToGather;
446   };
447
448   /// Create a new VectorizableTree entry.
449   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, bool Vectorized) {
450     VectorizableTree.push_back(TreeEntry());
451     int idx = VectorizableTree.size() - 1;
452     TreeEntry *Last = &VectorizableTree[idx];
453     Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
454     Last->NeedToGather = !Vectorized;
455     if (Vectorized) {
456       for (int i = 0, e = VL.size(); i != e; ++i) {
457         assert(!ScalarToTreeEntry.count(VL[i]) && "Scalar already in tree!");
458         ScalarToTreeEntry[VL[i]] = idx;
459       }
460     } else {
461       MustGather.insert(VL.begin(), VL.end());
462     }
463     return Last;
464   }
465   
466   /// -- Vectorization State --
467   /// Holds all of the tree entries.
468   std::vector<TreeEntry> VectorizableTree;
469
470   /// Maps a specific scalar to its tree entry.
471   SmallDenseMap<Value*, int> ScalarToTreeEntry;
472
473   /// A list of scalars that we found that we need to keep as scalars.
474   ValueSet MustGather;
475
476   /// This POD struct describes one external user in the vectorized tree.
477   struct ExternalUser {
478     ExternalUser (Value *S, llvm::User *U, int L) :
479       Scalar(S), User(U), Lane(L){};
480     // Which scalar in our function.
481     Value *Scalar;
482     // Which user that uses the scalar.
483     llvm::User *User;
484     // Which lane does the scalar belong to.
485     int Lane;
486   };
487   typedef SmallVector<ExternalUser, 16> UserList;
488
489   /// Checks if two instructions may access the same memory.
490   ///
491   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
492   /// is invariant in the calling loop.
493   bool isAliased(const AliasAnalysis::Location &Loc1, Instruction *Inst1,
494                  Instruction *Inst2) {
495
496     // First check if the result is already in the cache.
497     AliasCacheKey key = std::make_pair(Inst1, Inst2);
498     Optional<bool> &result = AliasCache[key];
499     if (result.hasValue()) {
500       return result.getValue();
501     }
502     AliasAnalysis::Location Loc2 = getLocation(Inst2, AA);
503     bool aliased = true;
504     if (Loc1.Ptr && Loc2.Ptr) {
505       // Do the alias check.
506       aliased = AA->alias(Loc1, Loc2);
507     }
508     // Store the result in the cache.
509     result = aliased;
510     return aliased;
511   }
512
513   typedef std::pair<Instruction *, Instruction *> AliasCacheKey;
514
515   /// Cache for alias results.
516   /// TODO: consider moving this to the AliasAnalysis itself.
517   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
518
519   /// Removes an instruction from its block and eventually deletes it.
520   /// It's like Instruction::eraseFromParent() except that the actual deletion
521   /// is delayed until BoUpSLP is destructed.
522   /// This is required to ensure that there are no incorrect collisions in the
523   /// AliasCache, which can happen if a new instruction is allocated at the
524   /// same address as a previously deleted instruction.
525   void eraseInstruction(Instruction *I) {
526     I->removeFromParent();
527     I->dropAllReferences();
528     DeletedInstructions.push_back(std::unique_ptr<Instruction>(I));
529   }
530
531   /// Temporary store for deleted instructions. Instructions will be deleted
532   /// eventually when the BoUpSLP is destructed.
533   SmallVector<std::unique_ptr<Instruction>, 8> DeletedInstructions;
534
535   /// A list of values that need to extracted out of the tree.
536   /// This list holds pairs of (Internal Scalar : External User).
537   UserList ExternalUses;
538
539   /// Values used only by @llvm.assume calls.
540   SmallPtrSet<const Value *, 32> EphValues;
541
542   /// Holds all of the instructions that we gathered.
543   SetVector<Instruction *> GatherSeq;
544   /// A list of blocks that we are going to CSE.
545   SetVector<BasicBlock *> CSEBlocks;
546
547   /// Contains all scheduling relevant data for an instruction.
548   /// A ScheduleData either represents a single instruction or a member of an
549   /// instruction bundle (= a group of instructions which is combined into a
550   /// vector instruction).
551   struct ScheduleData {
552
553     // The initial value for the dependency counters. It means that the
554     // dependencies are not calculated yet.
555     enum { InvalidDeps = -1 };
556
557     ScheduleData()
558         : Inst(nullptr), FirstInBundle(nullptr), NextInBundle(nullptr),
559           NextLoadStore(nullptr), SchedulingRegionID(0), SchedulingPriority(0),
560           Dependencies(InvalidDeps), UnscheduledDeps(InvalidDeps),
561           UnscheduledDepsInBundle(InvalidDeps), IsScheduled(false) {}
562
563     void init(int BlockSchedulingRegionID) {
564       FirstInBundle = this;
565       NextInBundle = nullptr;
566       NextLoadStore = nullptr;
567       IsScheduled = false;
568       SchedulingRegionID = BlockSchedulingRegionID;
569       UnscheduledDepsInBundle = UnscheduledDeps;
570       clearDependencies();
571     }
572
573     /// Returns true if the dependency information has been calculated.
574     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
575
576     /// Returns true for single instructions and for bundle representatives
577     /// (= the head of a bundle).
578     bool isSchedulingEntity() const { return FirstInBundle == this; }
579
580     /// Returns true if it represents an instruction bundle and not only a
581     /// single instruction.
582     bool isPartOfBundle() const {
583       return NextInBundle != nullptr || FirstInBundle != this;
584     }
585
586     /// Returns true if it is ready for scheduling, i.e. it has no more
587     /// unscheduled depending instructions/bundles.
588     bool isReady() const {
589       assert(isSchedulingEntity() &&
590              "can't consider non-scheduling entity for ready list");
591       return UnscheduledDepsInBundle == 0 && !IsScheduled;
592     }
593
594     /// Modifies the number of unscheduled dependencies, also updating it for
595     /// the whole bundle.
596     int incrementUnscheduledDeps(int Incr) {
597       UnscheduledDeps += Incr;
598       return FirstInBundle->UnscheduledDepsInBundle += Incr;
599     }
600
601     /// Sets the number of unscheduled dependencies to the number of
602     /// dependencies.
603     void resetUnscheduledDeps() {
604       incrementUnscheduledDeps(Dependencies - UnscheduledDeps);
605     }
606
607     /// Clears all dependency information.
608     void clearDependencies() {
609       Dependencies = InvalidDeps;
610       resetUnscheduledDeps();
611       MemoryDependencies.clear();
612     }
613
614     void dump(raw_ostream &os) const {
615       if (!isSchedulingEntity()) {
616         os << "/ " << *Inst;
617       } else if (NextInBundle) {
618         os << '[' << *Inst;
619         ScheduleData *SD = NextInBundle;
620         while (SD) {
621           os << ';' << *SD->Inst;
622           SD = SD->NextInBundle;
623         }
624         os << ']';
625       } else {
626         os << *Inst;
627       }
628     }
629
630     Instruction *Inst;
631
632     /// Points to the head in an instruction bundle (and always to this for
633     /// single instructions).
634     ScheduleData *FirstInBundle;
635
636     /// Single linked list of all instructions in a bundle. Null if it is a
637     /// single instruction.
638     ScheduleData *NextInBundle;
639
640     /// Single linked list of all memory instructions (e.g. load, store, call)
641     /// in the block - until the end of the scheduling region.
642     ScheduleData *NextLoadStore;
643
644     /// The dependent memory instructions.
645     /// This list is derived on demand in calculateDependencies().
646     SmallVector<ScheduleData *, 4> MemoryDependencies;
647
648     /// This ScheduleData is in the current scheduling region if this matches
649     /// the current SchedulingRegionID of BlockScheduling.
650     int SchedulingRegionID;
651
652     /// Used for getting a "good" final ordering of instructions.
653     int SchedulingPriority;
654
655     /// The number of dependencies. Constitutes of the number of users of the
656     /// instruction plus the number of dependent memory instructions (if any).
657     /// This value is calculated on demand.
658     /// If InvalidDeps, the number of dependencies is not calculated yet.
659     ///
660     int Dependencies;
661
662     /// The number of dependencies minus the number of dependencies of scheduled
663     /// instructions. As soon as this is zero, the instruction/bundle gets ready
664     /// for scheduling.
665     /// Note that this is negative as long as Dependencies is not calculated.
666     int UnscheduledDeps;
667
668     /// The sum of UnscheduledDeps in a bundle. Equals to UnscheduledDeps for
669     /// single instructions.
670     int UnscheduledDepsInBundle;
671
672     /// True if this instruction is scheduled (or considered as scheduled in the
673     /// dry-run).
674     bool IsScheduled;
675   };
676
677 #ifndef NDEBUG
678   friend raw_ostream &operator<<(raw_ostream &os,
679                                  const BoUpSLP::ScheduleData &SD);
680 #endif
681
682   /// Contains all scheduling data for a basic block.
683   ///
684   struct BlockScheduling {
685
686     BlockScheduling(BasicBlock *BB)
687         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize),
688           ScheduleStart(nullptr), ScheduleEnd(nullptr),
689           FirstLoadStoreInRegion(nullptr), LastLoadStoreInRegion(nullptr),
690           // Make sure that the initial SchedulingRegionID is greater than the
691           // initial SchedulingRegionID in ScheduleData (which is 0).
692           SchedulingRegionID(1) {}
693
694     void clear() {
695       ReadyInsts.clear();
696       ScheduleStart = nullptr;
697       ScheduleEnd = nullptr;
698       FirstLoadStoreInRegion = nullptr;
699       LastLoadStoreInRegion = nullptr;
700
701       // Make a new scheduling region, i.e. all existing ScheduleData is not
702       // in the new region yet.
703       ++SchedulingRegionID;
704     }
705
706     ScheduleData *getScheduleData(Value *V) {
707       ScheduleData *SD = ScheduleDataMap[V];
708       if (SD && SD->SchedulingRegionID == SchedulingRegionID)
709         return SD;
710       return nullptr;
711     }
712
713     bool isInSchedulingRegion(ScheduleData *SD) {
714       return SD->SchedulingRegionID == SchedulingRegionID;
715     }
716
717     /// Marks an instruction as scheduled and puts all dependent ready
718     /// instructions into the ready-list.
719     template <typename ReadyListType>
720     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
721       SD->IsScheduled = true;
722       DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
723
724       ScheduleData *BundleMember = SD;
725       while (BundleMember) {
726         // Handle the def-use chain dependencies.
727         for (Use &U : BundleMember->Inst->operands()) {
728           ScheduleData *OpDef = getScheduleData(U.get());
729           if (OpDef && OpDef->hasValidDependencies() &&
730               OpDef->incrementUnscheduledDeps(-1) == 0) {
731             // There are no more unscheduled dependencies after decrementing,
732             // so we can put the dependent instruction into the ready list.
733             ScheduleData *DepBundle = OpDef->FirstInBundle;
734             assert(!DepBundle->IsScheduled &&
735                    "already scheduled bundle gets ready");
736             ReadyList.insert(DepBundle);
737             DEBUG(dbgs() << "SLP:    gets ready (def): " << *DepBundle << "\n");
738           }
739         }
740         // Handle the memory dependencies.
741         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
742           if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
743             // There are no more unscheduled dependencies after decrementing,
744             // so we can put the dependent instruction into the ready list.
745             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
746             assert(!DepBundle->IsScheduled &&
747                    "already scheduled bundle gets ready");
748             ReadyList.insert(DepBundle);
749             DEBUG(dbgs() << "SLP:    gets ready (mem): " << *DepBundle << "\n");
750           }
751         }
752         BundleMember = BundleMember->NextInBundle;
753       }
754     }
755
756     /// Put all instructions into the ReadyList which are ready for scheduling.
757     template <typename ReadyListType>
758     void initialFillReadyList(ReadyListType &ReadyList) {
759       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
760         ScheduleData *SD = getScheduleData(I);
761         if (SD->isSchedulingEntity() && SD->isReady()) {
762           ReadyList.insert(SD);
763           DEBUG(dbgs() << "SLP:    initially in ready list: " << *I << "\n");
764         }
765       }
766     }
767
768     /// Checks if a bundle of instructions can be scheduled, i.e. has no
769     /// cyclic dependencies. This is only a dry-run, no instructions are
770     /// actually moved at this stage.
771     bool tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP);
772
773     /// Un-bundles a group of instructions.
774     void cancelScheduling(ArrayRef<Value *> VL);
775
776     /// Extends the scheduling region so that V is inside the region.
777     void extendSchedulingRegion(Value *V);
778
779     /// Initialize the ScheduleData structures for new instructions in the
780     /// scheduling region.
781     void initScheduleData(Instruction *FromI, Instruction *ToI,
782                           ScheduleData *PrevLoadStore,
783                           ScheduleData *NextLoadStore);
784
785     /// Updates the dependency information of a bundle and of all instructions/
786     /// bundles which depend on the original bundle.
787     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
788                                BoUpSLP *SLP);
789
790     /// Sets all instruction in the scheduling region to un-scheduled.
791     void resetSchedule();
792
793     BasicBlock *BB;
794
795     /// Simple memory allocation for ScheduleData.
796     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
797
798     /// The size of a ScheduleData array in ScheduleDataChunks.
799     int ChunkSize;
800
801     /// The allocator position in the current chunk, which is the last entry
802     /// of ScheduleDataChunks.
803     int ChunkPos;
804
805     /// Attaches ScheduleData to Instruction.
806     /// Note that the mapping survives during all vectorization iterations, i.e.
807     /// ScheduleData structures are recycled.
808     DenseMap<Value *, ScheduleData *> ScheduleDataMap;
809
810     struct ReadyList : SmallVector<ScheduleData *, 8> {
811       void insert(ScheduleData *SD) { push_back(SD); }
812     };
813
814     /// The ready-list for scheduling (only used for the dry-run).
815     ReadyList ReadyInsts;
816
817     /// The first instruction of the scheduling region.
818     Instruction *ScheduleStart;
819
820     /// The first instruction _after_ the scheduling region.
821     Instruction *ScheduleEnd;
822
823     /// The first memory accessing instruction in the scheduling region
824     /// (can be null).
825     ScheduleData *FirstLoadStoreInRegion;
826
827     /// The last memory accessing instruction in the scheduling region
828     /// (can be null).
829     ScheduleData *LastLoadStoreInRegion;
830
831     /// The ID of the scheduling region. For a new vectorization iteration this
832     /// is incremented which "removes" all ScheduleData from the region.
833     int SchedulingRegionID;
834   };
835
836   /// Attaches the BlockScheduling structures to basic blocks.
837   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
838
839   /// Performs the "real" scheduling. Done before vectorization is actually
840   /// performed in a basic block.
841   void scheduleBlock(BlockScheduling *BS);
842
843   /// List of users to ignore during scheduling and that don't need extracting.
844   ArrayRef<Value *> UserIgnoreList;
845
846   // Number of load-bundles, which contain consecutive loads.
847   int NumLoadsWantToKeepOrder;
848
849   // Number of load-bundles of size 2, which are consecutive loads if reversed.
850   int NumLoadsWantToChangeOrder;
851
852   // Analysis and block reference.
853   Function *F;
854   ScalarEvolution *SE;
855   const DataLayout *DL;
856   TargetTransformInfo *TTI;
857   TargetLibraryInfo *TLI;
858   AliasAnalysis *AA;
859   LoopInfo *LI;
860   DominatorTree *DT;
861   /// Instruction builder to construct the vectorized tree.
862   IRBuilder<> Builder;
863 };
864
865 #ifndef NDEBUG
866 raw_ostream &operator<<(raw_ostream &os, const BoUpSLP::ScheduleData &SD) {
867   SD.dump(os);
868   return os;
869 }
870 #endif
871
872 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
873                         ArrayRef<Value *> UserIgnoreLst) {
874   deleteTree();
875   UserIgnoreList = UserIgnoreLst;
876   if (!getSameType(Roots))
877     return;
878   buildTree_rec(Roots, 0);
879
880   // Collect the values that we need to extract from the tree.
881   for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
882     TreeEntry *Entry = &VectorizableTree[EIdx];
883
884     // For each lane:
885     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
886       Value *Scalar = Entry->Scalars[Lane];
887
888       // No need to handle users of gathered values.
889       if (Entry->NeedToGather)
890         continue;
891
892       for (User *U : Scalar->users()) {
893         DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
894
895         Instruction *UserInst = dyn_cast<Instruction>(U);
896         if (!UserInst)
897           continue;
898
899         // Skip in-tree scalars that become vectors
900         if (ScalarToTreeEntry.count(U)) {
901           int Idx = ScalarToTreeEntry[U];
902           TreeEntry *UseEntry = &VectorizableTree[Idx];
903           Value *UseScalar = UseEntry->Scalars[0];
904           // Some in-tree scalars will remain as scalar in vectorized
905           // instructions. If that is the case, the one in Lane 0 will
906           // be used.
907           if (UseScalar != U ||
908               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
909             DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
910                          << ".\n");
911             assert(!VectorizableTree[Idx].NeedToGather && "Bad state");
912             continue;
913           }
914         }
915
916         // Ignore users in the user ignore list.
917         if (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), UserInst) !=
918             UserIgnoreList.end())
919           continue;
920
921         DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane " <<
922               Lane << " from " << *Scalar << ".\n");
923         ExternalUses.push_back(ExternalUser(Scalar, U, Lane));
924       }
925     }
926   }
927 }
928
929
930 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth) {
931   bool SameTy = getSameType(VL); (void)SameTy;
932   bool isAltShuffle = false;
933   assert(SameTy && "Invalid types!");
934
935   if (Depth == RecursionMaxDepth) {
936     DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
937     newTreeEntry(VL, false);
938     return;
939   }
940
941   // Don't handle vectors.
942   if (VL[0]->getType()->isVectorTy()) {
943     DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
944     newTreeEntry(VL, false);
945     return;
946   }
947
948   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
949     if (SI->getValueOperand()->getType()->isVectorTy()) {
950       DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
951       newTreeEntry(VL, false);
952       return;
953     }
954   unsigned Opcode = getSameOpcode(VL);
955
956   // Check that this shuffle vector refers to the alternate
957   // sequence of opcodes.
958   if (Opcode == Instruction::ShuffleVector) {
959     Instruction *I0 = dyn_cast<Instruction>(VL[0]);
960     unsigned Op = I0->getOpcode();
961     if (Op != Instruction::ShuffleVector)
962       isAltShuffle = true;
963   }
964
965   // If all of the operands are identical or constant we have a simple solution.
966   if (allConstant(VL) || isSplat(VL) || !getSameBlock(VL) || !Opcode) {
967     DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
968     newTreeEntry(VL, false);
969     return;
970   }
971
972   // We now know that this is a vector of instructions of the same type from
973   // the same block.
974
975   // Don't vectorize ephemeral values.
976   for (unsigned i = 0, e = VL.size(); i != e; ++i) {
977     if (EphValues.count(VL[i])) {
978       DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
979             ") is ephemeral.\n");
980       newTreeEntry(VL, false);
981       return;
982     }
983   }
984
985   // Check if this is a duplicate of another entry.
986   if (ScalarToTreeEntry.count(VL[0])) {
987     int Idx = ScalarToTreeEntry[VL[0]];
988     TreeEntry *E = &VectorizableTree[Idx];
989     for (unsigned i = 0, e = VL.size(); i != e; ++i) {
990       DEBUG(dbgs() << "SLP: \tChecking bundle: " << *VL[i] << ".\n");
991       if (E->Scalars[i] != VL[i]) {
992         DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
993         newTreeEntry(VL, false);
994         return;
995       }
996     }
997     DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *VL[0] << ".\n");
998     return;
999   }
1000
1001   // Check that none of the instructions in the bundle are already in the tree.
1002   for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1003     if (ScalarToTreeEntry.count(VL[i])) {
1004       DEBUG(dbgs() << "SLP: The instruction (" << *VL[i] <<
1005             ") is already in tree.\n");
1006       newTreeEntry(VL, false);
1007       return;
1008     }
1009   }
1010
1011   // If any of the scalars is marked as a value that needs to stay scalar then
1012   // we need to gather the scalars.
1013   for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1014     if (MustGather.count(VL[i])) {
1015       DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
1016       newTreeEntry(VL, false);
1017       return;
1018     }
1019   }
1020
1021   // Check that all of the users of the scalars that we want to vectorize are
1022   // schedulable.
1023   Instruction *VL0 = cast<Instruction>(VL[0]);
1024   BasicBlock *BB = cast<Instruction>(VL0)->getParent();
1025
1026   if (!DT->isReachableFromEntry(BB)) {
1027     // Don't go into unreachable blocks. They may contain instructions with
1028     // dependency cycles which confuse the final scheduling.
1029     DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
1030     newTreeEntry(VL, false);
1031     return;
1032   }
1033   
1034   // Check that every instructions appears once in this bundle.
1035   for (unsigned i = 0, e = VL.size(); i < e; ++i)
1036     for (unsigned j = i+1; j < e; ++j)
1037       if (VL[i] == VL[j]) {
1038         DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
1039         newTreeEntry(VL, false);
1040         return;
1041       }
1042
1043   auto &BSRef = BlocksSchedules[BB];
1044   if (!BSRef) {
1045     BSRef = llvm::make_unique<BlockScheduling>(BB);
1046   }
1047   BlockScheduling &BS = *BSRef.get();
1048
1049   if (!BS.tryScheduleBundle(VL, this)) {
1050     DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
1051     BS.cancelScheduling(VL);
1052     newTreeEntry(VL, false);
1053     return;
1054   }
1055   DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
1056
1057   switch (Opcode) {
1058     case Instruction::PHI: {
1059       PHINode *PH = dyn_cast<PHINode>(VL0);
1060
1061       // Check for terminator values (e.g. invoke).
1062       for (unsigned j = 0; j < VL.size(); ++j)
1063         for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1064           TerminatorInst *Term = dyn_cast<TerminatorInst>(
1065               cast<PHINode>(VL[j])->getIncomingValueForBlock(PH->getIncomingBlock(i)));
1066           if (Term) {
1067             DEBUG(dbgs() << "SLP: Need to swizzle PHINodes (TerminatorInst use).\n");
1068             BS.cancelScheduling(VL);
1069             newTreeEntry(VL, false);
1070             return;
1071           }
1072         }
1073
1074       newTreeEntry(VL, true);
1075       DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
1076
1077       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1078         ValueList Operands;
1079         // Prepare the operand vector.
1080         for (unsigned j = 0; j < VL.size(); ++j)
1081           Operands.push_back(cast<PHINode>(VL[j])->getIncomingValueForBlock(
1082               PH->getIncomingBlock(i)));
1083
1084         buildTree_rec(Operands, Depth + 1);
1085       }
1086       return;
1087     }
1088     case Instruction::ExtractElement: {
1089       bool Reuse = CanReuseExtract(VL);
1090       if (Reuse) {
1091         DEBUG(dbgs() << "SLP: Reusing extract sequence.\n");
1092       } else {
1093         BS.cancelScheduling(VL);
1094       }
1095       newTreeEntry(VL, Reuse);
1096       return;
1097     }
1098     case Instruction::Load: {
1099       // Check if the loads are consecutive or of we need to swizzle them.
1100       for (unsigned i = 0, e = VL.size() - 1; i < e; ++i) {
1101         LoadInst *L = cast<LoadInst>(VL[i]);
1102         if (!L->isSimple()) {
1103           BS.cancelScheduling(VL);
1104           newTreeEntry(VL, false);
1105           DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
1106           return;
1107         }
1108         if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
1109           if (VL.size() == 2 && isConsecutiveAccess(VL[1], VL[0])) {
1110             ++NumLoadsWantToChangeOrder;
1111           }
1112           BS.cancelScheduling(VL);
1113           newTreeEntry(VL, false);
1114           DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
1115           return;
1116         }
1117       }
1118       ++NumLoadsWantToKeepOrder;
1119       newTreeEntry(VL, true);
1120       DEBUG(dbgs() << "SLP: added a vector of loads.\n");
1121       return;
1122     }
1123     case Instruction::ZExt:
1124     case Instruction::SExt:
1125     case Instruction::FPToUI:
1126     case Instruction::FPToSI:
1127     case Instruction::FPExt:
1128     case Instruction::PtrToInt:
1129     case Instruction::IntToPtr:
1130     case Instruction::SIToFP:
1131     case Instruction::UIToFP:
1132     case Instruction::Trunc:
1133     case Instruction::FPTrunc:
1134     case Instruction::BitCast: {
1135       Type *SrcTy = VL0->getOperand(0)->getType();
1136       for (unsigned i = 0; i < VL.size(); ++i) {
1137         Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
1138         if (Ty != SrcTy || Ty->isAggregateType() || Ty->isVectorTy()) {
1139           BS.cancelScheduling(VL);
1140           newTreeEntry(VL, false);
1141           DEBUG(dbgs() << "SLP: Gathering casts with different src types.\n");
1142           return;
1143         }
1144       }
1145       newTreeEntry(VL, true);
1146       DEBUG(dbgs() << "SLP: added a vector of casts.\n");
1147
1148       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1149         ValueList Operands;
1150         // Prepare the operand vector.
1151         for (unsigned j = 0; j < VL.size(); ++j)
1152           Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1153
1154         buildTree_rec(Operands, Depth+1);
1155       }
1156       return;
1157     }
1158     case Instruction::ICmp:
1159     case Instruction::FCmp: {
1160       // Check that all of the compares have the same predicate.
1161       CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
1162       Type *ComparedTy = cast<Instruction>(VL[0])->getOperand(0)->getType();
1163       for (unsigned i = 1, e = VL.size(); i < e; ++i) {
1164         CmpInst *Cmp = cast<CmpInst>(VL[i]);
1165         if (Cmp->getPredicate() != P0 ||
1166             Cmp->getOperand(0)->getType() != ComparedTy) {
1167           BS.cancelScheduling(VL);
1168           newTreeEntry(VL, false);
1169           DEBUG(dbgs() << "SLP: Gathering cmp with different predicate.\n");
1170           return;
1171         }
1172       }
1173
1174       newTreeEntry(VL, true);
1175       DEBUG(dbgs() << "SLP: added a vector of compares.\n");
1176
1177       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1178         ValueList Operands;
1179         // Prepare the operand vector.
1180         for (unsigned j = 0; j < VL.size(); ++j)
1181           Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1182
1183         buildTree_rec(Operands, Depth+1);
1184       }
1185       return;
1186     }
1187     case Instruction::Select:
1188     case Instruction::Add:
1189     case Instruction::FAdd:
1190     case Instruction::Sub:
1191     case Instruction::FSub:
1192     case Instruction::Mul:
1193     case Instruction::FMul:
1194     case Instruction::UDiv:
1195     case Instruction::SDiv:
1196     case Instruction::FDiv:
1197     case Instruction::URem:
1198     case Instruction::SRem:
1199     case Instruction::FRem:
1200     case Instruction::Shl:
1201     case Instruction::LShr:
1202     case Instruction::AShr:
1203     case Instruction::And:
1204     case Instruction::Or:
1205     case Instruction::Xor: {
1206       newTreeEntry(VL, true);
1207       DEBUG(dbgs() << "SLP: added a vector of bin op.\n");
1208
1209       // Sort operands of the instructions so that each side is more likely to
1210       // have the same opcode.
1211       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
1212         ValueList Left, Right;
1213         reorderInputsAccordingToOpcode(VL, Left, Right);
1214         buildTree_rec(Left, Depth + 1);
1215         buildTree_rec(Right, Depth + 1);
1216         return;
1217       }
1218
1219       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1220         ValueList Operands;
1221         // Prepare the operand vector.
1222         for (unsigned j = 0; j < VL.size(); ++j)
1223           Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1224
1225         buildTree_rec(Operands, Depth+1);
1226       }
1227       return;
1228     }
1229     case Instruction::GetElementPtr: {
1230       // We don't combine GEPs with complicated (nested) indexing.
1231       for (unsigned j = 0; j < VL.size(); ++j) {
1232         if (cast<Instruction>(VL[j])->getNumOperands() != 2) {
1233           DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
1234           BS.cancelScheduling(VL);
1235           newTreeEntry(VL, false);
1236           return;
1237         }
1238       }
1239
1240       // We can't combine several GEPs into one vector if they operate on
1241       // different types.
1242       Type *Ty0 = cast<Instruction>(VL0)->getOperand(0)->getType();
1243       for (unsigned j = 0; j < VL.size(); ++j) {
1244         Type *CurTy = cast<Instruction>(VL[j])->getOperand(0)->getType();
1245         if (Ty0 != CurTy) {
1246           DEBUG(dbgs() << "SLP: not-vectorizable GEP (different types).\n");
1247           BS.cancelScheduling(VL);
1248           newTreeEntry(VL, false);
1249           return;
1250         }
1251       }
1252
1253       // We don't combine GEPs with non-constant indexes.
1254       for (unsigned j = 0; j < VL.size(); ++j) {
1255         auto Op = cast<Instruction>(VL[j])->getOperand(1);
1256         if (!isa<ConstantInt>(Op)) {
1257           DEBUG(
1258               dbgs() << "SLP: not-vectorizable GEP (non-constant indexes).\n");
1259           BS.cancelScheduling(VL);
1260           newTreeEntry(VL, false);
1261           return;
1262         }
1263       }
1264
1265       newTreeEntry(VL, true);
1266       DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
1267       for (unsigned i = 0, e = 2; i < e; ++i) {
1268         ValueList Operands;
1269         // Prepare the operand vector.
1270         for (unsigned j = 0; j < VL.size(); ++j)
1271           Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1272
1273         buildTree_rec(Operands, Depth + 1);
1274       }
1275       return;
1276     }
1277     case Instruction::Store: {
1278       // Check if the stores are consecutive or of we need to swizzle them.
1279       for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
1280         if (!isConsecutiveAccess(VL[i], VL[i + 1])) {
1281           BS.cancelScheduling(VL);
1282           newTreeEntry(VL, false);
1283           DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
1284           return;
1285         }
1286
1287       newTreeEntry(VL, true);
1288       DEBUG(dbgs() << "SLP: added a vector of stores.\n");
1289
1290       ValueList Operands;
1291       for (unsigned j = 0; j < VL.size(); ++j)
1292         Operands.push_back(cast<Instruction>(VL[j])->getOperand(0));
1293
1294       buildTree_rec(Operands, Depth + 1);
1295       return;
1296     }
1297     case Instruction::Call: {
1298       // Check if the calls are all to the same vectorizable intrinsic.
1299       CallInst *CI = cast<CallInst>(VL[0]);
1300       // Check if this is an Intrinsic call or something that can be
1301       // represented by an intrinsic call
1302       Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
1303       if (!isTriviallyVectorizable(ID)) {
1304         BS.cancelScheduling(VL);
1305         newTreeEntry(VL, false);
1306         DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
1307         return;
1308       }
1309       Function *Int = CI->getCalledFunction();
1310       Value *A1I = nullptr;
1311       if (hasVectorInstrinsicScalarOpd(ID, 1))
1312         A1I = CI->getArgOperand(1);
1313       for (unsigned i = 1, e = VL.size(); i != e; ++i) {
1314         CallInst *CI2 = dyn_cast<CallInst>(VL[i]);
1315         if (!CI2 || CI2->getCalledFunction() != Int ||
1316             getIntrinsicIDForCall(CI2, TLI) != ID) {
1317           BS.cancelScheduling(VL);
1318           newTreeEntry(VL, false);
1319           DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *VL[i]
1320                        << "\n");
1321           return;
1322         }
1323         // ctlz,cttz and powi are special intrinsics whose second argument
1324         // should be same in order for them to be vectorized.
1325         if (hasVectorInstrinsicScalarOpd(ID, 1)) {
1326           Value *A1J = CI2->getArgOperand(1);
1327           if (A1I != A1J) {
1328             BS.cancelScheduling(VL);
1329             newTreeEntry(VL, false);
1330             DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
1331                          << " argument "<< A1I<<"!=" << A1J
1332                          << "\n");
1333             return;
1334           }
1335         }
1336       }
1337
1338       newTreeEntry(VL, true);
1339       for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) {
1340         ValueList Operands;
1341         // Prepare the operand vector.
1342         for (unsigned j = 0; j < VL.size(); ++j) {
1343           CallInst *CI2 = dyn_cast<CallInst>(VL[j]);
1344           Operands.push_back(CI2->getArgOperand(i));
1345         }
1346         buildTree_rec(Operands, Depth + 1);
1347       }
1348       return;
1349     }
1350     case Instruction::ShuffleVector: {
1351       // If this is not an alternate sequence of opcode like add-sub
1352       // then do not vectorize this instruction.
1353       if (!isAltShuffle) {
1354         BS.cancelScheduling(VL);
1355         newTreeEntry(VL, false);
1356         DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
1357         return;
1358       }
1359       newTreeEntry(VL, true);
1360       DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
1361
1362       // Reorder operands if reordering would enable vectorization.
1363       if (isa<BinaryOperator>(VL0)) {
1364         ValueList Left, Right;
1365         reorderAltShuffleOperands(VL, Left, Right);
1366         buildTree_rec(Left, Depth + 1);
1367         buildTree_rec(Right, Depth + 1);
1368         return;
1369       }
1370
1371       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1372         ValueList Operands;
1373         // Prepare the operand vector.
1374         for (unsigned j = 0; j < VL.size(); ++j)
1375           Operands.push_back(cast<Instruction>(VL[j])->getOperand(i));
1376
1377         buildTree_rec(Operands, Depth + 1);
1378       }
1379       return;
1380     }
1381     default:
1382       BS.cancelScheduling(VL);
1383       newTreeEntry(VL, false);
1384       DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
1385       return;
1386   }
1387 }
1388
1389 int BoUpSLP::getEntryCost(TreeEntry *E) {
1390   ArrayRef<Value*> VL = E->Scalars;
1391
1392   Type *ScalarTy = VL[0]->getType();
1393   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1394     ScalarTy = SI->getValueOperand()->getType();
1395   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1396
1397   if (E->NeedToGather) {
1398     if (allConstant(VL))
1399       return 0;
1400     if (isSplat(VL)) {
1401       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
1402     }
1403     return getGatherCost(E->Scalars);
1404   }
1405   unsigned Opcode = getSameOpcode(VL);
1406   assert(Opcode && getSameType(VL) && getSameBlock(VL) && "Invalid VL");
1407   Instruction *VL0 = cast<Instruction>(VL[0]);
1408   switch (Opcode) {
1409     case Instruction::PHI: {
1410       return 0;
1411     }
1412     case Instruction::ExtractElement: {
1413       if (CanReuseExtract(VL)) {
1414         int DeadCost = 0;
1415         for (unsigned i = 0, e = VL.size(); i < e; ++i) {
1416           ExtractElementInst *E = cast<ExtractElementInst>(VL[i]);
1417           if (E->hasOneUse())
1418             // Take credit for instruction that will become dead.
1419             DeadCost +=
1420                 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, i);
1421         }
1422         return -DeadCost;
1423       }
1424       return getGatherCost(VecTy);
1425     }
1426     case Instruction::ZExt:
1427     case Instruction::SExt:
1428     case Instruction::FPToUI:
1429     case Instruction::FPToSI:
1430     case Instruction::FPExt:
1431     case Instruction::PtrToInt:
1432     case Instruction::IntToPtr:
1433     case Instruction::SIToFP:
1434     case Instruction::UIToFP:
1435     case Instruction::Trunc:
1436     case Instruction::FPTrunc:
1437     case Instruction::BitCast: {
1438       Type *SrcTy = VL0->getOperand(0)->getType();
1439
1440       // Calculate the cost of this instruction.
1441       int ScalarCost = VL.size() * TTI->getCastInstrCost(VL0->getOpcode(),
1442                                                          VL0->getType(), SrcTy);
1443
1444       VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
1445       int VecCost = TTI->getCastInstrCost(VL0->getOpcode(), VecTy, SrcVecTy);
1446       return VecCost - ScalarCost;
1447     }
1448     case Instruction::FCmp:
1449     case Instruction::ICmp:
1450     case Instruction::Select:
1451     case Instruction::Add:
1452     case Instruction::FAdd:
1453     case Instruction::Sub:
1454     case Instruction::FSub:
1455     case Instruction::Mul:
1456     case Instruction::FMul:
1457     case Instruction::UDiv:
1458     case Instruction::SDiv:
1459     case Instruction::FDiv:
1460     case Instruction::URem:
1461     case Instruction::SRem:
1462     case Instruction::FRem:
1463     case Instruction::Shl:
1464     case Instruction::LShr:
1465     case Instruction::AShr:
1466     case Instruction::And:
1467     case Instruction::Or:
1468     case Instruction::Xor: {
1469       // Calculate the cost of this instruction.
1470       int ScalarCost = 0;
1471       int VecCost = 0;
1472       if (Opcode == Instruction::FCmp || Opcode == Instruction::ICmp ||
1473           Opcode == Instruction::Select) {
1474         VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
1475         ScalarCost = VecTy->getNumElements() *
1476         TTI->getCmpSelInstrCost(Opcode, ScalarTy, Builder.getInt1Ty());
1477         VecCost = TTI->getCmpSelInstrCost(Opcode, VecTy, MaskTy);
1478       } else {
1479         // Certain instructions can be cheaper to vectorize if they have a
1480         // constant second vector operand.
1481         TargetTransformInfo::OperandValueKind Op1VK =
1482             TargetTransformInfo::OK_AnyValue;
1483         TargetTransformInfo::OperandValueKind Op2VK =
1484             TargetTransformInfo::OK_UniformConstantValue;
1485         TargetTransformInfo::OperandValueProperties Op1VP =
1486             TargetTransformInfo::OP_None;
1487         TargetTransformInfo::OperandValueProperties Op2VP =
1488             TargetTransformInfo::OP_None;
1489
1490         // If all operands are exactly the same ConstantInt then set the
1491         // operand kind to OK_UniformConstantValue.
1492         // If instead not all operands are constants, then set the operand kind
1493         // to OK_AnyValue. If all operands are constants but not the same,
1494         // then set the operand kind to OK_NonUniformConstantValue.
1495         ConstantInt *CInt = nullptr;
1496         for (unsigned i = 0; i < VL.size(); ++i) {
1497           const Instruction *I = cast<Instruction>(VL[i]);
1498           if (!isa<ConstantInt>(I->getOperand(1))) {
1499             Op2VK = TargetTransformInfo::OK_AnyValue;
1500             break;
1501           }
1502           if (i == 0) {
1503             CInt = cast<ConstantInt>(I->getOperand(1));
1504             continue;
1505           }
1506           if (Op2VK == TargetTransformInfo::OK_UniformConstantValue &&
1507               CInt != cast<ConstantInt>(I->getOperand(1)))
1508             Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
1509         }
1510         // FIXME: Currently cost of model modification for division by
1511         // power of 2 is handled only for X86. Add support for other targets.
1512         if (Op2VK == TargetTransformInfo::OK_UniformConstantValue && CInt &&
1513             CInt->getValue().isPowerOf2())
1514           Op2VP = TargetTransformInfo::OP_PowerOf2;
1515
1516         ScalarCost = VecTy->getNumElements() *
1517                      TTI->getArithmeticInstrCost(Opcode, ScalarTy, Op1VK, Op2VK,
1518                                                  Op1VP, Op2VP);
1519         VecCost = TTI->getArithmeticInstrCost(Opcode, VecTy, Op1VK, Op2VK,
1520                                               Op1VP, Op2VP);
1521       }
1522       return VecCost - ScalarCost;
1523     }
1524     case Instruction::GetElementPtr: {
1525       TargetTransformInfo::OperandValueKind Op1VK =
1526           TargetTransformInfo::OK_AnyValue;
1527       TargetTransformInfo::OperandValueKind Op2VK =
1528           TargetTransformInfo::OK_UniformConstantValue;
1529
1530       int ScalarCost =
1531           VecTy->getNumElements() *
1532           TTI->getArithmeticInstrCost(Instruction::Add, ScalarTy, Op1VK, Op2VK);
1533       int VecCost =
1534           TTI->getArithmeticInstrCost(Instruction::Add, VecTy, Op1VK, Op2VK);
1535
1536       return VecCost - ScalarCost;
1537     }
1538     case Instruction::Load: {
1539       // Cost of wide load - cost of scalar loads.
1540       int ScalarLdCost = VecTy->getNumElements() *
1541       TTI->getMemoryOpCost(Instruction::Load, ScalarTy, 1, 0);
1542       int VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, 1, 0);
1543       return VecLdCost - ScalarLdCost;
1544     }
1545     case Instruction::Store: {
1546       // We know that we can merge the stores. Calculate the cost.
1547       int ScalarStCost = VecTy->getNumElements() *
1548       TTI->getMemoryOpCost(Instruction::Store, ScalarTy, 1, 0);
1549       int VecStCost = TTI->getMemoryOpCost(Instruction::Store, VecTy, 1, 0);
1550       return VecStCost - ScalarStCost;
1551     }
1552     case Instruction::Call: {
1553       CallInst *CI = cast<CallInst>(VL0);
1554       Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
1555
1556       // Calculate the cost of the scalar and vector calls.
1557       SmallVector<Type*, 4> ScalarTys, VecTys;
1558       for (unsigned op = 0, opc = CI->getNumArgOperands(); op!= opc; ++op) {
1559         ScalarTys.push_back(CI->getArgOperand(op)->getType());
1560         VecTys.push_back(VectorType::get(CI->getArgOperand(op)->getType(),
1561                                          VecTy->getNumElements()));
1562       }
1563
1564       int ScalarCallCost = VecTy->getNumElements() *
1565           TTI->getIntrinsicInstrCost(ID, ScalarTy, ScalarTys);
1566
1567       int VecCallCost = TTI->getIntrinsicInstrCost(ID, VecTy, VecTys);
1568
1569       DEBUG(dbgs() << "SLP: Call cost "<< VecCallCost - ScalarCallCost
1570             << " (" << VecCallCost  << "-" <<  ScalarCallCost << ")"
1571             << " for " << *CI << "\n");
1572
1573       return VecCallCost - ScalarCallCost;
1574     }
1575     case Instruction::ShuffleVector: {
1576       TargetTransformInfo::OperandValueKind Op1VK =
1577           TargetTransformInfo::OK_AnyValue;
1578       TargetTransformInfo::OperandValueKind Op2VK =
1579           TargetTransformInfo::OK_AnyValue;
1580       int ScalarCost = 0;
1581       int VecCost = 0;
1582       for (unsigned i = 0; i < VL.size(); ++i) {
1583         Instruction *I = cast<Instruction>(VL[i]);
1584         if (!I)
1585           break;
1586         ScalarCost +=
1587             TTI->getArithmeticInstrCost(I->getOpcode(), ScalarTy, Op1VK, Op2VK);
1588       }
1589       // VecCost is equal to sum of the cost of creating 2 vectors
1590       // and the cost of creating shuffle.
1591       Instruction *I0 = cast<Instruction>(VL[0]);
1592       VecCost =
1593           TTI->getArithmeticInstrCost(I0->getOpcode(), VecTy, Op1VK, Op2VK);
1594       Instruction *I1 = cast<Instruction>(VL[1]);
1595       VecCost +=
1596           TTI->getArithmeticInstrCost(I1->getOpcode(), VecTy, Op1VK, Op2VK);
1597       VecCost +=
1598           TTI->getShuffleCost(TargetTransformInfo::SK_Alternate, VecTy, 0);
1599       return VecCost - ScalarCost;
1600     }
1601     default:
1602       llvm_unreachable("Unknown instruction");
1603   }
1604 }
1605
1606 bool BoUpSLP::isFullyVectorizableTinyTree() {
1607   DEBUG(dbgs() << "SLP: Check whether the tree with height " <<
1608         VectorizableTree.size() << " is fully vectorizable .\n");
1609
1610   // We only handle trees of height 2.
1611   if (VectorizableTree.size() != 2)
1612     return false;
1613
1614   // Handle splat stores.
1615   if (!VectorizableTree[0].NeedToGather && isSplat(VectorizableTree[1].Scalars))
1616     return true;
1617
1618   // Gathering cost would be too much for tiny trees.
1619   if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather)
1620     return false;
1621
1622   return true;
1623 }
1624
1625 int BoUpSLP::getSpillCost() {
1626   // Walk from the bottom of the tree to the top, tracking which values are
1627   // live. When we see a call instruction that is not part of our tree,
1628   // query TTI to see if there is a cost to keeping values live over it
1629   // (for example, if spills and fills are required).
1630   unsigned BundleWidth = VectorizableTree.front().Scalars.size();
1631   int Cost = 0;
1632
1633   SmallPtrSet<Instruction*, 4> LiveValues;
1634   Instruction *PrevInst = nullptr; 
1635
1636   for (unsigned N = 0; N < VectorizableTree.size(); ++N) {
1637     Instruction *Inst = dyn_cast<Instruction>(VectorizableTree[N].Scalars[0]);
1638     if (!Inst)
1639       continue;
1640
1641     if (!PrevInst) {
1642       PrevInst = Inst;
1643       continue;
1644     }
1645
1646     DEBUG(
1647       dbgs() << "SLP: #LV: " << LiveValues.size();
1648       for (auto *X : LiveValues)
1649         dbgs() << " " << X->getName();
1650       dbgs() << ", Looking at ";
1651       Inst->dump();
1652       );
1653
1654     // Update LiveValues.
1655     LiveValues.erase(PrevInst);
1656     for (auto &J : PrevInst->operands()) {
1657       if (isa<Instruction>(&*J) && ScalarToTreeEntry.count(&*J))
1658         LiveValues.insert(cast<Instruction>(&*J));
1659     }    
1660
1661     // Now find the sequence of instructions between PrevInst and Inst.
1662     BasicBlock::reverse_iterator InstIt(Inst), PrevInstIt(PrevInst);
1663     --PrevInstIt;
1664     while (InstIt != PrevInstIt) {
1665       if (PrevInstIt == PrevInst->getParent()->rend()) {
1666         PrevInstIt = Inst->getParent()->rbegin();
1667         continue;
1668       }
1669
1670       if (isa<CallInst>(&*PrevInstIt) && &*PrevInstIt != PrevInst) {
1671         SmallVector<Type*, 4> V;
1672         for (auto *II : LiveValues)
1673           V.push_back(VectorType::get(II->getType(), BundleWidth));
1674         Cost += TTI->getCostOfKeepingLiveOverCall(V);
1675       }
1676
1677       ++PrevInstIt;
1678     }
1679
1680     PrevInst = Inst;
1681   }
1682
1683   DEBUG(dbgs() << "SLP: SpillCost=" << Cost << "\n");
1684   return Cost;
1685 }
1686
1687 int BoUpSLP::getTreeCost() {
1688   int Cost = 0;
1689   DEBUG(dbgs() << "SLP: Calculating cost for tree of size " <<
1690         VectorizableTree.size() << ".\n");
1691
1692   // We only vectorize tiny trees if it is fully vectorizable.
1693   if (VectorizableTree.size() < 3 && !isFullyVectorizableTinyTree()) {
1694     if (VectorizableTree.empty()) {
1695       assert(!ExternalUses.size() && "We should not have any external users");
1696     }
1697     return INT_MAX;
1698   }
1699
1700   unsigned BundleWidth = VectorizableTree[0].Scalars.size();
1701
1702   for (unsigned i = 0, e = VectorizableTree.size(); i != e; ++i) {
1703     int C = getEntryCost(&VectorizableTree[i]);
1704     DEBUG(dbgs() << "SLP: Adding cost " << C << " for bundle that starts with "
1705           << *VectorizableTree[i].Scalars[0] << " .\n");
1706     Cost += C;
1707   }
1708
1709   SmallSet<Value *, 16> ExtractCostCalculated;
1710   int ExtractCost = 0;
1711   for (UserList::iterator I = ExternalUses.begin(), E = ExternalUses.end();
1712        I != E; ++I) {
1713     // We only add extract cost once for the same scalar.
1714     if (!ExtractCostCalculated.insert(I->Scalar).second)
1715       continue;
1716
1717     // Uses by ephemeral values are free (because the ephemeral value will be
1718     // removed prior to code generation, and so the extraction will be
1719     // removed as well).
1720     if (EphValues.count(I->User))
1721       continue;
1722
1723     VectorType *VecTy = VectorType::get(I->Scalar->getType(), BundleWidth);
1724     ExtractCost += TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
1725                                            I->Lane);
1726   }
1727
1728   Cost += getSpillCost();
1729
1730   DEBUG(dbgs() << "SLP: Total Cost " << Cost + ExtractCost<< ".\n");
1731   return  Cost + ExtractCost;
1732 }
1733
1734 int BoUpSLP::getGatherCost(Type *Ty) {
1735   int Cost = 0;
1736   for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
1737     Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
1738   return Cost;
1739 }
1740
1741 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
1742   // Find the type of the operands in VL.
1743   Type *ScalarTy = VL[0]->getType();
1744   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
1745     ScalarTy = SI->getValueOperand()->getType();
1746   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
1747   // Find the cost of inserting/extracting values from the vector.
1748   return getGatherCost(VecTy);
1749 }
1750
1751 Value *BoUpSLP::getPointerOperand(Value *I) {
1752   if (LoadInst *LI = dyn_cast<LoadInst>(I))
1753     return LI->getPointerOperand();
1754   if (StoreInst *SI = dyn_cast<StoreInst>(I))
1755     return SI->getPointerOperand();
1756   return nullptr;
1757 }
1758
1759 unsigned BoUpSLP::getAddressSpaceOperand(Value *I) {
1760   if (LoadInst *L = dyn_cast<LoadInst>(I))
1761     return L->getPointerAddressSpace();
1762   if (StoreInst *S = dyn_cast<StoreInst>(I))
1763     return S->getPointerAddressSpace();
1764   return -1;
1765 }
1766
1767 bool BoUpSLP::isConsecutiveAccess(Value *A, Value *B) {
1768   Value *PtrA = getPointerOperand(A);
1769   Value *PtrB = getPointerOperand(B);
1770   unsigned ASA = getAddressSpaceOperand(A);
1771   unsigned ASB = getAddressSpaceOperand(B);
1772
1773   // Check that the address spaces match and that the pointers are valid.
1774   if (!PtrA || !PtrB || (ASA != ASB))
1775     return false;
1776
1777   // Make sure that A and B are different pointers of the same type.
1778   if (PtrA == PtrB || PtrA->getType() != PtrB->getType())
1779     return false;
1780
1781   unsigned PtrBitWidth = DL->getPointerSizeInBits(ASA);
1782   Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
1783   APInt Size(PtrBitWidth, DL->getTypeStoreSize(Ty));
1784
1785   APInt OffsetA(PtrBitWidth, 0), OffsetB(PtrBitWidth, 0);
1786   PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetA);
1787   PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(*DL, OffsetB);
1788
1789   APInt OffsetDelta = OffsetB - OffsetA;
1790
1791   // Check if they are based on the same pointer. That makes the offsets
1792   // sufficient.
1793   if (PtrA == PtrB)
1794     return OffsetDelta == Size;
1795
1796   // Compute the necessary base pointer delta to have the necessary final delta
1797   // equal to the size.
1798   APInt BaseDelta = Size - OffsetDelta;
1799
1800   // Otherwise compute the distance with SCEV between the base pointers.
1801   const SCEV *PtrSCEVA = SE->getSCEV(PtrA);
1802   const SCEV *PtrSCEVB = SE->getSCEV(PtrB);
1803   const SCEV *C = SE->getConstant(BaseDelta);
1804   const SCEV *X = SE->getAddExpr(PtrSCEVA, C);
1805   return X == PtrSCEVB;
1806 }
1807
1808 // Reorder commutative operations in alternate shuffle if the resulting vectors
1809 // are consecutive loads. This would allow us to vectorize the tree.
1810 // If we have something like-
1811 // load a[0] - load b[0]
1812 // load b[1] + load a[1]
1813 // load a[2] - load b[2]
1814 // load a[3] + load b[3]
1815 // Reordering the second load b[1]  load a[1] would allow us to vectorize this
1816 // code.
1817 void BoUpSLP::reorderAltShuffleOperands(ArrayRef<Value *> VL,
1818                                         SmallVectorImpl<Value *> &Left,
1819                                         SmallVectorImpl<Value *> &Right) {
1820
1821   // Push left and right operands of binary operation into Left and Right
1822   for (unsigned i = 0, e = VL.size(); i < e; ++i) {
1823     Left.push_back(cast<Instruction>(VL[i])->getOperand(0));
1824     Right.push_back(cast<Instruction>(VL[i])->getOperand(1));
1825   }
1826
1827   // Reorder if we have a commutative operation and consecutive access
1828   // are on either side of the alternate instructions.
1829   for (unsigned j = 0; j < VL.size() - 1; ++j) {
1830     if (LoadInst *L = dyn_cast<LoadInst>(Left[j])) {
1831       if (LoadInst *L1 = dyn_cast<LoadInst>(Right[j + 1])) {
1832         Instruction *VL1 = cast<Instruction>(VL[j]);
1833         Instruction *VL2 = cast<Instruction>(VL[j + 1]);
1834         if (isConsecutiveAccess(L, L1) && VL1->isCommutative()) {
1835           std::swap(Left[j], Right[j]);
1836           continue;
1837         } else if (isConsecutiveAccess(L, L1) && VL2->isCommutative()) {
1838           std::swap(Left[j + 1], Right[j + 1]);
1839           continue;
1840         }
1841         // else unchanged
1842       }
1843     }
1844     if (LoadInst *L = dyn_cast<LoadInst>(Right[j])) {
1845       if (LoadInst *L1 = dyn_cast<LoadInst>(Left[j + 1])) {
1846         Instruction *VL1 = cast<Instruction>(VL[j]);
1847         Instruction *VL2 = cast<Instruction>(VL[j + 1]);
1848         if (isConsecutiveAccess(L, L1) && VL1->isCommutative()) {
1849           std::swap(Left[j], Right[j]);
1850           continue;
1851         } else if (isConsecutiveAccess(L, L1) && VL2->isCommutative()) {
1852           std::swap(Left[j + 1], Right[j + 1]);
1853           continue;
1854         }
1855         // else unchanged
1856       }
1857     }
1858   }
1859 }
1860
1861 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
1862                                              SmallVectorImpl<Value *> &Left,
1863                                              SmallVectorImpl<Value *> &Right) {
1864
1865   SmallVector<Value *, 16> OrigLeft, OrigRight;
1866
1867   bool AllSameOpcodeLeft = true;
1868   bool AllSameOpcodeRight = true;
1869   for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1870     Instruction *I = cast<Instruction>(VL[i]);
1871     Value *VLeft = I->getOperand(0);
1872     Value *VRight = I->getOperand(1);
1873
1874     OrigLeft.push_back(VLeft);
1875     OrigRight.push_back(VRight);
1876
1877     Instruction *ILeft = dyn_cast<Instruction>(VLeft);
1878     Instruction *IRight = dyn_cast<Instruction>(VRight);
1879
1880     // Check whether all operands on one side have the same opcode. In this case
1881     // we want to preserve the original order and not make things worse by
1882     // reordering.
1883     if (i && AllSameOpcodeLeft && ILeft) {
1884       if (Instruction *PLeft = dyn_cast<Instruction>(OrigLeft[i - 1])) {
1885         if (PLeft->getOpcode() != ILeft->getOpcode())
1886           AllSameOpcodeLeft = false;
1887       } else
1888         AllSameOpcodeLeft = false;
1889     }
1890     if (i && AllSameOpcodeRight && IRight) {
1891       if (Instruction *PRight = dyn_cast<Instruction>(OrigRight[i - 1])) {
1892         if (PRight->getOpcode() != IRight->getOpcode())
1893           AllSameOpcodeRight = false;
1894       } else
1895         AllSameOpcodeRight = false;
1896     }
1897
1898     // Sort two opcodes. In the code below we try to preserve the ability to use
1899     // broadcast of values instead of individual inserts.
1900     // vl1 = load
1901     // vl2 = phi
1902     // vr1 = load
1903     // vr2 = vr2
1904     //    = vl1 x vr1
1905     //    = vl2 x vr2
1906     // If we just sorted according to opcode we would leave the first line in
1907     // tact but we would swap vl2 with vr2 because opcode(phi) > opcode(load).
1908     //    = vl1 x vr1
1909     //    = vr2 x vl2
1910     // Because vr2 and vr1 are from the same load we loose the opportunity of a
1911     // broadcast for the packed right side in the backend: we have [vr1, vl2]
1912     // instead of [vr1, vr2=vr1].
1913     if (ILeft && IRight) {
1914       if (!i && ILeft->getOpcode() > IRight->getOpcode()) {
1915         Left.push_back(IRight);
1916         Right.push_back(ILeft);
1917       } else if (i && ILeft->getOpcode() > IRight->getOpcode() &&
1918                  Right[i - 1] != IRight) {
1919         // Try not to destroy a broad cast for no apparent benefit.
1920         Left.push_back(IRight);
1921         Right.push_back(ILeft);
1922       } else if (i && ILeft->getOpcode() == IRight->getOpcode() &&
1923                  Right[i - 1] == ILeft) {
1924         // Try preserve broadcasts.
1925         Left.push_back(IRight);
1926         Right.push_back(ILeft);
1927       } else if (i && ILeft->getOpcode() == IRight->getOpcode() &&
1928                  Left[i - 1] == IRight) {
1929         // Try preserve broadcasts.
1930         Left.push_back(IRight);
1931         Right.push_back(ILeft);
1932       } else {
1933         Left.push_back(ILeft);
1934         Right.push_back(IRight);
1935       }
1936       continue;
1937     }
1938     // One opcode, put the instruction on the right.
1939     if (ILeft) {
1940       Left.push_back(VRight);
1941       Right.push_back(ILeft);
1942       continue;
1943     }
1944     Left.push_back(VLeft);
1945     Right.push_back(VRight);
1946   }
1947
1948   bool LeftBroadcast = isSplat(Left);
1949   bool RightBroadcast = isSplat(Right);
1950
1951   // If operands end up being broadcast return this operand order.
1952   if (LeftBroadcast || RightBroadcast)
1953     return;
1954
1955   // Don't reorder if the operands where good to begin.
1956   if (AllSameOpcodeRight || AllSameOpcodeLeft) {
1957     Left = OrigLeft;
1958     Right = OrigRight;
1959   }
1960
1961   // Finally check if we can get longer vectorizable chain by reordering
1962   // without breaking the good operand order detected above.
1963   // E.g. If we have something like-
1964   // load a[0]  load b[0]
1965   // load b[1]  load a[1]
1966   // load a[2]  load b[2]
1967   // load a[3]  load b[3]
1968   // Reordering the second load b[1]  load a[1] would allow us to vectorize
1969   // this code and we still retain AllSameOpcode property.
1970   // FIXME: This load reordering might break AllSameOpcode in some rare cases
1971   // such as-
1972   // add a[0],c[0]  load b[0]
1973   // add a[1],c[2]  load b[1]
1974   // b[2]           load b[2]
1975   // add a[3],c[3]  load b[3]
1976   for (unsigned j = 0; j < VL.size() - 1; ++j) {
1977     if (LoadInst *L = dyn_cast<LoadInst>(Left[j])) {
1978       if (LoadInst *L1 = dyn_cast<LoadInst>(Right[j + 1])) {
1979         if (isConsecutiveAccess(L, L1)) {
1980           std::swap(Left[j + 1], Right[j + 1]);
1981           continue;
1982         }
1983       }
1984     }
1985     if (LoadInst *L = dyn_cast<LoadInst>(Right[j])) {
1986       if (LoadInst *L1 = dyn_cast<LoadInst>(Left[j + 1])) {
1987         if (isConsecutiveAccess(L, L1)) {
1988           std::swap(Left[j + 1], Right[j + 1]);
1989           continue;
1990         }
1991       }
1992     }
1993     // else unchanged
1994   }
1995 }
1996
1997 void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL) {
1998   Instruction *VL0 = cast<Instruction>(VL[0]);
1999   BasicBlock::iterator NextInst = VL0;
2000   ++NextInst;
2001   Builder.SetInsertPoint(VL0->getParent(), NextInst);
2002   Builder.SetCurrentDebugLocation(VL0->getDebugLoc());
2003 }
2004
2005 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
2006   Value *Vec = UndefValue::get(Ty);
2007   // Generate the 'InsertElement' instruction.
2008   for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
2009     Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
2010     if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
2011       GatherSeq.insert(Insrt);
2012       CSEBlocks.insert(Insrt->getParent());
2013
2014       // Add to our 'need-to-extract' list.
2015       if (ScalarToTreeEntry.count(VL[i])) {
2016         int Idx = ScalarToTreeEntry[VL[i]];
2017         TreeEntry *E = &VectorizableTree[Idx];
2018         // Find which lane we need to extract.
2019         int FoundLane = -1;
2020         for (unsigned Lane = 0, LE = VL.size(); Lane != LE; ++Lane) {
2021           // Is this the lane of the scalar that we are looking for ?
2022           if (E->Scalars[Lane] == VL[i]) {
2023             FoundLane = Lane;
2024             break;
2025           }
2026         }
2027         assert(FoundLane >= 0 && "Could not find the correct lane");
2028         ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
2029       }
2030     }
2031   }
2032
2033   return Vec;
2034 }
2035
2036 Value *BoUpSLP::alreadyVectorized(ArrayRef<Value *> VL) const {
2037   SmallDenseMap<Value*, int>::const_iterator Entry
2038     = ScalarToTreeEntry.find(VL[0]);
2039   if (Entry != ScalarToTreeEntry.end()) {
2040     int Idx = Entry->second;
2041     const TreeEntry *En = &VectorizableTree[Idx];
2042     if (En->isSame(VL) && En->VectorizedValue)
2043       return En->VectorizedValue;
2044   }
2045   return nullptr;
2046 }
2047
2048 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
2049   if (ScalarToTreeEntry.count(VL[0])) {
2050     int Idx = ScalarToTreeEntry[VL[0]];
2051     TreeEntry *E = &VectorizableTree[Idx];
2052     if (E->isSame(VL))
2053       return vectorizeTree(E);
2054   }
2055
2056   Type *ScalarTy = VL[0]->getType();
2057   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
2058     ScalarTy = SI->getValueOperand()->getType();
2059   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
2060
2061   return Gather(VL, VecTy);
2062 }
2063
2064 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
2065   IRBuilder<>::InsertPointGuard Guard(Builder);
2066
2067   if (E->VectorizedValue) {
2068     DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
2069     return E->VectorizedValue;
2070   }
2071
2072   Instruction *VL0 = cast<Instruction>(E->Scalars[0]);
2073   Type *ScalarTy = VL0->getType();
2074   if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
2075     ScalarTy = SI->getValueOperand()->getType();
2076   VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
2077
2078   if (E->NeedToGather) {
2079     setInsertPointAfterBundle(E->Scalars);
2080     return Gather(E->Scalars, VecTy);
2081   }
2082
2083   unsigned Opcode = getSameOpcode(E->Scalars);
2084
2085   switch (Opcode) {
2086     case Instruction::PHI: {
2087       PHINode *PH = dyn_cast<PHINode>(VL0);
2088       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
2089       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
2090       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
2091       E->VectorizedValue = NewPhi;
2092
2093       // PHINodes may have multiple entries from the same block. We want to
2094       // visit every block once.
2095       SmallSet<BasicBlock*, 4> VisitedBBs;
2096
2097       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
2098         ValueList Operands;
2099         BasicBlock *IBB = PH->getIncomingBlock(i);
2100
2101         if (!VisitedBBs.insert(IBB).second) {
2102           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
2103           continue;
2104         }
2105
2106         // Prepare the operand vector.
2107         for (unsigned j = 0; j < E->Scalars.size(); ++j)
2108           Operands.push_back(cast<PHINode>(E->Scalars[j])->
2109                              getIncomingValueForBlock(IBB));
2110
2111         Builder.SetInsertPoint(IBB->getTerminator());
2112         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
2113         Value *Vec = vectorizeTree(Operands);
2114         NewPhi->addIncoming(Vec, IBB);
2115       }
2116
2117       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
2118              "Invalid number of incoming values");
2119       return NewPhi;
2120     }
2121
2122     case Instruction::ExtractElement: {
2123       if (CanReuseExtract(E->Scalars)) {
2124         Value *V = VL0->getOperand(0);
2125         E->VectorizedValue = V;
2126         return V;
2127       }
2128       return Gather(E->Scalars, VecTy);
2129     }
2130     case Instruction::ZExt:
2131     case Instruction::SExt:
2132     case Instruction::FPToUI:
2133     case Instruction::FPToSI:
2134     case Instruction::FPExt:
2135     case Instruction::PtrToInt:
2136     case Instruction::IntToPtr:
2137     case Instruction::SIToFP:
2138     case Instruction::UIToFP:
2139     case Instruction::Trunc:
2140     case Instruction::FPTrunc:
2141     case Instruction::BitCast: {
2142       ValueList INVL;
2143       for (int i = 0, e = E->Scalars.size(); i < e; ++i)
2144         INVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
2145
2146       setInsertPointAfterBundle(E->Scalars);
2147
2148       Value *InVec = vectorizeTree(INVL);
2149
2150       if (Value *V = alreadyVectorized(E->Scalars))
2151         return V;
2152
2153       CastInst *CI = dyn_cast<CastInst>(VL0);
2154       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
2155       E->VectorizedValue = V;
2156       ++NumVectorInstructions;
2157       return V;
2158     }
2159     case Instruction::FCmp:
2160     case Instruction::ICmp: {
2161       ValueList LHSV, RHSV;
2162       for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
2163         LHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
2164         RHSV.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
2165       }
2166
2167       setInsertPointAfterBundle(E->Scalars);
2168
2169       Value *L = vectorizeTree(LHSV);
2170       Value *R = vectorizeTree(RHSV);
2171
2172       if (Value *V = alreadyVectorized(E->Scalars))
2173         return V;
2174
2175       CmpInst::Predicate P0 = dyn_cast<CmpInst>(VL0)->getPredicate();
2176       Value *V;
2177       if (Opcode == Instruction::FCmp)
2178         V = Builder.CreateFCmp(P0, L, R);
2179       else
2180         V = Builder.CreateICmp(P0, L, R);
2181
2182       E->VectorizedValue = V;
2183       ++NumVectorInstructions;
2184       return V;
2185     }
2186     case Instruction::Select: {
2187       ValueList TrueVec, FalseVec, CondVec;
2188       for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
2189         CondVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
2190         TrueVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
2191         FalseVec.push_back(cast<Instruction>(E->Scalars[i])->getOperand(2));
2192       }
2193
2194       setInsertPointAfterBundle(E->Scalars);
2195
2196       Value *Cond = vectorizeTree(CondVec);
2197       Value *True = vectorizeTree(TrueVec);
2198       Value *False = vectorizeTree(FalseVec);
2199
2200       if (Value *V = alreadyVectorized(E->Scalars))
2201         return V;
2202
2203       Value *V = Builder.CreateSelect(Cond, True, False);
2204       E->VectorizedValue = V;
2205       ++NumVectorInstructions;
2206       return V;
2207     }
2208     case Instruction::Add:
2209     case Instruction::FAdd:
2210     case Instruction::Sub:
2211     case Instruction::FSub:
2212     case Instruction::Mul:
2213     case Instruction::FMul:
2214     case Instruction::UDiv:
2215     case Instruction::SDiv:
2216     case Instruction::FDiv:
2217     case Instruction::URem:
2218     case Instruction::SRem:
2219     case Instruction::FRem:
2220     case Instruction::Shl:
2221     case Instruction::LShr:
2222     case Instruction::AShr:
2223     case Instruction::And:
2224     case Instruction::Or:
2225     case Instruction::Xor: {
2226       ValueList LHSVL, RHSVL;
2227       if (isa<BinaryOperator>(VL0) && VL0->isCommutative())
2228         reorderInputsAccordingToOpcode(E->Scalars, LHSVL, RHSVL);
2229       else
2230         for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
2231           LHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(0));
2232           RHSVL.push_back(cast<Instruction>(E->Scalars[i])->getOperand(1));
2233         }
2234
2235       setInsertPointAfterBundle(E->Scalars);
2236
2237       Value *LHS = vectorizeTree(LHSVL);
2238       Value *RHS = vectorizeTree(RHSVL);
2239
2240       if (LHS == RHS && isa<Instruction>(LHS)) {
2241         assert((VL0->getOperand(0) == VL0->getOperand(1)) && "Invalid order");
2242       }
2243
2244       if (Value *V = alreadyVectorized(E->Scalars))
2245         return V;
2246
2247       BinaryOperator *BinOp = cast<BinaryOperator>(VL0);
2248       Value *V = Builder.CreateBinOp(BinOp->getOpcode(), LHS, RHS);
2249       E->VectorizedValue = V;
2250       propagateIRFlags(E->VectorizedValue, E->Scalars);
2251       ++NumVectorInstructions;
2252
2253       if (Instruction *I = dyn_cast<Instruction>(V))
2254         return propagateMetadata(I, E->Scalars);
2255
2256       return V;
2257     }
2258     case Instruction::Load: {
2259       // Loads are inserted at the head of the tree because we don't want to
2260       // sink them all the way down past store instructions.
2261       setInsertPointAfterBundle(E->Scalars);
2262
2263       LoadInst *LI = cast<LoadInst>(VL0);
2264       Type *ScalarLoadTy = LI->getType();
2265       unsigned AS = LI->getPointerAddressSpace();
2266
2267       Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(),
2268                                             VecTy->getPointerTo(AS));
2269
2270       // The pointer operand uses an in-tree scalar so we add the new BitCast to
2271       // ExternalUses list to make sure that an extract will be generated in the
2272       // future.
2273       if (ScalarToTreeEntry.count(LI->getPointerOperand()))
2274         ExternalUses.push_back(
2275             ExternalUser(LI->getPointerOperand(), cast<User>(VecPtr), 0));
2276
2277       unsigned Alignment = LI->getAlignment();
2278       LI = Builder.CreateLoad(VecPtr);
2279       if (!Alignment)
2280         Alignment = DL->getABITypeAlignment(ScalarLoadTy);
2281       LI->setAlignment(Alignment);
2282       E->VectorizedValue = LI;
2283       ++NumVectorInstructions;
2284       return propagateMetadata(LI, E->Scalars);
2285     }
2286     case Instruction::Store: {
2287       StoreInst *SI = cast<StoreInst>(VL0);
2288       unsigned Alignment = SI->getAlignment();
2289       unsigned AS = SI->getPointerAddressSpace();
2290
2291       ValueList ValueOp;
2292       for (int i = 0, e = E->Scalars.size(); i < e; ++i)
2293         ValueOp.push_back(cast<StoreInst>(E->Scalars[i])->getValueOperand());
2294
2295       setInsertPointAfterBundle(E->Scalars);
2296
2297       Value *VecValue = vectorizeTree(ValueOp);
2298       Value *VecPtr = Builder.CreateBitCast(SI->getPointerOperand(),
2299                                             VecTy->getPointerTo(AS));
2300       StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
2301
2302       // The pointer operand uses an in-tree scalar so we add the new BitCast to
2303       // ExternalUses list to make sure that an extract will be generated in the
2304       // future.
2305       if (ScalarToTreeEntry.count(SI->getPointerOperand()))
2306         ExternalUses.push_back(
2307             ExternalUser(SI->getPointerOperand(), cast<User>(VecPtr), 0));
2308
2309       if (!Alignment)
2310         Alignment = DL->getABITypeAlignment(SI->getValueOperand()->getType());
2311       S->setAlignment(Alignment);
2312       E->VectorizedValue = S;
2313       ++NumVectorInstructions;
2314       return propagateMetadata(S, E->Scalars);
2315     }
2316     case Instruction::GetElementPtr: {
2317       setInsertPointAfterBundle(E->Scalars);
2318
2319       ValueList Op0VL;
2320       for (int i = 0, e = E->Scalars.size(); i < e; ++i)
2321         Op0VL.push_back(cast<GetElementPtrInst>(E->Scalars[i])->getOperand(0));
2322
2323       Value *Op0 = vectorizeTree(Op0VL);
2324
2325       std::vector<Value *> OpVecs;
2326       for (int j = 1, e = cast<GetElementPtrInst>(VL0)->getNumOperands(); j < e;
2327            ++j) {
2328         ValueList OpVL;
2329         for (int i = 0, e = E->Scalars.size(); i < e; ++i)
2330           OpVL.push_back(cast<GetElementPtrInst>(E->Scalars[i])->getOperand(j));
2331
2332         Value *OpVec = vectorizeTree(OpVL);
2333         OpVecs.push_back(OpVec);
2334       }
2335
2336       Value *V = Builder.CreateGEP(Op0, OpVecs);
2337       E->VectorizedValue = V;
2338       ++NumVectorInstructions;
2339
2340       if (Instruction *I = dyn_cast<Instruction>(V))
2341         return propagateMetadata(I, E->Scalars);
2342
2343       return V;
2344     }
2345     case Instruction::Call: {
2346       CallInst *CI = cast<CallInst>(VL0);
2347       setInsertPointAfterBundle(E->Scalars);
2348       Function *FI;
2349       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
2350       Value *ScalarArg = nullptr;
2351       if (CI && (FI = CI->getCalledFunction())) {
2352         IID = (Intrinsic::ID) FI->getIntrinsicID();
2353       }
2354       std::vector<Value *> OpVecs;
2355       for (int j = 0, e = CI->getNumArgOperands(); j < e; ++j) {
2356         ValueList OpVL;
2357         // ctlz,cttz and powi are special intrinsics whose second argument is
2358         // a scalar. This argument should not be vectorized.
2359         if (hasVectorInstrinsicScalarOpd(IID, 1) && j == 1) {
2360           CallInst *CEI = cast<CallInst>(E->Scalars[0]);
2361           ScalarArg = CEI->getArgOperand(j);
2362           OpVecs.push_back(CEI->getArgOperand(j));
2363           continue;
2364         }
2365         for (int i = 0, e = E->Scalars.size(); i < e; ++i) {
2366           CallInst *CEI = cast<CallInst>(E->Scalars[i]);
2367           OpVL.push_back(CEI->getArgOperand(j));
2368         }
2369
2370         Value *OpVec = vectorizeTree(OpVL);
2371         DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
2372         OpVecs.push_back(OpVec);
2373       }
2374
2375       Module *M = F->getParent();
2376       Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
2377       Type *Tys[] = { VectorType::get(CI->getType(), E->Scalars.size()) };
2378       Function *CF = Intrinsic::getDeclaration(M, ID, Tys);
2379       Value *V = Builder.CreateCall(CF, OpVecs);
2380
2381       // The scalar argument uses an in-tree scalar so we add the new vectorized
2382       // call to ExternalUses list to make sure that an extract will be
2383       // generated in the future.
2384       if (ScalarArg && ScalarToTreeEntry.count(ScalarArg))
2385         ExternalUses.push_back(ExternalUser(ScalarArg, cast<User>(V), 0));
2386
2387       E->VectorizedValue = V;
2388       ++NumVectorInstructions;
2389       return V;
2390     }
2391     case Instruction::ShuffleVector: {
2392       ValueList LHSVL, RHSVL;
2393       assert(isa<BinaryOperator>(VL0) && "Invalid Shuffle Vector Operand");
2394       reorderAltShuffleOperands(E->Scalars, LHSVL, RHSVL);
2395       setInsertPointAfterBundle(E->Scalars);
2396
2397       Value *LHS = vectorizeTree(LHSVL);
2398       Value *RHS = vectorizeTree(RHSVL);
2399
2400       if (Value *V = alreadyVectorized(E->Scalars))
2401         return V;
2402
2403       // Create a vector of LHS op1 RHS
2404       BinaryOperator *BinOp0 = cast<BinaryOperator>(VL0);
2405       Value *V0 = Builder.CreateBinOp(BinOp0->getOpcode(), LHS, RHS);
2406
2407       // Create a vector of LHS op2 RHS
2408       Instruction *VL1 = cast<Instruction>(E->Scalars[1]);
2409       BinaryOperator *BinOp1 = cast<BinaryOperator>(VL1);
2410       Value *V1 = Builder.CreateBinOp(BinOp1->getOpcode(), LHS, RHS);
2411
2412       // Create shuffle to take alternate operations from the vector.
2413       // Also, gather up odd and even scalar ops to propagate IR flags to
2414       // each vector operation.
2415       ValueList OddScalars, EvenScalars;
2416       unsigned e = E->Scalars.size();
2417       SmallVector<Constant *, 8> Mask(e);
2418       for (unsigned i = 0; i < e; ++i) {
2419         if (i & 1) {
2420           Mask[i] = Builder.getInt32(e + i);
2421           OddScalars.push_back(E->Scalars[i]);
2422         } else {
2423           Mask[i] = Builder.getInt32(i);
2424           EvenScalars.push_back(E->Scalars[i]);
2425         }
2426       }
2427
2428       Value *ShuffleMask = ConstantVector::get(Mask);
2429       propagateIRFlags(V0, EvenScalars);
2430       propagateIRFlags(V1, OddScalars);
2431
2432       Value *V = Builder.CreateShuffleVector(V0, V1, ShuffleMask);
2433       E->VectorizedValue = V;
2434       ++NumVectorInstructions;
2435       if (Instruction *I = dyn_cast<Instruction>(V))
2436         return propagateMetadata(I, E->Scalars);
2437
2438       return V;
2439     }
2440     default:
2441     llvm_unreachable("unknown inst");
2442   }
2443   return nullptr;
2444 }
2445
2446 Value *BoUpSLP::vectorizeTree() {
2447   
2448   // All blocks must be scheduled before any instructions are inserted.
2449   for (auto &BSIter : BlocksSchedules) {
2450     scheduleBlock(BSIter.second.get());
2451   }
2452
2453   Builder.SetInsertPoint(F->getEntryBlock().begin());
2454   vectorizeTree(&VectorizableTree[0]);
2455
2456   DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
2457
2458   // Extract all of the elements with the external uses.
2459   for (UserList::iterator it = ExternalUses.begin(), e = ExternalUses.end();
2460        it != e; ++it) {
2461     Value *Scalar = it->Scalar;
2462     llvm::User *User = it->User;
2463
2464     // Skip users that we already RAUW. This happens when one instruction
2465     // has multiple uses of the same value.
2466     if (std::find(Scalar->user_begin(), Scalar->user_end(), User) ==
2467         Scalar->user_end())
2468       continue;
2469     assert(ScalarToTreeEntry.count(Scalar) && "Invalid scalar");
2470
2471     int Idx = ScalarToTreeEntry[Scalar];
2472     TreeEntry *E = &VectorizableTree[Idx];
2473     assert(!E->NeedToGather && "Extracting from a gather list");
2474
2475     Value *Vec = E->VectorizedValue;
2476     assert(Vec && "Can't find vectorizable value");
2477
2478     Value *Lane = Builder.getInt32(it->Lane);
2479     // Generate extracts for out-of-tree users.
2480     // Find the insertion point for the extractelement lane.
2481     if (isa<Instruction>(Vec)){
2482       if (PHINode *PH = dyn_cast<PHINode>(User)) {
2483         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
2484           if (PH->getIncomingValue(i) == Scalar) {
2485             Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
2486             Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2487             CSEBlocks.insert(PH->getIncomingBlock(i));
2488             PH->setOperand(i, Ex);
2489           }
2490         }
2491       } else {
2492         Builder.SetInsertPoint(cast<Instruction>(User));
2493         Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2494         CSEBlocks.insert(cast<Instruction>(User)->getParent());
2495         User->replaceUsesOfWith(Scalar, Ex);
2496      }
2497     } else {
2498       Builder.SetInsertPoint(F->getEntryBlock().begin());
2499       Value *Ex = Builder.CreateExtractElement(Vec, Lane);
2500       CSEBlocks.insert(&F->getEntryBlock());
2501       User->replaceUsesOfWith(Scalar, Ex);
2502     }
2503
2504     DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
2505   }
2506
2507   // For each vectorized value:
2508   for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
2509     TreeEntry *Entry = &VectorizableTree[EIdx];
2510
2511     // For each lane:
2512     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
2513       Value *Scalar = Entry->Scalars[Lane];
2514       // No need to handle users of gathered values.
2515       if (Entry->NeedToGather)
2516         continue;
2517
2518       assert(Entry->VectorizedValue && "Can't find vectorizable value");
2519
2520       Type *Ty = Scalar->getType();
2521       if (!Ty->isVoidTy()) {
2522 #ifndef NDEBUG
2523         for (User *U : Scalar->users()) {
2524           DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
2525
2526           assert((ScalarToTreeEntry.count(U) ||
2527                   // It is legal to replace users in the ignorelist by undef.
2528                   (std::find(UserIgnoreList.begin(), UserIgnoreList.end(), U) !=
2529                    UserIgnoreList.end())) &&
2530                  "Replacing out-of-tree value with undef");
2531         }
2532 #endif
2533         Value *Undef = UndefValue::get(Ty);
2534         Scalar->replaceAllUsesWith(Undef);
2535       }
2536       DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
2537       eraseInstruction(cast<Instruction>(Scalar));
2538     }
2539   }
2540
2541   Builder.ClearInsertionPoint();
2542
2543   return VectorizableTree[0].VectorizedValue;
2544 }
2545
2546 void BoUpSLP::optimizeGatherSequence() {
2547   DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
2548         << " gather sequences instructions.\n");
2549   // LICM InsertElementInst sequences.
2550   for (SetVector<Instruction *>::iterator it = GatherSeq.begin(),
2551        e = GatherSeq.end(); it != e; ++it) {
2552     InsertElementInst *Insert = dyn_cast<InsertElementInst>(*it);
2553
2554     if (!Insert)
2555       continue;
2556
2557     // Check if this block is inside a loop.
2558     Loop *L = LI->getLoopFor(Insert->getParent());
2559     if (!L)
2560       continue;
2561
2562     // Check if it has a preheader.
2563     BasicBlock *PreHeader = L->getLoopPreheader();
2564     if (!PreHeader)
2565       continue;
2566
2567     // If the vector or the element that we insert into it are
2568     // instructions that are defined in this basic block then we can't
2569     // hoist this instruction.
2570     Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
2571     Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
2572     if (CurrVec && L->contains(CurrVec))
2573       continue;
2574     if (NewElem && L->contains(NewElem))
2575       continue;
2576
2577     // We can hoist this instruction. Move it to the pre-header.
2578     Insert->moveBefore(PreHeader->getTerminator());
2579   }
2580
2581   // Make a list of all reachable blocks in our CSE queue.
2582   SmallVector<const DomTreeNode *, 8> CSEWorkList;
2583   CSEWorkList.reserve(CSEBlocks.size());
2584   for (BasicBlock *BB : CSEBlocks)
2585     if (DomTreeNode *N = DT->getNode(BB)) {
2586       assert(DT->isReachableFromEntry(N));
2587       CSEWorkList.push_back(N);
2588     }
2589
2590   // Sort blocks by domination. This ensures we visit a block after all blocks
2591   // dominating it are visited.
2592   std::stable_sort(CSEWorkList.begin(), CSEWorkList.end(),
2593                    [this](const DomTreeNode *A, const DomTreeNode *B) {
2594     return DT->properlyDominates(A, B);
2595   });
2596
2597   // Perform O(N^2) search over the gather sequences and merge identical
2598   // instructions. TODO: We can further optimize this scan if we split the
2599   // instructions into different buckets based on the insert lane.
2600   SmallVector<Instruction *, 16> Visited;
2601   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
2602     assert((I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
2603            "Worklist not sorted properly!");
2604     BasicBlock *BB = (*I)->getBlock();
2605     // For all instructions in blocks containing gather sequences:
2606     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
2607       Instruction *In = it++;
2608       if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
2609         continue;
2610
2611       // Check if we can replace this instruction with any of the
2612       // visited instructions.
2613       for (SmallVectorImpl<Instruction *>::iterator v = Visited.begin(),
2614                                                     ve = Visited.end();
2615            v != ve; ++v) {
2616         if (In->isIdenticalTo(*v) &&
2617             DT->dominates((*v)->getParent(), In->getParent())) {
2618           In->replaceAllUsesWith(*v);
2619           eraseInstruction(In);
2620           In = nullptr;
2621           break;
2622         }
2623       }
2624       if (In) {
2625         assert(std::find(Visited.begin(), Visited.end(), In) == Visited.end());
2626         Visited.push_back(In);
2627       }
2628     }
2629   }
2630   CSEBlocks.clear();
2631   GatherSeq.clear();
2632 }
2633
2634 // Groups the instructions to a bundle (which is then a single scheduling entity)
2635 // and schedules instructions until the bundle gets ready.
2636 bool BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL,
2637                                                  BoUpSLP *SLP) {
2638   if (isa<PHINode>(VL[0]))
2639     return true;
2640
2641   // Initialize the instruction bundle.
2642   Instruction *OldScheduleEnd = ScheduleEnd;
2643   ScheduleData *PrevInBundle = nullptr;
2644   ScheduleData *Bundle = nullptr;
2645   bool ReSchedule = false;
2646   DEBUG(dbgs() << "SLP:  bundle: " << *VL[0] << "\n");
2647   for (Value *V : VL) {
2648     extendSchedulingRegion(V);
2649     ScheduleData *BundleMember = getScheduleData(V);
2650     assert(BundleMember &&
2651            "no ScheduleData for bundle member (maybe not in same basic block)");
2652     if (BundleMember->IsScheduled) {
2653       // A bundle member was scheduled as single instruction before and now
2654       // needs to be scheduled as part of the bundle. We just get rid of the
2655       // existing schedule.
2656       DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
2657                    << " was already scheduled\n");
2658       ReSchedule = true;
2659     }
2660     assert(BundleMember->isSchedulingEntity() &&
2661            "bundle member already part of other bundle");
2662     if (PrevInBundle) {
2663       PrevInBundle->NextInBundle = BundleMember;
2664     } else {
2665       Bundle = BundleMember;
2666     }
2667     BundleMember->UnscheduledDepsInBundle = 0;
2668     Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
2669
2670     // Group the instructions to a bundle.
2671     BundleMember->FirstInBundle = Bundle;
2672     PrevInBundle = BundleMember;
2673   }
2674   if (ScheduleEnd != OldScheduleEnd) {
2675     // The scheduling region got new instructions at the lower end (or it is a
2676     // new region for the first bundle). This makes it necessary to
2677     // recalculate all dependencies.
2678     // It is seldom that this needs to be done a second time after adding the
2679     // initial bundle to the region.
2680     for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2681       ScheduleData *SD = getScheduleData(I);
2682       SD->clearDependencies();
2683     }
2684     ReSchedule = true;
2685   }
2686   if (ReSchedule) {
2687     resetSchedule();
2688     initialFillReadyList(ReadyInsts);
2689   }
2690
2691   DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle << " in block "
2692                << BB->getName() << "\n");
2693
2694   calculateDependencies(Bundle, true, SLP);
2695
2696   // Now try to schedule the new bundle. As soon as the bundle is "ready" it
2697   // means that there are no cyclic dependencies and we can schedule it.
2698   // Note that's important that we don't "schedule" the bundle yet (see
2699   // cancelScheduling).
2700   while (!Bundle->isReady() && !ReadyInsts.empty()) {
2701
2702     ScheduleData *pickedSD = ReadyInsts.back();
2703     ReadyInsts.pop_back();
2704
2705     if (pickedSD->isSchedulingEntity() && pickedSD->isReady()) {
2706       schedule(pickedSD, ReadyInsts);
2707     }
2708   }
2709   return Bundle->isReady();
2710 }
2711
2712 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL) {
2713   if (isa<PHINode>(VL[0]))
2714     return;
2715
2716   ScheduleData *Bundle = getScheduleData(VL[0]);
2717   DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
2718   assert(!Bundle->IsScheduled &&
2719          "Can't cancel bundle which is already scheduled");
2720   assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
2721          "tried to unbundle something which is not a bundle");
2722
2723   // Un-bundle: make single instructions out of the bundle.
2724   ScheduleData *BundleMember = Bundle;
2725   while (BundleMember) {
2726     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
2727     BundleMember->FirstInBundle = BundleMember;
2728     ScheduleData *Next = BundleMember->NextInBundle;
2729     BundleMember->NextInBundle = nullptr;
2730     BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
2731     if (BundleMember->UnscheduledDepsInBundle == 0) {
2732       ReadyInsts.insert(BundleMember);
2733     }
2734     BundleMember = Next;
2735   }
2736 }
2737
2738 void BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V) {
2739   if (getScheduleData(V))
2740     return;
2741   Instruction *I = dyn_cast<Instruction>(V);
2742   assert(I && "bundle member must be an instruction");
2743   assert(!isa<PHINode>(I) && "phi nodes don't need to be scheduled");
2744   if (!ScheduleStart) {
2745     // It's the first instruction in the new region.
2746     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
2747     ScheduleStart = I;
2748     ScheduleEnd = I->getNextNode();
2749     assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
2750     DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
2751     return;
2752   }
2753   // Search up and down at the same time, because we don't know if the new
2754   // instruction is above or below the existing scheduling region.
2755   BasicBlock::reverse_iterator UpIter(ScheduleStart);
2756   BasicBlock::reverse_iterator UpperEnd = BB->rend();
2757   BasicBlock::iterator DownIter(ScheduleEnd);
2758   BasicBlock::iterator LowerEnd = BB->end();
2759   for (;;) {
2760     if (UpIter != UpperEnd) {
2761       if (&*UpIter == I) {
2762         initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
2763         ScheduleStart = I;
2764         DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I << "\n");
2765         return;
2766       }
2767       UpIter++;
2768     }
2769     if (DownIter != LowerEnd) {
2770       if (&*DownIter == I) {
2771         initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
2772                          nullptr);
2773         ScheduleEnd = I->getNextNode();
2774         assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
2775         DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
2776         return;
2777       }
2778       DownIter++;
2779     }
2780     assert((UpIter != UpperEnd || DownIter != LowerEnd) &&
2781            "instruction not found in block");
2782   }
2783 }
2784
2785 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
2786                                                 Instruction *ToI,
2787                                                 ScheduleData *PrevLoadStore,
2788                                                 ScheduleData *NextLoadStore) {
2789   ScheduleData *CurrentLoadStore = PrevLoadStore;
2790   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
2791     ScheduleData *SD = ScheduleDataMap[I];
2792     if (!SD) {
2793       // Allocate a new ScheduleData for the instruction.
2794       if (ChunkPos >= ChunkSize) {
2795         ScheduleDataChunks.push_back(
2796             llvm::make_unique<ScheduleData[]>(ChunkSize));
2797         ChunkPos = 0;
2798       }
2799       SD = &(ScheduleDataChunks.back()[ChunkPos++]);
2800       ScheduleDataMap[I] = SD;
2801       SD->Inst = I;
2802     }
2803     assert(!isInSchedulingRegion(SD) &&
2804            "new ScheduleData already in scheduling region");
2805     SD->init(SchedulingRegionID);
2806
2807     if (I->mayReadOrWriteMemory()) {
2808       // Update the linked list of memory accessing instructions.
2809       if (CurrentLoadStore) {
2810         CurrentLoadStore->NextLoadStore = SD;
2811       } else {
2812         FirstLoadStoreInRegion = SD;
2813       }
2814       CurrentLoadStore = SD;
2815     }
2816   }
2817   if (NextLoadStore) {
2818     if (CurrentLoadStore)
2819       CurrentLoadStore->NextLoadStore = NextLoadStore;
2820   } else {
2821     LastLoadStoreInRegion = CurrentLoadStore;
2822   }
2823 }
2824
2825 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
2826                                                      bool InsertInReadyList,
2827                                                      BoUpSLP *SLP) {
2828   assert(SD->isSchedulingEntity());
2829
2830   SmallVector<ScheduleData *, 10> WorkList;
2831   WorkList.push_back(SD);
2832
2833   while (!WorkList.empty()) {
2834     ScheduleData *SD = WorkList.back();
2835     WorkList.pop_back();
2836
2837     ScheduleData *BundleMember = SD;
2838     while (BundleMember) {
2839       assert(isInSchedulingRegion(BundleMember));
2840       if (!BundleMember->hasValidDependencies()) {
2841
2842         DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember << "\n");
2843         BundleMember->Dependencies = 0;
2844         BundleMember->resetUnscheduledDeps();
2845
2846         // Handle def-use chain dependencies.
2847         for (User *U : BundleMember->Inst->users()) {
2848           if (isa<Instruction>(U)) {
2849             ScheduleData *UseSD = getScheduleData(U);
2850             if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
2851               BundleMember->Dependencies++;
2852               ScheduleData *DestBundle = UseSD->FirstInBundle;
2853               if (!DestBundle->IsScheduled) {
2854                 BundleMember->incrementUnscheduledDeps(1);
2855               }
2856               if (!DestBundle->hasValidDependencies()) {
2857                 WorkList.push_back(DestBundle);
2858               }
2859             }
2860           } else {
2861             // I'm not sure if this can ever happen. But we need to be safe.
2862             // This lets the instruction/bundle never be scheduled and eventally
2863             // disable vectorization.
2864             BundleMember->Dependencies++;
2865             BundleMember->incrementUnscheduledDeps(1);
2866           }
2867         }
2868
2869         // Handle the memory dependencies.
2870         ScheduleData *DepDest = BundleMember->NextLoadStore;
2871         if (DepDest) {
2872           Instruction *SrcInst = BundleMember->Inst;
2873           AliasAnalysis::Location SrcLoc = getLocation(SrcInst, SLP->AA);
2874           bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
2875           unsigned numAliased = 0;
2876           unsigned DistToSrc = 1;
2877
2878           while (DepDest) {
2879             assert(isInSchedulingRegion(DepDest));
2880
2881             // We have two limits to reduce the complexity:
2882             // 1) AliasedCheckLimit: It's a small limit to reduce calls to
2883             //    SLP->isAliased (which is the expensive part in this loop).
2884             // 2) MaxMemDepDistance: It's for very large blocks and it aborts
2885             //    the whole loop (even if the loop is fast, it's quadratic).
2886             //    It's important for the loop break condition (see below) to
2887             //    check this limit even between two read-only instructions.
2888             if (DistToSrc >= MaxMemDepDistance ||
2889                     ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
2890                      (numAliased >= AliasedCheckLimit ||
2891                       SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
2892
2893               // We increment the counter only if the locations are aliased
2894               // (instead of counting all alias checks). This gives a better
2895               // balance between reduced runtime and accurate dependencies.
2896               numAliased++;
2897
2898               DepDest->MemoryDependencies.push_back(BundleMember);
2899               BundleMember->Dependencies++;
2900               ScheduleData *DestBundle = DepDest->FirstInBundle;
2901               if (!DestBundle->IsScheduled) {
2902                 BundleMember->incrementUnscheduledDeps(1);
2903               }
2904               if (!DestBundle->hasValidDependencies()) {
2905                 WorkList.push_back(DestBundle);
2906               }
2907             }
2908             DepDest = DepDest->NextLoadStore;
2909
2910             // Example, explaining the loop break condition: Let's assume our
2911             // starting instruction is i0 and MaxMemDepDistance = 3.
2912             //
2913             //                      +--------v--v--v
2914             //             i0,i1,i2,i3,i4,i5,i6,i7,i8
2915             //             +--------^--^--^
2916             //
2917             // MaxMemDepDistance let us stop alias-checking at i3 and we add
2918             // dependencies from i0 to i3,i4,.. (even if they are not aliased).
2919             // Previously we already added dependencies from i3 to i6,i7,i8
2920             // (because of MaxMemDepDistance). As we added a dependency from
2921             // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
2922             // and we can abort this loop at i6.
2923             if (DistToSrc >= 2 * MaxMemDepDistance)
2924                 break;
2925             DistToSrc++;
2926           }
2927         }
2928       }
2929       BundleMember = BundleMember->NextInBundle;
2930     }
2931     if (InsertInReadyList && SD->isReady()) {
2932       ReadyInsts.push_back(SD);
2933       DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst << "\n");
2934     }
2935   }
2936 }
2937
2938 void BoUpSLP::BlockScheduling::resetSchedule() {
2939   assert(ScheduleStart &&
2940          "tried to reset schedule on block which has not been scheduled");
2941   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2942     ScheduleData *SD = getScheduleData(I);
2943     assert(isInSchedulingRegion(SD));
2944     SD->IsScheduled = false;
2945     SD->resetUnscheduledDeps();
2946   }
2947   ReadyInsts.clear();
2948 }
2949
2950 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
2951   
2952   if (!BS->ScheduleStart)
2953     return;
2954   
2955   DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
2956
2957   BS->resetSchedule();
2958
2959   // For the real scheduling we use a more sophisticated ready-list: it is
2960   // sorted by the original instruction location. This lets the final schedule
2961   // be as  close as possible to the original instruction order.
2962   struct ScheduleDataCompare {
2963     bool operator()(ScheduleData *SD1, ScheduleData *SD2) {
2964       return SD2->SchedulingPriority < SD1->SchedulingPriority;
2965     }
2966   };
2967   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
2968
2969   // Ensure that all depencency data is updated and fill the ready-list with
2970   // initial instructions.
2971   int Idx = 0;
2972   int NumToSchedule = 0;
2973   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
2974        I = I->getNextNode()) {
2975     ScheduleData *SD = BS->getScheduleData(I);
2976     assert(
2977         SD->isPartOfBundle() == (ScalarToTreeEntry.count(SD->Inst) != 0) &&
2978         "scheduler and vectorizer have different opinion on what is a bundle");
2979     SD->FirstInBundle->SchedulingPriority = Idx++;
2980     if (SD->isSchedulingEntity()) {
2981       BS->calculateDependencies(SD, false, this);
2982       NumToSchedule++;
2983     }
2984   }
2985   BS->initialFillReadyList(ReadyInsts);
2986
2987   Instruction *LastScheduledInst = BS->ScheduleEnd;
2988
2989   // Do the "real" scheduling.
2990   while (!ReadyInsts.empty()) {
2991     ScheduleData *picked = *ReadyInsts.begin();
2992     ReadyInsts.erase(ReadyInsts.begin());
2993
2994     // Move the scheduled instruction(s) to their dedicated places, if not
2995     // there yet.
2996     ScheduleData *BundleMember = picked;
2997     while (BundleMember) {
2998       Instruction *pickedInst = BundleMember->Inst;
2999       if (LastScheduledInst->getNextNode() != pickedInst) {
3000         BS->BB->getInstList().remove(pickedInst);
3001         BS->BB->getInstList().insert(LastScheduledInst, pickedInst);
3002       }
3003       LastScheduledInst = pickedInst;
3004       BundleMember = BundleMember->NextInBundle;
3005     }
3006
3007     BS->schedule(picked, ReadyInsts);
3008     NumToSchedule--;
3009   }
3010   assert(NumToSchedule == 0 && "could not schedule all instructions");
3011
3012   // Avoid duplicate scheduling of the block.
3013   BS->ScheduleStart = nullptr;
3014 }
3015
3016 /// The SLPVectorizer Pass.
3017 struct SLPVectorizer : public FunctionPass {
3018   typedef SmallVector<StoreInst *, 8> StoreList;
3019   typedef MapVector<Value *, StoreList> StoreListMap;
3020
3021   /// Pass identification, replacement for typeid
3022   static char ID;
3023
3024   explicit SLPVectorizer() : FunctionPass(ID) {
3025     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
3026   }
3027
3028   ScalarEvolution *SE;
3029   const DataLayout *DL;
3030   TargetTransformInfo *TTI;
3031   TargetLibraryInfo *TLI;
3032   AliasAnalysis *AA;
3033   LoopInfo *LI;
3034   DominatorTree *DT;
3035   AssumptionCache *AC;
3036
3037   bool runOnFunction(Function &F) override {
3038     if (skipOptnoneFunction(F))
3039       return false;
3040
3041     SE = &getAnalysis<ScalarEvolution>();
3042     DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
3043     DL = DLP ? &DLP->getDataLayout() : nullptr;
3044     TTI = &getAnalysis<TargetTransformInfo>();
3045     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
3046     TLI = TLIP ? &TLIP->getTLI() : nullptr;
3047     AA = &getAnalysis<AliasAnalysis>();
3048     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
3049     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3050     AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
3051
3052     StoreRefs.clear();
3053     bool Changed = false;
3054
3055     // If the target claims to have no vector registers don't attempt
3056     // vectorization.
3057     if (!TTI->getNumberOfRegisters(true))
3058       return false;
3059
3060     // Must have DataLayout. We can't require it because some tests run w/o
3061     // triple.
3062     if (!DL)
3063       return false;
3064
3065     // Don't vectorize when the attribute NoImplicitFloat is used.
3066     if (F.hasFnAttribute(Attribute::NoImplicitFloat))
3067       return false;
3068
3069     DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
3070
3071     // Use the bottom up slp vectorizer to construct chains that start with
3072     // store instructions.
3073     BoUpSLP R(&F, SE, DL, TTI, TLI, AA, LI, DT, AC);
3074
3075     // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
3076     // delete instructions.
3077
3078     // Scan the blocks in the function in post order.
3079     for (po_iterator<BasicBlock*> it = po_begin(&F.getEntryBlock()),
3080          e = po_end(&F.getEntryBlock()); it != e; ++it) {
3081       BasicBlock *BB = *it;
3082       // Vectorize trees that end at stores.
3083       if (unsigned count = collectStores(BB, R)) {
3084         (void)count;
3085         DEBUG(dbgs() << "SLP: Found " << count << " stores to vectorize.\n");
3086         Changed |= vectorizeStoreChains(R);
3087       }
3088
3089       // Vectorize trees that end at reductions.
3090       Changed |= vectorizeChainsInBlock(BB, R);
3091     }
3092
3093     if (Changed) {
3094       R.optimizeGatherSequence();
3095       DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
3096       DEBUG(verifyFunction(F));
3097     }
3098     return Changed;
3099   }
3100
3101   void getAnalysisUsage(AnalysisUsage &AU) const override {
3102     FunctionPass::getAnalysisUsage(AU);
3103     AU.addRequired<AssumptionCacheTracker>();
3104     AU.addRequired<ScalarEvolution>();
3105     AU.addRequired<AliasAnalysis>();
3106     AU.addRequired<TargetTransformInfo>();
3107     AU.addRequired<LoopInfoWrapperPass>();
3108     AU.addRequired<DominatorTreeWrapperPass>();
3109     AU.addPreserved<LoopInfoWrapperPass>();
3110     AU.addPreserved<DominatorTreeWrapperPass>();
3111     AU.setPreservesCFG();
3112   }
3113
3114 private:
3115
3116   /// \brief Collect memory references and sort them according to their base
3117   /// object. We sort the stores to their base objects to reduce the cost of the
3118   /// quadratic search on the stores. TODO: We can further reduce this cost
3119   /// if we flush the chain creation every time we run into a memory barrier.
3120   unsigned collectStores(BasicBlock *BB, BoUpSLP &R);
3121
3122   /// \brief Try to vectorize a chain that starts at two arithmetic instrs.
3123   bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R);
3124
3125   /// \brief Try to vectorize a list of operands.
3126   /// \@param BuildVector A list of users to ignore for the purpose of
3127   ///                     scheduling and that don't need extracting.
3128   /// \returns true if a value was vectorized.
3129   bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
3130                           ArrayRef<Value *> BuildVector = None,
3131                           bool allowReorder = false);
3132
3133   /// \brief Try to vectorize a chain that may start at the operands of \V;
3134   bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
3135
3136   /// \brief Vectorize the stores that were collected in StoreRefs.
3137   bool vectorizeStoreChains(BoUpSLP &R);
3138
3139   /// \brief Scan the basic block and look for patterns that are likely to start
3140   /// a vectorization chain.
3141   bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
3142
3143   bool vectorizeStoreChain(ArrayRef<Value *> Chain, int CostThreshold,
3144                            BoUpSLP &R);
3145
3146   bool vectorizeStores(ArrayRef<StoreInst *> Stores, int costThreshold,
3147                        BoUpSLP &R);
3148 private:
3149   StoreListMap StoreRefs;
3150 };
3151
3152 /// \brief Check that the Values in the slice in VL array are still existent in
3153 /// the WeakVH array.
3154 /// Vectorization of part of the VL array may cause later values in the VL array
3155 /// to become invalid. We track when this has happened in the WeakVH array.
3156 static bool hasValueBeenRAUWed(ArrayRef<Value *> &VL,
3157                                SmallVectorImpl<WeakVH> &VH,
3158                                unsigned SliceBegin,
3159                                unsigned SliceSize) {
3160   for (unsigned i = SliceBegin; i < SliceBegin + SliceSize; ++i)
3161     if (VH[i] != VL[i])
3162       return true;
3163
3164   return false;
3165 }
3166
3167 bool SLPVectorizer::vectorizeStoreChain(ArrayRef<Value *> Chain,
3168                                           int CostThreshold, BoUpSLP &R) {
3169   unsigned ChainLen = Chain.size();
3170   DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
3171         << "\n");
3172   Type *StoreTy = cast<StoreInst>(Chain[0])->getValueOperand()->getType();
3173   unsigned Sz = DL->getTypeSizeInBits(StoreTy);
3174   unsigned VF = MinVecRegSize / Sz;
3175
3176   if (!isPowerOf2_32(Sz) || VF < 2)
3177     return false;
3178
3179   // Keep track of values that were deleted by vectorizing in the loop below.
3180   SmallVector<WeakVH, 8> TrackValues(Chain.begin(), Chain.end());
3181
3182   bool Changed = false;
3183   // Look for profitable vectorizable trees at all offsets, starting at zero.
3184   for (unsigned i = 0, e = ChainLen; i < e; ++i) {
3185     if (i + VF > e)
3186       break;
3187
3188     // Check that a previous iteration of this loop did not delete the Value.
3189     if (hasValueBeenRAUWed(Chain, TrackValues, i, VF))
3190       continue;
3191
3192     DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
3193           << "\n");
3194     ArrayRef<Value *> Operands = Chain.slice(i, VF);
3195
3196     R.buildTree(Operands);
3197
3198     int Cost = R.getTreeCost();
3199
3200     DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
3201     if (Cost < CostThreshold) {
3202       DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
3203       R.vectorizeTree();
3204
3205       // Move to the next bundle.
3206       i += VF - 1;
3207       Changed = true;
3208     }
3209   }
3210
3211   return Changed;
3212 }
3213
3214 bool SLPVectorizer::vectorizeStores(ArrayRef<StoreInst *> Stores,
3215                                     int costThreshold, BoUpSLP &R) {
3216   SetVector<Value *> Heads, Tails;
3217   SmallDenseMap<Value *, Value *> ConsecutiveChain;
3218
3219   // We may run into multiple chains that merge into a single chain. We mark the
3220   // stores that we vectorized so that we don't visit the same store twice.
3221   BoUpSLP::ValueSet VectorizedStores;
3222   bool Changed = false;
3223
3224   // Do a quadratic search on all of the given stores and find
3225   // all of the pairs of stores that follow each other.
3226   for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
3227     for (unsigned j = 0; j < e; ++j) {
3228       if (i == j)
3229         continue;
3230
3231       if (R.isConsecutiveAccess(Stores[i], Stores[j])) {
3232         Tails.insert(Stores[j]);
3233         Heads.insert(Stores[i]);
3234         ConsecutiveChain[Stores[i]] = Stores[j];
3235       }
3236     }
3237   }
3238
3239   // For stores that start but don't end a link in the chain:
3240   for (SetVector<Value *>::iterator it = Heads.begin(), e = Heads.end();
3241        it != e; ++it) {
3242     if (Tails.count(*it))
3243       continue;
3244
3245     // We found a store instr that starts a chain. Now follow the chain and try
3246     // to vectorize it.
3247     BoUpSLP::ValueList Operands;
3248     Value *I = *it;
3249     // Collect the chain into a list.
3250     while (Tails.count(I) || Heads.count(I)) {
3251       if (VectorizedStores.count(I))
3252         break;
3253       Operands.push_back(I);
3254       // Move to the next value in the chain.
3255       I = ConsecutiveChain[I];
3256     }
3257
3258     bool Vectorized = vectorizeStoreChain(Operands, costThreshold, R);
3259
3260     // Mark the vectorized stores so that we don't vectorize them again.
3261     if (Vectorized)
3262       VectorizedStores.insert(Operands.begin(), Operands.end());
3263     Changed |= Vectorized;
3264   }
3265
3266   return Changed;
3267 }
3268
3269
3270 unsigned SLPVectorizer::collectStores(BasicBlock *BB, BoUpSLP &R) {
3271   unsigned count = 0;
3272   StoreRefs.clear();
3273   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3274     StoreInst *SI = dyn_cast<StoreInst>(it);
3275     if (!SI)
3276       continue;
3277
3278     // Don't touch volatile stores.
3279     if (!SI->isSimple())
3280       continue;
3281
3282     // Check that the pointer points to scalars.
3283     Type *Ty = SI->getValueOperand()->getType();
3284     if (Ty->isAggregateType() || Ty->isVectorTy())
3285       continue;
3286
3287     // Find the base pointer.
3288     Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), DL);
3289
3290     // Save the store locations.
3291     StoreRefs[Ptr].push_back(SI);
3292     count++;
3293   }
3294   return count;
3295 }
3296
3297 bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
3298   if (!A || !B)
3299     return false;
3300   Value *VL[] = { A, B };
3301   return tryToVectorizeList(VL, R, None, true);
3302 }
3303
3304 bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
3305                                        ArrayRef<Value *> BuildVector,
3306                                        bool allowReorder) {
3307   if (VL.size() < 2)
3308     return false;
3309
3310   DEBUG(dbgs() << "SLP: Vectorizing a list of length = " << VL.size() << ".\n");
3311
3312   // Check that all of the parts are scalar instructions of the same type.
3313   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
3314   if (!I0)
3315     return false;
3316
3317   unsigned Opcode0 = I0->getOpcode();
3318
3319   Type *Ty0 = I0->getType();
3320   unsigned Sz = DL->getTypeSizeInBits(Ty0);
3321   unsigned VF = MinVecRegSize / Sz;
3322
3323   for (int i = 0, e = VL.size(); i < e; ++i) {
3324     Type *Ty = VL[i]->getType();
3325     if (Ty->isAggregateType() || Ty->isVectorTy())
3326       return false;
3327     Instruction *Inst = dyn_cast<Instruction>(VL[i]);
3328     if (!Inst || Inst->getOpcode() != Opcode0)
3329       return false;
3330   }
3331
3332   bool Changed = false;
3333
3334   // Keep track of values that were deleted by vectorizing in the loop below.
3335   SmallVector<WeakVH, 8> TrackValues(VL.begin(), VL.end());
3336
3337   for (unsigned i = 0, e = VL.size(); i < e; ++i) {
3338     unsigned OpsWidth = 0;
3339
3340     if (i + VF > e)
3341       OpsWidth = e - i;
3342     else
3343       OpsWidth = VF;
3344
3345     if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
3346       break;
3347
3348     // Check that a previous iteration of this loop did not delete the Value.
3349     if (hasValueBeenRAUWed(VL, TrackValues, i, OpsWidth))
3350       continue;
3351
3352     DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
3353                  << "\n");
3354     ArrayRef<Value *> Ops = VL.slice(i, OpsWidth);
3355
3356     ArrayRef<Value *> BuildVectorSlice;
3357     if (!BuildVector.empty())
3358       BuildVectorSlice = BuildVector.slice(i, OpsWidth);
3359
3360     R.buildTree(Ops, BuildVectorSlice);
3361     // TODO: check if we can allow reordering also for other cases than
3362     // tryToVectorizePair()
3363     if (allowReorder && R.shouldReorder()) {
3364       assert(Ops.size() == 2);
3365       assert(BuildVectorSlice.empty());
3366       Value *ReorderedOps[] = { Ops[1], Ops[0] };
3367       R.buildTree(ReorderedOps, None);
3368     }
3369     int Cost = R.getTreeCost();
3370
3371     if (Cost < -SLPCostThreshold) {
3372       DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
3373       Value *VectorizedRoot = R.vectorizeTree();
3374
3375       // Reconstruct the build vector by extracting the vectorized root. This
3376       // way we handle the case where some elements of the vector are undefined.
3377       //  (return (inserelt <4 xi32> (insertelt undef (opd0) 0) (opd1) 2))
3378       if (!BuildVectorSlice.empty()) {
3379         // The insert point is the last build vector instruction. The vectorized
3380         // root will precede it. This guarantees that we get an instruction. The
3381         // vectorized tree could have been constant folded.
3382         Instruction *InsertAfter = cast<Instruction>(BuildVectorSlice.back());
3383         unsigned VecIdx = 0;
3384         for (auto &V : BuildVectorSlice) {
3385           IRBuilder<true, NoFolder> Builder(
3386               ++BasicBlock::iterator(InsertAfter));
3387           InsertElementInst *IE = cast<InsertElementInst>(V);
3388           Instruction *Extract = cast<Instruction>(Builder.CreateExtractElement(
3389               VectorizedRoot, Builder.getInt32(VecIdx++)));
3390           IE->setOperand(1, Extract);
3391           IE->removeFromParent();
3392           IE->insertAfter(Extract);
3393           InsertAfter = IE;
3394         }
3395       }
3396       // Move to the next bundle.
3397       i += VF - 1;
3398       Changed = true;
3399     }
3400   }
3401
3402   return Changed;
3403 }
3404
3405 bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
3406   if (!V)
3407     return false;
3408
3409   // Try to vectorize V.
3410   if (tryToVectorizePair(V->getOperand(0), V->getOperand(1), R))
3411     return true;
3412
3413   BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
3414   BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
3415   // Try to skip B.
3416   if (B && B->hasOneUse()) {
3417     BinaryOperator *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
3418     BinaryOperator *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
3419     if (tryToVectorizePair(A, B0, R)) {
3420       return true;
3421     }
3422     if (tryToVectorizePair(A, B1, R)) {
3423       return true;
3424     }
3425   }
3426
3427   // Try to skip A.
3428   if (A && A->hasOneUse()) {
3429     BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
3430     BinaryOperator *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
3431     if (tryToVectorizePair(A0, B, R)) {
3432       return true;
3433     }
3434     if (tryToVectorizePair(A1, B, R)) {
3435       return true;
3436     }
3437   }
3438   return 0;
3439 }
3440
3441 /// \brief Generate a shuffle mask to be used in a reduction tree.
3442 ///
3443 /// \param VecLen The length of the vector to be reduced.
3444 /// \param NumEltsToRdx The number of elements that should be reduced in the
3445 ///        vector.
3446 /// \param IsPairwise Whether the reduction is a pairwise or splitting
3447 ///        reduction. A pairwise reduction will generate a mask of 
3448 ///        <0,2,...> or <1,3,..> while a splitting reduction will generate
3449 ///        <2,3, undef,undef> for a vector of 4 and NumElts = 2.
3450 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
3451 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
3452                                    bool IsPairwise, bool IsLeft,
3453                                    IRBuilder<> &Builder) {
3454   assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
3455
3456   SmallVector<Constant *, 32> ShuffleMask(
3457       VecLen, UndefValue::get(Builder.getInt32Ty()));
3458
3459   if (IsPairwise)
3460     // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
3461     for (unsigned i = 0; i != NumEltsToRdx; ++i)
3462       ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
3463   else
3464     // Move the upper half of the vector to the lower half.
3465     for (unsigned i = 0; i != NumEltsToRdx; ++i)
3466       ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
3467
3468   return ConstantVector::get(ShuffleMask);
3469 }
3470
3471
3472 /// Model horizontal reductions.
3473 ///
3474 /// A horizontal reduction is a tree of reduction operations (currently add and
3475 /// fadd) that has operations that can be put into a vector as its leaf.
3476 /// For example, this tree:
3477 ///
3478 /// mul mul mul mul
3479 ///  \  /    \  /
3480 ///   +       +
3481 ///    \     /
3482 ///       +
3483 /// This tree has "mul" as its reduced values and "+" as its reduction
3484 /// operations. A reduction might be feeding into a store or a binary operation
3485 /// feeding a phi.
3486 ///    ...
3487 ///    \  /
3488 ///     +
3489 ///     |
3490 ///  phi +=
3491 ///
3492 ///  Or:
3493 ///    ...
3494 ///    \  /
3495 ///     +
3496 ///     |
3497 ///   *p =
3498 ///
3499 class HorizontalReduction {
3500   SmallVector<Value *, 16> ReductionOps;
3501   SmallVector<Value *, 32> ReducedVals;
3502
3503   BinaryOperator *ReductionRoot;
3504   PHINode *ReductionPHI;
3505
3506   /// The opcode of the reduction.
3507   unsigned ReductionOpcode;
3508   /// The opcode of the values we perform a reduction on.
3509   unsigned ReducedValueOpcode;
3510   /// The width of one full horizontal reduction operation.
3511   unsigned ReduxWidth;
3512   /// Should we model this reduction as a pairwise reduction tree or a tree that
3513   /// splits the vector in halves and adds those halves.
3514   bool IsPairwiseReduction;
3515
3516 public:
3517   HorizontalReduction()
3518     : ReductionRoot(nullptr), ReductionPHI(nullptr), ReductionOpcode(0),
3519     ReducedValueOpcode(0), ReduxWidth(0), IsPairwiseReduction(false) {}
3520
3521   /// \brief Try to find a reduction tree.
3522   bool matchAssociativeReduction(PHINode *Phi, BinaryOperator *B,
3523                                  const DataLayout *DL) {
3524     assert((!Phi ||
3525             std::find(Phi->op_begin(), Phi->op_end(), B) != Phi->op_end()) &&
3526            "Thi phi needs to use the binary operator");
3527
3528     // We could have a initial reductions that is not an add.
3529     //  r *= v1 + v2 + v3 + v4
3530     // In such a case start looking for a tree rooted in the first '+'.
3531     if (Phi) {
3532       if (B->getOperand(0) == Phi) {
3533         Phi = nullptr;
3534         B = dyn_cast<BinaryOperator>(B->getOperand(1));
3535       } else if (B->getOperand(1) == Phi) {
3536         Phi = nullptr;
3537         B = dyn_cast<BinaryOperator>(B->getOperand(0));
3538       }
3539     }
3540
3541     if (!B)
3542       return false;
3543
3544     Type *Ty = B->getType();
3545     if (Ty->isVectorTy())
3546       return false;
3547
3548     ReductionOpcode = B->getOpcode();
3549     ReducedValueOpcode = 0;
3550     ReduxWidth = MinVecRegSize / DL->getTypeSizeInBits(Ty);
3551     ReductionRoot = B;
3552     ReductionPHI = Phi;
3553
3554     if (ReduxWidth < 4)
3555       return false;
3556
3557     // We currently only support adds.
3558     if (ReductionOpcode != Instruction::Add &&
3559         ReductionOpcode != Instruction::FAdd)
3560       return false;
3561
3562     // Post order traverse the reduction tree starting at B. We only handle true
3563     // trees containing only binary operators.
3564     SmallVector<std::pair<BinaryOperator *, unsigned>, 32> Stack;
3565     Stack.push_back(std::make_pair(B, 0));
3566     while (!Stack.empty()) {
3567       BinaryOperator *TreeN = Stack.back().first;
3568       unsigned EdgeToVist = Stack.back().second++;
3569       bool IsReducedValue = TreeN->getOpcode() != ReductionOpcode;
3570
3571       // Only handle trees in the current basic block.
3572       if (TreeN->getParent() != B->getParent())
3573         return false;
3574
3575       // Each tree node needs to have one user except for the ultimate
3576       // reduction.
3577       if (!TreeN->hasOneUse() && TreeN != B)
3578         return false;
3579
3580       // Postorder vist.
3581       if (EdgeToVist == 2 || IsReducedValue) {
3582         if (IsReducedValue) {
3583           // Make sure that the opcodes of the operations that we are going to
3584           // reduce match.
3585           if (!ReducedValueOpcode)
3586             ReducedValueOpcode = TreeN->getOpcode();
3587           else if (ReducedValueOpcode != TreeN->getOpcode())
3588             return false;
3589           ReducedVals.push_back(TreeN);
3590         } else {
3591           // We need to be able to reassociate the adds.
3592           if (!TreeN->isAssociative())
3593             return false;
3594           ReductionOps.push_back(TreeN);
3595         }
3596         // Retract.
3597         Stack.pop_back();
3598         continue;
3599       }
3600
3601       // Visit left or right.
3602       Value *NextV = TreeN->getOperand(EdgeToVist);
3603       BinaryOperator *Next = dyn_cast<BinaryOperator>(NextV);
3604       if (Next)
3605         Stack.push_back(std::make_pair(Next, 0));
3606       else if (NextV != Phi)
3607         return false;
3608     }
3609     return true;
3610   }
3611
3612   /// \brief Attempt to vectorize the tree found by
3613   /// matchAssociativeReduction.
3614   bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
3615     if (ReducedVals.empty())
3616       return false;
3617
3618     unsigned NumReducedVals = ReducedVals.size();
3619     if (NumReducedVals < ReduxWidth)
3620       return false;
3621
3622     Value *VectorizedTree = nullptr;
3623     IRBuilder<> Builder(ReductionRoot);
3624     FastMathFlags Unsafe;
3625     Unsafe.setUnsafeAlgebra();
3626     Builder.SetFastMathFlags(Unsafe);
3627     unsigned i = 0;
3628
3629     for (; i < NumReducedVals - ReduxWidth + 1; i += ReduxWidth) {
3630       V.buildTree(makeArrayRef(&ReducedVals[i], ReduxWidth), ReductionOps);
3631
3632       // Estimate cost.
3633       int Cost = V.getTreeCost() + getReductionCost(TTI, ReducedVals[i]);
3634       if (Cost >= -SLPCostThreshold)
3635         break;
3636
3637       DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost
3638                    << ". (HorRdx)\n");
3639
3640       // Vectorize a tree.
3641       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
3642       Value *VectorizedRoot = V.vectorizeTree();
3643
3644       // Emit a reduction.
3645       Value *ReducedSubTree = emitReduction(VectorizedRoot, Builder);
3646       if (VectorizedTree) {
3647         Builder.SetCurrentDebugLocation(Loc);
3648         VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
3649                                      ReducedSubTree, "bin.rdx");
3650       } else
3651         VectorizedTree = ReducedSubTree;
3652     }
3653
3654     if (VectorizedTree) {
3655       // Finish the reduction.
3656       for (; i < NumReducedVals; ++i) {
3657         Builder.SetCurrentDebugLocation(
3658           cast<Instruction>(ReducedVals[i])->getDebugLoc());
3659         VectorizedTree = createBinOp(Builder, ReductionOpcode, VectorizedTree,
3660                                      ReducedVals[i]);
3661       }
3662       // Update users.
3663       if (ReductionPHI) {
3664         assert(ReductionRoot && "Need a reduction operation");
3665         ReductionRoot->setOperand(0, VectorizedTree);
3666         ReductionRoot->setOperand(1, ReductionPHI);
3667       } else
3668         ReductionRoot->replaceAllUsesWith(VectorizedTree);
3669     }
3670     return VectorizedTree != nullptr;
3671   }
3672
3673 private:
3674
3675   /// \brief Calcuate the cost of a reduction.
3676   int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal) {
3677     Type *ScalarTy = FirstReducedVal->getType();
3678     Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
3679
3680     int PairwiseRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, true);
3681     int SplittingRdxCost = TTI->getReductionCost(ReductionOpcode, VecTy, false);
3682
3683     IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
3684     int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
3685
3686     int ScalarReduxCost =
3687         ReduxWidth * TTI->getArithmeticInstrCost(ReductionOpcode, VecTy);
3688
3689     DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
3690                  << " for reduction that starts with " << *FirstReducedVal
3691                  << " (It is a "
3692                  << (IsPairwiseReduction ? "pairwise" : "splitting")
3693                  << " reduction)\n");
3694
3695     return VecReduxCost - ScalarReduxCost;
3696   }
3697
3698   static Value *createBinOp(IRBuilder<> &Builder, unsigned Opcode, Value *L,
3699                             Value *R, const Twine &Name = "") {
3700     if (Opcode == Instruction::FAdd)
3701       return Builder.CreateFAdd(L, R, Name);
3702     return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, L, R, Name);
3703   }
3704
3705   /// \brief Emit a horizontal reduction of the vectorized value.
3706   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder) {
3707     assert(VectorizedValue && "Need to have a vectorized tree node");
3708     assert(isPowerOf2_32(ReduxWidth) &&
3709            "We only handle power-of-two reductions for now");
3710
3711     Value *TmpVec = VectorizedValue;
3712     for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
3713       if (IsPairwiseReduction) {
3714         Value *LeftMask =
3715           createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
3716         Value *RightMask =
3717           createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
3718
3719         Value *LeftShuf = Builder.CreateShuffleVector(
3720           TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
3721         Value *RightShuf = Builder.CreateShuffleVector(
3722           TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
3723           "rdx.shuf.r");
3724         TmpVec = createBinOp(Builder, ReductionOpcode, LeftShuf, RightShuf,
3725                              "bin.rdx");
3726       } else {
3727         Value *UpperHalf =
3728           createRdxShuffleMask(ReduxWidth, i, false, false, Builder);
3729         Value *Shuf = Builder.CreateShuffleVector(
3730           TmpVec, UndefValue::get(TmpVec->getType()), UpperHalf, "rdx.shuf");
3731         TmpVec = createBinOp(Builder, ReductionOpcode, TmpVec, Shuf, "bin.rdx");
3732       }
3733     }
3734
3735     // The result is in the first element of the vector.
3736     return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
3737   }
3738 };
3739
3740 /// \brief Recognize construction of vectors like
3741 ///  %ra = insertelement <4 x float> undef, float %s0, i32 0
3742 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
3743 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
3744 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
3745 ///
3746 /// Returns true if it matches
3747 ///
3748 static bool findBuildVector(InsertElementInst *FirstInsertElem,
3749                             SmallVectorImpl<Value *> &BuildVector,
3750                             SmallVectorImpl<Value *> &BuildVectorOpds) {
3751   if (!isa<UndefValue>(FirstInsertElem->getOperand(0)))
3752     return false;
3753
3754   InsertElementInst *IE = FirstInsertElem;
3755   while (true) {
3756     BuildVector.push_back(IE);
3757     BuildVectorOpds.push_back(IE->getOperand(1));
3758
3759     if (IE->use_empty())
3760       return false;
3761
3762     InsertElementInst *NextUse = dyn_cast<InsertElementInst>(IE->user_back());
3763     if (!NextUse)
3764       return true;
3765
3766     // If this isn't the final use, make sure the next insertelement is the only
3767     // use. It's OK if the final constructed vector is used multiple times
3768     if (!IE->hasOneUse())
3769       return false;
3770
3771     IE = NextUse;
3772   }
3773
3774   return false;
3775 }
3776
3777 static bool PhiTypeSorterFunc(Value *V, Value *V2) {
3778   return V->getType() < V2->getType();
3779 }
3780
3781 bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
3782   bool Changed = false;
3783   SmallVector<Value *, 4> Incoming;
3784   SmallSet<Value *, 16> VisitedInstrs;
3785
3786   bool HaveVectorizedPhiNodes = true;
3787   while (HaveVectorizedPhiNodes) {
3788     HaveVectorizedPhiNodes = false;
3789
3790     // Collect the incoming values from the PHIs.
3791     Incoming.clear();
3792     for (BasicBlock::iterator instr = BB->begin(), ie = BB->end(); instr != ie;
3793          ++instr) {
3794       PHINode *P = dyn_cast<PHINode>(instr);
3795       if (!P)
3796         break;
3797
3798       if (!VisitedInstrs.count(P))
3799         Incoming.push_back(P);
3800     }
3801
3802     // Sort by type.
3803     std::stable_sort(Incoming.begin(), Incoming.end(), PhiTypeSorterFunc);
3804
3805     // Try to vectorize elements base on their type.
3806     for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
3807                                            E = Incoming.end();
3808          IncIt != E;) {
3809
3810       // Look for the next elements with the same type.
3811       SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
3812       while (SameTypeIt != E &&
3813              (*SameTypeIt)->getType() == (*IncIt)->getType()) {
3814         VisitedInstrs.insert(*SameTypeIt);
3815         ++SameTypeIt;
3816       }
3817
3818       // Try to vectorize them.
3819       unsigned NumElts = (SameTypeIt - IncIt);
3820       DEBUG(errs() << "SLP: Trying to vectorize starting at PHIs (" << NumElts << ")\n");
3821       if (NumElts > 1 && tryToVectorizeList(makeArrayRef(IncIt, NumElts), R)) {
3822         // Success start over because instructions might have been changed.
3823         HaveVectorizedPhiNodes = true;
3824         Changed = true;
3825         break;
3826       }
3827
3828       // Start over at the next instruction of a different type (or the end).
3829       IncIt = SameTypeIt;
3830     }
3831   }
3832
3833   VisitedInstrs.clear();
3834
3835   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
3836     // We may go through BB multiple times so skip the one we have checked.
3837     if (!VisitedInstrs.insert(it).second)
3838       continue;
3839
3840     if (isa<DbgInfoIntrinsic>(it))
3841       continue;
3842
3843     // Try to vectorize reductions that use PHINodes.
3844     if (PHINode *P = dyn_cast<PHINode>(it)) {
3845       // Check that the PHI is a reduction PHI.
3846       if (P->getNumIncomingValues() != 2)
3847         return Changed;
3848       Value *Rdx =
3849           (P->getIncomingBlock(0) == BB
3850                ? (P->getIncomingValue(0))
3851                : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1)
3852                                                : nullptr));
3853       // Check if this is a Binary Operator.
3854       BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
3855       if (!BI)
3856         continue;
3857
3858       // Try to match and vectorize a horizontal reduction.
3859       HorizontalReduction HorRdx;
3860       if (ShouldVectorizeHor &&
3861           HorRdx.matchAssociativeReduction(P, BI, DL) &&
3862           HorRdx.tryToReduce(R, TTI)) {
3863         Changed = true;
3864         it = BB->begin();
3865         e = BB->end();
3866         continue;
3867       }
3868
3869      Value *Inst = BI->getOperand(0);
3870       if (Inst == P)
3871         Inst = BI->getOperand(1);
3872
3873       if (tryToVectorize(dyn_cast<BinaryOperator>(Inst), R)) {
3874         // We would like to start over since some instructions are deleted
3875         // and the iterator may become invalid value.
3876         Changed = true;
3877         it = BB->begin();
3878         e = BB->end();
3879         continue;
3880       }
3881
3882       continue;
3883     }
3884
3885     // Try to vectorize horizontal reductions feeding into a store.
3886     if (ShouldStartVectorizeHorAtStore)
3887       if (StoreInst *SI = dyn_cast<StoreInst>(it))
3888         if (BinaryOperator *BinOp =
3889                 dyn_cast<BinaryOperator>(SI->getValueOperand())) {
3890           HorizontalReduction HorRdx;
3891           if (((HorRdx.matchAssociativeReduction(nullptr, BinOp, DL) &&
3892                 HorRdx.tryToReduce(R, TTI)) ||
3893                tryToVectorize(BinOp, R))) {
3894             Changed = true;
3895             it = BB->begin();
3896             e = BB->end();
3897             continue;
3898           }
3899         }
3900
3901     // Try to vectorize horizontal reductions feeding into a return.
3902     if (ReturnInst *RI = dyn_cast<ReturnInst>(it))
3903       if (RI->getNumOperands() != 0)
3904         if (BinaryOperator *BinOp =
3905                 dyn_cast<BinaryOperator>(RI->getOperand(0))) {
3906           DEBUG(dbgs() << "SLP: Found a return to vectorize.\n");
3907           if (tryToVectorizePair(BinOp->getOperand(0),
3908                                  BinOp->getOperand(1), R)) {
3909             Changed = true;
3910             it = BB->begin();
3911             e = BB->end();
3912             continue;
3913           }
3914         }
3915
3916     // Try to vectorize trees that start at compare instructions.
3917     if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
3918       if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R)) {
3919         Changed = true;
3920         // We would like to start over since some instructions are deleted
3921         // and the iterator may become invalid value.
3922         it = BB->begin();
3923         e = BB->end();
3924         continue;
3925       }
3926
3927       for (int i = 0; i < 2; ++i) {
3928         if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i))) {
3929           if (tryToVectorizePair(BI->getOperand(0), BI->getOperand(1), R)) {
3930             Changed = true;
3931             // We would like to start over since some instructions are deleted
3932             // and the iterator may become invalid value.
3933             it = BB->begin();
3934             e = BB->end();
3935           }
3936         }
3937       }
3938       continue;
3939     }
3940
3941     // Try to vectorize trees that start at insertelement instructions.
3942     if (InsertElementInst *FirstInsertElem = dyn_cast<InsertElementInst>(it)) {
3943       SmallVector<Value *, 16> BuildVector;
3944       SmallVector<Value *, 16> BuildVectorOpds;
3945       if (!findBuildVector(FirstInsertElem, BuildVector, BuildVectorOpds))
3946         continue;
3947
3948       // Vectorize starting with the build vector operands ignoring the
3949       // BuildVector instructions for the purpose of scheduling and user
3950       // extraction.
3951       if (tryToVectorizeList(BuildVectorOpds, R, BuildVector)) {
3952         Changed = true;
3953         it = BB->begin();
3954         e = BB->end();
3955       }
3956
3957       continue;
3958     }
3959   }
3960
3961   return Changed;
3962 }
3963
3964 bool SLPVectorizer::vectorizeStoreChains(BoUpSLP &R) {
3965   bool Changed = false;
3966   // Attempt to sort and vectorize each of the store-groups.
3967   for (StoreListMap::iterator it = StoreRefs.begin(), e = StoreRefs.end();
3968        it != e; ++it) {
3969     if (it->second.size() < 2)
3970       continue;
3971
3972     DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
3973           << it->second.size() << ".\n");
3974
3975     // Process the stores in chunks of 16.
3976     for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
3977       unsigned Len = std::min<unsigned>(CE - CI, 16);
3978       Changed |= vectorizeStores(makeArrayRef(&it->second[CI], Len),
3979                                  -SLPCostThreshold, R);
3980     }
3981   }
3982   return Changed;
3983 }
3984
3985 } // end anonymous namespace
3986
3987 char SLPVectorizer::ID = 0;
3988 static const char lv_name[] = "SLP Vectorizer";
3989 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
3990 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3991 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
3992 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3993 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
3994 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
3995 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
3996
3997 namespace llvm {
3998 Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }
3999 }