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