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