1 2 #include "polly/Support/SCEVValidator.h" 3 #include "polly/ScopInfo.h" 4 #include "llvm/Analysis/RegionInfo.h" 5 #include "llvm/Analysis/ScalarEvolution.h" 6 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 7 #include "llvm/Support/Debug.h" 8 9 using namespace llvm; 10 using namespace polly; 11 12 #define DEBUG_TYPE "polly-scev-validator" 13 14 namespace SCEVType { 15 /// The type of a SCEV 16 /// 17 /// To check for the validity of a SCEV we assign to each SCEV a type. The 18 /// possible types are INT, PARAM, IV and INVALID. The order of the types is 19 /// important. The subexpressions of SCEV with a type X can only have a type 20 /// that is smaller or equal than X. 21 enum TYPE { 22 // An integer value. 23 INT, 24 25 // An expression that is constant during the execution of the Scop, 26 // but that may depend on parameters unknown at compile time. 27 PARAM, 28 29 // An expression that may change during the execution of the SCoP. 30 IV, 31 32 // An invalid expression. 33 INVALID 34 }; 35 } // namespace SCEVType 36 37 /// The result the validator returns for a SCEV expression. 38 class ValidatorResult { 39 /// The type of the expression 40 SCEVType::TYPE Type; 41 42 /// The set of Parameters in the expression. 43 ParameterSetTy Parameters; 44 45 public: 46 /// The copy constructor 47 ValidatorResult(const ValidatorResult &Source) { 48 Type = Source.Type; 49 Parameters = Source.Parameters; 50 } 51 52 /// Construct a result with a certain type and no parameters. 53 ValidatorResult(SCEVType::TYPE Type) : Type(Type) { 54 assert(Type != SCEVType::PARAM && "Did you forget to pass the parameter"); 55 } 56 57 /// Construct a result with a certain type and a single parameter. 58 ValidatorResult(SCEVType::TYPE Type, const SCEV *Expr) : Type(Type) { 59 Parameters.insert(Expr); 60 } 61 62 /// Get the type of the ValidatorResult. 63 SCEVType::TYPE getType() { return Type; } 64 65 /// Is the analyzed SCEV constant during the execution of the SCoP. 66 bool isConstant() { return Type == SCEVType::INT || Type == SCEVType::PARAM; } 67 68 /// Is the analyzed SCEV valid. 69 bool isValid() { return Type != SCEVType::INVALID; } 70 71 /// Is the analyzed SCEV of Type IV. 72 bool isIV() { return Type == SCEVType::IV; } 73 74 /// Is the analyzed SCEV of Type INT. 75 bool isINT() { return Type == SCEVType::INT; } 76 77 /// Is the analyzed SCEV of Type PARAM. 78 bool isPARAM() { return Type == SCEVType::PARAM; } 79 80 /// Get the parameters of this validator result. 81 const ParameterSetTy &getParameters() { return Parameters; } 82 83 /// Add the parameters of Source to this result. 84 void addParamsFrom(const ValidatorResult &Source) { 85 Parameters.insert(Source.Parameters.begin(), Source.Parameters.end()); 86 } 87 88 /// Merge a result. 89 /// 90 /// This means to merge the parameters and to set the Type to the most 91 /// specific Type that matches both. 92 void merge(const ValidatorResult &ToMerge) { 93 Type = std::max(Type, ToMerge.Type); 94 addParamsFrom(ToMerge); 95 } 96 97 void print(raw_ostream &OS) { 98 switch (Type) { 99 case SCEVType::INT: 100 OS << "SCEVType::INT"; 101 break; 102 case SCEVType::PARAM: 103 OS << "SCEVType::PARAM"; 104 break; 105 case SCEVType::IV: 106 OS << "SCEVType::IV"; 107 break; 108 case SCEVType::INVALID: 109 OS << "SCEVType::INVALID"; 110 break; 111 } 112 } 113 }; 114 115 raw_ostream &operator<<(raw_ostream &OS, class ValidatorResult &VR) { 116 VR.print(OS); 117 return OS; 118 } 119 120 /// Check if a SCEV is valid in a SCoP. 121 struct SCEVValidator 122 : public SCEVVisitor<SCEVValidator, class ValidatorResult> { 123 private: 124 const Region *R; 125 Loop *Scope; 126 ScalarEvolution &SE; 127 InvariantLoadsSetTy *ILS; 128 129 public: 130 SCEVValidator(const Region *R, Loop *Scope, ScalarEvolution &SE, 131 InvariantLoadsSetTy *ILS) 132 : R(R), Scope(Scope), SE(SE), ILS(ILS) {} 133 134 class ValidatorResult visitConstant(const SCEVConstant *Constant) { 135 return ValidatorResult(SCEVType::INT); 136 } 137 138 class ValidatorResult visitTruncateExpr(const SCEVTruncateExpr *Expr) { 139 return visit(Expr->getOperand()); 140 } 141 142 class ValidatorResult visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 143 return visit(Expr->getOperand()); 144 } 145 146 class ValidatorResult visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 147 return visit(Expr->getOperand()); 148 } 149 150 class ValidatorResult visitAddExpr(const SCEVAddExpr *Expr) { 151 ValidatorResult Return(SCEVType::INT); 152 153 for (int i = 0, e = Expr->getNumOperands(); i < e; ++i) { 154 ValidatorResult Op = visit(Expr->getOperand(i)); 155 Return.merge(Op); 156 157 // Early exit. 158 if (!Return.isValid()) 159 break; 160 } 161 162 return Return; 163 } 164 165 class ValidatorResult visitMulExpr(const SCEVMulExpr *Expr) { 166 ValidatorResult Return(SCEVType::INT); 167 168 bool HasMultipleParams = false; 169 170 for (int i = 0, e = Expr->getNumOperands(); i < e; ++i) { 171 ValidatorResult Op = visit(Expr->getOperand(i)); 172 173 if (Op.isINT()) 174 continue; 175 176 if (Op.isPARAM() && Return.isPARAM()) { 177 HasMultipleParams = true; 178 continue; 179 } 180 181 if ((Op.isIV() || Op.isPARAM()) && !Return.isINT()) { 182 DEBUG(dbgs() << "INVALID: More than one non-int operand in MulExpr\n" 183 << "\tExpr: " << *Expr << "\n" 184 << "\tPrevious expression type: " << Return << "\n" 185 << "\tNext operand (" << Op 186 << "): " << *Expr->getOperand(i) << "\n"); 187 188 return ValidatorResult(SCEVType::INVALID); 189 } 190 191 Return.merge(Op); 192 } 193 194 if (HasMultipleParams && Return.isValid()) 195 return ValidatorResult(SCEVType::PARAM, Expr); 196 197 return Return; 198 } 199 200 class ValidatorResult visitAddRecExpr(const SCEVAddRecExpr *Expr) { 201 if (!Expr->isAffine()) { 202 DEBUG(dbgs() << "INVALID: AddRec is not affine"); 203 return ValidatorResult(SCEVType::INVALID); 204 } 205 206 ValidatorResult Start = visit(Expr->getStart()); 207 ValidatorResult Recurrence = visit(Expr->getStepRecurrence(SE)); 208 209 if (!Start.isValid()) 210 return Start; 211 212 if (!Recurrence.isValid()) 213 return Recurrence; 214 215 auto *L = Expr->getLoop(); 216 if (R->contains(L) && (!Scope || !L->contains(Scope))) { 217 DEBUG(dbgs() << "INVALID: Loop of AddRec expression boxed in an a " 218 "non-affine subregion or has a non-synthesizable exit " 219 "value."); 220 return ValidatorResult(SCEVType::INVALID); 221 } 222 223 if (R->contains(L)) { 224 if (Recurrence.isINT()) { 225 ValidatorResult Result(SCEVType::IV); 226 Result.addParamsFrom(Start); 227 return Result; 228 } 229 230 DEBUG(dbgs() << "INVALID: AddRec within scop has non-int" 231 "recurrence part"); 232 return ValidatorResult(SCEVType::INVALID); 233 } 234 235 assert(Recurrence.isConstant() && "Expected 'Recurrence' to be constant"); 236 237 // Directly generate ValidatorResult for Expr if 'start' is zero. 238 if (Expr->getStart()->isZero()) 239 return ValidatorResult(SCEVType::PARAM, Expr); 240 241 // Translate AddRecExpr from '{start, +, inc}' into 'start + {0, +, inc}' 242 // if 'start' is not zero. 243 const SCEV *ZeroStartExpr = SE.getAddRecExpr( 244 SE.getConstant(Expr->getStart()->getType(), 0), 245 Expr->getStepRecurrence(SE), Expr->getLoop(), Expr->getNoWrapFlags()); 246 247 ValidatorResult ZeroStartResult = 248 ValidatorResult(SCEVType::PARAM, ZeroStartExpr); 249 ZeroStartResult.addParamsFrom(Start); 250 251 return ZeroStartResult; 252 } 253 254 class ValidatorResult visitSMaxExpr(const SCEVSMaxExpr *Expr) { 255 ValidatorResult Return(SCEVType::INT); 256 257 for (int i = 0, e = Expr->getNumOperands(); i < e; ++i) { 258 ValidatorResult Op = visit(Expr->getOperand(i)); 259 260 if (!Op.isValid()) 261 return Op; 262 263 Return.merge(Op); 264 } 265 266 return Return; 267 } 268 269 class ValidatorResult visitUMaxExpr(const SCEVUMaxExpr *Expr) { 270 // We do not support unsigned max operations. If 'Expr' is constant during 271 // Scop execution we treat this as a parameter, otherwise we bail out. 272 for (int i = 0, e = Expr->getNumOperands(); i < e; ++i) { 273 ValidatorResult Op = visit(Expr->getOperand(i)); 274 275 if (!Op.isConstant()) { 276 DEBUG(dbgs() << "INVALID: UMaxExpr has a non-constant operand"); 277 return ValidatorResult(SCEVType::INVALID); 278 } 279 } 280 281 return ValidatorResult(SCEVType::PARAM, Expr); 282 } 283 284 ValidatorResult visitGenericInst(Instruction *I, const SCEV *S) { 285 if (R->contains(I)) { 286 DEBUG(dbgs() << "INVALID: UnknownExpr references an instruction " 287 "within the region\n"); 288 return ValidatorResult(SCEVType::INVALID); 289 } 290 291 return ValidatorResult(SCEVType::PARAM, S); 292 } 293 294 ValidatorResult visitLoadInstruction(Instruction *I, const SCEV *S) { 295 if (R->contains(I) && ILS) { 296 ILS->insert(cast<LoadInst>(I)); 297 return ValidatorResult(SCEVType::PARAM, S); 298 } 299 300 return visitGenericInst(I, S); 301 } 302 303 ValidatorResult visitDivision(const SCEV *Dividend, const SCEV *Divisor, 304 const SCEV *DivExpr, 305 Instruction *SDiv = nullptr) { 306 307 // First check if we might be able to model the division, thus if the 308 // divisor is constant. If so, check the dividend, otherwise check if 309 // the whole division can be seen as a parameter. 310 if (isa<SCEVConstant>(Divisor) && !Divisor->isZero()) 311 return visit(Dividend); 312 313 // For signed divisions use the SDiv instruction to check for a parameter 314 // division, for unsigned divisions check the operands. 315 if (SDiv) 316 return visitGenericInst(SDiv, DivExpr); 317 318 ValidatorResult LHS = visit(Dividend); 319 ValidatorResult RHS = visit(Divisor); 320 if (LHS.isConstant() && RHS.isConstant()) 321 return ValidatorResult(SCEVType::PARAM, DivExpr); 322 323 DEBUG(dbgs() << "INVALID: unsigned division of non-constant expressions"); 324 return ValidatorResult(SCEVType::INVALID); 325 } 326 327 ValidatorResult visitUDivExpr(const SCEVUDivExpr *Expr) { 328 auto *Dividend = Expr->getLHS(); 329 auto *Divisor = Expr->getRHS(); 330 return visitDivision(Dividend, Divisor, Expr); 331 } 332 333 ValidatorResult visitSDivInstruction(Instruction *SDiv, const SCEV *Expr) { 334 assert(SDiv->getOpcode() == Instruction::SDiv && 335 "Assumed SDiv instruction!"); 336 337 auto *Dividend = SE.getSCEV(SDiv->getOperand(0)); 338 auto *Divisor = SE.getSCEV(SDiv->getOperand(1)); 339 return visitDivision(Dividend, Divisor, Expr, SDiv); 340 } 341 342 ValidatorResult visitSRemInstruction(Instruction *SRem, const SCEV *S) { 343 assert(SRem->getOpcode() == Instruction::SRem && 344 "Assumed SRem instruction!"); 345 346 auto *Divisor = SRem->getOperand(1); 347 auto *CI = dyn_cast<ConstantInt>(Divisor); 348 if (!CI || CI->isZeroValue()) 349 return visitGenericInst(SRem, S); 350 351 auto *Dividend = SRem->getOperand(0); 352 auto *DividendSCEV = SE.getSCEV(Dividend); 353 return visit(DividendSCEV); 354 } 355 356 ValidatorResult visitUnknown(const SCEVUnknown *Expr) { 357 Value *V = Expr->getValue(); 358 359 if (!Expr->getType()->isIntegerTy() && !Expr->getType()->isPointerTy()) { 360 DEBUG(dbgs() << "INVALID: UnknownExpr is not an integer or pointer"); 361 return ValidatorResult(SCEVType::INVALID); 362 } 363 364 if (isa<UndefValue>(V)) { 365 DEBUG(dbgs() << "INVALID: UnknownExpr references an undef value"); 366 return ValidatorResult(SCEVType::INVALID); 367 } 368 369 if (Instruction *I = dyn_cast<Instruction>(Expr->getValue())) { 370 switch (I->getOpcode()) { 371 case Instruction::IntToPtr: 372 return visit(SE.getSCEVAtScope(I->getOperand(0), Scope)); 373 case Instruction::PtrToInt: 374 return visit(SE.getSCEVAtScope(I->getOperand(0), Scope)); 375 case Instruction::Load: 376 return visitLoadInstruction(I, Expr); 377 case Instruction::SDiv: 378 return visitSDivInstruction(I, Expr); 379 case Instruction::SRem: 380 return visitSRemInstruction(I, Expr); 381 default: 382 return visitGenericInst(I, Expr); 383 } 384 } 385 386 return ValidatorResult(SCEVType::PARAM, Expr); 387 } 388 }; 389 390 /// Check whether a SCEV refers to an SSA name defined inside a region. 391 class SCEVInRegionDependences { 392 const Region *R; 393 Loop *Scope; 394 bool AllowLoops; 395 bool HasInRegionDeps = false; 396 397 public: 398 SCEVInRegionDependences(const Region *R, Loop *Scope, bool AllowLoops) 399 : R(R), Scope(Scope), AllowLoops(AllowLoops) {} 400 401 bool follow(const SCEV *S) { 402 if (auto Unknown = dyn_cast<SCEVUnknown>(S)) { 403 Instruction *Inst = dyn_cast<Instruction>(Unknown->getValue()); 404 405 // Return true when Inst is defined inside the region R. 406 if (!Inst || !R->contains(Inst)) 407 return true; 408 409 HasInRegionDeps = true; 410 return false; 411 } 412 413 if (auto AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 414 if (AllowLoops) 415 return true; 416 417 if (!Scope) { 418 HasInRegionDeps = true; 419 return false; 420 } 421 auto *L = AddRec->getLoop(); 422 if (R->contains(L) && !L->contains(Scope)) { 423 HasInRegionDeps = true; 424 return false; 425 } 426 } 427 428 return true; 429 } 430 bool isDone() { return false; } 431 bool hasDependences() { return HasInRegionDeps; } 432 }; 433 434 namespace polly { 435 /// Find all loops referenced in SCEVAddRecExprs. 436 class SCEVFindLoops { 437 SetVector<const Loop *> &Loops; 438 439 public: 440 SCEVFindLoops(SetVector<const Loop *> &Loops) : Loops(Loops) {} 441 442 bool follow(const SCEV *S) { 443 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) 444 Loops.insert(AddRec->getLoop()); 445 return true; 446 } 447 bool isDone() { return false; } 448 }; 449 450 void findLoops(const SCEV *Expr, SetVector<const Loop *> &Loops) { 451 SCEVFindLoops FindLoops(Loops); 452 SCEVTraversal<SCEVFindLoops> ST(FindLoops); 453 ST.visitAll(Expr); 454 } 455 456 /// Find all values referenced in SCEVUnknowns. 457 class SCEVFindValues { 458 ScalarEvolution &SE; 459 SetVector<Value *> &Values; 460 461 public: 462 SCEVFindValues(ScalarEvolution &SE, SetVector<Value *> &Values) 463 : SE(SE), Values(Values) {} 464 465 bool follow(const SCEV *S) { 466 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(S); 467 if (!Unknown) 468 return true; 469 470 Values.insert(Unknown->getValue()); 471 Instruction *Inst = dyn_cast<Instruction>(Unknown->getValue()); 472 if (!Inst || (Inst->getOpcode() != Instruction::SRem && 473 Inst->getOpcode() != Instruction::SDiv)) 474 return false; 475 476 auto *Dividend = SE.getSCEV(Inst->getOperand(1)); 477 if (!isa<SCEVConstant>(Dividend)) 478 return false; 479 480 auto *Divisor = SE.getSCEV(Inst->getOperand(0)); 481 SCEVFindValues FindValues(SE, Values); 482 SCEVTraversal<SCEVFindValues> ST(FindValues); 483 ST.visitAll(Dividend); 484 ST.visitAll(Divisor); 485 486 return false; 487 } 488 bool isDone() { return false; } 489 }; 490 491 void findValues(const SCEV *Expr, ScalarEvolution &SE, 492 SetVector<Value *> &Values) { 493 SCEVFindValues FindValues(SE, Values); 494 SCEVTraversal<SCEVFindValues> ST(FindValues); 495 ST.visitAll(Expr); 496 } 497 498 bool hasScalarDepsInsideRegion(const SCEV *Expr, const Region *R, 499 llvm::Loop *Scope, bool AllowLoops) { 500 SCEVInRegionDependences InRegionDeps(R, Scope, AllowLoops); 501 SCEVTraversal<SCEVInRegionDependences> ST(InRegionDeps); 502 ST.visitAll(Expr); 503 return InRegionDeps.hasDependences(); 504 } 505 506 bool isAffineExpr(const Region *R, llvm::Loop *Scope, const SCEV *Expr, 507 ScalarEvolution &SE, InvariantLoadsSetTy *ILS) { 508 if (isa<SCEVCouldNotCompute>(Expr)) 509 return false; 510 511 SCEVValidator Validator(R, Scope, SE, ILS); 512 DEBUG({ 513 dbgs() << "\n"; 514 dbgs() << "Expr: " << *Expr << "\n"; 515 dbgs() << "Region: " << R->getNameStr() << "\n"; 516 dbgs() << " -> "; 517 }); 518 519 ValidatorResult Result = Validator.visit(Expr); 520 521 DEBUG({ 522 if (Result.isValid()) 523 dbgs() << "VALID\n"; 524 dbgs() << "\n"; 525 }); 526 527 return Result.isValid(); 528 } 529 530 static bool isAffineExpr(Value *V, const Region *R, Loop *Scope, 531 ScalarEvolution &SE, ParameterSetTy &Params) { 532 auto *E = SE.getSCEV(V); 533 if (isa<SCEVCouldNotCompute>(E)) 534 return false; 535 536 SCEVValidator Validator(R, Scope, SE, nullptr); 537 ValidatorResult Result = Validator.visit(E); 538 if (!Result.isValid()) 539 return false; 540 541 auto ResultParams = Result.getParameters(); 542 Params.insert(ResultParams.begin(), ResultParams.end()); 543 544 return true; 545 } 546 547 bool isAffineConstraint(Value *V, const Region *R, llvm::Loop *Scope, 548 ScalarEvolution &SE, ParameterSetTy &Params, 549 bool OrExpr) { 550 if (auto *ICmp = dyn_cast<ICmpInst>(V)) { 551 return isAffineConstraint(ICmp->getOperand(0), R, Scope, SE, Params, 552 true) && 553 isAffineConstraint(ICmp->getOperand(1), R, Scope, SE, Params, true); 554 } else if (auto *BinOp = dyn_cast<BinaryOperator>(V)) { 555 auto Opcode = BinOp->getOpcode(); 556 if (Opcode == Instruction::And || Opcode == Instruction::Or) 557 return isAffineConstraint(BinOp->getOperand(0), R, Scope, SE, Params, 558 false) && 559 isAffineConstraint(BinOp->getOperand(1), R, Scope, SE, Params, 560 false); 561 /* Fall through */ 562 } 563 564 if (!OrExpr) 565 return false; 566 567 return isAffineExpr(V, R, Scope, SE, Params); 568 } 569 570 ParameterSetTy getParamsInAffineExpr(const Region *R, Loop *Scope, 571 const SCEV *Expr, ScalarEvolution &SE) { 572 if (isa<SCEVCouldNotCompute>(Expr)) 573 return ParameterSetTy(); 574 575 InvariantLoadsSetTy ILS; 576 SCEVValidator Validator(R, Scope, SE, &ILS); 577 ValidatorResult Result = Validator.visit(Expr); 578 assert(Result.isValid() && "Requested parameters for an invalid SCEV!"); 579 580 return Result.getParameters(); 581 } 582 583 std::pair<const SCEVConstant *, const SCEV *> 584 extractConstantFactor(const SCEV *S, ScalarEvolution &SE) { 585 auto *ConstPart = cast<SCEVConstant>(SE.getConstant(S->getType(), 1)); 586 587 if (auto *Constant = dyn_cast<SCEVConstant>(S)) 588 return std::make_pair(Constant, SE.getConstant(S->getType(), 1)); 589 590 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 591 if (AddRec) { 592 auto *StartExpr = AddRec->getStart(); 593 if (StartExpr->isZero()) { 594 auto StepPair = extractConstantFactor(AddRec->getStepRecurrence(SE), SE); 595 auto *LeftOverAddRec = 596 SE.getAddRecExpr(StartExpr, StepPair.second, AddRec->getLoop(), 597 AddRec->getNoWrapFlags()); 598 return std::make_pair(StepPair.first, LeftOverAddRec); 599 } 600 return std::make_pair(ConstPart, S); 601 } 602 603 if (auto *Add = dyn_cast<SCEVAddExpr>(S)) { 604 SmallVector<const SCEV *, 4> LeftOvers; 605 auto Op0Pair = extractConstantFactor(Add->getOperand(0), SE); 606 auto *Factor = Op0Pair.first; 607 if (SE.isKnownNegative(Factor)) { 608 Factor = cast<SCEVConstant>(SE.getNegativeSCEV(Factor)); 609 LeftOvers.push_back(SE.getNegativeSCEV(Op0Pair.second)); 610 } else { 611 LeftOvers.push_back(Op0Pair.second); 612 } 613 614 for (unsigned u = 1, e = Add->getNumOperands(); u < e; u++) { 615 auto OpUPair = extractConstantFactor(Add->getOperand(u), SE); 616 // TODO: Use something smarter than equality here, e.g., gcd. 617 if (Factor == OpUPair.first) 618 LeftOvers.push_back(OpUPair.second); 619 else if (Factor == SE.getNegativeSCEV(OpUPair.first)) 620 LeftOvers.push_back(SE.getNegativeSCEV(OpUPair.second)); 621 else 622 return std::make_pair(ConstPart, S); 623 } 624 625 auto *NewAdd = SE.getAddExpr(LeftOvers, Add->getNoWrapFlags()); 626 return std::make_pair(Factor, NewAdd); 627 } 628 629 auto *Mul = dyn_cast<SCEVMulExpr>(S); 630 if (!Mul) 631 return std::make_pair(ConstPart, S); 632 633 SmallVector<const SCEV *, 4> LeftOvers; 634 for (auto *Op : Mul->operands()) 635 if (isa<SCEVConstant>(Op)) 636 ConstPart = cast<SCEVConstant>(SE.getMulExpr(ConstPart, Op)); 637 else 638 LeftOvers.push_back(Op); 639 640 return std::make_pair(ConstPart, SE.getMulExpr(LeftOvers)); 641 } 642 } // namespace polly 643