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