1 //===- DependenceInfo.cpp - Calculate dependency information for a Scop. --===// 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 // Calculate the data dependency relations for a Scop using ISL. 11 // 12 // The integer set library (ISL) from Sven, has a integrated dependency analysis 13 // to calculate data dependences. This pass takes advantage of this and 14 // calculate those dependences a Scop. 15 // 16 // The dependences in this pass are exact in terms that for a specific read 17 // statement instance only the last write statement instance is returned. In 18 // case of may writes a set of possible write instances is returned. This 19 // analysis will never produce redundant dependences. 20 // 21 //===----------------------------------------------------------------------===// 22 // 23 #include "polly/DependenceInfo.h" 24 #include "polly/LinkAllPasses.h" 25 #include "polly/Options.h" 26 #include "polly/ScopInfo.h" 27 #include "polly/Support/GICHelper.h" 28 #include "llvm/Support/Debug.h" 29 #include <isl/aff.h> 30 #include <isl/ctx.h> 31 #include <isl/flow.h> 32 #include <isl/map.h> 33 #include <isl/options.h> 34 #include <isl/schedule.h> 35 #include <isl/set.h> 36 #include <isl/union_map.h> 37 #include <isl/union_set.h> 38 39 using namespace polly; 40 using namespace llvm; 41 42 #define DEBUG_TYPE "polly-dependence" 43 44 static cl::opt<int> OptComputeOut( 45 "polly-dependences-computeout", 46 cl::desc("Bound the dependence analysis by a maximal amount of " 47 "computational steps (0 means no bound)"), 48 cl::Hidden, cl::init(500000), cl::ZeroOrMore, cl::cat(PollyCategory)); 49 50 static cl::opt<bool> LegalityCheckDisabled( 51 "disable-polly-legality", cl::desc("Disable polly legality check"), 52 cl::Hidden, cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory)); 53 54 static cl::opt<bool> 55 UseReductions("polly-dependences-use-reductions", 56 cl::desc("Exploit reductions in dependence analysis"), 57 cl::Hidden, cl::init(true), cl::ZeroOrMore, 58 cl::cat(PollyCategory)); 59 60 enum AnalysisType { VALUE_BASED_ANALYSIS, MEMORY_BASED_ANALYSIS }; 61 62 static cl::opt<enum AnalysisType> OptAnalysisType( 63 "polly-dependences-analysis-type", 64 cl::desc("The kind of dependence analysis to use"), 65 cl::values(clEnumValN(VALUE_BASED_ANALYSIS, "value-based", 66 "Exact dependences without transitive dependences"), 67 clEnumValN(MEMORY_BASED_ANALYSIS, "memory-based", 68 "Overapproximation of dependences"), 69 clEnumValEnd), 70 cl::Hidden, cl::init(VALUE_BASED_ANALYSIS), cl::ZeroOrMore, 71 cl::cat(PollyCategory)); 72 73 static cl::opt<Dependences::AnalyisLevel> OptAnalysisLevel( 74 "polly-dependences-analysis-level", 75 cl::desc("The level of dependence analysis"), 76 cl::values(clEnumValN(Dependences::AL_Statement, "statement-wise", 77 "Statement-level analysis"), 78 clEnumValN(Dependences::AL_Reference, "reference-wise", 79 "Memory reference level analysis that distinguish" 80 " accessed references in the same statement"), 81 clEnumValN(Dependences::AL_Access, "access-wise", 82 "Memory reference level analysis that distinguish" 83 " access instructions in the same statement"), 84 clEnumValEnd), 85 cl::Hidden, cl::init(Dependences::AL_Statement), cl::ZeroOrMore, 86 cl::cat(PollyCategory)); 87 88 //===----------------------------------------------------------------------===// 89 90 /// Tag the @p Relation domain with @p TagId 91 static __isl_give isl_map *tag(__isl_take isl_map *Relation, 92 __isl_take isl_id *TagId) { 93 isl_space *Space = isl_map_get_space(Relation); 94 Space = isl_space_drop_dims(Space, isl_dim_out, 0, isl_map_n_out(Relation)); 95 Space = isl_space_set_tuple_id(Space, isl_dim_out, TagId); 96 isl_multi_aff *Tag = isl_multi_aff_domain_map(Space); 97 Relation = isl_map_preimage_domain_multi_aff(Relation, Tag); 98 return Relation; 99 } 100 101 /// Tag the @p Relation domain with either MA->getArrayId() or 102 /// MA->getId() based on @p TagLevel 103 static __isl_give isl_map *tag(__isl_take isl_map *Relation, MemoryAccess *MA, 104 Dependences::AnalyisLevel TagLevel) { 105 if (TagLevel == Dependences::AL_Reference) 106 return tag(Relation, MA->getArrayId()); 107 108 if (TagLevel == Dependences::AL_Access) 109 return tag(Relation, MA->getId()); 110 111 // No need to tag at the statement level. 112 return Relation; 113 } 114 115 /// Collect information about the SCoP @p S. 116 static void collectInfo(Scop &S, isl_union_map **Read, isl_union_map **Write, 117 isl_union_map **MayWrite, 118 isl_union_map **AccessSchedule, 119 isl_union_map **StmtSchedule, 120 Dependences::AnalyisLevel Level) { 121 isl_space *Space = S.getParamSpace(); 122 *Read = isl_union_map_empty(isl_space_copy(Space)); 123 *Write = isl_union_map_empty(isl_space_copy(Space)); 124 *MayWrite = isl_union_map_empty(isl_space_copy(Space)); 125 *AccessSchedule = isl_union_map_empty(isl_space_copy(Space)); 126 *StmtSchedule = isl_union_map_empty(Space); 127 128 SmallPtrSet<const Value *, 8> ReductionBaseValues; 129 if (UseReductions) 130 for (ScopStmt &Stmt : S) 131 for (MemoryAccess *MA : Stmt) 132 if (MA->isReductionLike()) 133 ReductionBaseValues.insert(MA->getBaseAddr()); 134 135 for (ScopStmt &Stmt : S) { 136 for (MemoryAccess *MA : Stmt) { 137 isl_set *domcp = Stmt.getDomain(); 138 isl_map *accdom = MA->getAccessRelation(); 139 140 accdom = isl_map_intersect_domain(accdom, domcp); 141 142 if (ReductionBaseValues.count(MA->getBaseAddr())) { 143 // Wrap the access domain and adjust the schedule accordingly. 144 // 145 // An access domain like 146 // Stmt[i0, i1] -> MemAcc_A[i0 + i1] 147 // will be transformed into 148 // [Stmt[i0, i1] -> MemAcc_A[i0 + i1]] -> MemAcc_A[i0 + i1] 149 // 150 // The original schedule looks like 151 // Stmt[i0, i1] -> [0, i0, 2, i1, 0] 152 // but as we transformed the access domain we need the schedule 153 // to match the new access domains, thus we need 154 // [Stmt[i0, i1] -> MemAcc_A[i0 + i1]] -> [0, i0, 2, i1, 0] 155 isl_map *Schedule = Stmt.getSchedule(); 156 assert(Schedule && "Schedules that contain extension nodes require " 157 "special handling."); 158 Schedule = isl_map_apply_domain( 159 Schedule, 160 isl_map_reverse(isl_map_domain_map(isl_map_copy(accdom)))); 161 accdom = isl_map_range_map(accdom); 162 163 *AccessSchedule = isl_union_map_add_map(*AccessSchedule, Schedule); 164 } else { 165 accdom = tag(accdom, MA, Level); 166 if (Level > Dependences::AL_Statement) { 167 auto *StmtScheduleMap = Stmt.getSchedule(); 168 assert(StmtScheduleMap && "Schedules that contain extension nodes " 169 "require special handling."); 170 isl_map *Schedule = tag(StmtScheduleMap, MA, Level); 171 *StmtSchedule = isl_union_map_add_map(*StmtSchedule, Schedule); 172 } 173 } 174 175 if (MA->isRead()) 176 *Read = isl_union_map_add_map(*Read, accdom); 177 else 178 *Write = isl_union_map_add_map(*Write, accdom); 179 } 180 181 if (!ReductionBaseValues.empty() && Level == Dependences::AL_Statement) 182 *StmtSchedule = isl_union_map_add_map(*StmtSchedule, Stmt.getSchedule()); 183 } 184 185 *StmtSchedule = 186 isl_union_map_intersect_params(*StmtSchedule, S.getAssumedContext()); 187 188 *Read = isl_union_map_coalesce(*Read); 189 *Write = isl_union_map_coalesce(*Write); 190 *MayWrite = isl_union_map_coalesce(*MayWrite); 191 } 192 193 /// Fix all dimension of @p Zero to 0 and add it to @p user 194 static isl_stat fixSetToZero(__isl_take isl_set *Zero, void *user) { 195 isl_union_set **User = (isl_union_set **)user; 196 for (unsigned i = 0; i < isl_set_dim(Zero, isl_dim_set); i++) 197 Zero = isl_set_fix_si(Zero, isl_dim_set, i, 0); 198 *User = isl_union_set_add_set(*User, Zero); 199 return isl_stat_ok; 200 } 201 202 /// Compute the privatization dependences for a given dependency @p Map 203 /// 204 /// Privatization dependences are widened original dependences which originate 205 /// or end in a reduction access. To compute them we apply the transitive close 206 /// of the reduction dependences (which maps each iteration of a reduction 207 /// statement to all following ones) on the RAW/WAR/WAW dependences. The 208 /// dependences which start or end at a reduction statement will be extended to 209 /// depend on all following reduction statement iterations as well. 210 /// Note: "Following" here means according to the reduction dependences. 211 /// 212 /// For the input: 213 /// 214 /// S0: *sum = 0; 215 /// for (int i = 0; i < 1024; i++) 216 /// S1: *sum += i; 217 /// S2: *sum = *sum * 3; 218 /// 219 /// we have the following dependences before we add privatization dependences: 220 /// 221 /// RAW: 222 /// { S0[] -> S1[0]; S1[1023] -> S2[] } 223 /// WAR: 224 /// { } 225 /// WAW: 226 /// { S0[] -> S1[0]; S1[1024] -> S2[] } 227 /// RED: 228 /// { S1[i0] -> S1[1 + i0] : i0 >= 0 and i0 <= 1022 } 229 /// 230 /// and afterwards: 231 /// 232 /// RAW: 233 /// { S0[] -> S1[i0] : i0 >= 0 and i0 <= 1023; 234 /// S1[i0] -> S2[] : i0 >= 0 and i0 <= 1023} 235 /// WAR: 236 /// { } 237 /// WAW: 238 /// { S0[] -> S1[i0] : i0 >= 0 and i0 <= 1023; 239 /// S1[i0] -> S2[] : i0 >= 0 and i0 <= 1023} 240 /// RED: 241 /// { S1[i0] -> S1[1 + i0] : i0 >= 0 and i0 <= 1022 } 242 /// 243 /// Note: This function also computes the (reverse) transitive closure of the 244 /// reduction dependences. 245 void Dependences::addPrivatizationDependences() { 246 isl_union_map *PrivRAW, *PrivWAW, *PrivWAR; 247 248 // The transitive closure might be over approximated, thus could lead to 249 // dependency cycles in the privatization dependences. To make sure this 250 // will not happen we remove all negative dependences after we computed 251 // the transitive closure. 252 TC_RED = isl_union_map_transitive_closure(isl_union_map_copy(RED), nullptr); 253 254 // FIXME: Apply the current schedule instead of assuming the identity schedule 255 // here. The current approach is only valid as long as we compute the 256 // dependences only with the initial (identity schedule). Any other 257 // schedule could change "the direction of the backward dependences" we 258 // want to eliminate here. 259 isl_union_set *UDeltas = isl_union_map_deltas(isl_union_map_copy(TC_RED)); 260 isl_union_set *Universe = isl_union_set_universe(isl_union_set_copy(UDeltas)); 261 isl_union_set *Zero = isl_union_set_empty(isl_union_set_get_space(Universe)); 262 isl_union_set_foreach_set(Universe, fixSetToZero, &Zero); 263 isl_union_map *NonPositive = isl_union_set_lex_le_union_set(UDeltas, Zero); 264 265 TC_RED = isl_union_map_subtract(TC_RED, NonPositive); 266 267 TC_RED = isl_union_map_union( 268 TC_RED, isl_union_map_reverse(isl_union_map_copy(TC_RED))); 269 TC_RED = isl_union_map_coalesce(TC_RED); 270 271 isl_union_map **Maps[] = {&RAW, &WAW, &WAR}; 272 isl_union_map **PrivMaps[] = {&PrivRAW, &PrivWAW, &PrivWAR}; 273 for (unsigned u = 0; u < 3; u++) { 274 isl_union_map **Map = Maps[u], **PrivMap = PrivMaps[u]; 275 276 *PrivMap = isl_union_map_apply_range(isl_union_map_copy(*Map), 277 isl_union_map_copy(TC_RED)); 278 *PrivMap = isl_union_map_union( 279 *PrivMap, isl_union_map_apply_range(isl_union_map_copy(TC_RED), 280 isl_union_map_copy(*Map))); 281 282 *Map = isl_union_map_union(*Map, *PrivMap); 283 } 284 285 isl_union_set_free(Universe); 286 } 287 288 static isl_stat getMaxScheduleDim(__isl_take isl_map *Map, void *User) { 289 unsigned int *MaxScheduleDim = (unsigned int *)User; 290 *MaxScheduleDim = std::max(*MaxScheduleDim, isl_map_dim(Map, isl_dim_out)); 291 isl_map_free(Map); 292 return isl_stat_ok; 293 } 294 295 static __isl_give isl_union_map * 296 addZeroPaddingToSchedule(__isl_take isl_union_map *Schedule) { 297 unsigned int MaxScheduleDim = 0; 298 299 isl_union_map_foreach_map(Schedule, getMaxScheduleDim, &MaxScheduleDim); 300 301 auto ExtensionMap = isl_union_map_empty(isl_union_map_get_space(Schedule)); 302 for (unsigned int i = 0; i <= MaxScheduleDim; i++) { 303 auto *Map = isl_map_identity( 304 isl_space_alloc(isl_union_map_get_ctx(Schedule), 0, i, i)); 305 Map = isl_map_add_dims(Map, isl_dim_out, MaxScheduleDim - i); 306 for (unsigned int j = 0; j < MaxScheduleDim - i; j++) 307 Map = isl_map_fix_si(Map, isl_dim_out, i + j, 0); 308 309 ExtensionMap = isl_union_map_add_map(ExtensionMap, Map); 310 } 311 Schedule = isl_union_map_apply_range(Schedule, ExtensionMap); 312 313 return Schedule; 314 } 315 316 static __isl_give isl_union_flow *buildFlow(__isl_keep isl_union_map *Snk, 317 __isl_keep isl_union_map *Src, 318 __isl_keep isl_union_map *MaySrc, 319 __isl_keep isl_schedule *Schedule) { 320 isl_union_access_info *AI; 321 322 AI = isl_union_access_info_from_sink(isl_union_map_copy(Snk)); 323 AI = isl_union_access_info_set_may_source(AI, isl_union_map_copy(MaySrc)); 324 if (Src) 325 AI = isl_union_access_info_set_must_source(AI, isl_union_map_copy(Src)); 326 AI = isl_union_access_info_set_schedule(AI, isl_schedule_copy(Schedule)); 327 auto Flow = isl_union_access_info_compute_flow(AI); 328 DEBUG(if (!Flow) dbgs() << "last error: " 329 << isl_ctx_last_error(isl_schedule_get_ctx(Schedule)) 330 << '\n';); 331 return Flow; 332 } 333 334 void Dependences::calculateDependences(Scop &S) { 335 isl_union_map *Read, *Write, *MayWrite, *AccessSchedule, *StmtSchedule; 336 isl_schedule *Schedule; 337 338 DEBUG(dbgs() << "Scop: \n" << S << "\n"); 339 340 collectInfo(S, &Read, &Write, &MayWrite, &AccessSchedule, &StmtSchedule, 341 Level); 342 343 bool HasReductions = !isl_union_map_is_empty(AccessSchedule); 344 345 DEBUG(dbgs() << "Read: " << Read << '\n'; 346 dbgs() << "Write: " << Write << '\n'; 347 dbgs() << "MayWrite: " << MayWrite << '\n'; 348 dbgs() << "AccessSchedule: " << AccessSchedule << '\n'; 349 dbgs() << "StmtSchedule: " << StmtSchedule << '\n';); 350 351 if (!HasReductions) { 352 isl_union_map_free(AccessSchedule); 353 Schedule = S.getScheduleTree(); 354 // Tag the schedule tree if we want fine-grain dependence info 355 if (Level > AL_Statement) { 356 auto TaggedDom = isl_union_map_domain((isl_union_map_copy(StmtSchedule))); 357 auto TaggedMap = isl_union_set_unwrap(TaggedDom); 358 auto Tags = isl_union_map_domain_map_union_pw_multi_aff(TaggedMap); 359 Schedule = isl_schedule_pullback_union_pw_multi_aff(Schedule, Tags); 360 } 361 } else { 362 auto *ScheduleMap = 363 isl_union_map_union(AccessSchedule, isl_union_map_copy(StmtSchedule)); 364 Schedule = isl_schedule_from_domain( 365 isl_union_map_domain(isl_union_map_copy(ScheduleMap))); 366 if (!isl_union_map_is_empty(ScheduleMap)) { 367 ScheduleMap = addZeroPaddingToSchedule(ScheduleMap); 368 Schedule = isl_schedule_insert_partial_schedule( 369 Schedule, isl_multi_union_pw_aff_from_union_map(ScheduleMap)); 370 } else { 371 isl_union_map_free(ScheduleMap); 372 } 373 } 374 375 long MaxOpsOld = isl_ctx_get_max_operations(IslCtx.get()); 376 if (OptComputeOut) { 377 isl_ctx_reset_operations(IslCtx.get()); 378 isl_ctx_set_max_operations(IslCtx.get(), OptComputeOut); 379 } 380 381 auto OnErrorStatus = isl_options_get_on_error(IslCtx.get()); 382 isl_options_set_on_error(IslCtx.get(), ISL_ON_ERROR_CONTINUE); 383 384 DEBUG(dbgs() << "Read: " << Read << "\n"; 385 dbgs() << "Write: " << Write << "\n"; 386 dbgs() << "MayWrite: " << MayWrite << "\n"; 387 dbgs() << "Schedule: " << Schedule << "\n"); 388 389 RAW = WAW = WAR = RED = nullptr; 390 391 if (OptAnalysisType == VALUE_BASED_ANALYSIS) { 392 isl_union_flow *Flow; 393 394 Flow = buildFlow(Read, Write, MayWrite, Schedule); 395 396 RAW = isl_union_flow_get_must_dependence(Flow); 397 isl_union_flow_free(Flow); 398 399 Flow = buildFlow(Write, Write, Read, Schedule); 400 401 WAW = isl_union_flow_get_must_dependence(Flow); 402 WAR = isl_union_flow_get_may_dependence(Flow); 403 404 // This subtraction is needed to obtain the same results as were given by 405 // isl_union_map_compute_flow. For large sets this may add some compile-time 406 // cost. As there does not seem to be a need to distinguish between WAW and 407 // WAR, refactoring Polly to only track general non-flow dependences may 408 // improve performance. 409 WAR = isl_union_map_subtract(WAR, isl_union_map_copy(WAW)); 410 411 isl_union_flow_free(Flow); 412 isl_schedule_free(Schedule); 413 } else { 414 isl_union_flow *Flow; 415 416 Write = isl_union_map_union(Write, isl_union_map_copy(MayWrite)); 417 418 Flow = buildFlow(Read, nullptr, Write, Schedule); 419 420 RAW = isl_union_flow_get_may_dependence(Flow); 421 isl_union_flow_free(Flow); 422 423 Flow = buildFlow(Write, nullptr, Read, Schedule); 424 425 WAR = isl_union_flow_get_may_dependence(Flow); 426 isl_union_flow_free(Flow); 427 428 Flow = buildFlow(Write, nullptr, Write, Schedule); 429 430 WAW = isl_union_flow_get_may_dependence(Flow); 431 isl_union_flow_free(Flow); 432 isl_schedule_free(Schedule); 433 } 434 435 isl_union_map_free(MayWrite); 436 isl_union_map_free(Write); 437 isl_union_map_free(Read); 438 439 RAW = isl_union_map_coalesce(RAW); 440 WAW = isl_union_map_coalesce(WAW); 441 WAR = isl_union_map_coalesce(WAR); 442 443 if (isl_ctx_last_error(IslCtx.get()) == isl_error_quota) { 444 isl_union_map_free(RAW); 445 isl_union_map_free(WAW); 446 isl_union_map_free(WAR); 447 RAW = WAW = WAR = nullptr; 448 isl_ctx_reset_error(IslCtx.get()); 449 } 450 isl_options_set_on_error(IslCtx.get(), OnErrorStatus); 451 isl_ctx_reset_operations(IslCtx.get()); 452 isl_ctx_set_max_operations(IslCtx.get(), MaxOpsOld); 453 454 // Drop out early, as the remaining computations are only needed for 455 // reduction dependences or dependences that are finer than statement 456 // level dependences. 457 if (!HasReductions && Level == AL_Statement) { 458 TC_RED = isl_union_map_empty(isl_union_map_get_space(StmtSchedule)); 459 isl_union_map_free(StmtSchedule); 460 return; 461 } 462 463 isl_union_map *STMT_RAW, *STMT_WAW, *STMT_WAR; 464 STMT_RAW = isl_union_map_intersect_domain( 465 isl_union_map_copy(RAW), 466 isl_union_map_domain(isl_union_map_copy(StmtSchedule))); 467 STMT_WAW = isl_union_map_intersect_domain( 468 isl_union_map_copy(WAW), 469 isl_union_map_domain(isl_union_map_copy(StmtSchedule))); 470 STMT_WAR = isl_union_map_intersect_domain(isl_union_map_copy(WAR), 471 isl_union_map_domain(StmtSchedule)); 472 DEBUG({ 473 dbgs() << "Wrapped Dependences:\n"; 474 dump(); 475 dbgs() << "\n"; 476 }); 477 478 // To handle reduction dependences we proceed as follows: 479 // 1) Aggregate all possible reduction dependences, namely all self 480 // dependences on reduction like statements. 481 // 2) Intersect them with the actual RAW & WAW dependences to the get the 482 // actual reduction dependences. This will ensure the load/store memory 483 // addresses were __identical__ in the two iterations of the statement. 484 // 3) Relax the original RAW and WAW dependences by subtracting the actual 485 // reduction dependences. Binary reductions (sum += A[i]) cause both, and 486 // the same, RAW and WAW dependences. 487 // 4) Add the privatization dependences which are widened versions of 488 // already present dependences. They model the effect of manual 489 // privatization at the outermost possible place (namely after the last 490 // write and before the first access to a reduction location). 491 492 // Step 1) 493 RED = isl_union_map_empty(isl_union_map_get_space(RAW)); 494 for (ScopStmt &Stmt : S) { 495 for (MemoryAccess *MA : Stmt) { 496 if (!MA->isReductionLike()) 497 continue; 498 isl_set *AccDomW = isl_map_wrap(MA->getAccessRelation()); 499 isl_map *Identity = 500 isl_map_from_domain_and_range(isl_set_copy(AccDomW), AccDomW); 501 RED = isl_union_map_add_map(RED, Identity); 502 } 503 } 504 505 // Step 2) 506 RED = isl_union_map_intersect(RED, isl_union_map_copy(RAW)); 507 RED = isl_union_map_intersect(RED, isl_union_map_copy(WAW)); 508 509 if (!isl_union_map_is_empty(RED)) { 510 511 // Step 3) 512 RAW = isl_union_map_subtract(RAW, isl_union_map_copy(RED)); 513 WAW = isl_union_map_subtract(WAW, isl_union_map_copy(RED)); 514 515 // Step 4) 516 addPrivatizationDependences(); 517 } 518 519 DEBUG({ 520 dbgs() << "Final Wrapped Dependences:\n"; 521 dump(); 522 dbgs() << "\n"; 523 }); 524 525 // RED_SIN is used to collect all reduction dependences again after we 526 // split them according to the causing memory accesses. The current assumption 527 // is that our method of splitting will not have any leftovers. In the end 528 // we validate this assumption until we have more confidence in this method. 529 isl_union_map *RED_SIN = isl_union_map_empty(isl_union_map_get_space(RAW)); 530 531 // For each reduction like memory access, check if there are reduction 532 // dependences with the access relation of the memory access as a domain 533 // (wrapped space!). If so these dependences are caused by this memory access. 534 // We then move this portion of reduction dependences back to the statement -> 535 // statement space and add a mapping from the memory access to these 536 // dependences. 537 for (ScopStmt &Stmt : S) { 538 for (MemoryAccess *MA : Stmt) { 539 if (!MA->isReductionLike()) 540 continue; 541 542 isl_set *AccDomW = isl_map_wrap(MA->getAccessRelation()); 543 isl_union_map *AccRedDepU = isl_union_map_intersect_domain( 544 isl_union_map_copy(TC_RED), isl_union_set_from_set(AccDomW)); 545 if (isl_union_map_is_empty(AccRedDepU)) { 546 isl_union_map_free(AccRedDepU); 547 continue; 548 } 549 550 isl_map *AccRedDep = isl_map_from_union_map(AccRedDepU); 551 RED_SIN = isl_union_map_add_map(RED_SIN, isl_map_copy(AccRedDep)); 552 AccRedDep = isl_map_zip(AccRedDep); 553 AccRedDep = isl_set_unwrap(isl_map_domain(AccRedDep)); 554 setReductionDependences(MA, AccRedDep); 555 } 556 } 557 558 assert(isl_union_map_is_equal(RED_SIN, TC_RED) && 559 "Intersecting the reduction dependence domain with the wrapped access " 560 "relation is not enough, we need to loosen the access relation also"); 561 isl_union_map_free(RED_SIN); 562 563 RAW = isl_union_map_zip(RAW); 564 WAW = isl_union_map_zip(WAW); 565 WAR = isl_union_map_zip(WAR); 566 RED = isl_union_map_zip(RED); 567 TC_RED = isl_union_map_zip(TC_RED); 568 569 DEBUG({ 570 dbgs() << "Zipped Dependences:\n"; 571 dump(); 572 dbgs() << "\n"; 573 }); 574 575 RAW = isl_union_set_unwrap(isl_union_map_domain(RAW)); 576 WAW = isl_union_set_unwrap(isl_union_map_domain(WAW)); 577 WAR = isl_union_set_unwrap(isl_union_map_domain(WAR)); 578 RED = isl_union_set_unwrap(isl_union_map_domain(RED)); 579 TC_RED = isl_union_set_unwrap(isl_union_map_domain(TC_RED)); 580 581 DEBUG({ 582 dbgs() << "Unwrapped Dependences:\n"; 583 dump(); 584 dbgs() << "\n"; 585 }); 586 587 RAW = isl_union_map_union(RAW, STMT_RAW); 588 WAW = isl_union_map_union(WAW, STMT_WAW); 589 WAR = isl_union_map_union(WAR, STMT_WAR); 590 591 RAW = isl_union_map_coalesce(RAW); 592 WAW = isl_union_map_coalesce(WAW); 593 WAR = isl_union_map_coalesce(WAR); 594 RED = isl_union_map_coalesce(RED); 595 TC_RED = isl_union_map_coalesce(TC_RED); 596 597 DEBUG(dump()); 598 } 599 600 bool Dependences::isValidSchedule(Scop &S, 601 StatementToIslMapTy *NewSchedule) const { 602 if (LegalityCheckDisabled) 603 return true; 604 605 isl_union_map *Dependences = getDependences(TYPE_RAW | TYPE_WAW | TYPE_WAR); 606 isl_space *Space = S.getParamSpace(); 607 isl_union_map *Schedule = isl_union_map_empty(Space); 608 609 isl_space *ScheduleSpace = nullptr; 610 611 for (ScopStmt &Stmt : S) { 612 isl_map *StmtScat; 613 614 if (NewSchedule->find(&Stmt) == NewSchedule->end()) 615 StmtScat = Stmt.getSchedule(); 616 else 617 StmtScat = isl_map_copy((*NewSchedule)[&Stmt]); 618 assert(StmtScat && 619 "Schedules that contain extension nodes require special handling."); 620 621 if (!ScheduleSpace) 622 ScheduleSpace = isl_space_range(isl_map_get_space(StmtScat)); 623 624 Schedule = isl_union_map_add_map(Schedule, StmtScat); 625 } 626 627 Dependences = 628 isl_union_map_apply_domain(Dependences, isl_union_map_copy(Schedule)); 629 Dependences = isl_union_map_apply_range(Dependences, Schedule); 630 631 isl_set *Zero = isl_set_universe(isl_space_copy(ScheduleSpace)); 632 for (unsigned i = 0; i < isl_set_dim(Zero, isl_dim_set); i++) 633 Zero = isl_set_fix_si(Zero, isl_dim_set, i, 0); 634 635 isl_union_set *UDeltas = isl_union_map_deltas(Dependences); 636 isl_set *Deltas = isl_union_set_extract_set(UDeltas, ScheduleSpace); 637 isl_union_set_free(UDeltas); 638 639 isl_map *NonPositive = isl_set_lex_le_set(Deltas, Zero); 640 bool IsValid = isl_map_is_empty(NonPositive); 641 isl_map_free(NonPositive); 642 643 return IsValid; 644 } 645 646 // Check if the current scheduling dimension is parallel. 647 // 648 // We check for parallelism by verifying that the loop does not carry any 649 // dependences. 650 // 651 // Parallelism test: if the distance is zero in all outer dimensions, then it 652 // has to be zero in the current dimension as well. 653 // 654 // Implementation: first, translate dependences into time space, then force 655 // outer dimensions to be equal. If the distance is zero in the current 656 // dimension, then the loop is parallel. The distance is zero in the current 657 // dimension if it is a subset of a map with equal values for the current 658 // dimension. 659 bool Dependences::isParallel(isl_union_map *Schedule, isl_union_map *Deps, 660 isl_pw_aff **MinDistancePtr) const { 661 isl_set *Deltas, *Distance; 662 isl_map *ScheduleDeps; 663 unsigned Dimension; 664 bool IsParallel; 665 666 Deps = isl_union_map_apply_range(Deps, isl_union_map_copy(Schedule)); 667 Deps = isl_union_map_apply_domain(Deps, isl_union_map_copy(Schedule)); 668 669 if (isl_union_map_is_empty(Deps)) { 670 isl_union_map_free(Deps); 671 return true; 672 } 673 674 ScheduleDeps = isl_map_from_union_map(Deps); 675 Dimension = isl_map_dim(ScheduleDeps, isl_dim_out) - 1; 676 677 for (unsigned i = 0; i < Dimension; i++) 678 ScheduleDeps = isl_map_equate(ScheduleDeps, isl_dim_out, i, isl_dim_in, i); 679 680 Deltas = isl_map_deltas(ScheduleDeps); 681 Distance = isl_set_universe(isl_set_get_space(Deltas)); 682 683 // [0, ..., 0, +] - All zeros and last dimension larger than zero 684 for (unsigned i = 0; i < Dimension; i++) 685 Distance = isl_set_fix_si(Distance, isl_dim_set, i, 0); 686 687 Distance = isl_set_lower_bound_si(Distance, isl_dim_set, Dimension, 1); 688 Distance = isl_set_intersect(Distance, Deltas); 689 690 IsParallel = isl_set_is_empty(Distance); 691 if (IsParallel || !MinDistancePtr) { 692 isl_set_free(Distance); 693 return IsParallel; 694 } 695 696 Distance = isl_set_project_out(Distance, isl_dim_set, 0, Dimension); 697 Distance = isl_set_coalesce(Distance); 698 699 // This last step will compute a expression for the minimal value in the 700 // distance polyhedron Distance with regards to the first (outer most) 701 // dimension. 702 *MinDistancePtr = isl_pw_aff_coalesce(isl_set_dim_min(Distance, 0)); 703 704 return false; 705 } 706 707 static void printDependencyMap(raw_ostream &OS, __isl_keep isl_union_map *DM) { 708 if (DM) 709 OS << DM << "\n"; 710 else 711 OS << "n/a\n"; 712 } 713 714 void Dependences::print(raw_ostream &OS) const { 715 OS << "\tRAW dependences:\n\t\t"; 716 printDependencyMap(OS, RAW); 717 OS << "\tWAR dependences:\n\t\t"; 718 printDependencyMap(OS, WAR); 719 OS << "\tWAW dependences:\n\t\t"; 720 printDependencyMap(OS, WAW); 721 OS << "\tReduction dependences:\n\t\t"; 722 printDependencyMap(OS, RED); 723 OS << "\tTransitive closure of reduction dependences:\n\t\t"; 724 printDependencyMap(OS, TC_RED); 725 } 726 727 void Dependences::dump() const { print(dbgs()); } 728 729 void Dependences::releaseMemory() { 730 isl_union_map_free(RAW); 731 isl_union_map_free(WAR); 732 isl_union_map_free(WAW); 733 isl_union_map_free(RED); 734 isl_union_map_free(TC_RED); 735 736 RED = RAW = WAR = WAW = TC_RED = nullptr; 737 738 for (auto &ReductionDeps : ReductionDependences) 739 isl_map_free(ReductionDeps.second); 740 ReductionDependences.clear(); 741 } 742 743 __isl_give isl_union_map *Dependences::getDependences(int Kinds) const { 744 assert(hasValidDependences() && "No valid dependences available"); 745 isl_space *Space = isl_union_map_get_space(RAW); 746 isl_union_map *Deps = isl_union_map_empty(Space); 747 748 if (Kinds & TYPE_RAW) 749 Deps = isl_union_map_union(Deps, isl_union_map_copy(RAW)); 750 751 if (Kinds & TYPE_WAR) 752 Deps = isl_union_map_union(Deps, isl_union_map_copy(WAR)); 753 754 if (Kinds & TYPE_WAW) 755 Deps = isl_union_map_union(Deps, isl_union_map_copy(WAW)); 756 757 if (Kinds & TYPE_RED) 758 Deps = isl_union_map_union(Deps, isl_union_map_copy(RED)); 759 760 if (Kinds & TYPE_TC_RED) 761 Deps = isl_union_map_union(Deps, isl_union_map_copy(TC_RED)); 762 763 Deps = isl_union_map_coalesce(Deps); 764 Deps = isl_union_map_detect_equalities(Deps); 765 return Deps; 766 } 767 768 bool Dependences::hasValidDependences() const { 769 return (RAW != nullptr) && (WAR != nullptr) && (WAW != nullptr); 770 } 771 772 __isl_give isl_map * 773 Dependences::getReductionDependences(MemoryAccess *MA) const { 774 return isl_map_copy(ReductionDependences.lookup(MA)); 775 } 776 777 void Dependences::setReductionDependences(MemoryAccess *MA, isl_map *D) { 778 assert(ReductionDependences.count(MA) == 0 && 779 "Reduction dependences set twice!"); 780 ReductionDependences[MA] = D; 781 } 782 783 const Dependences & 784 DependenceInfo::getDependences(Dependences::AnalyisLevel Level) { 785 if (Dependences *d = D[Level].get()) 786 return *d; 787 788 return recomputeDependences(Level); 789 } 790 791 const Dependences & 792 DependenceInfo::recomputeDependences(Dependences::AnalyisLevel Level) { 793 D[Level].reset(new Dependences(S->getSharedIslCtx(), Level)); 794 D[Level]->calculateDependences(*S); 795 return *D[Level]; 796 } 797 798 bool DependenceInfo::runOnScop(Scop &ScopVar) { 799 S = &ScopVar; 800 return false; 801 } 802 803 /// Print the dependences for the given SCoP to @p OS. 804 805 void polly::DependenceInfo::printScop(raw_ostream &OS, Scop &S) const { 806 if (auto d = D[OptAnalysisLevel].get()) { 807 d->print(OS); 808 return; 809 } 810 811 // Otherwise create the dependences on-the-fly and print it 812 Dependences D(S.getSharedIslCtx(), OptAnalysisLevel); 813 D.calculateDependences(S); 814 D.print(OS); 815 } 816 817 void DependenceInfo::getAnalysisUsage(AnalysisUsage &AU) const { 818 AU.addRequiredTransitive<ScopInfoRegionPass>(); 819 AU.setPreservesAll(); 820 } 821 822 char DependenceInfo::ID = 0; 823 824 Pass *polly::createDependenceInfoPass() { return new DependenceInfo(); } 825 826 INITIALIZE_PASS_BEGIN(DependenceInfo, "polly-dependences", 827 "Polly - Calculate dependences", false, false); 828 INITIALIZE_PASS_DEPENDENCY(ScopInfoRegionPass); 829 INITIALIZE_PASS_END(DependenceInfo, "polly-dependences", 830 "Polly - Calculate dependences", false, false) 831 832 //===----------------------------------------------------------------------===// 833 const Dependences & 834 DependenceInfoWrapperPass::getDependences(Scop *S, 835 Dependences::AnalyisLevel Level) { 836 auto It = ScopToDepsMap.find(S); 837 if (It != ScopToDepsMap.end()) 838 if (It->second) { 839 if (It->second->getDependenceLevel() == Level) 840 return *It->second.get(); 841 } 842 return recomputeDependences(S, Level); 843 } 844 845 const Dependences &DependenceInfoWrapperPass::recomputeDependences( 846 Scop *S, Dependences::AnalyisLevel Level) { 847 std::unique_ptr<Dependences> D(new Dependences(S->getSharedIslCtx(), Level)); 848 D->calculateDependences(*S); 849 auto Inserted = ScopToDepsMap.insert(std::make_pair(S, std::move(D))); 850 return *Inserted.first->second; 851 } 852 853 bool DependenceInfoWrapperPass::runOnFunction(Function &F) { 854 auto &SI = getAnalysis<ScopInfoWrapperPass>(); 855 for (auto &It : SI) { 856 assert(It.second && "Invalid SCoP object!"); 857 recomputeDependences(It.second.get(), Dependences::AL_Access); 858 } 859 return false; 860 } 861 862 void DependenceInfoWrapperPass::print(raw_ostream &OS, const Module *M) const { 863 for (auto &It : ScopToDepsMap) { 864 assert((It.first && It.second) && "Invalid Scop or Dependence object!\n"); 865 It.second->print(OS); 866 } 867 } 868 869 void DependenceInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 870 AU.addRequiredTransitive<ScopInfoWrapperPass>(); 871 AU.setPreservesAll(); 872 } 873 874 char DependenceInfoWrapperPass::ID = 0; 875 876 Pass *polly::createDependenceInfoWrapperPassPass() { 877 return new DependenceInfoWrapperPass(); 878 } 879 880 INITIALIZE_PASS_BEGIN( 881 DependenceInfoWrapperPass, "polly-function-dependences", 882 "Polly - Calculate dependences for all the SCoPs of a function", false, 883 false) 884 INITIALIZE_PASS_DEPENDENCY(ScopInfoWrapperPass); 885 INITIALIZE_PASS_END( 886 DependenceInfoWrapperPass, "polly-function-dependences", 887 "Polly - Calculate dependences for all the SCoPs of a function", false, 888 false) 889