1 //===------ IslNodeBuilder.cpp - Translate an isl AST into a LLVM-IR AST---===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the IslNodeBuilder, a class to translate an isl AST into
11 // a LLVM-IR AST.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "polly/CodeGen/IslNodeBuilder.h"
16 #include "polly/CodeGen/BlockGenerators.h"
17 #include "polly/CodeGen/CodeGeneration.h"
18 #include "polly/CodeGen/IslAst.h"
19 #include "polly/CodeGen/IslExprBuilder.h"
20 #include "polly/CodeGen/LoopGenerators.h"
21 #include "polly/CodeGen/RuntimeDebugBuilder.h"
22 #include "polly/CodeGen/Utils.h"
23 #include "polly/Config/config.h"
24 #include "polly/DependenceInfo.h"
25 #include "polly/LinkAllPasses.h"
26 #include "polly/Options.h"
27 #include "polly/ScopInfo.h"
28 #include "polly/Support/GICHelper.h"
29 #include "polly/Support/SCEVValidator.h"
30 #include "polly/Support/ScopHelper.h"
31 #include "llvm/ADT/PostOrderIterator.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/Analysis/LoopInfo.h"
34 #include "llvm/IR/DataLayout.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/Verifier.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
40 #include "isl/aff.h"
41 #include "isl/ast.h"
42 #include "isl/ast_build.h"
43 #include "isl/list.h"
44 #include "isl/map.h"
45 #include "isl/set.h"
46 #include "isl/union_map.h"
47 #include "isl/union_set.h"
48 
49 using namespace polly;
50 using namespace llvm;
51 
52 #define DEBUG_TYPE "polly-codegen"
53 
54 STATISTIC(VersionedScops, "Number of SCoPs that required versioning.");
55 
56 static cl::opt<bool> PollyGenerateRTCPrint(
57     "polly-codegen-emit-rtc-print",
58     cl::desc("Emit code that prints the runtime check result dynamically."),
59     cl::Hidden, cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
60 
61 // If this option is set we always use the isl AST generator to regenerate
62 // memory accesses. Without this option set we regenerate expressions using the
63 // original SCEV expressions and only generate new expressions in case the
64 // access relation has been changed and consequently must be regenerated.
65 static cl::opt<bool> PollyGenerateExpressions(
66     "polly-codegen-generate-expressions",
67     cl::desc("Generate AST expressions for unmodified and modified accesses"),
68     cl::Hidden, cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
69 
70 static cl::opt<int> PollyTargetFirstLevelCacheLineSize(
71     "polly-target-first-level-cache-line-size",
72     cl::desc("The size of the first level cache line size specified in bytes."),
73     cl::Hidden, cl::init(64), cl::ZeroOrMore, cl::cat(PollyCategory));
74 
75 __isl_give isl_ast_expr *
76 IslNodeBuilder::getUpperBound(__isl_keep isl_ast_node *For,
77                               ICmpInst::Predicate &Predicate) {
78   isl_id *UBID, *IteratorID;
79   isl_ast_expr *Cond, *Iterator, *UB, *Arg0;
80   isl_ast_op_type Type;
81 
82   Cond = isl_ast_node_for_get_cond(For);
83   Iterator = isl_ast_node_for_get_iterator(For);
84   assert(isl_ast_expr_get_type(Cond) == isl_ast_expr_op &&
85          "conditional expression is not an atomic upper bound");
86 
87   Type = isl_ast_expr_get_op_type(Cond);
88 
89   switch (Type) {
90   case isl_ast_op_le:
91     Predicate = ICmpInst::ICMP_SLE;
92     break;
93   case isl_ast_op_lt:
94     Predicate = ICmpInst::ICMP_SLT;
95     break;
96   default:
97     llvm_unreachable("Unexpected comparison type in loop condition");
98   }
99 
100   Arg0 = isl_ast_expr_get_op_arg(Cond, 0);
101 
102   assert(isl_ast_expr_get_type(Arg0) == isl_ast_expr_id &&
103          "conditional expression is not an atomic upper bound");
104 
105   UBID = isl_ast_expr_get_id(Arg0);
106 
107   assert(isl_ast_expr_get_type(Iterator) == isl_ast_expr_id &&
108          "Could not get the iterator");
109 
110   IteratorID = isl_ast_expr_get_id(Iterator);
111 
112   assert(UBID == IteratorID &&
113          "conditional expression is not an atomic upper bound");
114 
115   UB = isl_ast_expr_get_op_arg(Cond, 1);
116 
117   isl_ast_expr_free(Cond);
118   isl_ast_expr_free(Iterator);
119   isl_ast_expr_free(Arg0);
120   isl_id_free(IteratorID);
121   isl_id_free(UBID);
122 
123   return UB;
124 }
125 
126 /// Return true if a return value of Predicate is true for the value represented
127 /// by passed isl_ast_expr_int.
128 static bool checkIslAstExprInt(__isl_take isl_ast_expr *Expr,
129                                isl_bool (*Predicate)(__isl_keep isl_val *)) {
130   if (isl_ast_expr_get_type(Expr) != isl_ast_expr_int) {
131     isl_ast_expr_free(Expr);
132     return false;
133   }
134   auto ExprVal = isl_ast_expr_get_val(Expr);
135   isl_ast_expr_free(Expr);
136   if (Predicate(ExprVal) != true) {
137     isl_val_free(ExprVal);
138     return false;
139   }
140   isl_val_free(ExprVal);
141   return true;
142 }
143 
144 int IslNodeBuilder::getNumberOfIterations(__isl_keep isl_ast_node *For) {
145   assert(isl_ast_node_get_type(For) == isl_ast_node_for);
146   auto Body = isl_ast_node_for_get_body(For);
147 
148   // First, check if we can actually handle this code.
149   switch (isl_ast_node_get_type(Body)) {
150   case isl_ast_node_user:
151     break;
152   case isl_ast_node_block: {
153     isl_ast_node_list *List = isl_ast_node_block_get_children(Body);
154     for (int i = 0; i < isl_ast_node_list_n_ast_node(List); ++i) {
155       isl_ast_node *Node = isl_ast_node_list_get_ast_node(List, i);
156       int Type = isl_ast_node_get_type(Node);
157       isl_ast_node_free(Node);
158       if (Type != isl_ast_node_user) {
159         isl_ast_node_list_free(List);
160         isl_ast_node_free(Body);
161         return -1;
162       }
163     }
164     isl_ast_node_list_free(List);
165     break;
166   }
167   default:
168     isl_ast_node_free(Body);
169     return -1;
170   }
171   isl_ast_node_free(Body);
172 
173   auto Init = isl_ast_node_for_get_init(For);
174   if (!checkIslAstExprInt(Init, isl_val_is_zero))
175     return -1;
176   auto Inc = isl_ast_node_for_get_inc(For);
177   if (!checkIslAstExprInt(Inc, isl_val_is_one))
178     return -1;
179   CmpInst::Predicate Predicate;
180   auto UB = getUpperBound(For, Predicate);
181   if (isl_ast_expr_get_type(UB) != isl_ast_expr_int) {
182     isl_ast_expr_free(UB);
183     return -1;
184   }
185   auto UpVal = isl_ast_expr_get_val(UB);
186   isl_ast_expr_free(UB);
187   int NumberIterations = isl_val_get_num_si(UpVal);
188   isl_val_free(UpVal);
189   if (NumberIterations < 0)
190     return -1;
191   if (Predicate == CmpInst::ICMP_SLT)
192     return NumberIterations;
193   else
194     return NumberIterations + 1;
195 }
196 
197 /// Extract the values and SCEVs needed to generate code for a block.
198 static int findReferencesInBlock(struct SubtreeReferences &References,
199                                  const ScopStmt *Stmt, const BasicBlock *BB) {
200   for (const Instruction &Inst : *BB)
201     for (Value *SrcVal : Inst.operands()) {
202       auto *Scope = References.LI.getLoopFor(BB);
203       if (canSynthesize(SrcVal, References.S, &References.SE, Scope)) {
204         References.SCEVs.insert(References.SE.getSCEVAtScope(SrcVal, Scope));
205         continue;
206       } else if (Value *NewVal = References.GlobalMap.lookup(SrcVal))
207         References.Values.insert(NewVal);
208     }
209   return 0;
210 }
211 
212 isl_stat addReferencesFromStmt(const ScopStmt *Stmt, void *UserPtr,
213                                bool CreateScalarRefs) {
214   auto &References = *static_cast<struct SubtreeReferences *>(UserPtr);
215 
216   if (Stmt->isBlockStmt())
217     findReferencesInBlock(References, Stmt, Stmt->getBasicBlock());
218   else {
219     assert(Stmt->isRegionStmt() &&
220            "Stmt was neither block nor region statement");
221     for (const BasicBlock *BB : Stmt->getRegion()->blocks())
222       findReferencesInBlock(References, Stmt, BB);
223   }
224 
225   for (auto &Access : *Stmt) {
226     if (Access->isLatestArrayKind()) {
227       auto *BasePtr = Access->getScopArrayInfo()->getBasePtr();
228       if (Instruction *OpInst = dyn_cast<Instruction>(BasePtr))
229         if (Stmt->getParent()->contains(OpInst))
230           continue;
231 
232       References.Values.insert(BasePtr);
233       continue;
234     }
235 
236     if (CreateScalarRefs)
237       References.Values.insert(References.BlockGen.getOrCreateAlloca(*Access));
238   }
239 
240   return isl_stat_ok;
241 }
242 
243 /// Extract the out-of-scop values and SCEVs referenced from a set describing
244 /// a ScopStmt.
245 ///
246 /// This includes the SCEVUnknowns referenced by the SCEVs used in the
247 /// statement and the base pointers of the memory accesses. For scalar
248 /// statements we force the generation of alloca memory locations and list
249 /// these locations in the set of out-of-scop values as well.
250 ///
251 /// @param Set     A set which references the ScopStmt we are interested in.
252 /// @param UserPtr A void pointer that can be casted to a SubtreeReferences
253 ///                structure.
254 static isl_stat addReferencesFromStmtSet(__isl_take isl_set *Set,
255                                          void *UserPtr) {
256   isl_id *Id = isl_set_get_tuple_id(Set);
257   auto *Stmt = static_cast<const ScopStmt *>(isl_id_get_user(Id));
258   isl_id_free(Id);
259   isl_set_free(Set);
260   return addReferencesFromStmt(Stmt, UserPtr);
261 }
262 
263 /// Extract the out-of-scop values and SCEVs referenced from a union set
264 /// referencing multiple ScopStmts.
265 ///
266 /// This includes the SCEVUnknowns referenced by the SCEVs used in the
267 /// statement and the base pointers of the memory accesses. For scalar
268 /// statements we force the generation of alloca memory locations and list
269 /// these locations in the set of out-of-scop values as well.
270 ///
271 /// @param USet       A union set referencing the ScopStmts we are interested
272 ///                   in.
273 /// @param References The SubtreeReferences data structure through which
274 ///                   results are returned and further information is
275 ///                   provided.
276 static void
277 addReferencesFromStmtUnionSet(isl_union_set *USet,
278                               struct SubtreeReferences &References) {
279   isl_union_set_foreach_set(USet, addReferencesFromStmtSet, &References);
280   isl_union_set_free(USet);
281 }
282 
283 __isl_give isl_union_map *
284 IslNodeBuilder::getScheduleForAstNode(__isl_keep isl_ast_node *For) {
285   return IslAstInfo::getSchedule(For);
286 }
287 
288 void IslNodeBuilder::getReferencesInSubtree(__isl_keep isl_ast_node *For,
289                                             SetVector<Value *> &Values,
290                                             SetVector<const Loop *> &Loops) {
291 
292   SetVector<const SCEV *> SCEVs;
293   struct SubtreeReferences References = {
294       LI, SE, S, ValueMap, Values, SCEVs, getBlockGenerator()};
295 
296   for (const auto &I : IDToValue)
297     Values.insert(I.second);
298 
299   // NOTE: this is populated in IslNodeBuilder::addParameters
300   for (const auto &I : OutsideLoopIterations)
301     Values.insert(cast<SCEVUnknown>(I.second)->getValue());
302 
303   isl_union_set *Schedule = isl_union_map_domain(getScheduleForAstNode(For));
304   addReferencesFromStmtUnionSet(Schedule, References);
305 
306   for (const SCEV *Expr : SCEVs) {
307     findValues(Expr, SE, Values);
308     findLoops(Expr, Loops);
309   }
310 
311   Values.remove_if([](const Value *V) { return isa<GlobalValue>(V); });
312 
313   /// Note: Code generation of induction variables of loops outside Scops
314   ///
315   /// Remove loops that contain the scop or that are part of the scop, as they
316   /// are considered local. This leaves only loops that are before the scop, but
317   /// do not contain the scop itself.
318   /// We ignore loops perfectly contained in the Scop because these are already
319   /// generated at `IslNodeBuilder::addParameters`. These `Loops` are loops
320   /// whose induction variables are referred to by the Scop, but the Scop is not
321   /// fully contained in these Loops. Since there can be many of these,
322   /// we choose to codegen these on-demand.
323   /// @see IslNodeBuilder::materializeNonScopLoopInductionVariable.
324   Loops.remove_if([this](const Loop *L) {
325     return S.contains(L) || L->contains(S.getEntry());
326   });
327 
328   // Contains Values that may need to be replaced with other values
329   // due to replacements from the ValueMap. We should make sure
330   // that we return correctly remapped values.
331   // NOTE: this code path is tested by:
332   //     1.  test/Isl/CodeGen/OpenMP/single_loop_with_loop_invariant_baseptr.ll
333   //     2.  test/Isl/CodeGen/OpenMP/loop-body-references-outer-values-3.ll
334   SetVector<Value *> ReplacedValues;
335   for (Value *V : Values) {
336     ReplacedValues.insert(getLatestValue(V));
337   }
338   Values = ReplacedValues;
339 }
340 
341 void IslNodeBuilder::updateValues(ValueMapT &NewValues) {
342   SmallPtrSet<Value *, 5> Inserted;
343 
344   for (const auto &I : IDToValue) {
345     IDToValue[I.first] = NewValues[I.second];
346     Inserted.insert(I.second);
347   }
348 
349   for (const auto &I : NewValues) {
350     if (Inserted.count(I.first))
351       continue;
352 
353     ValueMap[I.first] = I.second;
354   }
355 }
356 
357 Value *IslNodeBuilder::getLatestValue(Value *Original) const {
358   auto It = ValueMap.find(Original);
359   if (It == ValueMap.end())
360     return Original;
361   return It->second;
362 }
363 
364 void IslNodeBuilder::createUserVector(__isl_take isl_ast_node *User,
365                                       std::vector<Value *> &IVS,
366                                       __isl_take isl_id *IteratorID,
367                                       __isl_take isl_union_map *Schedule) {
368   isl_ast_expr *Expr = isl_ast_node_user_get_expr(User);
369   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
370   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
371   isl_ast_expr_free(StmtExpr);
372   ScopStmt *Stmt = (ScopStmt *)isl_id_get_user(Id);
373   std::vector<LoopToScevMapT> VLTS(IVS.size());
374 
375   isl_union_set *Domain = isl_union_set_from_set(Stmt->getDomain().release());
376   Schedule = isl_union_map_intersect_domain(Schedule, Domain);
377   isl_map *S = isl_map_from_union_map(Schedule);
378 
379   auto *NewAccesses = createNewAccesses(Stmt, User);
380   createSubstitutionsVector(Expr, Stmt, VLTS, IVS, IteratorID);
381   VectorBlockGenerator::generate(BlockGen, *Stmt, VLTS, S, NewAccesses);
382   isl_id_to_ast_expr_free(NewAccesses);
383   isl_map_free(S);
384   isl_id_free(Id);
385   isl_ast_node_free(User);
386 }
387 
388 void IslNodeBuilder::createMark(__isl_take isl_ast_node *Node) {
389   auto *Id = isl_ast_node_mark_get_id(Node);
390   auto Child = isl_ast_node_mark_get_node(Node);
391   isl_ast_node_free(Node);
392   // If a child node of a 'SIMD mark' is a loop that has a single iteration,
393   // it will be optimized away and we should skip it.
394   if (!strcmp(isl_id_get_name(Id), "SIMD") &&
395       isl_ast_node_get_type(Child) == isl_ast_node_for) {
396     bool Vector = PollyVectorizerChoice == VECTORIZER_POLLY;
397     int VectorWidth = getNumberOfIterations(Child);
398     if (Vector && 1 < VectorWidth && VectorWidth <= 16)
399       createForVector(Child, VectorWidth);
400     else
401       createForSequential(Child, true);
402     isl_id_free(Id);
403     return;
404   }
405   if (!strcmp(isl_id_get_name(Id), "Inter iteration alias-free")) {
406     auto *BasePtr = static_cast<Value *>(isl_id_get_user(Id));
407     Annotator.addInterIterationAliasFreeBasePtr(BasePtr);
408   }
409   create(Child);
410   isl_id_free(Id);
411 }
412 
413 void IslNodeBuilder::createForVector(__isl_take isl_ast_node *For,
414                                      int VectorWidth) {
415   isl_ast_node *Body = isl_ast_node_for_get_body(For);
416   isl_ast_expr *Init = isl_ast_node_for_get_init(For);
417   isl_ast_expr *Inc = isl_ast_node_for_get_inc(For);
418   isl_ast_expr *Iterator = isl_ast_node_for_get_iterator(For);
419   isl_id *IteratorID = isl_ast_expr_get_id(Iterator);
420 
421   Value *ValueLB = ExprBuilder.create(Init);
422   Value *ValueInc = ExprBuilder.create(Inc);
423 
424   Type *MaxType = ExprBuilder.getType(Iterator);
425   MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType());
426   MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType());
427 
428   if (MaxType != ValueLB->getType())
429     ValueLB = Builder.CreateSExt(ValueLB, MaxType);
430   if (MaxType != ValueInc->getType())
431     ValueInc = Builder.CreateSExt(ValueInc, MaxType);
432 
433   std::vector<Value *> IVS(VectorWidth);
434   IVS[0] = ValueLB;
435 
436   for (int i = 1; i < VectorWidth; i++)
437     IVS[i] = Builder.CreateAdd(IVS[i - 1], ValueInc, "p_vector_iv");
438 
439   isl_union_map *Schedule = getScheduleForAstNode(For);
440   assert(Schedule && "For statement annotation does not contain its schedule");
441 
442   IDToValue[IteratorID] = ValueLB;
443 
444   switch (isl_ast_node_get_type(Body)) {
445   case isl_ast_node_user:
446     createUserVector(Body, IVS, isl_id_copy(IteratorID),
447                      isl_union_map_copy(Schedule));
448     break;
449   case isl_ast_node_block: {
450     isl_ast_node_list *List = isl_ast_node_block_get_children(Body);
451 
452     for (int i = 0; i < isl_ast_node_list_n_ast_node(List); ++i)
453       createUserVector(isl_ast_node_list_get_ast_node(List, i), IVS,
454                        isl_id_copy(IteratorID), isl_union_map_copy(Schedule));
455 
456     isl_ast_node_free(Body);
457     isl_ast_node_list_free(List);
458     break;
459   }
460   default:
461     isl_ast_node_dump(Body);
462     llvm_unreachable("Unhandled isl_ast_node in vectorizer");
463   }
464 
465   IDToValue.erase(IDToValue.find(IteratorID));
466   isl_id_free(IteratorID);
467   isl_union_map_free(Schedule);
468 
469   isl_ast_node_free(For);
470   isl_ast_expr_free(Iterator);
471 }
472 
473 void IslNodeBuilder::createForSequential(__isl_take isl_ast_node *For,
474                                          bool KnownParallel) {
475   isl_ast_node *Body;
476   isl_ast_expr *Init, *Inc, *Iterator, *UB;
477   isl_id *IteratorID;
478   Value *ValueLB, *ValueUB, *ValueInc;
479   Type *MaxType;
480   BasicBlock *ExitBlock;
481   Value *IV;
482   CmpInst::Predicate Predicate;
483   bool Parallel;
484 
485   Parallel = KnownParallel || (IslAstInfo::isParallel(For) &&
486                                !IslAstInfo::isReductionParallel(For));
487 
488   Body = isl_ast_node_for_get_body(For);
489 
490   // isl_ast_node_for_is_degenerate(For)
491   //
492   // TODO: For degenerated loops we could generate a plain assignment.
493   //       However, for now we just reuse the logic for normal loops, which will
494   //       create a loop with a single iteration.
495 
496   Init = isl_ast_node_for_get_init(For);
497   Inc = isl_ast_node_for_get_inc(For);
498   Iterator = isl_ast_node_for_get_iterator(For);
499   IteratorID = isl_ast_expr_get_id(Iterator);
500   UB = getUpperBound(For, Predicate);
501 
502   ValueLB = ExprBuilder.create(Init);
503   ValueUB = ExprBuilder.create(UB);
504   ValueInc = ExprBuilder.create(Inc);
505 
506   MaxType = ExprBuilder.getType(Iterator);
507   MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType());
508   MaxType = ExprBuilder.getWidestType(MaxType, ValueUB->getType());
509   MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType());
510 
511   if (MaxType != ValueLB->getType())
512     ValueLB = Builder.CreateSExt(ValueLB, MaxType);
513   if (MaxType != ValueUB->getType())
514     ValueUB = Builder.CreateSExt(ValueUB, MaxType);
515   if (MaxType != ValueInc->getType())
516     ValueInc = Builder.CreateSExt(ValueInc, MaxType);
517 
518   // If we can show that LB <Predicate> UB holds at least once, we can
519   // omit the GuardBB in front of the loop.
520   bool UseGuardBB =
521       !SE.isKnownPredicate(Predicate, SE.getSCEV(ValueLB), SE.getSCEV(ValueUB));
522   IV = createLoop(ValueLB, ValueUB, ValueInc, Builder, LI, DT, ExitBlock,
523                   Predicate, &Annotator, Parallel, UseGuardBB);
524   IDToValue[IteratorID] = IV;
525 
526   create(Body);
527 
528   Annotator.popLoop(Parallel);
529 
530   IDToValue.erase(IDToValue.find(IteratorID));
531 
532   Builder.SetInsertPoint(&ExitBlock->front());
533 
534   isl_ast_node_free(For);
535   isl_ast_expr_free(Iterator);
536   isl_id_free(IteratorID);
537 }
538 
539 /// Remove the BBs contained in a (sub)function from the dominator tree.
540 ///
541 /// This function removes the basic blocks that are part of a subfunction from
542 /// the dominator tree. Specifically, when generating code it may happen that at
543 /// some point the code generation continues in a new sub-function (e.g., when
544 /// generating OpenMP code). The basic blocks that are created in this
545 /// sub-function are then still part of the dominator tree of the original
546 /// function, such that the dominator tree reaches over function boundaries.
547 /// This is not only incorrect, but also causes crashes. This function now
548 /// removes from the dominator tree all basic blocks that are dominated (and
549 /// consequently reachable) from the entry block of this (sub)function.
550 ///
551 /// FIXME: A LLVM (function or region) pass should not touch anything outside of
552 /// the function/region it runs on. Hence, the pure need for this function shows
553 /// that we do not comply to this rule. At the moment, this does not cause any
554 /// issues, but we should be aware that such issues may appear. Unfortunately
555 /// the current LLVM pass infrastructure does not allow to make Polly a module
556 /// or call-graph pass to solve this issue, as such a pass would not have access
557 /// to the per-function analyses passes needed by Polly. A future pass manager
558 /// infrastructure is supposed to enable such kind of access possibly allowing
559 /// us to create a cleaner solution here.
560 ///
561 /// FIXME: Instead of adding the dominance information and then dropping it
562 /// later on, we should try to just not add it in the first place. This requires
563 /// some careful testing to make sure this does not break in interaction with
564 /// the SCEVBuilder and SplitBlock which may rely on the dominator tree or
565 /// which may try to update it.
566 ///
567 /// @param F The function which contains the BBs to removed.
568 /// @param DT The dominator tree from which to remove the BBs.
569 static void removeSubFuncFromDomTree(Function *F, DominatorTree &DT) {
570   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
571   std::vector<BasicBlock *> Nodes;
572 
573   // We can only remove an element from the dominator tree, if all its children
574   // have been removed. To ensure this we obtain the list of nodes to remove
575   // using a post-order tree traversal.
576   for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
577     Nodes.push_back(I->getBlock());
578 
579   for (BasicBlock *BB : Nodes)
580     DT.eraseNode(BB);
581 }
582 
583 void IslNodeBuilder::createForParallel(__isl_take isl_ast_node *For) {
584   isl_ast_node *Body;
585   isl_ast_expr *Init, *Inc, *Iterator, *UB;
586   isl_id *IteratorID;
587   Value *ValueLB, *ValueUB, *ValueInc;
588   Type *MaxType;
589   Value *IV;
590   CmpInst::Predicate Predicate;
591 
592   // The preamble of parallel code interacts different than normal code with
593   // e.g., scalar initialization. Therefore, we ensure the parallel code is
594   // separated from the last basic block.
595   BasicBlock *ParBB = SplitBlock(Builder.GetInsertBlock(),
596                                  &*Builder.GetInsertPoint(), &DT, &LI);
597   ParBB->setName("polly.parallel.for");
598   Builder.SetInsertPoint(&ParBB->front());
599 
600   Body = isl_ast_node_for_get_body(For);
601   Init = isl_ast_node_for_get_init(For);
602   Inc = isl_ast_node_for_get_inc(For);
603   Iterator = isl_ast_node_for_get_iterator(For);
604   IteratorID = isl_ast_expr_get_id(Iterator);
605   UB = getUpperBound(For, Predicate);
606 
607   ValueLB = ExprBuilder.create(Init);
608   ValueUB = ExprBuilder.create(UB);
609   ValueInc = ExprBuilder.create(Inc);
610 
611   // OpenMP always uses SLE. In case the isl generated AST uses a SLT
612   // expression, we need to adjust the loop bound by one.
613   if (Predicate == CmpInst::ICMP_SLT)
614     ValueUB = Builder.CreateAdd(
615         ValueUB, Builder.CreateSExt(Builder.getTrue(), ValueUB->getType()));
616 
617   MaxType = ExprBuilder.getType(Iterator);
618   MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType());
619   MaxType = ExprBuilder.getWidestType(MaxType, ValueUB->getType());
620   MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType());
621 
622   if (MaxType != ValueLB->getType())
623     ValueLB = Builder.CreateSExt(ValueLB, MaxType);
624   if (MaxType != ValueUB->getType())
625     ValueUB = Builder.CreateSExt(ValueUB, MaxType);
626   if (MaxType != ValueInc->getType())
627     ValueInc = Builder.CreateSExt(ValueInc, MaxType);
628 
629   BasicBlock::iterator LoopBody;
630 
631   SetVector<Value *> SubtreeValues;
632   SetVector<const Loop *> Loops;
633 
634   getReferencesInSubtree(For, SubtreeValues, Loops);
635 
636   // Create for all loops we depend on values that contain the current loop
637   // iteration. These values are necessary to generate code for SCEVs that
638   // depend on such loops. As a result we need to pass them to the subfunction.
639   // See [Code generation of induction variables of loops outside Scops]
640   for (const Loop *L : Loops) {
641     Value *LoopInductionVar = materializeNonScopLoopInductionVariable(L);
642     SubtreeValues.insert(LoopInductionVar);
643   }
644 
645   ValueMapT NewValues;
646   ParallelLoopGenerator ParallelLoopGen(Builder, LI, DT, DL);
647 
648   IV = ParallelLoopGen.createParallelLoop(ValueLB, ValueUB, ValueInc,
649                                           SubtreeValues, NewValues, &LoopBody);
650   BasicBlock::iterator AfterLoop = Builder.GetInsertPoint();
651   Builder.SetInsertPoint(&*LoopBody);
652 
653   // Remember the parallel subfunction
654   ParallelSubfunctions.push_back(LoopBody->getFunction());
655 
656   // Save the current values.
657   auto ValueMapCopy = ValueMap;
658   IslExprBuilder::IDToValueTy IDToValueCopy = IDToValue;
659 
660   updateValues(NewValues);
661   IDToValue[IteratorID] = IV;
662 
663   ValueMapT NewValuesReverse;
664 
665   for (auto P : NewValues)
666     NewValuesReverse[P.second] = P.first;
667 
668   Annotator.addAlternativeAliasBases(NewValuesReverse);
669 
670   create(Body);
671 
672   Annotator.resetAlternativeAliasBases();
673   // Restore the original values.
674   ValueMap = ValueMapCopy;
675   IDToValue = IDToValueCopy;
676 
677   Builder.SetInsertPoint(&*AfterLoop);
678   removeSubFuncFromDomTree((*LoopBody).getParent()->getParent(), DT);
679 
680   for (const Loop *L : Loops)
681     OutsideLoopIterations.erase(L);
682 
683   isl_ast_node_free(For);
684   isl_ast_expr_free(Iterator);
685   isl_id_free(IteratorID);
686 }
687 
688 /// Return whether any of @p Node's statements contain partial accesses.
689 ///
690 /// Partial accesses are not supported by Polly's vector code generator.
691 static bool hasPartialAccesses(__isl_take isl_ast_node *Node) {
692   return isl_ast_node_foreach_descendant_top_down(
693              Node,
694              [](isl_ast_node *Node, void *User) -> isl_bool {
695                if (isl_ast_node_get_type(Node) != isl_ast_node_user)
696                  return isl_bool_true;
697 
698                isl::ast_expr Expr = give(isl_ast_node_user_get_expr(Node));
699                isl::ast_expr StmtExpr =
700                    give(isl_ast_expr_get_op_arg(Expr.keep(), 0));
701                isl::id Id = give(isl_ast_expr_get_id(StmtExpr.keep()));
702 
703                ScopStmt *Stmt =
704                    static_cast<ScopStmt *>(isl_id_get_user(Id.keep()));
705                isl::set StmtDom = Stmt->getDomain();
706                for (auto *MA : *Stmt) {
707                  if (MA->isLatestPartialAccess())
708                    return isl_bool_error;
709                }
710                return isl_bool_true;
711              },
712              nullptr) == isl_stat_error;
713 }
714 
715 void IslNodeBuilder::createFor(__isl_take isl_ast_node *For) {
716   bool Vector = PollyVectorizerChoice == VECTORIZER_POLLY;
717 
718   if (Vector && IslAstInfo::isInnermostParallel(For) &&
719       !IslAstInfo::isReductionParallel(For)) {
720     int VectorWidth = getNumberOfIterations(For);
721     if (1 < VectorWidth && VectorWidth <= 16 && !hasPartialAccesses(For)) {
722       createForVector(For, VectorWidth);
723       return;
724     }
725   }
726 
727   if (IslAstInfo::isExecutedInParallel(For)) {
728     createForParallel(For);
729     return;
730   }
731   createForSequential(For, false);
732 }
733 
734 void IslNodeBuilder::createIf(__isl_take isl_ast_node *If) {
735   isl_ast_expr *Cond = isl_ast_node_if_get_cond(If);
736 
737   Function *F = Builder.GetInsertBlock()->getParent();
738   LLVMContext &Context = F->getContext();
739 
740   BasicBlock *CondBB = SplitBlock(Builder.GetInsertBlock(),
741                                   &*Builder.GetInsertPoint(), &DT, &LI);
742   CondBB->setName("polly.cond");
743   BasicBlock *MergeBB = SplitBlock(CondBB, &CondBB->front(), &DT, &LI);
744   MergeBB->setName("polly.merge");
745   BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
746   BasicBlock *ElseBB = BasicBlock::Create(Context, "polly.else", F);
747 
748   DT.addNewBlock(ThenBB, CondBB);
749   DT.addNewBlock(ElseBB, CondBB);
750   DT.changeImmediateDominator(MergeBB, CondBB);
751 
752   Loop *L = LI.getLoopFor(CondBB);
753   if (L) {
754     L->addBasicBlockToLoop(ThenBB, LI);
755     L->addBasicBlockToLoop(ElseBB, LI);
756   }
757 
758   CondBB->getTerminator()->eraseFromParent();
759 
760   Builder.SetInsertPoint(CondBB);
761   Value *Predicate = ExprBuilder.create(Cond);
762   Builder.CreateCondBr(Predicate, ThenBB, ElseBB);
763   Builder.SetInsertPoint(ThenBB);
764   Builder.CreateBr(MergeBB);
765   Builder.SetInsertPoint(ElseBB);
766   Builder.CreateBr(MergeBB);
767   Builder.SetInsertPoint(&ThenBB->front());
768 
769   create(isl_ast_node_if_get_then(If));
770 
771   Builder.SetInsertPoint(&ElseBB->front());
772 
773   if (isl_ast_node_if_has_else(If))
774     create(isl_ast_node_if_get_else(If));
775 
776   Builder.SetInsertPoint(&MergeBB->front());
777 
778   isl_ast_node_free(If);
779 }
780 
781 __isl_give isl_id_to_ast_expr *
782 IslNodeBuilder::createNewAccesses(ScopStmt *Stmt,
783                                   __isl_keep isl_ast_node *Node) {
784   isl_id_to_ast_expr *NewAccesses =
785       isl_id_to_ast_expr_alloc(Stmt->getParent()->getIslCtx(), 0);
786 
787   auto *Build = IslAstInfo::getBuild(Node);
788   assert(Build && "Could not obtain isl_ast_build from user node");
789   Stmt->setAstBuild(isl::manage(isl_ast_build_copy(Build)));
790 
791   for (auto *MA : *Stmt) {
792     if (!MA->hasNewAccessRelation()) {
793       if (PollyGenerateExpressions) {
794         if (!MA->isAffine())
795           continue;
796         if (MA->getLatestScopArrayInfo()->getBasePtrOriginSAI())
797           continue;
798 
799         auto *BasePtr =
800             dyn_cast<Instruction>(MA->getLatestScopArrayInfo()->getBasePtr());
801         if (BasePtr && Stmt->getParent()->getRegion().contains(BasePtr))
802           continue;
803       } else {
804         continue;
805       }
806     }
807     assert(MA->isAffine() &&
808            "Only affine memory accesses can be code generated");
809 
810     auto Schedule = isl_ast_build_get_schedule(Build);
811 
812 #ifndef NDEBUG
813     if (MA->isRead()) {
814       auto Dom = Stmt->getDomain().release();
815       auto SchedDom = isl_set_from_union_set(
816           isl_union_map_domain(isl_union_map_copy(Schedule)));
817       auto AccDom = isl_map_domain(MA->getAccessRelation().release());
818       Dom = isl_set_intersect_params(Dom,
819                                      Stmt->getParent()->getContext().release());
820       SchedDom = isl_set_intersect_params(
821           SchedDom, Stmt->getParent()->getContext().release());
822       assert(isl_set_is_subset(SchedDom, AccDom) &&
823              "Access relation not defined on full schedule domain");
824       assert(isl_set_is_subset(Dom, AccDom) &&
825              "Access relation not defined on full domain");
826       isl_set_free(AccDom);
827       isl_set_free(SchedDom);
828       isl_set_free(Dom);
829     }
830 #endif
831 
832     auto PWAccRel =
833         MA->applyScheduleToAccessRelation(isl::manage(Schedule)).release();
834 
835     // isl cannot generate an index expression for access-nothing accesses.
836     isl::set AccDomain =
837         give(isl_pw_multi_aff_domain(isl_pw_multi_aff_copy(PWAccRel)));
838     if (isl_set_is_empty(AccDomain.keep()) == isl_bool_true) {
839       isl_pw_multi_aff_free(PWAccRel);
840       continue;
841     }
842 
843     auto AccessExpr = isl_ast_build_access_from_pw_multi_aff(Build, PWAccRel);
844     NewAccesses =
845         isl_id_to_ast_expr_set(NewAccesses, MA->getId().release(), AccessExpr);
846   }
847 
848   return NewAccesses;
849 }
850 
851 void IslNodeBuilder::createSubstitutions(__isl_take isl_ast_expr *Expr,
852                                          ScopStmt *Stmt, LoopToScevMapT &LTS) {
853   assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
854          "Expression of type 'op' expected");
855   assert(isl_ast_expr_get_op_type(Expr) == isl_ast_op_call &&
856          "Operation of type 'call' expected");
857   for (int i = 0; i < isl_ast_expr_get_op_n_arg(Expr) - 1; ++i) {
858     isl_ast_expr *SubExpr;
859     Value *V;
860 
861     SubExpr = isl_ast_expr_get_op_arg(Expr, i + 1);
862     V = ExprBuilder.create(SubExpr);
863     ScalarEvolution *SE = Stmt->getParent()->getSE();
864     LTS[Stmt->getLoopForDimension(i)] = SE->getUnknown(V);
865   }
866 
867   isl_ast_expr_free(Expr);
868 }
869 
870 void IslNodeBuilder::createSubstitutionsVector(
871     __isl_take isl_ast_expr *Expr, ScopStmt *Stmt,
872     std::vector<LoopToScevMapT> &VLTS, std::vector<Value *> &IVS,
873     __isl_take isl_id *IteratorID) {
874   int i = 0;
875 
876   Value *OldValue = IDToValue[IteratorID];
877   for (Value *IV : IVS) {
878     IDToValue[IteratorID] = IV;
879     createSubstitutions(isl_ast_expr_copy(Expr), Stmt, VLTS[i]);
880     i++;
881   }
882 
883   IDToValue[IteratorID] = OldValue;
884   isl_id_free(IteratorID);
885   isl_ast_expr_free(Expr);
886 }
887 
888 void IslNodeBuilder::generateCopyStmt(
889     ScopStmt *Stmt, __isl_keep isl_id_to_ast_expr *NewAccesses) {
890   assert(Stmt->size() == 2);
891   auto ReadAccess = Stmt->begin();
892   auto WriteAccess = ReadAccess++;
893   assert((*ReadAccess)->isRead() && (*WriteAccess)->isMustWrite());
894   assert((*ReadAccess)->getElementType() == (*WriteAccess)->getElementType() &&
895          "Accesses use the same data type");
896   assert((*ReadAccess)->isArrayKind() && (*WriteAccess)->isArrayKind());
897   auto *AccessExpr =
898       isl_id_to_ast_expr_get(NewAccesses, (*ReadAccess)->getId().release());
899   auto *LoadValue = ExprBuilder.create(AccessExpr);
900   AccessExpr =
901       isl_id_to_ast_expr_get(NewAccesses, (*WriteAccess)->getId().release());
902   auto *StoreAddr = ExprBuilder.createAccessAddress(AccessExpr);
903   Builder.CreateStore(LoadValue, StoreAddr);
904 }
905 
906 Value *IslNodeBuilder::materializeNonScopLoopInductionVariable(const Loop *L) {
907   assert(OutsideLoopIterations.find(L) == OutsideLoopIterations.end() &&
908          "trying to materialize loop induction variable twice");
909   const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
910                                           SE.getUnknown(Builder.getInt64(1)), L,
911                                           SCEV::FlagAnyWrap);
912   Value *V = generateSCEV(OuterLIV);
913   OutsideLoopIterations[L] = SE.getUnknown(V);
914   return V;
915 }
916 
917 void IslNodeBuilder::createUser(__isl_take isl_ast_node *User) {
918   LoopToScevMapT LTS;
919   isl_id *Id;
920   ScopStmt *Stmt;
921 
922   isl_ast_expr *Expr = isl_ast_node_user_get_expr(User);
923   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
924   Id = isl_ast_expr_get_id(StmtExpr);
925   isl_ast_expr_free(StmtExpr);
926 
927   LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
928 
929   Stmt = (ScopStmt *)isl_id_get_user(Id);
930   auto *NewAccesses = createNewAccesses(Stmt, User);
931   if (Stmt->isCopyStmt()) {
932     generateCopyStmt(Stmt, NewAccesses);
933     isl_ast_expr_free(Expr);
934   } else {
935     createSubstitutions(Expr, Stmt, LTS);
936 
937     if (Stmt->isBlockStmt())
938       BlockGen.copyStmt(*Stmt, LTS, NewAccesses);
939     else
940       RegionGen.copyStmt(*Stmt, LTS, NewAccesses);
941   }
942 
943   isl_id_to_ast_expr_free(NewAccesses);
944   isl_ast_node_free(User);
945   isl_id_free(Id);
946 }
947 
948 void IslNodeBuilder::createBlock(__isl_take isl_ast_node *Block) {
949   isl_ast_node_list *List = isl_ast_node_block_get_children(Block);
950 
951   for (int i = 0; i < isl_ast_node_list_n_ast_node(List); ++i)
952     create(isl_ast_node_list_get_ast_node(List, i));
953 
954   isl_ast_node_free(Block);
955   isl_ast_node_list_free(List);
956 }
957 
958 void IslNodeBuilder::create(__isl_take isl_ast_node *Node) {
959   switch (isl_ast_node_get_type(Node)) {
960   case isl_ast_node_error:
961     llvm_unreachable("code generation error");
962   case isl_ast_node_mark:
963     createMark(Node);
964     return;
965   case isl_ast_node_for:
966     createFor(Node);
967     return;
968   case isl_ast_node_if:
969     createIf(Node);
970     return;
971   case isl_ast_node_user:
972     createUser(Node);
973     return;
974   case isl_ast_node_block:
975     createBlock(Node);
976     return;
977   }
978 
979   llvm_unreachable("Unknown isl_ast_node type");
980 }
981 
982 bool IslNodeBuilder::materializeValue(isl_id *Id) {
983   // If the Id is already mapped, skip it.
984   if (!IDToValue.count(Id)) {
985     auto *ParamSCEV = (const SCEV *)isl_id_get_user(Id);
986     Value *V = nullptr;
987 
988     // Parameters could refer to invariant loads that need to be
989     // preloaded before we can generate code for the parameter. Thus,
990     // check if any value referred to in ParamSCEV is an invariant load
991     // and if so make sure its equivalence class is preloaded.
992     SetVector<Value *> Values;
993     findValues(ParamSCEV, SE, Values);
994     for (auto *Val : Values) {
995 
996       // Check if the value is an instruction in a dead block within the SCoP
997       // and if so do not code generate it.
998       if (auto *Inst = dyn_cast<Instruction>(Val)) {
999         if (S.contains(Inst)) {
1000           bool IsDead = true;
1001 
1002           // Check for "undef" loads first, then if there is a statement for
1003           // the parent of Inst and lastly if the parent of Inst has an empty
1004           // domain. In the first and last case the instruction is dead but if
1005           // there is a statement or the domain is not empty Inst is not dead.
1006           auto MemInst = MemAccInst::dyn_cast(Inst);
1007           auto Address = MemInst ? MemInst.getPointerOperand() : nullptr;
1008           if (Address && SE.getUnknown(UndefValue::get(Address->getType())) ==
1009                              SE.getPointerBase(SE.getSCEV(Address))) {
1010           } else if (S.getStmtFor(Inst)) {
1011             IsDead = false;
1012           } else {
1013             auto *Domain = S.getDomainConditions(Inst->getParent()).release();
1014             IsDead = isl_set_is_empty(Domain);
1015             isl_set_free(Domain);
1016           }
1017 
1018           if (IsDead) {
1019             V = UndefValue::get(ParamSCEV->getType());
1020             break;
1021           }
1022         }
1023       }
1024 
1025       if (auto *IAClass = S.lookupInvariantEquivClass(Val)) {
1026 
1027         // Check if this invariant access class is empty, hence if we never
1028         // actually added a loads instruction to it. In that case it has no
1029         // (meaningful) users and we should not try to code generate it.
1030         if (IAClass->InvariantAccesses.empty())
1031           V = UndefValue::get(ParamSCEV->getType());
1032 
1033         if (!preloadInvariantEquivClass(*IAClass)) {
1034           isl_id_free(Id);
1035           return false;
1036         }
1037       }
1038     }
1039 
1040     V = V ? V : generateSCEV(ParamSCEV);
1041     IDToValue[Id] = V;
1042   }
1043 
1044   isl_id_free(Id);
1045   return true;
1046 }
1047 
1048 bool IslNodeBuilder::materializeParameters(isl_set *Set) {
1049   for (unsigned i = 0, e = isl_set_dim(Set, isl_dim_param); i < e; ++i) {
1050     if (!isl_set_involves_dims(Set, isl_dim_param, i, 1))
1051       continue;
1052     isl_id *Id = isl_set_get_dim_id(Set, isl_dim_param, i);
1053     if (!materializeValue(Id))
1054       return false;
1055   }
1056   return true;
1057 }
1058 
1059 bool IslNodeBuilder::materializeParameters() {
1060   for (const SCEV *Param : S.parameters()) {
1061     isl_id *Id = S.getIdForParam(Param).release();
1062     if (!materializeValue(Id))
1063       return false;
1064   }
1065   return true;
1066 }
1067 
1068 /// Generate the computation of the size of the outermost dimension from the
1069 /// Fortran array descriptor (in this case, `@g_arr`). The final `%size`
1070 /// contains the size of the array.
1071 ///
1072 /// %arrty = type { i8*, i64, i64, [3 x %desc.dimensionty] }
1073 /// %desc.dimensionty = type { i64, i64, i64 }
1074 /// @g_arr = global %arrty zeroinitializer, align 32
1075 /// ...
1076 /// %0 = load i64, i64* getelementptr inbounds
1077 ///                       (%arrty, %arrty* @g_arr, i64 0, i32 3, i64 0, i32 2)
1078 /// %1 = load i64, i64* getelementptr inbounds
1079 ///                      (%arrty, %arrty* @g_arr, i64 0, i32 3, i64 0, i32 1)
1080 /// %2 = sub nsw i64 %0, %1
1081 /// %size = add nsw i64 %2, 1
1082 static Value *buildFADOutermostDimensionLoad(Value *GlobalDescriptor,
1083                                              PollyIRBuilder &Builder,
1084                                              std::string ArrayName) {
1085   assert(GlobalDescriptor && "invalid global descriptor given");
1086 
1087   Value *endIdx[4] = {Builder.getInt64(0), Builder.getInt32(3),
1088                       Builder.getInt64(0), Builder.getInt32(2)};
1089   Value *endPtr = Builder.CreateInBoundsGEP(GlobalDescriptor, endIdx,
1090                                             ArrayName + "_end_ptr");
1091   Value *end = Builder.CreateLoad(endPtr, ArrayName + "_end");
1092 
1093   Value *beginIdx[4] = {Builder.getInt64(0), Builder.getInt32(3),
1094                         Builder.getInt64(0), Builder.getInt32(1)};
1095   Value *beginPtr = Builder.CreateInBoundsGEP(GlobalDescriptor, beginIdx,
1096                                               ArrayName + "_begin_ptr");
1097   Value *begin = Builder.CreateLoad(beginPtr, ArrayName + "_begin");
1098 
1099   Value *size =
1100       Builder.CreateNSWSub(end, begin, ArrayName + "_end_begin_delta");
1101   Type *endType = dyn_cast<IntegerType>(end->getType());
1102   assert(endType && "expected type of end to be integral");
1103 
1104   size = Builder.CreateNSWAdd(end,
1105                               ConstantInt::get(endType, 1, /* signed = */ true),
1106                               ArrayName + "_size");
1107 
1108   return size;
1109 }
1110 
1111 bool IslNodeBuilder::materializeFortranArrayOutermostDimension() {
1112   for (const ScopStmt &Stmt : S) {
1113     for (const MemoryAccess *Access : Stmt) {
1114       if (!Access->isArrayKind())
1115         continue;
1116 
1117       const ScopArrayInfo *Array = Access->getScopArrayInfo();
1118       if (!Array)
1119         continue;
1120 
1121       if (Array->getNumberOfDimensions() == 0)
1122         continue;
1123 
1124       Value *FAD = Access->getFortranArrayDescriptor();
1125       if (!FAD)
1126         continue;
1127 
1128       isl_pw_aff *ParametricPwAff = Array->getDimensionSizePw(0).release();
1129       assert(ParametricPwAff && "parametric pw_aff corresponding "
1130                                 "to outermost dimension does not "
1131                                 "exist");
1132 
1133       isl_id *Id = isl_pw_aff_get_dim_id(ParametricPwAff, isl_dim_param, 0);
1134       isl_pw_aff_free(ParametricPwAff);
1135 
1136       assert(Id && "pw_aff is not parametric");
1137 
1138       if (IDToValue.count(Id)) {
1139         isl_id_free(Id);
1140         continue;
1141       }
1142 
1143       Value *FinalValue =
1144           buildFADOutermostDimensionLoad(FAD, Builder, Array->getName());
1145       assert(FinalValue && "unable to build Fortran array "
1146                            "descriptor load of outermost dimension");
1147       IDToValue[Id] = FinalValue;
1148       isl_id_free(Id);
1149     }
1150   }
1151   return true;
1152 }
1153 
1154 Value *IslNodeBuilder::preloadUnconditionally(isl_set *AccessRange,
1155                                               isl_ast_build *Build,
1156                                               Instruction *AccInst) {
1157   isl_pw_multi_aff *PWAccRel = isl_pw_multi_aff_from_set(AccessRange);
1158   isl_ast_expr *Access =
1159       isl_ast_build_access_from_pw_multi_aff(Build, PWAccRel);
1160   auto *Address = isl_ast_expr_address_of(Access);
1161   auto *AddressValue = ExprBuilder.create(Address);
1162   Value *PreloadVal;
1163 
1164   // Correct the type as the SAI might have a different type than the user
1165   // expects, especially if the base pointer is a struct.
1166   Type *Ty = AccInst->getType();
1167 
1168   auto *Ptr = AddressValue;
1169   auto Name = Ptr->getName();
1170   auto AS = Ptr->getType()->getPointerAddressSpace();
1171   Ptr = Builder.CreatePointerCast(Ptr, Ty->getPointerTo(AS), Name + ".cast");
1172   PreloadVal = Builder.CreateLoad(Ptr, Name + ".load");
1173   if (LoadInst *PreloadInst = dyn_cast<LoadInst>(PreloadVal))
1174     PreloadInst->setAlignment(dyn_cast<LoadInst>(AccInst)->getAlignment());
1175 
1176   // TODO: This is only a hot fix for SCoP sequences that use the same load
1177   //       instruction contained and hoisted by one of the SCoPs.
1178   if (SE.isSCEVable(Ty))
1179     SE.forgetValue(AccInst);
1180 
1181   return PreloadVal;
1182 }
1183 
1184 Value *IslNodeBuilder::preloadInvariantLoad(const MemoryAccess &MA,
1185                                             isl_set *Domain) {
1186 
1187   isl_set *AccessRange = isl_map_range(MA.getAddressFunction().release());
1188   AccessRange = isl_set_gist_params(AccessRange, S.getContext().release());
1189 
1190   if (!materializeParameters(AccessRange)) {
1191     isl_set_free(AccessRange);
1192     isl_set_free(Domain);
1193     return nullptr;
1194   }
1195 
1196   auto *Build =
1197       isl_ast_build_from_context(isl_set_universe(S.getParamSpace().release()));
1198   isl_set *Universe = isl_set_universe(isl_set_get_space(Domain));
1199   bool AlwaysExecuted = isl_set_is_equal(Domain, Universe);
1200   isl_set_free(Universe);
1201 
1202   Instruction *AccInst = MA.getAccessInstruction();
1203   Type *AccInstTy = AccInst->getType();
1204 
1205   Value *PreloadVal = nullptr;
1206   if (AlwaysExecuted) {
1207     PreloadVal = preloadUnconditionally(AccessRange, Build, AccInst);
1208     isl_ast_build_free(Build);
1209     isl_set_free(Domain);
1210     return PreloadVal;
1211   }
1212 
1213   if (!materializeParameters(Domain)) {
1214     isl_ast_build_free(Build);
1215     isl_set_free(AccessRange);
1216     isl_set_free(Domain);
1217     return nullptr;
1218   }
1219 
1220   isl_ast_expr *DomainCond = isl_ast_build_expr_from_set(Build, Domain);
1221   Domain = nullptr;
1222 
1223   ExprBuilder.setTrackOverflow(true);
1224   Value *Cond = ExprBuilder.create(DomainCond);
1225   Value *OverflowHappened = Builder.CreateNot(ExprBuilder.getOverflowState(),
1226                                               "polly.preload.cond.overflown");
1227   Cond = Builder.CreateAnd(Cond, OverflowHappened, "polly.preload.cond.result");
1228   ExprBuilder.setTrackOverflow(false);
1229 
1230   if (!Cond->getType()->isIntegerTy(1))
1231     Cond = Builder.CreateIsNotNull(Cond);
1232 
1233   BasicBlock *CondBB = SplitBlock(Builder.GetInsertBlock(),
1234                                   &*Builder.GetInsertPoint(), &DT, &LI);
1235   CondBB->setName("polly.preload.cond");
1236 
1237   BasicBlock *MergeBB = SplitBlock(CondBB, &CondBB->front(), &DT, &LI);
1238   MergeBB->setName("polly.preload.merge");
1239 
1240   Function *F = Builder.GetInsertBlock()->getParent();
1241   LLVMContext &Context = F->getContext();
1242   BasicBlock *ExecBB = BasicBlock::Create(Context, "polly.preload.exec", F);
1243 
1244   DT.addNewBlock(ExecBB, CondBB);
1245   if (Loop *L = LI.getLoopFor(CondBB))
1246     L->addBasicBlockToLoop(ExecBB, LI);
1247 
1248   auto *CondBBTerminator = CondBB->getTerminator();
1249   Builder.SetInsertPoint(CondBBTerminator);
1250   Builder.CreateCondBr(Cond, ExecBB, MergeBB);
1251   CondBBTerminator->eraseFromParent();
1252 
1253   Builder.SetInsertPoint(ExecBB);
1254   Builder.CreateBr(MergeBB);
1255 
1256   Builder.SetInsertPoint(ExecBB->getTerminator());
1257   Value *PreAccInst = preloadUnconditionally(AccessRange, Build, AccInst);
1258   Builder.SetInsertPoint(MergeBB->getTerminator());
1259   auto *MergePHI = Builder.CreatePHI(
1260       AccInstTy, 2, "polly.preload." + AccInst->getName() + ".merge");
1261   PreloadVal = MergePHI;
1262 
1263   if (!PreAccInst) {
1264     PreloadVal = nullptr;
1265     PreAccInst = UndefValue::get(AccInstTy);
1266   }
1267 
1268   MergePHI->addIncoming(PreAccInst, ExecBB);
1269   MergePHI->addIncoming(Constant::getNullValue(AccInstTy), CondBB);
1270 
1271   isl_ast_build_free(Build);
1272   return PreloadVal;
1273 }
1274 
1275 bool IslNodeBuilder::preloadInvariantEquivClass(
1276     InvariantEquivClassTy &IAClass) {
1277   // For an equivalence class of invariant loads we pre-load the representing
1278   // element with the unified execution context. However, we have to map all
1279   // elements of the class to the one preloaded load as they are referenced
1280   // during the code generation and therefor need to be mapped.
1281   const MemoryAccessList &MAs = IAClass.InvariantAccesses;
1282   if (MAs.empty())
1283     return true;
1284 
1285   MemoryAccess *MA = MAs.front();
1286   assert(MA->isArrayKind() && MA->isRead());
1287 
1288   // If the access function was already mapped, the preload of this equivalence
1289   // class was triggered earlier already and doesn't need to be done again.
1290   if (ValueMap.count(MA->getAccessInstruction()))
1291     return true;
1292 
1293   // Check for recursion which can be caused by additional constraints, e.g.,
1294   // non-finite loop constraints. In such a case we have to bail out and insert
1295   // a "false" runtime check that will cause the original code to be executed.
1296   auto PtrId = std::make_pair(IAClass.IdentifyingPointer, IAClass.AccessType);
1297   if (!PreloadedPtrs.insert(PtrId).second)
1298     return false;
1299 
1300   // The execution context of the IAClass.
1301   isl_set *&ExecutionCtx = IAClass.ExecutionContext;
1302 
1303   // If the base pointer of this class is dependent on another one we have to
1304   // make sure it was preloaded already.
1305   auto *SAI = MA->getScopArrayInfo();
1306   if (auto *BaseIAClass = S.lookupInvariantEquivClass(SAI->getBasePtr())) {
1307     if (!preloadInvariantEquivClass(*BaseIAClass))
1308       return false;
1309 
1310     // After we preloaded the BaseIAClass we adjusted the BaseExecutionCtx and
1311     // we need to refine the ExecutionCtx.
1312     isl_set *BaseExecutionCtx = isl_set_copy(BaseIAClass->ExecutionContext);
1313     ExecutionCtx = isl_set_intersect(ExecutionCtx, BaseExecutionCtx);
1314   }
1315 
1316   // If the size of a dimension is dependent on another class, make sure it is
1317   // preloaded.
1318   for (unsigned i = 1, e = SAI->getNumberOfDimensions(); i < e; ++i) {
1319     const SCEV *Dim = SAI->getDimensionSize(i);
1320     SetVector<Value *> Values;
1321     findValues(Dim, SE, Values);
1322     for (auto *Val : Values) {
1323       if (auto *BaseIAClass = S.lookupInvariantEquivClass(Val)) {
1324         if (!preloadInvariantEquivClass(*BaseIAClass))
1325           return false;
1326 
1327         // After we preloaded the BaseIAClass we adjusted the BaseExecutionCtx
1328         // and we need to refine the ExecutionCtx.
1329         isl_set *BaseExecutionCtx = isl_set_copy(BaseIAClass->ExecutionContext);
1330         ExecutionCtx = isl_set_intersect(ExecutionCtx, BaseExecutionCtx);
1331       }
1332     }
1333   }
1334 
1335   Instruction *AccInst = MA->getAccessInstruction();
1336   Type *AccInstTy = AccInst->getType();
1337 
1338   Value *PreloadVal = preloadInvariantLoad(*MA, isl_set_copy(ExecutionCtx));
1339   if (!PreloadVal)
1340     return false;
1341 
1342   for (const MemoryAccess *MA : MAs) {
1343     Instruction *MAAccInst = MA->getAccessInstruction();
1344     assert(PreloadVal->getType() == MAAccInst->getType());
1345     ValueMap[MAAccInst] = PreloadVal;
1346   }
1347 
1348   if (SE.isSCEVable(AccInstTy)) {
1349     isl_id *ParamId = S.getIdForParam(SE.getSCEV(AccInst)).release();
1350     if (ParamId)
1351       IDToValue[ParamId] = PreloadVal;
1352     isl_id_free(ParamId);
1353   }
1354 
1355   BasicBlock *EntryBB = &Builder.GetInsertBlock()->getParent()->getEntryBlock();
1356   auto *Alloca = new AllocaInst(AccInstTy, DL.getAllocaAddrSpace(),
1357                                 AccInst->getName() + ".preload.s2a");
1358   Alloca->insertBefore(&*EntryBB->getFirstInsertionPt());
1359   Builder.CreateStore(PreloadVal, Alloca);
1360   ValueMapT PreloadedPointer;
1361   PreloadedPointer[PreloadVal] = AccInst;
1362   Annotator.addAlternativeAliasBases(PreloadedPointer);
1363 
1364   for (auto *DerivedSAI : SAI->getDerivedSAIs()) {
1365     Value *BasePtr = DerivedSAI->getBasePtr();
1366 
1367     for (const MemoryAccess *MA : MAs) {
1368       // As the derived SAI information is quite coarse, any load from the
1369       // current SAI could be the base pointer of the derived SAI, however we
1370       // should only change the base pointer of the derived SAI if we actually
1371       // preloaded it.
1372       if (BasePtr == MA->getOriginalBaseAddr()) {
1373         assert(BasePtr->getType() == PreloadVal->getType());
1374         DerivedSAI->setBasePtr(PreloadVal);
1375       }
1376 
1377       // For scalar derived SAIs we remap the alloca used for the derived value.
1378       if (BasePtr == MA->getAccessInstruction())
1379         ScalarMap[DerivedSAI] = Alloca;
1380     }
1381   }
1382 
1383   for (const MemoryAccess *MA : MAs) {
1384 
1385     Instruction *MAAccInst = MA->getAccessInstruction();
1386     // Use the escape system to get the correct value to users outside the SCoP.
1387     BlockGenerator::EscapeUserVectorTy EscapeUsers;
1388     for (auto *U : MAAccInst->users())
1389       if (Instruction *UI = dyn_cast<Instruction>(U))
1390         if (!S.contains(UI))
1391           EscapeUsers.push_back(UI);
1392 
1393     if (EscapeUsers.empty())
1394       continue;
1395 
1396     EscapeMap[MA->getAccessInstruction()] =
1397         std::make_pair(Alloca, std::move(EscapeUsers));
1398   }
1399 
1400   return true;
1401 }
1402 
1403 void IslNodeBuilder::allocateNewArrays(BBPair StartExitBlocks) {
1404   for (auto &SAI : S.arrays()) {
1405     if (SAI->getBasePtr())
1406       continue;
1407 
1408     assert(SAI->getNumberOfDimensions() > 0 && SAI->getDimensionSize(0) &&
1409            "The size of the outermost dimension is used to declare newly "
1410            "created arrays that require memory allocation.");
1411 
1412     Type *NewArrayType = nullptr;
1413 
1414     // Get the size of the array = size(dim_1)*...*size(dim_n)
1415     uint64_t ArraySizeInt = 1;
1416     for (int i = SAI->getNumberOfDimensions() - 1; i >= 0; i--) {
1417       auto *DimSize = SAI->getDimensionSize(i);
1418       unsigned UnsignedDimSize = static_cast<const SCEVConstant *>(DimSize)
1419                                      ->getAPInt()
1420                                      .getLimitedValue();
1421 
1422       if (!NewArrayType)
1423         NewArrayType = SAI->getElementType();
1424 
1425       NewArrayType = ArrayType::get(NewArrayType, UnsignedDimSize);
1426       ArraySizeInt *= UnsignedDimSize;
1427     }
1428 
1429     if (SAI->isOnHeap()) {
1430       LLVMContext &Ctx = NewArrayType->getContext();
1431 
1432       // Get the IntPtrTy from the Datalayout
1433       auto IntPtrTy = DL.getIntPtrType(Ctx);
1434 
1435       // Get the size of the element type in bits
1436       unsigned Size = SAI->getElemSizeInBytes();
1437 
1438       // Insert the malloc call at polly.start
1439       auto InstIt = std::get<0>(StartExitBlocks)->getTerminator();
1440       auto *CreatedArray = CallInst::CreateMalloc(
1441           &*InstIt, IntPtrTy, SAI->getElementType(),
1442           ConstantInt::get(Type::getInt64Ty(Ctx), Size),
1443           ConstantInt::get(Type::getInt64Ty(Ctx), ArraySizeInt), nullptr,
1444           SAI->getName());
1445 
1446       SAI->setBasePtr(CreatedArray);
1447 
1448       // Insert the free call at polly.exiting
1449       CallInst::CreateFree(CreatedArray,
1450                            std::get<1>(StartExitBlocks)->getTerminator());
1451 
1452     } else {
1453       auto InstIt = Builder.GetInsertBlock()
1454                         ->getParent()
1455                         ->getEntryBlock()
1456                         .getTerminator();
1457 
1458       auto *CreatedArray = new AllocaInst(NewArrayType, DL.getAllocaAddrSpace(),
1459                                           SAI->getName(), &*InstIt);
1460       CreatedArray->setAlignment(PollyTargetFirstLevelCacheLineSize);
1461       SAI->setBasePtr(CreatedArray);
1462     }
1463   }
1464 }
1465 
1466 bool IslNodeBuilder::preloadInvariantLoads() {
1467 
1468   auto &InvariantEquivClasses = S.getInvariantAccesses();
1469   if (InvariantEquivClasses.empty())
1470     return true;
1471 
1472   BasicBlock *PreLoadBB = SplitBlock(Builder.GetInsertBlock(),
1473                                      &*Builder.GetInsertPoint(), &DT, &LI);
1474   PreLoadBB->setName("polly.preload.begin");
1475   Builder.SetInsertPoint(&PreLoadBB->front());
1476 
1477   for (auto &IAClass : InvariantEquivClasses)
1478     if (!preloadInvariantEquivClass(IAClass))
1479       return false;
1480 
1481   return true;
1482 }
1483 
1484 void IslNodeBuilder::addParameters(__isl_take isl_set *Context) {
1485   // Materialize values for the parameters of the SCoP.
1486   materializeParameters();
1487 
1488   // materialize the outermost dimension parameters for a Fortran array.
1489   // NOTE: materializeParameters() does not work since it looks through
1490   // the SCEVs. We don't have a corresponding SCEV for the array size
1491   // parameter
1492   materializeFortranArrayOutermostDimension();
1493 
1494   // Generate values for the current loop iteration for all surrounding loops.
1495   //
1496   // We may also reference loops outside of the scop which do not contain the
1497   // scop itself, but as the number of such scops may be arbitrarily large we do
1498   // not generate code for them here, but only at the point of code generation
1499   // where these values are needed.
1500   Loop *L = LI.getLoopFor(S.getEntry());
1501 
1502   while (L != nullptr && S.contains(L))
1503     L = L->getParentLoop();
1504 
1505   while (L != nullptr) {
1506     materializeNonScopLoopInductionVariable(L);
1507     L = L->getParentLoop();
1508   }
1509 
1510   isl_set_free(Context);
1511 }
1512 
1513 Value *IslNodeBuilder::generateSCEV(const SCEV *Expr) {
1514   /// We pass the insert location of our Builder, as Polly ensures during IR
1515   /// generation that there is always a valid CFG into which instructions are
1516   /// inserted. As a result, the insertpoint is known to be always followed by a
1517   /// terminator instruction. This means the insert point may be specified by a
1518   /// terminator instruction, but it can never point to an ->end() iterator
1519   /// which does not have a corresponding instruction. Hence, dereferencing
1520   /// the insertpoint to obtain an instruction is known to be save.
1521   ///
1522   /// We also do not need to update the Builder here, as new instructions are
1523   /// always inserted _before_ the given InsertLocation. As a result, the
1524   /// insert location remains valid.
1525   assert(Builder.GetInsertBlock()->end() != Builder.GetInsertPoint() &&
1526          "Insert location points after last valid instruction");
1527   Instruction *InsertLocation = &*Builder.GetInsertPoint();
1528   return expandCodeFor(S, SE, DL, "polly", Expr, Expr->getType(),
1529                        InsertLocation, &ValueMap,
1530                        StartBlock->getSinglePredecessor());
1531 }
1532 
1533 /// The AST expression we generate to perform the run-time check assumes
1534 /// computations on integer types of infinite size. As we only use 64-bit
1535 /// arithmetic we check for overflows, in case of which we set the result
1536 /// of this run-time check to false to be conservatively correct,
1537 Value *IslNodeBuilder::createRTC(isl_ast_expr *Condition) {
1538   auto ExprBuilder = getExprBuilder();
1539   ExprBuilder.setTrackOverflow(true);
1540   Value *RTC = ExprBuilder.create(Condition);
1541   if (!RTC->getType()->isIntegerTy(1))
1542     RTC = Builder.CreateIsNotNull(RTC);
1543   Value *OverflowHappened =
1544       Builder.CreateNot(ExprBuilder.getOverflowState(), "polly.rtc.overflown");
1545 
1546   if (PollyGenerateRTCPrint) {
1547     auto *F = Builder.GetInsertBlock()->getParent();
1548     RuntimeDebugBuilder::createCPUPrinter(
1549         Builder,
1550         "F: " + F->getName().str() + " R: " + S.getRegion().getNameStr() +
1551             " __RTC: ",
1552         RTC, " Overflow: ", OverflowHappened, "\n");
1553   }
1554 
1555   RTC = Builder.CreateAnd(RTC, OverflowHappened, "polly.rtc.result");
1556   ExprBuilder.setTrackOverflow(false);
1557 
1558   if (!isa<ConstantInt>(RTC))
1559     VersionedScops++;
1560 
1561   return RTC;
1562 }
1563