LoopVectorize.cpp 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400
  1. //===- LoopVectorize.cpp - A Loop Vectorizer ------------------------------===//
  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. #include "LoopVectorize.h"
  10. #include "llvm/ADT/StringExtras.h"
  11. #include "llvm/Analysis/AliasAnalysis.h"
  12. #include "llvm/Analysis/AliasSetTracker.h"
  13. #include "llvm/Analysis/Dominators.h"
  14. #include "llvm/Analysis/LoopInfo.h"
  15. #include "llvm/Analysis/LoopIterator.h"
  16. #include "llvm/Analysis/LoopPass.h"
  17. #include "llvm/Analysis/ScalarEvolutionExpander.h"
  18. #include "llvm/Analysis/ScalarEvolutionExpressions.h"
  19. #include "llvm/Analysis/ValueTracking.h"
  20. #include "llvm/Analysis/Verifier.h"
  21. #include "llvm/IR/Constants.h"
  22. #include "llvm/IR/DataLayout.h"
  23. #include "llvm/IR/DerivedTypes.h"
  24. #include "llvm/IR/Function.h"
  25. #include "llvm/IR/Instructions.h"
  26. #include "llvm/IR/IntrinsicInst.h"
  27. #include "llvm/IR/LLVMContext.h"
  28. #include "llvm/IR/Module.h"
  29. #include "llvm/IR/Type.h"
  30. #include "llvm/IR/Value.h"
  31. #include "llvm/Pass.h"
  32. #include "llvm/Support/CommandLine.h"
  33. #include "llvm/Support/Debug.h"
  34. #include "llvm/Support/raw_ostream.h"
  35. #include "llvm/TargetTransformInfo.h"
  36. #include "llvm/Transforms/Scalar.h"
  37. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  38. #include "llvm/Transforms/Utils/Local.h"
  39. #include "llvm/Transforms/Vectorize.h"
  40. static cl::opt<unsigned>
  41. VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
  42. cl::desc("Sets the SIMD width. Zero is autoselect."));
  43. static cl::opt<unsigned>
  44. VectorizationUnroll("force-vector-unroll", cl::init(1), cl::Hidden,
  45. cl::desc("Sets the vectorization unroll count. "
  46. "Zero is autoselect."));
  47. static cl::opt<bool>
  48. EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
  49. cl::desc("Enable if-conversion during vectorization."));
  50. namespace {
  51. /// The LoopVectorize Pass.
  52. struct LoopVectorize : public LoopPass {
  53. /// Pass identification, replacement for typeid
  54. static char ID;
  55. explicit LoopVectorize() : LoopPass(ID) {
  56. initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
  57. }
  58. ScalarEvolution *SE;
  59. DataLayout *DL;
  60. LoopInfo *LI;
  61. TargetTransformInfo *TTI;
  62. DominatorTree *DT;
  63. virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
  64. // We only vectorize innermost loops.
  65. if (!L->empty())
  66. return false;
  67. SE = &getAnalysis<ScalarEvolution>();
  68. DL = getAnalysisIfAvailable<DataLayout>();
  69. LI = &getAnalysis<LoopInfo>();
  70. TTI = getAnalysisIfAvailable<TargetTransformInfo>();
  71. DT = &getAnalysis<DominatorTree>();
  72. DEBUG(dbgs() << "LV: Checking a loop in \"" <<
  73. L->getHeader()->getParent()->getName() << "\"\n");
  74. // Check if it is legal to vectorize the loop.
  75. LoopVectorizationLegality LVL(L, SE, DL, DT);
  76. if (!LVL.canVectorize()) {
  77. DEBUG(dbgs() << "LV: Not vectorizing.\n");
  78. return false;
  79. }
  80. // Select the preffered vectorization factor.
  81. const VectorTargetTransformInfo *VTTI = 0;
  82. if (TTI)
  83. VTTI = TTI->getVectorTargetTransformInfo();
  84. // Use the cost model.
  85. LoopVectorizationCostModel CM(L, SE, &LVL, VTTI);
  86. // Check the function attribues to find out if this function should be
  87. // optimized for size.
  88. Function *F = L->getHeader()->getParent();
  89. Attribute::AttrKind SzAttr = Attribute::OptimizeForSize;
  90. Attribute::AttrKind FlAttr = Attribute::NoImplicitFloat;
  91. unsigned FnIndex = AttributeSet::FunctionIndex;
  92. bool OptForSize = F->getAttributes().hasAttribute(FnIndex, SzAttr);
  93. bool NoFloat = F->getAttributes().hasAttribute(FnIndex, FlAttr);
  94. if (NoFloat) {
  95. DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
  96. "attribute is used.\n");
  97. return false;
  98. }
  99. unsigned VF = CM.selectVectorizationFactor(OptForSize, VectorizationFactor);
  100. if (VF == 1) {
  101. DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
  102. return false;
  103. }
  104. DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< VF << ") in "<<
  105. F->getParent()->getModuleIdentifier()<<"\n");
  106. // If we decided that it is *legal* to vectorizer the loop then do it.
  107. InnerLoopVectorizer LB(L, SE, LI, DT, DL, VF, VectorizationUnroll);
  108. LB.vectorize(&LVL);
  109. DEBUG(verifyFunction(*L->getHeader()->getParent()));
  110. return true;
  111. }
  112. virtual void getAnalysisUsage(AnalysisUsage &AU) const {
  113. LoopPass::getAnalysisUsage(AU);
  114. AU.addRequiredID(LoopSimplifyID);
  115. AU.addRequiredID(LCSSAID);
  116. AU.addRequired<LoopInfo>();
  117. AU.addRequired<ScalarEvolution>();
  118. AU.addRequired<DominatorTree>();
  119. AU.addPreserved<LoopInfo>();
  120. AU.addPreserved<DominatorTree>();
  121. }
  122. };
  123. }// namespace
  124. //===----------------------------------------------------------------------===//
  125. // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
  126. // LoopVectorizationCostModel.
  127. //===----------------------------------------------------------------------===//
  128. void
  129. LoopVectorizationLegality::RuntimePointerCheck::insert(ScalarEvolution *SE,
  130. Loop *Lp, Value *Ptr) {
  131. const SCEV *Sc = SE->getSCEV(Ptr);
  132. const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
  133. assert(AR && "Invalid addrec expression");
  134. const SCEV *Ex = SE->getExitCount(Lp, Lp->getLoopLatch());
  135. const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
  136. Pointers.push_back(Ptr);
  137. Starts.push_back(AR->getStart());
  138. Ends.push_back(ScEnd);
  139. }
  140. Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
  141. // Save the current insertion location.
  142. Instruction *Loc = Builder.GetInsertPoint();
  143. // We need to place the broadcast of invariant variables outside the loop.
  144. Instruction *Instr = dyn_cast<Instruction>(V);
  145. bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody);
  146. bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
  147. // Place the code for broadcasting invariant variables in the new preheader.
  148. if (Invariant)
  149. Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
  150. // Broadcast the scalar into all locations in the vector.
  151. Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
  152. // Restore the builder insertion point.
  153. if (Invariant)
  154. Builder.SetInsertPoint(Loc);
  155. return Shuf;
  156. }
  157. Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, unsigned StartIdx,
  158. bool Negate) {
  159. assert(Val->getType()->isVectorTy() && "Must be a vector");
  160. assert(Val->getType()->getScalarType()->isIntegerTy() &&
  161. "Elem must be an integer");
  162. // Create the types.
  163. Type *ITy = Val->getType()->getScalarType();
  164. VectorType *Ty = cast<VectorType>(Val->getType());
  165. int VLen = Ty->getNumElements();
  166. SmallVector<Constant*, 8> Indices;
  167. // Create a vector of consecutive numbers from zero to VF.
  168. for (int i = 0; i < VLen; ++i) {
  169. int Idx = Negate ? (-i): i;
  170. Indices.push_back(ConstantInt::get(ITy, StartIdx + Idx));
  171. }
  172. // Add the consecutive indices to the vector value.
  173. Constant *Cv = ConstantVector::get(Indices);
  174. assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
  175. return Builder.CreateAdd(Val, Cv, "induction");
  176. }
  177. int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
  178. assert(Ptr->getType()->isPointerTy() && "Unexpected non ptr");
  179. // If this value is a pointer induction variable we know it is consecutive.
  180. PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
  181. if (Phi && Inductions.count(Phi)) {
  182. InductionInfo II = Inductions[Phi];
  183. if (PtrInduction == II.IK)
  184. return 1;
  185. }
  186. GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
  187. if (!Gep)
  188. return 0;
  189. unsigned NumOperands = Gep->getNumOperands();
  190. Value *LastIndex = Gep->getOperand(NumOperands - 1);
  191. // Check that all of the gep indices are uniform except for the last.
  192. for (unsigned i = 0; i < NumOperands - 1; ++i)
  193. if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
  194. return 0;
  195. // We can emit wide load/stores only if the last index is the induction
  196. // variable.
  197. const SCEV *Last = SE->getSCEV(LastIndex);
  198. if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
  199. const SCEV *Step = AR->getStepRecurrence(*SE);
  200. // The memory is consecutive because the last index is consecutive
  201. // and all other indices are loop invariant.
  202. if (Step->isOne())
  203. return 1;
  204. if (Step->isAllOnesValue())
  205. return -1;
  206. }
  207. return 0;
  208. }
  209. bool LoopVectorizationLegality::isUniform(Value *V) {
  210. return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
  211. }
  212. InnerLoopVectorizer::VectorParts&
  213. InnerLoopVectorizer::getVectorValue(Value *V) {
  214. assert(V != Induction && "The new induction variable should not be used.");
  215. assert(!V->getType()->isVectorTy() && "Can't widen a vector");
  216. // If we have this scalar in the map, return it.
  217. if (WidenMap.has(V))
  218. return WidenMap.get(V);
  219. // If this scalar is unknown, assume that it is a constant or that it is
  220. // loop invariant. Broadcast V and save the value for future uses.
  221. Value *B = getBroadcastInstrs(V);
  222. WidenMap.splat(V, B);
  223. return WidenMap.get(V);
  224. }
  225. Constant*
  226. InnerLoopVectorizer::getUniformVector(unsigned Val, Type* ScalarTy) {
  227. return ConstantVector::getSplat(VF, ConstantInt::get(ScalarTy, Val, true));
  228. }
  229. Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
  230. assert(Vec->getType()->isVectorTy() && "Invalid type");
  231. SmallVector<Constant*, 8> ShuffleMask;
  232. for (unsigned i = 0; i < VF; ++i)
  233. ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
  234. return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
  235. ConstantVector::get(ShuffleMask),
  236. "reverse");
  237. }
  238. void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
  239. assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
  240. // Holds vector parameters or scalars, in case of uniform vals.
  241. SmallVector<VectorParts, 4> Params;
  242. // Find all of the vectorized parameters.
  243. for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
  244. Value *SrcOp = Instr->getOperand(op);
  245. // If we are accessing the old induction variable, use the new one.
  246. if (SrcOp == OldInduction) {
  247. Params.push_back(getVectorValue(SrcOp));
  248. continue;
  249. }
  250. // Try using previously calculated values.
  251. Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
  252. // If the src is an instruction that appeared earlier in the basic block
  253. // then it should already be vectorized.
  254. if (SrcInst && OrigLoop->contains(SrcInst)) {
  255. assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
  256. // The parameter is a vector value from earlier.
  257. Params.push_back(WidenMap.get(SrcInst));
  258. } else {
  259. // The parameter is a scalar from outside the loop. Maybe even a constant.
  260. VectorParts Scalars;
  261. Scalars.append(UF, SrcOp);
  262. Params.push_back(Scalars);
  263. }
  264. }
  265. assert(Params.size() == Instr->getNumOperands() &&
  266. "Invalid number of operands");
  267. // Does this instruction return a value ?
  268. bool IsVoidRetTy = Instr->getType()->isVoidTy();
  269. Value *UndefVec = IsVoidRetTy ? 0 :
  270. UndefValue::get(VectorType::get(Instr->getType(), VF));
  271. // Create a new entry in the WidenMap and initialize it to Undef or Null.
  272. VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
  273. // For each scalar that we create:
  274. for (unsigned Width = 0; Width < VF; ++Width) {
  275. // For each vector unroll 'part':
  276. for (unsigned Part = 0; Part < UF; ++Part) {
  277. Instruction *Cloned = Instr->clone();
  278. if (!IsVoidRetTy)
  279. Cloned->setName(Instr->getName() + ".cloned");
  280. // Replace the operands of the cloned instrucions with extracted scalars.
  281. for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
  282. Value *Op = Params[op][Part];
  283. // Param is a vector. Need to extract the right lane.
  284. if (Op->getType()->isVectorTy())
  285. Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
  286. Cloned->setOperand(op, Op);
  287. }
  288. // Place the cloned scalar in the new loop.
  289. Builder.Insert(Cloned);
  290. // If the original scalar returns a value we need to place it in a vector
  291. // so that future users will be able to use it.
  292. if (!IsVoidRetTy)
  293. VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
  294. Builder.getInt32(Width));
  295. }
  296. }
  297. }
  298. Value*
  299. InnerLoopVectorizer::addRuntimeCheck(LoopVectorizationLegality *Legal,
  300. Instruction *Loc) {
  301. LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
  302. Legal->getRuntimePointerCheck();
  303. if (!PtrRtCheck->Need)
  304. return NULL;
  305. Value *MemoryRuntimeCheck = 0;
  306. unsigned NumPointers = PtrRtCheck->Pointers.size();
  307. SmallVector<Value* , 2> Starts;
  308. SmallVector<Value* , 2> Ends;
  309. SCEVExpander Exp(*SE, "induction");
  310. // Use this type for pointer arithmetic.
  311. Type* PtrArithTy = Type::getInt8PtrTy(Loc->getContext(), 0);
  312. for (unsigned i = 0; i < NumPointers; ++i) {
  313. Value *Ptr = PtrRtCheck->Pointers[i];
  314. const SCEV *Sc = SE->getSCEV(Ptr);
  315. if (SE->isLoopInvariant(Sc, OrigLoop)) {
  316. DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
  317. *Ptr <<"\n");
  318. Starts.push_back(Ptr);
  319. Ends.push_back(Ptr);
  320. } else {
  321. DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr <<"\n");
  322. Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
  323. Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
  324. Starts.push_back(Start);
  325. Ends.push_back(End);
  326. }
  327. }
  328. for (unsigned i = 0; i < NumPointers; ++i) {
  329. for (unsigned j = i+1; j < NumPointers; ++j) {
  330. Instruction::CastOps Op = Instruction::BitCast;
  331. Value *Start0 = CastInst::Create(Op, Starts[i], PtrArithTy, "bc", Loc);
  332. Value *Start1 = CastInst::Create(Op, Starts[j], PtrArithTy, "bc", Loc);
  333. Value *End0 = CastInst::Create(Op, Ends[i], PtrArithTy, "bc", Loc);
  334. Value *End1 = CastInst::Create(Op, Ends[j], PtrArithTy, "bc", Loc);
  335. Value *Cmp0 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_ULE,
  336. Start0, End1, "bound0", Loc);
  337. Value *Cmp1 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_ULE,
  338. Start1, End0, "bound1", Loc);
  339. Value *IsConflict = BinaryOperator::Create(Instruction::And, Cmp0, Cmp1,
  340. "found.conflict", Loc);
  341. if (MemoryRuntimeCheck)
  342. MemoryRuntimeCheck = BinaryOperator::Create(Instruction::Or,
  343. MemoryRuntimeCheck,
  344. IsConflict,
  345. "conflict.rdx", Loc);
  346. else
  347. MemoryRuntimeCheck = IsConflict;
  348. }
  349. }
  350. return MemoryRuntimeCheck;
  351. }
  352. void
  353. InnerLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) {
  354. /*
  355. In this function we generate a new loop. The new loop will contain
  356. the vectorized instructions while the old loop will continue to run the
  357. scalar remainder.
  358. [ ] <-- vector loop bypass.
  359. / |
  360. / v
  361. | [ ] <-- vector pre header.
  362. | |
  363. | v
  364. | [ ] \
  365. | [ ]_| <-- vector loop.
  366. | |
  367. \ v
  368. >[ ] <--- middle-block.
  369. / |
  370. / v
  371. | [ ] <--- new preheader.
  372. | |
  373. | v
  374. | [ ] \
  375. | [ ]_| <-- old scalar loop to handle remainder.
  376. \ |
  377. \ v
  378. >[ ] <-- exit block.
  379. ...
  380. */
  381. BasicBlock *OldBasicBlock = OrigLoop->getHeader();
  382. BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
  383. BasicBlock *ExitBlock = OrigLoop->getExitBlock();
  384. assert(ExitBlock && "Must have an exit block");
  385. // Some loops have a single integer induction variable, while other loops
  386. // don't. One example is c++ iterators that often have multiple pointer
  387. // induction variables. In the code below we also support a case where we
  388. // don't have a single induction variable.
  389. OldInduction = Legal->getInduction();
  390. Type *IdxTy = OldInduction ? OldInduction->getType() :
  391. DL->getIntPtrType(SE->getContext());
  392. // Find the loop boundaries.
  393. const SCEV *ExitCount = SE->getExitCount(OrigLoop, OrigLoop->getLoopLatch());
  394. assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
  395. // Get the total trip count from the count by adding 1.
  396. ExitCount = SE->getAddExpr(ExitCount,
  397. SE->getConstant(ExitCount->getType(), 1));
  398. // Expand the trip count and place the new instructions in the preheader.
  399. // Notice that the pre-header does not change, only the loop body.
  400. SCEVExpander Exp(*SE, "induction");
  401. // Count holds the overall loop count (N).
  402. Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
  403. BypassBlock->getTerminator());
  404. // The loop index does not have to start at Zero. Find the original start
  405. // value from the induction PHI node. If we don't have an induction variable
  406. // then we know that it starts at zero.
  407. Value *StartIdx = OldInduction ?
  408. OldInduction->getIncomingValueForBlock(BypassBlock):
  409. ConstantInt::get(IdxTy, 0);
  410. assert(BypassBlock && "Invalid loop structure");
  411. // Generate the code that checks in runtime if arrays overlap.
  412. Value *MemoryRuntimeCheck = addRuntimeCheck(Legal,
  413. BypassBlock->getTerminator());
  414. // Split the single block loop into the two loop structure described above.
  415. BasicBlock *VectorPH =
  416. BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
  417. BasicBlock *VecBody =
  418. VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
  419. BasicBlock *MiddleBlock =
  420. VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
  421. BasicBlock *ScalarPH =
  422. MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
  423. // This is the location in which we add all of the logic for bypassing
  424. // the new vector loop.
  425. Instruction *Loc = BypassBlock->getTerminator();
  426. // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
  427. // inside the loop.
  428. Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
  429. // Generate the induction variable.
  430. Induction = Builder.CreatePHI(IdxTy, 2, "index");
  431. // The loop step is equal to the vectorization factor (num of SIMD elements)
  432. // times the unroll factor (num of SIMD instructions).
  433. Constant *Step = ConstantInt::get(IdxTy, VF * UF);
  434. // We may need to extend the index in case there is a type mismatch.
  435. // We know that the count starts at zero and does not overflow.
  436. if (Count->getType() != IdxTy) {
  437. // The exit count can be of pointer type. Convert it to the correct
  438. // integer type.
  439. if (ExitCount->getType()->isPointerTy())
  440. Count = CastInst::CreatePointerCast(Count, IdxTy, "ptrcnt.to.int", Loc);
  441. else
  442. Count = CastInst::CreateZExtOrBitCast(Count, IdxTy, "zext.cnt", Loc);
  443. }
  444. // Add the start index to the loop count to get the new end index.
  445. Value *IdxEnd = BinaryOperator::CreateAdd(Count, StartIdx, "end.idx", Loc);
  446. // Now we need to generate the expression for N - (N % VF), which is
  447. // the part that the vectorized body will execute.
  448. Value *R = BinaryOperator::CreateURem(Count, Step, "n.mod.vf", Loc);
  449. Value *CountRoundDown = BinaryOperator::CreateSub(Count, R, "n.vec", Loc);
  450. Value *IdxEndRoundDown = BinaryOperator::CreateAdd(CountRoundDown, StartIdx,
  451. "end.idx.rnd.down", Loc);
  452. // Now, compare the new count to zero. If it is zero skip the vector loop and
  453. // jump to the scalar loop.
  454. Value *Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
  455. IdxEndRoundDown,
  456. StartIdx,
  457. "cmp.zero", Loc);
  458. // If we are using memory runtime checks, include them in.
  459. if (MemoryRuntimeCheck)
  460. Cmp = BinaryOperator::Create(Instruction::Or, Cmp, MemoryRuntimeCheck,
  461. "CntOrMem", Loc);
  462. BranchInst::Create(MiddleBlock, VectorPH, Cmp, Loc);
  463. // Remove the old terminator.
  464. Loc->eraseFromParent();
  465. // We are going to resume the execution of the scalar loop.
  466. // Go over all of the induction variables that we found and fix the
  467. // PHIs that are left in the scalar version of the loop.
  468. // The starting values of PHI nodes depend on the counter of the last
  469. // iteration in the vectorized loop.
  470. // If we come from a bypass edge then we need to start from the original
  471. // start value.
  472. // This variable saves the new starting index for the scalar loop.
  473. PHINode *ResumeIndex = 0;
  474. LoopVectorizationLegality::InductionList::iterator I, E;
  475. LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
  476. for (I = List->begin(), E = List->end(); I != E; ++I) {
  477. PHINode *OrigPhi = I->first;
  478. LoopVectorizationLegality::InductionInfo II = I->second;
  479. PHINode *ResumeVal = PHINode::Create(OrigPhi->getType(), 2, "resume.val",
  480. MiddleBlock->getTerminator());
  481. Value *EndValue = 0;
  482. switch (II.IK) {
  483. case LoopVectorizationLegality::NoInduction:
  484. llvm_unreachable("Unknown induction");
  485. case LoopVectorizationLegality::IntInduction: {
  486. // Handle the integer induction counter:
  487. assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
  488. assert(OrigPhi == OldInduction && "Unknown integer PHI");
  489. // We know what the end value is.
  490. EndValue = IdxEndRoundDown;
  491. // We also know which PHI node holds it.
  492. ResumeIndex = ResumeVal;
  493. break;
  494. }
  495. case LoopVectorizationLegality::ReverseIntInduction: {
  496. // Convert the CountRoundDown variable to the PHI size.
  497. unsigned CRDSize = CountRoundDown->getType()->getScalarSizeInBits();
  498. unsigned IISize = II.StartValue->getType()->getScalarSizeInBits();
  499. Value *CRD = CountRoundDown;
  500. if (CRDSize > IISize)
  501. CRD = CastInst::Create(Instruction::Trunc, CountRoundDown,
  502. II.StartValue->getType(),
  503. "tr.crd", BypassBlock->getTerminator());
  504. else if (CRDSize < IISize)
  505. CRD = CastInst::Create(Instruction::SExt, CountRoundDown,
  506. II.StartValue->getType(),
  507. "sext.crd", BypassBlock->getTerminator());
  508. // Handle reverse integer induction counter:
  509. EndValue = BinaryOperator::CreateSub(II.StartValue, CRD, "rev.ind.end",
  510. BypassBlock->getTerminator());
  511. break;
  512. }
  513. case LoopVectorizationLegality::PtrInduction: {
  514. // For pointer induction variables, calculate the offset using
  515. // the end index.
  516. EndValue = GetElementPtrInst::Create(II.StartValue, CountRoundDown,
  517. "ptr.ind.end",
  518. BypassBlock->getTerminator());
  519. break;
  520. }
  521. }// end of case
  522. // The new PHI merges the original incoming value, in case of a bypass,
  523. // or the value at the end of the vectorized loop.
  524. ResumeVal->addIncoming(II.StartValue, BypassBlock);
  525. ResumeVal->addIncoming(EndValue, VecBody);
  526. // Fix the scalar body counter (PHI node).
  527. unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
  528. OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
  529. }
  530. // If we are generating a new induction variable then we also need to
  531. // generate the code that calculates the exit value. This value is not
  532. // simply the end of the counter because we may skip the vectorized body
  533. // in case of a runtime check.
  534. if (!OldInduction){
  535. assert(!ResumeIndex && "Unexpected resume value found");
  536. ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
  537. MiddleBlock->getTerminator());
  538. ResumeIndex->addIncoming(StartIdx, BypassBlock);
  539. ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
  540. }
  541. // Make sure that we found the index where scalar loop needs to continue.
  542. assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
  543. "Invalid resume Index");
  544. // Add a check in the middle block to see if we have completed
  545. // all of the iterations in the first vector loop.
  546. // If (N - N%VF) == N, then we *don't* need to run the remainder.
  547. Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
  548. ResumeIndex, "cmp.n",
  549. MiddleBlock->getTerminator());
  550. BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
  551. // Remove the old terminator.
  552. MiddleBlock->getTerminator()->eraseFromParent();
  553. // Create i+1 and fill the PHINode.
  554. Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
  555. Induction->addIncoming(StartIdx, VectorPH);
  556. Induction->addIncoming(NextIdx, VecBody);
  557. // Create the compare.
  558. Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
  559. Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
  560. // Now we have two terminators. Remove the old one from the block.
  561. VecBody->getTerminator()->eraseFromParent();
  562. // Get ready to start creating new instructions into the vectorized body.
  563. Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
  564. // Create and register the new vector loop.
  565. Loop* Lp = new Loop();
  566. Loop *ParentLoop = OrigLoop->getParentLoop();
  567. // Insert the new loop into the loop nest and register the new basic blocks.
  568. if (ParentLoop) {
  569. ParentLoop->addChildLoop(Lp);
  570. ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
  571. ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
  572. ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
  573. } else {
  574. LI->addTopLevelLoop(Lp);
  575. }
  576. Lp->addBasicBlockToLoop(VecBody, LI->getBase());
  577. // Save the state.
  578. LoopVectorPreHeader = VectorPH;
  579. LoopScalarPreHeader = ScalarPH;
  580. LoopMiddleBlock = MiddleBlock;
  581. LoopExitBlock = ExitBlock;
  582. LoopVectorBody = VecBody;
  583. LoopScalarBody = OldBasicBlock;
  584. LoopBypassBlock = BypassBlock;
  585. }
  586. /// This function returns the identity element (or neutral element) for
  587. /// the operation K.
  588. static unsigned
  589. getReductionIdentity(LoopVectorizationLegality::ReductionKind K) {
  590. switch (K) {
  591. case LoopVectorizationLegality::IntegerXor:
  592. case LoopVectorizationLegality::IntegerAdd:
  593. case LoopVectorizationLegality::IntegerOr:
  594. // Adding, Xoring, Oring zero to a number does not change it.
  595. return 0;
  596. case LoopVectorizationLegality::IntegerMult:
  597. // Multiplying a number by 1 does not change it.
  598. return 1;
  599. case LoopVectorizationLegality::IntegerAnd:
  600. // AND-ing a number with an all-1 value does not change it.
  601. return -1;
  602. default:
  603. llvm_unreachable("Unknown reduction kind");
  604. }
  605. }
  606. static bool
  607. isTriviallyVectorizableIntrinsic(Instruction *Inst) {
  608. IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst);
  609. if (!II)
  610. return false;
  611. switch (II->getIntrinsicID()) {
  612. case Intrinsic::sqrt:
  613. case Intrinsic::sin:
  614. case Intrinsic::cos:
  615. case Intrinsic::exp:
  616. case Intrinsic::exp2:
  617. case Intrinsic::log:
  618. case Intrinsic::log10:
  619. case Intrinsic::log2:
  620. case Intrinsic::fabs:
  621. case Intrinsic::floor:
  622. case Intrinsic::ceil:
  623. case Intrinsic::trunc:
  624. case Intrinsic::rint:
  625. case Intrinsic::nearbyint:
  626. case Intrinsic::pow:
  627. case Intrinsic::fma:
  628. case Intrinsic::fmuladd:
  629. return true;
  630. default:
  631. return false;
  632. }
  633. return false;
  634. }
  635. void
  636. InnerLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) {
  637. //===------------------------------------------------===//
  638. //
  639. // Notice: any optimization or new instruction that go
  640. // into the code below should be also be implemented in
  641. // the cost-model.
  642. //
  643. //===------------------------------------------------===//
  644. BasicBlock &BB = *OrigLoop->getHeader();
  645. Constant *Zero =
  646. ConstantInt::get(IntegerType::getInt32Ty(BB.getContext()), 0);
  647. // In order to support reduction variables we need to be able to vectorize
  648. // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
  649. // stages. First, we create a new vector PHI node with no incoming edges.
  650. // We use this value when we vectorize all of the instructions that use the
  651. // PHI. Next, after all of the instructions in the block are complete we
  652. // add the new incoming edges to the PHI. At this point all of the
  653. // instructions in the basic block are vectorized, so we can use them to
  654. // construct the PHI.
  655. PhiVector RdxPHIsToFix;
  656. // Scan the loop in a topological order to ensure that defs are vectorized
  657. // before users.
  658. LoopBlocksDFS DFS(OrigLoop);
  659. DFS.perform(LI);
  660. // Vectorize all of the blocks in the original loop.
  661. for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
  662. be = DFS.endRPO(); bb != be; ++bb)
  663. vectorizeBlockInLoop(Legal, *bb, &RdxPHIsToFix);
  664. // At this point every instruction in the original loop is widened to
  665. // a vector form. We are almost done. Now, we need to fix the PHI nodes
  666. // that we vectorized. The PHI nodes are currently empty because we did
  667. // not want to introduce cycles. Notice that the remaining PHI nodes
  668. // that we need to fix are reduction variables.
  669. // Create the 'reduced' values for each of the induction vars.
  670. // The reduced values are the vector values that we scalarize and combine
  671. // after the loop is finished.
  672. for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
  673. it != e; ++it) {
  674. PHINode *RdxPhi = *it;
  675. assert(RdxPhi && "Unable to recover vectorized PHI");
  676. // Find the reduction variable descriptor.
  677. assert(Legal->getReductionVars()->count(RdxPhi) &&
  678. "Unable to find the reduction variable");
  679. LoopVectorizationLegality::ReductionDescriptor RdxDesc =
  680. (*Legal->getReductionVars())[RdxPhi];
  681. // We need to generate a reduction vector from the incoming scalar.
  682. // To do so, we need to generate the 'identity' vector and overide
  683. // one of the elements with the incoming scalar reduction. We need
  684. // to do it in the vector-loop preheader.
  685. Builder.SetInsertPoint(LoopBypassBlock->getTerminator());
  686. // This is the vector-clone of the value that leaves the loop.
  687. VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
  688. Type *VecTy = VectorExit[0]->getType();
  689. // Find the reduction identity variable. Zero for addition, or, xor,
  690. // one for multiplication, -1 for And.
  691. Constant *Identity = getUniformVector(getReductionIdentity(RdxDesc.Kind),
  692. VecTy->getScalarType());
  693. // This vector is the Identity vector where the first element is the
  694. // incoming scalar reduction.
  695. Value *VectorStart = Builder.CreateInsertElement(Identity,
  696. RdxDesc.StartValue, Zero);
  697. // Fix the vector-loop phi.
  698. // We created the induction variable so we know that the
  699. // preheader is the first entry.
  700. BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
  701. // Reductions do not have to start at zero. They can start with
  702. // any loop invariant values.
  703. VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
  704. BasicBlock *Latch = OrigLoop->getLoopLatch();
  705. Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
  706. VectorParts &Val = getVectorValue(LoopVal);
  707. for (unsigned part = 0; part < UF; ++part) {
  708. // Make sure to add the reduction stat value only to the
  709. // first unroll part.
  710. Value *StartVal = (part == 0) ? VectorStart : Identity;
  711. cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader);
  712. cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part], LoopVectorBody);
  713. }
  714. // Before each round, move the insertion point right between
  715. // the PHIs and the values we are going to write.
  716. // This allows us to write both PHINodes and the extractelement
  717. // instructions.
  718. Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
  719. VectorParts RdxParts;
  720. for (unsigned part = 0; part < UF; ++part) {
  721. // This PHINode contains the vectorized reduction variable, or
  722. // the initial value vector, if we bypass the vector loop.
  723. VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
  724. PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
  725. Value *StartVal = (part == 0) ? VectorStart : Identity;
  726. NewPhi->addIncoming(StartVal, LoopBypassBlock);
  727. NewPhi->addIncoming(RdxExitVal[part], LoopVectorBody);
  728. RdxParts.push_back(NewPhi);
  729. }
  730. // Reduce all of the unrolled parts into a single vector.
  731. Value *ReducedPartRdx = RdxParts[0];
  732. for (unsigned part = 1; part < UF; ++part) {
  733. switch (RdxDesc.Kind) {
  734. case LoopVectorizationLegality::IntegerAdd:
  735. ReducedPartRdx =
  736. Builder.CreateAdd(RdxParts[part], ReducedPartRdx, "add.rdx");
  737. break;
  738. case LoopVectorizationLegality::IntegerMult:
  739. ReducedPartRdx =
  740. Builder.CreateMul(RdxParts[part], ReducedPartRdx, "mul.rdx");
  741. break;
  742. case LoopVectorizationLegality::IntegerOr:
  743. ReducedPartRdx =
  744. Builder.CreateOr(RdxParts[part], ReducedPartRdx, "or.rdx");
  745. break;
  746. case LoopVectorizationLegality::IntegerAnd:
  747. ReducedPartRdx =
  748. Builder.CreateAnd(RdxParts[part], ReducedPartRdx, "and.rdx");
  749. break;
  750. case LoopVectorizationLegality::IntegerXor:
  751. ReducedPartRdx =
  752. Builder.CreateXor(RdxParts[part], ReducedPartRdx, "xor.rdx");
  753. break;
  754. default:
  755. llvm_unreachable("Unknown reduction operation");
  756. }
  757. }
  758. // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
  759. // and vector ops, reducing the set of values being computed by half each
  760. // round.
  761. assert(isPowerOf2_32(VF) &&
  762. "Reduction emission only supported for pow2 vectors!");
  763. Value *TmpVec = ReducedPartRdx;
  764. SmallVector<Constant*, 32> ShuffleMask(VF, 0);
  765. for (unsigned i = VF; i != 1; i >>= 1) {
  766. // Move the upper half of the vector to the lower half.
  767. for (unsigned j = 0; j != i/2; ++j)
  768. ShuffleMask[j] = Builder.getInt32(i/2 + j);
  769. // Fill the rest of the mask with undef.
  770. std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
  771. UndefValue::get(Builder.getInt32Ty()));
  772. Value *Shuf =
  773. Builder.CreateShuffleVector(TmpVec,
  774. UndefValue::get(TmpVec->getType()),
  775. ConstantVector::get(ShuffleMask),
  776. "rdx.shuf");
  777. // Emit the operation on the shuffled value.
  778. switch (RdxDesc.Kind) {
  779. case LoopVectorizationLegality::IntegerAdd:
  780. TmpVec = Builder.CreateAdd(TmpVec, Shuf, "add.rdx");
  781. break;
  782. case LoopVectorizationLegality::IntegerMult:
  783. TmpVec = Builder.CreateMul(TmpVec, Shuf, "mul.rdx");
  784. break;
  785. case LoopVectorizationLegality::IntegerOr:
  786. TmpVec = Builder.CreateOr(TmpVec, Shuf, "or.rdx");
  787. break;
  788. case LoopVectorizationLegality::IntegerAnd:
  789. TmpVec = Builder.CreateAnd(TmpVec, Shuf, "and.rdx");
  790. break;
  791. case LoopVectorizationLegality::IntegerXor:
  792. TmpVec = Builder.CreateXor(TmpVec, Shuf, "xor.rdx");
  793. break;
  794. default:
  795. llvm_unreachable("Unknown reduction operation");
  796. }
  797. }
  798. // The result is in the first element of the vector.
  799. Value *Scalar0 = Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
  800. // Now, we need to fix the users of the reduction variable
  801. // inside and outside of the scalar remainder loop.
  802. // We know that the loop is in LCSSA form. We need to update the
  803. // PHI nodes in the exit blocks.
  804. for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
  805. LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
  806. PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
  807. if (!LCSSAPhi) continue;
  808. // All PHINodes need to have a single entry edge, or two if
  809. // we already fixed them.
  810. assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
  811. // We found our reduction value exit-PHI. Update it with the
  812. // incoming bypass edge.
  813. if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
  814. // Add an edge coming from the bypass.
  815. LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock);
  816. break;
  817. }
  818. }// end of the LCSSA phi scan.
  819. // Fix the scalar loop reduction variable with the incoming reduction sum
  820. // from the vector body and from the backedge value.
  821. int IncomingEdgeBlockIdx =
  822. (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
  823. assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
  824. // Pick the other block.
  825. int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
  826. (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0);
  827. (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
  828. }// end of for each redux variable.
  829. // The Loop exit block may have single value PHI nodes where the incoming
  830. // value is 'undef'. While vectorizing we only handled real values that
  831. // were defined inside the loop. Here we handle the 'undef case'.
  832. // See PR14725.
  833. for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
  834. LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
  835. PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
  836. if (!LCSSAPhi) continue;
  837. if (LCSSAPhi->getNumIncomingValues() == 1)
  838. LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
  839. LoopMiddleBlock);
  840. }
  841. }
  842. InnerLoopVectorizer::VectorParts
  843. InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
  844. assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
  845. "Invalid edge");
  846. VectorParts SrcMask = createBlockInMask(Src);
  847. // The terminator has to be a branch inst!
  848. BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
  849. assert(BI && "Unexpected terminator found");
  850. if (BI->isConditional()) {
  851. VectorParts EdgeMask = getVectorValue(BI->getCondition());
  852. if (BI->getSuccessor(0) != Dst)
  853. for (unsigned part = 0; part < UF; ++part)
  854. EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
  855. for (unsigned part = 0; part < UF; ++part)
  856. EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
  857. return EdgeMask;
  858. }
  859. return SrcMask;
  860. }
  861. InnerLoopVectorizer::VectorParts
  862. InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
  863. assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
  864. // Loop incoming mask is all-one.
  865. if (OrigLoop->getHeader() == BB) {
  866. Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
  867. return getVectorValue(C);
  868. }
  869. // This is the block mask. We OR all incoming edges, and with zero.
  870. Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
  871. VectorParts BlockMask = getVectorValue(Zero);
  872. // For each pred:
  873. for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
  874. VectorParts EM = createEdgeMask(*it, BB);
  875. for (unsigned part = 0; part < UF; ++part)
  876. BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
  877. }
  878. return BlockMask;
  879. }
  880. void
  881. InnerLoopVectorizer::vectorizeBlockInLoop(LoopVectorizationLegality *Legal,
  882. BasicBlock *BB, PhiVector *PV) {
  883. Constant *Zero = Builder.getInt32(0);
  884. // For each instruction in the old loop.
  885. for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
  886. VectorParts &Entry = WidenMap.get(it);
  887. switch (it->getOpcode()) {
  888. case Instruction::Br:
  889. // Nothing to do for PHIs and BR, since we already took care of the
  890. // loop control flow instructions.
  891. continue;
  892. case Instruction::PHI:{
  893. PHINode* P = cast<PHINode>(it);
  894. // Handle reduction variables:
  895. if (Legal->getReductionVars()->count(P)) {
  896. for (unsigned part = 0; part < UF; ++part) {
  897. // This is phase one of vectorizing PHIs.
  898. Type *VecTy = VectorType::get(it->getType(), VF);
  899. Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
  900. LoopVectorBody-> getFirstInsertionPt());
  901. }
  902. PV->push_back(P);
  903. continue;
  904. }
  905. // Check for PHI nodes that are lowered to vector selects.
  906. if (P->getParent() != OrigLoop->getHeader()) {
  907. // We know that all PHIs in non header blocks are converted into
  908. // selects, so we don't have to worry about the insertion order and we
  909. // can just use the builder.
  910. // At this point we generate the predication tree. There may be
  911. // duplications since this is a simple recursive scan, but future
  912. // optimizations will clean it up.
  913. VectorParts Cond = createEdgeMask(P->getIncomingBlock(0),
  914. P->getParent());
  915. for (unsigned part = 0; part < UF; ++part) {
  916. VectorParts &In0 = getVectorValue(P->getIncomingValue(0));
  917. VectorParts &In1 = getVectorValue(P->getIncomingValue(1));
  918. Entry[part] = Builder.CreateSelect(Cond[part], In0[part], In1[part],
  919. "predphi");
  920. }
  921. continue;
  922. }
  923. // This PHINode must be an induction variable.
  924. // Make sure that we know about it.
  925. assert(Legal->getInductionVars()->count(P) &&
  926. "Not an induction variable");
  927. LoopVectorizationLegality::InductionInfo II =
  928. Legal->getInductionVars()->lookup(P);
  929. switch (II.IK) {
  930. case LoopVectorizationLegality::NoInduction:
  931. llvm_unreachable("Unknown induction");
  932. case LoopVectorizationLegality::IntInduction: {
  933. assert(P == OldInduction && "Unexpected PHI");
  934. Value *Broadcasted = getBroadcastInstrs(Induction);
  935. // After broadcasting the induction variable we need to make the
  936. // vector consecutive by adding 0, 1, 2 ...
  937. for (unsigned part = 0; part < UF; ++part)
  938. Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false);
  939. continue;
  940. }
  941. case LoopVectorizationLegality::ReverseIntInduction:
  942. case LoopVectorizationLegality::PtrInduction:
  943. // Handle reverse integer and pointer inductions.
  944. Value *StartIdx = 0;
  945. // If we have a single integer induction variable then use it.
  946. // Otherwise, start counting at zero.
  947. if (OldInduction) {
  948. LoopVectorizationLegality::InductionInfo OldII =
  949. Legal->getInductionVars()->lookup(OldInduction);
  950. StartIdx = OldII.StartValue;
  951. } else {
  952. StartIdx = ConstantInt::get(Induction->getType(), 0);
  953. }
  954. // This is the normalized GEP that starts counting at zero.
  955. Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
  956. "normalized.idx");
  957. // Handle the reverse integer induction variable case.
  958. if (LoopVectorizationLegality::ReverseIntInduction == II.IK) {
  959. IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
  960. Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
  961. "resize.norm.idx");
  962. Value *ReverseInd = Builder.CreateSub(II.StartValue, CNI,
  963. "reverse.idx");
  964. // This is a new value so do not hoist it out.
  965. Value *Broadcasted = getBroadcastInstrs(ReverseInd);
  966. // After broadcasting the induction variable we need to make the
  967. // vector consecutive by adding ... -3, -2, -1, 0.
  968. for (unsigned part = 0; part < UF; ++part)
  969. Entry[part] = getConsecutiveVector(Broadcasted, -VF * part, true);
  970. continue;
  971. }
  972. // Handle the pointer induction variable case.
  973. assert(P->getType()->isPointerTy() && "Unexpected type.");
  974. // This is the vector of results. Notice that we don't generate
  975. // vector geps because scalar geps result in better code.
  976. for (unsigned part = 0; part < UF; ++part) {
  977. Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
  978. for (unsigned int i = 0; i < VF; ++i) {
  979. Constant *Idx = ConstantInt::get(Induction->getType(),
  980. i + part * VF);
  981. Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx,
  982. "gep.idx");
  983. Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
  984. "next.gep");
  985. VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
  986. Builder.getInt32(i),
  987. "insert.gep");
  988. }
  989. Entry[part] = VecVal;
  990. }
  991. continue;
  992. }
  993. }// End of PHI.
  994. case Instruction::Add:
  995. case Instruction::FAdd:
  996. case Instruction::Sub:
  997. case Instruction::FSub:
  998. case Instruction::Mul:
  999. case Instruction::FMul:
  1000. case Instruction::UDiv:
  1001. case Instruction::SDiv:
  1002. case Instruction::FDiv:
  1003. case Instruction::URem:
  1004. case Instruction::SRem:
  1005. case Instruction::FRem:
  1006. case Instruction::Shl:
  1007. case Instruction::LShr:
  1008. case Instruction::AShr:
  1009. case Instruction::And:
  1010. case Instruction::Or:
  1011. case Instruction::Xor: {
  1012. // Just widen binops.
  1013. BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
  1014. VectorParts &A = getVectorValue(it->getOperand(0));
  1015. VectorParts &B = getVectorValue(it->getOperand(1));
  1016. // Use this vector value for all users of the original instruction.
  1017. for (unsigned Part = 0; Part < UF; ++Part) {
  1018. Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
  1019. // Update the NSW, NUW and Exact flags.
  1020. BinaryOperator *VecOp = cast<BinaryOperator>(V);
  1021. if (isa<OverflowingBinaryOperator>(BinOp)) {
  1022. VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
  1023. VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
  1024. }
  1025. if (isa<PossiblyExactOperator>(VecOp))
  1026. VecOp->setIsExact(BinOp->isExact());
  1027. Entry[Part] = V;
  1028. }
  1029. break;
  1030. }
  1031. case Instruction::Select: {
  1032. // Widen selects.
  1033. // If the selector is loop invariant we can create a select
  1034. // instruction with a scalar condition. Otherwise, use vector-select.
  1035. bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
  1036. OrigLoop);
  1037. // The condition can be loop invariant but still defined inside the
  1038. // loop. This means that we can't just use the original 'cond' value.
  1039. // We have to take the 'vectorized' value and pick the first lane.
  1040. // Instcombine will make this a no-op.
  1041. VectorParts &Cond = getVectorValue(it->getOperand(0));
  1042. VectorParts &Op0 = getVectorValue(it->getOperand(1));
  1043. VectorParts &Op1 = getVectorValue(it->getOperand(2));
  1044. Value *ScalarCond = Builder.CreateExtractElement(Cond[0],
  1045. Builder.getInt32(0));
  1046. for (unsigned Part = 0; Part < UF; ++Part) {
  1047. Entry[Part] = Builder.CreateSelect(
  1048. InvariantCond ? ScalarCond : Cond[Part],
  1049. Op0[Part],
  1050. Op1[Part]);
  1051. }
  1052. break;
  1053. }
  1054. case Instruction::ICmp:
  1055. case Instruction::FCmp: {
  1056. // Widen compares. Generate vector compares.
  1057. bool FCmp = (it->getOpcode() == Instruction::FCmp);
  1058. CmpInst *Cmp = dyn_cast<CmpInst>(it);
  1059. VectorParts &A = getVectorValue(it->getOperand(0));
  1060. VectorParts &B = getVectorValue(it->getOperand(1));
  1061. for (unsigned Part = 0; Part < UF; ++Part) {
  1062. Value *C = 0;
  1063. if (FCmp)
  1064. C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
  1065. else
  1066. C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
  1067. Entry[Part] = C;
  1068. }
  1069. break;
  1070. }
  1071. case Instruction::Store: {
  1072. // Attempt to issue a wide store.
  1073. StoreInst *SI = dyn_cast<StoreInst>(it);
  1074. Type *StTy = VectorType::get(SI->getValueOperand()->getType(), VF);
  1075. Value *Ptr = SI->getPointerOperand();
  1076. unsigned Alignment = SI->getAlignment();
  1077. assert(!Legal->isUniform(Ptr) &&
  1078. "We do not allow storing to uniform addresses");
  1079. int Stride = Legal->isConsecutivePtr(Ptr);
  1080. bool Reverse = Stride < 0;
  1081. if (Stride == 0) {
  1082. scalarizeInstruction(it);
  1083. break;
  1084. }
  1085. // Handle consecutive stores.
  1086. GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
  1087. if (Gep) {
  1088. // The last index does not have to be the induction. It can be
  1089. // consecutive and be a function of the index. For example A[I+1];
  1090. unsigned NumOperands = Gep->getNumOperands();
  1091. Value *LastGepOperand = Gep->getOperand(NumOperands - 1);
  1092. VectorParts &GEPParts = getVectorValue(LastGepOperand);
  1093. Value *LastIndex = GEPParts[0];
  1094. LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
  1095. // Create the new GEP with the new induction variable.
  1096. GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
  1097. Gep2->setOperand(NumOperands - 1, LastIndex);
  1098. Ptr = Builder.Insert(Gep2);
  1099. } else {
  1100. // Use the induction element ptr.
  1101. assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
  1102. VectorParts &PtrVal = getVectorValue(Ptr);
  1103. Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
  1104. }
  1105. VectorParts &StoredVal = getVectorValue(SI->getValueOperand());
  1106. for (unsigned Part = 0; Part < UF; ++Part) {
  1107. // Calculate the pointer for the specific unroll-part.
  1108. Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
  1109. if (Reverse) {
  1110. // If we store to reverse consecutive memory locations then we need
  1111. // to reverse the order of elements in the stored value.
  1112. StoredVal[Part] = reverseVector(StoredVal[Part]);
  1113. // If the address is consecutive but reversed, then the
  1114. // wide store needs to start at the last vector element.
  1115. PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
  1116. PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
  1117. }
  1118. Value *VecPtr = Builder.CreateBitCast(PartPtr, StTy->getPointerTo());
  1119. Builder.CreateStore(StoredVal[Part], VecPtr)->setAlignment(Alignment);
  1120. }
  1121. break;
  1122. }
  1123. case Instruction::Load: {
  1124. // Attempt to issue a wide load.
  1125. LoadInst *LI = dyn_cast<LoadInst>(it);
  1126. Type *RetTy = VectorType::get(LI->getType(), VF);
  1127. Value *Ptr = LI->getPointerOperand();
  1128. unsigned Alignment = LI->getAlignment();
  1129. // If the pointer is loop invariant or if it is non consecutive,
  1130. // scalarize the load.
  1131. int Stride = Legal->isConsecutivePtr(Ptr);
  1132. bool Reverse = Stride < 0;
  1133. if (Legal->isUniform(Ptr) || Stride == 0) {
  1134. scalarizeInstruction(it);
  1135. break;
  1136. }
  1137. GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
  1138. if (Gep) {
  1139. // The last index does not have to be the induction. It can be
  1140. // consecutive and be a function of the index. For example A[I+1];
  1141. unsigned NumOperands = Gep->getNumOperands();
  1142. Value *LastGepOperand = Gep->getOperand(NumOperands - 1);
  1143. VectorParts &GEPParts = getVectorValue(LastGepOperand);
  1144. Value *LastIndex = GEPParts[0];
  1145. LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
  1146. // Create the new GEP with the new induction variable.
  1147. GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
  1148. Gep2->setOperand(NumOperands - 1, LastIndex);
  1149. Ptr = Builder.Insert(Gep2);
  1150. } else {
  1151. // Use the induction element ptr.
  1152. assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
  1153. VectorParts &PtrVal = getVectorValue(Ptr);
  1154. Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
  1155. }
  1156. for (unsigned Part = 0; Part < UF; ++Part) {
  1157. // Calculate the pointer for the specific unroll-part.
  1158. Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
  1159. if (Reverse) {
  1160. // If the address is consecutive but reversed, then the
  1161. // wide store needs to start at the last vector element.
  1162. PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
  1163. PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
  1164. }
  1165. Value *VecPtr = Builder.CreateBitCast(PartPtr, RetTy->getPointerTo());
  1166. Value *LI = Builder.CreateLoad(VecPtr, "wide.load");
  1167. cast<LoadInst>(LI)->setAlignment(Alignment);
  1168. Entry[Part] = Reverse ? reverseVector(LI) : LI;
  1169. }
  1170. break;
  1171. }
  1172. case Instruction::ZExt:
  1173. case Instruction::SExt:
  1174. case Instruction::FPToUI:
  1175. case Instruction::FPToSI:
  1176. case Instruction::FPExt:
  1177. case Instruction::PtrToInt:
  1178. case Instruction::IntToPtr:
  1179. case Instruction::SIToFP:
  1180. case Instruction::UIToFP:
  1181. case Instruction::Trunc:
  1182. case Instruction::FPTrunc:
  1183. case Instruction::BitCast: {
  1184. CastInst *CI = dyn_cast<CastInst>(it);
  1185. /// Optimize the special case where the source is the induction
  1186. /// variable. Notice that we can only optimize the 'trunc' case
  1187. /// because: a. FP conversions lose precision, b. sext/zext may wrap,
  1188. /// c. other casts depend on pointer size.
  1189. if (CI->getOperand(0) == OldInduction &&
  1190. it->getOpcode() == Instruction::Trunc) {
  1191. Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
  1192. CI->getType());
  1193. Value *Broadcasted = getBroadcastInstrs(ScalarCast);
  1194. for (unsigned Part = 0; Part < UF; ++Part)
  1195. Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
  1196. break;
  1197. }
  1198. /// Vectorize casts.
  1199. Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
  1200. VectorParts &A = getVectorValue(it->getOperand(0));
  1201. for (unsigned Part = 0; Part < UF; ++Part)
  1202. Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
  1203. break;
  1204. }
  1205. case Instruction::Call: {
  1206. assert(isTriviallyVectorizableIntrinsic(it));
  1207. Module *M = BB->getParent()->getParent();
  1208. IntrinsicInst *II = cast<IntrinsicInst>(it);
  1209. Intrinsic::ID ID = II->getIntrinsicID();
  1210. for (unsigned Part = 0; Part < UF; ++Part) {
  1211. SmallVector<Value*, 4> Args;
  1212. for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i) {
  1213. VectorParts &Arg = getVectorValue(II->getArgOperand(i));
  1214. Args.push_back(Arg[Part]);
  1215. }
  1216. Type *Tys[] = { VectorType::get(II->getType()->getScalarType(), VF) };
  1217. Function *F = Intrinsic::getDeclaration(M, ID, Tys);
  1218. Entry[Part] = Builder.CreateCall(F, Args);
  1219. }
  1220. break;
  1221. }
  1222. default:
  1223. // All other instructions are unsupported. Scalarize them.
  1224. scalarizeInstruction(it);
  1225. break;
  1226. }// end of switch.
  1227. }// end of for_each instr.
  1228. }
  1229. void InnerLoopVectorizer::updateAnalysis() {
  1230. // Forget the original basic block.
  1231. SE->forgetLoop(OrigLoop);
  1232. // Update the dominator tree information.
  1233. assert(DT->properlyDominates(LoopBypassBlock, LoopExitBlock) &&
  1234. "Entry does not dominate exit.");
  1235. DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlock);
  1236. DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
  1237. DT->addNewBlock(LoopMiddleBlock, LoopBypassBlock);
  1238. DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
  1239. DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
  1240. DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
  1241. DEBUG(DT->verifyAnalysis());
  1242. }
  1243. bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
  1244. if (!EnableIfConversion)
  1245. return false;
  1246. assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
  1247. std::vector<BasicBlock*> &LoopBlocks = TheLoop->getBlocksVector();
  1248. // Collect the blocks that need predication.
  1249. for (unsigned i = 0, e = LoopBlocks.size(); i < e; ++i) {
  1250. BasicBlock *BB = LoopBlocks[i];
  1251. // We don't support switch statements inside loops.
  1252. if (!isa<BranchInst>(BB->getTerminator()))
  1253. return false;
  1254. // We must have at most two predecessors because we need to convert
  1255. // all PHIs to selects.
  1256. unsigned Preds = std::distance(pred_begin(BB), pred_end(BB));
  1257. if (Preds > 2)
  1258. return false;
  1259. // We must be able to predicate all blocks that need to be predicated.
  1260. if (blockNeedsPredication(BB) && !blockCanBePredicated(BB))
  1261. return false;
  1262. }
  1263. // We can if-convert this loop.
  1264. return true;
  1265. }
  1266. bool LoopVectorizationLegality::canVectorize() {
  1267. assert(TheLoop->getLoopPreheader() && "No preheader!!");
  1268. // We can only vectorize innermost loops.
  1269. if (TheLoop->getSubLoopsVector().size())
  1270. return false;
  1271. // We must have a single backedge.
  1272. if (TheLoop->getNumBackEdges() != 1)
  1273. return false;
  1274. // We must have a single exiting block.
  1275. if (!TheLoop->getExitingBlock())
  1276. return false;
  1277. unsigned NumBlocks = TheLoop->getNumBlocks();
  1278. // Check if we can if-convert non single-bb loops.
  1279. if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
  1280. DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
  1281. return false;
  1282. }
  1283. // We need to have a loop header.
  1284. BasicBlock *Latch = TheLoop->getLoopLatch();
  1285. DEBUG(dbgs() << "LV: Found a loop: " <<
  1286. TheLoop->getHeader()->getName() << "\n");
  1287. // ScalarEvolution needs to be able to find the exit count.
  1288. const SCEV *ExitCount = SE->getExitCount(TheLoop, Latch);
  1289. if (ExitCount == SE->getCouldNotCompute()) {
  1290. DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
  1291. return false;
  1292. }
  1293. // Do not loop-vectorize loops with a tiny trip count.
  1294. unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch);
  1295. if (TC > 0u && TC < TinyTripCountThreshold) {
  1296. DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
  1297. "This loop is not worth vectorizing.\n");
  1298. return false;
  1299. }
  1300. // Check if we can vectorize the instructions and CFG in this loop.
  1301. if (!canVectorizeInstrs()) {
  1302. DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
  1303. return false;
  1304. }
  1305. // Go over each instruction and look at memory deps.
  1306. if (!canVectorizeMemory()) {
  1307. DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
  1308. return false;
  1309. }
  1310. // Collect all of the variables that remain uniform after vectorization.
  1311. collectLoopUniforms();
  1312. DEBUG(dbgs() << "LV: We can vectorize this loop" <<
  1313. (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
  1314. <<"!\n");
  1315. // Okay! We can vectorize. At this point we don't have any other mem analysis
  1316. // which may limit our maximum vectorization factor, so just return true with
  1317. // no restrictions.
  1318. return true;
  1319. }
  1320. bool LoopVectorizationLegality::canVectorizeInstrs() {
  1321. BasicBlock *PreHeader = TheLoop->getLoopPreheader();
  1322. BasicBlock *Header = TheLoop->getHeader();
  1323. // For each block in the loop.
  1324. for (Loop::block_iterator bb = TheLoop->block_begin(),
  1325. be = TheLoop->block_end(); bb != be; ++bb) {
  1326. // Scan the instructions in the block and look for hazards.
  1327. for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
  1328. ++it) {
  1329. if (PHINode *Phi = dyn_cast<PHINode>(it)) {
  1330. // This should not happen because the loop should be normalized.
  1331. if (Phi->getNumIncomingValues() != 2) {
  1332. DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
  1333. return false;
  1334. }
  1335. // Check that this PHI type is allowed.
  1336. if (!Phi->getType()->isIntegerTy() &&
  1337. !Phi->getType()->isPointerTy()) {
  1338. DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
  1339. return false;
  1340. }
  1341. // If this PHINode is not in the header block, then we know that we
  1342. // can convert it to select during if-conversion. No need to check if
  1343. // the PHIs in this block are induction or reduction variables.
  1344. if (*bb != Header)
  1345. continue;
  1346. // This is the value coming from the preheader.
  1347. Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
  1348. // Check if this is an induction variable.
  1349. InductionKind IK = isInductionVariable(Phi);
  1350. if (NoInduction != IK) {
  1351. // Int inductions are special because we only allow one IV.
  1352. if (IK == IntInduction) {
  1353. if (Induction) {
  1354. DEBUG(dbgs() << "LV: Found too many inductions."<< *Phi <<"\n");
  1355. return false;
  1356. }
  1357. Induction = Phi;
  1358. }
  1359. DEBUG(dbgs() << "LV: Found an induction variable.\n");
  1360. Inductions[Phi] = InductionInfo(StartValue, IK);
  1361. continue;
  1362. }
  1363. if (AddReductionVar(Phi, IntegerAdd)) {
  1364. DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
  1365. continue;
  1366. }
  1367. if (AddReductionVar(Phi, IntegerMult)) {
  1368. DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
  1369. continue;
  1370. }
  1371. if (AddReductionVar(Phi, IntegerOr)) {
  1372. DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
  1373. continue;
  1374. }
  1375. if (AddReductionVar(Phi, IntegerAnd)) {
  1376. DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
  1377. continue;
  1378. }
  1379. if (AddReductionVar(Phi, IntegerXor)) {
  1380. DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
  1381. continue;
  1382. }
  1383. DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
  1384. return false;
  1385. }// end of PHI handling
  1386. // We still don't handle functions.
  1387. CallInst *CI = dyn_cast<CallInst>(it);
  1388. if (CI && !isTriviallyVectorizableIntrinsic(it)) {
  1389. DEBUG(dbgs() << "LV: Found a call site.\n");
  1390. return false;
  1391. }
  1392. // Check that the instruction return type is vectorizable.
  1393. if (!VectorType::isValidElementType(it->getType()) &&
  1394. !it->getType()->isVoidTy()) {
  1395. DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
  1396. return false;
  1397. }
  1398. // Check that the stored type is vectorizable.
  1399. if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
  1400. Type *T = ST->getValueOperand()->getType();
  1401. if (!VectorType::isValidElementType(T))
  1402. return false;
  1403. }
  1404. // Reduction instructions are allowed to have exit users.
  1405. // All other instructions must not have external users.
  1406. if (!AllowedExit.count(it))
  1407. //Check that all of the users of the loop are inside the BB.
  1408. for (Value::use_iterator I = it->use_begin(), E = it->use_end();
  1409. I != E; ++I) {
  1410. Instruction *U = cast<Instruction>(*I);
  1411. // This user may be a reduction exit value.
  1412. if (!TheLoop->contains(U)) {
  1413. DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
  1414. return false;
  1415. }
  1416. }
  1417. } // next instr.
  1418. }
  1419. if (!Induction) {
  1420. DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
  1421. assert(getInductionVars()->size() && "No induction variables");
  1422. }
  1423. return true;
  1424. }
  1425. void LoopVectorizationLegality::collectLoopUniforms() {
  1426. // We now know that the loop is vectorizable!
  1427. // Collect variables that will remain uniform after vectorization.
  1428. std::vector<Value*> Worklist;
  1429. BasicBlock *Latch = TheLoop->getLoopLatch();
  1430. // Start with the conditional branch and walk up the block.
  1431. Worklist.push_back(Latch->getTerminator()->getOperand(0));
  1432. while (Worklist.size()) {
  1433. Instruction *I = dyn_cast<Instruction>(Worklist.back());
  1434. Worklist.pop_back();
  1435. // Look at instructions inside this loop.
  1436. // Stop when reaching PHI nodes.
  1437. // TODO: we need to follow values all over the loop, not only in this block.
  1438. if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
  1439. continue;
  1440. // This is a known uniform.
  1441. Uniforms.insert(I);
  1442. // Insert all operands.
  1443. for (int i = 0, Op = I->getNumOperands(); i < Op; ++i) {
  1444. Worklist.push_back(I->getOperand(i));
  1445. }
  1446. }
  1447. }
  1448. bool LoopVectorizationLegality::canVectorizeMemory() {
  1449. typedef SmallVector<Value*, 16> ValueVector;
  1450. typedef SmallPtrSet<Value*, 16> ValueSet;
  1451. // Holds the Load and Store *instructions*.
  1452. ValueVector Loads;
  1453. ValueVector Stores;
  1454. PtrRtCheck.Pointers.clear();
  1455. PtrRtCheck.Need = false;
  1456. // For each block.
  1457. for (Loop::block_iterator bb = TheLoop->block_begin(),
  1458. be = TheLoop->block_end(); bb != be; ++bb) {
  1459. // Scan the BB and collect legal loads and stores.
  1460. for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
  1461. ++it) {
  1462. // If this is a load, save it. If this instruction can read from memory
  1463. // but is not a load, then we quit. Notice that we don't handle function
  1464. // calls that read or write.
  1465. if (it->mayReadFromMemory()) {
  1466. LoadInst *Ld = dyn_cast<LoadInst>(it);
  1467. if (!Ld) return false;
  1468. if (!Ld->isSimple()) {
  1469. DEBUG(dbgs() << "LV: Found a non-simple load.\n");
  1470. return false;
  1471. }
  1472. Loads.push_back(Ld);
  1473. continue;
  1474. }
  1475. // Save 'store' instructions. Abort if other instructions write to memory.
  1476. if (it->mayWriteToMemory()) {
  1477. StoreInst *St = dyn_cast<StoreInst>(it);
  1478. if (!St) return false;
  1479. if (!St->isSimple()) {
  1480. DEBUG(dbgs() << "LV: Found a non-simple store.\n");
  1481. return false;
  1482. }
  1483. Stores.push_back(St);
  1484. }
  1485. } // next instr.
  1486. } // next block.
  1487. // Now we have two lists that hold the loads and the stores.
  1488. // Next, we find the pointers that they use.
  1489. // Check if we see any stores. If there are no stores, then we don't
  1490. // care if the pointers are *restrict*.
  1491. if (!Stores.size()) {
  1492. DEBUG(dbgs() << "LV: Found a read-only loop!\n");
  1493. return true;
  1494. }
  1495. // Holds the read and read-write *pointers* that we find.
  1496. ValueVector Reads;
  1497. ValueVector ReadWrites;
  1498. // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
  1499. // multiple times on the same object. If the ptr is accessed twice, once
  1500. // for read and once for write, it will only appear once (on the write
  1501. // list). This is okay, since we are going to check for conflicts between
  1502. // writes and between reads and writes, but not between reads and reads.
  1503. ValueSet Seen;
  1504. ValueVector::iterator I, IE;
  1505. for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
  1506. StoreInst *ST = cast<StoreInst>(*I);
  1507. Value* Ptr = ST->getPointerOperand();
  1508. if (isUniform(Ptr)) {
  1509. DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
  1510. return false;
  1511. }
  1512. // If we did *not* see this pointer before, insert it to
  1513. // the read-write list. At this phase it is only a 'write' list.
  1514. if (Seen.insert(Ptr))
  1515. ReadWrites.push_back(Ptr);
  1516. }
  1517. for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
  1518. LoadInst *LD = cast<LoadInst>(*I);
  1519. Value* Ptr = LD->getPointerOperand();
  1520. // If we did *not* see this pointer before, insert it to the
  1521. // read list. If we *did* see it before, then it is already in
  1522. // the read-write list. This allows us to vectorize expressions
  1523. // such as A[i] += x; Because the address of A[i] is a read-write
  1524. // pointer. This only works if the index of A[i] is consecutive.
  1525. // If the address of i is unknown (for example A[B[i]]) then we may
  1526. // read a few words, modify, and write a few words, and some of the
  1527. // words may be written to the same address.
  1528. if (Seen.insert(Ptr) || 0 == isConsecutivePtr(Ptr))
  1529. Reads.push_back(Ptr);
  1530. }
  1531. // If we write (or read-write) to a single destination and there are no
  1532. // other reads in this loop then is it safe to vectorize.
  1533. if (ReadWrites.size() == 1 && Reads.size() == 0) {
  1534. DEBUG(dbgs() << "LV: Found a write-only loop!\n");
  1535. return true;
  1536. }
  1537. // Find pointers with computable bounds. We are going to use this information
  1538. // to place a runtime bound check.
  1539. bool CanDoRT = true;
  1540. for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I)
  1541. if (hasComputableBounds(*I)) {
  1542. PtrRtCheck.insert(SE, TheLoop, *I);
  1543. DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
  1544. } else {
  1545. CanDoRT = false;
  1546. break;
  1547. }
  1548. for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I)
  1549. if (hasComputableBounds(*I)) {
  1550. PtrRtCheck.insert(SE, TheLoop, *I);
  1551. DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
  1552. } else {
  1553. CanDoRT = false;
  1554. break;
  1555. }
  1556. // Check that we did not collect too many pointers or found a
  1557. // unsizeable pointer.
  1558. if (!CanDoRT || PtrRtCheck.Pointers.size() > RuntimeMemoryCheckThreshold) {
  1559. PtrRtCheck.reset();
  1560. CanDoRT = false;
  1561. }
  1562. if (CanDoRT) {
  1563. DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
  1564. }
  1565. bool NeedRTCheck = false;
  1566. // Now that the pointers are in two lists (Reads and ReadWrites), we
  1567. // can check that there are no conflicts between each of the writes and
  1568. // between the writes to the reads.
  1569. ValueSet WriteObjects;
  1570. ValueVector TempObjects;
  1571. // Check that the read-writes do not conflict with other read-write
  1572. // pointers.
  1573. bool AllWritesIdentified = true;
  1574. for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I) {
  1575. GetUnderlyingObjects(*I, TempObjects, DL);
  1576. for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
  1577. it != e; ++it) {
  1578. if (!isIdentifiedObject(*it)) {
  1579. DEBUG(dbgs() << "LV: Found an unidentified write ptr:"<< **it <<"\n");
  1580. NeedRTCheck = true;
  1581. AllWritesIdentified = false;
  1582. }
  1583. if (!WriteObjects.insert(*it)) {
  1584. DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
  1585. << **it <<"\n");
  1586. return false;
  1587. }
  1588. }
  1589. TempObjects.clear();
  1590. }
  1591. /// Check that the reads don't conflict with the read-writes.
  1592. for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I) {
  1593. GetUnderlyingObjects(*I, TempObjects, DL);
  1594. for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
  1595. it != e; ++it) {
  1596. // If all of the writes are identified then we don't care if the read
  1597. // pointer is identified or not.
  1598. if (!AllWritesIdentified && !isIdentifiedObject(*it)) {
  1599. DEBUG(dbgs() << "LV: Found an unidentified read ptr:"<< **it <<"\n");
  1600. NeedRTCheck = true;
  1601. }
  1602. if (WriteObjects.count(*it)) {
  1603. DEBUG(dbgs() << "LV: Found a possible read/write reorder:"
  1604. << **it <<"\n");
  1605. return false;
  1606. }
  1607. }
  1608. TempObjects.clear();
  1609. }
  1610. PtrRtCheck.Need = NeedRTCheck;
  1611. if (NeedRTCheck && !CanDoRT) {
  1612. DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
  1613. "the array bounds.\n");
  1614. PtrRtCheck.reset();
  1615. return false;
  1616. }
  1617. DEBUG(dbgs() << "LV: We "<< (NeedRTCheck ? "" : "don't") <<
  1618. " need a runtime memory check.\n");
  1619. return true;
  1620. }
  1621. bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
  1622. ReductionKind Kind) {
  1623. if (Phi->getNumIncomingValues() != 2)
  1624. return false;
  1625. // Reduction variables are only found in the loop header block.
  1626. if (Phi->getParent() != TheLoop->getHeader())
  1627. return false;
  1628. // Obtain the reduction start value from the value that comes from the loop
  1629. // preheader.
  1630. Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
  1631. // ExitInstruction is the single value which is used outside the loop.
  1632. // We only allow for a single reduction value to be used outside the loop.
  1633. // This includes users of the reduction, variables (which form a cycle
  1634. // which ends in the phi node).
  1635. Instruction *ExitInstruction = 0;
  1636. // Iter is our iterator. We start with the PHI node and scan for all of the
  1637. // users of this instruction. All users must be instructions that can be
  1638. // used as reduction variables (such as ADD). We may have a single
  1639. // out-of-block user. The cycle must end with the original PHI.
  1640. Instruction *Iter = Phi;
  1641. while (true) {
  1642. // If the instruction has no users then this is a broken
  1643. // chain and can't be a reduction variable.
  1644. if (Iter->use_empty())
  1645. return false;
  1646. // Any reduction instr must be of one of the allowed kinds.
  1647. if (!isReductionInstr(Iter, Kind))
  1648. return false;
  1649. // Did we find a user inside this loop already ?
  1650. bool FoundInBlockUser = false;
  1651. // Did we reach the initial PHI node already ?
  1652. bool FoundStartPHI = false;
  1653. // For each of the *users* of iter.
  1654. for (Value::use_iterator it = Iter->use_begin(), e = Iter->use_end();
  1655. it != e; ++it) {
  1656. Instruction *U = cast<Instruction>(*it);
  1657. // We already know that the PHI is a user.
  1658. if (U == Phi) {
  1659. FoundStartPHI = true;
  1660. continue;
  1661. }
  1662. // Check if we found the exit user.
  1663. BasicBlock *Parent = U->getParent();
  1664. if (!TheLoop->contains(Parent)) {
  1665. // Exit if you find multiple outside users.
  1666. if (ExitInstruction != 0)
  1667. return false;
  1668. ExitInstruction = Iter;
  1669. }
  1670. // We allow in-loop PHINodes which are not the original reduction PHI
  1671. // node. If this PHI is the only user of Iter (happens in IF w/ no ELSE
  1672. // structure) then don't skip this PHI.
  1673. if (isa<PHINode>(Iter) && isa<PHINode>(U) &&
  1674. U->getParent() != TheLoop->getHeader() &&
  1675. TheLoop->contains(U) &&
  1676. Iter->getNumUses() > 1)
  1677. continue;
  1678. // We can't have multiple inside users.
  1679. if (FoundInBlockUser)
  1680. return false;
  1681. FoundInBlockUser = true;
  1682. Iter = U;
  1683. }
  1684. // We found a reduction var if we have reached the original
  1685. // phi node and we only have a single instruction with out-of-loop
  1686. // users.
  1687. if (FoundStartPHI && ExitInstruction) {
  1688. // This instruction is allowed to have out-of-loop users.
  1689. AllowedExit.insert(ExitInstruction);
  1690. // Save the description of this reduction variable.
  1691. ReductionDescriptor RD(RdxStart, ExitInstruction, Kind);
  1692. Reductions[Phi] = RD;
  1693. return true;
  1694. }
  1695. // If we've reached the start PHI but did not find an outside user then
  1696. // this is dead code. Abort.
  1697. if (FoundStartPHI)
  1698. return false;
  1699. }
  1700. }
  1701. bool
  1702. LoopVectorizationLegality::isReductionInstr(Instruction *I,
  1703. ReductionKind Kind) {
  1704. switch (I->getOpcode()) {
  1705. default:
  1706. return false;
  1707. case Instruction::PHI:
  1708. // possibly.
  1709. return true;
  1710. case Instruction::Add:
  1711. case Instruction::Sub:
  1712. return Kind == IntegerAdd;
  1713. case Instruction::Mul:
  1714. return Kind == IntegerMult;
  1715. case Instruction::And:
  1716. return Kind == IntegerAnd;
  1717. case Instruction::Or:
  1718. return Kind == IntegerOr;
  1719. case Instruction::Xor:
  1720. return Kind == IntegerXor;
  1721. }
  1722. }
  1723. LoopVectorizationLegality::InductionKind
  1724. LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
  1725. Type *PhiTy = Phi->getType();
  1726. // We only handle integer and pointer inductions variables.
  1727. if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
  1728. return NoInduction;
  1729. // Check that the PHI is consecutive and starts at zero.
  1730. const SCEV *PhiScev = SE->getSCEV(Phi);
  1731. const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
  1732. if (!AR) {
  1733. DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
  1734. return NoInduction;
  1735. }
  1736. const SCEV *Step = AR->getStepRecurrence(*SE);
  1737. // Integer inductions need to have a stride of one.
  1738. if (PhiTy->isIntegerTy()) {
  1739. if (Step->isOne())
  1740. return IntInduction;
  1741. if (Step->isAllOnesValue())
  1742. return ReverseIntInduction;
  1743. return NoInduction;
  1744. }
  1745. // Calculate the pointer stride and check if it is consecutive.
  1746. const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
  1747. if (!C)
  1748. return NoInduction;
  1749. assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
  1750. uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
  1751. if (C->getValue()->equalsInt(Size))
  1752. return PtrInduction;
  1753. return NoInduction;
  1754. }
  1755. bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
  1756. Value *In0 = const_cast<Value*>(V);
  1757. PHINode *PN = dyn_cast_or_null<PHINode>(In0);
  1758. if (!PN)
  1759. return false;
  1760. return Inductions.count(PN);
  1761. }
  1762. bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
  1763. assert(TheLoop->contains(BB) && "Unknown block used");
  1764. // Blocks that do not dominate the latch need predication.
  1765. BasicBlock* Latch = TheLoop->getLoopLatch();
  1766. return !DT->dominates(BB, Latch);
  1767. }
  1768. bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB) {
  1769. for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
  1770. // We don't predicate loads/stores at the moment.
  1771. if (it->mayReadFromMemory() || it->mayWriteToMemory() || it->mayThrow())
  1772. return false;
  1773. // The instructions below can trap.
  1774. switch (it->getOpcode()) {
  1775. default: continue;
  1776. case Instruction::UDiv:
  1777. case Instruction::SDiv:
  1778. case Instruction::URem:
  1779. case Instruction::SRem:
  1780. return false;
  1781. }
  1782. }
  1783. return true;
  1784. }
  1785. bool LoopVectorizationLegality::hasComputableBounds(Value *Ptr) {
  1786. const SCEV *PhiScev = SE->getSCEV(Ptr);
  1787. const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
  1788. if (!AR)
  1789. return false;
  1790. return AR->isAffine();
  1791. }
  1792. unsigned
  1793. LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
  1794. unsigned UserVF) {
  1795. if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
  1796. DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
  1797. return 1;
  1798. }
  1799. // Find the trip count.
  1800. unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
  1801. DEBUG(dbgs() << "LV: Found trip count:"<<TC<<"\n");
  1802. unsigned VF = MaxVectorSize;
  1803. // If we optimize the program for size, avoid creating the tail loop.
  1804. if (OptForSize) {
  1805. // If we are unable to calculate the trip count then don't try to vectorize.
  1806. if (TC < 2) {
  1807. DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
  1808. return 1;
  1809. }
  1810. // Find the maximum SIMD width that can fit within the trip count.
  1811. VF = TC % MaxVectorSize;
  1812. if (VF == 0)
  1813. VF = MaxVectorSize;
  1814. // If the trip count that we found modulo the vectorization factor is not
  1815. // zero then we require a tail.
  1816. if (VF < 2) {
  1817. DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
  1818. return 1;
  1819. }
  1820. }
  1821. if (UserVF != 0) {
  1822. assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
  1823. DEBUG(dbgs() << "LV: Using user VF "<<UserVF<<".\n");
  1824. return UserVF;
  1825. }
  1826. if (!VTTI) {
  1827. DEBUG(dbgs() << "LV: No vector target information. Not vectorizing. \n");
  1828. return 1;
  1829. }
  1830. float Cost = expectedCost(1);
  1831. unsigned Width = 1;
  1832. DEBUG(dbgs() << "LV: Scalar loop costs: "<< (int)Cost << ".\n");
  1833. for (unsigned i=2; i <= VF; i*=2) {
  1834. // Notice that the vector loop needs to be executed less times, so
  1835. // we need to divide the cost of the vector loops by the width of
  1836. // the vector elements.
  1837. float VectorCost = expectedCost(i) / (float)i;
  1838. DEBUG(dbgs() << "LV: Vector loop of width "<< i << " costs: " <<
  1839. (int)VectorCost << ".\n");
  1840. if (VectorCost < Cost) {
  1841. Cost = VectorCost;
  1842. Width = i;
  1843. }
  1844. }
  1845. DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
  1846. return Width;
  1847. }
  1848. unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
  1849. unsigned Cost = 0;
  1850. // For each block.
  1851. for (Loop::block_iterator bb = TheLoop->block_begin(),
  1852. be = TheLoop->block_end(); bb != be; ++bb) {
  1853. unsigned BlockCost = 0;
  1854. BasicBlock *BB = *bb;
  1855. // For each instruction in the old loop.
  1856. for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
  1857. unsigned C = getInstructionCost(it, VF);
  1858. Cost += C;
  1859. DEBUG(dbgs() << "LV: Found an estimated cost of "<< C <<" for VF " <<
  1860. VF << " For instruction: "<< *it << "\n");
  1861. }
  1862. // We assume that if-converted blocks have a 50% chance of being executed.
  1863. // When the code is scalar then some of the blocks are avoided due to CF.
  1864. // When the code is vectorized we execute all code paths.
  1865. if (Legal->blockNeedsPredication(*bb) && VF == 1)
  1866. BlockCost /= 2;
  1867. Cost += BlockCost;
  1868. }
  1869. return Cost;
  1870. }
  1871. unsigned
  1872. LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
  1873. assert(VTTI && "Invalid vector target transformation info");
  1874. // If we know that this instruction will remain uniform, check the cost of
  1875. // the scalar version.
  1876. if (Legal->isUniformAfterVectorization(I))
  1877. VF = 1;
  1878. Type *RetTy = I->getType();
  1879. Type *VectorTy = ToVectorTy(RetTy, VF);
  1880. // TODO: We need to estimate the cost of intrinsic calls.
  1881. switch (I->getOpcode()) {
  1882. case Instruction::GetElementPtr:
  1883. // We mark this instruction as zero-cost because scalar GEPs are usually
  1884. // lowered to the intruction addressing mode. At the moment we don't
  1885. // generate vector geps.
  1886. return 0;
  1887. case Instruction::Br: {
  1888. return VTTI->getCFInstrCost(I->getOpcode());
  1889. }
  1890. case Instruction::PHI:
  1891. //TODO: IF-converted IFs become selects.
  1892. return 0;
  1893. case Instruction::Add:
  1894. case Instruction::FAdd:
  1895. case Instruction::Sub:
  1896. case Instruction::FSub:
  1897. case Instruction::Mul:
  1898. case Instruction::FMul:
  1899. case Instruction::UDiv:
  1900. case Instruction::SDiv:
  1901. case Instruction::FDiv:
  1902. case Instruction::URem:
  1903. case Instruction::SRem:
  1904. case Instruction::FRem:
  1905. case Instruction::Shl:
  1906. case Instruction::LShr:
  1907. case Instruction::AShr:
  1908. case Instruction::And:
  1909. case Instruction::Or:
  1910. case Instruction::Xor:
  1911. return VTTI->getArithmeticInstrCost(I->getOpcode(), VectorTy);
  1912. case Instruction::Select: {
  1913. SelectInst *SI = cast<SelectInst>(I);
  1914. const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
  1915. bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
  1916. Type *CondTy = SI->getCondition()->getType();
  1917. if (ScalarCond)
  1918. CondTy = VectorType::get(CondTy, VF);
  1919. return VTTI->getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
  1920. }
  1921. case Instruction::ICmp:
  1922. case Instruction::FCmp: {
  1923. Type *ValTy = I->getOperand(0)->getType();
  1924. VectorTy = ToVectorTy(ValTy, VF);
  1925. return VTTI->getCmpSelInstrCost(I->getOpcode(), VectorTy);
  1926. }
  1927. case Instruction::Store: {
  1928. StoreInst *SI = cast<StoreInst>(I);
  1929. Type *ValTy = SI->getValueOperand()->getType();
  1930. VectorTy = ToVectorTy(ValTy, VF);
  1931. if (VF == 1)
  1932. return VTTI->getMemoryOpCost(I->getOpcode(), VectorTy,
  1933. SI->getAlignment(),
  1934. SI->getPointerAddressSpace());
  1935. // Scalarized stores.
  1936. int Stride = Legal->isConsecutivePtr(SI->getPointerOperand());
  1937. bool Reverse = Stride < 0;
  1938. if (0 == Stride) {
  1939. unsigned Cost = 0;
  1940. // The cost of extracting from the value vector and pointer vector.
  1941. Type *PtrTy = ToVectorTy(I->getOperand(0)->getType(), VF);
  1942. for (unsigned i = 0; i < VF; ++i) {
  1943. Cost += VTTI->getVectorInstrCost(Instruction::ExtractElement,
  1944. VectorTy, i);
  1945. Cost += VTTI->getVectorInstrCost(Instruction::ExtractElement,
  1946. PtrTy, i);
  1947. }
  1948. // The cost of the scalar stores.
  1949. Cost += VF * VTTI->getMemoryOpCost(I->getOpcode(),
  1950. ValTy->getScalarType(),
  1951. SI->getAlignment(),
  1952. SI->getPointerAddressSpace());
  1953. return Cost;
  1954. }
  1955. // Wide stores.
  1956. unsigned Cost = VTTI->getMemoryOpCost(I->getOpcode(), VectorTy,
  1957. SI->getAlignment(),
  1958. SI->getPointerAddressSpace());
  1959. if (Reverse)
  1960. Cost += VTTI->getShuffleCost(VectorTargetTransformInfo::Reverse,
  1961. VectorTy, 0);
  1962. return Cost;
  1963. }
  1964. case Instruction::Load: {
  1965. LoadInst *LI = cast<LoadInst>(I);
  1966. if (VF == 1)
  1967. return VTTI->getMemoryOpCost(I->getOpcode(), VectorTy,
  1968. LI->getAlignment(),
  1969. LI->getPointerAddressSpace());
  1970. // Scalarized loads.
  1971. int Stride = Legal->isConsecutivePtr(LI->getPointerOperand());
  1972. bool Reverse = Stride < 0;
  1973. if (0 == Stride) {
  1974. unsigned Cost = 0;
  1975. Type *PtrTy = ToVectorTy(I->getOperand(0)->getType(), VF);
  1976. // The cost of extracting from the pointer vector.
  1977. for (unsigned i = 0; i < VF; ++i)
  1978. Cost += VTTI->getVectorInstrCost(Instruction::ExtractElement,
  1979. PtrTy, i);
  1980. // The cost of inserting data to the result vector.
  1981. for (unsigned i = 0; i < VF; ++i)
  1982. Cost += VTTI->getVectorInstrCost(Instruction::InsertElement,
  1983. VectorTy, i);
  1984. // The cost of the scalar stores.
  1985. Cost += VF * VTTI->getMemoryOpCost(I->getOpcode(),
  1986. RetTy->getScalarType(),
  1987. LI->getAlignment(),
  1988. LI->getPointerAddressSpace());
  1989. return Cost;
  1990. }
  1991. // Wide loads.
  1992. unsigned Cost = VTTI->getMemoryOpCost(I->getOpcode(), VectorTy,
  1993. LI->getAlignment(),
  1994. LI->getPointerAddressSpace());
  1995. if (Reverse)
  1996. Cost += VTTI->getShuffleCost(VectorTargetTransformInfo::Reverse,
  1997. VectorTy, 0);
  1998. return Cost;
  1999. }
  2000. case Instruction::ZExt:
  2001. case Instruction::SExt:
  2002. case Instruction::FPToUI:
  2003. case Instruction::FPToSI:
  2004. case Instruction::FPExt:
  2005. case Instruction::PtrToInt:
  2006. case Instruction::IntToPtr:
  2007. case Instruction::SIToFP:
  2008. case Instruction::UIToFP:
  2009. case Instruction::Trunc:
  2010. case Instruction::FPTrunc:
  2011. case Instruction::BitCast: {
  2012. // We optimize the truncation of induction variable.
  2013. // The cost of these is the same as the scalar operation.
  2014. if (I->getOpcode() == Instruction::Trunc &&
  2015. Legal->isInductionVariable(I->getOperand(0)))
  2016. return VTTI->getCastInstrCost(I->getOpcode(), I->getType(),
  2017. I->getOperand(0)->getType());
  2018. Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
  2019. return VTTI->getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
  2020. }
  2021. case Instruction::Call: {
  2022. assert(isTriviallyVectorizableIntrinsic(I));
  2023. IntrinsicInst *II = cast<IntrinsicInst>(I);
  2024. Type *RetTy = ToVectorTy(II->getType(), VF);
  2025. SmallVector<Type*, 4> Tys;
  2026. for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i)
  2027. Tys.push_back(ToVectorTy(II->getArgOperand(i)->getType(), VF));
  2028. return VTTI->getIntrinsicInstrCost(II->getIntrinsicID(), RetTy, Tys);
  2029. }
  2030. default: {
  2031. // We are scalarizing the instruction. Return the cost of the scalar
  2032. // instruction, plus the cost of insert and extract into vector
  2033. // elements, times the vector width.
  2034. unsigned Cost = 0;
  2035. if (!RetTy->isVoidTy() && VF != 1) {
  2036. unsigned InsCost = VTTI->getVectorInstrCost(Instruction::InsertElement,
  2037. VectorTy);
  2038. unsigned ExtCost = VTTI->getVectorInstrCost(Instruction::ExtractElement,
  2039. VectorTy);
  2040. // The cost of inserting the results plus extracting each one of the
  2041. // operands.
  2042. Cost += VF * (InsCost + ExtCost * I->getNumOperands());
  2043. }
  2044. // The cost of executing VF copies of the scalar instruction. This opcode
  2045. // is unknown. Assume that it is the same as 'mul'.
  2046. Cost += VF * VTTI->getArithmeticInstrCost(Instruction::Mul, VectorTy);
  2047. return Cost;
  2048. }
  2049. }// end of switch.
  2050. }
  2051. Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
  2052. if (Scalar->isVoidTy() || VF == 1)
  2053. return Scalar;
  2054. return VectorType::get(Scalar, VF);
  2055. }
  2056. char LoopVectorize::ID = 0;
  2057. static const char lv_name[] = "Loop Vectorization";
  2058. INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
  2059. INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
  2060. INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
  2061. INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
  2062. INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
  2063. namespace llvm {
  2064. Pass *createLoopVectorizePass() {
  2065. return new LoopVectorize();
  2066. }
  2067. }