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 = KnownParallel || (IslAstInfo::isParallel(For) && 462 !IslAstInfo::isReductionParallel(For)); 463 464 Body = isl_ast_node_for_get_body(For); 465 466 // isl_ast_node_for_is_degenerate(For) 467 // 468 // TODO: For degenerated loops we could generate a plain assignment. 469 // However, for now we just reuse the logic for normal loops, which will 470 // create a loop with a single iteration. 471 472 Init = isl_ast_node_for_get_init(For); 473 Inc = isl_ast_node_for_get_inc(For); 474 Iterator = isl_ast_node_for_get_iterator(For); 475 IteratorID = isl_ast_expr_get_id(Iterator); 476 UB = getUpperBound(For, Predicate); 477 478 ValueLB = ExprBuilder.create(Init); 479 ValueUB = ExprBuilder.create(UB); 480 ValueInc = ExprBuilder.create(Inc); 481 482 MaxType = ExprBuilder.getType(Iterator); 483 MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType()); 484 MaxType = ExprBuilder.getWidestType(MaxType, ValueUB->getType()); 485 MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType()); 486 487 if (MaxType != ValueLB->getType()) 488 ValueLB = Builder.CreateSExt(ValueLB, MaxType); 489 if (MaxType != ValueUB->getType()) 490 ValueUB = Builder.CreateSExt(ValueUB, MaxType); 491 if (MaxType != ValueInc->getType()) 492 ValueInc = Builder.CreateSExt(ValueInc, MaxType); 493 494 // If we can show that LB <Predicate> UB holds at least once, we can 495 // omit the GuardBB in front of the loop. 496 bool UseGuardBB = 497 !SE.isKnownPredicate(Predicate, SE.getSCEV(ValueLB), SE.getSCEV(ValueUB)); 498 IV = createLoop(ValueLB, ValueUB, ValueInc, Builder, P, LI, DT, ExitBlock, 499 Predicate, &Annotator, Parallel, UseGuardBB); 500 IDToValue[IteratorID] = IV; 501 502 create(Body); 503 504 Annotator.popLoop(Parallel); 505 506 IDToValue.erase(IDToValue.find(IteratorID)); 507 508 Builder.SetInsertPoint(&ExitBlock->front()); 509 510 isl_ast_node_free(For); 511 isl_ast_expr_free(Iterator); 512 isl_id_free(IteratorID); 513 } 514 515 /// Remove the BBs contained in a (sub)function from the dominator tree. 516 /// 517 /// This function removes the basic blocks that are part of a subfunction from 518 /// the dominator tree. Specifically, when generating code it may happen that at 519 /// some point the code generation continues in a new sub-function (e.g., when 520 /// generating OpenMP code). The basic blocks that are created in this 521 /// sub-function are then still part of the dominator tree of the original 522 /// function, such that the dominator tree reaches over function boundaries. 523 /// This is not only incorrect, but also causes crashes. This function now 524 /// removes from the dominator tree all basic blocks that are dominated (and 525 /// consequently reachable) from the entry block of this (sub)function. 526 /// 527 /// FIXME: A LLVM (function or region) pass should not touch anything outside of 528 /// the function/region it runs on. Hence, the pure need for this function shows 529 /// that we do not comply to this rule. At the moment, this does not cause any 530 /// issues, but we should be aware that such issues may appear. Unfortunately 531 /// the current LLVM pass infrastructure does not allow to make Polly a module 532 /// or call-graph pass to solve this issue, as such a pass would not have access 533 /// to the per-function analyses passes needed by Polly. A future pass manager 534 /// infrastructure is supposed to enable such kind of access possibly allowing 535 /// us to create a cleaner solution here. 536 /// 537 /// FIXME: Instead of adding the dominance information and then dropping it 538 /// later on, we should try to just not add it in the first place. This requires 539 /// some careful testing to make sure this does not break in interaction with 540 /// the SCEVBuilder and SplitBlock which may rely on the dominator tree or 541 /// which may try to update it. 542 /// 543 /// @param F The function which contains the BBs to removed. 544 /// @param DT The dominator tree from which to remove the BBs. 545 static void removeSubFuncFromDomTree(Function *F, DominatorTree &DT) { 546 DomTreeNode *N = DT.getNode(&F->getEntryBlock()); 547 std::vector<BasicBlock *> Nodes; 548 549 // We can only remove an element from the dominator tree, if all its children 550 // have been removed. To ensure this we obtain the list of nodes to remove 551 // using a post-order tree traversal. 552 for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I) 553 Nodes.push_back(I->getBlock()); 554 555 for (BasicBlock *BB : Nodes) 556 DT.eraseNode(BB); 557 } 558 559 void IslNodeBuilder::createForParallel(__isl_take isl_ast_node *For) { 560 isl_ast_node *Body; 561 isl_ast_expr *Init, *Inc, *Iterator, *UB; 562 isl_id *IteratorID; 563 Value *ValueLB, *ValueUB, *ValueInc; 564 Type *MaxType; 565 Value *IV; 566 CmpInst::Predicate Predicate; 567 568 // The preamble of parallel code interacts different than normal code with 569 // e.g., scalar initialization. Therefore, we ensure the parallel code is 570 // separated from the last basic block. 571 BasicBlock *ParBB = SplitBlock(Builder.GetInsertBlock(), 572 &*Builder.GetInsertPoint(), &DT, &LI); 573 ParBB->setName("polly.parallel.for"); 574 Builder.SetInsertPoint(&ParBB->front()); 575 576 Body = isl_ast_node_for_get_body(For); 577 Init = isl_ast_node_for_get_init(For); 578 Inc = isl_ast_node_for_get_inc(For); 579 Iterator = isl_ast_node_for_get_iterator(For); 580 IteratorID = isl_ast_expr_get_id(Iterator); 581 UB = getUpperBound(For, Predicate); 582 583 ValueLB = ExprBuilder.create(Init); 584 ValueUB = ExprBuilder.create(UB); 585 ValueInc = ExprBuilder.create(Inc); 586 587 // OpenMP always uses SLE. In case the isl generated AST uses a SLT 588 // expression, we need to adjust the loop blound by one. 589 if (Predicate == CmpInst::ICMP_SLT) 590 ValueUB = Builder.CreateAdd( 591 ValueUB, Builder.CreateSExt(Builder.getTrue(), ValueUB->getType())); 592 593 MaxType = ExprBuilder.getType(Iterator); 594 MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType()); 595 MaxType = ExprBuilder.getWidestType(MaxType, ValueUB->getType()); 596 MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType()); 597 598 if (MaxType != ValueLB->getType()) 599 ValueLB = Builder.CreateSExt(ValueLB, MaxType); 600 if (MaxType != ValueUB->getType()) 601 ValueUB = Builder.CreateSExt(ValueUB, MaxType); 602 if (MaxType != ValueInc->getType()) 603 ValueInc = Builder.CreateSExt(ValueInc, MaxType); 604 605 BasicBlock::iterator LoopBody; 606 607 SetVector<Value *> SubtreeValues; 608 SetVector<const Loop *> Loops; 609 610 getReferencesInSubtree(For, SubtreeValues, Loops); 611 612 // Create for all loops we depend on values that contain the current loop 613 // iteration. These values are necessary to generate code for SCEVs that 614 // depend on such loops. As a result we need to pass them to the subfunction. 615 for (const Loop *L : Loops) { 616 const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)), 617 SE.getUnknown(Builder.getInt64(1)), 618 L, SCEV::FlagAnyWrap); 619 Value *V = generateSCEV(OuterLIV); 620 OutsideLoopIterations[L] = SE.getUnknown(V); 621 SubtreeValues.insert(V); 622 } 623 624 ValueMapT NewValues; 625 ParallelLoopGenerator ParallelLoopGen(Builder, P, LI, DT, DL); 626 627 IV = ParallelLoopGen.createParallelLoop(ValueLB, ValueUB, ValueInc, 628 SubtreeValues, NewValues, &LoopBody); 629 BasicBlock::iterator AfterLoop = Builder.GetInsertPoint(); 630 Builder.SetInsertPoint(&*LoopBody); 631 632 // Remember the parallel subfunction 633 ParallelSubfunctions.push_back(LoopBody->getFunction()); 634 635 // Save the current values. 636 auto ValueMapCopy = ValueMap; 637 IslExprBuilder::IDToValueTy IDToValueCopy = IDToValue; 638 639 updateValues(NewValues); 640 IDToValue[IteratorID] = IV; 641 642 ValueMapT NewValuesReverse; 643 644 for (auto P : NewValues) 645 NewValuesReverse[P.second] = P.first; 646 647 Annotator.addAlternativeAliasBases(NewValuesReverse); 648 649 create(Body); 650 651 Annotator.resetAlternativeAliasBases(); 652 // Restore the original values. 653 ValueMap = ValueMapCopy; 654 IDToValue = IDToValueCopy; 655 656 Builder.SetInsertPoint(&*AfterLoop); 657 removeSubFuncFromDomTree((*LoopBody).getParent()->getParent(), DT); 658 659 for (const Loop *L : Loops) 660 OutsideLoopIterations.erase(L); 661 662 isl_ast_node_free(For); 663 isl_ast_expr_free(Iterator); 664 isl_id_free(IteratorID); 665 } 666 667 void IslNodeBuilder::createFor(__isl_take isl_ast_node *For) { 668 bool Vector = PollyVectorizerChoice == VECTORIZER_POLLY; 669 670 if (Vector && IslAstInfo::isInnermostParallel(For) && 671 !IslAstInfo::isReductionParallel(For)) { 672 int VectorWidth = getNumberOfIterations(For); 673 if (1 < VectorWidth && VectorWidth <= 16) { 674 createForVector(For, VectorWidth); 675 return; 676 } 677 } 678 679 if (IslAstInfo::isExecutedInParallel(For)) { 680 createForParallel(For); 681 return; 682 } 683 createForSequential(For, false); 684 } 685 686 void IslNodeBuilder::createIf(__isl_take isl_ast_node *If) { 687 isl_ast_expr *Cond = isl_ast_node_if_get_cond(If); 688 689 Function *F = Builder.GetInsertBlock()->getParent(); 690 LLVMContext &Context = F->getContext(); 691 692 BasicBlock *CondBB = SplitBlock(Builder.GetInsertBlock(), 693 &*Builder.GetInsertPoint(), &DT, &LI); 694 CondBB->setName("polly.cond"); 695 BasicBlock *MergeBB = SplitBlock(CondBB, &CondBB->front(), &DT, &LI); 696 MergeBB->setName("polly.merge"); 697 BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F); 698 BasicBlock *ElseBB = BasicBlock::Create(Context, "polly.else", F); 699 700 DT.addNewBlock(ThenBB, CondBB); 701 DT.addNewBlock(ElseBB, CondBB); 702 DT.changeImmediateDominator(MergeBB, CondBB); 703 704 Loop *L = LI.getLoopFor(CondBB); 705 if (L) { 706 L->addBasicBlockToLoop(ThenBB, LI); 707 L->addBasicBlockToLoop(ElseBB, LI); 708 } 709 710 CondBB->getTerminator()->eraseFromParent(); 711 712 Builder.SetInsertPoint(CondBB); 713 Value *Predicate = ExprBuilder.create(Cond); 714 Builder.CreateCondBr(Predicate, ThenBB, ElseBB); 715 Builder.SetInsertPoint(ThenBB); 716 Builder.CreateBr(MergeBB); 717 Builder.SetInsertPoint(ElseBB); 718 Builder.CreateBr(MergeBB); 719 Builder.SetInsertPoint(&ThenBB->front()); 720 721 create(isl_ast_node_if_get_then(If)); 722 723 Builder.SetInsertPoint(&ElseBB->front()); 724 725 if (isl_ast_node_if_has_else(If)) 726 create(isl_ast_node_if_get_else(If)); 727 728 Builder.SetInsertPoint(&MergeBB->front()); 729 730 isl_ast_node_free(If); 731 } 732 733 __isl_give isl_id_to_ast_expr * 734 IslNodeBuilder::createNewAccesses(ScopStmt *Stmt, 735 __isl_keep isl_ast_node *Node) { 736 isl_id_to_ast_expr *NewAccesses = 737 isl_id_to_ast_expr_alloc(Stmt->getParent()->getIslCtx(), 0); 738 739 auto *Build = IslAstInfo::getBuild(Node); 740 assert(Build && "Could not obtain isl_ast_build from user node"); 741 Stmt->setAstBuild(Build); 742 743 for (auto *MA : *Stmt) { 744 if (!MA->hasNewAccessRelation()) { 745 if (PollyGenerateExpressions) { 746 if (!MA->isAffine()) 747 continue; 748 if (MA->getLatestScopArrayInfo()->getBasePtrOriginSAI()) 749 continue; 750 751 auto *BasePtr = 752 dyn_cast<Instruction>(MA->getLatestScopArrayInfo()->getBasePtr()); 753 if (BasePtr && Stmt->getParent()->getRegion().contains(BasePtr)) 754 continue; 755 } else { 756 continue; 757 } 758 } 759 assert(MA->isAffine() && 760 "Only affine memory accesses can be code generated"); 761 762 auto Schedule = isl_ast_build_get_schedule(Build); 763 764 #ifndef NDEBUG 765 auto Dom = Stmt->getDomain(); 766 auto SchedDom = isl_set_from_union_set( 767 isl_union_map_domain(isl_union_map_copy(Schedule))); 768 auto AccDom = isl_map_domain(MA->getAccessRelation()); 769 Dom = isl_set_intersect_params(Dom, Stmt->getParent()->getContext()); 770 SchedDom = 771 isl_set_intersect_params(SchedDom, Stmt->getParent()->getContext()); 772 assert(isl_set_is_subset(SchedDom, AccDom) && 773 "Access relation not defined on full schedule domain"); 774 assert(isl_set_is_subset(Dom, AccDom) && 775 "Access relation not defined on full domain"); 776 isl_set_free(AccDom); 777 isl_set_free(SchedDom); 778 isl_set_free(Dom); 779 #endif 780 781 auto PWAccRel = MA->applyScheduleToAccessRelation(Schedule); 782 783 auto AccessExpr = isl_ast_build_access_from_pw_multi_aff(Build, PWAccRel); 784 NewAccesses = isl_id_to_ast_expr_set(NewAccesses, MA->getId(), AccessExpr); 785 } 786 787 return NewAccesses; 788 } 789 790 void IslNodeBuilder::createSubstitutions(__isl_take isl_ast_expr *Expr, 791 ScopStmt *Stmt, LoopToScevMapT <S) { 792 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op && 793 "Expression of type 'op' expected"); 794 assert(isl_ast_expr_get_op_type(Expr) == isl_ast_op_call && 795 "Opertation of type 'call' expected"); 796 for (int i = 0; i < isl_ast_expr_get_op_n_arg(Expr) - 1; ++i) { 797 isl_ast_expr *SubExpr; 798 Value *V; 799 800 SubExpr = isl_ast_expr_get_op_arg(Expr, i + 1); 801 V = ExprBuilder.create(SubExpr); 802 ScalarEvolution *SE = Stmt->getParent()->getSE(); 803 LTS[Stmt->getLoopForDimension(i)] = SE->getUnknown(V); 804 } 805 806 isl_ast_expr_free(Expr); 807 } 808 809 void IslNodeBuilder::createSubstitutionsVector( 810 __isl_take isl_ast_expr *Expr, ScopStmt *Stmt, 811 std::vector<LoopToScevMapT> &VLTS, std::vector<Value *> &IVS, 812 __isl_take isl_id *IteratorID) { 813 int i = 0; 814 815 Value *OldValue = IDToValue[IteratorID]; 816 for (Value *IV : IVS) { 817 IDToValue[IteratorID] = IV; 818 createSubstitutions(isl_ast_expr_copy(Expr), Stmt, VLTS[i]); 819 i++; 820 } 821 822 IDToValue[IteratorID] = OldValue; 823 isl_id_free(IteratorID); 824 isl_ast_expr_free(Expr); 825 } 826 827 void IslNodeBuilder::generateCopyStmt( 828 ScopStmt *Stmt, __isl_keep isl_id_to_ast_expr *NewAccesses) { 829 assert(Stmt->size() == 2); 830 auto ReadAccess = Stmt->begin(); 831 auto WriteAccess = ReadAccess++; 832 assert((*ReadAccess)->isRead() && (*WriteAccess)->isMustWrite()); 833 assert((*ReadAccess)->getElementType() == (*WriteAccess)->getElementType() && 834 "Accesses use the same data type"); 835 assert((*ReadAccess)->isArrayKind() && (*WriteAccess)->isArrayKind()); 836 auto *AccessExpr = 837 isl_id_to_ast_expr_get(NewAccesses, (*ReadAccess)->getId()); 838 auto *LoadValue = ExprBuilder.create(AccessExpr); 839 AccessExpr = isl_id_to_ast_expr_get(NewAccesses, (*WriteAccess)->getId()); 840 auto *StoreAddr = ExprBuilder.createAccessAddress(AccessExpr); 841 Builder.CreateStore(LoadValue, StoreAddr); 842 } 843 844 void IslNodeBuilder::createUser(__isl_take isl_ast_node *User) { 845 LoopToScevMapT LTS; 846 isl_id *Id; 847 ScopStmt *Stmt; 848 849 isl_ast_expr *Expr = isl_ast_node_user_get_expr(User); 850 isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0); 851 Id = isl_ast_expr_get_id(StmtExpr); 852 isl_ast_expr_free(StmtExpr); 853 854 LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end()); 855 856 Stmt = (ScopStmt *)isl_id_get_user(Id); 857 auto *NewAccesses = createNewAccesses(Stmt, User); 858 if (Stmt->isCopyStmt()) { 859 generateCopyStmt(Stmt, NewAccesses); 860 isl_ast_expr_free(Expr); 861 } else { 862 createSubstitutions(Expr, Stmt, LTS); 863 864 if (Stmt->isBlockStmt()) 865 BlockGen.copyStmt(*Stmt, LTS, NewAccesses); 866 else 867 RegionGen.copyStmt(*Stmt, LTS, NewAccesses); 868 } 869 870 isl_id_to_ast_expr_free(NewAccesses); 871 isl_ast_node_free(User); 872 isl_id_free(Id); 873 } 874 875 void IslNodeBuilder::createBlock(__isl_take isl_ast_node *Block) { 876 isl_ast_node_list *List = isl_ast_node_block_get_children(Block); 877 878 for (int i = 0; i < isl_ast_node_list_n_ast_node(List); ++i) 879 create(isl_ast_node_list_get_ast_node(List, i)); 880 881 isl_ast_node_free(Block); 882 isl_ast_node_list_free(List); 883 } 884 885 void IslNodeBuilder::create(__isl_take isl_ast_node *Node) { 886 switch (isl_ast_node_get_type(Node)) { 887 case isl_ast_node_error: 888 llvm_unreachable("code generation error"); 889 case isl_ast_node_mark: 890 createMark(Node); 891 return; 892 case isl_ast_node_for: 893 createFor(Node); 894 return; 895 case isl_ast_node_if: 896 createIf(Node); 897 return; 898 case isl_ast_node_user: 899 createUser(Node); 900 return; 901 case isl_ast_node_block: 902 createBlock(Node); 903 return; 904 } 905 906 llvm_unreachable("Unknown isl_ast_node type"); 907 } 908 909 bool IslNodeBuilder::materializeValue(isl_id *Id) { 910 // If the Id is already mapped, skip it. 911 if (!IDToValue.count(Id)) { 912 auto *ParamSCEV = (const SCEV *)isl_id_get_user(Id); 913 Value *V = nullptr; 914 915 // Parameters could refere to invariant loads that need to be 916 // preloaded before we can generate code for the parameter. Thus, 917 // check if any value refered to in ParamSCEV is an invariant load 918 // and if so make sure its equivalence class is preloaded. 919 SetVector<Value *> Values; 920 findValues(ParamSCEV, SE, Values); 921 for (auto *Val : Values) { 922 923 // Check if the value is an instruction in a dead block within the SCoP 924 // and if so do not code generate it. 925 if (auto *Inst = dyn_cast<Instruction>(Val)) { 926 if (S.contains(Inst)) { 927 bool IsDead = true; 928 929 // Check for "undef" loads first, then if there is a statement for 930 // the parent of Inst and lastly if the parent of Inst has an empty 931 // domain. In the first and last case the instruction is dead but if 932 // there is a statement or the domain is not empty Inst is not dead. 933 auto MemInst = MemAccInst::dyn_cast(Inst); 934 auto Address = MemInst ? MemInst.getPointerOperand() : nullptr; 935 if (Address && SE.getUnknown(UndefValue::get(Address->getType())) == 936 SE.getPointerBase(SE.getSCEV(Address))) { 937 } else if (S.getStmtFor(Inst)) { 938 IsDead = false; 939 } else { 940 auto *Domain = S.getDomainConditions(Inst->getParent()); 941 IsDead = isl_set_is_empty(Domain); 942 isl_set_free(Domain); 943 } 944 945 if (IsDead) { 946 V = UndefValue::get(ParamSCEV->getType()); 947 break; 948 } 949 } 950 } 951 952 if (auto *IAClass = S.lookupInvariantEquivClass(Val)) { 953 954 // Check if this invariant access class is empty, hence if we never 955 // actually added a loads instruction to it. In that case it has no 956 // (meaningful) users and we should not try to code generate it. 957 if (IAClass->InvariantAccesses.empty()) 958 V = UndefValue::get(ParamSCEV->getType()); 959 960 if (!preloadInvariantEquivClass(*IAClass)) { 961 isl_id_free(Id); 962 return false; 963 } 964 } 965 } 966 967 V = V ? V : generateSCEV(ParamSCEV); 968 IDToValue[Id] = V; 969 } 970 971 isl_id_free(Id); 972 return true; 973 } 974 975 bool IslNodeBuilder::materializeParameters(isl_set *Set, bool All) { 976 for (unsigned i = 0, e = isl_set_dim(Set, isl_dim_param); i < e; ++i) { 977 if (!All && !isl_set_involves_dims(Set, isl_dim_param, i, 1)) 978 continue; 979 isl_id *Id = isl_set_get_dim_id(Set, isl_dim_param, i); 980 if (!materializeValue(Id)) 981 return false; 982 } 983 return true; 984 } 985 986 /// Add the number of dimensions in @p BS to @p U. 987 static isl_stat countTotalDims(__isl_take isl_basic_set *BS, void *U) { 988 unsigned *NumTotalDim = static_cast<unsigned *>(U); 989 *NumTotalDim += isl_basic_set_total_dim(BS); 990 isl_basic_set_free(BS); 991 return isl_stat_ok; 992 } 993 994 Value *IslNodeBuilder::preloadUnconditionally(isl_set *AccessRange, 995 isl_ast_build *Build, 996 Instruction *AccInst) { 997 998 // TODO: This check could be performed in the ScopInfo already. 999 unsigned NumTotalDim = 0; 1000 isl_set_foreach_basic_set(AccessRange, countTotalDims, &NumTotalDim); 1001 if (NumTotalDim > MaxDimensionsInAccessRange) { 1002 isl_set_free(AccessRange); 1003 return nullptr; 1004 } 1005 1006 isl_pw_multi_aff *PWAccRel = isl_pw_multi_aff_from_set(AccessRange); 1007 isl_ast_expr *Access = 1008 isl_ast_build_access_from_pw_multi_aff(Build, PWAccRel); 1009 auto *Address = isl_ast_expr_address_of(Access); 1010 auto *AddressValue = ExprBuilder.create(Address); 1011 Value *PreloadVal; 1012 1013 // Correct the type as the SAI might have a different type than the user 1014 // expects, especially if the base pointer is a struct. 1015 Type *Ty = AccInst->getType(); 1016 1017 auto *Ptr = AddressValue; 1018 auto Name = Ptr->getName(); 1019 Ptr = Builder.CreatePointerCast(Ptr, Ty->getPointerTo(), Name + ".cast"); 1020 PreloadVal = Builder.CreateLoad(Ptr, Name + ".load"); 1021 if (LoadInst *PreloadInst = dyn_cast<LoadInst>(PreloadVal)) 1022 PreloadInst->setAlignment(dyn_cast<LoadInst>(AccInst)->getAlignment()); 1023 1024 // TODO: This is only a hot fix for SCoP sequences that use the same load 1025 // instruction contained and hoisted by one of the SCoPs. 1026 if (SE.isSCEVable(Ty)) 1027 SE.forgetValue(AccInst); 1028 1029 return PreloadVal; 1030 } 1031 1032 Value *IslNodeBuilder::preloadInvariantLoad(const MemoryAccess &MA, 1033 isl_set *Domain) { 1034 1035 isl_set *AccessRange = isl_map_range(MA.getAddressFunction()); 1036 AccessRange = isl_set_gist_params(AccessRange, S.getContext()); 1037 1038 if (!materializeParameters(AccessRange, false)) { 1039 isl_set_free(AccessRange); 1040 isl_set_free(Domain); 1041 return nullptr; 1042 } 1043 1044 auto *Build = isl_ast_build_from_context(isl_set_universe(S.getParamSpace())); 1045 isl_set *Universe = isl_set_universe(isl_set_get_space(Domain)); 1046 bool AlwaysExecuted = isl_set_is_equal(Domain, Universe); 1047 isl_set_free(Universe); 1048 1049 Instruction *AccInst = MA.getAccessInstruction(); 1050 Type *AccInstTy = AccInst->getType(); 1051 1052 Value *PreloadVal = nullptr; 1053 if (AlwaysExecuted) { 1054 PreloadVal = preloadUnconditionally(AccessRange, Build, AccInst); 1055 isl_ast_build_free(Build); 1056 isl_set_free(Domain); 1057 return PreloadVal; 1058 } 1059 1060 if (!materializeParameters(Domain, false)) { 1061 isl_ast_build_free(Build); 1062 isl_set_free(AccessRange); 1063 isl_set_free(Domain); 1064 return nullptr; 1065 } 1066 1067 isl_ast_expr *DomainCond = isl_ast_build_expr_from_set(Build, Domain); 1068 Domain = nullptr; 1069 1070 ExprBuilder.setTrackOverflow(true); 1071 Value *Cond = ExprBuilder.create(DomainCond); 1072 Value *OverflowHappened = Builder.CreateNot(ExprBuilder.getOverflowState(), 1073 "polly.preload.cond.overflown"); 1074 Cond = Builder.CreateAnd(Cond, OverflowHappened, "polly.preload.cond.result"); 1075 ExprBuilder.setTrackOverflow(false); 1076 1077 if (!Cond->getType()->isIntegerTy(1)) 1078 Cond = Builder.CreateIsNotNull(Cond); 1079 1080 BasicBlock *CondBB = SplitBlock(Builder.GetInsertBlock(), 1081 &*Builder.GetInsertPoint(), &DT, &LI); 1082 CondBB->setName("polly.preload.cond"); 1083 1084 BasicBlock *MergeBB = SplitBlock(CondBB, &CondBB->front(), &DT, &LI); 1085 MergeBB->setName("polly.preload.merge"); 1086 1087 Function *F = Builder.GetInsertBlock()->getParent(); 1088 LLVMContext &Context = F->getContext(); 1089 BasicBlock *ExecBB = BasicBlock::Create(Context, "polly.preload.exec", F); 1090 1091 DT.addNewBlock(ExecBB, CondBB); 1092 if (Loop *L = LI.getLoopFor(CondBB)) 1093 L->addBasicBlockToLoop(ExecBB, LI); 1094 1095 auto *CondBBTerminator = CondBB->getTerminator(); 1096 Builder.SetInsertPoint(CondBBTerminator); 1097 Builder.CreateCondBr(Cond, ExecBB, MergeBB); 1098 CondBBTerminator->eraseFromParent(); 1099 1100 Builder.SetInsertPoint(ExecBB); 1101 Builder.CreateBr(MergeBB); 1102 1103 Builder.SetInsertPoint(ExecBB->getTerminator()); 1104 Value *PreAccInst = preloadUnconditionally(AccessRange, Build, AccInst); 1105 Builder.SetInsertPoint(MergeBB->getTerminator()); 1106 auto *MergePHI = Builder.CreatePHI( 1107 AccInstTy, 2, "polly.preload." + AccInst->getName() + ".merge"); 1108 PreloadVal = MergePHI; 1109 1110 if (!PreAccInst) { 1111 PreloadVal = nullptr; 1112 PreAccInst = UndefValue::get(AccInstTy); 1113 } 1114 1115 MergePHI->addIncoming(PreAccInst, ExecBB); 1116 MergePHI->addIncoming(Constant::getNullValue(AccInstTy), CondBB); 1117 1118 isl_ast_build_free(Build); 1119 return PreloadVal; 1120 } 1121 1122 bool IslNodeBuilder::preloadInvariantEquivClass( 1123 InvariantEquivClassTy &IAClass) { 1124 // For an equivalence class of invariant loads we pre-load the representing 1125 // element with the unified execution context. However, we have to map all 1126 // elements of the class to the one preloaded load as they are referenced 1127 // during the code generation and therefor need to be mapped. 1128 const MemoryAccessList &MAs = IAClass.InvariantAccesses; 1129 if (MAs.empty()) 1130 return true; 1131 1132 MemoryAccess *MA = MAs.front(); 1133 assert(MA->isArrayKind() && MA->isRead()); 1134 1135 // If the access function was already mapped, the preload of this equivalence 1136 // class was triggered earlier already and doesn't need to be done again. 1137 if (ValueMap.count(MA->getAccessInstruction())) 1138 return true; 1139 1140 // Check for recursion which can be caused by additional constraints, e.g., 1141 // non-finite loop constraints. In such a case we have to bail out and insert 1142 // a "false" runtime check that will cause the original code to be executed. 1143 auto PtrId = std::make_pair(IAClass.IdentifyingPointer, IAClass.AccessType); 1144 if (!PreloadedPtrs.insert(PtrId).second) 1145 return false; 1146 1147 // The execution context of the IAClass. 1148 isl_set *&ExecutionCtx = IAClass.ExecutionContext; 1149 1150 // If the base pointer of this class is dependent on another one we have to 1151 // make sure it was preloaded already. 1152 auto *SAI = MA->getScopArrayInfo(); 1153 if (auto *BaseIAClass = S.lookupInvariantEquivClass(SAI->getBasePtr())) { 1154 if (!preloadInvariantEquivClass(*BaseIAClass)) 1155 return false; 1156 1157 // After we preloaded the BaseIAClass we adjusted the BaseExecutionCtx and 1158 // we need to refine the ExecutionCtx. 1159 isl_set *BaseExecutionCtx = isl_set_copy(BaseIAClass->ExecutionContext); 1160 ExecutionCtx = isl_set_intersect(ExecutionCtx, BaseExecutionCtx); 1161 } 1162 1163 // If the size of a dimension is dependent on another class, make sure it is 1164 // preloaded. 1165 for (unsigned i = 1, e = SAI->getNumberOfDimensions(); i < e; ++i) { 1166 const SCEV *Dim = SAI->getDimensionSize(i); 1167 SetVector<Value *> Values; 1168 findValues(Dim, SE, Values); 1169 for (auto *Val : Values) { 1170 if (auto *BaseIAClass = S.lookupInvariantEquivClass(Val)) { 1171 if (!preloadInvariantEquivClass(*BaseIAClass)) 1172 return false; 1173 1174 // After we preloaded the BaseIAClass we adjusted the BaseExecutionCtx 1175 // and we need to refine the ExecutionCtx. 1176 isl_set *BaseExecutionCtx = isl_set_copy(BaseIAClass->ExecutionContext); 1177 ExecutionCtx = isl_set_intersect(ExecutionCtx, BaseExecutionCtx); 1178 } 1179 } 1180 } 1181 1182 Instruction *AccInst = MA->getAccessInstruction(); 1183 Type *AccInstTy = AccInst->getType(); 1184 1185 Value *PreloadVal = preloadInvariantLoad(*MA, isl_set_copy(ExecutionCtx)); 1186 if (!PreloadVal) 1187 return false; 1188 1189 for (const MemoryAccess *MA : MAs) { 1190 Instruction *MAAccInst = MA->getAccessInstruction(); 1191 assert(PreloadVal->getType() == MAAccInst->getType()); 1192 ValueMap[MAAccInst] = PreloadVal; 1193 } 1194 1195 if (SE.isSCEVable(AccInstTy)) { 1196 isl_id *ParamId = S.getIdForParam(SE.getSCEV(AccInst)); 1197 if (ParamId) 1198 IDToValue[ParamId] = PreloadVal; 1199 isl_id_free(ParamId); 1200 } 1201 1202 BasicBlock *EntryBB = &Builder.GetInsertBlock()->getParent()->getEntryBlock(); 1203 auto *Alloca = new AllocaInst(AccInstTy, AccInst->getName() + ".preload.s2a"); 1204 Alloca->insertBefore(&*EntryBB->getFirstInsertionPt()); 1205 Builder.CreateStore(PreloadVal, Alloca); 1206 1207 for (auto *DerivedSAI : SAI->getDerivedSAIs()) { 1208 Value *BasePtr = DerivedSAI->getBasePtr(); 1209 1210 for (const MemoryAccess *MA : MAs) { 1211 // As the derived SAI information is quite coarse, any load from the 1212 // current SAI could be the base pointer of the derived SAI, however we 1213 // should only change the base pointer of the derived SAI if we actually 1214 // preloaded it. 1215 if (BasePtr == MA->getBaseAddr()) { 1216 assert(BasePtr->getType() == PreloadVal->getType()); 1217 DerivedSAI->setBasePtr(PreloadVal); 1218 } 1219 1220 // For scalar derived SAIs we remap the alloca used for the derived value. 1221 if (BasePtr == MA->getAccessInstruction()) 1222 ScalarMap[DerivedSAI] = Alloca; 1223 } 1224 } 1225 1226 for (const MemoryAccess *MA : MAs) { 1227 1228 Instruction *MAAccInst = MA->getAccessInstruction(); 1229 // Use the escape system to get the correct value to users outside the SCoP. 1230 BlockGenerator::EscapeUserVectorTy EscapeUsers; 1231 for (auto *U : MAAccInst->users()) 1232 if (Instruction *UI = dyn_cast<Instruction>(U)) 1233 if (!S.contains(UI)) 1234 EscapeUsers.push_back(UI); 1235 1236 if (EscapeUsers.empty()) 1237 continue; 1238 1239 EscapeMap[MA->getAccessInstruction()] = 1240 std::make_pair(Alloca, std::move(EscapeUsers)); 1241 } 1242 1243 return true; 1244 } 1245 1246 void IslNodeBuilder::allocateNewArrays() { 1247 for (auto &SAI : S.arrays()) { 1248 if (SAI->getBasePtr()) 1249 continue; 1250 1251 assert(SAI->getNumberOfDimensions() > 0 && SAI->getDimensionSize(0) && 1252 "The size of the outermost dimension is used to declare newly " 1253 "created arrays that require memory allocation."); 1254 1255 Type *NewArrayType = nullptr; 1256 for (int i = SAI->getNumberOfDimensions() - 1; i >= 0; i--) { 1257 auto *DimSize = SAI->getDimensionSize(i); 1258 unsigned UnsignedDimSize = static_cast<const SCEVConstant *>(DimSize) 1259 ->getAPInt() 1260 .getLimitedValue(); 1261 1262 if (!NewArrayType) 1263 NewArrayType = SAI->getElementType(); 1264 1265 NewArrayType = ArrayType::get(NewArrayType, UnsignedDimSize); 1266 } 1267 1268 auto InstIt = 1269 Builder.GetInsertBlock()->getParent()->getEntryBlock().getTerminator(); 1270 auto *CreatedArray = new AllocaInst(NewArrayType, SAI->getName(), &*InstIt); 1271 CreatedArray->setAlignment(PollyTargetFirstLevelCacheLineSize); 1272 SAI->setBasePtr(CreatedArray); 1273 } 1274 } 1275 1276 bool IslNodeBuilder::preloadInvariantLoads() { 1277 1278 auto &InvariantEquivClasses = S.getInvariantAccesses(); 1279 if (InvariantEquivClasses.empty()) 1280 return true; 1281 1282 BasicBlock *PreLoadBB = SplitBlock(Builder.GetInsertBlock(), 1283 &*Builder.GetInsertPoint(), &DT, &LI); 1284 PreLoadBB->setName("polly.preload.begin"); 1285 Builder.SetInsertPoint(&PreLoadBB->front()); 1286 1287 for (auto &IAClass : InvariantEquivClasses) 1288 if (!preloadInvariantEquivClass(IAClass)) 1289 return false; 1290 1291 return true; 1292 } 1293 1294 void IslNodeBuilder::addParameters(__isl_take isl_set *Context) { 1295 1296 // Materialize values for the parameters of the SCoP. 1297 materializeParameters(Context, /* all */ true); 1298 1299 // Generate values for the current loop iteration for all surrounding loops. 1300 // 1301 // We may also reference loops outside of the scop which do not contain the 1302 // scop itself, but as the number of such scops may be arbitrarily large we do 1303 // not generate code for them here, but only at the point of code generation 1304 // where these values are needed. 1305 Loop *L = LI.getLoopFor(S.getEntry()); 1306 1307 while (L != nullptr && S.contains(L)) 1308 L = L->getParentLoop(); 1309 1310 while (L != nullptr) { 1311 const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)), 1312 SE.getUnknown(Builder.getInt64(1)), 1313 L, SCEV::FlagAnyWrap); 1314 Value *V = generateSCEV(OuterLIV); 1315 OutsideLoopIterations[L] = SE.getUnknown(V); 1316 L = L->getParentLoop(); 1317 } 1318 1319 isl_set_free(Context); 1320 } 1321 1322 Value *IslNodeBuilder::generateSCEV(const SCEV *Expr) { 1323 /// We pass the insert location of our Builder, as Polly ensures during IR 1324 /// generation that there is always a valid CFG into which instructions are 1325 /// inserted. As a result, the insertpoint is known to be always followed by a 1326 /// terminator instruction. This means the insert point may be specified by a 1327 /// terminator instruction, but it can never point to an ->end() iterator 1328 /// which does not have a corresponding instruction. Hence, dereferencing 1329 /// the insertpoint to obtain an instruction is known to be save. 1330 /// 1331 /// We also do not need to update the Builder here, as new instructions are 1332 /// always inserted _before_ the given InsertLocation. As a result, the 1333 /// insert location remains valid. 1334 assert(Builder.GetInsertBlock()->end() != Builder.GetInsertPoint() && 1335 "Insert location points after last valid instruction"); 1336 Instruction *InsertLocation = &*Builder.GetInsertPoint(); 1337 return expandCodeFor(S, SE, DL, "polly", Expr, Expr->getType(), 1338 InsertLocation, &ValueMap, 1339 StartBlock->getSinglePredecessor()); 1340 } 1341 1342 /// The AST expression we generate to perform the run-time check assumes 1343 /// computations on integer types of infinite size. As we only use 64-bit 1344 /// arithmetic we check for overflows, in case of which we set the result 1345 /// of this run-time check to false to be cosnservatively correct, 1346 Value *IslNodeBuilder::createRTC(isl_ast_expr *Condition) { 1347 auto ExprBuilder = getExprBuilder(); 1348 ExprBuilder.setTrackOverflow(true); 1349 Value *RTC = ExprBuilder.create(Condition); 1350 if (!RTC->getType()->isIntegerTy(1)) 1351 RTC = Builder.CreateIsNotNull(RTC); 1352 Value *OverflowHappened = 1353 Builder.CreateNot(ExprBuilder.getOverflowState(), "polly.rtc.overflown"); 1354 1355 if (PollyGenerateRTCPrint) { 1356 auto *F = Builder.GetInsertBlock()->getParent(); 1357 RuntimeDebugBuilder::createCPUPrinter( 1358 Builder, 1359 "F: " + F->getName().str() + " R: " + S.getRegion().getNameStr() + 1360 " __RTC: ", 1361 RTC, " Overflow: ", OverflowHappened, "\n"); 1362 } 1363 1364 RTC = Builder.CreateAnd(RTC, OverflowHappened, "polly.rtc.result"); 1365 ExprBuilder.setTrackOverflow(false); 1366 1367 if (!isa<ConstantInt>(RTC)) 1368 VersionedScops++; 1369 1370 return RTC; 1371 } 1372