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/Utils.h"
22 #include "polly/Config/config.h"
23 #include "polly/DependenceInfo.h"
24 #include "polly/LinkAllPasses.h"
25 #include "polly/ScopInfo.h"
26 #include "polly/Support/GICHelper.h"
27 #include "polly/Support/SCEVValidator.h"
28 #include "polly/Support/ScopHelper.h"
29 #include "llvm/ADT/PostOrderIterator.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/Analysis/LoopInfo.h"
32 #include "llvm/Analysis/PostDominators.h"
33 #include "llvm/IR/DataLayout.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/IR/Verifier.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
39 #include "isl/aff.h"
40 #include "isl/ast.h"
41 #include "isl/ast_build.h"
42 #include "isl/list.h"
43 #include "isl/map.h"
44 #include "isl/set.h"
45 #include "isl/union_map.h"
46 #include "isl/union_set.h"
47 
48 using namespace polly;
49 using namespace llvm;
50 
51 // The maximal number of dimensions we allow during invariant load construction.
52 // More complex access ranges will result in very high compile time and are also
53 // unlikely to result in good code. This value is very high and should only
54 // trigger for corner cases (e.g., the "dct_luma" function in h264, SPEC2006).
55 static int const MaxDimensionsInAccessRange = 9;
56 
57 __isl_give isl_ast_expr *
58 IslNodeBuilder::getUpperBound(__isl_keep isl_ast_node *For,
59                               ICmpInst::Predicate &Predicate) {
60   isl_id *UBID, *IteratorID;
61   isl_ast_expr *Cond, *Iterator, *UB, *Arg0;
62   isl_ast_op_type Type;
63 
64   Cond = isl_ast_node_for_get_cond(For);
65   Iterator = isl_ast_node_for_get_iterator(For);
66   isl_ast_expr_get_type(Cond);
67   assert(isl_ast_expr_get_type(Cond) == isl_ast_expr_op &&
68          "conditional expression is not an atomic upper bound");
69 
70   Type = isl_ast_expr_get_op_type(Cond);
71 
72   switch (Type) {
73   case isl_ast_op_le:
74     Predicate = ICmpInst::ICMP_SLE;
75     break;
76   case isl_ast_op_lt:
77     Predicate = ICmpInst::ICMP_SLT;
78     break;
79   default:
80     llvm_unreachable("Unexpected comparision type in loop conditon");
81   }
82 
83   Arg0 = isl_ast_expr_get_op_arg(Cond, 0);
84 
85   assert(isl_ast_expr_get_type(Arg0) == isl_ast_expr_id &&
86          "conditional expression is not an atomic upper bound");
87 
88   UBID = isl_ast_expr_get_id(Arg0);
89 
90   assert(isl_ast_expr_get_type(Iterator) == isl_ast_expr_id &&
91          "Could not get the iterator");
92 
93   IteratorID = isl_ast_expr_get_id(Iterator);
94 
95   assert(UBID == IteratorID &&
96          "conditional expression is not an atomic upper bound");
97 
98   UB = isl_ast_expr_get_op_arg(Cond, 1);
99 
100   isl_ast_expr_free(Cond);
101   isl_ast_expr_free(Iterator);
102   isl_ast_expr_free(Arg0);
103   isl_id_free(IteratorID);
104   isl_id_free(UBID);
105 
106   return UB;
107 }
108 
109 /// @brief Return true if a return value of Predicate is true for the value
110 /// represented by passed isl_ast_expr_int.
111 static bool checkIslAstExprInt(__isl_take isl_ast_expr *Expr,
112                                isl_bool (*Predicate)(__isl_keep isl_val *)) {
113   if (isl_ast_expr_get_type(Expr) != isl_ast_expr_int) {
114     isl_ast_expr_free(Expr);
115     return false;
116   }
117   auto ExprVal = isl_ast_expr_get_val(Expr);
118   isl_ast_expr_free(Expr);
119   if (Predicate(ExprVal) != true) {
120     isl_val_free(ExprVal);
121     return false;
122   }
123   isl_val_free(ExprVal);
124   return true;
125 }
126 
127 int IslNodeBuilder::getNumberOfIterations(__isl_keep isl_ast_node *For) {
128   assert(isl_ast_node_get_type(For) == isl_ast_node_for);
129   auto Body = isl_ast_node_for_get_body(For);
130 
131   // First, check if we can actually handle this code
132   switch (isl_ast_node_get_type(Body)) {
133   case isl_ast_node_user:
134     break;
135   case isl_ast_node_block: {
136     isl_ast_node_list *List = isl_ast_node_block_get_children(Body);
137     for (int i = 0; i < isl_ast_node_list_n_ast_node(List); ++i) {
138       isl_ast_node *Node = isl_ast_node_list_get_ast_node(List, i);
139       int Type = isl_ast_node_get_type(Node);
140       isl_ast_node_free(Node);
141       if (Type != isl_ast_node_user) {
142         isl_ast_node_list_free(List);
143         isl_ast_node_free(Body);
144         return -1;
145       }
146     }
147     isl_ast_node_list_free(List);
148     break;
149   }
150   default:
151     isl_ast_node_free(Body);
152     return -1;
153   }
154   isl_ast_node_free(Body);
155 
156   auto Init = isl_ast_node_for_get_init(For);
157   if (!checkIslAstExprInt(Init, isl_val_is_zero))
158     return -1;
159   auto Inc = isl_ast_node_for_get_inc(For);
160   if (!checkIslAstExprInt(Inc, isl_val_is_one))
161     return -1;
162   CmpInst::Predicate Predicate;
163   auto UB = getUpperBound(For, Predicate);
164   if (isl_ast_expr_get_type(UB) != isl_ast_expr_int) {
165     isl_ast_expr_free(UB);
166     return -1;
167   }
168   auto UpVal = isl_ast_expr_get_val(UB);
169   isl_ast_expr_free(UB);
170   int NumberIterations = isl_val_get_num_si(UpVal);
171   isl_val_free(UpVal);
172   if (NumberIterations < 0)
173     return -1;
174   if (Predicate == CmpInst::ICMP_SLT)
175     return NumberIterations;
176   else
177     return NumberIterations + 1;
178 }
179 
180 struct SubtreeReferences {
181   LoopInfo &LI;
182   ScalarEvolution &SE;
183   Scop &S;
184   ValueMapT &GlobalMap;
185   SetVector<Value *> &Values;
186   SetVector<const SCEV *> &SCEVs;
187   BlockGenerator &BlockGen;
188 };
189 
190 /// @brief Extract the values and SCEVs needed to generate code for a block.
191 static int findReferencesInBlock(struct SubtreeReferences &References,
192                                  const ScopStmt *Stmt, const BasicBlock *BB) {
193   for (const Instruction &Inst : *BB)
194     for (Value *SrcVal : Inst.operands()) {
195       auto *Scope = References.LI.getLoopFor(BB);
196       if (canSynthesize(SrcVal, References.S, &References.LI, &References.SE,
197                         Scope)) {
198         References.SCEVs.insert(References.SE.getSCEVAtScope(SrcVal, Scope));
199         continue;
200       } else if (Value *NewVal = References.GlobalMap.lookup(SrcVal))
201         References.Values.insert(NewVal);
202     }
203   return 0;
204 }
205 
206 /// Extract the out-of-scop values and SCEVs referenced from a ScopStmt.
207 ///
208 /// This includes the SCEVUnknowns referenced by the SCEVs used in the
209 /// statement and the base pointers of the memory accesses. For scalar
210 /// statements we force the generation of alloca memory locations and list
211 /// these locations in the set of out-of-scop values as well.
212 ///
213 /// @param Stmt    The statement for which to extract the information.
214 /// @param UserPtr A void pointer that can be casted to a SubtreeReferences
215 ///                structure.
216 static isl_stat addReferencesFromStmt(const ScopStmt *Stmt, void *UserPtr) {
217   auto &References = *static_cast<struct SubtreeReferences *>(UserPtr);
218 
219   if (Stmt->isBlockStmt())
220     findReferencesInBlock(References, Stmt, Stmt->getBasicBlock());
221   else {
222     assert(Stmt->isRegionStmt() &&
223            "Stmt was neither block nor region statement");
224     for (const BasicBlock *BB : Stmt->getRegion()->blocks())
225       findReferencesInBlock(References, Stmt, BB);
226   }
227 
228   for (auto &Access : *Stmt) {
229     if (Access->isArrayKind()) {
230       auto *BasePtr = Access->getScopArrayInfo()->getBasePtr();
231       if (Instruction *OpInst = dyn_cast<Instruction>(BasePtr))
232         if (Stmt->getParent()->contains(OpInst))
233           continue;
234 
235       References.Values.insert(BasePtr);
236       continue;
237     }
238 
239     References.Values.insert(References.BlockGen.getOrCreateAlloca(*Access));
240   }
241 
242   return isl_stat_ok;
243 }
244 
245 /// Extract the out-of-scop values and SCEVs referenced from a set describing
246 /// a ScopStmt.
247 ///
248 /// This includes the SCEVUnknowns referenced by the SCEVs used in the
249 /// statement and the base pointers of the memory accesses. For scalar
250 /// statements we force the generation of alloca memory locations and list
251 /// these locations in the set of out-of-scop values as well.
252 ///
253 /// @param Set     A set which references the ScopStmt we are interested in.
254 /// @param UserPtr A void pointer that can be casted to a SubtreeReferences
255 ///                structure.
256 static isl_stat addReferencesFromStmtSet(isl_set *Set, void *UserPtr) {
257   isl_id *Id = isl_set_get_tuple_id(Set);
258   auto *Stmt = static_cast<const ScopStmt *>(isl_id_get_user(Id));
259   isl_id_free(Id);
260   isl_set_free(Set);
261   return addReferencesFromStmt(Stmt, UserPtr);
262 }
263 
264 /// Extract the out-of-scop values and SCEVs referenced from a union set
265 /// referencing multiple ScopStmts.
266 ///
267 /// This includes the SCEVUnknowns referenced by the SCEVs used in the
268 /// statement and the base pointers of the memory accesses. For scalar
269 /// statements we force the generation of alloca memory locations and list
270 /// these locations in the set of out-of-scop values as well.
271 ///
272 /// @param USet       A union set referencing the ScopStmts we are interested
273 ///                   in.
274 /// @param References The SubtreeReferences data structure through which
275 ///                   results are returned and further information is
276 ///                   provided.
277 static void
278 addReferencesFromStmtUnionSet(isl_union_set *USet,
279                               struct SubtreeReferences &References) {
280   isl_union_set_foreach_set(USet, addReferencesFromStmtSet, &References);
281   isl_union_set_free(USet);
282 }
283 
284 __isl_give isl_union_map *
285 IslNodeBuilder::getScheduleForAstNode(__isl_keep isl_ast_node *For) {
286   return IslAstInfo::getSchedule(For);
287 }
288 
289 void IslNodeBuilder::getReferencesInSubtree(__isl_keep isl_ast_node *For,
290                                             SetVector<Value *> &Values,
291                                             SetVector<const Loop *> &Loops) {
292 
293   SetVector<const SCEV *> SCEVs;
294   struct SubtreeReferences References = {
295       LI, SE, S, ValueMap, Values, SCEVs, getBlockGenerator()};
296 
297   for (const auto &I : IDToValue)
298     Values.insert(I.second);
299 
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   /// Remove loops that contain the scop or that are part of the scop, as they
314   /// are considered local. This leaves only loops that are before the scop, but
315   /// do not contain the scop itself.
316   Loops.remove_if([this](const Loop *L) {
317     return S.contains(L) || L->contains(S.getEntry());
318   });
319 }
320 
321 void IslNodeBuilder::updateValues(ValueMapT &NewValues) {
322   SmallPtrSet<Value *, 5> Inserted;
323 
324   for (const auto &I : IDToValue) {
325     IDToValue[I.first] = NewValues[I.second];
326     Inserted.insert(I.second);
327   }
328 
329   for (const auto &I : NewValues) {
330     if (Inserted.count(I.first))
331       continue;
332 
333     ValueMap[I.first] = I.second;
334   }
335 }
336 
337 void IslNodeBuilder::createUserVector(__isl_take isl_ast_node *User,
338                                       std::vector<Value *> &IVS,
339                                       __isl_take isl_id *IteratorID,
340                                       __isl_take isl_union_map *Schedule) {
341   isl_ast_expr *Expr = isl_ast_node_user_get_expr(User);
342   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
343   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
344   isl_ast_expr_free(StmtExpr);
345   ScopStmt *Stmt = (ScopStmt *)isl_id_get_user(Id);
346   std::vector<LoopToScevMapT> VLTS(IVS.size());
347 
348   isl_union_set *Domain = isl_union_set_from_set(Stmt->getDomain());
349   Schedule = isl_union_map_intersect_domain(Schedule, Domain);
350   isl_map *S = isl_map_from_union_map(Schedule);
351 
352   auto *NewAccesses = createNewAccesses(Stmt, User);
353   createSubstitutionsVector(Expr, Stmt, VLTS, IVS, IteratorID);
354   VectorBlockGenerator::generate(BlockGen, *Stmt, VLTS, S, NewAccesses);
355   isl_id_to_ast_expr_free(NewAccesses);
356   isl_map_free(S);
357   isl_id_free(Id);
358   isl_ast_node_free(User);
359 }
360 
361 void IslNodeBuilder::createMark(__isl_take isl_ast_node *Node) {
362   auto *Id = isl_ast_node_mark_get_id(Node);
363   auto Child = isl_ast_node_mark_get_node(Node);
364   isl_ast_node_free(Node);
365   // If a child node of a 'SIMD mark' is a loop that has a single iteration,
366   // it will be optimized away and we should skip it.
367   if (!strcmp(isl_id_get_name(Id), "SIMD") &&
368       isl_ast_node_get_type(Child) == isl_ast_node_for) {
369     bool Vector = PollyVectorizerChoice == VECTORIZER_POLLY;
370     int VectorWidth = getNumberOfIterations(Child);
371     if (Vector && 1 < VectorWidth && VectorWidth <= 16)
372       createForVector(Child, VectorWidth);
373     else
374       createForSequential(Child, true);
375     isl_id_free(Id);
376     return;
377   }
378   create(Child);
379   isl_id_free(Id);
380 }
381 
382 void IslNodeBuilder::createForVector(__isl_take isl_ast_node *For,
383                                      int VectorWidth) {
384   isl_ast_node *Body = isl_ast_node_for_get_body(For);
385   isl_ast_expr *Init = isl_ast_node_for_get_init(For);
386   isl_ast_expr *Inc = isl_ast_node_for_get_inc(For);
387   isl_ast_expr *Iterator = isl_ast_node_for_get_iterator(For);
388   isl_id *IteratorID = isl_ast_expr_get_id(Iterator);
389 
390   Value *ValueLB = ExprBuilder.create(Init);
391   Value *ValueInc = ExprBuilder.create(Inc);
392 
393   Type *MaxType = ExprBuilder.getType(Iterator);
394   MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType());
395   MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType());
396 
397   if (MaxType != ValueLB->getType())
398     ValueLB = Builder.CreateSExt(ValueLB, MaxType);
399   if (MaxType != ValueInc->getType())
400     ValueInc = Builder.CreateSExt(ValueInc, MaxType);
401 
402   std::vector<Value *> IVS(VectorWidth);
403   IVS[0] = ValueLB;
404 
405   for (int i = 1; i < VectorWidth; i++)
406     IVS[i] = Builder.CreateAdd(IVS[i - 1], ValueInc, "p_vector_iv");
407 
408   isl_union_map *Schedule = getScheduleForAstNode(For);
409   assert(Schedule && "For statement annotation does not contain its schedule");
410 
411   IDToValue[IteratorID] = ValueLB;
412 
413   switch (isl_ast_node_get_type(Body)) {
414   case isl_ast_node_user:
415     createUserVector(Body, IVS, isl_id_copy(IteratorID),
416                      isl_union_map_copy(Schedule));
417     break;
418   case isl_ast_node_block: {
419     isl_ast_node_list *List = isl_ast_node_block_get_children(Body);
420 
421     for (int i = 0; i < isl_ast_node_list_n_ast_node(List); ++i)
422       createUserVector(isl_ast_node_list_get_ast_node(List, i), IVS,
423                        isl_id_copy(IteratorID), isl_union_map_copy(Schedule));
424 
425     isl_ast_node_free(Body);
426     isl_ast_node_list_free(List);
427     break;
428   }
429   default:
430     isl_ast_node_dump(Body);
431     llvm_unreachable("Unhandled isl_ast_node in vectorizer");
432   }
433 
434   IDToValue.erase(IDToValue.find(IteratorID));
435   isl_id_free(IteratorID);
436   isl_union_map_free(Schedule);
437 
438   isl_ast_node_free(For);
439   isl_ast_expr_free(Iterator);
440 }
441 
442 void IslNodeBuilder::createForSequential(__isl_take isl_ast_node *For,
443                                          bool KnownParallel) {
444   isl_ast_node *Body;
445   isl_ast_expr *Init, *Inc, *Iterator, *UB;
446   isl_id *IteratorID;
447   Value *ValueLB, *ValueUB, *ValueInc;
448   Type *MaxType;
449   BasicBlock *ExitBlock;
450   Value *IV;
451   CmpInst::Predicate Predicate;
452   bool Parallel;
453 
454   Parallel = KnownParallel || (IslAstInfo::isParallel(For) &&
455                                !IslAstInfo::isReductionParallel(For));
456 
457   Body = isl_ast_node_for_get_body(For);
458 
459   // isl_ast_node_for_is_degenerate(For)
460   //
461   // TODO: For degenerated loops we could generate a plain assignment.
462   //       However, for now we just reuse the logic for normal loops, which will
463   //       create a loop with a single iteration.
464 
465   Init = isl_ast_node_for_get_init(For);
466   Inc = isl_ast_node_for_get_inc(For);
467   Iterator = isl_ast_node_for_get_iterator(For);
468   IteratorID = isl_ast_expr_get_id(Iterator);
469   UB = getUpperBound(For, Predicate);
470 
471   ValueLB = ExprBuilder.create(Init);
472   ValueUB = ExprBuilder.create(UB);
473   ValueInc = ExprBuilder.create(Inc);
474 
475   MaxType = ExprBuilder.getType(Iterator);
476   MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType());
477   MaxType = ExprBuilder.getWidestType(MaxType, ValueUB->getType());
478   MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType());
479 
480   if (MaxType != ValueLB->getType())
481     ValueLB = Builder.CreateSExt(ValueLB, MaxType);
482   if (MaxType != ValueUB->getType())
483     ValueUB = Builder.CreateSExt(ValueUB, MaxType);
484   if (MaxType != ValueInc->getType())
485     ValueInc = Builder.CreateSExt(ValueInc, MaxType);
486 
487   // If we can show that LB <Predicate> UB holds at least once, we can
488   // omit the GuardBB in front of the loop.
489   bool UseGuardBB =
490       !SE.isKnownPredicate(Predicate, SE.getSCEV(ValueLB), SE.getSCEV(ValueUB));
491   IV = createLoop(ValueLB, ValueUB, ValueInc, Builder, P, LI, DT, ExitBlock,
492                   Predicate, &Annotator, Parallel, UseGuardBB);
493   IDToValue[IteratorID] = IV;
494 
495   create(Body);
496 
497   Annotator.popLoop(Parallel);
498 
499   IDToValue.erase(IDToValue.find(IteratorID));
500 
501   Builder.SetInsertPoint(&ExitBlock->front());
502 
503   isl_ast_node_free(For);
504   isl_ast_expr_free(Iterator);
505   isl_id_free(IteratorID);
506 }
507 
508 /// @brief Remove the BBs contained in a (sub)function from the dominator tree.
509 ///
510 /// This function removes the basic blocks that are part of a subfunction from
511 /// the dominator tree. Specifically, when generating code it may happen that at
512 /// some point the code generation continues in a new sub-function (e.g., when
513 /// generating OpenMP code). The basic blocks that are created in this
514 /// sub-function are then still part of the dominator tree of the original
515 /// function, such that the dominator tree reaches over function boundaries.
516 /// This is not only incorrect, but also causes crashes. This function now
517 /// removes from the dominator tree all basic blocks that are dominated (and
518 /// consequently reachable) from the entry block of this (sub)function.
519 ///
520 /// FIXME: A LLVM (function or region) pass should not touch anything outside of
521 /// the function/region it runs on. Hence, the pure need for this function shows
522 /// that we do not comply to this rule. At the moment, this does not cause any
523 /// issues, but we should be aware that such issues may appear. Unfortunately
524 /// the current LLVM pass infrastructure does not allow to make Polly a module
525 /// or call-graph pass to solve this issue, as such a pass would not have access
526 /// to the per-function analyses passes needed by Polly. A future pass manager
527 /// infrastructure is supposed to enable such kind of access possibly allowing
528 /// us to create a cleaner solution here.
529 ///
530 /// FIXME: Instead of adding the dominance information and then dropping it
531 /// later on, we should try to just not add it in the first place. This requires
532 /// some careful testing to make sure this does not break in interaction with
533 /// the SCEVBuilder and SplitBlock which may rely on the dominator tree or
534 /// which may try to update it.
535 ///
536 /// @param F The function which contains the BBs to removed.
537 /// @param DT The dominator tree from which to remove the BBs.
538 static void removeSubFuncFromDomTree(Function *F, DominatorTree &DT) {
539   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
540   std::vector<BasicBlock *> Nodes;
541 
542   // We can only remove an element from the dominator tree, if all its children
543   // have been removed. To ensure this we obtain the list of nodes to remove
544   // using a post-order tree traversal.
545   for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
546     Nodes.push_back(I->getBlock());
547 
548   for (BasicBlock *BB : Nodes)
549     DT.eraseNode(BB);
550 }
551 
552 void IslNodeBuilder::createForParallel(__isl_take isl_ast_node *For) {
553   isl_ast_node *Body;
554   isl_ast_expr *Init, *Inc, *Iterator, *UB;
555   isl_id *IteratorID;
556   Value *ValueLB, *ValueUB, *ValueInc;
557   Type *MaxType;
558   Value *IV;
559   CmpInst::Predicate Predicate;
560 
561   // The preamble of parallel code interacts different than normal code with
562   // e.g., scalar initialization. Therefore, we ensure the parallel code is
563   // separated from the last basic block.
564   BasicBlock *ParBB = SplitBlock(Builder.GetInsertBlock(),
565                                  &*Builder.GetInsertPoint(), &DT, &LI);
566   ParBB->setName("polly.parallel.for");
567   Builder.SetInsertPoint(&ParBB->front());
568 
569   Body = isl_ast_node_for_get_body(For);
570   Init = isl_ast_node_for_get_init(For);
571   Inc = isl_ast_node_for_get_inc(For);
572   Iterator = isl_ast_node_for_get_iterator(For);
573   IteratorID = isl_ast_expr_get_id(Iterator);
574   UB = getUpperBound(For, Predicate);
575 
576   ValueLB = ExprBuilder.create(Init);
577   ValueUB = ExprBuilder.create(UB);
578   ValueInc = ExprBuilder.create(Inc);
579 
580   // OpenMP always uses SLE. In case the isl generated AST uses a SLT
581   // expression, we need to adjust the loop blound by one.
582   if (Predicate == CmpInst::ICMP_SLT)
583     ValueUB = Builder.CreateAdd(
584         ValueUB, Builder.CreateSExt(Builder.getTrue(), ValueUB->getType()));
585 
586   MaxType = ExprBuilder.getType(Iterator);
587   MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType());
588   MaxType = ExprBuilder.getWidestType(MaxType, ValueUB->getType());
589   MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType());
590 
591   if (MaxType != ValueLB->getType())
592     ValueLB = Builder.CreateSExt(ValueLB, MaxType);
593   if (MaxType != ValueUB->getType())
594     ValueUB = Builder.CreateSExt(ValueUB, MaxType);
595   if (MaxType != ValueInc->getType())
596     ValueInc = Builder.CreateSExt(ValueInc, MaxType);
597 
598   BasicBlock::iterator LoopBody;
599 
600   SetVector<Value *> SubtreeValues;
601   SetVector<const Loop *> Loops;
602 
603   getReferencesInSubtree(For, SubtreeValues, Loops);
604 
605   // Create for all loops we depend on values that contain the current loop
606   // iteration. These values are necessary to generate code for SCEVs that
607   // depend on such loops. As a result we need to pass them to the subfunction.
608   for (const Loop *L : Loops) {
609     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
610                                             SE.getUnknown(Builder.getInt64(1)),
611                                             L, SCEV::FlagAnyWrap);
612     Value *V = generateSCEV(OuterLIV);
613     OutsideLoopIterations[L] = SE.getUnknown(V);
614     SubtreeValues.insert(V);
615   }
616 
617   ValueMapT NewValues;
618   ParallelLoopGenerator ParallelLoopGen(Builder, P, LI, DT, DL);
619 
620   IV = ParallelLoopGen.createParallelLoop(ValueLB, ValueUB, ValueInc,
621                                           SubtreeValues, NewValues, &LoopBody);
622   BasicBlock::iterator AfterLoop = Builder.GetInsertPoint();
623   Builder.SetInsertPoint(&*LoopBody);
624 
625   // Remember the parallel subfunction
626   ParallelSubfunctions.push_back(LoopBody->getFunction());
627 
628   // Save the current values.
629   auto ValueMapCopy = ValueMap;
630   IslExprBuilder::IDToValueTy IDToValueCopy = IDToValue;
631 
632   updateValues(NewValues);
633   IDToValue[IteratorID] = IV;
634 
635   ValueMapT NewValuesReverse;
636 
637   for (auto P : NewValues)
638     NewValuesReverse[P.second] = P.first;
639 
640   Annotator.addAlternativeAliasBases(NewValuesReverse);
641 
642   create(Body);
643 
644   Annotator.resetAlternativeAliasBases();
645   // Restore the original values.
646   ValueMap = ValueMapCopy;
647   IDToValue = IDToValueCopy;
648 
649   Builder.SetInsertPoint(&*AfterLoop);
650   removeSubFuncFromDomTree((*LoopBody).getParent()->getParent(), DT);
651 
652   for (const Loop *L : Loops)
653     OutsideLoopIterations.erase(L);
654 
655   isl_ast_node_free(For);
656   isl_ast_expr_free(Iterator);
657   isl_id_free(IteratorID);
658 }
659 
660 void IslNodeBuilder::createFor(__isl_take isl_ast_node *For) {
661   bool Vector = PollyVectorizerChoice == VECTORIZER_POLLY;
662 
663   if (Vector && IslAstInfo::isInnermostParallel(For) &&
664       !IslAstInfo::isReductionParallel(For)) {
665     int VectorWidth = getNumberOfIterations(For);
666     if (1 < VectorWidth && VectorWidth <= 16) {
667       createForVector(For, VectorWidth);
668       return;
669     }
670   }
671 
672   if (IslAstInfo::isExecutedInParallel(For)) {
673     createForParallel(For);
674     return;
675   }
676   createForSequential(For, false);
677 }
678 
679 void IslNodeBuilder::createIf(__isl_take isl_ast_node *If) {
680   isl_ast_expr *Cond = isl_ast_node_if_get_cond(If);
681 
682   Function *F = Builder.GetInsertBlock()->getParent();
683   LLVMContext &Context = F->getContext();
684 
685   BasicBlock *CondBB = SplitBlock(Builder.GetInsertBlock(),
686                                   &*Builder.GetInsertPoint(), &DT, &LI);
687   CondBB->setName("polly.cond");
688   BasicBlock *MergeBB = SplitBlock(CondBB, &CondBB->front(), &DT, &LI);
689   MergeBB->setName("polly.merge");
690   BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
691   BasicBlock *ElseBB = BasicBlock::Create(Context, "polly.else", F);
692 
693   DT.addNewBlock(ThenBB, CondBB);
694   DT.addNewBlock(ElseBB, CondBB);
695   DT.changeImmediateDominator(MergeBB, CondBB);
696 
697   Loop *L = LI.getLoopFor(CondBB);
698   if (L) {
699     L->addBasicBlockToLoop(ThenBB, LI);
700     L->addBasicBlockToLoop(ElseBB, LI);
701   }
702 
703   CondBB->getTerminator()->eraseFromParent();
704 
705   Builder.SetInsertPoint(CondBB);
706   Value *Predicate = ExprBuilder.create(Cond);
707   Builder.CreateCondBr(Predicate, ThenBB, ElseBB);
708   Builder.SetInsertPoint(ThenBB);
709   Builder.CreateBr(MergeBB);
710   Builder.SetInsertPoint(ElseBB);
711   Builder.CreateBr(MergeBB);
712   Builder.SetInsertPoint(&ThenBB->front());
713 
714   create(isl_ast_node_if_get_then(If));
715 
716   Builder.SetInsertPoint(&ElseBB->front());
717 
718   if (isl_ast_node_if_has_else(If))
719     create(isl_ast_node_if_get_else(If));
720 
721   Builder.SetInsertPoint(&MergeBB->front());
722 
723   isl_ast_node_free(If);
724 }
725 
726 __isl_give isl_id_to_ast_expr *
727 IslNodeBuilder::createNewAccesses(ScopStmt *Stmt,
728                                   __isl_keep isl_ast_node *Node) {
729   isl_id_to_ast_expr *NewAccesses =
730       isl_id_to_ast_expr_alloc(Stmt->getParent()->getIslCtx(), 0);
731 
732   auto *Build = IslAstInfo::getBuild(Node);
733   assert(Build && "Could not obtain isl_ast_build from user node");
734   Stmt->setAstBuild(Build);
735 
736   for (auto *MA : *Stmt) {
737     if (!MA->hasNewAccessRelation())
738       continue;
739 
740     auto Schedule = isl_ast_build_get_schedule(Build);
741     auto PWAccRel = MA->applyScheduleToAccessRelation(Schedule);
742 
743     auto AccessExpr = isl_ast_build_access_from_pw_multi_aff(Build, PWAccRel);
744     NewAccesses = isl_id_to_ast_expr_set(NewAccesses, MA->getId(), AccessExpr);
745   }
746 
747   return NewAccesses;
748 }
749 
750 void IslNodeBuilder::createSubstitutions(isl_ast_expr *Expr, ScopStmt *Stmt,
751                                          LoopToScevMapT &LTS) {
752   assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
753          "Expression of type 'op' expected");
754   assert(isl_ast_expr_get_op_type(Expr) == isl_ast_op_call &&
755          "Opertation of type 'call' expected");
756   for (int i = 0; i < isl_ast_expr_get_op_n_arg(Expr) - 1; ++i) {
757     isl_ast_expr *SubExpr;
758     Value *V;
759 
760     SubExpr = isl_ast_expr_get_op_arg(Expr, i + 1);
761     V = ExprBuilder.create(SubExpr);
762     ScalarEvolution *SE = Stmt->getParent()->getSE();
763     LTS[Stmt->getLoopForDimension(i)] = SE->getUnknown(V);
764   }
765 
766   isl_ast_expr_free(Expr);
767 }
768 
769 void IslNodeBuilder::createSubstitutionsVector(
770     __isl_take isl_ast_expr *Expr, ScopStmt *Stmt,
771     std::vector<LoopToScevMapT> &VLTS, std::vector<Value *> &IVS,
772     __isl_take isl_id *IteratorID) {
773   int i = 0;
774 
775   Value *OldValue = IDToValue[IteratorID];
776   for (Value *IV : IVS) {
777     IDToValue[IteratorID] = IV;
778     createSubstitutions(isl_ast_expr_copy(Expr), Stmt, VLTS[i]);
779     i++;
780   }
781 
782   IDToValue[IteratorID] = OldValue;
783   isl_id_free(IteratorID);
784   isl_ast_expr_free(Expr);
785 }
786 
787 void IslNodeBuilder::createUser(__isl_take isl_ast_node *User) {
788   LoopToScevMapT LTS;
789   isl_id *Id;
790   ScopStmt *Stmt;
791 
792   isl_ast_expr *Expr = isl_ast_node_user_get_expr(User);
793   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
794   Id = isl_ast_expr_get_id(StmtExpr);
795   isl_ast_expr_free(StmtExpr);
796 
797   LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
798 
799   Stmt = (ScopStmt *)isl_id_get_user(Id);
800   auto *NewAccesses = createNewAccesses(Stmt, User);
801   createSubstitutions(Expr, Stmt, LTS);
802 
803   if (Stmt->isBlockStmt())
804     BlockGen.copyStmt(*Stmt, LTS, NewAccesses);
805   else
806     RegionGen.copyStmt(*Stmt, LTS, NewAccesses);
807 
808   isl_id_to_ast_expr_free(NewAccesses);
809   isl_ast_node_free(User);
810   isl_id_free(Id);
811 }
812 
813 void IslNodeBuilder::createBlock(__isl_take isl_ast_node *Block) {
814   isl_ast_node_list *List = isl_ast_node_block_get_children(Block);
815 
816   for (int i = 0; i < isl_ast_node_list_n_ast_node(List); ++i)
817     create(isl_ast_node_list_get_ast_node(List, i));
818 
819   isl_ast_node_free(Block);
820   isl_ast_node_list_free(List);
821 }
822 
823 void IslNodeBuilder::create(__isl_take isl_ast_node *Node) {
824   switch (isl_ast_node_get_type(Node)) {
825   case isl_ast_node_error:
826     llvm_unreachable("code generation error");
827   case isl_ast_node_mark:
828     createMark(Node);
829     return;
830   case isl_ast_node_for:
831     createFor(Node);
832     return;
833   case isl_ast_node_if:
834     createIf(Node);
835     return;
836   case isl_ast_node_user:
837     createUser(Node);
838     return;
839   case isl_ast_node_block:
840     createBlock(Node);
841     return;
842   }
843 
844   llvm_unreachable("Unknown isl_ast_node type");
845 }
846 
847 bool IslNodeBuilder::materializeValue(isl_id *Id) {
848   // If the Id is already mapped, skip it.
849   if (!IDToValue.count(Id)) {
850     auto *ParamSCEV = (const SCEV *)isl_id_get_user(Id);
851     Value *V = nullptr;
852 
853     // Parameters could refere to invariant loads that need to be
854     // preloaded before we can generate code for the parameter. Thus,
855     // check if any value refered to in ParamSCEV is an invariant load
856     // and if so make sure its equivalence class is preloaded.
857     SetVector<Value *> Values;
858     findValues(ParamSCEV, SE, Values);
859     for (auto *Val : Values) {
860 
861       // Check if the value is an instruction in a dead block within the SCoP
862       // and if so do not code generate it.
863       if (auto *Inst = dyn_cast<Instruction>(Val)) {
864         if (S.contains(Inst)) {
865           bool IsDead = true;
866 
867           // Check for "undef" loads first, then if there is a statement for
868           // the parent of Inst and lastly if the parent of Inst has an empty
869           // domain. In the first and last case the instruction is dead but if
870           // there is a statement or the domain is not empty Inst is not dead.
871           auto MemInst = MemAccInst::dyn_cast(Inst);
872           auto Address = MemInst ? MemInst.getPointerOperand() : nullptr;
873           if (Address &&
874               SE.getUnknown(UndefValue::get(Address->getType())) ==
875                   SE.getPointerBase(SE.getSCEV(Address))) {
876           } else if (S.getStmtFor(Inst)) {
877             IsDead = false;
878           } else {
879             auto *Domain = S.getDomainConditions(Inst->getParent());
880             IsDead = isl_set_is_empty(Domain);
881             isl_set_free(Domain);
882           }
883 
884           if (IsDead) {
885             V = UndefValue::get(ParamSCEV->getType());
886             break;
887           }
888         }
889       }
890 
891       if (auto *IAClass = S.lookupInvariantEquivClass(Val)) {
892 
893         // Check if this invariant access class is empty, hence if we never
894         // actually added a loads instruction to it. In that case it has no
895         // (meaningful) users and we should not try to code generate it.
896         if (std::get<1>(*IAClass).empty())
897           V = UndefValue::get(ParamSCEV->getType());
898 
899         if (!preloadInvariantEquivClass(*IAClass)) {
900           isl_id_free(Id);
901           return false;
902         }
903       }
904     }
905 
906     V = V ? V : generateSCEV(ParamSCEV);
907     IDToValue[Id] = V;
908   }
909 
910   isl_id_free(Id);
911   return true;
912 }
913 
914 bool IslNodeBuilder::materializeParameters(isl_set *Set, bool All) {
915   for (unsigned i = 0, e = isl_set_dim(Set, isl_dim_param); i < e; ++i) {
916     if (!All && !isl_set_involves_dims(Set, isl_dim_param, i, 1))
917       continue;
918     isl_id *Id = isl_set_get_dim_id(Set, isl_dim_param, i);
919     if (!materializeValue(Id))
920       return false;
921   }
922   return true;
923 }
924 
925 /// @brief Add the number of dimensions in @p BS to @p U.
926 static isl_stat countTotalDims(isl_basic_set *BS, void *U) {
927   unsigned *NumTotalDim = static_cast<unsigned *>(U);
928   *NumTotalDim += isl_basic_set_total_dim(BS);
929   isl_basic_set_free(BS);
930   return isl_stat_ok;
931 }
932 
933 Value *IslNodeBuilder::preloadUnconditionally(isl_set *AccessRange,
934                                               isl_ast_build *Build,
935                                               Instruction *AccInst) {
936 
937   // TODO: This check could be performed in the ScopInfo already.
938   unsigned NumTotalDim = 0;
939   isl_set_foreach_basic_set(AccessRange, countTotalDims, &NumTotalDim);
940   if (NumTotalDim > MaxDimensionsInAccessRange) {
941     isl_set_free(AccessRange);
942     return nullptr;
943   }
944 
945   isl_pw_multi_aff *PWAccRel = isl_pw_multi_aff_from_set(AccessRange);
946   isl_ast_expr *Access =
947       isl_ast_build_access_from_pw_multi_aff(Build, PWAccRel);
948   auto *Address = isl_ast_expr_address_of(Access);
949   auto *AddressValue = ExprBuilder.create(Address);
950   Value *PreloadVal;
951 
952   // Correct the type as the SAI might have a different type than the user
953   // expects, especially if the base pointer is a struct.
954   Type *Ty = AccInst->getType();
955 
956   auto *Ptr = AddressValue;
957   auto Name = Ptr->getName();
958   Ptr = Builder.CreatePointerCast(Ptr, Ty->getPointerTo(), Name + ".cast");
959   PreloadVal = Builder.CreateLoad(Ptr, Name + ".load");
960   if (LoadInst *PreloadInst = dyn_cast<LoadInst>(PreloadVal))
961     PreloadInst->setAlignment(dyn_cast<LoadInst>(AccInst)->getAlignment());
962 
963   // TODO: This is only a hot fix for SCoP sequences that use the same load
964   //       instruction contained and hoisted by one of the SCoPs.
965   if (SE.isSCEVable(Ty))
966     SE.forgetValue(AccInst);
967 
968   return PreloadVal;
969 }
970 
971 Value *IslNodeBuilder::preloadInvariantLoad(const MemoryAccess &MA,
972                                             isl_set *Domain) {
973 
974   isl_set *AccessRange = isl_map_range(MA.getAddressFunction());
975   AccessRange = isl_set_gist_params(AccessRange, S.getContext());
976 
977   if (!materializeParameters(AccessRange, false)) {
978     isl_set_free(AccessRange);
979     isl_set_free(Domain);
980     return nullptr;
981   }
982 
983   auto *Build = isl_ast_build_from_context(isl_set_universe(S.getParamSpace()));
984   isl_set *Universe = isl_set_universe(isl_set_get_space(Domain));
985   bool AlwaysExecuted = isl_set_is_equal(Domain, Universe);
986   isl_set_free(Universe);
987 
988   Instruction *AccInst = MA.getAccessInstruction();
989   Type *AccInstTy = AccInst->getType();
990 
991   Value *PreloadVal = nullptr;
992   if (AlwaysExecuted) {
993     PreloadVal = preloadUnconditionally(AccessRange, Build, AccInst);
994     isl_ast_build_free(Build);
995     isl_set_free(Domain);
996     return PreloadVal;
997   }
998 
999   if (!materializeParameters(Domain, false)) {
1000     isl_ast_build_free(Build);
1001     isl_set_free(AccessRange);
1002     isl_set_free(Domain);
1003     return nullptr;
1004   }
1005 
1006   isl_ast_expr *DomainCond = isl_ast_build_expr_from_set(Build, Domain);
1007   Domain = nullptr;
1008 
1009   ExprBuilder.setTrackOverflow(true);
1010   Value *Cond = ExprBuilder.create(DomainCond);
1011   Value *OverflowHappened = Builder.CreateNot(ExprBuilder.getOverflowState(),
1012                                               "polly.preload.cond.overflown");
1013   Cond = Builder.CreateAnd(Cond, OverflowHappened, "polly.preload.cond.result");
1014   ExprBuilder.setTrackOverflow(false);
1015 
1016   if (!Cond->getType()->isIntegerTy(1))
1017     Cond = Builder.CreateIsNotNull(Cond);
1018 
1019   BasicBlock *CondBB = SplitBlock(Builder.GetInsertBlock(),
1020                                   &*Builder.GetInsertPoint(), &DT, &LI);
1021   CondBB->setName("polly.preload.cond");
1022 
1023   BasicBlock *MergeBB = SplitBlock(CondBB, &CondBB->front(), &DT, &LI);
1024   MergeBB->setName("polly.preload.merge");
1025 
1026   Function *F = Builder.GetInsertBlock()->getParent();
1027   LLVMContext &Context = F->getContext();
1028   BasicBlock *ExecBB = BasicBlock::Create(Context, "polly.preload.exec", F);
1029 
1030   DT.addNewBlock(ExecBB, CondBB);
1031   if (Loop *L = LI.getLoopFor(CondBB))
1032     L->addBasicBlockToLoop(ExecBB, LI);
1033 
1034   auto *CondBBTerminator = CondBB->getTerminator();
1035   Builder.SetInsertPoint(CondBBTerminator);
1036   Builder.CreateCondBr(Cond, ExecBB, MergeBB);
1037   CondBBTerminator->eraseFromParent();
1038 
1039   Builder.SetInsertPoint(ExecBB);
1040   Builder.CreateBr(MergeBB);
1041 
1042   Builder.SetInsertPoint(ExecBB->getTerminator());
1043   Value *PreAccInst = preloadUnconditionally(AccessRange, Build, AccInst);
1044   Builder.SetInsertPoint(MergeBB->getTerminator());
1045   auto *MergePHI = Builder.CreatePHI(
1046       AccInstTy, 2, "polly.preload." + AccInst->getName() + ".merge");
1047   PreloadVal = MergePHI;
1048 
1049   if (!PreAccInst) {
1050     PreloadVal = nullptr;
1051     PreAccInst = UndefValue::get(AccInstTy);
1052   }
1053 
1054   MergePHI->addIncoming(PreAccInst, ExecBB);
1055   MergePHI->addIncoming(Constant::getNullValue(AccInstTy), CondBB);
1056 
1057   isl_ast_build_free(Build);
1058   return PreloadVal;
1059 }
1060 
1061 bool IslNodeBuilder::preloadInvariantEquivClass(
1062     InvariantEquivClassTy &IAClass) {
1063   // For an equivalence class of invariant loads we pre-load the representing
1064   // element with the unified execution context. However, we have to map all
1065   // elements of the class to the one preloaded load as they are referenced
1066   // during the code generation and therefor need to be mapped.
1067   const MemoryAccessList &MAs = std::get<1>(IAClass);
1068   if (MAs.empty())
1069     return true;
1070 
1071   MemoryAccess *MA = MAs.front();
1072   assert(MA->isArrayKind() && MA->isRead());
1073 
1074   // If the access function was already mapped, the preload of this equivalence
1075   // class was triggered earlier already and doesn't need to be done again.
1076   if (ValueMap.count(MA->getAccessInstruction()))
1077     return true;
1078 
1079   // Check for recurrsion which can be caused by additional constraints, e.g.,
1080   // non-finitie loop contraints. In such a case we have to bail out and insert
1081   // a "false" runtime check that will cause the original code to be executed.
1082   auto PtrId = std::make_pair(std::get<0>(IAClass), std::get<3>(IAClass));
1083   if (!PreloadedPtrs.insert(PtrId).second)
1084     return false;
1085 
1086   // The exectution context of the IAClass.
1087   isl_set *&ExecutionCtx = std::get<2>(IAClass);
1088 
1089   // If the base pointer of this class is dependent on another one we have to
1090   // make sure it was preloaded already.
1091   auto *SAI = MA->getScopArrayInfo();
1092   if (auto *BaseIAClass = S.lookupInvariantEquivClass(SAI->getBasePtr())) {
1093     if (!preloadInvariantEquivClass(*BaseIAClass))
1094       return false;
1095 
1096     // After we preloaded the BaseIAClass we adjusted the BaseExecutionCtx and
1097     // we need to refine the ExecutionCtx.
1098     isl_set *BaseExecutionCtx = isl_set_copy(std::get<2>(*BaseIAClass));
1099     ExecutionCtx = isl_set_intersect(ExecutionCtx, BaseExecutionCtx);
1100   }
1101 
1102   Instruction *AccInst = MA->getAccessInstruction();
1103   Type *AccInstTy = AccInst->getType();
1104 
1105   Value *PreloadVal = preloadInvariantLoad(*MA, isl_set_copy(ExecutionCtx));
1106   if (!PreloadVal)
1107     return false;
1108 
1109   for (const MemoryAccess *MA : MAs) {
1110     Instruction *MAAccInst = MA->getAccessInstruction();
1111     assert(PreloadVal->getType() == MAAccInst->getType());
1112     ValueMap[MAAccInst] = PreloadVal;
1113   }
1114 
1115   if (SE.isSCEVable(AccInstTy)) {
1116     isl_id *ParamId = S.getIdForParam(SE.getSCEV(AccInst));
1117     if (ParamId)
1118       IDToValue[ParamId] = PreloadVal;
1119     isl_id_free(ParamId);
1120   }
1121 
1122   BasicBlock *EntryBB = &Builder.GetInsertBlock()->getParent()->getEntryBlock();
1123   auto *Alloca = new AllocaInst(AccInstTy, AccInst->getName() + ".preload.s2a");
1124   Alloca->insertBefore(&*EntryBB->getFirstInsertionPt());
1125   Builder.CreateStore(PreloadVal, Alloca);
1126 
1127   for (auto *DerivedSAI : SAI->getDerivedSAIs()) {
1128     Value *BasePtr = DerivedSAI->getBasePtr();
1129 
1130     for (const MemoryAccess *MA : MAs) {
1131       // As the derived SAI information is quite coarse, any load from the
1132       // current SAI could be the base pointer of the derived SAI, however we
1133       // should only change the base pointer of the derived SAI if we actually
1134       // preloaded it.
1135       if (BasePtr == MA->getBaseAddr()) {
1136         assert(BasePtr->getType() == PreloadVal->getType());
1137         DerivedSAI->setBasePtr(PreloadVal);
1138       }
1139 
1140       // For scalar derived SAIs we remap the alloca used for the derived value.
1141       if (BasePtr == MA->getAccessInstruction()) {
1142         if (DerivedSAI->isPHIKind())
1143           PHIOpMap[BasePtr] = Alloca;
1144         else
1145           ScalarMap[BasePtr] = Alloca;
1146       }
1147     }
1148   }
1149 
1150   for (const MemoryAccess *MA : MAs) {
1151 
1152     Instruction *MAAccInst = MA->getAccessInstruction();
1153     // Use the escape system to get the correct value to users outside the SCoP.
1154     BlockGenerator::EscapeUserVectorTy EscapeUsers;
1155     for (auto *U : MAAccInst->users())
1156       if (Instruction *UI = dyn_cast<Instruction>(U))
1157         if (!S.contains(UI))
1158           EscapeUsers.push_back(UI);
1159 
1160     if (EscapeUsers.empty())
1161       continue;
1162 
1163     EscapeMap[MA->getAccessInstruction()] =
1164         std::make_pair(Alloca, std::move(EscapeUsers));
1165   }
1166 
1167   return true;
1168 }
1169 
1170 bool IslNodeBuilder::preloadInvariantLoads() {
1171 
1172   auto &InvariantEquivClasses = S.getInvariantAccesses();
1173   if (InvariantEquivClasses.empty())
1174     return true;
1175 
1176   BasicBlock *PreLoadBB = SplitBlock(Builder.GetInsertBlock(),
1177                                      &*Builder.GetInsertPoint(), &DT, &LI);
1178   PreLoadBB->setName("polly.preload.begin");
1179   Builder.SetInsertPoint(&PreLoadBB->front());
1180 
1181   for (auto &IAClass : InvariantEquivClasses)
1182     if (!preloadInvariantEquivClass(IAClass))
1183       return false;
1184 
1185   return true;
1186 }
1187 
1188 void IslNodeBuilder::addParameters(__isl_take isl_set *Context) {
1189 
1190   // Materialize values for the parameters of the SCoP.
1191   materializeParameters(Context, /* all */ true);
1192 
1193   // Generate values for the current loop iteration for all surrounding loops.
1194   //
1195   // We may also reference loops outside of the scop which do not contain the
1196   // scop itself, but as the number of such scops may be arbitrarily large we do
1197   // not generate code for them here, but only at the point of code generation
1198   // where these values are needed.
1199   Loop *L = LI.getLoopFor(S.getEntry());
1200 
1201   while (L != nullptr && S.contains(L))
1202     L = L->getParentLoop();
1203 
1204   while (L != nullptr) {
1205     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
1206                                             SE.getUnknown(Builder.getInt64(1)),
1207                                             L, SCEV::FlagAnyWrap);
1208     Value *V = generateSCEV(OuterLIV);
1209     OutsideLoopIterations[L] = SE.getUnknown(V);
1210     L = L->getParentLoop();
1211   }
1212 
1213   isl_set_free(Context);
1214 }
1215 
1216 Value *IslNodeBuilder::generateSCEV(const SCEV *Expr) {
1217   Instruction *InsertLocation = &*--(Builder.GetInsertBlock()->end());
1218   return expandCodeFor(S, SE, DL, "polly", Expr, Expr->getType(),
1219                        InsertLocation, &ValueMap);
1220 }
1221