1 //===- ForwardOpTree.h ------------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Move instructions between statements.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "polly/ForwardOpTree.h"
15 #include "polly/Options.h"
16 #include "polly/ScopBuilder.h"
17 #include "polly/ScopInfo.h"
18 #include "polly/ScopPass.h"
19 #include "polly/Support/GICHelper.h"
20 #include "polly/Support/ISLOStream.h"
21 #include "polly/Support/ISLTools.h"
22 #include "polly/Support/VirtualInstruction.h"
23 #include "polly/ZoneAlgo.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Analysis/LoopInfo.h"
28 #include "llvm/Analysis/ValueTracking.h"
29 #include "llvm/IR/Instruction.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/Value.h"
32 #include "llvm/Pass.h"
33 #include "llvm/Support/Casting.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Compiler.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "isl/ctx.h"
40 #include "isl/isl-noexceptions.h"
41 #include <cassert>
42 #include <memory>
43 
44 #define DEBUG_TYPE "polly-optree"
45 
46 using namespace llvm;
47 using namespace polly;
48 
49 static cl::opt<bool>
50     AnalyzeKnown("polly-optree-analyze-known",
51                  cl::desc("Analyze array contents for load forwarding"),
52                  cl::cat(PollyCategory), cl::init(true), cl::Hidden);
53 
54 static cl::opt<unsigned long>
55     MaxOps("polly-optree-max-ops",
56            cl::desc("Maximum number of ISL operations to invest for known "
57                     "analysis; 0=no limit"),
58            cl::init(1000000), cl::cat(PollyCategory), cl::Hidden);
59 
60 STATISTIC(KnownAnalyzed, "Number of successfully analyzed SCoPs");
61 STATISTIC(KnownOutOfQuota,
62           "Analyses aborted because max_operations was reached");
63 
64 STATISTIC(TotalInstructionsCopied, "Number of copied instructions");
65 STATISTIC(TotalKnownLoadsForwarded,
66           "Number of forwarded loads because their value was known");
67 STATISTIC(TotalReadOnlyCopied, "Number of copied read-only accesses");
68 STATISTIC(TotalForwardedTrees, "Number of forwarded operand trees");
69 STATISTIC(TotalModifiedStmts,
70           "Number of statements with at least one forwarded tree");
71 
72 STATISTIC(ScopsModified, "Number of SCoPs with at least one forwarded tree");
73 
74 STATISTIC(NumValueWrites, "Number of scalar value writes after OpTree");
75 STATISTIC(NumValueWritesInLoops,
76           "Number of scalar value writes nested in affine loops after OpTree");
77 STATISTIC(NumPHIWrites, "Number of scalar phi writes after OpTree");
78 STATISTIC(NumPHIWritesInLoops,
79           "Number of scalar phi writes nested in affine loops after OpTree");
80 STATISTIC(NumSingletonWrites, "Number of singleton writes after OpTree");
81 STATISTIC(NumSingletonWritesInLoops,
82           "Number of singleton writes nested in affine loops after OpTree");
83 
84 namespace {
85 
86 /// The state of whether an operand tree was/can be forwarded.
87 ///
88 /// The items apply to an instructions and its operand tree with the instruction
89 /// as the root element. If the value in question is not an instruction in the
90 /// SCoP, it can be a leaf of an instruction's operand tree.
91 enum ForwardingDecision {
92   /// The root instruction or value cannot be forwarded at all.
93   FD_CannotForward,
94 
95   /// The root instruction or value can be forwarded as a leaf of a larger
96   /// operand tree.
97   /// It does not make sense to move the value itself, it would just replace it
98   /// by a use of itself. For instance, a constant "5" used in a statement can
99   /// be forwarded, but it would just replace it by the same constant "5".
100   /// However, it makes sense to move as an operand of
101   ///
102   ///   %add = add 5, 5
103   ///
104   /// where "5" is moved as part of a larger operand tree. "5" would be placed
105   /// (disregarding for a moment that literal constants don't have a location
106   /// and can be used anywhere) into the same statement as %add would.
107   FD_CanForwardLeaf,
108 
109   /// The root instruction can be forwarded in a non-trivial way. This requires
110   /// the operand tree root to be an instruction in some statement.
111   FD_CanForwardTree,
112 
113   /// Used to indicate that a forwarding has be carried out successfully.
114   FD_DidForward,
115 
116   /// A forwarding method cannot be applied to the operand tree.
117   /// The difference to FD_CannotForward is that there might be other methods
118   /// that can handle it.
119   /// The conditions that make an operand tree applicable must be checked even
120   /// with DoIt==true because a method following the one that returned
121   /// FD_NotApplicable might have returned FD_CanForwardTree.
122   FD_NotApplicable
123 };
124 
125 /// Implementation of operand tree forwarding for a specific SCoP.
126 ///
127 /// For a statement that requires a scalar value (through a value read
128 /// MemoryAccess), see if its operand can be moved into the statement. If so,
129 /// the MemoryAccess is removed and the all the operand tree instructions are
130 /// moved into the statement. All original instructions are left in the source
131 /// statements. The simplification pass can clean these up.
132 class ForwardOpTreeImpl : ZoneAlgorithm {
133 private:
134   /// How many instructions have been copied to other statements.
135   int NumInstructionsCopied = 0;
136 
137   /// Number of loads forwarded because their value was known.
138   int NumKnownLoadsForwarded = 0;
139 
140   /// How many read-only accesses have been copied.
141   int NumReadOnlyCopied = 0;
142 
143   /// How many operand trees have been forwarded.
144   int NumForwardedTrees = 0;
145 
146   /// Number of statements with at least one forwarded operand tree.
147   int NumModifiedStmts = 0;
148 
149   /// Whether we carried out at least one change to the SCoP.
150   bool Modified = false;
151 
152   /// Contains the zones where array elements are known to contain a specific
153   /// value.
154   /// { [Element[] -> Zone[]] -> ValInst[] }
155   /// @see computeKnown()
156   isl::union_map Known;
157 
158   /// Translator for newly introduced ValInsts to already existing ValInsts such
159   /// that new introduced load instructions can reuse the Known analysis of its
160   /// original load. { ValInst[] -> ValInst[] }
161   isl::union_map Translator;
162 
163   /// Get list of array elements that do contain the same ValInst[] at Domain[].
164   ///
165   /// @param ValInst { Domain[] -> ValInst[] }
166   ///                The values for which we search for alternative locations,
167   ///                per statement instance.
168   ///
169   /// @return { Domain[] -> Element[] }
170   ///         For each statement instance, the array elements that contain the
171   ///         same ValInst.
172   isl::union_map findSameContentElements(isl::union_map ValInst) {
173     assert(ValInst.is_single_valued().is_true());
174 
175     // { Domain[] }
176     isl::union_set Domain = ValInst.domain();
177 
178     // { Domain[] -> Scatter[] }
179     isl::union_map Schedule = getScatterFor(Domain);
180 
181     // { Element[] -> [Scatter[] -> ValInst[]] }
182     isl::union_map MustKnownCurried =
183         convertZoneToTimepoints(Known, isl::dim::in, false, true).curry();
184 
185     // { [Domain[] -> ValInst[]] -> Scatter[] }
186     isl::union_map DomValSched = ValInst.domain_map().apply_range(Schedule);
187 
188     // { [Scatter[] -> ValInst[]] -> [Domain[] -> ValInst[]] }
189     isl::union_map SchedValDomVal =
190         DomValSched.range_product(ValInst.range_map()).reverse();
191 
192     // { Element[] -> [Domain[] -> ValInst[]] }
193     isl::union_map MustKnownInst = MustKnownCurried.apply_range(SchedValDomVal);
194 
195     // { Domain[] -> Element[] }
196     isl::union_map MustKnownMap =
197         MustKnownInst.uncurry().domain().unwrap().reverse();
198     simplify(MustKnownMap);
199 
200     return MustKnownMap;
201   }
202 
203   /// Find a single array element for each statement instance, within a single
204   /// array.
205   ///
206   /// @param MustKnown { Domain[] -> Element[] }
207   ///                  Set of candidate array elements.
208   /// @param Domain    { Domain[] }
209   ///                  The statement instance for which we need elements for.
210   ///
211   /// @return { Domain[] -> Element[] }
212   ///         For each statement instance, an array element out of @p MustKnown.
213   ///         All array elements must be in the same array (Polly does not yet
214   ///         support reading from different accesses using the same
215   ///         MemoryAccess). If no mapping for all of @p Domain exists, returns
216   ///         null.
217   isl::map singleLocation(isl::union_map MustKnown, isl::set Domain) {
218     // { Domain[] -> Element[] }
219     isl::map Result;
220 
221     // MemoryAccesses can read only elements from a single array
222     // (i.e. not: { Dom[0] -> A[0]; Dom[1] -> B[1] }).
223     // Look through all spaces until we find one that contains at least the
224     // wanted statement instance.s
225     MustKnown.foreach_map([&](isl::map Map) -> isl::stat {
226       // Get the array this is accessing.
227       isl::id ArrayId = Map.get_tuple_id(isl::dim::out);
228       ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(ArrayId.get_user());
229 
230       // No support for generation of indirect array accesses.
231       if (SAI->getBasePtrOriginSAI())
232         return isl::stat::ok; // continue
233 
234       // Determine whether this map contains all wanted values.
235       isl::set MapDom = Map.domain();
236       if (!Domain.is_subset(MapDom).is_true())
237         return isl::stat::ok; // continue
238 
239       // There might be multiple array elements that contain the same value, but
240       // choose only one of them. lexmin is used because it returns a one-value
241       // mapping, we do not care about which one.
242       // TODO: Get the simplest access function.
243       Result = Map.lexmin();
244       return isl::stat::error; // break
245     });
246 
247     return Result;
248   }
249 
250 public:
251   ForwardOpTreeImpl(Scop *S, LoopInfo *LI)
252       : ZoneAlgorithm("polly-optree", S, LI) {}
253 
254   /// Compute the zones of known array element contents.
255   ///
256   /// @return True if the computed #Known is usable.
257   bool computeKnownValues() {
258     isl::union_map MustKnown, KnownFromLoad, KnownFromInit;
259 
260     // Check that nothing strange occurs.
261     collectCompatibleElts();
262 
263     isl_ctx_reset_error(IslCtx.get());
264     {
265       IslMaxOperationsGuard MaxOpGuard(IslCtx.get(), MaxOps);
266 
267       computeCommon();
268       Known = computeKnown(true, true);
269       simplify(Known);
270 
271       // Preexisting ValInsts use the known content analysis of themselves.
272       Translator = makeIdentityMap(Known.range(), false);
273     }
274 
275     if (!Known || !Translator) {
276       assert(isl_ctx_last_error(IslCtx.get()) == isl_error_quota);
277       KnownOutOfQuota++;
278       Known = nullptr;
279       Translator = nullptr;
280       DEBUG(dbgs() << "Known analysis exceeded max_operations\n");
281       return false;
282     }
283 
284     KnownAnalyzed++;
285     DEBUG(dbgs() << "All known: " << Known << "\n");
286 
287     return true;
288   }
289 
290   void printStatistics(raw_ostream &OS, int Indent = 0) {
291     OS.indent(Indent) << "Statistics {\n";
292     OS.indent(Indent + 4) << "Instructions copied: " << NumInstructionsCopied
293                           << '\n';
294     OS.indent(Indent + 4) << "Known loads forwarded: " << NumKnownLoadsForwarded
295                           << '\n';
296     OS.indent(Indent + 4) << "Read-only accesses copied: " << NumReadOnlyCopied
297                           << '\n';
298     OS.indent(Indent + 4) << "Operand trees forwarded: " << NumForwardedTrees
299                           << '\n';
300     OS.indent(Indent + 4) << "Statements with forwarded operand trees: "
301                           << NumModifiedStmts << '\n';
302     OS.indent(Indent) << "}\n";
303   }
304 
305   void printStatements(raw_ostream &OS, int Indent = 0) const {
306     OS.indent(Indent) << "After statements {\n";
307     for (auto &Stmt : *S) {
308       OS.indent(Indent + 4) << Stmt.getBaseName() << "\n";
309       for (auto *MA : Stmt)
310         MA->print(OS);
311 
312       OS.indent(Indent + 12);
313       Stmt.printInstructions(OS);
314     }
315     OS.indent(Indent) << "}\n";
316   }
317 
318   /// Create a new MemoryAccess of type read and MemoryKind::Array.
319   ///
320   /// @param Stmt           The statement in which the access occurs.
321   /// @param LI             The instruction that does the access.
322   /// @param AccessRelation The array element that each statement instance
323   ///                       accesses.
324   ///
325   /// @param The newly created access.
326   MemoryAccess *makeReadArrayAccess(ScopStmt *Stmt, LoadInst *LI,
327                                     isl::map AccessRelation) {
328     isl::id ArrayId = AccessRelation.get_tuple_id(isl::dim::out);
329     ScopArrayInfo *SAI = reinterpret_cast<ScopArrayInfo *>(ArrayId.get_user());
330 
331     // Create a dummy SCEV access, to be replaced anyway.
332     SmallVector<const SCEV *, 4> Sizes;
333     Sizes.reserve(SAI->getNumberOfDimensions());
334     SmallVector<const SCEV *, 4> Subscripts;
335     Subscripts.reserve(SAI->getNumberOfDimensions());
336     for (unsigned i = 0; i < SAI->getNumberOfDimensions(); i += 1) {
337       Sizes.push_back(SAI->getDimensionSize(i));
338       Subscripts.push_back(nullptr);
339     }
340 
341     MemoryAccess *Access =
342         new MemoryAccess(Stmt, LI, MemoryAccess::READ, SAI->getBasePtr(),
343                          LI->getType(), true, {}, Sizes, LI, MemoryKind::Array);
344     S->addAccessFunction(Access);
345     Stmt->addAccess(Access, true);
346 
347     Access->setNewAccessRelation(AccessRelation);
348 
349     return Access;
350   }
351 
352   /// For an llvm::Value defined in @p DefStmt, compute the RAW dependency for a
353   /// use in every instance of @p UseStmt.
354   ///
355   /// @param UseStmt Statement a scalar is used in.
356   /// @param DefStmt Statement a scalar is defined in.
357   ///
358   /// @return { DomainUse[] -> DomainDef[] }
359   isl::map computeUseToDefFlowDependency(ScopStmt *UseStmt, ScopStmt *DefStmt) {
360     // { DomainUse[] -> Scatter[] }
361     isl::map UseScatter = getScatterFor(UseStmt);
362 
363     // { Zone[] -> DomainDef[] }
364     isl::map ReachDefZone = getScalarReachingDefinition(DefStmt);
365 
366     // { Scatter[] -> DomainDef[] }
367     isl::map ReachDefTimepoints =
368         convertZoneToTimepoints(ReachDefZone, isl::dim::in, false, true);
369 
370     // { DomainUse[] -> DomainDef[] }
371     return UseScatter.apply_range(ReachDefTimepoints);
372   }
373 
374   /// Forward a load by reading from an array element that contains the same
375   /// value. Typically the location it was loaded from.
376   ///
377   /// @param TargetStmt  The statement the operand tree will be copied to.
378   /// @param Inst        The (possibly speculatable) instruction to forward.
379   /// @param UseStmt     The statement that uses @p Inst.
380   /// @param UseLoop     The loop @p Inst is used in.
381   /// @param UseToTarget { DomainUse[] -> DomainTarget[] }
382   ///                    A mapping from the statement instance @p Inst is used
383   ///                    to the statement instance it is forwarded to.
384   /// @param DefStmt     The statement @p Inst is defined in.
385   /// @param DefLoop     The loop which contains @p Inst.
386   /// @param DefToTarget { DomainDef[] -> DomainTarget[] }
387   ///                    A mapping from the statement instance @p Inst is
388   ///                    defined to the statement instance it is forwarded to.
389   /// @param DoIt        If false, only determine whether an operand tree can be
390   ///                    forwarded. If true, carry out the forwarding. Do not
391   ///                    use DoIt==true if an operand tree is not known to be
392   ///                    forwardable.
393   ///
394   /// @return FD_NotApplicable  if @p Inst is not a LoadInst.
395   ///         FD_CannotForward  if no array element to load from was found.
396   ///         FD_CanForwardLeaf if the load is already in the target statement
397   ///                           instance.
398   ///         FD_CanForwardTree if @p Inst is forwardable.
399   ///         FD_DidForward     if @p DoIt was true.
400   ForwardingDecision forwardKnownLoad(ScopStmt *TargetStmt, Instruction *Inst,
401                                       ScopStmt *UseStmt, Loop *UseLoop,
402                                       isl::map UseToTarget, ScopStmt *DefStmt,
403                                       Loop *DefLoop, isl::map DefToTarget,
404                                       bool DoIt) {
405     // Cannot do anything without successful known analysis.
406     if (Known.is_null())
407       return FD_NotApplicable;
408 
409     LoadInst *LI = dyn_cast<LoadInst>(Inst);
410     if (!LI)
411       return FD_NotApplicable;
412 
413     // If the load is already in the statement, no forwarding is necessary.
414     // However, it might happen that the LoadInst is already present in the
415     // statement's instruction list. In that case we do as follows:
416     // - For the evaluation (DoIt==false), we can trivially forward it as it is
417     //   benefit of forwarding an already present instruction.
418     // - For the execution (DoIt==true), prepend the instruction (to make it
419     //   available to all instructions following in the instruction list), but
420     //   do not add another MemoryAccess.
421     MemoryAccess *Access = TargetStmt->getArrayAccessOrNULLFor(LI);
422     if (Access && !DoIt)
423       return FD_CanForwardTree;
424 
425     if (DoIt)
426       TargetStmt->prependInstruction(LI);
427 
428     ForwardingDecision OpDecision =
429         forwardTree(TargetStmt, LI->getPointerOperand(), DefStmt, DefLoop,
430                     DefToTarget, DoIt);
431     switch (OpDecision) {
432     case FD_CannotForward:
433       assert(!DoIt);
434       return OpDecision;
435 
436     case FD_CanForwardLeaf:
437     case FD_CanForwardTree:
438       assert(!DoIt);
439       break;
440 
441     case FD_DidForward:
442       assert(DoIt);
443       break;
444 
445     default:
446       llvm_unreachable("Shouldn't return this");
447     }
448 
449     // { DomainDef[] -> ValInst[] }
450     isl::map ExpectedVal = makeValInst(Inst, UseStmt, UseLoop);
451 
452     // { DomainTarget[] -> ValInst[] }
453     isl::map TargetExpectedVal = ExpectedVal.apply_domain(UseToTarget);
454     isl::union_map TranslatedExpectedVal =
455         isl::union_map(TargetExpectedVal).apply_range(Translator);
456 
457     // { DomainTarget[] -> Element[] }
458     isl::union_map Candidates = findSameContentElements(TranslatedExpectedVal);
459 
460     isl::map SameVal = singleLocation(Candidates, getDomainFor(TargetStmt));
461     if (!SameVal)
462       return FD_CannotForward;
463 
464     if (!DoIt)
465       return FD_CanForwardTree;
466 
467     if (Access) {
468       DEBUG(dbgs() << "    forwarded known load with preexisting MemoryAccess"
469                    << Access << "\n");
470     } else {
471       Access = makeReadArrayAccess(TargetStmt, LI, SameVal);
472       DEBUG(dbgs() << "    forwarded known load with new MemoryAccess" << Access
473                    << "\n");
474 
475       // { ValInst[] }
476       isl::space ValInstSpace = ExpectedVal.get_space().range();
477 
478       // After adding a new load to the SCoP, also update the Known content
479       // about it. The new load will have a known ValInst of
480       // { [DomainTarget[] -> Value[]] }
481       // but which -- because it is a copy of it -- has same value as the
482       // { [DomainDef[] -> Value[]] }
483       // that it replicates. Instead of  cloning the known content of
484       // [DomainDef[] -> Value[]]
485       // for DomainTarget[], we add a 'translator' that maps
486       // [DomainTarget[] -> Value[]] to [DomainDef[] -> Value[]]
487       // before comparing to the known content.
488       // TODO: 'Translator' could also be used to map PHINodes to their incoming
489       // ValInsts.
490       if (ValInstSpace.is_wrapping()) {
491         // { DefDomain[] -> Value[] }
492         isl::map ValInsts = ExpectedVal.range().unwrap();
493 
494         // { DefDomain[] }
495         isl::set DefDomain = ValInsts.domain();
496 
497         // { Value[] }
498         isl::space ValSpace = ValInstSpace.unwrap().range();
499 
500         // { Value[] -> Value[] }
501         isl::map ValToVal =
502             isl::map::identity(ValSpace.map_from_domain_and_range(ValSpace));
503 
504         // { [TargetDomain[] -> Value[]] -> [DefDomain[] -> Value] }
505         isl::map LocalTranslator = DefToTarget.reverse().product(ValToVal);
506 
507         Translator = Translator.add_map(LocalTranslator);
508         DEBUG(dbgs() << "      local translator is " << LocalTranslator
509                      << "\n");
510       }
511     }
512     DEBUG(dbgs() << "      expected values where " << TargetExpectedVal
513                  << "\n");
514     DEBUG(dbgs() << "      candidate elements where " << Candidates << "\n");
515     assert(Access);
516 
517     NumKnownLoadsForwarded++;
518     TotalKnownLoadsForwarded++;
519     return FD_DidForward;
520   }
521 
522   /// Forwards a speculatively executable instruction.
523   ///
524   /// @param TargetStmt  The statement the operand tree will be copied to.
525   /// @param UseInst     The (possibly speculatable) instruction to forward.
526   /// @param DefStmt     The statement @p UseInst is defined in.
527   /// @param DefLoop     The loop which contains @p UseInst.
528   /// @param DefToTarget { DomainDef[] -> DomainTarget[] }
529   ///                    A mapping from the statement instance @p UseInst is
530   ///                    defined to the statement instance it is forwarded to.
531   /// @param DoIt        If false, only determine whether an operand tree can be
532   ///                    forwarded. If true, carry out the forwarding. Do not
533   ///                    use DoIt==true if an operand tree is not known to be
534   ///                    forwardable.
535   ///
536   /// @return FD_NotApplicable  if @p UseInst is not speculatable.
537   ///         FD_CannotForward  if one of @p UseInst's operands is not
538   ///                           forwardable.
539   ///         FD_CanForwardTree if @p UseInst is forwardable.
540   ///         FD_DidForward     if @p DoIt was true.
541   ForwardingDecision forwardSpeculatable(ScopStmt *TargetStmt,
542                                          Instruction *UseInst,
543                                          ScopStmt *DefStmt, Loop *DefLoop,
544                                          isl::map DefToTarget, bool DoIt) {
545     // PHIs, unless synthesizable, are not yet supported.
546     if (isa<PHINode>(UseInst))
547       return FD_NotApplicable;
548 
549     // Compatible instructions must satisfy the following conditions:
550     // 1. Idempotent (instruction will be copied, not moved; although its
551     //    original instance might be removed by simplification)
552     // 2. Not access memory (There might be memory writes between)
553     // 3. Not cause undefined behaviour (we might copy to a location when the
554     //    original instruction was no executed; this is currently not possible
555     //    because we do not forward PHINodes)
556     // 4. Not leak memory if executed multiple times (i.e. malloc)
557     //
558     // Instruction::mayHaveSideEffects is not sufficient because it considers
559     // malloc to not have side-effects. llvm::isSafeToSpeculativelyExecute is
560     // not sufficient because it allows memory accesses.
561     if (mayBeMemoryDependent(*UseInst))
562       return FD_NotApplicable;
563 
564     if (DoIt) {
565       // To ensure the right order, prepend this instruction before its
566       // operands. This ensures that its operands are inserted before the
567       // instruction using them.
568       // TODO: The operand tree is not really a tree, but a DAG. We should be
569       // able to handle DAGs without duplication.
570       TargetStmt->prependInstruction(UseInst);
571       NumInstructionsCopied++;
572       TotalInstructionsCopied++;
573     }
574 
575     for (Value *OpVal : UseInst->operand_values()) {
576       ForwardingDecision OpDecision =
577           forwardTree(TargetStmt, OpVal, DefStmt, DefLoop, DefToTarget, DoIt);
578       switch (OpDecision) {
579       case FD_CannotForward:
580         assert(!DoIt);
581         return FD_CannotForward;
582 
583       case FD_CanForwardLeaf:
584       case FD_CanForwardTree:
585         assert(!DoIt);
586         break;
587 
588       case FD_DidForward:
589         assert(DoIt);
590         break;
591 
592       case FD_NotApplicable:
593         llvm_unreachable("forwardTree should never return FD_NotApplicable");
594       }
595     }
596 
597     if (DoIt)
598       return FD_DidForward;
599     return FD_CanForwardTree;
600   }
601 
602   /// Determines whether an operand tree can be forwarded or carries out a
603   /// forwarding, depending on the @p DoIt flag.
604   ///
605   /// @param TargetStmt  The statement the operand tree will be copied to.
606   /// @param UseVal      The value (usually an instruction) which is root of an
607   ///                    operand tree.
608   /// @param UseStmt     The statement that uses @p UseVal.
609   /// @param UseLoop     The loop @p UseVal is used in.
610   /// @param UseToTarget { DomainUse[] -> DomainTarget[] }
611   ///                    A mapping from the statement instance @p UseVal is used
612   ///                    to the statement instance it is forwarded to.
613   /// @param DoIt        If false, only determine whether an operand tree can be
614   ///                    forwarded. If true, carry out the forwarding. Do not
615   ///                    use DoIt==true if an operand tree is not known to be
616   ///                    forwardable.
617   ///
618   /// @return If DoIt==false, return whether the operand tree can be forwarded.
619   ///         If DoIt==true, return FD_DidForward.
620   ForwardingDecision forwardTree(ScopStmt *TargetStmt, Value *UseVal,
621                                  ScopStmt *UseStmt, Loop *UseLoop,
622                                  isl::map UseToTarget, bool DoIt) {
623     ScopStmt *DefStmt = nullptr;
624     Loop *DefLoop = nullptr;
625 
626     // { DefDomain[] -> TargetDomain[] }
627     isl::map DefToTarget;
628 
629     VirtualUse VUse = VirtualUse::create(UseStmt, UseLoop, UseVal, true);
630     switch (VUse.getKind()) {
631     case VirtualUse::Constant:
632     case VirtualUse::Block:
633     case VirtualUse::Hoisted:
634       // These can be used anywhere without special considerations.
635       if (DoIt)
636         return FD_DidForward;
637       return FD_CanForwardLeaf;
638 
639     case VirtualUse::Synthesizable: {
640       // ScopExpander will take care for of generating the code at the new
641       // location.
642       if (DoIt)
643         return FD_DidForward;
644 
645       // Check if the value is synthesizable at the new location as well. This
646       // might be possible when leaving a loop for which ScalarEvolution is
647       // unable to derive the exit value for.
648       // TODO: If there is a LCSSA PHI at the loop exit, use that one.
649       // If the SCEV contains a SCEVAddRecExpr, we currently depend on that we
650       // do not forward past its loop header. This would require us to use a
651       // previous loop induction variable instead the current one. We currently
652       // do not allow forwarding PHI nodes, thus this should never occur (the
653       // only exception where no phi is necessary being an unreachable loop
654       // without edge from the outside).
655       VirtualUse TargetUse = VirtualUse::create(
656           S, TargetStmt, TargetStmt->getSurroundingLoop(), UseVal, true);
657       if (TargetUse.getKind() == VirtualUse::Synthesizable)
658         return FD_CanForwardLeaf;
659 
660       DEBUG(dbgs() << "    Synthesizable would not be synthesizable anymore: "
661                    << *UseVal << "\n");
662       return FD_CannotForward;
663     }
664 
665     case VirtualUse::ReadOnly:
666       // Note that we cannot return FD_CanForwardTree here. With a operand tree
667       // depth of 0, UseVal is the use in TargetStmt that we try to replace.
668       // With -polly-analyze-read-only-scalars=true we would ensure the
669       // existence of a MemoryAccess (which already exists for a leaf) and be
670       // removed again by tryForwardTree because it's goal is to remove this
671       // scalar MemoryAccess. It interprets FD_CanForwardTree as the permission
672       // to do so.
673       if (!DoIt)
674         return FD_CanForwardLeaf;
675 
676       // If we model read-only scalars, we need to create a MemoryAccess for it.
677       if (ModelReadOnlyScalars)
678         TargetStmt->ensureValueRead(UseVal);
679 
680       NumReadOnlyCopied++;
681       TotalReadOnlyCopied++;
682       return FD_DidForward;
683 
684     case VirtualUse::Intra:
685       // Knowing that UseStmt and DefStmt are the same statement instance, just
686       // reuse the information about UseStmt for DefStmt
687       DefStmt = UseStmt;
688       DefToTarget = UseToTarget;
689 
690       LLVM_FALLTHROUGH;
691     case VirtualUse::Inter:
692       Instruction *Inst = cast<Instruction>(UseVal);
693 
694       if (!DefStmt) {
695         DefStmt = S->getStmtFor(Inst);
696         if (!DefStmt)
697           return FD_CannotForward;
698       }
699 
700       DefLoop = LI->getLoopFor(Inst->getParent());
701 
702       if (DefToTarget.is_null() && !Known.is_null()) {
703         // { UseDomain[] -> DefDomain[] }
704         isl::map UseToDef = computeUseToDefFlowDependency(UseStmt, DefStmt);
705 
706         // { DefDomain[] -> UseDomain[] -> TargetDomain[] } shortened to
707         // { DefDomain[] -> TargetDomain[] }
708         DefToTarget = UseToTarget.apply_domain(UseToDef);
709         simplify(DefToTarget);
710       }
711 
712       ForwardingDecision SpeculativeResult = forwardSpeculatable(
713           TargetStmt, Inst, DefStmt, DefLoop, DefToTarget, DoIt);
714       if (SpeculativeResult != FD_NotApplicable)
715         return SpeculativeResult;
716 
717       ForwardingDecision KnownResult =
718           forwardKnownLoad(TargetStmt, Inst, UseStmt, UseLoop, UseToTarget,
719                            DefStmt, DefLoop, DefToTarget, DoIt);
720       if (KnownResult != FD_NotApplicable)
721         return KnownResult;
722 
723       // When no method is found to forward the operand tree, we effectively
724       // cannot handle it.
725       DEBUG(dbgs() << "    Cannot forward instruction: " << *Inst << "\n");
726       return FD_CannotForward;
727     }
728 
729     llvm_unreachable("Case unhandled");
730   }
731 
732   /// Try to forward an operand tree rooted in @p RA.
733   bool tryForwardTree(MemoryAccess *RA) {
734     assert(RA->isLatestScalarKind());
735     DEBUG(dbgs() << "Trying to forward operand tree " << RA << "...\n");
736 
737     ScopStmt *Stmt = RA->getStatement();
738     Loop *InLoop = Stmt->getSurroundingLoop();
739 
740     isl::map TargetToUse;
741     if (!Known.is_null()) {
742       isl::space DomSpace = Stmt->getDomainSpace();
743       TargetToUse =
744           isl::map::identity(DomSpace.map_from_domain_and_range(DomSpace));
745     }
746 
747     ForwardingDecision Assessment = forwardTree(
748         Stmt, RA->getAccessValue(), Stmt, InLoop, TargetToUse, false);
749     assert(Assessment != FD_DidForward);
750     if (Assessment != FD_CanForwardTree)
751       return false;
752 
753     ForwardingDecision Execution = forwardTree(Stmt, RA->getAccessValue(), Stmt,
754                                                InLoop, TargetToUse, true);
755     assert(Execution == FD_DidForward &&
756            "A previous positive assessment must also be executable");
757     (void)Execution;
758 
759     Stmt->removeSingleMemoryAccess(RA);
760     return true;
761   }
762 
763   /// Return which SCoP this instance is processing.
764   Scop *getScop() const { return S; }
765 
766   /// Run the algorithm: Use value read accesses as operand tree roots and try
767   /// to forward them into the statement.
768   bool forwardOperandTrees() {
769     for (ScopStmt &Stmt : *S) {
770       bool StmtModified = false;
771 
772       // Because we are modifying the MemoryAccess list, collect them first to
773       // avoid iterator invalidation.
774       SmallVector<MemoryAccess *, 16> Accs;
775       for (MemoryAccess *RA : Stmt) {
776         if (!RA->isRead())
777           continue;
778         if (!RA->isLatestScalarKind())
779           continue;
780 
781         Accs.push_back(RA);
782       }
783 
784       for (MemoryAccess *RA : Accs) {
785         if (tryForwardTree(RA)) {
786           Modified = true;
787           StmtModified = true;
788           NumForwardedTrees++;
789           TotalForwardedTrees++;
790         }
791       }
792 
793       if (StmtModified) {
794         NumModifiedStmts++;
795         TotalModifiedStmts++;
796       }
797     }
798 
799     if (Modified)
800       ScopsModified++;
801     return Modified;
802   }
803 
804   /// Print the pass result, performed transformations and the SCoP after the
805   /// transformation.
806   void print(raw_ostream &OS, int Indent = 0) {
807     printStatistics(OS, Indent);
808 
809     if (!Modified) {
810       // This line can easily be checked in regression tests.
811       OS << "ForwardOpTree executed, but did not modify anything\n";
812       return;
813     }
814 
815     printStatements(OS, Indent);
816   }
817 };
818 
819 /// Pass that redirects scalar reads to array elements that are known to contain
820 /// the same value.
821 ///
822 /// This reduces the number of scalar accesses and therefore potentially
823 /// increases the freedom of the scheduler. In the ideal case, all reads of a
824 /// scalar definition are redirected (We currently do not care about removing
825 /// the write in this case).  This is also useful for the main DeLICM pass as
826 /// there are less scalars to be mapped.
827 class ForwardOpTree : public ScopPass {
828 private:
829   /// The pass implementation, also holding per-scop data.
830   std::unique_ptr<ForwardOpTreeImpl> Impl;
831 
832 public:
833   static char ID;
834 
835   explicit ForwardOpTree() : ScopPass(ID) {}
836   ForwardOpTree(const ForwardOpTree &) = delete;
837   ForwardOpTree &operator=(const ForwardOpTree &) = delete;
838 
839   void getAnalysisUsage(AnalysisUsage &AU) const override {
840     AU.addRequiredTransitive<ScopInfoRegionPass>();
841     AU.addRequired<LoopInfoWrapperPass>();
842     AU.setPreservesAll();
843   }
844 
845   bool runOnScop(Scop &S) override {
846     // Free resources for previous SCoP's computation, if not yet done.
847     releaseMemory();
848 
849     LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
850     Impl = llvm::make_unique<ForwardOpTreeImpl>(&S, &LI);
851 
852     if (AnalyzeKnown) {
853       DEBUG(dbgs() << "Prepare forwarders...\n");
854       Impl->computeKnownValues();
855     }
856 
857     DEBUG(dbgs() << "Forwarding operand trees...\n");
858     Impl->forwardOperandTrees();
859 
860     DEBUG(dbgs() << "\nFinal Scop:\n");
861     DEBUG(dbgs() << S);
862 
863     // Update statistics
864     auto ScopStats = S.getStatistics();
865     NumValueWrites += ScopStats.NumValueWrites;
866     NumValueWritesInLoops += ScopStats.NumValueWritesInLoops;
867     NumPHIWrites += ScopStats.NumPHIWrites;
868     NumPHIWritesInLoops += ScopStats.NumPHIWritesInLoops;
869     NumSingletonWrites += ScopStats.NumSingletonWrites;
870     NumSingletonWritesInLoops += ScopStats.NumSingletonWritesInLoops;
871 
872     return false;
873   }
874 
875   void printScop(raw_ostream &OS, Scop &S) const override {
876     if (!Impl)
877       return;
878 
879     assert(Impl->getScop() == &S);
880     Impl->print(OS);
881   }
882 
883   void releaseMemory() override { Impl.reset(); }
884 }; // class ForwardOpTree
885 
886 char ForwardOpTree::ID;
887 
888 } // namespace
889 
890 ScopPass *polly::createForwardOpTreePass() { return new ForwardOpTree(); }
891 
892 INITIALIZE_PASS_BEGIN(ForwardOpTree, "polly-optree",
893                       "Polly - Forward operand tree", false, false)
894 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
895 INITIALIZE_PASS_END(ForwardOpTree, "polly-optree",
896                     "Polly - Forward operand tree", false, false)
897