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