LoopVectorizationLegality.cpp 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212
  1. //===- LoopVectorizationLegality.cpp --------------------------------------===//
  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 provides loop vectorization legality analysis. Original code
  11. // resided in LoopVectorize.cpp for a long time.
  12. //
  13. // At this point, it is implemented as a utility class, not as an analysis
  14. // pass. It should be easy to create an analysis pass around it if there
  15. // is a need (but D45420 needs to happen first).
  16. //
  17. #include "llvm/Transforms/Vectorize/LoopVectorizationLegality.h"
  18. #include "llvm/Analysis/VectorUtils.h"
  19. #include "llvm/IR/IntrinsicInst.h"
  20. using namespace llvm;
  21. #define LV_NAME "loop-vectorize"
  22. #define DEBUG_TYPE LV_NAME
  23. static cl::opt<bool>
  24. EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
  25. cl::desc("Enable if-conversion during vectorization."));
  26. static cl::opt<unsigned> PragmaVectorizeMemoryCheckThreshold(
  27. "pragma-vectorize-memory-check-threshold", cl::init(128), cl::Hidden,
  28. cl::desc("The maximum allowed number of runtime memory checks with a "
  29. "vectorize(enable) pragma."));
  30. static cl::opt<unsigned> VectorizeSCEVCheckThreshold(
  31. "vectorize-scev-check-threshold", cl::init(16), cl::Hidden,
  32. cl::desc("The maximum number of SCEV checks allowed."));
  33. static cl::opt<unsigned> PragmaVectorizeSCEVCheckThreshold(
  34. "pragma-vectorize-scev-check-threshold", cl::init(128), cl::Hidden,
  35. cl::desc("The maximum number of SCEV checks allowed with a "
  36. "vectorize(enable) pragma"));
  37. /// Maximum vectorization interleave count.
  38. static const unsigned MaxInterleaveFactor = 16;
  39. namespace llvm {
  40. OptimizationRemarkAnalysis createLVMissedAnalysis(const char *PassName,
  41. StringRef RemarkName,
  42. Loop *TheLoop,
  43. Instruction *I) {
  44. Value *CodeRegion = TheLoop->getHeader();
  45. DebugLoc DL = TheLoop->getStartLoc();
  46. if (I) {
  47. CodeRegion = I->getParent();
  48. // If there is no debug location attached to the instruction, revert back to
  49. // using the loop's.
  50. if (I->getDebugLoc())
  51. DL = I->getDebugLoc();
  52. }
  53. OptimizationRemarkAnalysis R(PassName, RemarkName, DL, CodeRegion);
  54. R << "loop not vectorized: ";
  55. return R;
  56. }
  57. bool LoopVectorizeHints::Hint::validate(unsigned Val) {
  58. switch (Kind) {
  59. case HK_WIDTH:
  60. return isPowerOf2_32(Val) && Val <= VectorizerParams::MaxVectorWidth;
  61. case HK_UNROLL:
  62. return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor;
  63. case HK_FORCE:
  64. return (Val <= 1);
  65. case HK_ISVECTORIZED:
  66. return (Val == 0 || Val == 1);
  67. }
  68. return false;
  69. }
  70. LoopVectorizeHints::LoopVectorizeHints(const Loop *L,
  71. bool InterleaveOnlyWhenForced,
  72. OptimizationRemarkEmitter &ORE)
  73. : Width("vectorize.width", VectorizerParams::VectorizationFactor, HK_WIDTH),
  74. Interleave("interleave.count", InterleaveOnlyWhenForced, HK_UNROLL),
  75. Force("vectorize.enable", FK_Undefined, HK_FORCE),
  76. IsVectorized("isvectorized", 0, HK_ISVECTORIZED), TheLoop(L), ORE(ORE) {
  77. // Populate values with existing loop metadata.
  78. getHintsFromMetadata();
  79. // force-vector-interleave overrides DisableInterleaving.
  80. if (VectorizerParams::isInterleaveForced())
  81. Interleave.Value = VectorizerParams::VectorizationInterleave;
  82. if (IsVectorized.Value != 1)
  83. // If the vectorization width and interleaving count are both 1 then
  84. // consider the loop to have been already vectorized because there's
  85. // nothing more that we can do.
  86. IsVectorized.Value = Width.Value == 1 && Interleave.Value == 1;
  87. LLVM_DEBUG(if (InterleaveOnlyWhenForced && Interleave.Value == 1) dbgs()
  88. << "LV: Interleaving disabled by the pass manager\n");
  89. }
  90. bool LoopVectorizeHints::allowVectorization(
  91. Function *F, Loop *L, bool VectorizeOnlyWhenForced) const {
  92. if (getForce() == LoopVectorizeHints::FK_Disabled) {
  93. LLVM_DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
  94. emitRemarkWithHints();
  95. return false;
  96. }
  97. if (VectorizeOnlyWhenForced && getForce() != LoopVectorizeHints::FK_Enabled) {
  98. LLVM_DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
  99. emitRemarkWithHints();
  100. return false;
  101. }
  102. if (getIsVectorized() == 1) {
  103. LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
  104. // FIXME: Add interleave.disable metadata. This will allow
  105. // vectorize.disable to be used without disabling the pass and errors
  106. // to differentiate between disabled vectorization and a width of 1.
  107. ORE.emit([&]() {
  108. return OptimizationRemarkAnalysis(vectorizeAnalysisPassName(),
  109. "AllDisabled", L->getStartLoc(),
  110. L->getHeader())
  111. << "loop not vectorized: vectorization and interleaving are "
  112. "explicitly disabled, or the loop has already been "
  113. "vectorized";
  114. });
  115. return false;
  116. }
  117. return true;
  118. }
  119. void LoopVectorizeHints::emitRemarkWithHints() const {
  120. using namespace ore;
  121. ORE.emit([&]() {
  122. if (Force.Value == LoopVectorizeHints::FK_Disabled)
  123. return OptimizationRemarkMissed(LV_NAME, "MissedExplicitlyDisabled",
  124. TheLoop->getStartLoc(),
  125. TheLoop->getHeader())
  126. << "loop not vectorized: vectorization is explicitly disabled";
  127. else {
  128. OptimizationRemarkMissed R(LV_NAME, "MissedDetails",
  129. TheLoop->getStartLoc(), TheLoop->getHeader());
  130. R << "loop not vectorized";
  131. if (Force.Value == LoopVectorizeHints::FK_Enabled) {
  132. R << " (Force=" << NV("Force", true);
  133. if (Width.Value != 0)
  134. R << ", Vector Width=" << NV("VectorWidth", Width.Value);
  135. if (Interleave.Value != 0)
  136. R << ", Interleave Count=" << NV("InterleaveCount", Interleave.Value);
  137. R << ")";
  138. }
  139. return R;
  140. }
  141. });
  142. }
  143. const char *LoopVectorizeHints::vectorizeAnalysisPassName() const {
  144. if (getWidth() == 1)
  145. return LV_NAME;
  146. if (getForce() == LoopVectorizeHints::FK_Disabled)
  147. return LV_NAME;
  148. if (getForce() == LoopVectorizeHints::FK_Undefined && getWidth() == 0)
  149. return LV_NAME;
  150. return OptimizationRemarkAnalysis::AlwaysPrint;
  151. }
  152. void LoopVectorizeHints::getHintsFromMetadata() {
  153. MDNode *LoopID = TheLoop->getLoopID();
  154. if (!LoopID)
  155. return;
  156. // First operand should refer to the loop id itself.
  157. assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
  158. assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
  159. for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
  160. const MDString *S = nullptr;
  161. SmallVector<Metadata *, 4> Args;
  162. // The expected hint is either a MDString or a MDNode with the first
  163. // operand a MDString.
  164. if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
  165. if (!MD || MD->getNumOperands() == 0)
  166. continue;
  167. S = dyn_cast<MDString>(MD->getOperand(0));
  168. for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
  169. Args.push_back(MD->getOperand(i));
  170. } else {
  171. S = dyn_cast<MDString>(LoopID->getOperand(i));
  172. assert(Args.size() == 0 && "too many arguments for MDString");
  173. }
  174. if (!S)
  175. continue;
  176. // Check if the hint starts with the loop metadata prefix.
  177. StringRef Name = S->getString();
  178. if (Args.size() == 1)
  179. setHint(Name, Args[0]);
  180. }
  181. }
  182. void LoopVectorizeHints::setHint(StringRef Name, Metadata *Arg) {
  183. if (!Name.startswith(Prefix()))
  184. return;
  185. Name = Name.substr(Prefix().size(), StringRef::npos);
  186. const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg);
  187. if (!C)
  188. return;
  189. unsigned Val = C->getZExtValue();
  190. Hint *Hints[] = {&Width, &Interleave, &Force, &IsVectorized};
  191. for (auto H : Hints) {
  192. if (Name == H->Name) {
  193. if (H->validate(Val))
  194. H->Value = Val;
  195. else
  196. LLVM_DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n");
  197. break;
  198. }
  199. }
  200. }
  201. MDNode *LoopVectorizeHints::createHintMetadata(StringRef Name,
  202. unsigned V) const {
  203. LLVMContext &Context = TheLoop->getHeader()->getContext();
  204. Metadata *MDs[] = {
  205. MDString::get(Context, Name),
  206. ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(Context), V))};
  207. return MDNode::get(Context, MDs);
  208. }
  209. bool LoopVectorizeHints::matchesHintMetadataName(MDNode *Node,
  210. ArrayRef<Hint> HintTypes) {
  211. MDString *Name = dyn_cast<MDString>(Node->getOperand(0));
  212. if (!Name)
  213. return false;
  214. for (auto H : HintTypes)
  215. if (Name->getString().endswith(H.Name))
  216. return true;
  217. return false;
  218. }
  219. void LoopVectorizeHints::writeHintsToMetadata(ArrayRef<Hint> HintTypes) {
  220. if (HintTypes.empty())
  221. return;
  222. // Reserve the first element to LoopID (see below).
  223. SmallVector<Metadata *, 4> MDs(1);
  224. // If the loop already has metadata, then ignore the existing operands.
  225. MDNode *LoopID = TheLoop->getLoopID();
  226. if (LoopID) {
  227. for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
  228. MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
  229. // If node in update list, ignore old value.
  230. if (!matchesHintMetadataName(Node, HintTypes))
  231. MDs.push_back(Node);
  232. }
  233. }
  234. // Now, add the missing hints.
  235. for (auto H : HintTypes)
  236. MDs.push_back(createHintMetadata(Twine(Prefix(), H.Name).str(), H.Value));
  237. // Replace current metadata node with new one.
  238. LLVMContext &Context = TheLoop->getHeader()->getContext();
  239. MDNode *NewLoopID = MDNode::get(Context, MDs);
  240. // Set operand 0 to refer to the loop id itself.
  241. NewLoopID->replaceOperandWith(0, NewLoopID);
  242. TheLoop->setLoopID(NewLoopID);
  243. }
  244. bool LoopVectorizationRequirements::doesNotMeet(
  245. Function *F, Loop *L, const LoopVectorizeHints &Hints) {
  246. const char *PassName = Hints.vectorizeAnalysisPassName();
  247. bool Failed = false;
  248. if (UnsafeAlgebraInst && !Hints.allowReordering()) {
  249. ORE.emit([&]() {
  250. return OptimizationRemarkAnalysisFPCommute(
  251. PassName, "CantReorderFPOps", UnsafeAlgebraInst->getDebugLoc(),
  252. UnsafeAlgebraInst->getParent())
  253. << "loop not vectorized: cannot prove it is safe to reorder "
  254. "floating-point operations";
  255. });
  256. Failed = true;
  257. }
  258. // Test if runtime memcheck thresholds are exceeded.
  259. bool PragmaThresholdReached =
  260. NumRuntimePointerChecks > PragmaVectorizeMemoryCheckThreshold;
  261. bool ThresholdReached =
  262. NumRuntimePointerChecks > VectorizerParams::RuntimeMemoryCheckThreshold;
  263. if ((ThresholdReached && !Hints.allowReordering()) ||
  264. PragmaThresholdReached) {
  265. ORE.emit([&]() {
  266. return OptimizationRemarkAnalysisAliasing(PassName, "CantReorderMemOps",
  267. L->getStartLoc(),
  268. L->getHeader())
  269. << "loop not vectorized: cannot prove it is safe to reorder "
  270. "memory operations";
  271. });
  272. LLVM_DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
  273. Failed = true;
  274. }
  275. return Failed;
  276. }
  277. // Return true if the inner loop \p Lp is uniform with regard to the outer loop
  278. // \p OuterLp (i.e., if the outer loop is vectorized, all the vector lanes
  279. // executing the inner loop will execute the same iterations). This check is
  280. // very constrained for now but it will be relaxed in the future. \p Lp is
  281. // considered uniform if it meets all the following conditions:
  282. // 1) it has a canonical IV (starting from 0 and with stride 1),
  283. // 2) its latch terminator is a conditional branch and,
  284. // 3) its latch condition is a compare instruction whose operands are the
  285. // canonical IV and an OuterLp invariant.
  286. // This check doesn't take into account the uniformity of other conditions not
  287. // related to the loop latch because they don't affect the loop uniformity.
  288. //
  289. // NOTE: We decided to keep all these checks and its associated documentation
  290. // together so that we can easily have a picture of the current supported loop
  291. // nests. However, some of the current checks don't depend on \p OuterLp and
  292. // would be redundantly executed for each \p Lp if we invoked this function for
  293. // different candidate outer loops. This is not the case for now because we
  294. // don't currently have the infrastructure to evaluate multiple candidate outer
  295. // loops and \p OuterLp will be a fixed parameter while we only support explicit
  296. // outer loop vectorization. It's also very likely that these checks go away
  297. // before introducing the aforementioned infrastructure. However, if this is not
  298. // the case, we should move the \p OuterLp independent checks to a separate
  299. // function that is only executed once for each \p Lp.
  300. static bool isUniformLoop(Loop *Lp, Loop *OuterLp) {
  301. assert(Lp->getLoopLatch() && "Expected loop with a single latch.");
  302. // If Lp is the outer loop, it's uniform by definition.
  303. if (Lp == OuterLp)
  304. return true;
  305. assert(OuterLp->contains(Lp) && "OuterLp must contain Lp.");
  306. // 1.
  307. PHINode *IV = Lp->getCanonicalInductionVariable();
  308. if (!IV) {
  309. LLVM_DEBUG(dbgs() << "LV: Canonical IV not found.\n");
  310. return false;
  311. }
  312. // 2.
  313. BasicBlock *Latch = Lp->getLoopLatch();
  314. auto *LatchBr = dyn_cast<BranchInst>(Latch->getTerminator());
  315. if (!LatchBr || LatchBr->isUnconditional()) {
  316. LLVM_DEBUG(dbgs() << "LV: Unsupported loop latch branch.\n");
  317. return false;
  318. }
  319. // 3.
  320. auto *LatchCmp = dyn_cast<CmpInst>(LatchBr->getCondition());
  321. if (!LatchCmp) {
  322. LLVM_DEBUG(
  323. dbgs() << "LV: Loop latch condition is not a compare instruction.\n");
  324. return false;
  325. }
  326. Value *CondOp0 = LatchCmp->getOperand(0);
  327. Value *CondOp1 = LatchCmp->getOperand(1);
  328. Value *IVUpdate = IV->getIncomingValueForBlock(Latch);
  329. if (!(CondOp0 == IVUpdate && OuterLp->isLoopInvariant(CondOp1)) &&
  330. !(CondOp1 == IVUpdate && OuterLp->isLoopInvariant(CondOp0))) {
  331. LLVM_DEBUG(dbgs() << "LV: Loop latch condition is not uniform.\n");
  332. return false;
  333. }
  334. return true;
  335. }
  336. // Return true if \p Lp and all its nested loops are uniform with regard to \p
  337. // OuterLp.
  338. static bool isUniformLoopNest(Loop *Lp, Loop *OuterLp) {
  339. if (!isUniformLoop(Lp, OuterLp))
  340. return false;
  341. // Check if nested loops are uniform.
  342. for (Loop *SubLp : *Lp)
  343. if (!isUniformLoopNest(SubLp, OuterLp))
  344. return false;
  345. return true;
  346. }
  347. /// Check whether it is safe to if-convert this phi node.
  348. ///
  349. /// Phi nodes with constant expressions that can trap are not safe to if
  350. /// convert.
  351. static bool canIfConvertPHINodes(BasicBlock *BB) {
  352. for (PHINode &Phi : BB->phis()) {
  353. for (Value *V : Phi.incoming_values())
  354. if (auto *C = dyn_cast<Constant>(V))
  355. if (C->canTrap())
  356. return false;
  357. }
  358. return true;
  359. }
  360. static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
  361. if (Ty->isPointerTy())
  362. return DL.getIntPtrType(Ty);
  363. // It is possible that char's or short's overflow when we ask for the loop's
  364. // trip count, work around this by changing the type size.
  365. if (Ty->getScalarSizeInBits() < 32)
  366. return Type::getInt32Ty(Ty->getContext());
  367. return Ty;
  368. }
  369. static Type *getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
  370. Ty0 = convertPointerToIntegerType(DL, Ty0);
  371. Ty1 = convertPointerToIntegerType(DL, Ty1);
  372. if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
  373. return Ty0;
  374. return Ty1;
  375. }
  376. /// Check that the instruction has outside loop users and is not an
  377. /// identified reduction variable.
  378. static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
  379. SmallPtrSetImpl<Value *> &AllowedExit) {
  380. // Reductions, Inductions and non-header phis are allowed to have exit users. All
  381. // other instructions must not have external users.
  382. if (!AllowedExit.count(Inst))
  383. // Check that all of the users of the loop are inside the BB.
  384. for (User *U : Inst->users()) {
  385. Instruction *UI = cast<Instruction>(U);
  386. // This user may be a reduction exit value.
  387. if (!TheLoop->contains(UI)) {
  388. LLVM_DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
  389. return true;
  390. }
  391. }
  392. return false;
  393. }
  394. int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
  395. const ValueToValueMap &Strides =
  396. getSymbolicStrides() ? *getSymbolicStrides() : ValueToValueMap();
  397. int Stride = getPtrStride(PSE, Ptr, TheLoop, Strides, true, false);
  398. if (Stride == 1 || Stride == -1)
  399. return Stride;
  400. return 0;
  401. }
  402. bool LoopVectorizationLegality::isUniform(Value *V) {
  403. return LAI->isUniform(V);
  404. }
  405. bool LoopVectorizationLegality::canVectorizeOuterLoop() {
  406. assert(!TheLoop->empty() && "We are not vectorizing an outer loop.");
  407. // Store the result and return it at the end instead of exiting early, in case
  408. // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
  409. bool Result = true;
  410. bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
  411. for (BasicBlock *BB : TheLoop->blocks()) {
  412. // Check whether the BB terminator is a BranchInst. Any other terminator is
  413. // not supported yet.
  414. auto *Br = dyn_cast<BranchInst>(BB->getTerminator());
  415. if (!Br) {
  416. LLVM_DEBUG(dbgs() << "LV: Unsupported basic block terminator.\n");
  417. ORE->emit(createMissedAnalysis("CFGNotUnderstood")
  418. << "loop control flow is not understood by vectorizer");
  419. if (DoExtraAnalysis)
  420. Result = false;
  421. else
  422. return false;
  423. }
  424. // Check whether the BranchInst is a supported one. Only unconditional
  425. // branches, conditional branches with an outer loop invariant condition or
  426. // backedges are supported.
  427. if (Br && Br->isConditional() &&
  428. !TheLoop->isLoopInvariant(Br->getCondition()) &&
  429. !LI->isLoopHeader(Br->getSuccessor(0)) &&
  430. !LI->isLoopHeader(Br->getSuccessor(1))) {
  431. LLVM_DEBUG(dbgs() << "LV: Unsupported conditional branch.\n");
  432. ORE->emit(createMissedAnalysis("CFGNotUnderstood")
  433. << "loop control flow is not understood by vectorizer");
  434. if (DoExtraAnalysis)
  435. Result = false;
  436. else
  437. return false;
  438. }
  439. }
  440. // Check whether inner loops are uniform. At this point, we only support
  441. // simple outer loops scenarios with uniform nested loops.
  442. if (!isUniformLoopNest(TheLoop /*loop nest*/,
  443. TheLoop /*context outer loop*/)) {
  444. LLVM_DEBUG(
  445. dbgs()
  446. << "LV: Not vectorizing: Outer loop contains divergent loops.\n");
  447. ORE->emit(createMissedAnalysis("CFGNotUnderstood")
  448. << "loop control flow is not understood by vectorizer");
  449. if (DoExtraAnalysis)
  450. Result = false;
  451. else
  452. return false;
  453. }
  454. // Check whether we are able to set up outer loop induction.
  455. if (!setupOuterLoopInductions()) {
  456. LLVM_DEBUG(
  457. dbgs() << "LV: Not vectorizing: Unsupported outer loop Phi(s).\n");
  458. ORE->emit(createMissedAnalysis("UnsupportedPhi")
  459. << "Unsupported outer loop Phi(s)");
  460. if (DoExtraAnalysis)
  461. Result = false;
  462. else
  463. return false;
  464. }
  465. return Result;
  466. }
  467. void LoopVectorizationLegality::addInductionPhi(
  468. PHINode *Phi, const InductionDescriptor &ID,
  469. SmallPtrSetImpl<Value *> &AllowedExit) {
  470. Inductions[Phi] = ID;
  471. // In case this induction also comes with casts that we know we can ignore
  472. // in the vectorized loop body, record them here. All casts could be recorded
  473. // here for ignoring, but suffices to record only the first (as it is the
  474. // only one that may bw used outside the cast sequence).
  475. const SmallVectorImpl<Instruction *> &Casts = ID.getCastInsts();
  476. if (!Casts.empty())
  477. InductionCastsToIgnore.insert(*Casts.begin());
  478. Type *PhiTy = Phi->getType();
  479. const DataLayout &DL = Phi->getModule()->getDataLayout();
  480. // Get the widest type.
  481. if (!PhiTy->isFloatingPointTy()) {
  482. if (!WidestIndTy)
  483. WidestIndTy = convertPointerToIntegerType(DL, PhiTy);
  484. else
  485. WidestIndTy = getWiderType(DL, PhiTy, WidestIndTy);
  486. }
  487. // Int inductions are special because we only allow one IV.
  488. if (ID.getKind() == InductionDescriptor::IK_IntInduction &&
  489. ID.getConstIntStepValue() && ID.getConstIntStepValue()->isOne() &&
  490. isa<Constant>(ID.getStartValue()) &&
  491. cast<Constant>(ID.getStartValue())->isNullValue()) {
  492. // Use the phi node with the widest type as induction. Use the last
  493. // one if there are multiple (no good reason for doing this other
  494. // than it is expedient). We've checked that it begins at zero and
  495. // steps by one, so this is a canonical induction variable.
  496. if (!PrimaryInduction || PhiTy == WidestIndTy)
  497. PrimaryInduction = Phi;
  498. }
  499. // Both the PHI node itself, and the "post-increment" value feeding
  500. // back into the PHI node may have external users.
  501. // We can allow those uses, except if the SCEVs we have for them rely
  502. // on predicates that only hold within the loop, since allowing the exit
  503. // currently means re-using this SCEV outside the loop (see PR33706 for more
  504. // details).
  505. if (PSE.getUnionPredicate().isAlwaysTrue()) {
  506. AllowedExit.insert(Phi);
  507. AllowedExit.insert(Phi->getIncomingValueForBlock(TheLoop->getLoopLatch()));
  508. }
  509. LLVM_DEBUG(dbgs() << "LV: Found an induction variable.\n");
  510. }
  511. bool LoopVectorizationLegality::setupOuterLoopInductions() {
  512. BasicBlock *Header = TheLoop->getHeader();
  513. // Returns true if a given Phi is a supported induction.
  514. auto isSupportedPhi = [&](PHINode &Phi) -> bool {
  515. InductionDescriptor ID;
  516. if (InductionDescriptor::isInductionPHI(&Phi, TheLoop, PSE, ID) &&
  517. ID.getKind() == InductionDescriptor::IK_IntInduction) {
  518. addInductionPhi(&Phi, ID, AllowedExit);
  519. return true;
  520. } else {
  521. // Bail out for any Phi in the outer loop header that is not a supported
  522. // induction.
  523. LLVM_DEBUG(
  524. dbgs()
  525. << "LV: Found unsupported PHI for outer loop vectorization.\n");
  526. return false;
  527. }
  528. };
  529. if (llvm::all_of(Header->phis(), isSupportedPhi))
  530. return true;
  531. else
  532. return false;
  533. }
  534. bool LoopVectorizationLegality::canVectorizeInstrs() {
  535. BasicBlock *Header = TheLoop->getHeader();
  536. // Look for the attribute signaling the absence of NaNs.
  537. Function &F = *Header->getParent();
  538. HasFunNoNaNAttr =
  539. F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
  540. // For each block in the loop.
  541. for (BasicBlock *BB : TheLoop->blocks()) {
  542. // Scan the instructions in the block and look for hazards.
  543. for (Instruction &I : *BB) {
  544. if (auto *Phi = dyn_cast<PHINode>(&I)) {
  545. Type *PhiTy = Phi->getType();
  546. // Check that this PHI type is allowed.
  547. if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() &&
  548. !PhiTy->isPointerTy()) {
  549. ORE->emit(createMissedAnalysis("CFGNotUnderstood", Phi)
  550. << "loop control flow is not understood by vectorizer");
  551. LLVM_DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
  552. return false;
  553. }
  554. // If this PHINode is not in the header block, then we know that we
  555. // can convert it to select during if-conversion. No need to check if
  556. // the PHIs in this block are induction or reduction variables.
  557. if (BB != Header) {
  558. // Non-header phi nodes that have outside uses can be vectorized. Add
  559. // them to the list of allowed exits.
  560. // Unsafe cyclic dependencies with header phis are identified during
  561. // legalization for reduction, induction and first order
  562. // recurrences.
  563. continue;
  564. }
  565. // We only allow if-converted PHIs with exactly two incoming values.
  566. if (Phi->getNumIncomingValues() != 2) {
  567. ORE->emit(createMissedAnalysis("CFGNotUnderstood", Phi)
  568. << "control flow not understood by vectorizer");
  569. LLVM_DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
  570. return false;
  571. }
  572. RecurrenceDescriptor RedDes;
  573. if (RecurrenceDescriptor::isReductionPHI(Phi, TheLoop, RedDes, DB, AC,
  574. DT)) {
  575. if (RedDes.hasUnsafeAlgebra())
  576. Requirements->addUnsafeAlgebraInst(RedDes.getUnsafeAlgebraInst());
  577. AllowedExit.insert(RedDes.getLoopExitInstr());
  578. Reductions[Phi] = RedDes;
  579. continue;
  580. }
  581. // TODO: Instead of recording the AllowedExit, it would be good to record the
  582. // complementary set: NotAllowedExit. These include (but may not be
  583. // limited to):
  584. // 1. Reduction phis as they represent the one-before-last value, which
  585. // is not available when vectorized
  586. // 2. Induction phis and increment when SCEV predicates cannot be used
  587. // outside the loop - see addInductionPhi
  588. // 3. Non-Phis with outside uses when SCEV predicates cannot be used
  589. // outside the loop - see call to hasOutsideLoopUser in the non-phi
  590. // handling below
  591. // 4. FirstOrderRecurrence phis that can possibly be handled by
  592. // extraction.
  593. // By recording these, we can then reason about ways to vectorize each
  594. // of these NotAllowedExit.
  595. InductionDescriptor ID;
  596. if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID)) {
  597. addInductionPhi(Phi, ID, AllowedExit);
  598. if (ID.hasUnsafeAlgebra() && !HasFunNoNaNAttr)
  599. Requirements->addUnsafeAlgebraInst(ID.getUnsafeAlgebraInst());
  600. continue;
  601. }
  602. if (RecurrenceDescriptor::isFirstOrderRecurrence(Phi, TheLoop,
  603. SinkAfter, DT)) {
  604. FirstOrderRecurrences.insert(Phi);
  605. continue;
  606. }
  607. // As a last resort, coerce the PHI to a AddRec expression
  608. // and re-try classifying it a an induction PHI.
  609. if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID, true)) {
  610. addInductionPhi(Phi, ID, AllowedExit);
  611. continue;
  612. }
  613. ORE->emit(createMissedAnalysis("NonReductionValueUsedOutsideLoop", Phi)
  614. << "value that could not be identified as "
  615. "reduction is used outside the loop");
  616. LLVM_DEBUG(dbgs() << "LV: Found an unidentified PHI." << *Phi << "\n");
  617. return false;
  618. } // end of PHI handling
  619. // We handle calls that:
  620. // * Are debug info intrinsics.
  621. // * Have a mapping to an IR intrinsic.
  622. // * Have a vector version available.
  623. auto *CI = dyn_cast<CallInst>(&I);
  624. if (CI && !getVectorIntrinsicIDForCall(CI, TLI) &&
  625. !isa<DbgInfoIntrinsic>(CI) &&
  626. !(CI->getCalledFunction() && TLI &&
  627. TLI->isFunctionVectorizable(CI->getCalledFunction()->getName()))) {
  628. // If the call is a recognized math libary call, it is likely that
  629. // we can vectorize it given loosened floating-point constraints.
  630. LibFunc Func;
  631. bool IsMathLibCall =
  632. TLI && CI->getCalledFunction() &&
  633. CI->getType()->isFloatingPointTy() &&
  634. TLI->getLibFunc(CI->getCalledFunction()->getName(), Func) &&
  635. TLI->hasOptimizedCodeGen(Func);
  636. if (IsMathLibCall) {
  637. // TODO: Ideally, we should not use clang-specific language here,
  638. // but it's hard to provide meaningful yet generic advice.
  639. // Also, should this be guarded by allowExtraAnalysis() and/or be part
  640. // of the returned info from isFunctionVectorizable()?
  641. ORE->emit(createMissedAnalysis("CantVectorizeLibcall", CI)
  642. << "library call cannot be vectorized. "
  643. "Try compiling with -fno-math-errno, -ffast-math, "
  644. "or similar flags");
  645. } else {
  646. ORE->emit(createMissedAnalysis("CantVectorizeCall", CI)
  647. << "call instruction cannot be vectorized");
  648. }
  649. LLVM_DEBUG(
  650. dbgs() << "LV: Found a non-intrinsic callsite.\n");
  651. return false;
  652. }
  653. // Intrinsics such as powi,cttz and ctlz are legal to vectorize if the
  654. // second argument is the same (i.e. loop invariant)
  655. if (CI && hasVectorInstrinsicScalarOpd(
  656. getVectorIntrinsicIDForCall(CI, TLI), 1)) {
  657. auto *SE = PSE.getSE();
  658. if (!SE->isLoopInvariant(PSE.getSCEV(CI->getOperand(1)), TheLoop)) {
  659. ORE->emit(createMissedAnalysis("CantVectorizeIntrinsic", CI)
  660. << "intrinsic instruction cannot be vectorized");
  661. LLVM_DEBUG(dbgs()
  662. << "LV: Found unvectorizable intrinsic " << *CI << "\n");
  663. return false;
  664. }
  665. }
  666. // Check that the instruction return type is vectorizable.
  667. // Also, we can't vectorize extractelement instructions.
  668. if ((!VectorType::isValidElementType(I.getType()) &&
  669. !I.getType()->isVoidTy()) ||
  670. isa<ExtractElementInst>(I)) {
  671. ORE->emit(createMissedAnalysis("CantVectorizeInstructionReturnType", &I)
  672. << "instruction return type cannot be vectorized");
  673. LLVM_DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
  674. return false;
  675. }
  676. // Check that the stored type is vectorizable.
  677. if (auto *ST = dyn_cast<StoreInst>(&I)) {
  678. Type *T = ST->getValueOperand()->getType();
  679. if (!VectorType::isValidElementType(T)) {
  680. ORE->emit(createMissedAnalysis("CantVectorizeStore", ST)
  681. << "store instruction cannot be vectorized");
  682. return false;
  683. }
  684. // FP instructions can allow unsafe algebra, thus vectorizable by
  685. // non-IEEE-754 compliant SIMD units.
  686. // This applies to floating-point math operations and calls, not memory
  687. // operations, shuffles, or casts, as they don't change precision or
  688. // semantics.
  689. } else if (I.getType()->isFloatingPointTy() && (CI || I.isBinaryOp()) &&
  690. !I.isFast()) {
  691. LLVM_DEBUG(dbgs() << "LV: Found FP op with unsafe algebra.\n");
  692. Hints->setPotentiallyUnsafe();
  693. }
  694. // Reduction instructions are allowed to have exit users.
  695. // All other instructions must not have external users.
  696. if (hasOutsideLoopUser(TheLoop, &I, AllowedExit)) {
  697. // We can safely vectorize loops where instructions within the loop are
  698. // used outside the loop only if the SCEV predicates within the loop is
  699. // same as outside the loop. Allowing the exit means reusing the SCEV
  700. // outside the loop.
  701. if (PSE.getUnionPredicate().isAlwaysTrue()) {
  702. AllowedExit.insert(&I);
  703. continue;
  704. }
  705. ORE->emit(createMissedAnalysis("ValueUsedOutsideLoop", &I)
  706. << "value cannot be used outside the loop");
  707. return false;
  708. }
  709. } // next instr.
  710. }
  711. if (!PrimaryInduction) {
  712. LLVM_DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
  713. if (Inductions.empty()) {
  714. ORE->emit(createMissedAnalysis("NoInductionVariable")
  715. << "loop induction variable could not be identified");
  716. return false;
  717. } else if (!WidestIndTy) {
  718. ORE->emit(createMissedAnalysis("NoIntegerInductionVariable")
  719. << "integer loop induction variable could not be identified");
  720. return false;
  721. }
  722. }
  723. // Now we know the widest induction type, check if our found induction
  724. // is the same size. If it's not, unset it here and InnerLoopVectorizer
  725. // will create another.
  726. if (PrimaryInduction && WidestIndTy != PrimaryInduction->getType())
  727. PrimaryInduction = nullptr;
  728. return true;
  729. }
  730. bool LoopVectorizationLegality::canVectorizeMemory() {
  731. LAI = &(*GetLAA)(*TheLoop);
  732. const OptimizationRemarkAnalysis *LAR = LAI->getReport();
  733. if (LAR) {
  734. ORE->emit([&]() {
  735. return OptimizationRemarkAnalysis(Hints->vectorizeAnalysisPassName(),
  736. "loop not vectorized: ", *LAR);
  737. });
  738. }
  739. if (!LAI->canVectorizeMemory())
  740. return false;
  741. if (LAI->hasDependenceInvolvingLoopInvariantAddress()) {
  742. ORE->emit(createMissedAnalysis("CantVectorizeStoreToLoopInvariantAddress")
  743. << "write to a loop invariant address could not "
  744. "be vectorized");
  745. LLVM_DEBUG(
  746. dbgs() << "LV: Non vectorizable stores to a uniform address\n");
  747. return false;
  748. }
  749. Requirements->addRuntimePointerChecks(LAI->getNumRuntimePointerChecks());
  750. PSE.addPredicate(LAI->getPSE().getUnionPredicate());
  751. return true;
  752. }
  753. bool LoopVectorizationLegality::isInductionPhi(const Value *V) {
  754. Value *In0 = const_cast<Value *>(V);
  755. PHINode *PN = dyn_cast_or_null<PHINode>(In0);
  756. if (!PN)
  757. return false;
  758. return Inductions.count(PN);
  759. }
  760. bool LoopVectorizationLegality::isCastedInductionVariable(const Value *V) {
  761. auto *Inst = dyn_cast<Instruction>(V);
  762. return (Inst && InductionCastsToIgnore.count(Inst));
  763. }
  764. bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
  765. return isInductionPhi(V) || isCastedInductionVariable(V);
  766. }
  767. bool LoopVectorizationLegality::isFirstOrderRecurrence(const PHINode *Phi) {
  768. return FirstOrderRecurrences.count(Phi);
  769. }
  770. bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
  771. return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
  772. }
  773. bool LoopVectorizationLegality::blockCanBePredicated(
  774. BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs) {
  775. const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
  776. for (Instruction &I : *BB) {
  777. // Check that we don't have a constant expression that can trap as operand.
  778. for (Value *Operand : I.operands()) {
  779. if (auto *C = dyn_cast<Constant>(Operand))
  780. if (C->canTrap())
  781. return false;
  782. }
  783. // We might be able to hoist the load.
  784. if (I.mayReadFromMemory()) {
  785. auto *LI = dyn_cast<LoadInst>(&I);
  786. if (!LI)
  787. return false;
  788. if (!SafePtrs.count(LI->getPointerOperand())) {
  789. // !llvm.mem.parallel_loop_access implies if-conversion safety.
  790. // Otherwise, record that the load needs (real or emulated) masking
  791. // and let the cost model decide.
  792. if (!IsAnnotatedParallel)
  793. MaskedOp.insert(LI);
  794. continue;
  795. }
  796. }
  797. if (I.mayWriteToMemory()) {
  798. auto *SI = dyn_cast<StoreInst>(&I);
  799. if (!SI)
  800. return false;
  801. // Predicated store requires some form of masking:
  802. // 1) masked store HW instruction,
  803. // 2) emulation via load-blend-store (only if safe and legal to do so,
  804. // be aware on the race conditions), or
  805. // 3) element-by-element predicate check and scalar store.
  806. MaskedOp.insert(SI);
  807. continue;
  808. }
  809. if (I.mayThrow())
  810. return false;
  811. }
  812. return true;
  813. }
  814. bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
  815. if (!EnableIfConversion) {
  816. ORE->emit(createMissedAnalysis("IfConversionDisabled")
  817. << "if-conversion is disabled");
  818. return false;
  819. }
  820. assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
  821. // A list of pointers that we can safely read and write to.
  822. SmallPtrSet<Value *, 8> SafePointes;
  823. // Collect safe addresses.
  824. for (BasicBlock *BB : TheLoop->blocks()) {
  825. if (blockNeedsPredication(BB))
  826. continue;
  827. for (Instruction &I : *BB)
  828. if (auto *Ptr = getLoadStorePointerOperand(&I))
  829. SafePointes.insert(Ptr);
  830. }
  831. // Collect the blocks that need predication.
  832. BasicBlock *Header = TheLoop->getHeader();
  833. for (BasicBlock *BB : TheLoop->blocks()) {
  834. // We don't support switch statements inside loops.
  835. if (!isa<BranchInst>(BB->getTerminator())) {
  836. ORE->emit(createMissedAnalysis("LoopContainsSwitch", BB->getTerminator())
  837. << "loop contains a switch statement");
  838. return false;
  839. }
  840. // We must be able to predicate all blocks that need to be predicated.
  841. if (blockNeedsPredication(BB)) {
  842. if (!blockCanBePredicated(BB, SafePointes)) {
  843. ORE->emit(createMissedAnalysis("NoCFGForSelect", BB->getTerminator())
  844. << "control flow cannot be substituted for a select");
  845. return false;
  846. }
  847. } else if (BB != Header && !canIfConvertPHINodes(BB)) {
  848. ORE->emit(createMissedAnalysis("NoCFGForSelect", BB->getTerminator())
  849. << "control flow cannot be substituted for a select");
  850. return false;
  851. }
  852. }
  853. // We can if-convert this loop.
  854. return true;
  855. }
  856. // Helper function to canVectorizeLoopNestCFG.
  857. bool LoopVectorizationLegality::canVectorizeLoopCFG(Loop *Lp,
  858. bool UseVPlanNativePath) {
  859. assert((UseVPlanNativePath || Lp->empty()) &&
  860. "VPlan-native path is not enabled.");
  861. // TODO: ORE should be improved to show more accurate information when an
  862. // outer loop can't be vectorized because a nested loop is not understood or
  863. // legal. Something like: "outer_loop_location: loop not vectorized:
  864. // (inner_loop_location) loop control flow is not understood by vectorizer".
  865. // Store the result and return it at the end instead of exiting early, in case
  866. // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
  867. bool Result = true;
  868. bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
  869. // We must have a loop in canonical form. Loops with indirectbr in them cannot
  870. // be canonicalized.
  871. if (!Lp->getLoopPreheader()) {
  872. LLVM_DEBUG(dbgs() << "LV: Loop doesn't have a legal pre-header.\n");
  873. ORE->emit(createMissedAnalysis("CFGNotUnderstood")
  874. << "loop control flow is not understood by vectorizer");
  875. if (DoExtraAnalysis)
  876. Result = false;
  877. else
  878. return false;
  879. }
  880. // We must have a single backedge.
  881. if (Lp->getNumBackEdges() != 1) {
  882. ORE->emit(createMissedAnalysis("CFGNotUnderstood")
  883. << "loop control flow is not understood by vectorizer");
  884. if (DoExtraAnalysis)
  885. Result = false;
  886. else
  887. return false;
  888. }
  889. // We must have a single exiting block.
  890. if (!Lp->getExitingBlock()) {
  891. ORE->emit(createMissedAnalysis("CFGNotUnderstood")
  892. << "loop control flow is not understood by vectorizer");
  893. if (DoExtraAnalysis)
  894. Result = false;
  895. else
  896. return false;
  897. }
  898. // We only handle bottom-tested loops, i.e. loop in which the condition is
  899. // checked at the end of each iteration. With that we can assume that all
  900. // instructions in the loop are executed the same number of times.
  901. if (Lp->getExitingBlock() != Lp->getLoopLatch()) {
  902. ORE->emit(createMissedAnalysis("CFGNotUnderstood")
  903. << "loop control flow is not understood by vectorizer");
  904. if (DoExtraAnalysis)
  905. Result = false;
  906. else
  907. return false;
  908. }
  909. return Result;
  910. }
  911. bool LoopVectorizationLegality::canVectorizeLoopNestCFG(
  912. Loop *Lp, bool UseVPlanNativePath) {
  913. // Store the result and return it at the end instead of exiting early, in case
  914. // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
  915. bool Result = true;
  916. bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
  917. if (!canVectorizeLoopCFG(Lp, UseVPlanNativePath)) {
  918. if (DoExtraAnalysis)
  919. Result = false;
  920. else
  921. return false;
  922. }
  923. // Recursively check whether the loop control flow of nested loops is
  924. // understood.
  925. for (Loop *SubLp : *Lp)
  926. if (!canVectorizeLoopNestCFG(SubLp, UseVPlanNativePath)) {
  927. if (DoExtraAnalysis)
  928. Result = false;
  929. else
  930. return false;
  931. }
  932. return Result;
  933. }
  934. bool LoopVectorizationLegality::canVectorize(bool UseVPlanNativePath) {
  935. // Store the result and return it at the end instead of exiting early, in case
  936. // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
  937. bool Result = true;
  938. bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
  939. // Check whether the loop-related control flow in the loop nest is expected by
  940. // vectorizer.
  941. if (!canVectorizeLoopNestCFG(TheLoop, UseVPlanNativePath)) {
  942. if (DoExtraAnalysis)
  943. Result = false;
  944. else
  945. return false;
  946. }
  947. // We need to have a loop header.
  948. LLVM_DEBUG(dbgs() << "LV: Found a loop: " << TheLoop->getHeader()->getName()
  949. << '\n');
  950. // Specific checks for outer loops. We skip the remaining legal checks at this
  951. // point because they don't support outer loops.
  952. if (!TheLoop->empty()) {
  953. assert(UseVPlanNativePath && "VPlan-native path is not enabled.");
  954. if (!canVectorizeOuterLoop()) {
  955. LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Unsupported outer loop.\n");
  956. // TODO: Implement DoExtraAnalysis when subsequent legal checks support
  957. // outer loops.
  958. return false;
  959. }
  960. LLVM_DEBUG(dbgs() << "LV: We can vectorize this outer loop!\n");
  961. return Result;
  962. }
  963. assert(TheLoop->empty() && "Inner loop expected.");
  964. // Check if we can if-convert non-single-bb loops.
  965. unsigned NumBlocks = TheLoop->getNumBlocks();
  966. if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
  967. LLVM_DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
  968. if (DoExtraAnalysis)
  969. Result = false;
  970. else
  971. return false;
  972. }
  973. // Check if we can vectorize the instructions and CFG in this loop.
  974. if (!canVectorizeInstrs()) {
  975. LLVM_DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
  976. if (DoExtraAnalysis)
  977. Result = false;
  978. else
  979. return false;
  980. }
  981. // Go over each instruction and look at memory deps.
  982. if (!canVectorizeMemory()) {
  983. LLVM_DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
  984. if (DoExtraAnalysis)
  985. Result = false;
  986. else
  987. return false;
  988. }
  989. LLVM_DEBUG(dbgs() << "LV: We can vectorize this loop"
  990. << (LAI->getRuntimePointerChecking()->Need
  991. ? " (with a runtime bound check)"
  992. : "")
  993. << "!\n");
  994. unsigned SCEVThreshold = VectorizeSCEVCheckThreshold;
  995. if (Hints->getForce() == LoopVectorizeHints::FK_Enabled)
  996. SCEVThreshold = PragmaVectorizeSCEVCheckThreshold;
  997. if (PSE.getUnionPredicate().getComplexity() > SCEVThreshold) {
  998. ORE->emit(createMissedAnalysis("TooManySCEVRunTimeChecks")
  999. << "Too many SCEV assumptions need to be made and checked "
  1000. << "at runtime");
  1001. LLVM_DEBUG(dbgs() << "LV: Too many SCEV checks needed.\n");
  1002. if (DoExtraAnalysis)
  1003. Result = false;
  1004. else
  1005. return false;
  1006. }
  1007. // Okay! We've done all the tests. If any have failed, return false. Otherwise
  1008. // we can vectorize, and at this point we don't have any other mem analysis
  1009. // which may limit our maximum vectorization factor, so just return true with
  1010. // no restrictions.
  1011. return Result;
  1012. }
  1013. bool LoopVectorizationLegality::canFoldTailByMasking() {
  1014. LLVM_DEBUG(dbgs() << "LV: checking if tail can be folded by masking.\n");
  1015. if (!PrimaryInduction) {
  1016. ORE->emit(createMissedAnalysis("NoPrimaryInduction")
  1017. << "Missing a primary induction variable in the loop, which is "
  1018. << "needed in order to fold tail by masking as required.");
  1019. LLVM_DEBUG(dbgs() << "LV: No primary induction, cannot fold tail by "
  1020. << "masking.\n");
  1021. return false;
  1022. }
  1023. // TODO: handle reductions when tail is folded by masking.
  1024. if (!Reductions.empty()) {
  1025. ORE->emit(createMissedAnalysis("ReductionFoldingTailByMasking")
  1026. << "Cannot fold tail by masking in the presence of reductions.");
  1027. LLVM_DEBUG(dbgs() << "LV: Loop has reductions, cannot fold tail by "
  1028. << "masking.\n");
  1029. return false;
  1030. }
  1031. // TODO: handle outside users when tail is folded by masking.
  1032. for (auto *AE : AllowedExit) {
  1033. // Check that all users of allowed exit values are inside the loop.
  1034. for (User *U : AE->users()) {
  1035. Instruction *UI = cast<Instruction>(U);
  1036. if (TheLoop->contains(UI))
  1037. continue;
  1038. ORE->emit(createMissedAnalysis("LiveOutFoldingTailByMasking")
  1039. << "Cannot fold tail by masking in the presence of live outs.");
  1040. LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking, loop has an "
  1041. << "outside user for : " << *UI << '\n');
  1042. return false;
  1043. }
  1044. }
  1045. // The list of pointers that we can safely read and write to remains empty.
  1046. SmallPtrSet<Value *, 8> SafePointers;
  1047. // Check and mark all blocks for predication, including those that ordinarily
  1048. // do not need predication such as the header block.
  1049. for (BasicBlock *BB : TheLoop->blocks()) {
  1050. if (!blockCanBePredicated(BB, SafePointers)) {
  1051. ORE->emit(createMissedAnalysis("NoCFGForSelect", BB->getTerminator())
  1052. << "control flow cannot be substituted for a select");
  1053. LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking as required.\n");
  1054. return false;
  1055. }
  1056. }
  1057. LLVM_DEBUG(dbgs() << "LV: can fold tail by masking.\n");
  1058. return true;
  1059. }
  1060. } // namespace llvm