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