1 //===--- BlockGenerators.cpp - Generate code for statements -----*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the BlockGenerator and VectorBlockGenerator classes, 10 // which generate sequential code and vectorized code for a polyhedral 11 // statement, respectively. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "polly/CodeGen/BlockGenerators.h" 16 #include "polly/CodeGen/IslExprBuilder.h" 17 #include "polly/CodeGen/RuntimeDebugBuilder.h" 18 #include "polly/Options.h" 19 #include "polly/ScopInfo.h" 20 #include "polly/Support/ISLTools.h" 21 #include "polly/Support/ScopHelper.h" 22 #include "polly/Support/VirtualInstruction.h" 23 #include "llvm/Analysis/LoopInfo.h" 24 #include "llvm/Analysis/RegionInfo.h" 25 #include "llvm/Analysis/ScalarEvolution.h" 26 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 27 #include "llvm/Transforms/Utils/Local.h" 28 #include "isl/ast.h" 29 #include <deque> 30 31 using namespace llvm; 32 using namespace polly; 33 34 static cl::opt<bool> Aligned("enable-polly-aligned", 35 cl::desc("Assumed aligned memory accesses."), 36 cl::Hidden, cl::cat(PollyCategory)); 37 38 bool PollyDebugPrinting; 39 static cl::opt<bool, true> DebugPrintingX( 40 "polly-codegen-add-debug-printing", 41 cl::desc("Add printf calls that show the values loaded/stored."), 42 cl::location(PollyDebugPrinting), cl::Hidden, cl::init(false), 43 cl::ZeroOrMore, cl::cat(PollyCategory)); 44 45 static cl::opt<bool> TraceStmts( 46 "polly-codegen-trace-stmts", 47 cl::desc("Add printf calls that print the statement being executed"), 48 cl::Hidden, cl::cat(PollyCategory)); 49 50 static cl::opt<bool> TraceScalars( 51 "polly-codegen-trace-scalars", 52 cl::desc("Add printf calls that print the values of all scalar values " 53 "used in a statement. Requires -polly-codegen-trace-stmts."), 54 cl::Hidden, cl::cat(PollyCategory)); 55 56 BlockGenerator::BlockGenerator( 57 PollyIRBuilder &B, LoopInfo &LI, ScalarEvolution &SE, DominatorTree &DT, 58 AllocaMapTy &ScalarMap, EscapeUsersAllocaMapTy &EscapeMap, 59 ValueMapT &GlobalMap, IslExprBuilder *ExprBuilder, BasicBlock *StartBlock) 60 : Builder(B), LI(LI), SE(SE), ExprBuilder(ExprBuilder), DT(DT), 61 EntryBB(nullptr), ScalarMap(ScalarMap), EscapeMap(EscapeMap), 62 GlobalMap(GlobalMap), StartBlock(StartBlock) {} 63 64 Value *BlockGenerator::trySynthesizeNewValue(ScopStmt &Stmt, Value *Old, 65 ValueMapT &BBMap, 66 LoopToScevMapT <S, 67 Loop *L) const { 68 if (!SE.isSCEVable(Old->getType())) 69 return nullptr; 70 71 const SCEV *Scev = SE.getSCEVAtScope(Old, L); 72 if (!Scev) 73 return nullptr; 74 75 if (isa<SCEVCouldNotCompute>(Scev)) 76 return nullptr; 77 78 const SCEV *NewScev = SCEVLoopAddRecRewriter::rewrite(Scev, LTS, SE); 79 ValueMapT VTV; 80 VTV.insert(BBMap.begin(), BBMap.end()); 81 VTV.insert(GlobalMap.begin(), GlobalMap.end()); 82 83 Scop &S = *Stmt.getParent(); 84 const DataLayout &DL = S.getFunction().getParent()->getDataLayout(); 85 auto IP = Builder.GetInsertPoint(); 86 87 assert(IP != Builder.GetInsertBlock()->end() && 88 "Only instructions can be insert points for SCEVExpander"); 89 Value *Expanded = 90 expandCodeFor(S, SE, DL, "polly", NewScev, Old->getType(), &*IP, &VTV, 91 StartBlock->getSinglePredecessor()); 92 93 BBMap[Old] = Expanded; 94 return Expanded; 95 } 96 97 Value *BlockGenerator::getNewValue(ScopStmt &Stmt, Value *Old, ValueMapT &BBMap, 98 LoopToScevMapT <S, Loop *L) const { 99 100 auto lookupGlobally = [this](Value *Old) -> Value * { 101 Value *New = GlobalMap.lookup(Old); 102 if (!New) 103 return nullptr; 104 105 // Required by: 106 // * Isl/CodeGen/OpenMP/invariant_base_pointer_preloaded.ll 107 // * Isl/CodeGen/OpenMP/invariant_base_pointer_preloaded_different_bb.ll 108 // * Isl/CodeGen/OpenMP/invariant_base_pointer_preloaded_pass_only_needed.ll 109 // * Isl/CodeGen/OpenMP/invariant_base_pointers_preloaded.ll 110 // * Isl/CodeGen/OpenMP/loop-body-references-outer-values-3.ll 111 // * Isl/CodeGen/OpenMP/single_loop_with_loop_invariant_baseptr.ll 112 // GlobalMap should be a mapping from (value in original SCoP) to (copied 113 // value in generated SCoP), without intermediate mappings, which might 114 // easily require transitiveness as well. 115 if (Value *NewRemapped = GlobalMap.lookup(New)) 116 New = NewRemapped; 117 118 // No test case for this code. 119 if (Old->getType()->getScalarSizeInBits() < 120 New->getType()->getScalarSizeInBits()) 121 New = Builder.CreateTruncOrBitCast(New, Old->getType()); 122 123 return New; 124 }; 125 126 Value *New = nullptr; 127 auto VUse = VirtualUse::create(&Stmt, L, Old, true); 128 switch (VUse.getKind()) { 129 case VirtualUse::Block: 130 // BasicBlock are constants, but the BlockGenerator copies them. 131 New = BBMap.lookup(Old); 132 break; 133 134 case VirtualUse::Constant: 135 // Used by: 136 // * Isl/CodeGen/OpenMP/reference-argument-from-non-affine-region.ll 137 // Constants should not be redefined. In this case, the GlobalMap just 138 // contains a mapping to the same constant, which is unnecessary, but 139 // harmless. 140 if ((New = lookupGlobally(Old))) 141 break; 142 143 assert(!BBMap.count(Old)); 144 New = Old; 145 break; 146 147 case VirtualUse::ReadOnly: 148 assert(!GlobalMap.count(Old)); 149 150 // Required for: 151 // * Isl/CodeGen/MemAccess/create_arrays.ll 152 // * Isl/CodeGen/read-only-scalars.ll 153 // * ScheduleOptimizer/pattern-matching-based-opts_10.ll 154 // For some reason these reload a read-only value. The reloaded value ends 155 // up in BBMap, buts its value should be identical. 156 // 157 // Required for: 158 // * Isl/CodeGen/OpenMP/single_loop_with_param.ll 159 // The parallel subfunctions need to reference the read-only value from the 160 // parent function, this is done by reloading them locally. 161 if ((New = BBMap.lookup(Old))) 162 break; 163 164 New = Old; 165 break; 166 167 case VirtualUse::Synthesizable: 168 // Used by: 169 // * Isl/CodeGen/OpenMP/loop-body-references-outer-values-3.ll 170 // * Isl/CodeGen/OpenMP/recomputed-srem.ll 171 // * Isl/CodeGen/OpenMP/reference-other-bb.ll 172 // * Isl/CodeGen/OpenMP/two-parallel-loops-reference-outer-indvar.ll 173 // For some reason synthesizable values end up in GlobalMap. Their values 174 // are the same as trySynthesizeNewValue would return. The legacy 175 // implementation prioritized GlobalMap, so this is what we do here as well. 176 // Ideally, synthesizable values should not end up in GlobalMap. 177 if ((New = lookupGlobally(Old))) 178 break; 179 180 // Required for: 181 // * Isl/CodeGen/RuntimeDebugBuilder/combine_different_values.ll 182 // * Isl/CodeGen/getNumberOfIterations.ll 183 // * Isl/CodeGen/non_affine_float_compare.ll 184 // * ScheduleOptimizer/pattern-matching-based-opts_10.ll 185 // Ideally, synthesizable values are synthesized by trySynthesizeNewValue, 186 // not precomputed (SCEVExpander has its own caching mechanism). 187 // These tests fail without this, but I think trySynthesizeNewValue would 188 // just re-synthesize the same instructions. 189 if ((New = BBMap.lookup(Old))) 190 break; 191 192 New = trySynthesizeNewValue(Stmt, Old, BBMap, LTS, L); 193 break; 194 195 case VirtualUse::Hoisted: 196 // TODO: Hoisted invariant loads should be found in GlobalMap only, but not 197 // redefined locally (which will be ignored anyway). That is, the following 198 // assertion should apply: assert(!BBMap.count(Old)) 199 200 New = lookupGlobally(Old); 201 break; 202 203 case VirtualUse::Intra: 204 case VirtualUse::Inter: 205 assert(!GlobalMap.count(Old) && 206 "Intra and inter-stmt values are never global"); 207 New = BBMap.lookup(Old); 208 break; 209 } 210 assert(New && "Unexpected scalar dependence in region!"); 211 return New; 212 } 213 214 void BlockGenerator::copyInstScalar(ScopStmt &Stmt, Instruction *Inst, 215 ValueMapT &BBMap, LoopToScevMapT <S) { 216 // We do not generate debug intrinsics as we did not investigate how to 217 // copy them correctly. At the current state, they just crash the code 218 // generation as the meta-data operands are not correctly copied. 219 if (isa<DbgInfoIntrinsic>(Inst)) 220 return; 221 222 Instruction *NewInst = Inst->clone(); 223 224 // Replace old operands with the new ones. 225 for (Value *OldOperand : Inst->operands()) { 226 Value *NewOperand = 227 getNewValue(Stmt, OldOperand, BBMap, LTS, getLoopForStmt(Stmt)); 228 229 if (!NewOperand) { 230 assert(!isa<StoreInst>(NewInst) && 231 "Store instructions are always needed!"); 232 NewInst->deleteValue(); 233 return; 234 } 235 236 NewInst->replaceUsesOfWith(OldOperand, NewOperand); 237 } 238 239 Builder.Insert(NewInst); 240 BBMap[Inst] = NewInst; 241 242 // When copying the instruction onto the Module meant for the GPU, 243 // debug metadata attached to an instruction causes all related 244 // metadata to be pulled into the Module. This includes the DICompileUnit, 245 // which will not be listed in llvm.dbg.cu of the Module since the Module 246 // doesn't contain one. This fails the verification of the Module and the 247 // subsequent generation of the ASM string. 248 if (NewInst->getModule() != Inst->getModule()) 249 NewInst->setDebugLoc(llvm::DebugLoc()); 250 251 if (!NewInst->getType()->isVoidTy()) 252 NewInst->setName("p_" + Inst->getName()); 253 } 254 255 Value * 256 BlockGenerator::generateLocationAccessed(ScopStmt &Stmt, MemAccInst Inst, 257 ValueMapT &BBMap, LoopToScevMapT <S, 258 isl_id_to_ast_expr *NewAccesses) { 259 const MemoryAccess &MA = Stmt.getArrayAccessFor(Inst); 260 return generateLocationAccessed( 261 Stmt, getLoopForStmt(Stmt), 262 Inst.isNull() ? nullptr : Inst.getPointerOperand(), BBMap, LTS, 263 NewAccesses, MA.getId().release(), MA.getAccessValue()->getType()); 264 } 265 266 Value *BlockGenerator::generateLocationAccessed( 267 ScopStmt &Stmt, Loop *L, Value *Pointer, ValueMapT &BBMap, 268 LoopToScevMapT <S, isl_id_to_ast_expr *NewAccesses, __isl_take isl_id *Id, 269 Type *ExpectedType) { 270 isl_ast_expr *AccessExpr = isl_id_to_ast_expr_get(NewAccesses, Id); 271 272 if (AccessExpr) { 273 AccessExpr = isl_ast_expr_address_of(AccessExpr); 274 auto Address = ExprBuilder->create(AccessExpr); 275 276 // Cast the address of this memory access to a pointer type that has the 277 // same element type as the original access, but uses the address space of 278 // the newly generated pointer. 279 auto OldPtrTy = ExpectedType->getPointerTo(); 280 auto NewPtrTy = Address->getType(); 281 OldPtrTy = PointerType::getWithSamePointeeType( 282 OldPtrTy, NewPtrTy->getPointerAddressSpace()); 283 284 if (OldPtrTy != NewPtrTy) 285 Address = Builder.CreateBitOrPointerCast(Address, OldPtrTy); 286 return Address; 287 } 288 assert( 289 Pointer && 290 "If expression was not generated, must use the original pointer value"); 291 return getNewValue(Stmt, Pointer, BBMap, LTS, L); 292 } 293 294 Value * 295 BlockGenerator::getImplicitAddress(MemoryAccess &Access, Loop *L, 296 LoopToScevMapT <S, ValueMapT &BBMap, 297 __isl_keep isl_id_to_ast_expr *NewAccesses) { 298 if (Access.isLatestArrayKind()) 299 return generateLocationAccessed(*Access.getStatement(), L, nullptr, BBMap, 300 LTS, NewAccesses, Access.getId().release(), 301 Access.getAccessValue()->getType()); 302 303 return getOrCreateAlloca(Access); 304 } 305 306 Loop *BlockGenerator::getLoopForStmt(const ScopStmt &Stmt) const { 307 auto *StmtBB = Stmt.getEntryBlock(); 308 return LI.getLoopFor(StmtBB); 309 } 310 311 Value *BlockGenerator::generateArrayLoad(ScopStmt &Stmt, LoadInst *Load, 312 ValueMapT &BBMap, LoopToScevMapT <S, 313 isl_id_to_ast_expr *NewAccesses) { 314 if (Value *PreloadLoad = GlobalMap.lookup(Load)) 315 return PreloadLoad; 316 317 Value *NewPointer = 318 generateLocationAccessed(Stmt, Load, BBMap, LTS, NewAccesses); 319 Value *ScalarLoad = 320 Builder.CreateAlignedLoad(Load->getType(), NewPointer, Load->getAlign(), 321 Load->getName() + "_p_scalar_"); 322 323 if (PollyDebugPrinting) 324 RuntimeDebugBuilder::createCPUPrinter(Builder, "Load from ", NewPointer, 325 ": ", ScalarLoad, "\n"); 326 327 return ScalarLoad; 328 } 329 330 void BlockGenerator::generateArrayStore(ScopStmt &Stmt, StoreInst *Store, 331 ValueMapT &BBMap, LoopToScevMapT <S, 332 isl_id_to_ast_expr *NewAccesses) { 333 MemoryAccess &MA = Stmt.getArrayAccessFor(Store); 334 isl::set AccDom = MA.getAccessRelation().domain(); 335 std::string Subject = MA.getId().get_name(); 336 337 generateConditionalExecution(Stmt, AccDom, Subject.c_str(), [&, this]() { 338 Value *NewPointer = 339 generateLocationAccessed(Stmt, Store, BBMap, LTS, NewAccesses); 340 Value *ValueOperand = getNewValue(Stmt, Store->getValueOperand(), BBMap, 341 LTS, getLoopForStmt(Stmt)); 342 343 if (PollyDebugPrinting) 344 RuntimeDebugBuilder::createCPUPrinter(Builder, "Store to ", NewPointer, 345 ": ", ValueOperand, "\n"); 346 347 Builder.CreateAlignedStore(ValueOperand, NewPointer, Store->getAlign()); 348 }); 349 } 350 351 bool BlockGenerator::canSyntheziseInStmt(ScopStmt &Stmt, Instruction *Inst) { 352 Loop *L = getLoopForStmt(Stmt); 353 return (Stmt.isBlockStmt() || !Stmt.getRegion()->contains(L)) && 354 canSynthesize(Inst, *Stmt.getParent(), &SE, L); 355 } 356 357 void BlockGenerator::copyInstruction(ScopStmt &Stmt, Instruction *Inst, 358 ValueMapT &BBMap, LoopToScevMapT <S, 359 isl_id_to_ast_expr *NewAccesses) { 360 // Terminator instructions control the control flow. They are explicitly 361 // expressed in the clast and do not need to be copied. 362 if (Inst->isTerminator()) 363 return; 364 365 // Synthesizable statements will be generated on-demand. 366 if (canSyntheziseInStmt(Stmt, Inst)) 367 return; 368 369 if (auto *Load = dyn_cast<LoadInst>(Inst)) { 370 Value *NewLoad = generateArrayLoad(Stmt, Load, BBMap, LTS, NewAccesses); 371 // Compute NewLoad before its insertion in BBMap to make the insertion 372 // deterministic. 373 BBMap[Load] = NewLoad; 374 return; 375 } 376 377 if (auto *Store = dyn_cast<StoreInst>(Inst)) { 378 // Identified as redundant by -polly-simplify. 379 if (!Stmt.getArrayAccessOrNULLFor(Store)) 380 return; 381 382 generateArrayStore(Stmt, Store, BBMap, LTS, NewAccesses); 383 return; 384 } 385 386 if (auto *PHI = dyn_cast<PHINode>(Inst)) { 387 copyPHIInstruction(Stmt, PHI, BBMap, LTS); 388 return; 389 } 390 391 // Skip some special intrinsics for which we do not adjust the semantics to 392 // the new schedule. All others are handled like every other instruction. 393 if (isIgnoredIntrinsic(Inst)) 394 return; 395 396 copyInstScalar(Stmt, Inst, BBMap, LTS); 397 } 398 399 void BlockGenerator::removeDeadInstructions(BasicBlock *BB, ValueMapT &BBMap) { 400 auto NewBB = Builder.GetInsertBlock(); 401 for (auto I = NewBB->rbegin(); I != NewBB->rend(); I++) { 402 Instruction *NewInst = &*I; 403 404 if (!isInstructionTriviallyDead(NewInst)) 405 continue; 406 407 for (auto Pair : BBMap) 408 if (Pair.second == NewInst) { 409 BBMap.erase(Pair.first); 410 } 411 412 NewInst->eraseFromParent(); 413 I = NewBB->rbegin(); 414 } 415 } 416 417 void BlockGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT <S, 418 __isl_keep isl_id_to_ast_expr *NewAccesses) { 419 assert(Stmt.isBlockStmt() && 420 "Only block statements can be copied by the block generator"); 421 422 ValueMapT BBMap; 423 424 BasicBlock *BB = Stmt.getBasicBlock(); 425 copyBB(Stmt, BB, BBMap, LTS, NewAccesses); 426 removeDeadInstructions(BB, BBMap); 427 } 428 429 BasicBlock *BlockGenerator::splitBB(BasicBlock *BB) { 430 BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(), 431 &*Builder.GetInsertPoint(), &DT, &LI); 432 CopyBB->setName("polly.stmt." + BB->getName()); 433 return CopyBB; 434 } 435 436 BasicBlock *BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB, 437 ValueMapT &BBMap, LoopToScevMapT <S, 438 isl_id_to_ast_expr *NewAccesses) { 439 BasicBlock *CopyBB = splitBB(BB); 440 Builder.SetInsertPoint(&CopyBB->front()); 441 generateScalarLoads(Stmt, LTS, BBMap, NewAccesses); 442 generateBeginStmtTrace(Stmt, LTS, BBMap); 443 444 copyBB(Stmt, BB, CopyBB, BBMap, LTS, NewAccesses); 445 446 // After a basic block was copied store all scalars that escape this block in 447 // their alloca. 448 generateScalarStores(Stmt, LTS, BBMap, NewAccesses); 449 return CopyBB; 450 } 451 452 void BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB, BasicBlock *CopyBB, 453 ValueMapT &BBMap, LoopToScevMapT <S, 454 isl_id_to_ast_expr *NewAccesses) { 455 EntryBB = &CopyBB->getParent()->getEntryBlock(); 456 457 // Block statements and the entry blocks of region statement are code 458 // generated from instruction lists. This allow us to optimize the 459 // instructions that belong to a certain scop statement. As the code 460 // structure of region statements might be arbitrary complex, optimizing the 461 // instruction list is not yet supported. 462 if (Stmt.isBlockStmt() || (Stmt.isRegionStmt() && Stmt.getEntryBlock() == BB)) 463 for (Instruction *Inst : Stmt.getInstructions()) 464 copyInstruction(Stmt, Inst, BBMap, LTS, NewAccesses); 465 else 466 for (Instruction &Inst : *BB) 467 copyInstruction(Stmt, &Inst, BBMap, LTS, NewAccesses); 468 } 469 470 Value *BlockGenerator::getOrCreateAlloca(const MemoryAccess &Access) { 471 assert(!Access.isLatestArrayKind() && "Trying to get alloca for array kind"); 472 473 return getOrCreateAlloca(Access.getLatestScopArrayInfo()); 474 } 475 476 Value *BlockGenerator::getOrCreateAlloca(const ScopArrayInfo *Array) { 477 assert(!Array->isArrayKind() && "Trying to get alloca for array kind"); 478 479 auto &Addr = ScalarMap[Array]; 480 481 if (Addr) { 482 // Allow allocas to be (temporarily) redirected once by adding a new 483 // old-alloca-addr to new-addr mapping to GlobalMap. This functionality 484 // is used for example by the OpenMP code generation where a first use 485 // of a scalar while still in the host code allocates a normal alloca with 486 // getOrCreateAlloca. When the values of this scalar are accessed during 487 // the generation of the parallel subfunction, these values are copied over 488 // to the parallel subfunction and each request for a scalar alloca slot 489 // must be forwarded to the temporary in-subfunction slot. This mapping is 490 // removed when the subfunction has been generated and again normal host 491 // code is generated. Due to the following reasons it is not possible to 492 // perform the GlobalMap lookup right after creating the alloca below, but 493 // instead we need to check GlobalMap at each call to getOrCreateAlloca: 494 // 495 // 1) GlobalMap may be changed multiple times (for each parallel loop), 496 // 2) The temporary mapping is commonly only known after the initial 497 // alloca has already been generated, and 498 // 3) The original alloca value must be restored after leaving the 499 // sub-function. 500 if (Value *NewAddr = GlobalMap.lookup(&*Addr)) 501 return NewAddr; 502 return Addr; 503 } 504 505 Type *Ty = Array->getElementType(); 506 Value *ScalarBase = Array->getBasePtr(); 507 std::string NameExt; 508 if (Array->isPHIKind()) 509 NameExt = ".phiops"; 510 else 511 NameExt = ".s2a"; 512 513 const DataLayout &DL = Builder.GetInsertBlock()->getModule()->getDataLayout(); 514 515 Addr = 516 new AllocaInst(Ty, DL.getAllocaAddrSpace(), nullptr, 517 DL.getPrefTypeAlign(Ty), ScalarBase->getName() + NameExt); 518 EntryBB = &Builder.GetInsertBlock()->getParent()->getEntryBlock(); 519 Addr->insertBefore(&*EntryBB->getFirstInsertionPt()); 520 521 return Addr; 522 } 523 524 void BlockGenerator::handleOutsideUsers(const Scop &S, ScopArrayInfo *Array) { 525 Instruction *Inst = cast<Instruction>(Array->getBasePtr()); 526 527 // If there are escape users we get the alloca for this instruction and put it 528 // in the EscapeMap for later finalization. Lastly, if the instruction was 529 // copied multiple times we already did this and can exit. 530 if (EscapeMap.count(Inst)) 531 return; 532 533 EscapeUserVectorTy EscapeUsers; 534 for (User *U : Inst->users()) { 535 536 // Non-instruction user will never escape. 537 Instruction *UI = dyn_cast<Instruction>(U); 538 if (!UI) 539 continue; 540 541 if (S.contains(UI)) 542 continue; 543 544 EscapeUsers.push_back(UI); 545 } 546 547 // Exit if no escape uses were found. 548 if (EscapeUsers.empty()) 549 return; 550 551 // Get or create an escape alloca for this instruction. 552 auto *ScalarAddr = getOrCreateAlloca(Array); 553 554 // Remember that this instruction has escape uses and the escape alloca. 555 EscapeMap[Inst] = std::make_pair(ScalarAddr, std::move(EscapeUsers)); 556 } 557 558 void BlockGenerator::generateScalarLoads( 559 ScopStmt &Stmt, LoopToScevMapT <S, ValueMapT &BBMap, 560 __isl_keep isl_id_to_ast_expr *NewAccesses) { 561 for (MemoryAccess *MA : Stmt) { 562 if (MA->isOriginalArrayKind() || MA->isWrite()) 563 continue; 564 565 #ifndef NDEBUG 566 auto StmtDom = 567 Stmt.getDomain().intersect_params(Stmt.getParent()->getContext()); 568 auto AccDom = MA->getAccessRelation().domain(); 569 assert(!StmtDom.is_subset(AccDom).is_false() && 570 "Scalar must be loaded in all statement instances"); 571 #endif 572 573 auto *Address = 574 getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS, BBMap, NewAccesses); 575 assert((!isa<Instruction>(Address) || 576 DT.dominates(cast<Instruction>(Address)->getParent(), 577 Builder.GetInsertBlock())) && 578 "Domination violation"); 579 BBMap[MA->getAccessValue()] = Builder.CreateLoad( 580 MA->getElementType(), Address, Address->getName() + ".reload"); 581 } 582 } 583 584 Value *BlockGenerator::buildContainsCondition(ScopStmt &Stmt, 585 const isl::set &Subdomain) { 586 isl::ast_build AstBuild = Stmt.getAstBuild(); 587 isl::set Domain = Stmt.getDomain(); 588 589 isl::union_map USchedule = AstBuild.get_schedule(); 590 USchedule = USchedule.intersect_domain(Domain); 591 592 assert(!USchedule.is_empty()); 593 isl::map Schedule = isl::map::from_union_map(USchedule); 594 595 isl::set ScheduledDomain = Schedule.range(); 596 isl::set ScheduledSet = Subdomain.apply(Schedule); 597 598 isl::ast_build RestrictedBuild = AstBuild.restrict(ScheduledDomain); 599 600 isl::ast_expr IsInSet = RestrictedBuild.expr_from(ScheduledSet); 601 Value *IsInSetExpr = ExprBuilder->create(IsInSet.copy()); 602 IsInSetExpr = Builder.CreateICmpNE( 603 IsInSetExpr, ConstantInt::get(IsInSetExpr->getType(), 0)); 604 605 return IsInSetExpr; 606 } 607 608 void BlockGenerator::generateConditionalExecution( 609 ScopStmt &Stmt, const isl::set &Subdomain, StringRef Subject, 610 const std::function<void()> &GenThenFunc) { 611 isl::set StmtDom = Stmt.getDomain(); 612 613 // If the condition is a tautology, don't generate a condition around the 614 // code. 615 bool IsPartialWrite = 616 !StmtDom.intersect_params(Stmt.getParent()->getContext()) 617 .is_subset(Subdomain); 618 if (!IsPartialWrite) { 619 GenThenFunc(); 620 return; 621 } 622 623 // Generate the condition. 624 Value *Cond = buildContainsCondition(Stmt, Subdomain); 625 626 // Don't call GenThenFunc if it is never executed. An ast index expression 627 // might not be defined in this case. 628 if (auto *Const = dyn_cast<ConstantInt>(Cond)) 629 if (Const->isZero()) 630 return; 631 632 BasicBlock *HeadBlock = Builder.GetInsertBlock(); 633 StringRef BlockName = HeadBlock->getName(); 634 635 // Generate the conditional block. 636 SplitBlockAndInsertIfThen(Cond, &*Builder.GetInsertPoint(), false, nullptr, 637 &DT, &LI); 638 BranchInst *Branch = cast<BranchInst>(HeadBlock->getTerminator()); 639 BasicBlock *ThenBlock = Branch->getSuccessor(0); 640 BasicBlock *TailBlock = Branch->getSuccessor(1); 641 642 // Assign descriptive names. 643 if (auto *CondInst = dyn_cast<Instruction>(Cond)) 644 CondInst->setName("polly." + Subject + ".cond"); 645 ThenBlock->setName(BlockName + "." + Subject + ".partial"); 646 TailBlock->setName(BlockName + ".cont"); 647 648 // Put the client code into the conditional block and continue in the merge 649 // block afterwards. 650 Builder.SetInsertPoint(ThenBlock, ThenBlock->getFirstInsertionPt()); 651 GenThenFunc(); 652 Builder.SetInsertPoint(TailBlock, TailBlock->getFirstInsertionPt()); 653 } 654 655 static std::string getInstName(Value *Val) { 656 std::string Result; 657 raw_string_ostream OS(Result); 658 Val->printAsOperand(OS, false); 659 return OS.str(); 660 } 661 662 void BlockGenerator::generateBeginStmtTrace(ScopStmt &Stmt, LoopToScevMapT <S, 663 ValueMapT &BBMap) { 664 if (!TraceStmts) 665 return; 666 667 Scop *S = Stmt.getParent(); 668 const char *BaseName = Stmt.getBaseName(); 669 670 isl::ast_build AstBuild = Stmt.getAstBuild(); 671 isl::set Domain = Stmt.getDomain(); 672 673 isl::union_map USchedule = AstBuild.get_schedule().intersect_domain(Domain); 674 isl::map Schedule = isl::map::from_union_map(USchedule); 675 assert(Schedule.is_empty().is_false() && 676 "The stmt must have a valid instance"); 677 678 isl::multi_pw_aff ScheduleMultiPwAff = 679 isl::pw_multi_aff::from_map(Schedule.reverse()); 680 isl::ast_build RestrictedBuild = AstBuild.restrict(Schedule.range()); 681 682 // Sequence of strings to print. 683 SmallVector<llvm::Value *, 8> Values; 684 685 // Print the name of the statement. 686 // TODO: Indent by the depth of the statement instance in the schedule tree. 687 Values.push_back(RuntimeDebugBuilder::getPrintableString(Builder, BaseName)); 688 Values.push_back(RuntimeDebugBuilder::getPrintableString(Builder, "(")); 689 690 // Add the coordinate of the statement instance. 691 for (unsigned i : rangeIslSize(0, ScheduleMultiPwAff.dim(isl::dim::out))) { 692 if (i > 0) 693 Values.push_back(RuntimeDebugBuilder::getPrintableString(Builder, ",")); 694 695 isl::ast_expr IsInSet = RestrictedBuild.expr_from(ScheduleMultiPwAff.at(i)); 696 Values.push_back(ExprBuilder->create(IsInSet.copy())); 697 } 698 699 if (TraceScalars) { 700 Values.push_back(RuntimeDebugBuilder::getPrintableString(Builder, ")")); 701 DenseSet<Instruction *> Encountered; 702 703 // Add the value of each scalar (and the result of PHIs) used in the 704 // statement. 705 // TODO: Values used in region-statements. 706 for (Instruction *Inst : Stmt.insts()) { 707 if (!RuntimeDebugBuilder::isPrintable(Inst->getType())) 708 continue; 709 710 if (isa<PHINode>(Inst)) { 711 Values.push_back(RuntimeDebugBuilder::getPrintableString(Builder, " ")); 712 Values.push_back(RuntimeDebugBuilder::getPrintableString( 713 Builder, getInstName(Inst))); 714 Values.push_back(RuntimeDebugBuilder::getPrintableString(Builder, "=")); 715 Values.push_back(getNewValue(Stmt, Inst, BBMap, LTS, 716 LI.getLoopFor(Inst->getParent()))); 717 } else { 718 for (Value *Op : Inst->operand_values()) { 719 // Do not print values that cannot change during the execution of the 720 // SCoP. 721 auto *OpInst = dyn_cast<Instruction>(Op); 722 if (!OpInst) 723 continue; 724 if (!S->contains(OpInst)) 725 continue; 726 727 // Print each scalar at most once, and exclude values defined in the 728 // statement itself. 729 if (Encountered.count(OpInst)) 730 continue; 731 732 Values.push_back( 733 RuntimeDebugBuilder::getPrintableString(Builder, " ")); 734 Values.push_back(RuntimeDebugBuilder::getPrintableString( 735 Builder, getInstName(OpInst))); 736 Values.push_back( 737 RuntimeDebugBuilder::getPrintableString(Builder, "=")); 738 Values.push_back(getNewValue(Stmt, OpInst, BBMap, LTS, 739 LI.getLoopFor(Inst->getParent()))); 740 Encountered.insert(OpInst); 741 } 742 } 743 744 Encountered.insert(Inst); 745 } 746 747 Values.push_back(RuntimeDebugBuilder::getPrintableString(Builder, "\n")); 748 } else { 749 Values.push_back(RuntimeDebugBuilder::getPrintableString(Builder, ")\n")); 750 } 751 752 RuntimeDebugBuilder::createCPUPrinter(Builder, ArrayRef<Value *>(Values)); 753 } 754 755 void BlockGenerator::generateScalarStores( 756 ScopStmt &Stmt, LoopToScevMapT <S, ValueMapT &BBMap, 757 __isl_keep isl_id_to_ast_expr *NewAccesses) { 758 Loop *L = LI.getLoopFor(Stmt.getBasicBlock()); 759 760 assert(Stmt.isBlockStmt() && 761 "Region statements need to use the generateScalarStores() function in " 762 "the RegionGenerator"); 763 764 for (MemoryAccess *MA : Stmt) { 765 if (MA->isOriginalArrayKind() || MA->isRead()) 766 continue; 767 768 isl::set AccDom = MA->getAccessRelation().domain(); 769 std::string Subject = MA->getId().get_name(); 770 771 generateConditionalExecution( 772 Stmt, AccDom, Subject.c_str(), [&, this, MA]() { 773 Value *Val = MA->getAccessValue(); 774 if (MA->isAnyPHIKind()) { 775 assert(MA->getIncoming().size() >= 1 && 776 "Block statements have exactly one exiting block, or " 777 "multiple but " 778 "with same incoming block and value"); 779 assert(std::all_of(MA->getIncoming().begin(), 780 MA->getIncoming().end(), 781 [&](std::pair<BasicBlock *, Value *> p) -> bool { 782 return p.first == Stmt.getBasicBlock(); 783 }) && 784 "Incoming block must be statement's block"); 785 Val = MA->getIncoming()[0].second; 786 } 787 auto Address = getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS, 788 BBMap, NewAccesses); 789 790 Val = getNewValue(Stmt, Val, BBMap, LTS, L); 791 assert((!isa<Instruction>(Val) || 792 DT.dominates(cast<Instruction>(Val)->getParent(), 793 Builder.GetInsertBlock())) && 794 "Domination violation"); 795 assert((!isa<Instruction>(Address) || 796 DT.dominates(cast<Instruction>(Address)->getParent(), 797 Builder.GetInsertBlock())) && 798 "Domination violation"); 799 800 // The new Val might have a different type than the old Val due to 801 // ScalarEvolution looking through bitcasts. 802 Address = Builder.CreateBitOrPointerCast( 803 Address, Val->getType()->getPointerTo( 804 Address->getType()->getPointerAddressSpace())); 805 806 Builder.CreateStore(Val, Address); 807 }); 808 } 809 } 810 811 void BlockGenerator::createScalarInitialization(Scop &S) { 812 BasicBlock *ExitBB = S.getExit(); 813 BasicBlock *PreEntryBB = S.getEnteringBlock(); 814 815 Builder.SetInsertPoint(&*StartBlock->begin()); 816 817 for (auto &Array : S.arrays()) { 818 if (Array->getNumberOfDimensions() != 0) 819 continue; 820 if (Array->isPHIKind()) { 821 // For PHI nodes, the only values we need to store are the ones that 822 // reach the PHI node from outside the region. In general there should 823 // only be one such incoming edge and this edge should enter through 824 // 'PreEntryBB'. 825 auto PHI = cast<PHINode>(Array->getBasePtr()); 826 827 for (auto BI = PHI->block_begin(), BE = PHI->block_end(); BI != BE; BI++) 828 if (!S.contains(*BI) && *BI != PreEntryBB) 829 llvm_unreachable("Incoming edges from outside the scop should always " 830 "come from PreEntryBB"); 831 832 int Idx = PHI->getBasicBlockIndex(PreEntryBB); 833 if (Idx < 0) 834 continue; 835 836 Value *ScalarValue = PHI->getIncomingValue(Idx); 837 838 Builder.CreateStore(ScalarValue, getOrCreateAlloca(Array)); 839 continue; 840 } 841 842 auto *Inst = dyn_cast<Instruction>(Array->getBasePtr()); 843 844 if (Inst && S.contains(Inst)) 845 continue; 846 847 // PHI nodes that are not marked as such in their SAI object are either exit 848 // PHI nodes we model as common scalars but without initialization, or 849 // incoming phi nodes that need to be initialized. Check if the first is the 850 // case for Inst and do not create and initialize memory if so. 851 if (auto *PHI = dyn_cast_or_null<PHINode>(Inst)) 852 if (!S.hasSingleExitEdge() && PHI->getBasicBlockIndex(ExitBB) >= 0) 853 continue; 854 855 Builder.CreateStore(Array->getBasePtr(), getOrCreateAlloca(Array)); 856 } 857 } 858 859 void BlockGenerator::createScalarFinalization(Scop &S) { 860 // The exit block of the __unoptimized__ region. 861 BasicBlock *ExitBB = S.getExitingBlock(); 862 // The merge block __just after__ the region and the optimized region. 863 BasicBlock *MergeBB = S.getExit(); 864 865 // The exit block of the __optimized__ region. 866 BasicBlock *OptExitBB = *(pred_begin(MergeBB)); 867 if (OptExitBB == ExitBB) 868 OptExitBB = *(++pred_begin(MergeBB)); 869 870 Builder.SetInsertPoint(OptExitBB->getTerminator()); 871 for (const auto &EscapeMapping : EscapeMap) { 872 // Extract the escaping instruction and the escaping users as well as the 873 // alloca the instruction was demoted to. 874 Instruction *EscapeInst = EscapeMapping.first; 875 const auto &EscapeMappingValue = EscapeMapping.second; 876 const EscapeUserVectorTy &EscapeUsers = EscapeMappingValue.second; 877 auto *ScalarAddr = cast<AllocaInst>(&*EscapeMappingValue.first); 878 879 // Reload the demoted instruction in the optimized version of the SCoP. 880 Value *EscapeInstReload = 881 Builder.CreateLoad(ScalarAddr->getAllocatedType(), ScalarAddr, 882 EscapeInst->getName() + ".final_reload"); 883 EscapeInstReload = 884 Builder.CreateBitOrPointerCast(EscapeInstReload, EscapeInst->getType()); 885 886 // Create the merge PHI that merges the optimized and unoptimized version. 887 PHINode *MergePHI = PHINode::Create(EscapeInst->getType(), 2, 888 EscapeInst->getName() + ".merge"); 889 MergePHI->insertBefore(&*MergeBB->getFirstInsertionPt()); 890 891 // Add the respective values to the merge PHI. 892 MergePHI->addIncoming(EscapeInstReload, OptExitBB); 893 MergePHI->addIncoming(EscapeInst, ExitBB); 894 895 // The information of scalar evolution about the escaping instruction needs 896 // to be revoked so the new merged instruction will be used. 897 if (SE.isSCEVable(EscapeInst->getType())) 898 SE.forgetValue(EscapeInst); 899 900 // Replace all uses of the demoted instruction with the merge PHI. 901 for (Instruction *EUser : EscapeUsers) 902 EUser->replaceUsesOfWith(EscapeInst, MergePHI); 903 } 904 } 905 906 void BlockGenerator::findOutsideUsers(Scop &S) { 907 for (auto &Array : S.arrays()) { 908 909 if (Array->getNumberOfDimensions() != 0) 910 continue; 911 912 if (Array->isPHIKind()) 913 continue; 914 915 auto *Inst = dyn_cast<Instruction>(Array->getBasePtr()); 916 917 if (!Inst) 918 continue; 919 920 // Scop invariant hoisting moves some of the base pointers out of the scop. 921 // We can ignore these, as the invariant load hoisting already registers the 922 // relevant outside users. 923 if (!S.contains(Inst)) 924 continue; 925 926 handleOutsideUsers(S, Array); 927 } 928 } 929 930 void BlockGenerator::createExitPHINodeMerges(Scop &S) { 931 if (S.hasSingleExitEdge()) 932 return; 933 934 auto *ExitBB = S.getExitingBlock(); 935 auto *MergeBB = S.getExit(); 936 auto *AfterMergeBB = MergeBB->getSingleSuccessor(); 937 BasicBlock *OptExitBB = *(pred_begin(MergeBB)); 938 if (OptExitBB == ExitBB) 939 OptExitBB = *(++pred_begin(MergeBB)); 940 941 Builder.SetInsertPoint(OptExitBB->getTerminator()); 942 943 for (auto &SAI : S.arrays()) { 944 auto *Val = SAI->getBasePtr(); 945 946 // Only Value-like scalars need a merge PHI. Exit block PHIs receive either 947 // the original PHI's value or the reloaded incoming values from the 948 // generated code. An llvm::Value is merged between the original code's 949 // value or the generated one. 950 if (!SAI->isExitPHIKind()) 951 continue; 952 953 PHINode *PHI = dyn_cast<PHINode>(Val); 954 if (!PHI) 955 continue; 956 957 if (PHI->getParent() != AfterMergeBB) 958 continue; 959 960 std::string Name = PHI->getName().str(); 961 Value *ScalarAddr = getOrCreateAlloca(SAI); 962 Value *Reload = Builder.CreateLoad(SAI->getElementType(), ScalarAddr, 963 Name + ".ph.final_reload"); 964 Reload = Builder.CreateBitOrPointerCast(Reload, PHI->getType()); 965 Value *OriginalValue = PHI->getIncomingValueForBlock(MergeBB); 966 assert((!isa<Instruction>(OriginalValue) || 967 cast<Instruction>(OriginalValue)->getParent() != MergeBB) && 968 "Original value must no be one we just generated."); 969 auto *MergePHI = PHINode::Create(PHI->getType(), 2, Name + ".ph.merge"); 970 MergePHI->insertBefore(&*MergeBB->getFirstInsertionPt()); 971 MergePHI->addIncoming(Reload, OptExitBB); 972 MergePHI->addIncoming(OriginalValue, ExitBB); 973 int Idx = PHI->getBasicBlockIndex(MergeBB); 974 PHI->setIncomingValue(Idx, MergePHI); 975 } 976 } 977 978 void BlockGenerator::invalidateScalarEvolution(Scop &S) { 979 for (auto &Stmt : S) 980 if (Stmt.isCopyStmt()) 981 continue; 982 else if (Stmt.isBlockStmt()) 983 for (auto &Inst : *Stmt.getBasicBlock()) 984 SE.forgetValue(&Inst); 985 else if (Stmt.isRegionStmt()) 986 for (auto *BB : Stmt.getRegion()->blocks()) 987 for (auto &Inst : *BB) 988 SE.forgetValue(&Inst); 989 else 990 llvm_unreachable("Unexpected statement type found"); 991 992 // Invalidate SCEV of loops surrounding the EscapeUsers. 993 for (const auto &EscapeMapping : EscapeMap) { 994 const EscapeUserVectorTy &EscapeUsers = EscapeMapping.second.second; 995 for (Instruction *EUser : EscapeUsers) { 996 if (Loop *L = LI.getLoopFor(EUser->getParent())) 997 while (L) { 998 SE.forgetLoop(L); 999 L = L->getParentLoop(); 1000 } 1001 } 1002 } 1003 } 1004 1005 void BlockGenerator::finalizeSCoP(Scop &S) { 1006 findOutsideUsers(S); 1007 createScalarInitialization(S); 1008 createExitPHINodeMerges(S); 1009 createScalarFinalization(S); 1010 invalidateScalarEvolution(S); 1011 } 1012 1013 VectorBlockGenerator::VectorBlockGenerator(BlockGenerator &BlockGen, 1014 std::vector<LoopToScevMapT> &VLTS, 1015 isl_map *Schedule) 1016 : BlockGenerator(BlockGen), VLTS(VLTS), Schedule(Schedule) { 1017 assert(Schedule && "No statement domain provided"); 1018 } 1019 1020 Value *VectorBlockGenerator::getVectorValue(ScopStmt &Stmt, Value *Old, 1021 ValueMapT &VectorMap, 1022 VectorValueMapT &ScalarMaps, 1023 Loop *L) { 1024 if (Value *NewValue = VectorMap.lookup(Old)) 1025 return NewValue; 1026 1027 int Width = getVectorWidth(); 1028 1029 Value *Vector = UndefValue::get(FixedVectorType::get(Old->getType(), Width)); 1030 1031 for (int Lane = 0; Lane < Width; Lane++) 1032 Vector = Builder.CreateInsertElement( 1033 Vector, getNewValue(Stmt, Old, ScalarMaps[Lane], VLTS[Lane], L), 1034 Builder.getInt32(Lane)); 1035 1036 VectorMap[Old] = Vector; 1037 1038 return Vector; 1039 } 1040 1041 Value *VectorBlockGenerator::generateStrideOneLoad( 1042 ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps, 1043 __isl_keep isl_id_to_ast_expr *NewAccesses, bool NegativeStride = false) { 1044 unsigned VectorWidth = getVectorWidth(); 1045 Type *VectorType = FixedVectorType::get(Load->getType(), VectorWidth); 1046 Type *VectorPtrType = 1047 PointerType::get(VectorType, Load->getPointerAddressSpace()); 1048 unsigned Offset = NegativeStride ? VectorWidth - 1 : 0; 1049 1050 Value *NewPointer = generateLocationAccessed(Stmt, Load, ScalarMaps[Offset], 1051 VLTS[Offset], NewAccesses); 1052 Value *VectorPtr = 1053 Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr"); 1054 LoadInst *VecLoad = Builder.CreateLoad(VectorType, VectorPtr, 1055 Load->getName() + "_p_vec_full"); 1056 if (!Aligned) 1057 VecLoad->setAlignment(Align(8)); 1058 1059 if (NegativeStride) { 1060 SmallVector<Constant *, 16> Indices; 1061 for (int i = VectorWidth - 1; i >= 0; i--) 1062 Indices.push_back(ConstantInt::get(Builder.getInt32Ty(), i)); 1063 Constant *SV = llvm::ConstantVector::get(Indices); 1064 Value *RevVecLoad = Builder.CreateShuffleVector( 1065 VecLoad, VecLoad, SV, Load->getName() + "_reverse"); 1066 return RevVecLoad; 1067 } 1068 1069 return VecLoad; 1070 } 1071 1072 Value *VectorBlockGenerator::generateStrideZeroLoad( 1073 ScopStmt &Stmt, LoadInst *Load, ValueMapT &BBMap, 1074 __isl_keep isl_id_to_ast_expr *NewAccesses) { 1075 Type *VectorType = FixedVectorType::get(Load->getType(), 1); 1076 Type *VectorPtrType = 1077 PointerType::get(VectorType, Load->getPointerAddressSpace()); 1078 Value *NewPointer = 1079 generateLocationAccessed(Stmt, Load, BBMap, VLTS[0], NewAccesses); 1080 Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType, 1081 Load->getName() + "_p_vec_p"); 1082 LoadInst *ScalarLoad = Builder.CreateLoad(VectorType, VectorPtr, 1083 Load->getName() + "_p_splat_one"); 1084 1085 if (!Aligned) 1086 ScalarLoad->setAlignment(Align(8)); 1087 1088 Constant *SplatVector = Constant::getNullValue( 1089 FixedVectorType::get(Builder.getInt32Ty(), getVectorWidth())); 1090 1091 Value *VectorLoad = Builder.CreateShuffleVector( 1092 ScalarLoad, ScalarLoad, SplatVector, Load->getName() + "_p_splat"); 1093 return VectorLoad; 1094 } 1095 1096 Value *VectorBlockGenerator::generateUnknownStrideLoad( 1097 ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps, 1098 __isl_keep isl_id_to_ast_expr *NewAccesses) { 1099 int VectorWidth = getVectorWidth(); 1100 Type *ElemTy = Load->getType(); 1101 auto *FVTy = FixedVectorType::get(ElemTy, VectorWidth); 1102 1103 Value *Vector = UndefValue::get(FVTy); 1104 1105 for (int i = 0; i < VectorWidth; i++) { 1106 Value *NewPointer = generateLocationAccessed(Stmt, Load, ScalarMaps[i], 1107 VLTS[i], NewAccesses); 1108 Value *ScalarLoad = 1109 Builder.CreateLoad(ElemTy, NewPointer, Load->getName() + "_p_scalar_"); 1110 Vector = Builder.CreateInsertElement( 1111 Vector, ScalarLoad, Builder.getInt32(i), Load->getName() + "_p_vec_"); 1112 } 1113 1114 return Vector; 1115 } 1116 1117 void VectorBlockGenerator::generateLoad( 1118 ScopStmt &Stmt, LoadInst *Load, ValueMapT &VectorMap, 1119 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) { 1120 if (Value *PreloadLoad = GlobalMap.lookup(Load)) { 1121 VectorMap[Load] = Builder.CreateVectorSplat(getVectorWidth(), PreloadLoad, 1122 Load->getName() + "_p"); 1123 return; 1124 } 1125 1126 if (!VectorType::isValidElementType(Load->getType())) { 1127 for (int i = 0; i < getVectorWidth(); i++) 1128 ScalarMaps[i][Load] = 1129 generateArrayLoad(Stmt, Load, ScalarMaps[i], VLTS[i], NewAccesses); 1130 return; 1131 } 1132 1133 const MemoryAccess &Access = Stmt.getArrayAccessFor(Load); 1134 1135 // Make sure we have scalar values available to access the pointer to 1136 // the data location. 1137 extractScalarValues(Load, VectorMap, ScalarMaps); 1138 1139 Value *NewLoad; 1140 if (Access.isStrideZero(isl::manage_copy(Schedule))) 1141 NewLoad = generateStrideZeroLoad(Stmt, Load, ScalarMaps[0], NewAccesses); 1142 else if (Access.isStrideOne(isl::manage_copy(Schedule))) 1143 NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses); 1144 else if (Access.isStrideX(isl::manage_copy(Schedule), -1)) 1145 NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses, true); 1146 else 1147 NewLoad = generateUnknownStrideLoad(Stmt, Load, ScalarMaps, NewAccesses); 1148 1149 VectorMap[Load] = NewLoad; 1150 } 1151 1152 void VectorBlockGenerator::copyUnaryInst(ScopStmt &Stmt, UnaryInstruction *Inst, 1153 ValueMapT &VectorMap, 1154 VectorValueMapT &ScalarMaps) { 1155 int VectorWidth = getVectorWidth(); 1156 Value *NewOperand = getVectorValue(Stmt, Inst->getOperand(0), VectorMap, 1157 ScalarMaps, getLoopForStmt(Stmt)); 1158 1159 assert(isa<CastInst>(Inst) && "Can not generate vector code for instruction"); 1160 1161 const CastInst *Cast = dyn_cast<CastInst>(Inst); 1162 auto *DestType = FixedVectorType::get(Inst->getType(), VectorWidth); 1163 VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand, DestType); 1164 } 1165 1166 void VectorBlockGenerator::copyBinaryInst(ScopStmt &Stmt, BinaryOperator *Inst, 1167 ValueMapT &VectorMap, 1168 VectorValueMapT &ScalarMaps) { 1169 Loop *L = getLoopForStmt(Stmt); 1170 Value *OpZero = Inst->getOperand(0); 1171 Value *OpOne = Inst->getOperand(1); 1172 1173 Value *NewOpZero, *NewOpOne; 1174 NewOpZero = getVectorValue(Stmt, OpZero, VectorMap, ScalarMaps, L); 1175 NewOpOne = getVectorValue(Stmt, OpOne, VectorMap, ScalarMaps, L); 1176 1177 Value *NewInst = Builder.CreateBinOp(Inst->getOpcode(), NewOpZero, NewOpOne, 1178 Inst->getName() + "p_vec"); 1179 VectorMap[Inst] = NewInst; 1180 } 1181 1182 void VectorBlockGenerator::copyStore( 1183 ScopStmt &Stmt, StoreInst *Store, ValueMapT &VectorMap, 1184 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) { 1185 const MemoryAccess &Access = Stmt.getArrayAccessFor(Store); 1186 1187 Value *Vector = getVectorValue(Stmt, Store->getValueOperand(), VectorMap, 1188 ScalarMaps, getLoopForStmt(Stmt)); 1189 1190 // Make sure we have scalar values available to access the pointer to 1191 // the data location. 1192 extractScalarValues(Store, VectorMap, ScalarMaps); 1193 1194 if (Access.isStrideOne(isl::manage_copy(Schedule))) { 1195 Type *VectorType = FixedVectorType::get(Store->getValueOperand()->getType(), 1196 getVectorWidth()); 1197 Type *VectorPtrType = 1198 PointerType::get(VectorType, Store->getPointerAddressSpace()); 1199 Value *NewPointer = generateLocationAccessed(Stmt, Store, ScalarMaps[0], 1200 VLTS[0], NewAccesses); 1201 1202 Value *VectorPtr = 1203 Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr"); 1204 StoreInst *Store = Builder.CreateStore(Vector, VectorPtr); 1205 1206 if (!Aligned) 1207 Store->setAlignment(Align(8)); 1208 } else { 1209 for (unsigned i = 0; i < ScalarMaps.size(); i++) { 1210 Value *Scalar = Builder.CreateExtractElement(Vector, Builder.getInt32(i)); 1211 Value *NewPointer = generateLocationAccessed(Stmt, Store, ScalarMaps[i], 1212 VLTS[i], NewAccesses); 1213 Builder.CreateStore(Scalar, NewPointer); 1214 } 1215 } 1216 } 1217 1218 bool VectorBlockGenerator::hasVectorOperands(const Instruction *Inst, 1219 ValueMapT &VectorMap) { 1220 for (Value *Operand : Inst->operands()) 1221 if (VectorMap.count(Operand)) 1222 return true; 1223 return false; 1224 } 1225 1226 bool VectorBlockGenerator::extractScalarValues(const Instruction *Inst, 1227 ValueMapT &VectorMap, 1228 VectorValueMapT &ScalarMaps) { 1229 bool HasVectorOperand = false; 1230 int VectorWidth = getVectorWidth(); 1231 1232 for (Value *Operand : Inst->operands()) { 1233 ValueMapT::iterator VecOp = VectorMap.find(Operand); 1234 1235 if (VecOp == VectorMap.end()) 1236 continue; 1237 1238 HasVectorOperand = true; 1239 Value *NewVector = VecOp->second; 1240 1241 for (int i = 0; i < VectorWidth; ++i) { 1242 ValueMapT &SM = ScalarMaps[i]; 1243 1244 // If there is one scalar extracted, all scalar elements should have 1245 // already been extracted by the code here. So no need to check for the 1246 // existence of all of them. 1247 if (SM.count(Operand)) 1248 break; 1249 1250 SM[Operand] = 1251 Builder.CreateExtractElement(NewVector, Builder.getInt32(i)); 1252 } 1253 } 1254 1255 return HasVectorOperand; 1256 } 1257 1258 void VectorBlockGenerator::copyInstScalarized( 1259 ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap, 1260 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) { 1261 bool HasVectorOperand; 1262 int VectorWidth = getVectorWidth(); 1263 1264 HasVectorOperand = extractScalarValues(Inst, VectorMap, ScalarMaps); 1265 1266 for (int VectorLane = 0; VectorLane < getVectorWidth(); VectorLane++) 1267 BlockGenerator::copyInstruction(Stmt, Inst, ScalarMaps[VectorLane], 1268 VLTS[VectorLane], NewAccesses); 1269 1270 if (!VectorType::isValidElementType(Inst->getType()) || !HasVectorOperand) 1271 return; 1272 1273 // Make the result available as vector value. 1274 auto *FVTy = FixedVectorType::get(Inst->getType(), VectorWidth); 1275 Value *Vector = UndefValue::get(FVTy); 1276 1277 for (int i = 0; i < VectorWidth; i++) 1278 Vector = Builder.CreateInsertElement(Vector, ScalarMaps[i][Inst], 1279 Builder.getInt32(i)); 1280 1281 VectorMap[Inst] = Vector; 1282 } 1283 1284 int VectorBlockGenerator::getVectorWidth() { return VLTS.size(); } 1285 1286 void VectorBlockGenerator::copyInstruction( 1287 ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap, 1288 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) { 1289 // Terminator instructions control the control flow. They are explicitly 1290 // expressed in the clast and do not need to be copied. 1291 if (Inst->isTerminator()) 1292 return; 1293 1294 if (canSyntheziseInStmt(Stmt, Inst)) 1295 return; 1296 1297 if (auto *Load = dyn_cast<LoadInst>(Inst)) { 1298 generateLoad(Stmt, Load, VectorMap, ScalarMaps, NewAccesses); 1299 return; 1300 } 1301 1302 if (hasVectorOperands(Inst, VectorMap)) { 1303 if (auto *Store = dyn_cast<StoreInst>(Inst)) { 1304 // Identified as redundant by -polly-simplify. 1305 if (!Stmt.getArrayAccessOrNULLFor(Store)) 1306 return; 1307 1308 copyStore(Stmt, Store, VectorMap, ScalarMaps, NewAccesses); 1309 return; 1310 } 1311 1312 if (auto *Unary = dyn_cast<UnaryInstruction>(Inst)) { 1313 copyUnaryInst(Stmt, Unary, VectorMap, ScalarMaps); 1314 return; 1315 } 1316 1317 if (auto *Binary = dyn_cast<BinaryOperator>(Inst)) { 1318 copyBinaryInst(Stmt, Binary, VectorMap, ScalarMaps); 1319 return; 1320 } 1321 1322 // Fallthrough: We generate scalar instructions, if we don't know how to 1323 // generate vector code. 1324 } 1325 1326 copyInstScalarized(Stmt, Inst, VectorMap, ScalarMaps, NewAccesses); 1327 } 1328 1329 void VectorBlockGenerator::generateScalarVectorLoads( 1330 ScopStmt &Stmt, ValueMapT &VectorBlockMap) { 1331 for (MemoryAccess *MA : Stmt) { 1332 if (MA->isArrayKind() || MA->isWrite()) 1333 continue; 1334 1335 auto *Address = getOrCreateAlloca(*MA); 1336 Type *VectorType = FixedVectorType::get(MA->getElementType(), 1); 1337 Type *VectorPtrType = PointerType::get( 1338 VectorType, Address->getType()->getPointerAddressSpace()); 1339 Value *VectorPtr = Builder.CreateBitCast(Address, VectorPtrType, 1340 Address->getName() + "_p_vec_p"); 1341 auto *Val = Builder.CreateLoad(VectorType, VectorPtr, 1342 Address->getName() + ".reload"); 1343 Constant *SplatVector = Constant::getNullValue( 1344 FixedVectorType::get(Builder.getInt32Ty(), getVectorWidth())); 1345 1346 Value *VectorVal = Builder.CreateShuffleVector( 1347 Val, Val, SplatVector, Address->getName() + "_p_splat"); 1348 VectorBlockMap[MA->getAccessValue()] = VectorVal; 1349 } 1350 } 1351 1352 void VectorBlockGenerator::verifyNoScalarStores(ScopStmt &Stmt) { 1353 for (MemoryAccess *MA : Stmt) { 1354 if (MA->isArrayKind() || MA->isRead()) 1355 continue; 1356 1357 llvm_unreachable("Scalar stores not expected in vector loop"); 1358 } 1359 } 1360 1361 void VectorBlockGenerator::copyStmt( 1362 ScopStmt &Stmt, __isl_keep isl_id_to_ast_expr *NewAccesses) { 1363 assert(Stmt.isBlockStmt() && 1364 "TODO: Only block statements can be copied by the vector block " 1365 "generator"); 1366 1367 BasicBlock *BB = Stmt.getBasicBlock(); 1368 BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(), 1369 &*Builder.GetInsertPoint(), &DT, &LI); 1370 CopyBB->setName("polly.stmt." + BB->getName()); 1371 Builder.SetInsertPoint(&CopyBB->front()); 1372 1373 // Create two maps that store the mapping from the original instructions of 1374 // the old basic block to their copies in the new basic block. Those maps 1375 // are basic block local. 1376 // 1377 // As vector code generation is supported there is one map for scalar values 1378 // and one for vector values. 1379 // 1380 // In case we just do scalar code generation, the vectorMap is not used and 1381 // the scalarMap has just one dimension, which contains the mapping. 1382 // 1383 // In case vector code generation is done, an instruction may either appear 1384 // in the vector map once (as it is calculating >vectorwidth< values at a 1385 // time. Or (if the values are calculated using scalar operations), it 1386 // appears once in every dimension of the scalarMap. 1387 VectorValueMapT ScalarBlockMap(getVectorWidth()); 1388 ValueMapT VectorBlockMap; 1389 1390 generateScalarVectorLoads(Stmt, VectorBlockMap); 1391 1392 for (Instruction *Inst : Stmt.getInstructions()) 1393 copyInstruction(Stmt, Inst, VectorBlockMap, ScalarBlockMap, NewAccesses); 1394 1395 verifyNoScalarStores(Stmt); 1396 } 1397 1398 BasicBlock *RegionGenerator::repairDominance(BasicBlock *BB, 1399 BasicBlock *BBCopy) { 1400 1401 BasicBlock *BBIDom = DT.getNode(BB)->getIDom()->getBlock(); 1402 BasicBlock *BBCopyIDom = EndBlockMap.lookup(BBIDom); 1403 1404 if (BBCopyIDom) 1405 DT.changeImmediateDominator(BBCopy, BBCopyIDom); 1406 1407 return StartBlockMap.lookup(BBIDom); 1408 } 1409 1410 // This is to determine whether an llvm::Value (defined in @p BB) is usable when 1411 // leaving a subregion. The straight-forward DT.dominates(BB, R->getExitBlock()) 1412 // does not work in cases where the exit block has edges from outside the 1413 // region. In that case the llvm::Value would never be usable in in the exit 1414 // block. The RegionGenerator however creates an new exit block ('ExitBBCopy') 1415 // for the subregion's exiting edges only. We need to determine whether an 1416 // llvm::Value is usable in there. We do this by checking whether it dominates 1417 // all exiting blocks individually. 1418 static bool isDominatingSubregionExit(const DominatorTree &DT, Region *R, 1419 BasicBlock *BB) { 1420 for (auto ExitingBB : predecessors(R->getExit())) { 1421 // Check for non-subregion incoming edges. 1422 if (!R->contains(ExitingBB)) 1423 continue; 1424 1425 if (!DT.dominates(BB, ExitingBB)) 1426 return false; 1427 } 1428 1429 return true; 1430 } 1431 1432 // Find the direct dominator of the subregion's exit block if the subregion was 1433 // simplified. 1434 static BasicBlock *findExitDominator(DominatorTree &DT, Region *R) { 1435 BasicBlock *Common = nullptr; 1436 for (auto ExitingBB : predecessors(R->getExit())) { 1437 // Check for non-subregion incoming edges. 1438 if (!R->contains(ExitingBB)) 1439 continue; 1440 1441 // First exiting edge. 1442 if (!Common) { 1443 Common = ExitingBB; 1444 continue; 1445 } 1446 1447 Common = DT.findNearestCommonDominator(Common, ExitingBB); 1448 } 1449 1450 assert(Common && R->contains(Common)); 1451 return Common; 1452 } 1453 1454 void RegionGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT <S, 1455 __isl_keep isl_id_to_ast_expr *IdToAstExp) { 1456 assert(Stmt.isRegionStmt() && 1457 "Only region statements can be copied by the region generator"); 1458 1459 // Forget all old mappings. 1460 StartBlockMap.clear(); 1461 EndBlockMap.clear(); 1462 RegionMaps.clear(); 1463 IncompletePHINodeMap.clear(); 1464 1465 // Collection of all values related to this subregion. 1466 ValueMapT ValueMap; 1467 1468 // The region represented by the statement. 1469 Region *R = Stmt.getRegion(); 1470 1471 // Create a dedicated entry for the region where we can reload all demoted 1472 // inputs. 1473 BasicBlock *EntryBB = R->getEntry(); 1474 BasicBlock *EntryBBCopy = SplitBlock(Builder.GetInsertBlock(), 1475 &*Builder.GetInsertPoint(), &DT, &LI); 1476 EntryBBCopy->setName("polly.stmt." + EntryBB->getName() + ".entry"); 1477 Builder.SetInsertPoint(&EntryBBCopy->front()); 1478 1479 ValueMapT &EntryBBMap = RegionMaps[EntryBBCopy]; 1480 generateScalarLoads(Stmt, LTS, EntryBBMap, IdToAstExp); 1481 generateBeginStmtTrace(Stmt, LTS, EntryBBMap); 1482 1483 for (auto PI = pred_begin(EntryBB), PE = pred_end(EntryBB); PI != PE; ++PI) 1484 if (!R->contains(*PI)) { 1485 StartBlockMap[*PI] = EntryBBCopy; 1486 EndBlockMap[*PI] = EntryBBCopy; 1487 } 1488 1489 // Iterate over all blocks in the region in a breadth-first search. 1490 std::deque<BasicBlock *> Blocks; 1491 SmallSetVector<BasicBlock *, 8> SeenBlocks; 1492 Blocks.push_back(EntryBB); 1493 SeenBlocks.insert(EntryBB); 1494 1495 while (!Blocks.empty()) { 1496 BasicBlock *BB = Blocks.front(); 1497 Blocks.pop_front(); 1498 1499 // First split the block and update dominance information. 1500 BasicBlock *BBCopy = splitBB(BB); 1501 BasicBlock *BBCopyIDom = repairDominance(BB, BBCopy); 1502 1503 // Get the mapping for this block and initialize it with either the scalar 1504 // loads from the generated entering block (which dominates all blocks of 1505 // this subregion) or the maps of the immediate dominator, if part of the 1506 // subregion. The latter necessarily includes the former. 1507 ValueMapT *InitBBMap; 1508 if (BBCopyIDom) { 1509 assert(RegionMaps.count(BBCopyIDom)); 1510 InitBBMap = &RegionMaps[BBCopyIDom]; 1511 } else 1512 InitBBMap = &EntryBBMap; 1513 auto Inserted = RegionMaps.insert(std::make_pair(BBCopy, *InitBBMap)); 1514 ValueMapT &RegionMap = Inserted.first->second; 1515 1516 // Copy the block with the BlockGenerator. 1517 Builder.SetInsertPoint(&BBCopy->front()); 1518 copyBB(Stmt, BB, BBCopy, RegionMap, LTS, IdToAstExp); 1519 1520 // In order to remap PHI nodes we store also basic block mappings. 1521 StartBlockMap[BB] = BBCopy; 1522 EndBlockMap[BB] = Builder.GetInsertBlock(); 1523 1524 // Add values to incomplete PHI nodes waiting for this block to be copied. 1525 for (const PHINodePairTy &PHINodePair : IncompletePHINodeMap[BB]) 1526 addOperandToPHI(Stmt, PHINodePair.first, PHINodePair.second, BB, LTS); 1527 IncompletePHINodeMap[BB].clear(); 1528 1529 // And continue with new successors inside the region. 1530 for (auto SI = succ_begin(BB), SE = succ_end(BB); SI != SE; SI++) 1531 if (R->contains(*SI) && SeenBlocks.insert(*SI)) 1532 Blocks.push_back(*SI); 1533 1534 // Remember value in case it is visible after this subregion. 1535 if (isDominatingSubregionExit(DT, R, BB)) 1536 ValueMap.insert(RegionMap.begin(), RegionMap.end()); 1537 } 1538 1539 // Now create a new dedicated region exit block and add it to the region map. 1540 BasicBlock *ExitBBCopy = SplitBlock(Builder.GetInsertBlock(), 1541 &*Builder.GetInsertPoint(), &DT, &LI); 1542 ExitBBCopy->setName("polly.stmt." + R->getExit()->getName() + ".exit"); 1543 StartBlockMap[R->getExit()] = ExitBBCopy; 1544 EndBlockMap[R->getExit()] = ExitBBCopy; 1545 1546 BasicBlock *ExitDomBBCopy = EndBlockMap.lookup(findExitDominator(DT, R)); 1547 assert(ExitDomBBCopy && 1548 "Common exit dominator must be within region; at least the entry node " 1549 "must match"); 1550 DT.changeImmediateDominator(ExitBBCopy, ExitDomBBCopy); 1551 1552 // As the block generator doesn't handle control flow we need to add the 1553 // region control flow by hand after all blocks have been copied. 1554 for (BasicBlock *BB : SeenBlocks) { 1555 1556 BasicBlock *BBCopyStart = StartBlockMap[BB]; 1557 BasicBlock *BBCopyEnd = EndBlockMap[BB]; 1558 Instruction *TI = BB->getTerminator(); 1559 if (isa<UnreachableInst>(TI)) { 1560 while (!BBCopyEnd->empty()) 1561 BBCopyEnd->begin()->eraseFromParent(); 1562 new UnreachableInst(BBCopyEnd->getContext(), BBCopyEnd); 1563 continue; 1564 } 1565 1566 Instruction *BICopy = BBCopyEnd->getTerminator(); 1567 1568 ValueMapT &RegionMap = RegionMaps[BBCopyStart]; 1569 RegionMap.insert(StartBlockMap.begin(), StartBlockMap.end()); 1570 1571 Builder.SetInsertPoint(BICopy); 1572 copyInstScalar(Stmt, TI, RegionMap, LTS); 1573 BICopy->eraseFromParent(); 1574 } 1575 1576 // Add counting PHI nodes to all loops in the region that can be used as 1577 // replacement for SCEVs referring to the old loop. 1578 for (BasicBlock *BB : SeenBlocks) { 1579 Loop *L = LI.getLoopFor(BB); 1580 if (L == nullptr || L->getHeader() != BB || !R->contains(L)) 1581 continue; 1582 1583 BasicBlock *BBCopy = StartBlockMap[BB]; 1584 Value *NullVal = Builder.getInt32(0); 1585 PHINode *LoopPHI = 1586 PHINode::Create(Builder.getInt32Ty(), 2, "polly.subregion.iv"); 1587 Instruction *LoopPHIInc = BinaryOperator::CreateAdd( 1588 LoopPHI, Builder.getInt32(1), "polly.subregion.iv.inc"); 1589 LoopPHI->insertBefore(&BBCopy->front()); 1590 LoopPHIInc->insertBefore(BBCopy->getTerminator()); 1591 1592 for (auto *PredBB : make_range(pred_begin(BB), pred_end(BB))) { 1593 if (!R->contains(PredBB)) 1594 continue; 1595 if (L->contains(PredBB)) 1596 LoopPHI->addIncoming(LoopPHIInc, EndBlockMap[PredBB]); 1597 else 1598 LoopPHI->addIncoming(NullVal, EndBlockMap[PredBB]); 1599 } 1600 1601 for (auto *PredBBCopy : make_range(pred_begin(BBCopy), pred_end(BBCopy))) 1602 if (LoopPHI->getBasicBlockIndex(PredBBCopy) < 0) 1603 LoopPHI->addIncoming(NullVal, PredBBCopy); 1604 1605 LTS[L] = SE.getUnknown(LoopPHI); 1606 } 1607 1608 // Continue generating code in the exit block. 1609 Builder.SetInsertPoint(&*ExitBBCopy->getFirstInsertionPt()); 1610 1611 // Write values visible to other statements. 1612 generateScalarStores(Stmt, LTS, ValueMap, IdToAstExp); 1613 StartBlockMap.clear(); 1614 EndBlockMap.clear(); 1615 RegionMaps.clear(); 1616 IncompletePHINodeMap.clear(); 1617 } 1618 1619 PHINode *RegionGenerator::buildExitPHI(MemoryAccess *MA, LoopToScevMapT <S, 1620 ValueMapT &BBMap, Loop *L) { 1621 ScopStmt *Stmt = MA->getStatement(); 1622 Region *SubR = Stmt->getRegion(); 1623 auto Incoming = MA->getIncoming(); 1624 1625 PollyIRBuilder::InsertPointGuard IPGuard(Builder); 1626 PHINode *OrigPHI = cast<PHINode>(MA->getAccessInstruction()); 1627 BasicBlock *NewSubregionExit = Builder.GetInsertBlock(); 1628 1629 // This can happen if the subregion is simplified after the ScopStmts 1630 // have been created; simplification happens as part of CodeGeneration. 1631 if (OrigPHI->getParent() != SubR->getExit()) { 1632 BasicBlock *FormerExit = SubR->getExitingBlock(); 1633 if (FormerExit) 1634 NewSubregionExit = StartBlockMap.lookup(FormerExit); 1635 } 1636 1637 PHINode *NewPHI = PHINode::Create(OrigPHI->getType(), Incoming.size(), 1638 "polly." + OrigPHI->getName(), 1639 NewSubregionExit->getFirstNonPHI()); 1640 1641 // Add the incoming values to the PHI. 1642 for (auto &Pair : Incoming) { 1643 BasicBlock *OrigIncomingBlock = Pair.first; 1644 BasicBlock *NewIncomingBlockStart = StartBlockMap.lookup(OrigIncomingBlock); 1645 BasicBlock *NewIncomingBlockEnd = EndBlockMap.lookup(OrigIncomingBlock); 1646 Builder.SetInsertPoint(NewIncomingBlockEnd->getTerminator()); 1647 assert(RegionMaps.count(NewIncomingBlockStart)); 1648 assert(RegionMaps.count(NewIncomingBlockEnd)); 1649 ValueMapT *LocalBBMap = &RegionMaps[NewIncomingBlockStart]; 1650 1651 Value *OrigIncomingValue = Pair.second; 1652 Value *NewIncomingValue = 1653 getNewValue(*Stmt, OrigIncomingValue, *LocalBBMap, LTS, L); 1654 NewPHI->addIncoming(NewIncomingValue, NewIncomingBlockEnd); 1655 } 1656 1657 return NewPHI; 1658 } 1659 1660 Value *RegionGenerator::getExitScalar(MemoryAccess *MA, LoopToScevMapT <S, 1661 ValueMapT &BBMap) { 1662 ScopStmt *Stmt = MA->getStatement(); 1663 1664 // TODO: Add some test cases that ensure this is really the right choice. 1665 Loop *L = LI.getLoopFor(Stmt->getRegion()->getExit()); 1666 1667 if (MA->isAnyPHIKind()) { 1668 auto Incoming = MA->getIncoming(); 1669 assert(!Incoming.empty() && 1670 "PHI WRITEs must have originate from at least one incoming block"); 1671 1672 // If there is only one incoming value, we do not need to create a PHI. 1673 if (Incoming.size() == 1) { 1674 Value *OldVal = Incoming[0].second; 1675 return getNewValue(*Stmt, OldVal, BBMap, LTS, L); 1676 } 1677 1678 return buildExitPHI(MA, LTS, BBMap, L); 1679 } 1680 1681 // MemoryKind::Value accesses leaving the subregion must dominate the exit 1682 // block; just pass the copied value. 1683 Value *OldVal = MA->getAccessValue(); 1684 return getNewValue(*Stmt, OldVal, BBMap, LTS, L); 1685 } 1686 1687 void RegionGenerator::generateScalarStores( 1688 ScopStmt &Stmt, LoopToScevMapT <S, ValueMapT &BBMap, 1689 __isl_keep isl_id_to_ast_expr *NewAccesses) { 1690 assert(Stmt.getRegion() && 1691 "Block statements need to use the generateScalarStores() " 1692 "function in the BlockGenerator"); 1693 1694 // Get the exit scalar values before generating the writes. 1695 // This is necessary because RegionGenerator::getExitScalar may insert 1696 // PHINodes that depend on the region's exiting blocks. But 1697 // BlockGenerator::generateConditionalExecution may insert a new basic block 1698 // such that the current basic block is not a direct successor of the exiting 1699 // blocks anymore. Hence, build the PHINodes while the current block is still 1700 // the direct successor. 1701 SmallDenseMap<MemoryAccess *, Value *> NewExitScalars; 1702 for (MemoryAccess *MA : Stmt) { 1703 if (MA->isOriginalArrayKind() || MA->isRead()) 1704 continue; 1705 1706 Value *NewVal = getExitScalar(MA, LTS, BBMap); 1707 NewExitScalars[MA] = NewVal; 1708 } 1709 1710 for (MemoryAccess *MA : Stmt) { 1711 if (MA->isOriginalArrayKind() || MA->isRead()) 1712 continue; 1713 1714 isl::set AccDom = MA->getAccessRelation().domain(); 1715 std::string Subject = MA->getId().get_name(); 1716 generateConditionalExecution( 1717 Stmt, AccDom, Subject.c_str(), [&, this, MA]() { 1718 Value *NewVal = NewExitScalars.lookup(MA); 1719 assert(NewVal && "The exit scalar must be determined before"); 1720 Value *Address = getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS, 1721 BBMap, NewAccesses); 1722 assert((!isa<Instruction>(NewVal) || 1723 DT.dominates(cast<Instruction>(NewVal)->getParent(), 1724 Builder.GetInsertBlock())) && 1725 "Domination violation"); 1726 assert((!isa<Instruction>(Address) || 1727 DT.dominates(cast<Instruction>(Address)->getParent(), 1728 Builder.GetInsertBlock())) && 1729 "Domination violation"); 1730 Builder.CreateStore(NewVal, Address); 1731 }); 1732 } 1733 } 1734 1735 void RegionGenerator::addOperandToPHI(ScopStmt &Stmt, PHINode *PHI, 1736 PHINode *PHICopy, BasicBlock *IncomingBB, 1737 LoopToScevMapT <S) { 1738 // If the incoming block was not yet copied mark this PHI as incomplete. 1739 // Once the block will be copied the incoming value will be added. 1740 BasicBlock *BBCopyStart = StartBlockMap[IncomingBB]; 1741 BasicBlock *BBCopyEnd = EndBlockMap[IncomingBB]; 1742 if (!BBCopyStart) { 1743 assert(!BBCopyEnd); 1744 assert(Stmt.represents(IncomingBB) && 1745 "Bad incoming block for PHI in non-affine region"); 1746 IncompletePHINodeMap[IncomingBB].push_back(std::make_pair(PHI, PHICopy)); 1747 return; 1748 } 1749 1750 assert(RegionMaps.count(BBCopyStart) && 1751 "Incoming PHI block did not have a BBMap"); 1752 ValueMapT &BBCopyMap = RegionMaps[BBCopyStart]; 1753 1754 Value *OpCopy = nullptr; 1755 1756 if (Stmt.represents(IncomingBB)) { 1757 Value *Op = PHI->getIncomingValueForBlock(IncomingBB); 1758 1759 // If the current insert block is different from the PHIs incoming block 1760 // change it, otherwise do not. 1761 auto IP = Builder.GetInsertPoint(); 1762 if (IP->getParent() != BBCopyEnd) 1763 Builder.SetInsertPoint(BBCopyEnd->getTerminator()); 1764 OpCopy = getNewValue(Stmt, Op, BBCopyMap, LTS, getLoopForStmt(Stmt)); 1765 if (IP->getParent() != BBCopyEnd) 1766 Builder.SetInsertPoint(&*IP); 1767 } else { 1768 // All edges from outside the non-affine region become a single edge 1769 // in the new copy of the non-affine region. Make sure to only add the 1770 // corresponding edge the first time we encounter a basic block from 1771 // outside the non-affine region. 1772 if (PHICopy->getBasicBlockIndex(BBCopyEnd) >= 0) 1773 return; 1774 1775 // Get the reloaded value. 1776 OpCopy = getNewValue(Stmt, PHI, BBCopyMap, LTS, getLoopForStmt(Stmt)); 1777 } 1778 1779 assert(OpCopy && "Incoming PHI value was not copied properly"); 1780 PHICopy->addIncoming(OpCopy, BBCopyEnd); 1781 } 1782 1783 void RegionGenerator::copyPHIInstruction(ScopStmt &Stmt, PHINode *PHI, 1784 ValueMapT &BBMap, 1785 LoopToScevMapT <S) { 1786 unsigned NumIncoming = PHI->getNumIncomingValues(); 1787 PHINode *PHICopy = 1788 Builder.CreatePHI(PHI->getType(), NumIncoming, "polly." + PHI->getName()); 1789 PHICopy->moveBefore(PHICopy->getParent()->getFirstNonPHI()); 1790 BBMap[PHI] = PHICopy; 1791 1792 for (BasicBlock *IncomingBB : PHI->blocks()) 1793 addOperandToPHI(Stmt, PHI, PHICopy, IncomingBB, LTS); 1794 } 1795