LoopVectorizationLegality.cpp 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216
  1. //===- LoopVectorizationLegality.cpp --------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file provides loop vectorization legality analysis. Original code
  10. // resided in LoopVectorize.cpp for a long time.
  11. //
  12. // At this point, it is implemented as a utility class, not as an analysis
  13. // pass. It should be easy to create an analysis pass around it if there
  14. // is a need (but D45420 needs to happen first).
  15. //
  16. #include "llvm/Transforms/Vectorize/LoopVectorizationLegality.h"
  17. #include "llvm/Analysis/VectorUtils.h"
  18. #include "llvm/IR/IntrinsicInst.h"
  19. using namespace llvm;
  20. #define LV_NAME "loop-vectorize"
  21. #define DEBUG_TYPE LV_NAME
  22. extern cl::opt<bool> EnableVPlanPredication;
  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. // FIXME: We skip these checks when VPlan predication is enabled as we
  428. // want to allow divergent branches. This whole check will be removed
  429. // once VPlan predication is on by default.
  430. if (!EnableVPlanPredication && Br && Br->isConditional() &&
  431. !TheLoop->isLoopInvariant(Br->getCondition()) &&
  432. !LI->isLoopHeader(Br->getSuccessor(0)) &&
  433. !LI->isLoopHeader(Br->getSuccessor(1))) {
  434. LLVM_DEBUG(dbgs() << "LV: Unsupported conditional branch.\n");
  435. ORE->emit(createMissedAnalysis("CFGNotUnderstood")
  436. << "loop control flow is not understood by vectorizer");
  437. if (DoExtraAnalysis)
  438. Result = false;
  439. else
  440. return false;
  441. }
  442. }
  443. // Check whether inner loops are uniform. At this point, we only support
  444. // simple outer loops scenarios with uniform nested loops.
  445. if (!isUniformLoopNest(TheLoop /*loop nest*/,
  446. TheLoop /*context outer loop*/)) {
  447. LLVM_DEBUG(
  448. dbgs()
  449. << "LV: Not vectorizing: Outer loop contains divergent loops.\n");
  450. ORE->emit(createMissedAnalysis("CFGNotUnderstood")
  451. << "loop control flow is not understood by vectorizer");
  452. if (DoExtraAnalysis)
  453. Result = false;
  454. else
  455. return false;
  456. }
  457. // Check whether we are able to set up outer loop induction.
  458. if (!setupOuterLoopInductions()) {
  459. LLVM_DEBUG(
  460. dbgs() << "LV: Not vectorizing: Unsupported outer loop Phi(s).\n");
  461. ORE->emit(createMissedAnalysis("UnsupportedPhi")
  462. << "Unsupported outer loop Phi(s)");
  463. if (DoExtraAnalysis)
  464. Result = false;
  465. else
  466. return false;
  467. }
  468. return Result;
  469. }
  470. void LoopVectorizationLegality::addInductionPhi(
  471. PHINode *Phi, const InductionDescriptor &ID,
  472. SmallPtrSetImpl<Value *> &AllowedExit) {
  473. Inductions[Phi] = ID;
  474. // In case this induction also comes with casts that we know we can ignore
  475. // in the vectorized loop body, record them here. All casts could be recorded
  476. // here for ignoring, but suffices to record only the first (as it is the
  477. // only one that may bw used outside the cast sequence).
  478. const SmallVectorImpl<Instruction *> &Casts = ID.getCastInsts();
  479. if (!Casts.empty())
  480. InductionCastsToIgnore.insert(*Casts.begin());
  481. Type *PhiTy = Phi->getType();
  482. const DataLayout &DL = Phi->getModule()->getDataLayout();
  483. // Get the widest type.
  484. if (!PhiTy->isFloatingPointTy()) {
  485. if (!WidestIndTy)
  486. WidestIndTy = convertPointerToIntegerType(DL, PhiTy);
  487. else
  488. WidestIndTy = getWiderType(DL, PhiTy, WidestIndTy);
  489. }
  490. // Int inductions are special because we only allow one IV.
  491. if (ID.getKind() == InductionDescriptor::IK_IntInduction &&
  492. ID.getConstIntStepValue() && ID.getConstIntStepValue()->isOne() &&
  493. isa<Constant>(ID.getStartValue()) &&
  494. cast<Constant>(ID.getStartValue())->isNullValue()) {
  495. // Use the phi node with the widest type as induction. Use the last
  496. // one if there are multiple (no good reason for doing this other
  497. // than it is expedient). We've checked that it begins at zero and
  498. // steps by one, so this is a canonical induction variable.
  499. if (!PrimaryInduction || PhiTy == WidestIndTy)
  500. PrimaryInduction = Phi;
  501. }
  502. // Both the PHI node itself, and the "post-increment" value feeding
  503. // back into the PHI node may have external users.
  504. // We can allow those uses, except if the SCEVs we have for them rely
  505. // on predicates that only hold within the loop, since allowing the exit
  506. // currently means re-using this SCEV outside the loop (see PR33706 for more
  507. // details).
  508. if (PSE.getUnionPredicate().isAlwaysTrue()) {
  509. AllowedExit.insert(Phi);
  510. AllowedExit.insert(Phi->getIncomingValueForBlock(TheLoop->getLoopLatch()));
  511. }
  512. LLVM_DEBUG(dbgs() << "LV: Found an induction variable.\n");
  513. }
  514. bool LoopVectorizationLegality::setupOuterLoopInductions() {
  515. BasicBlock *Header = TheLoop->getHeader();
  516. // Returns true if a given Phi is a supported induction.
  517. auto isSupportedPhi = [&](PHINode &Phi) -> bool {
  518. InductionDescriptor ID;
  519. if (InductionDescriptor::isInductionPHI(&Phi, TheLoop, PSE, ID) &&
  520. ID.getKind() == InductionDescriptor::IK_IntInduction) {
  521. addInductionPhi(&Phi, ID, AllowedExit);
  522. return true;
  523. } else {
  524. // Bail out for any Phi in the outer loop header that is not a supported
  525. // induction.
  526. LLVM_DEBUG(
  527. dbgs()
  528. << "LV: Found unsupported PHI for outer loop vectorization.\n");
  529. return false;
  530. }
  531. };
  532. if (llvm::all_of(Header->phis(), isSupportedPhi))
  533. return true;
  534. else
  535. return false;
  536. }
  537. bool LoopVectorizationLegality::canVectorizeInstrs() {
  538. BasicBlock *Header = TheLoop->getHeader();
  539. // Look for the attribute signaling the absence of NaNs.
  540. Function &F = *Header->getParent();
  541. HasFunNoNaNAttr =
  542. F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
  543. // For each block in the loop.
  544. for (BasicBlock *BB : TheLoop->blocks()) {
  545. // Scan the instructions in the block and look for hazards.
  546. for (Instruction &I : *BB) {
  547. if (auto *Phi = dyn_cast<PHINode>(&I)) {
  548. Type *PhiTy = Phi->getType();
  549. // Check that this PHI type is allowed.
  550. if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() &&
  551. !PhiTy->isPointerTy()) {
  552. ORE->emit(createMissedAnalysis("CFGNotUnderstood", Phi)
  553. << "loop control flow is not understood by vectorizer");
  554. LLVM_DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
  555. return false;
  556. }
  557. // If this PHINode is not in the header block, then we know that we
  558. // can convert it to select during if-conversion. No need to check if
  559. // the PHIs in this block are induction or reduction variables.
  560. if (BB != Header) {
  561. // Non-header phi nodes that have outside uses can be vectorized. Add
  562. // them to the list of allowed exits.
  563. // Unsafe cyclic dependencies with header phis are identified during
  564. // legalization for reduction, induction and first order
  565. // recurrences.
  566. continue;
  567. }
  568. // We only allow if-converted PHIs with exactly two incoming values.
  569. if (Phi->getNumIncomingValues() != 2) {
  570. ORE->emit(createMissedAnalysis("CFGNotUnderstood", Phi)
  571. << "control flow not understood by vectorizer");
  572. LLVM_DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
  573. return false;
  574. }
  575. RecurrenceDescriptor RedDes;
  576. if (RecurrenceDescriptor::isReductionPHI(Phi, TheLoop, RedDes, DB, AC,
  577. DT)) {
  578. if (RedDes.hasUnsafeAlgebra())
  579. Requirements->addUnsafeAlgebraInst(RedDes.getUnsafeAlgebraInst());
  580. AllowedExit.insert(RedDes.getLoopExitInstr());
  581. Reductions[Phi] = RedDes;
  582. continue;
  583. }
  584. // TODO: Instead of recording the AllowedExit, it would be good to record the
  585. // complementary set: NotAllowedExit. These include (but may not be
  586. // limited to):
  587. // 1. Reduction phis as they represent the one-before-last value, which
  588. // is not available when vectorized
  589. // 2. Induction phis and increment when SCEV predicates cannot be used
  590. // outside the loop - see addInductionPhi
  591. // 3. Non-Phis with outside uses when SCEV predicates cannot be used
  592. // outside the loop - see call to hasOutsideLoopUser in the non-phi
  593. // handling below
  594. // 4. FirstOrderRecurrence phis that can possibly be handled by
  595. // extraction.
  596. // By recording these, we can then reason about ways to vectorize each
  597. // of these NotAllowedExit.
  598. InductionDescriptor ID;
  599. if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID)) {
  600. addInductionPhi(Phi, ID, AllowedExit);
  601. if (ID.hasUnsafeAlgebra() && !HasFunNoNaNAttr)
  602. Requirements->addUnsafeAlgebraInst(ID.getUnsafeAlgebraInst());
  603. continue;
  604. }
  605. if (RecurrenceDescriptor::isFirstOrderRecurrence(Phi, TheLoop,
  606. SinkAfter, DT)) {
  607. FirstOrderRecurrences.insert(Phi);
  608. continue;
  609. }
  610. // As a last resort, coerce the PHI to a AddRec expression
  611. // and re-try classifying it a an induction PHI.
  612. if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID, true)) {
  613. addInductionPhi(Phi, ID, AllowedExit);
  614. continue;
  615. }
  616. ORE->emit(createMissedAnalysis("NonReductionValueUsedOutsideLoop", Phi)
  617. << "value that could not be identified as "
  618. "reduction is used outside the loop");
  619. LLVM_DEBUG(dbgs() << "LV: Found an unidentified PHI." << *Phi << "\n");
  620. return false;
  621. } // end of PHI handling
  622. // We handle calls that:
  623. // * Are debug info intrinsics.
  624. // * Have a mapping to an IR intrinsic.
  625. // * Have a vector version available.
  626. auto *CI = dyn_cast<CallInst>(&I);
  627. if (CI && !getVectorIntrinsicIDForCall(CI, TLI) &&
  628. !isa<DbgInfoIntrinsic>(CI) &&
  629. !(CI->getCalledFunction() && TLI &&
  630. TLI->isFunctionVectorizable(CI->getCalledFunction()->getName()))) {
  631. // If the call is a recognized math libary call, it is likely that
  632. // we can vectorize it given loosened floating-point constraints.
  633. LibFunc Func;
  634. bool IsMathLibCall =
  635. TLI && CI->getCalledFunction() &&
  636. CI->getType()->isFloatingPointTy() &&
  637. TLI->getLibFunc(CI->getCalledFunction()->getName(), Func) &&
  638. TLI->hasOptimizedCodeGen(Func);
  639. if (IsMathLibCall) {
  640. // TODO: Ideally, we should not use clang-specific language here,
  641. // but it's hard to provide meaningful yet generic advice.
  642. // Also, should this be guarded by allowExtraAnalysis() and/or be part
  643. // of the returned info from isFunctionVectorizable()?
  644. ORE->emit(createMissedAnalysis("CantVectorizeLibcall", CI)
  645. << "library call cannot be vectorized. "
  646. "Try compiling with -fno-math-errno, -ffast-math, "
  647. "or similar flags");
  648. } else {
  649. ORE->emit(createMissedAnalysis("CantVectorizeCall", CI)
  650. << "call instruction cannot be vectorized");
  651. }
  652. LLVM_DEBUG(
  653. dbgs() << "LV: Found a non-intrinsic callsite.\n");
  654. return false;
  655. }
  656. // Intrinsics such as powi,cttz and ctlz are legal to vectorize if the
  657. // second argument is the same (i.e. loop invariant)
  658. if (CI && hasVectorInstrinsicScalarOpd(
  659. getVectorIntrinsicIDForCall(CI, TLI), 1)) {
  660. auto *SE = PSE.getSE();
  661. if (!SE->isLoopInvariant(PSE.getSCEV(CI->getOperand(1)), TheLoop)) {
  662. ORE->emit(createMissedAnalysis("CantVectorizeIntrinsic", CI)
  663. << "intrinsic instruction cannot be vectorized");
  664. LLVM_DEBUG(dbgs()
  665. << "LV: Found unvectorizable intrinsic " << *CI << "\n");
  666. return false;
  667. }
  668. }
  669. // Check that the instruction return type is vectorizable.
  670. // Also, we can't vectorize extractelement instructions.
  671. if ((!VectorType::isValidElementType(I.getType()) &&
  672. !I.getType()->isVoidTy()) ||
  673. isa<ExtractElementInst>(I)) {
  674. ORE->emit(createMissedAnalysis("CantVectorizeInstructionReturnType", &I)
  675. << "instruction return type cannot be vectorized");
  676. LLVM_DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
  677. return false;
  678. }
  679. // Check that the stored type is vectorizable.
  680. if (auto *ST = dyn_cast<StoreInst>(&I)) {
  681. Type *T = ST->getValueOperand()->getType();
  682. if (!VectorType::isValidElementType(T)) {
  683. ORE->emit(createMissedAnalysis("CantVectorizeStore", ST)
  684. << "store instruction cannot be vectorized");
  685. return false;
  686. }
  687. // FP instructions can allow unsafe algebra, thus vectorizable by
  688. // non-IEEE-754 compliant SIMD units.
  689. // This applies to floating-point math operations and calls, not memory
  690. // operations, shuffles, or casts, as they don't change precision or
  691. // semantics.
  692. } else if (I.getType()->isFloatingPointTy() && (CI || I.isBinaryOp()) &&
  693. !I.isFast()) {
  694. LLVM_DEBUG(dbgs() << "LV: Found FP op with unsafe algebra.\n");
  695. Hints->setPotentiallyUnsafe();
  696. }
  697. // Reduction instructions are allowed to have exit users.
  698. // All other instructions must not have external users.
  699. if (hasOutsideLoopUser(TheLoop, &I, AllowedExit)) {
  700. // We can safely vectorize loops where instructions within the loop are
  701. // used outside the loop only if the SCEV predicates within the loop is
  702. // same as outside the loop. Allowing the exit means reusing the SCEV
  703. // outside the loop.
  704. if (PSE.getUnionPredicate().isAlwaysTrue()) {
  705. AllowedExit.insert(&I);
  706. continue;
  707. }
  708. ORE->emit(createMissedAnalysis("ValueUsedOutsideLoop", &I)
  709. << "value cannot be used outside the loop");
  710. return false;
  711. }
  712. } // next instr.
  713. }
  714. if (!PrimaryInduction) {
  715. LLVM_DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
  716. if (Inductions.empty()) {
  717. ORE->emit(createMissedAnalysis("NoInductionVariable")
  718. << "loop induction variable could not be identified");
  719. return false;
  720. } else if (!WidestIndTy) {
  721. ORE->emit(createMissedAnalysis("NoIntegerInductionVariable")
  722. << "integer loop induction variable could not be identified");
  723. return false;
  724. }
  725. }
  726. // Now we know the widest induction type, check if our found induction
  727. // is the same size. If it's not, unset it here and InnerLoopVectorizer
  728. // will create another.
  729. if (PrimaryInduction && WidestIndTy != PrimaryInduction->getType())
  730. PrimaryInduction = nullptr;
  731. return true;
  732. }
  733. bool LoopVectorizationLegality::canVectorizeMemory() {
  734. LAI = &(*GetLAA)(*TheLoop);
  735. const OptimizationRemarkAnalysis *LAR = LAI->getReport();
  736. if (LAR) {
  737. ORE->emit([&]() {
  738. return OptimizationRemarkAnalysis(Hints->vectorizeAnalysisPassName(),
  739. "loop not vectorized: ", *LAR);
  740. });
  741. }
  742. if (!LAI->canVectorizeMemory())
  743. return false;
  744. if (LAI->hasDependenceInvolvingLoopInvariantAddress()) {
  745. ORE->emit(createMissedAnalysis("CantVectorizeStoreToLoopInvariantAddress")
  746. << "write to a loop invariant address could not "
  747. "be vectorized");
  748. LLVM_DEBUG(
  749. dbgs() << "LV: Non vectorizable stores to a uniform address\n");
  750. return false;
  751. }
  752. Requirements->addRuntimePointerChecks(LAI->getNumRuntimePointerChecks());
  753. PSE.addPredicate(LAI->getPSE().getUnionPredicate());
  754. return true;
  755. }
  756. bool LoopVectorizationLegality::isInductionPhi(const Value *V) {
  757. Value *In0 = const_cast<Value *>(V);
  758. PHINode *PN = dyn_cast_or_null<PHINode>(In0);
  759. if (!PN)
  760. return false;
  761. return Inductions.count(PN);
  762. }
  763. bool LoopVectorizationLegality::isCastedInductionVariable(const Value *V) {
  764. auto *Inst = dyn_cast<Instruction>(V);
  765. return (Inst && InductionCastsToIgnore.count(Inst));
  766. }
  767. bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
  768. return isInductionPhi(V) || isCastedInductionVariable(V);
  769. }
  770. bool LoopVectorizationLegality::isFirstOrderRecurrence(const PHINode *Phi) {
  771. return FirstOrderRecurrences.count(Phi);
  772. }
  773. bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
  774. return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
  775. }
  776. bool LoopVectorizationLegality::blockCanBePredicated(
  777. BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs) {
  778. const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
  779. for (Instruction &I : *BB) {
  780. // Check that we don't have a constant expression that can trap as operand.
  781. for (Value *Operand : I.operands()) {
  782. if (auto *C = dyn_cast<Constant>(Operand))
  783. if (C->canTrap())
  784. return false;
  785. }
  786. // We might be able to hoist the load.
  787. if (I.mayReadFromMemory()) {
  788. auto *LI = dyn_cast<LoadInst>(&I);
  789. if (!LI)
  790. return false;
  791. if (!SafePtrs.count(LI->getPointerOperand())) {
  792. // !llvm.mem.parallel_loop_access implies if-conversion safety.
  793. // Otherwise, record that the load needs (real or emulated) masking
  794. // and let the cost model decide.
  795. if (!IsAnnotatedParallel)
  796. MaskedOp.insert(LI);
  797. continue;
  798. }
  799. }
  800. if (I.mayWriteToMemory()) {
  801. auto *SI = dyn_cast<StoreInst>(&I);
  802. if (!SI)
  803. return false;
  804. // Predicated store requires some form of masking:
  805. // 1) masked store HW instruction,
  806. // 2) emulation via load-blend-store (only if safe and legal to do so,
  807. // be aware on the race conditions), or
  808. // 3) element-by-element predicate check and scalar store.
  809. MaskedOp.insert(SI);
  810. continue;
  811. }
  812. if (I.mayThrow())
  813. return false;
  814. }
  815. return true;
  816. }
  817. bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
  818. if (!EnableIfConversion) {
  819. ORE->emit(createMissedAnalysis("IfConversionDisabled")
  820. << "if-conversion is disabled");
  821. return false;
  822. }
  823. assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
  824. // A list of pointers that we can safely read and write to.
  825. SmallPtrSet<Value *, 8> SafePointes;
  826. // Collect safe addresses.
  827. for (BasicBlock *BB : TheLoop->blocks()) {
  828. if (blockNeedsPredication(BB))
  829. continue;
  830. for (Instruction &I : *BB)
  831. if (auto *Ptr = getLoadStorePointerOperand(&I))
  832. SafePointes.insert(Ptr);
  833. }
  834. // Collect the blocks that need predication.
  835. BasicBlock *Header = TheLoop->getHeader();
  836. for (BasicBlock *BB : TheLoop->blocks()) {
  837. // We don't support switch statements inside loops.
  838. if (!isa<BranchInst>(BB->getTerminator())) {
  839. ORE->emit(createMissedAnalysis("LoopContainsSwitch", BB->getTerminator())
  840. << "loop contains a switch statement");
  841. return false;
  842. }
  843. // We must be able to predicate all blocks that need to be predicated.
  844. if (blockNeedsPredication(BB)) {
  845. if (!blockCanBePredicated(BB, SafePointes)) {
  846. ORE->emit(createMissedAnalysis("NoCFGForSelect", BB->getTerminator())
  847. << "control flow cannot be substituted for a select");
  848. return false;
  849. }
  850. } else if (BB != Header && !canIfConvertPHINodes(BB)) {
  851. ORE->emit(createMissedAnalysis("NoCFGForSelect", BB->getTerminator())
  852. << "control flow cannot be substituted for a select");
  853. return false;
  854. }
  855. }
  856. // We can if-convert this loop.
  857. return true;
  858. }
  859. // Helper function to canVectorizeLoopNestCFG.
  860. bool LoopVectorizationLegality::canVectorizeLoopCFG(Loop *Lp,
  861. bool UseVPlanNativePath) {
  862. assert((UseVPlanNativePath || Lp->empty()) &&
  863. "VPlan-native path is not enabled.");
  864. // TODO: ORE should be improved to show more accurate information when an
  865. // outer loop can't be vectorized because a nested loop is not understood or
  866. // legal. Something like: "outer_loop_location: loop not vectorized:
  867. // (inner_loop_location) loop control flow is not understood by vectorizer".
  868. // Store the result and return it at the end instead of exiting early, in case
  869. // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
  870. bool Result = true;
  871. bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
  872. // We must have a loop in canonical form. Loops with indirectbr in them cannot
  873. // be canonicalized.
  874. if (!Lp->getLoopPreheader()) {
  875. LLVM_DEBUG(dbgs() << "LV: Loop doesn't have a legal pre-header.\n");
  876. ORE->emit(createMissedAnalysis("CFGNotUnderstood")
  877. << "loop control flow is not understood by vectorizer");
  878. if (DoExtraAnalysis)
  879. Result = false;
  880. else
  881. return false;
  882. }
  883. // We must have a single backedge.
  884. if (Lp->getNumBackEdges() != 1) {
  885. ORE->emit(createMissedAnalysis("CFGNotUnderstood")
  886. << "loop control flow is not understood by vectorizer");
  887. if (DoExtraAnalysis)
  888. Result = false;
  889. else
  890. return false;
  891. }
  892. // We must have a single exiting block.
  893. if (!Lp->getExitingBlock()) {
  894. ORE->emit(createMissedAnalysis("CFGNotUnderstood")
  895. << "loop control flow is not understood by vectorizer");
  896. if (DoExtraAnalysis)
  897. Result = false;
  898. else
  899. return false;
  900. }
  901. // We only handle bottom-tested loops, i.e. loop in which the condition is
  902. // checked at the end of each iteration. With that we can assume that all
  903. // instructions in the loop are executed the same number of times.
  904. if (Lp->getExitingBlock() != Lp->getLoopLatch()) {
  905. ORE->emit(createMissedAnalysis("CFGNotUnderstood")
  906. << "loop control flow is not understood by vectorizer");
  907. if (DoExtraAnalysis)
  908. Result = false;
  909. else
  910. return false;
  911. }
  912. return Result;
  913. }
  914. bool LoopVectorizationLegality::canVectorizeLoopNestCFG(
  915. Loop *Lp, bool UseVPlanNativePath) {
  916. // Store the result and return it at the end instead of exiting early, in case
  917. // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
  918. bool Result = true;
  919. bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
  920. if (!canVectorizeLoopCFG(Lp, UseVPlanNativePath)) {
  921. if (DoExtraAnalysis)
  922. Result = false;
  923. else
  924. return false;
  925. }
  926. // Recursively check whether the loop control flow of nested loops is
  927. // understood.
  928. for (Loop *SubLp : *Lp)
  929. if (!canVectorizeLoopNestCFG(SubLp, UseVPlanNativePath)) {
  930. if (DoExtraAnalysis)
  931. Result = false;
  932. else
  933. return false;
  934. }
  935. return Result;
  936. }
  937. bool LoopVectorizationLegality::canVectorize(bool UseVPlanNativePath) {
  938. // Store the result and return it at the end instead of exiting early, in case
  939. // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
  940. bool Result = true;
  941. bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE);
  942. // Check whether the loop-related control flow in the loop nest is expected by
  943. // vectorizer.
  944. if (!canVectorizeLoopNestCFG(TheLoop, UseVPlanNativePath)) {
  945. if (DoExtraAnalysis)
  946. Result = false;
  947. else
  948. return false;
  949. }
  950. // We need to have a loop header.
  951. LLVM_DEBUG(dbgs() << "LV: Found a loop: " << TheLoop->getHeader()->getName()
  952. << '\n');
  953. // Specific checks for outer loops. We skip the remaining legal checks at this
  954. // point because they don't support outer loops.
  955. if (!TheLoop->empty()) {
  956. assert(UseVPlanNativePath && "VPlan-native path is not enabled.");
  957. if (!canVectorizeOuterLoop()) {
  958. LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Unsupported outer loop.\n");
  959. // TODO: Implement DoExtraAnalysis when subsequent legal checks support
  960. // outer loops.
  961. return false;
  962. }
  963. LLVM_DEBUG(dbgs() << "LV: We can vectorize this outer loop!\n");
  964. return Result;
  965. }
  966. assert(TheLoop->empty() && "Inner loop expected.");
  967. // Check if we can if-convert non-single-bb loops.
  968. unsigned NumBlocks = TheLoop->getNumBlocks();
  969. if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
  970. LLVM_DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
  971. if (DoExtraAnalysis)
  972. Result = false;
  973. else
  974. return false;
  975. }
  976. // Check if we can vectorize the instructions and CFG in this loop.
  977. if (!canVectorizeInstrs()) {
  978. LLVM_DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
  979. if (DoExtraAnalysis)
  980. Result = false;
  981. else
  982. return false;
  983. }
  984. // Go over each instruction and look at memory deps.
  985. if (!canVectorizeMemory()) {
  986. LLVM_DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
  987. if (DoExtraAnalysis)
  988. Result = false;
  989. else
  990. return false;
  991. }
  992. LLVM_DEBUG(dbgs() << "LV: We can vectorize this loop"
  993. << (LAI->getRuntimePointerChecking()->Need
  994. ? " (with a runtime bound check)"
  995. : "")
  996. << "!\n");
  997. unsigned SCEVThreshold = VectorizeSCEVCheckThreshold;
  998. if (Hints->getForce() == LoopVectorizeHints::FK_Enabled)
  999. SCEVThreshold = PragmaVectorizeSCEVCheckThreshold;
  1000. if (PSE.getUnionPredicate().getComplexity() > SCEVThreshold) {
  1001. ORE->emit(createMissedAnalysis("TooManySCEVRunTimeChecks")
  1002. << "Too many SCEV assumptions need to be made and checked "
  1003. << "at runtime");
  1004. LLVM_DEBUG(dbgs() << "LV: Too many SCEV checks needed.\n");
  1005. if (DoExtraAnalysis)
  1006. Result = false;
  1007. else
  1008. return false;
  1009. }
  1010. // Okay! We've done all the tests. If any have failed, return false. Otherwise
  1011. // we can vectorize, and at this point we don't have any other mem analysis
  1012. // which may limit our maximum vectorization factor, so just return true with
  1013. // no restrictions.
  1014. return Result;
  1015. }
  1016. bool LoopVectorizationLegality::canFoldTailByMasking() {
  1017. LLVM_DEBUG(dbgs() << "LV: checking if tail can be folded by masking.\n");
  1018. if (!PrimaryInduction) {
  1019. ORE->emit(createMissedAnalysis("NoPrimaryInduction")
  1020. << "Missing a primary induction variable in the loop, which is "
  1021. << "needed in order to fold tail by masking as required.");
  1022. LLVM_DEBUG(dbgs() << "LV: No primary induction, cannot fold tail by "
  1023. << "masking.\n");
  1024. return false;
  1025. }
  1026. // TODO: handle reductions when tail is folded by masking.
  1027. if (!Reductions.empty()) {
  1028. ORE->emit(createMissedAnalysis("ReductionFoldingTailByMasking")
  1029. << "Cannot fold tail by masking in the presence of reductions.");
  1030. LLVM_DEBUG(dbgs() << "LV: Loop has reductions, cannot fold tail by "
  1031. << "masking.\n");
  1032. return false;
  1033. }
  1034. // TODO: handle outside users when tail is folded by masking.
  1035. for (auto *AE : AllowedExit) {
  1036. // Check that all users of allowed exit values are inside the loop.
  1037. for (User *U : AE->users()) {
  1038. Instruction *UI = cast<Instruction>(U);
  1039. if (TheLoop->contains(UI))
  1040. continue;
  1041. ORE->emit(createMissedAnalysis("LiveOutFoldingTailByMasking")
  1042. << "Cannot fold tail by masking in the presence of live outs.");
  1043. LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking, loop has an "
  1044. << "outside user for : " << *UI << '\n');
  1045. return false;
  1046. }
  1047. }
  1048. // The list of pointers that we can safely read and write to remains empty.
  1049. SmallPtrSet<Value *, 8> SafePointers;
  1050. // Check and mark all blocks for predication, including those that ordinarily
  1051. // do not need predication such as the header block.
  1052. for (BasicBlock *BB : TheLoop->blocks()) {
  1053. if (!blockCanBePredicated(BB, SafePointers)) {
  1054. ORE->emit(createMissedAnalysis("NoCFGForSelect", BB->getTerminator())
  1055. << "control flow cannot be substituted for a select");
  1056. LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking as required.\n");
  1057. return false;
  1058. }
  1059. }
  1060. LLVM_DEBUG(dbgs() << "LV: can fold tail by masking.\n");
  1061. return true;
  1062. }
  1063. } // namespace llvm