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