Polly 24.0.0git
IslNodeBuilder.cpp
Go to the documentation of this file.
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
22#include "polly/Options.h"
23#include "polly/ScopInfo.h"
28#include "llvm/ADT/APInt.h"
29#include "llvm/ADT/PostOrderIterator.h"
30#include "llvm/ADT/SetVector.h"
31#include "llvm/ADT/Statistic.h"
32#include "llvm/Analysis/AssumptionCache.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/Analysis/TargetLibraryInfo.h"
38#include "llvm/IR/BasicBlock.h"
39#include "llvm/IR/Constant.h"
40#include "llvm/IR/Constants.h"
41#include "llvm/IR/DataLayout.h"
42#include "llvm/IR/DerivedTypes.h"
43#include "llvm/IR/Dominators.h"
44#include "llvm/IR/Function.h"
45#include "llvm/IR/InstrTypes.h"
46#include "llvm/IR/Instruction.h"
47#include "llvm/IR/Instructions.h"
48#include "llvm/IR/Module.h"
49#include "llvm/IR/Type.h"
50#include "llvm/IR/Value.h"
51#include "llvm/Support/Casting.h"
52#include "llvm/Support/CommandLine.h"
53#include "llvm/Support/ErrorHandling.h"
54#include "llvm/TargetParser/Triple.h"
55#include "llvm/Transforms/Utils/BasicBlockUtils.h"
56#include "isl/aff.h"
57#include "isl/aff_type.h"
58#include "isl/ast.h"
59#include "isl/ast_build.h"
61#include "isl/map.h"
62#include "isl/set.h"
63#include "isl/union_map.h"
64#include "isl/union_set.h"
65#include "isl/val.h"
66#include <algorithm>
67#include <cassert>
68#include <cstdint>
69#include <cstring>
70#include <string>
71#include <utility>
72#include <vector>
73
74using namespace llvm;
75using namespace polly;
76
77#define DEBUG_TYPE "polly-codegen"
78
79STATISTIC(VersionedScops, "Number of SCoPs that required versioning.");
80
81STATISTIC(SequentialLoops, "Number of generated sequential for-loops");
82STATISTIC(ParallelLoops, "Number of generated parallel for-loops");
83STATISTIC(IfConditions, "Number of generated if-conditions");
84
85/// OpenMP backend options
86enum class OpenMPBackend { GNU, LLVM };
87
88static cl::opt<bool> PollyGenerateRTCPrint(
89 "polly-codegen-emit-rtc-print",
90 cl::desc("Emit code that prints the runtime check result dynamically."),
91 cl::Hidden, cl::cat(PollyCategory));
92
93// If this option is set we always use the isl AST generator to regenerate
94// memory accesses. Without this option set we regenerate expressions using the
95// original SCEV expressions and only generate new expressions in case the
96// access relation has been changed and consequently must be regenerated.
97static cl::opt<bool> PollyGenerateExpressions(
98 "polly-codegen-generate-expressions",
99 cl::desc("Generate AST expressions for unmodified and modified accesses"),
100 cl::Hidden, cl::cat(PollyCategory));
101
103 "polly-target-first-level-cache-line-size",
104 cl::desc("The size of the first level cache line size specified in bytes."),
105 cl::Hidden, cl::init(64), cl::cat(PollyCategory));
106
107static cl::opt<OpenMPBackend> PollyOmpBackend(
108 "polly-omp-backend", cl::desc("Choose the OpenMP library to use:"),
109 cl::values(clEnumValN(OpenMPBackend::GNU, "GNU", "GNU OpenMP"),
110 clEnumValN(OpenMPBackend::LLVM, "LLVM", "LLVM OpenMP")),
111 cl::Hidden, cl::init(OpenMPBackend::GNU), cl::cat(PollyCategory));
112
114 ICmpInst::Predicate &Predicate) {
115 isl::ast_expr Cond = For.cond();
116 isl::ast_expr Iterator = For.iterator();
118 "conditional expression is not an atomic upper bound");
119
121
122 switch (OpType) {
123 case isl_ast_op_le:
124 Predicate = ICmpInst::ICMP_SLE;
125 break;
126 case isl_ast_op_lt:
127 Predicate = ICmpInst::ICMP_SLT;
128 break;
129 default:
130 llvm_unreachable("Unexpected comparison type in loop condition");
131 }
132
133 isl::ast_expr Arg0 = Cond.get_op_arg(0);
134
136 "conditional expression is not an atomic upper bound");
137
138 isl::id UBID = Arg0.get_id();
139
141 "Could not get the iterator");
142
143 isl::id IteratorID = Iterator.get_id();
144
145 assert(UBID.get() == IteratorID.get() &&
146 "conditional expression is not an atomic upper bound");
147
148 return Cond.get_op_arg(1);
149}
150
153 isl::ast_node Body = For.body();
154
155 // First, check if we can actually handle this code.
156 switch (isl_ast_node_get_type(Body.get())) {
158 break;
159 case isl_ast_node_block: {
160 isl::ast_node_block BodyBlock = Body.as<isl::ast_node_block>();
161 isl::ast_node_list List = BodyBlock.children();
162 for (isl::ast_node Node : List) {
163 isl_ast_node_type NodeType = isl_ast_node_get_type(Node.get());
164 if (NodeType != isl_ast_node_user)
165 return -1;
166 }
167 break;
168 }
169 default:
170 return -1;
171 }
172
173 isl::ast_expr Init = For.init();
174 if (!Init.isa<isl::ast_expr_int>() || !Init.val().is_zero())
175 return -1;
176 isl::ast_expr Inc = For.inc();
177 if (!Inc.isa<isl::ast_expr_int>() || !Inc.val().is_one())
178 return -1;
179 CmpInst::Predicate Predicate;
180 isl::ast_expr UB = getUpperBound(For, Predicate);
181 if (!UB.isa<isl::ast_expr_int>())
182 return -1;
183 isl::val UpVal = UB.get_val();
184 int NumberIterations = UpVal.get_num_si();
185 if (NumberIterations < 0)
186 return -1;
187 if (Predicate == CmpInst::ICMP_SLT)
188 return NumberIterations;
189 else
190 return NumberIterations + 1;
191}
192
193static void findReferencesByUse(Value *SrcVal, ScopStmt *UserStmt,
194 Loop *UserScope, const ValueMapT &GlobalMap,
195 SetVector<Value *> &Values,
196 SetVector<const SCEV *> &SCEVs) {
197 VirtualUse VUse = VirtualUse::create(UserStmt, UserScope, SrcVal, true);
198 switch (VUse.getKind()) {
200 // When accelerator-offloading, GlobalValue is a host address whose content
201 // must still be transferred to the GPU.
202 if (isa<GlobalValue>(SrcVal))
203 Values.insert(SrcVal);
204 break;
205
207 SCEVs.insert(VUse.getScevExpr());
208 return;
209
215 break;
216 }
217
218 if (Value *NewVal = GlobalMap.lookup(SrcVal))
219 Values.insert(NewVal);
220}
221
222static void findReferencesInInst(Instruction *Inst, ScopStmt *UserStmt,
223 Loop *UserScope, const ValueMapT &GlobalMap,
224 SetVector<Value *> &Values,
225 SetVector<const SCEV *> &SCEVs) {
226 for (Use &U : Inst->operands())
227 findReferencesByUse(U.get(), UserStmt, UserScope, GlobalMap, Values, SCEVs);
228}
229
230static void findReferencesInStmt(ScopStmt *Stmt, SetVector<Value *> &Values,
231 ValueMapT &GlobalMap,
232 SetVector<const SCEV *> &SCEVs) {
233 LoopInfo *LI = Stmt->getParent()->getLI();
234
235 BasicBlock *BB = Stmt->getBasicBlock();
236 // TODO: Should BB ever be null?
237 Loop *Scope = BB ? LI->getLoopFor(BB) : nullptr;
238 for (Instruction *Inst : Stmt->getInstructions())
239 findReferencesInInst(Inst, Stmt, Scope, GlobalMap, Values, SCEVs);
240
241 if (Stmt->isRegionStmt()) {
242 for (BasicBlock *BB : Stmt->getRegion()->blocks()) {
243 Loop *Scope = LI->getLoopFor(BB);
244 for (Instruction &Inst : *BB)
245 findReferencesInInst(&Inst, Stmt, Scope, GlobalMap, Values, SCEVs);
246 }
247 }
248}
249
250void polly::addReferencesFromStmt(ScopStmt *Stmt, void *UserPtr,
251 bool CreateScalarRefs) {
252 auto &References = *static_cast<SubtreeReferences *>(UserPtr);
253
254 findReferencesInStmt(Stmt, References.Values, References.GlobalMap,
255 References.SCEVs);
256
257 for (auto &Access : *Stmt) {
258 if (References.ParamSpace) {
259 isl::space ParamSpace = Access->getLatestAccessRelation().get_space();
260 (*References.ParamSpace) =
261 References.ParamSpace->align_params(ParamSpace);
262 }
263
264 if (Access->isLatestArrayKind()) {
265 auto *BasePtr = Access->getLatestScopArrayInfo()->getBasePtr();
266 if (Instruction *OpInst = dyn_cast<Instruction>(BasePtr))
267 if (Stmt->getParent()->contains(OpInst))
268 continue;
269
270 References.Values.insert(BasePtr);
271 continue;
272 }
273
274 if (CreateScalarRefs)
275 References.Values.insert(References.BlockGen.getOrCreateAlloca(*Access));
276 }
277}
278
279/// Extract the out-of-scop values and SCEVs referenced from a set describing
280/// a ScopStmt.
281///
282/// This includes the SCEVUnknowns referenced by the SCEVs used in the
283/// statement and the base pointers of the memory accesses. For scalar
284/// statements we force the generation of alloca memory locations and list
285/// these locations in the set of out-of-scop values as well.
286///
287/// @param Set A set which references the ScopStmt we are interested in.
288/// @param UserPtr A void pointer that can be casted to a SubtreeReferences
289/// structure.
291 isl::id Id = Set.get_tuple_id();
292 auto *Stmt = static_cast<ScopStmt *>(Id.get_user());
293 addReferencesFromStmt(Stmt, UserPtr);
294}
295
296/// Extract the out-of-scop values and SCEVs referenced from a union set
297/// referencing multiple ScopStmts.
298///
299/// This includes the SCEVUnknowns referenced by the SCEVs used in the
300/// statement and the base pointers of the memory accesses. For scalar
301/// statements we force the generation of alloca memory locations and list
302/// these locations in the set of out-of-scop values as well.
303///
304/// @param USet A union set referencing the ScopStmts we are interested
305/// in.
306/// @param References The SubtreeReferences data structure through which
307/// results are returned and further information is
308/// provided.
310 SubtreeReferences &References) {
311
312 for (isl::set Set : USet.get_set_list())
313 addReferencesFromStmtSet(Set, &References);
314}
315
316isl::union_map
320
322 SetVector<Value *> &Values,
323 SetVector<const Loop *> &Loops) {
324 SetVector<const SCEV *> SCEVs;
325 SubtreeReferences References = {
326 LI, SE, S, ValueMap, Values, SCEVs, getBlockGenerator(), nullptr};
327
328 Values.insert_range(llvm::make_second_range(IDToValue));
329
330 // NOTE: this is populated in IslNodeBuilder::addParameters
331 for (const auto &I : OutsideLoopIterations)
332 Values.insert(cast<SCEVUnknown>(I.second)->getValue());
333
335 addReferencesFromStmtUnionSet(Schedule, References);
336
337 for (const SCEV *Expr : SCEVs) {
338 findValues(Expr, SE, Values);
339 findLoops(Expr, Loops);
340 }
341
342 Values.remove_if([](const Value *V) { return isa<GlobalValue>(V); });
343
344 /// Note: Code generation of induction variables of loops outside Scops
345 ///
346 /// Remove loops that contain the scop or that are part of the scop, as they
347 /// are considered local. This leaves only loops that are before the scop, but
348 /// do not contain the scop itself.
349 /// We ignore loops perfectly contained in the Scop because these are already
350 /// generated at `IslNodeBuilder::addParameters`. These `Loops` are loops
351 /// whose induction variables are referred to by the Scop, but the Scop is not
352 /// fully contained in these Loops. Since there can be many of these,
353 /// we choose to codegen these on-demand.
354 /// @see IslNodeBuilder::materializeNonScopLoopInductionVariable.
355 Loops.remove_if([this](const Loop *L) {
356 return S.contains(L) || L->contains(S.getEntry());
357 });
358
359 // Contains Values that may need to be replaced with other values
360 // due to replacements from the ValueMap. We should make sure
361 // that we return correctly remapped values.
362 // NOTE: this code path is tested by:
363 // 1. test/Isl/CodeGen/OpenMP/single_loop_with_loop_invariant_baseptr.ll
364 // 2. test/Isl/CodeGen/OpenMP/loop-body-references-outer-values-3.ll
365 SetVector<Value *> ReplacedValues;
366 for (Value *V : Values) {
367 ReplacedValues.insert(getLatestValue(V));
368 }
369 Values = ReplacedValues;
370}
371
373 auto It = ValueMap.find(Original);
374 if (It == ValueMap.end())
375 return Original;
376 return It->second;
377}
378
380 auto *Id = isl_ast_node_mark_get_id(Node);
381 auto Child = isl_ast_node_mark_get_node(Node);
382 isl_ast_node_free(Node);
383 // If a child node of a 'SIMD mark' is a loop that has a single iteration,
384 // it will be optimized away and we should skip it.
385 if (strcmp(isl_id_get_name(Id), "SIMD") == 0 &&
387 createForSequential(isl::manage(Child).as<isl::ast_node_for>(), true);
388 isl_id_free(Id);
389 return;
390 }
391
392 BandAttr *ChildLoopAttr = getLoopAttr(isl::manage_copy(Id));
393 BandAttr *AncestorLoopAttr;
394 if (ChildLoopAttr) {
395 // Save current LoopAttr environment to restore again when leaving this
396 // subtree. This means there was no loop between the ancestor LoopAttr and
397 // this mark, i.e. the ancestor LoopAttr did not directly mark a loop. This
398 // can happen e.g. if the AST build peeled or unrolled the loop.
399 AncestorLoopAttr = Annotator.getStagingAttrEnv();
400
401 Annotator.getStagingAttrEnv() = ChildLoopAttr;
402 }
403
404 create(Child);
405
406 if (ChildLoopAttr) {
407 assert(Annotator.getStagingAttrEnv() == ChildLoopAttr &&
408 "Nest must not overwrite loop attr environment");
409 Annotator.getStagingAttrEnv() = AncestorLoopAttr;
410 }
411
412 isl_id_free(Id);
413}
414
415/// Restore the initial ordering of dimensions of the band node
416///
417/// In case the band node represents all the dimensions of the iteration
418/// domain, recreate the band node to restore the initial ordering of the
419/// dimensions.
420///
421/// @param Node The band node to be modified.
422/// @return The modified schedule node.
425 isl::ast_node Body = Node.body();
427 return false;
428
429 isl::ast_node_mark BodyMark = Body.as<isl::ast_node_mark>();
430 auto Id = BodyMark.id();
431 if (strcmp(Id.get_name().c_str(), "Loop Vectorizer Disabled") == 0)
432 return true;
433 return false;
434}
435
436/// Returns true if the loop has a dist=1 dependence involving FP operations
437/// (array-carried RAW/WAW or scalar FP reduction). In that case we omit the
438/// vectorize.enable annotation and let the Loop Vectorizer decide.
441 if (PwaDist.is_null())
442 return false;
443
444 isl::set Dist = isl::manage(isl_pw_aff_domain(PwaDist.copy()));
445 isl::pw_aff PwaOne = isl::pw_aff(Dist, isl::val::one(S.getIslCtx()));
446 if (isl_pw_aff_is_equal(PwaDist.get(), PwaOne.get()) != isl_bool_true)
447 return false;
448
449 // dist=1: suppress forced vectorization if the body has FP operations.
450 for (isl::set StmtSet :
451 IslAstInfo::getSchedule(For).domain().get_set_list()) {
452 auto *Stmt = static_cast<ScopStmt *>(StmtSet.get_tuple_id().get_user());
453 for (Instruction *Inst : Stmt->getInstructions()) {
454 if (Inst->getType()->isFloatingPointTy() ||
455 (Inst->getNumOperands() > 0 &&
456 Inst->getOperand(0)->getType()->isFloatingPointTy()))
457 return true;
458 }
459 }
460
461 return false;
462}
463
464/// Sign-extend or truncate V to Ty.
465///
466/// Returns V unchanged if it already has type Ty, sign-extends it if
467/// Ty is wider, or truncates it if Ty is narrower.
468static Value *castToType(IRBuilderBase &Builder, Value *V, Type *Ty) {
469 if (V->getType() == Ty)
470 return V;
471 return Builder.CreateSExtOrTrunc(V, Ty);
472}
473
474/// Returns true when V is known to fit in IntPtrTy without data loss.
475/// Accepts i64 constants such as 0 and 1 that ISL materialises as i64 even on
476/// 32-bit targets.
477static bool fitsInTy(Value *V, IntegerType *IntTy) {
478 if (V->getType()->getIntegerBitWidth() <= IntTy->getBitWidth())
479 return true;
480 if (auto *CI = dyn_cast<ConstantInt>(V))
481 return CI->getValue().isSignedIntN(IntTy->getBitWidth());
482 return false;
483}
484
486 bool MarkParallel) {
487 Value *ValueLB, *ValueUB, *ValueInc;
488 Type *MaxType;
489 BasicBlock *ExitBlock;
490 Value *IV;
491 CmpInst::Predicate Predicate;
492
493 bool LoopVectorizerDisabled = IsLoopVectorizerDisabled(For);
494
495 isl::ast_node Body = For.body();
496
497 // isl_ast_node_for_is_degenerate(For)
498 //
499 // TODO: For degenerated loops we could generate a plain assignment.
500 // However, for now we just reuse the logic for normal loops, which will
501 // create a loop with a single iteration.
502
503 isl::ast_expr Init = For.init();
504 isl::ast_expr Inc = For.inc();
505 isl::ast_expr Iterator = For.iterator();
506 isl::id IteratorID = Iterator.get_id();
507 isl::ast_expr UB = getUpperBound(For, Predicate);
508
509 ValueLB = ExprBuilder.create(Init.release());
510 ValueUB = ExprBuilder.create(UB.release());
511 ValueInc = ExprBuilder.create(Inc.release());
512
513 MaxType = ExprBuilder.getType(Iterator.get());
514 MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType());
515 MaxType = ExprBuilder.getWidestType(MaxType, ValueUB->getType());
516 MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType());
517
518 // Narrow the IV type to pointer size when all three bounds are known to fit.
519 // On 32-bit targets (e.g. Hexagon) this avoids i64 IVs and the truncations
520 // they cause in loop bodies. This also allows Hexagon to represent loops as
521 // Hardware loops. ISL materializes constants (e.g. LB=0, Inc=1)
522 // as i64 even when they fit in i32, so we accept those via isSignedIntN.
523 // Non-constant variables with a type wider than PtrBits are left unchanged
524 // to avoid an unsafe truncation.
525 IntegerType *IntPtrTy = Builder.getIntPtrTy(DL);
526 if (MaxType->getIntegerBitWidth() > IntPtrTy->getBitWidth() &&
527 fitsInTy(ValueLB, IntPtrTy) && fitsInTy(ValueUB, IntPtrTy) &&
528 fitsInTy(ValueInc, IntPtrTy))
529 MaxType = IntPtrTy;
530
531 // Coerce each bound to MaxType, using trunc when MaxType was narrowed.
532 ValueLB = castToType(Builder, ValueLB, MaxType);
533 ValueUB = castToType(Builder, ValueUB, MaxType);
534 ValueInc = castToType(Builder, ValueInc, MaxType);
535
536 // If we can show that LB <Predicate> UB holds at least once, we can
537 // omit the GuardBB in front of the loop.
538 bool UseGuardBB = !GenSE->isKnownPredicate(Predicate, GenSE->getSCEV(ValueLB),
539 GenSE->getSCEV(ValueUB));
540
541 // FIXME: This is a workaround for
542 // https://github.com/llvm/llvm-project/issues/198726.
543 // llvm.loop.vectorize.enable=true has an additional property beyond
544 // requesting vectorization — it implicitly allows FP operation reordering.
545 // This is a limitation of the metadata format: there is no way to separate
546 // the request for vectorization from the request for reassociating FP ops.
547 // Once LoopVectorize is fixed to not reorder FP ops without explicit
548 // permission, this workaround can be removed.
549 // For now, skip vectorize.enable for dist=1 FP loops to avoid correctness
550 // failures from FP reassociation.
551 bool SkipVectorizeEnableMetadata = hasLoopCarriedDependence(For, S);
552
553 IV = createLoop(ValueLB, ValueUB, ValueInc, Builder, *GenLI, *GenDT,
554 ExitBlock, Predicate, &Annotator, MarkParallel, UseGuardBB,
555 LoopVectorizerDisabled, SkipVectorizeEnableMetadata);
556 IDToValue[IteratorID.get()] = IV;
557
558 create(Body.release());
559
560 Annotator.popLoop(MarkParallel);
561
562 IDToValue.erase(IDToValue.find(IteratorID.get()));
563
564 Builder.SetInsertPoint(ExitBlock->begin());
565
566 SequentialLoops++;
567}
568
570 isl_ast_node *Body;
571 isl_ast_expr *Init, *Inc, *Iterator, *UB;
572 isl_id *IteratorID;
573 Value *ValueLB, *ValueUB, *ValueInc;
574 Type *MaxType;
575 Value *IV;
576 CmpInst::Predicate Predicate;
577
578 // The preamble of parallel code interacts different than normal code with
579 // e.g., scalar initialization. Therefore, we ensure the parallel code is
580 // separated from the last basic block.
581 BasicBlock *ParBB =
582 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), &DT, &LI);
583 ParBB->setName("polly.parallel.for");
584 Builder.SetInsertPoint(ParBB->begin());
585
586 Body = isl_ast_node_for_get_body(For);
587 Init = isl_ast_node_for_get_init(For);
588 Inc = isl_ast_node_for_get_inc(For);
589 Iterator = isl_ast_node_for_get_iterator(For);
590 IteratorID = isl_ast_expr_get_id(Iterator);
591 UB = getUpperBound(isl::manage_copy(For).as<isl::ast_node_for>(), Predicate)
592 .release();
593
594 ValueLB = ExprBuilder.create(Init);
595 ValueUB = ExprBuilder.create(UB);
596 ValueInc = ExprBuilder.create(Inc);
597
598 // OpenMP always uses SLE. In case the isl generated AST uses a SLT
599 // expression, we need to adjust the loop bound by one.
600 if (Predicate == CmpInst::ICMP_SLT)
601 ValueUB = Builder.CreateAdd(
602 ValueUB, Builder.CreateSExt(Builder.getTrue(), ValueUB->getType()));
603
604 MaxType = ExprBuilder.getType(Iterator);
605 MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType());
606 MaxType = ExprBuilder.getWidestType(MaxType, ValueUB->getType());
607 MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType());
608
609 // Narrow the IV type to pointer size when all three bounds are known to fit.
610 // On 32-bit targets (e.g. Hexagon) this avoids i64 IVs and the truncations
611 // they cause in loop bodies. ISL materializes constants (e.g. LB=0, Inc=1)
612 // as i64 even when they fit in i32, so we accept those via isSignedIntN.
613 // Non-constant variables with a type wider than PtrBits are left unchanged
614 // to avoid an unsafe truncation.
615 IntegerType *IntPtrTy = Builder.getIntPtrTy(DL);
616 if (MaxType->getIntegerBitWidth() > IntPtrTy->getBitWidth() &&
617 fitsInTy(ValueLB, IntPtrTy) && fitsInTy(ValueUB, IntPtrTy) &&
618 fitsInTy(ValueInc, IntPtrTy))
619 MaxType = IntPtrTy;
620
621 // Coerce each bound to MaxType, using trunc when MaxType was narrowed.
622 ValueLB = castToType(Builder, ValueLB, MaxType);
623 ValueUB = castToType(Builder, ValueUB, MaxType);
624 ValueInc = castToType(Builder, ValueInc, MaxType);
625
626 BasicBlock::iterator LoopBody;
627
628 SetVector<Value *> SubtreeValues;
629 SetVector<const Loop *> Loops;
630
631 getReferencesInSubtree(isl::manage_copy(For), SubtreeValues, Loops);
632
633 // Create for all loops we depend on values that contain the current loop
634 // iteration. These values are necessary to generate code for SCEVs that
635 // depend on such loops. As a result we need to pass them to the subfunction.
636 // See [Code generation of induction variables of loops outside Scops]
637 for (const Loop *L : Loops) {
638 Value *LoopInductionVar = materializeNonScopLoopInductionVariable(L);
639 SubtreeValues.insert(LoopInductionVar);
640 }
641
642 ValueMapT NewValues;
643
644 std::unique_ptr<ParallelLoopGenerator> ParallelLoopGenPtr;
645
646 switch (PollyOmpBackend) {
648 ParallelLoopGenPtr.reset(new ParallelLoopGeneratorGOMP(Builder, DL));
649 break;
651 ParallelLoopGenPtr.reset(new ParallelLoopGeneratorKMP(Builder, DL));
652 break;
653 }
654
655 IV = ParallelLoopGenPtr->createParallelLoop(
656 ValueLB, ValueUB, ValueInc, SubtreeValues, NewValues, &LoopBody);
657 BasicBlock::iterator AfterLoop = Builder.GetInsertPoint();
658
659 // Remember the parallel subfunction
660 Function *SubFn = LoopBody->getFunction();
661 ParallelSubfunctions.push_back(SubFn);
662
663 // We start working on the outlined function. Since DominatorTree/LoopInfo are
664 // not an inter-procedural passes, we temporarily switch them out. Save the
665 // old ones first.
666 Function *CallerFn = Builder.GetInsertBlock()->getParent();
667 DominatorTree *CallerDT = GenDT;
668 LoopInfo *CallerLI = GenLI;
669 ScalarEvolution *CallerSE = GenSE;
670 ValueMapT CallerGlobals = ValueMap;
672 MapVector<const Loop *, const SCEV *> OutsideLoopIterationsCopy =
674
675 // Get the analyses for the subfunction. ParallelLoopGenerator already create
676 // DominatorTree and LoopInfo for us.
677 DominatorTree *SubDT = ParallelLoopGenPtr->getCalleeDominatorTree();
678 LoopInfo *SubLI = ParallelLoopGenPtr->getCalleeLoopInfo();
679
680 // Create TargetLibraryInfo, AssumptionCachem and ScalarEvolution ourselves.
681 // TODO: Ideally, we would use the pass manager's TargetLibraryInfoPass and
682 // AssumptionAnalysis instead of our own. They contain more target-specific
683 // information than we have available here: TargetLibraryInfoImpl can be a
684 // derived class determined by TargetMachine, AssumptionCache can be
685 // configured using a TargetTransformInfo object also derived from
686 // TargetMachine.
687 TargetLibraryInfoImpl BaselineInfoImpl(SubFn->getParent()->getTargetTriple());
688 TargetLibraryInfo CalleeTLI(BaselineInfoImpl, SubFn);
689 AssumptionCache CalleeAC(*SubFn);
690 std::unique_ptr<ScalarEvolution> SubSE = std::make_unique<ScalarEvolution>(
691 *SubFn, CalleeTLI, CalleeAC, *SubDT, *SubLI);
692
693 // Switch to the subfunction
694 GenDT = SubDT;
695 GenLI = SubLI;
696 GenSE = SubSE.get();
697 BlockGen.switchGeneratedFunc(SubFn, GenDT, GenLI, GenSE);
698 RegionGen.switchGeneratedFunc(SubFn, GenDT, GenLI, GenSE);
699 ExprBuilder.switchGeneratedFunc(SubFn, GenDT, GenLI, GenSE);
700 Builder.SetInsertPoint(LoopBody);
701
702 // Update the ValueMap to use instructions in the subfunction. Note that
703 // "GlobalMap" used in BlockGenerator/IslExprBuilder is a reference to this
704 // ValueMap.
705 ValueMap.remove_if([&](auto &P) {
706 P.second = NewValues.lookup(P.second);
707 // Clean up any value that getReferencesInSubtree thinks we do not need.
708 return !P.second;
709 });
710
711 // This is for NewVals that do not appear in ValueMap (such as SCoP-invariant
712 // values whose original value can be reused as long as we are in the same
713 // function). No need to map the others.
714 for (auto &[NewVal, NewNewVal] : NewValues) {
715 if (Instruction *NewValInst = dyn_cast<Instruction>((Value *)NewVal)) {
716 if (S.contains(NewValInst))
717 continue;
718 assert(NewValInst->getFunction() == &S.getFunction());
719 }
720 assert(!ValueMap.contains(NewVal));
721 ValueMap[NewVal] = NewNewVal;
722 }
723
724 // Also update the IDToValue map to use instructions from the subfunction.
725 for (auto &[OldVal, NewVal] : IDToValue) {
726 NewVal = NewValues.lookup(NewVal);
727 assert(NewVal);
728 }
729 IDToValue[IteratorID] = IV;
730
731 // Also update OutsideLoopIterations to use values from the subfunction.
732 // SCEVExpander may fold identity operations (e.g. x+0 -> x), returning the
733 // original loop PHI instead of a new instruction. We need to remap these
734 // values through NewValues so GenSE (now SubSE) doesn't operate on values
735 // from the caller function.
736 for (auto &[L, S] : OutsideLoopIterations) {
737 if (auto *U = dyn_cast<SCEVUnknown>(S)) {
738 Value *NewVal = NewValues.lookup(U->getValue());
739 assert(NewVal && "must have a new value");
740 OutsideLoopIterations[L] = GenSE->getUnknown(NewVal);
741 }
742 }
743
744#ifndef NDEBUG
745 // Check whether the maps now exclusively refer to SubFn values.
746 for (auto &[OldVal, SubVal] : ValueMap) {
747 Instruction *SubInst = dyn_cast<Instruction>((Value *)SubVal);
748 assert(SubInst->getFunction() == SubFn &&
749 "Instructions from outside the subfn cannot be accessed within the "
750 "subfn");
751 }
752 for (auto &[Id, SubVal] : IDToValue) {
753 Instruction *SubInst = dyn_cast<Instruction>((Value *)SubVal);
754 assert(SubInst->getFunction() == SubFn &&
755 "Instructions from outside the subfn cannot be accessed within the "
756 "subfn");
757 }
758#endif
759
760 ValueMapT NewValuesReverse;
761 for (auto P : NewValues)
762 NewValuesReverse[P.second] = P.first;
763
764 Annotator.addAlternativeAliasBases(NewValuesReverse);
765
766 create(Body);
767
768 Annotator.resetAlternativeAliasBases();
769
770 // Resume working on the caller function.
771 GenDT = CallerDT;
772 GenLI = CallerLI;
773 GenSE = CallerSE;
774 IDToValue = std::move(IDToValueCopy);
775 ValueMap = std::move(CallerGlobals);
776 OutsideLoopIterations = std::move(OutsideLoopIterationsCopy);
777 ExprBuilder.switchGeneratedFunc(CallerFn, CallerDT, CallerLI, CallerSE);
778 RegionGen.switchGeneratedFunc(CallerFn, CallerDT, CallerLI, CallerSE);
779 BlockGen.switchGeneratedFunc(CallerFn, CallerDT, CallerLI, CallerSE);
780 Builder.SetInsertPoint(AfterLoop);
781
783 isl_ast_expr_free(Iterator);
784 isl_id_free(IteratorID);
785
786 ParallelLoops++;
787}
788
792 return;
793 }
794 bool Parallel = (IslAstInfo::isParallel(isl::manage_copy(For)) &&
796 createForSequential(isl::manage(For).as<isl::ast_node_for>(), Parallel);
797}
798
801
802 Function *F = Builder.GetInsertBlock()->getParent();
803 LLVMContext &Context = F->getContext();
804
805 BasicBlock *CondBB = SplitBlock(Builder.GetInsertBlock(),
806 Builder.GetInsertPoint(), GenDT, GenLI);
807 CondBB->setName("polly.cond");
808 BasicBlock *MergeBB = SplitBlock(CondBB, CondBB->begin(), GenDT, GenLI);
809 MergeBB->setName("polly.merge");
810 BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
811 BasicBlock *ElseBB = BasicBlock::Create(Context, "polly.else", F);
812
813 GenDT->addNewBlock(ThenBB, CondBB);
814 GenDT->addNewBlock(ElseBB, CondBB);
815 GenDT->changeImmediateDominator(MergeBB, CondBB);
816
817 Loop *L = GenLI->getLoopFor(CondBB);
818 if (L) {
819 L->addBasicBlockToLoop(ThenBB, *GenLI);
820 L->addBasicBlockToLoop(ElseBB, *GenLI);
821 }
822
823 CondBB->getTerminator()->eraseFromParent();
824
825 Builder.SetInsertPoint(CondBB);
826 Value *Predicate = ExprBuilder.create(Cond);
827 Builder.CreateCondBr(Predicate, ThenBB, ElseBB);
828 Builder.SetInsertPoint(ThenBB);
829 Builder.CreateBr(MergeBB);
830 Builder.SetInsertPoint(ElseBB);
831 Builder.CreateBr(MergeBB);
832 Builder.SetInsertPoint(ThenBB->begin());
833
835
836 Builder.SetInsertPoint(ElseBB->begin());
837
840
841 Builder.SetInsertPoint(MergeBB->begin());
842
844
845 IfConditions++;
846}
847
848__isl_give isl_id_to_ast_expr *
850 __isl_keep isl_ast_node *Node) {
851 isl::id_to_ast_expr NewAccesses =
853
855 assert(!Build.is_null() && "Could not obtain isl_ast_build from user node");
856 Stmt->setAstBuild(Build);
857
858 for (auto *MA : *Stmt) {
859 if (!MA->hasNewAccessRelation()) {
861 if (!MA->isAffine())
862 continue;
863 if (MA->getLatestScopArrayInfo()->getBasePtrOriginSAI())
864 continue;
865
866 auto *BasePtr =
867 dyn_cast<Instruction>(MA->getLatestScopArrayInfo()->getBasePtr());
868 if (BasePtr && Stmt->getParent()->getRegion().contains(BasePtr))
869 continue;
870 } else {
871 continue;
872 }
873 }
874 assert(MA->isAffine() &&
875 "Only affine memory accesses can be code generated");
876
877 isl::union_map Schedule = Build.get_schedule();
878
879#ifndef NDEBUG
880 if (MA->isRead()) {
881 auto Dom = Stmt->getDomain().release();
882 auto SchedDom = isl_set_from_union_set(Schedule.domain().release());
883 auto AccDom = isl_map_domain(MA->getAccessRelation().release());
884 Dom = isl_set_intersect_params(Dom,
885 Stmt->getParent()->getContext().release());
886 SchedDom = isl_set_intersect_params(
887 SchedDom, Stmt->getParent()->getContext().release());
888 // Restrict to defined behavior context to match DeLICM's contract:
889 // new read accesses are only required to cover the defined-behavior
890 // subset of the domain.
891 auto *DefinedBehavior =
893 SchedDom =
894 isl_set_intersect_params(SchedDom, isl_set_copy(DefinedBehavior));
895 Dom = isl_set_intersect_params(Dom, DefinedBehavior);
896 assert(isl_set_is_subset(SchedDom, AccDom) != isl_bool_false &&
897 "Access relation not defined on full schedule domain");
898 assert(isl_set_is_subset(Dom, AccDom) != isl_bool_false &&
899 "Access relation not defined on full domain");
900 isl_set_free(AccDom);
901 isl_set_free(SchedDom);
902 isl_set_free(Dom);
903 }
904#endif
905
906 isl::pw_multi_aff PWAccRel = MA->applyScheduleToAccessRelation(Schedule);
907
908 // isl cannot generate an index expression for access-nothing accesses.
909 isl::set AccDomain = PWAccRel.domain();
910 if (AccDomain.is_empty())
911 continue;
912
913 isl::ast_expr AccessExpr = Build.access_from(PWAccRel);
914 NewAccesses = NewAccesses.set(MA->getId(), AccessExpr);
915 }
916
917 return NewAccesses.release();
918}
919
921 ScopStmt *Stmt, LoopToScevMapT &LTS) {
923 "Expression of type 'op' expected");
925 "Operation of type 'call' expected");
926 for (int i = 0; i < isl_ast_expr_get_op_n_arg(Expr) - 1; ++i) {
927 isl_ast_expr *SubExpr;
928 Value *V;
929
930 SubExpr = isl_ast_expr_get_op_arg(Expr, i + 1);
931 V = ExprBuilder.create(SubExpr);
932 ScalarEvolution *SE = Stmt->getParent()->getSE();
933 LTS[Stmt->getLoopForDimension(i)] = SE->getUnknown(V);
934 }
935
936 isl_ast_expr_free(Expr);
937}
938
940 __isl_take isl_ast_expr *Expr, ScopStmt *Stmt,
941 std::vector<LoopToScevMapT> &VLTS, std::vector<Value *> &IVS,
942 __isl_take isl_id *IteratorID) {
943 int i = 0;
944
945 Value *OldValue = IDToValue[IteratorID];
946 for (Value *IV : IVS) {
947 IDToValue[IteratorID] = IV;
948 createSubstitutions(isl_ast_expr_copy(Expr), Stmt, VLTS[i]);
949 i++;
950 }
951
952 IDToValue[IteratorID] = OldValue;
953 isl_id_free(IteratorID);
954 isl_ast_expr_free(Expr);
955}
956
958 ScopStmt *Stmt, __isl_keep isl_id_to_ast_expr *NewAccesses) {
959 assert(Stmt->size() == 2);
960 auto ReadAccess = Stmt->begin();
961 auto WriteAccess = ReadAccess++;
962 assert((*ReadAccess)->isRead() && (*WriteAccess)->isMustWrite());
963 assert((*ReadAccess)->getElementType() == (*WriteAccess)->getElementType() &&
964 "Accesses use the same data type");
965 assert((*ReadAccess)->isArrayKind() && (*WriteAccess)->isArrayKind());
966 auto *AccessExpr =
967 isl_id_to_ast_expr_get(NewAccesses, (*ReadAccess)->getId().release());
968 auto *LoadValue = ExprBuilder.create(AccessExpr);
969 AccessExpr =
970 isl_id_to_ast_expr_get(NewAccesses, (*WriteAccess)->getId().release());
971 auto *StoreAddr = ExprBuilder.createAccessAddress(AccessExpr).first;
972 Builder.CreateStore(LoadValue, StoreAddr);
973}
974
976 assert(!OutsideLoopIterations.contains(L) &&
977 "trying to materialize loop induction variable twice");
978 const SCEV *OuterLIV =
979 SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
980 SE.getUnknown(Builder.getInt64(1)), L, SCEV::FlagNone);
981 Value *V = generateSCEV(OuterLIV);
982 OutsideLoopIterations[L] = SE.getUnknown(V);
983 return V;
984}
985
987 LoopToScevMapT LTS;
988 isl_id *Id;
989 ScopStmt *Stmt;
990
992 isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
993 Id = isl_ast_expr_get_id(StmtExpr);
994 isl_ast_expr_free(StmtExpr);
995
996 LTS.insert_range(OutsideLoopIterations);
997
998 Stmt = (ScopStmt *)isl_id_get_user(Id);
999 auto *NewAccesses = createNewAccesses(Stmt, User);
1000 if (Stmt->isCopyStmt()) {
1001 generateCopyStmt(Stmt, NewAccesses);
1002 isl_ast_expr_free(Expr);
1003 } else {
1004 createSubstitutions(Expr, Stmt, LTS);
1005
1006 if (Stmt->isBlockStmt())
1007 BlockGen.copyStmt(*Stmt, LTS, NewAccesses);
1008 else
1009 RegionGen.copyStmt(*Stmt, LTS, NewAccesses);
1010 }
1011
1012 isl_id_to_ast_expr_free(NewAccesses);
1013 isl_ast_node_free(User);
1014 isl_id_free(Id);
1015}
1016
1018 isl_ast_node_list *List = isl_ast_node_block_get_children(Block);
1019
1020 for (int i = 0; i < isl_ast_node_list_n_ast_node(List); ++i)
1021 create(isl_ast_node_list_get_ast_node(List, i));
1022
1023 isl_ast_node_free(Block);
1024 isl_ast_node_list_free(List);
1025}
1026
1028 if (!TraceStmts)
1029 return;
1030
1031 // Sequence of strings to print.
1032 SmallVector<llvm::Value *, 8> Values;
1033 Values.push_back(RuntimeDebugBuilder::getPrintableString(Builder, "Scop: "));
1034
1035 auto Params = S.getParamSpace();
1036 for (int i : rangeIslSize(0, Params.dim(isl::dim::param))) {
1037 if (i != 0)
1038 Values.push_back(RuntimeDebugBuilder::getPrintableString(Builder, " "));
1039
1040 isl::id PId = Params.get_dim_id(isl::dim::param, i);
1041 Values.push_back(
1043 Values.push_back(RuntimeDebugBuilder::getPrintableString(Builder, "="));
1044 Values.push_back(IDToValue.lookup(PId.get()));
1045 }
1046
1047 Values.push_back(RuntimeDebugBuilder::getPrintableString(Builder, "\n"));
1048 RuntimeDebugBuilder::createCPUPrinter(Builder, ArrayRef<Value *>(Values));
1049}
1050
1052 switch (isl_ast_node_get_type(Node)) {
1053 case isl_ast_node_error:
1054 llvm_unreachable("code generation error");
1055 case isl_ast_node_mark:
1056 createMark(Node);
1057 return;
1058 case isl_ast_node_for:
1059 createFor(Node);
1060 return;
1061 case isl_ast_node_if:
1062 createIf(Node);
1063 return;
1064 case isl_ast_node_user:
1065 createUser(Node);
1066 return;
1067 case isl_ast_node_block:
1068 createBlock(Node);
1069 return;
1070 }
1071
1072 llvm_unreachable("Unknown isl_ast_node type");
1073}
1074
1076 // If the Id is already mapped, skip it.
1077 if (!IDToValue.count(Id)) {
1078 auto *ParamSCEV = (const SCEV *)isl_id_get_user(Id);
1079 Value *V = nullptr;
1080
1081 // Parameters could refer to invariant loads that need to be
1082 // preloaded before we can generate code for the parameter. Thus,
1083 // check if any value referred to in ParamSCEV is an invariant load
1084 // and if so make sure its equivalence class is preloaded.
1085 SetVector<Value *> Values;
1086 findValues(ParamSCEV, SE, Values);
1087 for (auto *Val : Values) {
1088 // Check if the value is an instruction in a dead block within the SCoP
1089 // and if so do not code generate it.
1090 if (auto *Inst = dyn_cast<Instruction>(Val)) {
1091 if (S.contains(Inst)) {
1092 bool IsDead = true;
1093
1094 // Check for "undef" loads first, then if there is a statement for
1095 // the parent of Inst and lastly if the parent of Inst has an empty
1096 // domain. In the first and last case the instruction is dead but if
1097 // there is a statement or the domain is not empty Inst is not dead.
1098 auto MemInst = MemAccInst::dyn_cast(Inst);
1099 auto Address = MemInst ? MemInst.getPointerOperand() : nullptr;
1100 if (Address && SE.getUnknown(UndefValue::get(Address->getType())) ==
1101 SE.getPointerBase(SE.getSCEV(Address))) {
1102 } else if (S.getStmtFor(Inst)) {
1103 IsDead = false;
1104 } else {
1105 auto *Domain = S.getDomainConditions(Inst->getParent()).release();
1106 IsDead = isl_set_is_empty(Domain);
1108 }
1109
1110 if (IsDead) {
1111 V = UndefValue::get(ParamSCEV->getType());
1112 break;
1113 }
1114 }
1115 }
1116
1117 if (auto *IAClass = S.lookupInvariantEquivClass(Val)) {
1118 // Check if this invariant access class is empty, hence if we never
1119 // actually added a loads instruction to it. In that case it has no
1120 // (meaningful) users and we should not try to code generate it.
1121 if (IAClass->InvariantAccesses.empty())
1122 V = UndefValue::get(ParamSCEV->getType());
1123
1124 if (!preloadInvariantEquivClass(*IAClass)) {
1125 isl_id_free(Id);
1126 return false;
1127 }
1128 }
1129 }
1130
1131 V = V ? V : generateSCEV(ParamSCEV);
1132 IDToValue[Id] = V;
1133 }
1134
1135 isl_id_free(Id);
1136 return true;
1137}
1138
1140 for (unsigned i = 0, e = isl_set_dim(Set, isl_dim_param); i < e; ++i) {
1141 if (!isl_set_involves_dims(Set, isl_dim_param, i, 1))
1142 continue;
1144 if (!materializeValue(Id))
1145 return false;
1146 }
1147 return true;
1148}
1149
1151 for (const SCEV *Param : S.parameters()) {
1152 isl_id *Id = S.getIdForParam(Param).release();
1153 if (!materializeValue(Id))
1154 return false;
1155 }
1156 return true;
1157}
1158
1160 isl::ast_build Build,
1161 Instruction *AccInst) {
1162 isl::pw_multi_aff PWAccRel = isl::pw_multi_aff::from_set(AccessRange);
1163 PWAccRel = PWAccRel.gist_params(S.getContext());
1164 isl::ast_expr Access = Build.access_from(PWAccRel);
1165 isl::ast_expr Address = Access.address_of();
1166 Value *AddressValue = ExprBuilder.create(Address.release());
1167 Value *PreloadVal;
1168
1169 // Correct the type as the SAI might have a different type than the user
1170 // expects, especially if the base pointer is a struct.
1171 Type *Ty = AccInst->getType();
1172
1173 auto *Ptr = AddressValue;
1174 auto Name = Ptr->getName();
1175 PreloadVal = Builder.CreateLoad(Ty, Ptr, Name + ".load");
1176 if (LoadInst *PreloadInst = dyn_cast<LoadInst>(PreloadVal))
1177 PreloadInst->setAlignment(cast<LoadInst>(AccInst)->getAlign());
1178
1179 return PreloadVal;
1180}
1181
1183 isl::set Domain) {
1184 isl::set AccessRange = MA.getAddressFunction().range();
1185
1186 if (!materializeParameters(AccessRange.get()))
1187 return nullptr;
1188
1189 isl::ast_build Build =
1191 isl::set Universe = isl::set::universe(Domain.get_space());
1192 bool AlwaysExecuted = Domain.is_equal(Universe);
1193
1194 Instruction *AccInst = MA.getAccessInstruction();
1195 Type *AccInstTy = AccInst->getType();
1196
1197 if (AlwaysExecuted)
1198 return preloadUnconditionally(AccessRange, Build, AccInst);
1199
1200 if (!materializeParameters(Domain.get()))
1201 return nullptr;
1202
1203 isl::ast_expr DomainCond = Build.expr_from(Domain);
1204
1205 ExprBuilder.setTrackOverflow(true);
1206 Value *Cond = ExprBuilder.createBool(DomainCond.release());
1207 Value *OverflowHappened = Builder.CreateNot(ExprBuilder.getOverflowState(),
1208 "polly.preload.cond.overflown");
1209 Cond = Builder.CreateAnd(Cond, OverflowHappened, "polly.preload.cond.result");
1210 ExprBuilder.setTrackOverflow(false);
1211
1212 if (!Cond->getType()->isIntegerTy(1))
1213 Cond = Builder.CreateIsNotNull(Cond);
1214
1215 BasicBlock *CondBB = SplitBlock(Builder.GetInsertBlock(),
1216 Builder.GetInsertPoint(), GenDT, GenLI);
1217 CondBB->setName("polly.preload.cond");
1218
1219 BasicBlock *MergeBB = SplitBlock(CondBB, CondBB->begin(), GenDT, GenLI);
1220 MergeBB->setName("polly.preload.merge");
1221
1222 Function *F = Builder.GetInsertBlock()->getParent();
1223 LLVMContext &Context = F->getContext();
1224 BasicBlock *ExecBB = BasicBlock::Create(Context, "polly.preload.exec", F);
1225
1226 GenDT->addNewBlock(ExecBB, CondBB);
1227 if (Loop *L = GenLI->getLoopFor(CondBB))
1228 L->addBasicBlockToLoop(ExecBB, *GenLI);
1229
1230 auto *CondBBTerminator = CondBB->getTerminator();
1231 Builder.SetInsertPoint(CondBBTerminator->getIterator());
1232 Builder.CreateCondBr(Cond, ExecBB, MergeBB);
1233 CondBBTerminator->eraseFromParent();
1234
1235 Builder.SetInsertPoint(ExecBB);
1236 Builder.CreateBr(MergeBB);
1237
1238 Builder.SetInsertPoint(ExecBB->getTerminator()->getIterator());
1239 Value *PreAccInst = preloadUnconditionally(AccessRange, Build, AccInst);
1240 Builder.SetInsertPoint(MergeBB->getTerminator()->getIterator());
1241 auto *MergePHI = Builder.CreatePHI(
1242 AccInstTy, 2, "polly.preload." + AccInst->getName() + ".merge");
1243 Value *PreloadVal = MergePHI;
1244
1245 if (!PreAccInst) {
1246 PreloadVal = nullptr;
1247 PreAccInst = UndefValue::get(AccInstTy);
1248 }
1249
1250 MergePHI->addIncoming(PreAccInst, ExecBB);
1251 MergePHI->addIncoming(Constant::getNullValue(AccInstTy), CondBB);
1252
1253 return PreloadVal;
1254}
1255
1257 InvariantEquivClassTy &IAClass) {
1258 // For an equivalence class of invariant loads we pre-load the representing
1259 // element with the unified execution context. However, we have to map all
1260 // elements of the class to the one preloaded load as they are referenced
1261 // during the code generation and therefore need to be mapped.
1262 const MemoryAccessList &MAs = IAClass.InvariantAccesses;
1263 if (MAs.empty())
1264 return true;
1265
1266 MemoryAccess *MA = MAs.front();
1267 assert(MA->isArrayKind() && MA->isRead());
1268
1269 // If the access function was already mapped, the preload of this equivalence
1270 // class was triggered earlier already and doesn't need to be done again.
1271 if (ValueMap.count(MA->getAccessInstruction()))
1272 return true;
1273
1274 // Check for recursion which can be caused by additional constraints, e.g.,
1275 // non-finite loop constraints. In such a case we have to bail out and insert
1276 // a "false" runtime check that will cause the original code to be executed.
1277 auto PtrId = std::make_pair(IAClass.IdentifyingPointer, IAClass.AccessType);
1278 if (!PreloadedPtrs.insert(PtrId).second)
1279 return false;
1280
1281 // The execution context of the IAClass.
1282 isl::set &ExecutionCtx = IAClass.ExecutionContext;
1283
1284 // If the base pointer of this class is dependent on another one we have to
1285 // make sure it was preloaded already.
1286 auto *SAI = MA->getScopArrayInfo();
1287 if (auto *BaseIAClass = S.lookupInvariantEquivClass(SAI->getBasePtr())) {
1288 if (!preloadInvariantEquivClass(*BaseIAClass))
1289 return false;
1290
1291 // After we preloaded the BaseIAClass we adjusted the BaseExecutionCtx and
1292 // we need to refine the ExecutionCtx.
1293 isl::set BaseExecutionCtx = BaseIAClass->ExecutionContext;
1294 ExecutionCtx = ExecutionCtx.intersect(BaseExecutionCtx);
1295 }
1296
1297 // If the size of a dimension is dependent on another class, make sure it is
1298 // preloaded.
1299 for (unsigned i = 1, e = SAI->getNumberOfDimensions(); i < e; ++i) {
1300 const SCEV *Dim = SAI->getDimensionSize(i);
1301 SetVector<Value *> Values;
1302 findValues(Dim, SE, Values);
1303 for (auto *Val : Values) {
1304 if (auto *BaseIAClass = S.lookupInvariantEquivClass(Val)) {
1305 if (!preloadInvariantEquivClass(*BaseIAClass))
1306 return false;
1307
1308 // After we preloaded the BaseIAClass we adjusted the BaseExecutionCtx
1309 // and we need to refine the ExecutionCtx.
1310 isl::set BaseExecutionCtx = BaseIAClass->ExecutionContext;
1311 ExecutionCtx = ExecutionCtx.intersect(BaseExecutionCtx);
1312 }
1313 }
1314 }
1315
1316 Instruction *AccInst = MA->getAccessInstruction();
1317 Type *AccInstTy = AccInst->getType();
1318
1319 Value *PreloadVal = preloadInvariantLoad(*MA, ExecutionCtx);
1320 if (!PreloadVal)
1321 return false;
1322
1323 for (const MemoryAccess *MA : MAs) {
1324 Instruction *MAAccInst = MA->getAccessInstruction();
1325 assert(PreloadVal->getType() == MAAccInst->getType());
1326 ValueMap[MAAccInst] = PreloadVal;
1327 }
1328
1329 if (SE.isSCEVable(AccInstTy)) {
1330 isl_id *ParamId = S.getIdForParam(SE.getSCEV(AccInst)).release();
1331 if (ParamId)
1332 IDToValue[ParamId] = PreloadVal;
1333 isl_id_free(ParamId);
1334 }
1335
1336 BasicBlock *EntryBB = &Builder.GetInsertBlock()->getParent()->getEntryBlock();
1337 auto *Alloca = new AllocaInst(AccInstTy, DL.getAllocaAddrSpace(),
1338 AccInst->getName() + ".preload.s2a",
1339 EntryBB->getFirstInsertionPt());
1340 Builder.CreateStore(PreloadVal, Alloca);
1341 ValueMapT PreloadedPointer;
1342 PreloadedPointer[PreloadVal] = AccInst;
1343 Annotator.addAlternativeAliasBases(PreloadedPointer);
1344
1345 for (auto *DerivedSAI : SAI->getDerivedSAIs()) {
1346 Value *BasePtr = DerivedSAI->getBasePtr();
1347
1348 for (const MemoryAccess *MA : MAs) {
1349 // As the derived SAI information is quite coarse, any load from the
1350 // current SAI could be the base pointer of the derived SAI, however we
1351 // should only change the base pointer of the derived SAI if we actually
1352 // preloaded it.
1353 if (BasePtr == MA->getOriginalBaseAddr()) {
1354 assert(BasePtr->getType() == PreloadVal->getType());
1355 DerivedSAI->setBasePtr(PreloadVal);
1356 }
1357
1358 // For scalar derived SAIs we remap the alloca used for the derived value.
1359 if (BasePtr == MA->getAccessInstruction())
1360 ScalarMap[DerivedSAI] = Alloca;
1361 }
1362 }
1363
1364 for (const MemoryAccess *MA : MAs) {
1365 Instruction *MAAccInst = MA->getAccessInstruction();
1366 // Use the escape system to get the correct value to users outside the SCoP.
1368 for (Instruction *UI : MAAccInst->users())
1369 if (!S.contains(UI))
1370 EscapeUsers.push_back(UI);
1371
1372 if (EscapeUsers.empty())
1373 continue;
1374
1376 std::make_pair(Alloca, std::move(EscapeUsers));
1377 }
1378
1379 return true;
1380}
1381
1383 for (auto &SAI : S.arrays()) {
1384 if (SAI->getBasePtr())
1385 continue;
1386
1387 assert(SAI->getNumberOfDimensions() > 0 && SAI->getDimensionSize(0) &&
1388 "The size of the outermost dimension is used to declare newly "
1389 "created arrays that require memory allocation.");
1390
1391 Type *NewArrayType = nullptr;
1392
1393 // Get the size of the array = size(dim_1)*...*size(dim_n)
1394 uint64_t ArraySizeInt = 1;
1395 for (int i = SAI->getNumberOfDimensions() - 1; i >= 0; i--) {
1396 auto *DimSize = SAI->getDimensionSize(i);
1397 unsigned UnsignedDimSize = static_cast<const SCEVConstant *>(DimSize)
1398 ->getAPInt()
1399 .getLimitedValue();
1400
1401 if (!NewArrayType)
1402 NewArrayType = SAI->getElementType();
1403
1404 NewArrayType = ArrayType::get(NewArrayType, UnsignedDimSize);
1405 ArraySizeInt *= UnsignedDimSize;
1406 }
1407
1408 if (SAI->isOnHeap()) {
1409 LLVMContext &Ctx = NewArrayType->getContext();
1410
1411 // Get the IntPtrTy from the Datalayout
1412 auto IntPtrTy = DL.getIntPtrType(Ctx);
1413
1414 // Get the size of the element type in bits
1415 unsigned Size = SAI->getElemSizeInBytes();
1416
1417 // Insert the malloc call at polly.start
1418 BasicBlock *StartBlock = std::get<0>(StartExitBlocks);
1419 Builder.SetInsertPoint(StartBlock->getTerminator()->getIterator());
1420 auto *CreatedArray = Builder.CreateMalloc(
1421 IntPtrTy, ConstantInt::get(Type::getInt64Ty(Ctx), Size),
1422 ConstantInt::get(Type::getInt64Ty(Ctx), ArraySizeInt), nullptr,
1423 SAI->getName());
1424
1425 SAI->setBasePtr(CreatedArray);
1426
1427 // Insert the free call at polly.exiting
1428 BasicBlock *ExitingBlock = std::get<1>(StartExitBlocks);
1429 Builder.SetInsertPoint(ExitingBlock->getTerminator()->getIterator());
1430 Builder.CreateFree(CreatedArray);
1431 } else {
1432 auto InstIt = Builder.GetInsertBlock()
1433 ->getParent()
1434 ->getEntryBlock()
1435 .getTerminator()
1436 ->getIterator();
1437
1438 auto *CreatedArray = new AllocaInst(NewArrayType, DL.getAllocaAddrSpace(),
1439 SAI->getName(), InstIt);
1441 CreatedArray->setAlignment(Align(PollyTargetFirstLevelCacheLineSize));
1442 SAI->setBasePtr(CreatedArray);
1443 }
1444 }
1445}
1446
1448 auto &InvariantEquivClasses = S.getInvariantAccesses();
1449 if (InvariantEquivClasses.empty())
1450 return true;
1451
1452 BasicBlock *PreLoadBB = SplitBlock(Builder.GetInsertBlock(),
1453 Builder.GetInsertPoint(), GenDT, GenLI);
1454 PreLoadBB->setName("polly.preload.begin");
1455 Builder.SetInsertPoint(PreLoadBB->begin());
1456
1457 for (auto &IAClass : InvariantEquivClasses)
1458 if (!preloadInvariantEquivClass(IAClass))
1459 return false;
1460
1461 return true;
1462}
1463
1465 // Materialize values for the parameters of the SCoP.
1467
1468 // Generate values for the current loop iteration for all surrounding loops.
1469 //
1470 // We may also reference loops outside of the scop which do not contain the
1471 // scop itself, but as the number of such scops may be arbitrarily large we do
1472 // not generate code for them here, but only at the point of code generation
1473 // where these values are needed.
1474 Loop *L = LI.getLoopFor(S.getEntry());
1475
1476 while (L != nullptr && S.contains(L))
1477 L = L->getParentLoop();
1478
1479 while (L != nullptr) {
1481 L = L->getParentLoop();
1482 }
1483
1484 isl_set_free(Context);
1485}
1486
1488 /// We pass the insert location of our Builder, as Polly ensures during IR
1489 /// generation that there is always a valid CFG into which instructions are
1490 /// inserted. As a result, the insertpoint is known to be always followed by a
1491 /// terminator instruction. This means the insert point may be specified by a
1492 /// terminator instruction, but it can never point to an ->end() iterator
1493 /// which does not have a corresponding instruction. Hence, dereferencing
1494 /// the insertpoint to obtain an instruction is known to be save.
1495 ///
1496 /// We also do not need to update the Builder here, as new instructions are
1497 /// always inserted _before_ the given InsertLocation. As a result, the
1498 /// insert location remains valid.
1499 assert(Builder.GetInsertBlock()->end() != Builder.GetInsertPoint() &&
1500 "Insert location points after last valid instruction");
1501 BasicBlock::iterator InsertLocation = Builder.GetInsertPoint();
1502
1503 return expandCodeFor(S, SE, Builder.GetInsertBlock()->getParent(), *GenSE, DL,
1504 "polly", Expr, Expr->getType(), InsertLocation,
1505 &ValueMap, /*LoopToScevMap*/ nullptr,
1506 StartBlock->getSinglePredecessor());
1507}
1508
1509/// The AST expression we generate to perform the run-time check assumes
1510/// computations on integer types of infinite size. As we only use 64-bit
1511/// arithmetic we check for overflows, in case of which we set the result
1512/// of this run-time check to false to be conservatively correct,
1514 auto ExprBuilder = getExprBuilder();
1515
1516 // In case the AST expression has integers larger than 64 bit, bail out. The
1517 // resulting LLVM-IR will contain operations on types that use more than 64
1518 // bits. These are -- in case wrapping intrinsics are used -- translated to
1519 // runtime library calls that are not available on all systems (e.g., Android)
1520 // and consequently will result in linker errors.
1521 if (ExprBuilder.hasLargeInts(isl::manage_copy(Condition))) {
1522 isl_ast_expr_free(Condition);
1523 return Builder.getFalse();
1524 }
1525
1526 ExprBuilder.setTrackOverflow(true);
1527 Value *RTC = ExprBuilder.create(Condition);
1528 if (!RTC->getType()->isIntegerTy(1))
1529 RTC = Builder.CreateIsNotNull(RTC);
1530 Value *OverflowHappened =
1531 Builder.CreateNot(ExprBuilder.getOverflowState(), "polly.rtc.overflown");
1532
1534 auto *F = Builder.GetInsertBlock()->getParent();
1536 Builder,
1537 "F: " + F->getName().str() + " R: " + S.getRegion().getNameStr() +
1538 "RTC: ",
1539 RTC, " Overflow: ", OverflowHappened,
1540 "\n"
1541 " (0 failed, -1 succeeded)\n"
1542 " (if one or both are 0 falling back to original code, if both are -1 "
1543 "executing Polly code)\n");
1544 }
1545
1546 RTC = Builder.CreateAnd(RTC, OverflowHappened, "polly.rtc.result");
1547 ExprBuilder.setTrackOverflow(false);
1548
1549 if (!isa<ConstantInt>(RTC))
1550 VersionedScops++;
1551
1552 return RTC;
1553}
static void findReferencesInInst(Instruction *Inst, ScopStmt *UserStmt, Loop *UserScope, const ValueMapT &GlobalMap, SetVector< Value * > &Values, SetVector< const SCEV * > &SCEVs)
static void findReferencesByUse(Value *SrcVal, ScopStmt *UserStmt, Loop *UserScope, const ValueMapT &GlobalMap, SetVector< Value * > &Values, SetVector< const SCEV * > &SCEVs)
static Value * castToType(IRBuilderBase &Builder, Value *V, Type *Ty)
Sign-extend or truncate V to Ty.
static void addReferencesFromStmtSet(isl::set Set, SubtreeReferences *UserPtr)
Extract the out-of-scop values and SCEVs referenced from a set describing a ScopStmt.
static cl::opt< bool > PollyGenerateRTCPrint("polly-codegen-emit-rtc-print", cl::desc("Emit code that prints the runtime check result dynamically."), cl::Hidden, cl::cat(PollyCategory))
static void addReferencesFromStmtUnionSet(isl::union_set USet, SubtreeReferences &References)
Extract the out-of-scop values and SCEVs referenced from a union set referencing multiple ScopStmts.
static cl::opt< bool > PollyGenerateExpressions("polly-codegen-generate-expressions", cl::desc("Generate AST expressions for unmodified and modified accesses"), cl::Hidden, cl::cat(PollyCategory))
static bool fitsInTy(Value *V, IntegerType *IntTy)
Returns true when V is known to fit in IntPtrTy without data loss.
STATISTIC(VersionedScops, "Number of SCoPs that required versioning.")
static bool hasLoopCarriedDependence(isl::ast_node_for For, const Scop &S)
Returns true if the loop has a dist=1 dependence involving FP operations (array-carried RAW/WAW or sc...
static bool IsLoopVectorizerDisabled(isl::ast_node_for Node)
Restore the initial ordering of dimensions of the band node.
static void findReferencesInStmt(ScopStmt *Stmt, SetVector< Value * > &Values, ValueMapT &GlobalMap, SetVector< const SCEV * > &SCEVs)
static cl::opt< OpenMPBackend > PollyOmpBackend("polly-omp-backend", cl::desc("Choose the OpenMP library to use:"), cl::values(clEnumValN(OpenMPBackend::GNU, "GNU", "GNU OpenMP"), clEnumValN(OpenMPBackend::LLVM, "LLVM", "LLVM OpenMP")), cl::Hidden, cl::init(OpenMPBackend::GNU), cl::cat(PollyCategory))
static cl::opt< int > PollyTargetFirstLevelCacheLineSize("polly-target-first-level-cache-line-size", cl::desc("The size of the first level cache line size specified in bytes."), cl::Hidden, cl::init(64), cl::cat(PollyCategory))
OpenMPBackend
OpenMP backend options.
llvm::cl::OptionCategory PollyCategory
bool TraceStmts
isl_bool isl_pw_aff_is_equal(__isl_keep isl_pw_aff *pa1, __isl_keep isl_pw_aff *pa2)
Definition isl_aff.c:7156
__isl_export __isl_give isl_set * isl_pw_aff_domain(__isl_take isl_pw_aff *pwaff)
__isl_export __isl_give isl_ast_expr * isl_ast_node_for_get_init(__isl_keep isl_ast_node *node)
Definition isl_ast.c:1383
__isl_export __isl_give isl_ast_node_list * isl_ast_node_block_get_children(__isl_keep isl_ast_node *node)
Definition isl_ast.c:1576
__isl_null isl_ast_expr * isl_ast_expr_free(__isl_take isl_ast_expr *expr)
Definition isl_ast.c:243
isl_size isl_ast_expr_get_op_n_arg(__isl_keep isl_ast_expr *expr)
Definition isl_ast.c:359
enum isl_ast_expr_op_type isl_ast_expr_get_op_type(__isl_keep isl_ast_expr *expr)
Definition isl_ast.c:342
__isl_give isl_ast_expr * isl_ast_expr_get_op_arg(__isl_keep isl_ast_expr *expr, int pos)
Definition isl_ast.c:377
__isl_export __isl_give isl_ast_node * isl_ast_node_mark_get_node(__isl_keep isl_ast_node *node)
Definition isl_ast.c:1650
__isl_export __isl_give isl_ast_expr * isl_ast_node_for_get_inc(__isl_keep isl_ast_node *node)
Definition isl_ast.c:1416
__isl_give isl_ast_node * isl_ast_node_if_get_else(__isl_keep isl_ast_node *node)
Definition isl_ast.c:1517
__isl_export __isl_give isl_ast_node * isl_ast_node_for_get_body(__isl_keep isl_ast_node *node)
Definition isl_ast.c:1348
__isl_give isl_id * isl_ast_expr_get_id(__isl_keep isl_ast_expr *expr)
Definition isl_ast.c:313
__isl_export __isl_give isl_ast_expr * isl_ast_node_user_get_expr(__isl_keep isl_ast_node *node)
Definition isl_ast.c:1629
__isl_export __isl_give isl_ast_expr * isl_ast_node_if_get_cond(__isl_keep isl_ast_node *node)
Definition isl_ast.c:1568
__isl_export __isl_give isl_id * isl_ast_node_mark_get_id(__isl_keep isl_ast_node *node)
Definition isl_ast.c:1640
__isl_export __isl_give isl_ast_expr * isl_ast_node_for_get_iterator(__isl_keep isl_ast_node *node)
Definition isl_ast.c:1375
__isl_null isl_ast_node * isl_ast_node_free(__isl_take isl_ast_node *node)
Definition isl_ast.c:1180
__isl_give isl_ast_node * isl_ast_node_if_get_then(__isl_keep isl_ast_node *node)
Definition isl_ast.c:1482
isl_bool isl_ast_node_if_has_else(__isl_keep isl_ast_node *node)
Definition isl_ast.c:1499
__isl_give isl_ast_expr * isl_ast_expr_copy(__isl_keep isl_ast_expr *expr)
Definition isl_ast.c:195
@ isl_ast_expr_id
Definition ast_type.h:78
@ isl_ast_expr_op
Definition ast_type.h:77
#define isl_ast_op_le
Definition ast_type.h:66
#define isl_ast_op_lt
Definition ast_type.h:67
isl_ast_node_type
Definition ast_type.h:82
@ isl_ast_node_block
Definition ast_type.h:86
@ isl_ast_node_for
Definition ast_type.h:84
@ isl_ast_node_mark
Definition ast_type.h:87
@ isl_ast_node_if
Definition ast_type.h:85
@ isl_ast_node_error
Definition ast_type.h:83
@ isl_ast_node_user
Definition ast_type.h:88
#define isl_ast_op_type
Definition ast_type.h:46
#define isl_ast_op_call
Definition ast_type.h:70
static isl::ast_build from_context(isl::set set)
isl::checked::ast_expr access_from(isl::checked::multi_pw_aff mpa) const
isl::checked::union_map get_schedule() const
isl::checked::ast_expr expr_from(isl::checked::pw_aff pa) const
boolean isa() const
__isl_give isl_ast_expr * release()
__isl_keep isl_ast_expr * get() const
isl::checked::ast_node_list children() const
isl::checked::ast_node body() const
isl::checked::ast_expr init() const
isl::checked::ast_expr cond() const
isl::checked::ast_expr inc() const
isl::checked::ast_expr iterator() const
isl::checked::id id() const
__isl_keep isl_ast_node * get() const
__isl_give isl_ast_node * release()
__isl_give isl_id_to_ast_expr * release()
isl::checked::id_to_ast_expr set(isl::checked::id key, isl::checked::ast_expr val) const
std::string get_name() const
__isl_keep isl_id * get() const
isl::checked::set range() const
__isl_keep isl_pw_aff * get() const
__isl_give isl_pw_aff * copy() const &
isl::checked::pw_multi_aff gist_params(isl::checked::set set) const
isl::checked::set domain() const
isl::checked::set intersect(isl::checked::set set2) const
boolean is_empty() const
__isl_give isl_set * release()
__isl_keep isl_set * get() const
isl::checked::union_set domain() const
__isl_give isl_union_set * release()
isl::checked::set_list get_set_list() const
long get_num_si() const
static isl::id_to_ast_expr alloc(isl::ctx ctx, int min_size)
static isl::pw_multi_aff from_set(isl::set set)
static isl::set universe(isl::space space)
static isl::val one(isl::ctx ctx)
SmallVector< Instruction *, 4 > EscapeUserVectorTy
Simple vector of instructions to store escape users.
static bool isParallel(const isl::ast_node &Node)
Is this loop a parallel loop?
Definition IslAst.cpp:607
static isl::pw_aff getMinimalDependenceDistance(const isl::ast_node &Node)
Get minimal dependence distance or nullptr if not available.
Definition IslAst.cpp:652
static bool isExecutedInParallel(const isl::ast_node &Node)
Will the loop be run as thread parallel?
Definition IslAst.cpp:627
static isl::union_map getSchedule(const isl::ast_node &Node)
Get the nodes schedule or a nullptr if not available.
Definition IslAst.cpp:646
static isl::ast_build getBuild(const isl::ast_node &Node)
Get the nodes build context or a nullptr if not available.
Definition IslAst.cpp:663
static bool isReductionParallel(const isl::ast_node &Node)
Is this loop a reduction parallel loop?
Definition IslAst.cpp:622
llvm::MapVector< isl_id *, llvm::AssertingVH< llvm::Value > > IDToValueTy
A map from isl_ids to llvm::Values.
void addParameters(__isl_take isl_set *Context)
Value * getLatestValue(Value *Original) const
Return the most up-to-date version of the llvm::Value for code generation.
void create(__isl_take isl_ast_node *Node)
RegionGenerator RegionGen
The generator used to copy a non-affine region.
ScopAnnotator & Annotator
BlockGenerator::AllocaMapTy ScalarMap
Maps used by the block and region generator to demote scalars.
SmallVector< Function *, 8 > ParallelSubfunctions
A collection of all parallel subfunctions that have been created.
IslExprBuilder::IDToValueTy IDToValue
bool preloadInvariantEquivClass(InvariantEquivClassTy &IAClass)
Preload the invariant access equivalence class IAClass.
IslExprBuilder ExprBuilder
void createForSequential(isl::ast_node_for For, bool MarkParallel)
__isl_give isl_id_to_ast_expr * createNewAccesses(ScopStmt *Stmt, __isl_keep isl_ast_node *Node)
Create new access functions for modified memory accesses.
void createForParallel(__isl_take isl_ast_node *For)
Create LLVM-IR that executes a for node thread parallel.
Value * preloadUnconditionally(isl::set AccessRange, isl::ast_build Build, Instruction *AccInst)
Preload the memory access at AccessRange with Build.
bool preloadInvariantLoads()
Preload all memory loads that are invariant.
Value * generateSCEV(const SCEV *Expr)
Generate code for a given SCEV*.
bool materializeParameters()
Materialize all parameters in the current scop.
const DataLayout & DL
ValueMapT ValueMap
A set of Value -> Value remappings to apply when generating new code.
Value * preloadInvariantLoad(const MemoryAccess &MA, isl::set Domain)
Preload the memory load access MA.
bool materializeValue(__isl_take isl_id *Id)
Materialize code for Id if it was not done before.
SmallSet< std::pair< const SCEV *, Type * >, 16 > PreloadedPtrs
Set to remember materialized invariant loads.
Value * materializeNonScopLoopInductionVariable(const Loop *L)
Materialize a canonical loop induction variable for L, which is a loop that is not present in the Sco...
virtual void createBlock(__isl_take isl_ast_node *Block)
virtual void createUser(__isl_take isl_ast_node *User)
ScalarEvolution & SE
void createSubstitutionsVector(__isl_take isl_ast_expr *Expr, ScopStmt *Stmt, std::vector< LoopToScevMapT > &VLTS, std::vector< Value * > &IVS, __isl_take isl_id *IteratorID)
DominatorTree * GenDT
Relates to the region where the code is emitted into.
virtual void createFor(__isl_take isl_ast_node *For)
virtual void createMark(__isl_take isl_ast_node *Marker)
Generate code for a marker now.
void allocateNewArrays(BBPair StartExitBlocks)
Allocate memory for all new arrays created by Polly.
virtual isl::union_map getScheduleForAstNode(const isl::ast_node &Node)
Get the schedule for a given AST node.
PollyIRBuilder & Builder
void getReferencesInSubtree(const isl::ast_node &For, SetVector< Value * > &Values, SetVector< const Loop * > &Loops)
Compute the values and loops referenced in this subtree.
ScalarEvolution * GenSE
void generateCopyStmt(ScopStmt *Stmt, __isl_keep isl_id_to_ast_expr *NewAccesses)
Create code for a copy statement.
virtual void createIf(__isl_take isl_ast_node *If)
void createSubstitutions(__isl_take isl_ast_expr *Expr, ScopStmt *Stmt, LoopToScevMapT &LTS)
Generate LLVM-IR that computes the values of the original induction variables in function of the newl...
isl::ast_expr getUpperBound(isl::ast_node_for For, CmpInst::Predicate &Predicate)
BlockGenerator::EscapeUsersAllocaMapTy EscapeMap
See BlockGenerator::EscapeMap.
BlockGenerator BlockGen
The generator used to copy a basic block.
BlockGenerator & getBlockGenerator()
Get the associated block generator.
int getNumberOfIterations(isl::ast_node_for For)
Return non-negative number of iterations in case of the following form of a loop and -1 otherwise.
Value * createRTC(isl_ast_expr *Condition)
Generate code that evaluates Condition at run-time.
IslExprBuilder & getExprBuilder()
MapVector< const Loop *, const SCEV * > OutsideLoopIterations
The current iteration of out-of-scop loops.
static MemAccInst dyn_cast(llvm::Value &V)
Definition ScopHelper.h:179
Represent memory accesses in statements.
Definition ScopInfo.h:428
Instruction * getAccessInstruction() const
Return the access instruction of this memory access.
Definition ScopInfo.h:882
bool isRead() const
Is this a read memory access?
Definition ScopInfo.h:757
isl::map getAddressFunction() const
Get an isl map describing the memory address accessed.
Definition ScopInfo.cpp:627
const ScopArrayInfo * getScopArrayInfo() const
Legacy name of getOriginalScopArrayInfo().
Definition ScopInfo.h:850
Value * getOriginalBaseAddr() const
Get the original base address of this access (e.g.
Definition ScopInfo.h:830
bool isArrayKind() const
Old name of isOriginalArrayKind.
Definition ScopInfo.h:952
This ParallelLoopGenerator subclass handles the generation of parallelized code, utilizing the GNU Op...
This ParallelLoopGenerator subclass handles the generation of parallelized code, utilizing the LLVM O...
Statement of the Scop.
Definition ScopInfo.h:1137
Scop * getParent()
Definition ScopInfo.h:1525
const std::vector< Instruction * > & getInstructions() const
Definition ScopInfo.h:1528
bool isBlockStmt() const
Return true if this statement represents a single basic block.
Definition ScopInfo.h:1318
size_t size() const
Definition ScopInfo.h:1521
Region * getRegion() const
Get the region represented by this ScopStmt (if any).
Definition ScopInfo.h:1327
BasicBlock * getBasicBlock() const
Get the BasicBlock represented by this ScopStmt (if any).
Definition ScopInfo.h:1315
bool isCopyStmt() const
Return true if this is a copy statement.
Definition ScopInfo.h:1321
bool isRegionStmt() const
Return true if this statement represents a whole region.
Definition ScopInfo.h:1330
Loop * getLoopForDimension(unsigned Dimension) const
Get the loop for a dimension.
isl::set getDomain() const
Get the iteration domain of this ScopStmt.
void setAstBuild(isl::ast_build B)
Set the isl AST build.
Definition ScopInfo.h:1559
iterator begin()
Definition ScopInfo.h:1517
Static Control Part.
Definition ScopInfo.h:1627
ScalarEvolution * getSE() const
Return the scalar evolution.
isl::set getBestKnownDefinedBehaviorContext() const
Return the define behavior context, or if not available, its approximation from all other contexts.
Definition ScopInfo.h:2171
isl::ctx getIslCtx() const
Get the isl context of this static control part.
LoopInfo * getLI() const
Return the LoopInfo used for this Scop.
Definition ScopInfo.h:2013
bool contains(const Loop *L) const
Check if L is contained in the SCoP.
Definition ScopInfo.h:2095
const Region & getRegion() const
Get the maximum region of this static control part.
Definition ScopInfo.h:2088
isl::set getContext() const
Get the constraint on parameter of this Scop.
Determine the nature of a value's use within a statement.
const SCEV * getScevExpr() const
Return the ScalarEvolution representation of Val.
static VirtualUse create(Scop *S, const Use &U, LoopInfo *LI, bool Virtual)
Get a VirtualUse for an llvm::Use.
UseKind getKind() const
Return the type of use.
#define __isl_take
Definition ctx.h:23
#define __isl_give
Definition ctx.h:20
#define __isl_keep
Definition ctx.h:26
@ isl_bool_false
Definition ctx.h:92
@ isl_bool_true
Definition ctx.h:93
__isl_export __isl_keep const char * isl_id_get_name(__isl_keep isl_id *id)
Definition isl_id.c:41
__isl_null isl_id * isl_id_free(__isl_take isl_id *id)
Definition isl_id.c:207
void * isl_id_get_user(__isl_keep isl_id *id)
Definition isl_id.c:36
enum isl_ast_expr_type isl_ast_expr_get_type(__isl_keep isl_ast_expr *expr)
Definition isl_ast.c:276
enum isl_ast_node_type isl_ast_node_get_type(__isl_keep isl_ast_node *node)
Definition isl_ast.c:907
#define S(TYPE, NAME)
#define isl_set
#define assert(exp)
__isl_export __isl_give isl_set * isl_map_domain(__isl_take isl_map *bmap)
Definition isl_map.c:8777
boolean manage(isl_bool val)
Definition cpp-checked.h:98
aff manage_copy(__isl_keep isl_aff *ptr)
std::forward_list< MemoryAccess * > MemoryAccessList
Ordered list type to hold accesses.
Definition ScopInfo.h:1088
void findValues(const llvm::SCEV *Expr, llvm::ScalarEvolution &SE, llvm::SetVector< llvm::Value * > &Values)
Find the values referenced by SCEVUnknowns in a given SCEV expression.
void findLoops(const llvm::SCEV *Expr, llvm::SetVector< const llvm::Loop * > &Loops)
Find the loops referenced from a SCEV expression.
llvm::Value * expandCodeFor(Scop &S, llvm::ScalarEvolution &SE, llvm::Function *GenFn, llvm::ScalarEvolution &GenSE, const llvm::DataLayout &DL, const char *Name, const llvm::SCEV *E, llvm::Type *Ty, llvm::BasicBlock::iterator IP, ValueMapT *VMap, LoopToScevMapT *LoopMap, llvm::BasicBlock *RTCBB)
Wrapper for SCEVExpander extended to all Polly features.
@ Value
MemoryKind::Value: Models an llvm::Value.
Definition ScopInfo.h:151
void addReferencesFromStmt(ScopStmt *Stmt, void *UserPtr, bool CreateScalarRefs=true)
Extract the out-of-scop values and SCEVs referenced from a ScopStmt.
BandAttr * getLoopAttr(const isl::id &Id)
Return the BandAttr of a loop's isl::id.
Value * createLoop(Value *LowerBound, Value *UpperBound, Value *Stride, PollyIRBuilder &Builder, LoopInfo &LI, DominatorTree &DT, BasicBlock *&ExitBlock, ICmpInst::Predicate Predicate, ScopAnnotator *Annotator=nullptr, bool Parallel=false, bool UseGuard=true, bool LoopVectDisabled=false, bool SkipVectorizeEnableMetadata=false)
Create a scalar do/for-style loop.
llvm::iota_range< unsigned > rangeIslSize(unsigned Begin, isl::size End)
Check that End is valid and return an iterator from Begin to End.
Definition ISLTools.cpp:597
llvm::DenseMap< const llvm::Loop *, llvm::SCEVUse > LoopToScevMapT
Same as llvm/Analysis/ScalarEvolutionExpressions.h.
Definition ScopHelper.h:41
llvm::DenseMap< llvm::AssertingVH< llvm::Value >, llvm::AssertingVH< llvm::Value > > ValueMapT
Type to remap values.
Definition ScopHelper.h:106
std::pair< llvm::BasicBlock *, llvm::BasicBlock * > BBPair
Type to hold region delimiters (entry & exit block).
Definition Utils.h:31
__isl_export __isl_give isl_set * isl_set_intersect_params(__isl_take isl_set *set, __isl_take isl_set *params)
Definition isl_map.c:4538
__isl_null isl_set * isl_set_free(__isl_take isl_set *set)
Definition isl_map.c:4055
__isl_export isl_bool isl_set_is_subset(__isl_keep isl_set *set1, __isl_keep isl_set *set2)
__isl_give isl_set * isl_set_copy(__isl_keep isl_set *set)
Definition isl_map.c:1470
isl_bool isl_set_involves_dims(__isl_keep isl_set *set, enum isl_dim_type type, unsigned first, unsigned n)
Definition isl_map.c:3528
isl_size isl_set_dim(__isl_keep isl_set *set, enum isl_dim_type type)
Definition isl_map.c:132
__isl_give isl_id * isl_set_get_dim_id(__isl_keep isl_set *set, enum isl_dim_type type, unsigned pos)
Definition isl_map.c:1004
__isl_export isl_bool isl_set_is_empty(__isl_keep isl_set *set)
Definition isl_map.c:9828
@ isl_dim_param
Definition space_type.h:15
Represent the attributes of a loop.
Definition ScopHelper.h:538
Type for equivalent invariant accesses and their domain context.
Definition ScopInfo.h:1103
MemoryAccessList InvariantAccesses
Memory accesses now treated invariant.
Definition ScopInfo.h:1112
Type * AccessType
The type of the invariant access.
Definition ScopInfo.h:1124
isl::set ExecutionContext
The execution context under which the memory location is accessed.
Definition ScopInfo.h:1118
const SCEV * IdentifyingPointer
The pointer that identifies this equivalence class.
Definition ScopInfo.h:1105
static void createCPUPrinter(PollyIRBuilder &Builder, Args... args)
Print a set of LLVM-IR Values or StringRefs via printf.
static llvm::Value * getPrintableString(PollyIRBuilder &Builder, llvm::StringRef Str)
Generate a constant string into the builder's llvm::Module which can be passed to createCPUPrinter().
static TupleKindPtr Domain("Domain")
static TupleKindPtr Ctx
static Signature domain
__isl_give isl_set * isl_set_from_union_set(__isl_take isl_union_set *uset)