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