SimplifyLibCalls.cpp 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430
  1. //===------ SimplifyLibCalls.cpp - Library calls simplifier ---------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This is a utility pass used for testing the InstructionSimplify analysis.
  11. // The analysis is applied to every instruction, and if it simplifies then the
  12. // instruction is replaced by the simplification. If you are looking for a pass
  13. // that performs serious instruction folding, use the instcombine pass instead.
  14. //
  15. //===----------------------------------------------------------------------===//
  16. #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
  17. #include "llvm/ADT/SmallString.h"
  18. #include "llvm/ADT/StringMap.h"
  19. #include "llvm/ADT/Triple.h"
  20. #include "llvm/Analysis/TargetLibraryInfo.h"
  21. #include "llvm/Analysis/ValueTracking.h"
  22. #include "llvm/IR/DataLayout.h"
  23. #include "llvm/IR/DiagnosticInfo.h"
  24. #include "llvm/IR/Function.h"
  25. #include "llvm/IR/IRBuilder.h"
  26. #include "llvm/IR/IntrinsicInst.h"
  27. #include "llvm/IR/Intrinsics.h"
  28. #include "llvm/IR/LLVMContext.h"
  29. #include "llvm/IR/Module.h"
  30. #include "llvm/IR/PatternMatch.h"
  31. #include "llvm/Support/CommandLine.h"
  32. #include "llvm/Support/KnownBits.h"
  33. #include "llvm/Transforms/Utils/BuildLibCalls.h"
  34. #include "llvm/Transforms/Utils/Local.h"
  35. using namespace llvm;
  36. using namespace PatternMatch;
  37. static cl::opt<bool>
  38. EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
  39. cl::init(false),
  40. cl::desc("Enable unsafe double to float "
  41. "shrinking for math lib calls"));
  42. //===----------------------------------------------------------------------===//
  43. // Helper Functions
  44. //===----------------------------------------------------------------------===//
  45. static bool ignoreCallingConv(LibFunc Func) {
  46. return Func == LibFunc_abs || Func == LibFunc_labs ||
  47. Func == LibFunc_llabs || Func == LibFunc_strlen;
  48. }
  49. static bool isCallingConvCCompatible(CallInst *CI) {
  50. switch(CI->getCallingConv()) {
  51. default:
  52. return false;
  53. case llvm::CallingConv::C:
  54. return true;
  55. case llvm::CallingConv::ARM_APCS:
  56. case llvm::CallingConv::ARM_AAPCS:
  57. case llvm::CallingConv::ARM_AAPCS_VFP: {
  58. // The iOS ABI diverges from the standard in some cases, so for now don't
  59. // try to simplify those calls.
  60. if (Triple(CI->getModule()->getTargetTriple()).isiOS())
  61. return false;
  62. auto *FuncTy = CI->getFunctionType();
  63. if (!FuncTy->getReturnType()->isPointerTy() &&
  64. !FuncTy->getReturnType()->isIntegerTy() &&
  65. !FuncTy->getReturnType()->isVoidTy())
  66. return false;
  67. for (auto Param : FuncTy->params()) {
  68. if (!Param->isPointerTy() && !Param->isIntegerTy())
  69. return false;
  70. }
  71. return true;
  72. }
  73. }
  74. return false;
  75. }
  76. /// Return true if it only matters that the value is equal or not-equal to zero.
  77. static bool isOnlyUsedInZeroEqualityComparison(Value *V) {
  78. for (User *U : V->users()) {
  79. if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
  80. if (IC->isEquality())
  81. if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
  82. if (C->isNullValue())
  83. continue;
  84. // Unknown instruction.
  85. return false;
  86. }
  87. return true;
  88. }
  89. /// Return true if it is only used in equality comparisons with With.
  90. static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
  91. for (User *U : V->users()) {
  92. if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
  93. if (IC->isEquality() && IC->getOperand(1) == With)
  94. continue;
  95. // Unknown instruction.
  96. return false;
  97. }
  98. return true;
  99. }
  100. static bool callHasFloatingPointArgument(const CallInst *CI) {
  101. return any_of(CI->operands(), [](const Use &OI) {
  102. return OI->getType()->isFloatingPointTy();
  103. });
  104. }
  105. /// \brief Check whether the overloaded unary floating point function
  106. /// corresponding to \a Ty is available.
  107. static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
  108. LibFunc DoubleFn, LibFunc FloatFn,
  109. LibFunc LongDoubleFn) {
  110. switch (Ty->getTypeID()) {
  111. case Type::FloatTyID:
  112. return TLI->has(FloatFn);
  113. case Type::DoubleTyID:
  114. return TLI->has(DoubleFn);
  115. default:
  116. return TLI->has(LongDoubleFn);
  117. }
  118. }
  119. //===----------------------------------------------------------------------===//
  120. // String and Memory Library Call Optimizations
  121. //===----------------------------------------------------------------------===//
  122. Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
  123. // Extract some information from the instruction
  124. Value *Dst = CI->getArgOperand(0);
  125. Value *Src = CI->getArgOperand(1);
  126. // See if we can get the length of the input string.
  127. uint64_t Len = GetStringLength(Src);
  128. if (Len == 0)
  129. return nullptr;
  130. --Len; // Unbias length.
  131. // Handle the simple, do-nothing case: strcat(x, "") -> x
  132. if (Len == 0)
  133. return Dst;
  134. return emitStrLenMemCpy(Src, Dst, Len, B);
  135. }
  136. Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
  137. IRBuilder<> &B) {
  138. // We need to find the end of the destination string. That's where the
  139. // memory is to be moved to. We just generate a call to strlen.
  140. Value *DstLen = emitStrLen(Dst, B, DL, TLI);
  141. if (!DstLen)
  142. return nullptr;
  143. // Now that we have the destination's length, we must index into the
  144. // destination's pointer to get the actual memcpy destination (end of
  145. // the string .. we're concatenating).
  146. Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
  147. // We have enough information to now generate the memcpy call to do the
  148. // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
  149. B.CreateMemCpy(CpyDst, Src,
  150. ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1),
  151. 1);
  152. return Dst;
  153. }
  154. Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
  155. // Extract some information from the instruction.
  156. Value *Dst = CI->getArgOperand(0);
  157. Value *Src = CI->getArgOperand(1);
  158. uint64_t Len;
  159. // We don't do anything if length is not constant.
  160. if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
  161. Len = LengthArg->getZExtValue();
  162. else
  163. return nullptr;
  164. // See if we can get the length of the input string.
  165. uint64_t SrcLen = GetStringLength(Src);
  166. if (SrcLen == 0)
  167. return nullptr;
  168. --SrcLen; // Unbias length.
  169. // Handle the simple, do-nothing cases:
  170. // strncat(x, "", c) -> x
  171. // strncat(x, c, 0) -> x
  172. if (SrcLen == 0 || Len == 0)
  173. return Dst;
  174. // We don't optimize this case.
  175. if (Len < SrcLen)
  176. return nullptr;
  177. // strncat(x, s, c) -> strcat(x, s)
  178. // s is constant so the strcat can be optimized further.
  179. return emitStrLenMemCpy(Src, Dst, SrcLen, B);
  180. }
  181. Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
  182. Function *Callee = CI->getCalledFunction();
  183. FunctionType *FT = Callee->getFunctionType();
  184. Value *SrcStr = CI->getArgOperand(0);
  185. // If the second operand is non-constant, see if we can compute the length
  186. // of the input string and turn this into memchr.
  187. ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
  188. if (!CharC) {
  189. uint64_t Len = GetStringLength(SrcStr);
  190. if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
  191. return nullptr;
  192. return emitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
  193. ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
  194. B, DL, TLI);
  195. }
  196. // Otherwise, the character is a constant, see if the first argument is
  197. // a string literal. If so, we can constant fold.
  198. StringRef Str;
  199. if (!getConstantStringInfo(SrcStr, Str)) {
  200. if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
  201. return B.CreateGEP(B.getInt8Ty(), SrcStr, emitStrLen(SrcStr, B, DL, TLI),
  202. "strchr");
  203. return nullptr;
  204. }
  205. // Compute the offset, make sure to handle the case when we're searching for
  206. // zero (a weird way to spell strlen).
  207. size_t I = (0xFF & CharC->getSExtValue()) == 0
  208. ? Str.size()
  209. : Str.find(CharC->getSExtValue());
  210. if (I == StringRef::npos) // Didn't find the char. strchr returns null.
  211. return Constant::getNullValue(CI->getType());
  212. // strchr(s+n,c) -> gep(s+n+i,c)
  213. return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
  214. }
  215. Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
  216. Value *SrcStr = CI->getArgOperand(0);
  217. ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
  218. // Cannot fold anything if we're not looking for a constant.
  219. if (!CharC)
  220. return nullptr;
  221. StringRef Str;
  222. if (!getConstantStringInfo(SrcStr, Str)) {
  223. // strrchr(s, 0) -> strchr(s, 0)
  224. if (CharC->isZero())
  225. return emitStrChr(SrcStr, '\0', B, TLI);
  226. return nullptr;
  227. }
  228. // Compute the offset.
  229. size_t I = (0xFF & CharC->getSExtValue()) == 0
  230. ? Str.size()
  231. : Str.rfind(CharC->getSExtValue());
  232. if (I == StringRef::npos) // Didn't find the char. Return null.
  233. return Constant::getNullValue(CI->getType());
  234. // strrchr(s+n,c) -> gep(s+n+i,c)
  235. return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
  236. }
  237. Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
  238. Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
  239. if (Str1P == Str2P) // strcmp(x,x) -> 0
  240. return ConstantInt::get(CI->getType(), 0);
  241. StringRef Str1, Str2;
  242. bool HasStr1 = getConstantStringInfo(Str1P, Str1);
  243. bool HasStr2 = getConstantStringInfo(Str2P, Str2);
  244. // strcmp(x, y) -> cnst (if both x and y are constant strings)
  245. if (HasStr1 && HasStr2)
  246. return ConstantInt::get(CI->getType(), Str1.compare(Str2));
  247. if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
  248. return B.CreateNeg(
  249. B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
  250. if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
  251. return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
  252. // strcmp(P, "x") -> memcmp(P, "x", 2)
  253. uint64_t Len1 = GetStringLength(Str1P);
  254. uint64_t Len2 = GetStringLength(Str2P);
  255. if (Len1 && Len2) {
  256. return emitMemCmp(Str1P, Str2P,
  257. ConstantInt::get(DL.getIntPtrType(CI->getContext()),
  258. std::min(Len1, Len2)),
  259. B, DL, TLI);
  260. }
  261. return nullptr;
  262. }
  263. Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
  264. Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
  265. if (Str1P == Str2P) // strncmp(x,x,n) -> 0
  266. return ConstantInt::get(CI->getType(), 0);
  267. // Get the length argument if it is constant.
  268. uint64_t Length;
  269. if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
  270. Length = LengthArg->getZExtValue();
  271. else
  272. return nullptr;
  273. if (Length == 0) // strncmp(x,y,0) -> 0
  274. return ConstantInt::get(CI->getType(), 0);
  275. if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
  276. return emitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
  277. StringRef Str1, Str2;
  278. bool HasStr1 = getConstantStringInfo(Str1P, Str1);
  279. bool HasStr2 = getConstantStringInfo(Str2P, Str2);
  280. // strncmp(x, y) -> cnst (if both x and y are constant strings)
  281. if (HasStr1 && HasStr2) {
  282. StringRef SubStr1 = Str1.substr(0, Length);
  283. StringRef SubStr2 = Str2.substr(0, Length);
  284. return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
  285. }
  286. if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
  287. return B.CreateNeg(
  288. B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
  289. if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
  290. return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
  291. return nullptr;
  292. }
  293. Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
  294. Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
  295. if (Dst == Src) // strcpy(x,x) -> x
  296. return Src;
  297. // See if we can get the length of the input string.
  298. uint64_t Len = GetStringLength(Src);
  299. if (Len == 0)
  300. return nullptr;
  301. // We have enough information to now generate the memcpy call to do the
  302. // copy for us. Make a memcpy to copy the nul byte with align = 1.
  303. B.CreateMemCpy(Dst, Src,
  304. ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), 1);
  305. return Dst;
  306. }
  307. Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
  308. Function *Callee = CI->getCalledFunction();
  309. Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
  310. if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
  311. Value *StrLen = emitStrLen(Src, B, DL, TLI);
  312. return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
  313. }
  314. // See if we can get the length of the input string.
  315. uint64_t Len = GetStringLength(Src);
  316. if (Len == 0)
  317. return nullptr;
  318. Type *PT = Callee->getFunctionType()->getParamType(0);
  319. Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
  320. Value *DstEnd = B.CreateGEP(B.getInt8Ty(), Dst,
  321. ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
  322. // We have enough information to now generate the memcpy call to do the
  323. // copy for us. Make a memcpy to copy the nul byte with align = 1.
  324. B.CreateMemCpy(Dst, Src, LenV, 1);
  325. return DstEnd;
  326. }
  327. Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
  328. Function *Callee = CI->getCalledFunction();
  329. Value *Dst = CI->getArgOperand(0);
  330. Value *Src = CI->getArgOperand(1);
  331. Value *LenOp = CI->getArgOperand(2);
  332. // See if we can get the length of the input string.
  333. uint64_t SrcLen = GetStringLength(Src);
  334. if (SrcLen == 0)
  335. return nullptr;
  336. --SrcLen;
  337. if (SrcLen == 0) {
  338. // strncpy(x, "", y) -> memset(x, '\0', y, 1)
  339. B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
  340. return Dst;
  341. }
  342. uint64_t Len;
  343. if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
  344. Len = LengthArg->getZExtValue();
  345. else
  346. return nullptr;
  347. if (Len == 0)
  348. return Dst; // strncpy(x, y, 0) -> x
  349. // Let strncpy handle the zero padding
  350. if (Len > SrcLen + 1)
  351. return nullptr;
  352. Type *PT = Callee->getFunctionType()->getParamType(0);
  353. // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
  354. B.CreateMemCpy(Dst, Src, ConstantInt::get(DL.getIntPtrType(PT), Len), 1);
  355. return Dst;
  356. }
  357. Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
  358. Value *Src = CI->getArgOperand(0);
  359. // Constant folding: strlen("xyz") -> 3
  360. if (uint64_t Len = GetStringLength(Src))
  361. return ConstantInt::get(CI->getType(), Len - 1);
  362. // If s is a constant pointer pointing to a string literal, we can fold
  363. // strlen(s + x) to strlen(s) - x, when x is known to be in the range
  364. // [0, strlen(s)] or the string has a single null terminator '\0' at the end.
  365. // We only try to simplify strlen when the pointer s points to an array
  366. // of i8. Otherwise, we would need to scale the offset x before doing the
  367. // subtraction. This will make the optimization more complex, and it's not
  368. // very useful because calling strlen for a pointer of other types is
  369. // very uncommon.
  370. if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) {
  371. if (!isGEPBasedOnPointerToString(GEP))
  372. return nullptr;
  373. StringRef Str;
  374. if (getConstantStringInfo(GEP->getOperand(0), Str, 0, false)) {
  375. size_t NullTermIdx = Str.find('\0');
  376. // If the string does not have '\0', leave it to strlen to compute
  377. // its length.
  378. if (NullTermIdx == StringRef::npos)
  379. return nullptr;
  380. Value *Offset = GEP->getOperand(2);
  381. unsigned BitWidth = Offset->getType()->getIntegerBitWidth();
  382. KnownBits Known(BitWidth);
  383. computeKnownBits(Offset, Known, DL, 0, nullptr, CI, nullptr);
  384. Known.Zero.flipAllBits();
  385. size_t ArrSize =
  386. cast<ArrayType>(GEP->getSourceElementType())->getNumElements();
  387. // KnownZero's bits are flipped, so zeros in KnownZero now represent
  388. // bits known to be zeros in Offset, and ones in KnowZero represent
  389. // bits unknown in Offset. Therefore, Offset is known to be in range
  390. // [0, NullTermIdx] when the flipped KnownZero is non-negative and
  391. // unsigned-less-than NullTermIdx.
  392. //
  393. // If Offset is not provably in the range [0, NullTermIdx], we can still
  394. // optimize if we can prove that the program has undefined behavior when
  395. // Offset is outside that range. That is the case when GEP->getOperand(0)
  396. // is a pointer to an object whose memory extent is NullTermIdx+1.
  397. if ((Known.Zero.isNonNegative() && Known.Zero.ule(NullTermIdx)) ||
  398. (GEP->isInBounds() && isa<GlobalVariable>(GEP->getOperand(0)) &&
  399. NullTermIdx == ArrSize - 1))
  400. return B.CreateSub(ConstantInt::get(CI->getType(), NullTermIdx),
  401. Offset);
  402. }
  403. return nullptr;
  404. }
  405. // strlen(x?"foo":"bars") --> x ? 3 : 4
  406. if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
  407. uint64_t LenTrue = GetStringLength(SI->getTrueValue());
  408. uint64_t LenFalse = GetStringLength(SI->getFalseValue());
  409. if (LenTrue && LenFalse) {
  410. Function *Caller = CI->getParent()->getParent();
  411. emitOptimizationRemark(CI->getContext(), "simplify-libcalls", *Caller,
  412. SI->getDebugLoc(),
  413. "folded strlen(select) to select of constants");
  414. return B.CreateSelect(SI->getCondition(),
  415. ConstantInt::get(CI->getType(), LenTrue - 1),
  416. ConstantInt::get(CI->getType(), LenFalse - 1));
  417. }
  418. }
  419. // strlen(x) != 0 --> *x != 0
  420. // strlen(x) == 0 --> *x == 0
  421. if (isOnlyUsedInZeroEqualityComparison(CI))
  422. return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
  423. return nullptr;
  424. }
  425. Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
  426. StringRef S1, S2;
  427. bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
  428. bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
  429. // strpbrk(s, "") -> nullptr
  430. // strpbrk("", s) -> nullptr
  431. if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
  432. return Constant::getNullValue(CI->getType());
  433. // Constant folding.
  434. if (HasS1 && HasS2) {
  435. size_t I = S1.find_first_of(S2);
  436. if (I == StringRef::npos) // No match.
  437. return Constant::getNullValue(CI->getType());
  438. return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I),
  439. "strpbrk");
  440. }
  441. // strpbrk(s, "a") -> strchr(s, 'a')
  442. if (HasS2 && S2.size() == 1)
  443. return emitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
  444. return nullptr;
  445. }
  446. Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
  447. Value *EndPtr = CI->getArgOperand(1);
  448. if (isa<ConstantPointerNull>(EndPtr)) {
  449. // With a null EndPtr, this function won't capture the main argument.
  450. // It would be readonly too, except that it still may write to errno.
  451. CI->addParamAttr(0, Attribute::NoCapture);
  452. }
  453. return nullptr;
  454. }
  455. Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
  456. StringRef S1, S2;
  457. bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
  458. bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
  459. // strspn(s, "") -> 0
  460. // strspn("", s) -> 0
  461. if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
  462. return Constant::getNullValue(CI->getType());
  463. // Constant folding.
  464. if (HasS1 && HasS2) {
  465. size_t Pos = S1.find_first_not_of(S2);
  466. if (Pos == StringRef::npos)
  467. Pos = S1.size();
  468. return ConstantInt::get(CI->getType(), Pos);
  469. }
  470. return nullptr;
  471. }
  472. Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
  473. StringRef S1, S2;
  474. bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
  475. bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
  476. // strcspn("", s) -> 0
  477. if (HasS1 && S1.empty())
  478. return Constant::getNullValue(CI->getType());
  479. // Constant folding.
  480. if (HasS1 && HasS2) {
  481. size_t Pos = S1.find_first_of(S2);
  482. if (Pos == StringRef::npos)
  483. Pos = S1.size();
  484. return ConstantInt::get(CI->getType(), Pos);
  485. }
  486. // strcspn(s, "") -> strlen(s)
  487. if (HasS2 && S2.empty())
  488. return emitStrLen(CI->getArgOperand(0), B, DL, TLI);
  489. return nullptr;
  490. }
  491. Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
  492. // fold strstr(x, x) -> x.
  493. if (CI->getArgOperand(0) == CI->getArgOperand(1))
  494. return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
  495. // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
  496. if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
  497. Value *StrLen = emitStrLen(CI->getArgOperand(1), B, DL, TLI);
  498. if (!StrLen)
  499. return nullptr;
  500. Value *StrNCmp = emitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
  501. StrLen, B, DL, TLI);
  502. if (!StrNCmp)
  503. return nullptr;
  504. for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
  505. ICmpInst *Old = cast<ICmpInst>(*UI++);
  506. Value *Cmp =
  507. B.CreateICmp(Old->getPredicate(), StrNCmp,
  508. ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
  509. replaceAllUsesWith(Old, Cmp);
  510. }
  511. return CI;
  512. }
  513. // See if either input string is a constant string.
  514. StringRef SearchStr, ToFindStr;
  515. bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
  516. bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
  517. // fold strstr(x, "") -> x.
  518. if (HasStr2 && ToFindStr.empty())
  519. return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
  520. // If both strings are known, constant fold it.
  521. if (HasStr1 && HasStr2) {
  522. size_t Offset = SearchStr.find(ToFindStr);
  523. if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
  524. return Constant::getNullValue(CI->getType());
  525. // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
  526. Value *Result = castToCStr(CI->getArgOperand(0), B);
  527. Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
  528. return B.CreateBitCast(Result, CI->getType());
  529. }
  530. // fold strstr(x, "y") -> strchr(x, 'y').
  531. if (HasStr2 && ToFindStr.size() == 1) {
  532. Value *StrChr = emitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
  533. return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
  534. }
  535. return nullptr;
  536. }
  537. Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
  538. Value *SrcStr = CI->getArgOperand(0);
  539. ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
  540. ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
  541. // memchr(x, y, 0) -> null
  542. if (LenC && LenC->isNullValue())
  543. return Constant::getNullValue(CI->getType());
  544. // From now on we need at least constant length and string.
  545. StringRef Str;
  546. if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
  547. return nullptr;
  548. // Truncate the string to LenC. If Str is smaller than LenC we will still only
  549. // scan the string, as reading past the end of it is undefined and we can just
  550. // return null if we don't find the char.
  551. Str = Str.substr(0, LenC->getZExtValue());
  552. // If the char is variable but the input str and length are not we can turn
  553. // this memchr call into a simple bit field test. Of course this only works
  554. // when the return value is only checked against null.
  555. //
  556. // It would be really nice to reuse switch lowering here but we can't change
  557. // the CFG at this point.
  558. //
  559. // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
  560. // after bounds check.
  561. if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
  562. unsigned char Max =
  563. *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
  564. reinterpret_cast<const unsigned char *>(Str.end()));
  565. // Make sure the bit field we're about to create fits in a register on the
  566. // target.
  567. // FIXME: On a 64 bit architecture this prevents us from using the
  568. // interesting range of alpha ascii chars. We could do better by emitting
  569. // two bitfields or shifting the range by 64 if no lower chars are used.
  570. if (!DL.fitsInLegalInteger(Max + 1))
  571. return nullptr;
  572. // For the bit field use a power-of-2 type with at least 8 bits to avoid
  573. // creating unnecessary illegal types.
  574. unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
  575. // Now build the bit field.
  576. APInt Bitfield(Width, 0);
  577. for (char C : Str)
  578. Bitfield.setBit((unsigned char)C);
  579. Value *BitfieldC = B.getInt(Bitfield);
  580. // First check that the bit field access is within bounds.
  581. Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
  582. Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
  583. "memchr.bounds");
  584. // Create code that checks if the given bit is set in the field.
  585. Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
  586. Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
  587. // Finally merge both checks and cast to pointer type. The inttoptr
  588. // implicitly zexts the i1 to intptr type.
  589. return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
  590. }
  591. // Check if all arguments are constants. If so, we can constant fold.
  592. if (!CharC)
  593. return nullptr;
  594. // Compute the offset.
  595. size_t I = Str.find(CharC->getSExtValue() & 0xFF);
  596. if (I == StringRef::npos) // Didn't find the char. memchr returns null.
  597. return Constant::getNullValue(CI->getType());
  598. // memchr(s+n,c,l) -> gep(s+n+i,c)
  599. return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
  600. }
  601. Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
  602. Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
  603. if (LHS == RHS) // memcmp(s,s,x) -> 0
  604. return Constant::getNullValue(CI->getType());
  605. // Make sure we have a constant length.
  606. ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
  607. if (!LenC)
  608. return nullptr;
  609. uint64_t Len = LenC->getZExtValue();
  610. if (Len == 0) // memcmp(s1,s2,0) -> 0
  611. return Constant::getNullValue(CI->getType());
  612. // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
  613. if (Len == 1) {
  614. Value *LHSV = B.CreateZExt(B.CreateLoad(castToCStr(LHS, B), "lhsc"),
  615. CI->getType(), "lhsv");
  616. Value *RHSV = B.CreateZExt(B.CreateLoad(castToCStr(RHS, B), "rhsc"),
  617. CI->getType(), "rhsv");
  618. return B.CreateSub(LHSV, RHSV, "chardiff");
  619. }
  620. // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
  621. if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
  622. IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
  623. unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
  624. if (getKnownAlignment(LHS, DL, CI) >= PrefAlignment &&
  625. getKnownAlignment(RHS, DL, CI) >= PrefAlignment) {
  626. Type *LHSPtrTy =
  627. IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
  628. Type *RHSPtrTy =
  629. IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
  630. Value *LHSV =
  631. B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy, "lhsc"), "lhsv");
  632. Value *RHSV =
  633. B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy, "rhsc"), "rhsv");
  634. return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
  635. }
  636. }
  637. // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
  638. StringRef LHSStr, RHSStr;
  639. if (getConstantStringInfo(LHS, LHSStr) &&
  640. getConstantStringInfo(RHS, RHSStr)) {
  641. // Make sure we're not reading out-of-bounds memory.
  642. if (Len > LHSStr.size() || Len > RHSStr.size())
  643. return nullptr;
  644. // Fold the memcmp and normalize the result. This way we get consistent
  645. // results across multiple platforms.
  646. uint64_t Ret = 0;
  647. int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
  648. if (Cmp < 0)
  649. Ret = -1;
  650. else if (Cmp > 0)
  651. Ret = 1;
  652. return ConstantInt::get(CI->getType(), Ret);
  653. }
  654. return nullptr;
  655. }
  656. Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
  657. // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
  658. B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
  659. CI->getArgOperand(2), 1);
  660. return CI->getArgOperand(0);
  661. }
  662. Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
  663. // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
  664. B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
  665. CI->getArgOperand(2), 1);
  666. return CI->getArgOperand(0);
  667. }
  668. // TODO: Does this belong in BuildLibCalls or should all of those similar
  669. // functions be moved here?
  670. static Value *emitCalloc(Value *Num, Value *Size, const AttributeList &Attrs,
  671. IRBuilder<> &B, const TargetLibraryInfo &TLI) {
  672. LibFunc Func;
  673. if (!TLI.getLibFunc("calloc", Func) || !TLI.has(Func))
  674. return nullptr;
  675. Module *M = B.GetInsertBlock()->getModule();
  676. const DataLayout &DL = M->getDataLayout();
  677. IntegerType *PtrType = DL.getIntPtrType((B.GetInsertBlock()->getContext()));
  678. Value *Calloc = M->getOrInsertFunction("calloc", Attrs, B.getInt8PtrTy(),
  679. PtrType, PtrType);
  680. CallInst *CI = B.CreateCall(Calloc, { Num, Size }, "calloc");
  681. if (const auto *F = dyn_cast<Function>(Calloc->stripPointerCasts()))
  682. CI->setCallingConv(F->getCallingConv());
  683. return CI;
  684. }
  685. /// Fold memset[_chk](malloc(n), 0, n) --> calloc(1, n).
  686. static Value *foldMallocMemset(CallInst *Memset, IRBuilder<> &B,
  687. const TargetLibraryInfo &TLI) {
  688. // This has to be a memset of zeros (bzero).
  689. auto *FillValue = dyn_cast<ConstantInt>(Memset->getArgOperand(1));
  690. if (!FillValue || FillValue->getZExtValue() != 0)
  691. return nullptr;
  692. // TODO: We should handle the case where the malloc has more than one use.
  693. // This is necessary to optimize common patterns such as when the result of
  694. // the malloc is checked against null or when a memset intrinsic is used in
  695. // place of a memset library call.
  696. auto *Malloc = dyn_cast<CallInst>(Memset->getArgOperand(0));
  697. if (!Malloc || !Malloc->hasOneUse())
  698. return nullptr;
  699. // Is the inner call really malloc()?
  700. Function *InnerCallee = Malloc->getCalledFunction();
  701. if (!InnerCallee)
  702. return nullptr;
  703. LibFunc Func;
  704. if (!TLI.getLibFunc(*InnerCallee, Func) || !TLI.has(Func) ||
  705. Func != LibFunc_malloc)
  706. return nullptr;
  707. // The memset must cover the same number of bytes that are malloc'd.
  708. if (Memset->getArgOperand(2) != Malloc->getArgOperand(0))
  709. return nullptr;
  710. // Replace the malloc with a calloc. We need the data layout to know what the
  711. // actual size of a 'size_t' parameter is.
  712. B.SetInsertPoint(Malloc->getParent(), ++Malloc->getIterator());
  713. const DataLayout &DL = Malloc->getModule()->getDataLayout();
  714. IntegerType *SizeType = DL.getIntPtrType(B.GetInsertBlock()->getContext());
  715. Value *Calloc = emitCalloc(ConstantInt::get(SizeType, 1),
  716. Malloc->getArgOperand(0), Malloc->getAttributes(),
  717. B, TLI);
  718. if (!Calloc)
  719. return nullptr;
  720. Malloc->replaceAllUsesWith(Calloc);
  721. Malloc->eraseFromParent();
  722. return Calloc;
  723. }
  724. Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
  725. if (auto *Calloc = foldMallocMemset(CI, B, *TLI))
  726. return Calloc;
  727. // memset(p, v, n) -> llvm.memset(p, v, n, 1)
  728. Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
  729. B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
  730. return CI->getArgOperand(0);
  731. }
  732. //===----------------------------------------------------------------------===//
  733. // Math Library Optimizations
  734. //===----------------------------------------------------------------------===//
  735. /// Return a variant of Val with float type.
  736. /// Currently this works in two cases: If Val is an FPExtension of a float
  737. /// value to something bigger, simply return the operand.
  738. /// If Val is a ConstantFP but can be converted to a float ConstantFP without
  739. /// loss of precision do so.
  740. static Value *valueHasFloatPrecision(Value *Val) {
  741. if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
  742. Value *Op = Cast->getOperand(0);
  743. if (Op->getType()->isFloatTy())
  744. return Op;
  745. }
  746. if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
  747. APFloat F = Const->getValueAPF();
  748. bool losesInfo;
  749. (void)F.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
  750. &losesInfo);
  751. if (!losesInfo)
  752. return ConstantFP::get(Const->getContext(), F);
  753. }
  754. return nullptr;
  755. }
  756. /// Shrink double -> float for unary functions like 'floor'.
  757. static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
  758. bool CheckRetType) {
  759. Function *Callee = CI->getCalledFunction();
  760. // We know this libcall has a valid prototype, but we don't know which.
  761. if (!CI->getType()->isDoubleTy())
  762. return nullptr;
  763. if (CheckRetType) {
  764. // Check if all the uses for function like 'sin' are converted to float.
  765. for (User *U : CI->users()) {
  766. FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
  767. if (!Cast || !Cast->getType()->isFloatTy())
  768. return nullptr;
  769. }
  770. }
  771. // If this is something like 'floor((double)floatval)', convert to floorf.
  772. Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
  773. if (V == nullptr)
  774. return nullptr;
  775. // If call isn't an intrinsic, check that it isn't within a function with the
  776. // same name as the float version of this call.
  777. //
  778. // e.g. inline float expf(float val) { return (float) exp((double) val); }
  779. //
  780. // A similar such definition exists in the MinGW-w64 math.h header file which
  781. // when compiled with -O2 -ffast-math causes the generation of infinite loops
  782. // where expf is called.
  783. if (!Callee->isIntrinsic()) {
  784. const Function *F = CI->getFunction();
  785. StringRef FName = F->getName();
  786. StringRef CalleeName = Callee->getName();
  787. if ((FName.size() == (CalleeName.size() + 1)) &&
  788. (FName.back() == 'f') &&
  789. FName.startswith(CalleeName))
  790. return nullptr;
  791. }
  792. // Propagate fast-math flags from the existing call to the new call.
  793. IRBuilder<>::FastMathFlagGuard Guard(B);
  794. B.setFastMathFlags(CI->getFastMathFlags());
  795. // floor((double)floatval) -> (double)floorf(floatval)
  796. if (Callee->isIntrinsic()) {
  797. Module *M = CI->getModule();
  798. Intrinsic::ID IID = Callee->getIntrinsicID();
  799. Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
  800. V = B.CreateCall(F, V);
  801. } else {
  802. // The call is a library call rather than an intrinsic.
  803. V = emitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
  804. }
  805. return B.CreateFPExt(V, B.getDoubleTy());
  806. }
  807. // Replace a libcall \p CI with a call to intrinsic \p IID
  808. static Value *replaceUnaryCall(CallInst *CI, IRBuilder<> &B, Intrinsic::ID IID) {
  809. // Propagate fast-math flags from the existing call to the new call.
  810. IRBuilder<>::FastMathFlagGuard Guard(B);
  811. B.setFastMathFlags(CI->getFastMathFlags());
  812. Module *M = CI->getModule();
  813. Value *V = CI->getArgOperand(0);
  814. Function *F = Intrinsic::getDeclaration(M, IID, CI->getType());
  815. CallInst *NewCall = B.CreateCall(F, V);
  816. NewCall->takeName(CI);
  817. return NewCall;
  818. }
  819. /// Shrink double -> float for binary functions like 'fmin/fmax'.
  820. static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
  821. Function *Callee = CI->getCalledFunction();
  822. // We know this libcall has a valid prototype, but we don't know which.
  823. if (!CI->getType()->isDoubleTy())
  824. return nullptr;
  825. // If this is something like 'fmin((double)floatval1, (double)floatval2)',
  826. // or fmin(1.0, (double)floatval), then we convert it to fminf.
  827. Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
  828. if (V1 == nullptr)
  829. return nullptr;
  830. Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
  831. if (V2 == nullptr)
  832. return nullptr;
  833. // Propagate fast-math flags from the existing call to the new call.
  834. IRBuilder<>::FastMathFlagGuard Guard(B);
  835. B.setFastMathFlags(CI->getFastMathFlags());
  836. // fmin((double)floatval1, (double)floatval2)
  837. // -> (double)fminf(floatval1, floatval2)
  838. // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
  839. Value *V = emitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
  840. Callee->getAttributes());
  841. return B.CreateFPExt(V, B.getDoubleTy());
  842. }
  843. Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
  844. Function *Callee = CI->getCalledFunction();
  845. Value *Ret = nullptr;
  846. StringRef Name = Callee->getName();
  847. if (UnsafeFPShrink && Name == "cos" && hasFloatVersion(Name))
  848. Ret = optimizeUnaryDoubleFP(CI, B, true);
  849. // cos(-x) -> cos(x)
  850. Value *Op1 = CI->getArgOperand(0);
  851. if (BinaryOperator::isFNeg(Op1)) {
  852. BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
  853. return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
  854. }
  855. return Ret;
  856. }
  857. static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B) {
  858. // Multiplications calculated using Addition Chains.
  859. // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html
  860. assert(Exp != 0 && "Incorrect exponent 0 not handled");
  861. if (InnerChain[Exp])
  862. return InnerChain[Exp];
  863. static const unsigned AddChain[33][2] = {
  864. {0, 0}, // Unused.
  865. {0, 0}, // Unused (base case = pow1).
  866. {1, 1}, // Unused (pre-computed).
  867. {1, 2}, {2, 2}, {2, 3}, {3, 3}, {2, 5}, {4, 4},
  868. {1, 8}, {5, 5}, {1, 10}, {6, 6}, {4, 9}, {7, 7},
  869. {3, 12}, {8, 8}, {8, 9}, {2, 16}, {1, 18}, {10, 10},
  870. {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13},
  871. {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16},
  872. };
  873. InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B),
  874. getPow(InnerChain, AddChain[Exp][1], B));
  875. return InnerChain[Exp];
  876. }
  877. Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
  878. Function *Callee = CI->getCalledFunction();
  879. Value *Ret = nullptr;
  880. StringRef Name = Callee->getName();
  881. if (UnsafeFPShrink && Name == "pow" && hasFloatVersion(Name))
  882. Ret = optimizeUnaryDoubleFP(CI, B, true);
  883. Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
  884. // pow(1.0, x) -> 1.0
  885. if (match(Op1, m_SpecificFP(1.0)))
  886. return Op1;
  887. // pow(2.0, x) -> llvm.exp2(x)
  888. if (match(Op1, m_SpecificFP(2.0))) {
  889. Value *Exp2 = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::exp2,
  890. CI->getType());
  891. return B.CreateCall(Exp2, Op2, "exp2");
  892. }
  893. // There's no llvm.exp10 intrinsic yet, but, maybe, some day there will
  894. // be one.
  895. if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
  896. // pow(10.0, x) -> exp10(x)
  897. if (Op1C->isExactlyValue(10.0) &&
  898. hasUnaryFloatFn(TLI, Op1->getType(), LibFunc_exp10, LibFunc_exp10f,
  899. LibFunc_exp10l))
  900. return emitUnaryFloatFnCall(Op2, TLI->getName(LibFunc_exp10), B,
  901. Callee->getAttributes());
  902. }
  903. // pow(exp(x), y) -> exp(x * y)
  904. // pow(exp2(x), y) -> exp2(x * y)
  905. // We enable these only with fast-math. Besides rounding differences, the
  906. // transformation changes overflow and underflow behavior quite dramatically.
  907. // Example: x = 1000, y = 0.001.
  908. // pow(exp(x), y) = pow(inf, 0.001) = inf, whereas exp(x*y) = exp(1).
  909. auto *OpC = dyn_cast<CallInst>(Op1);
  910. if (OpC && OpC->hasUnsafeAlgebra() && CI->hasUnsafeAlgebra()) {
  911. LibFunc Func;
  912. Function *OpCCallee = OpC->getCalledFunction();
  913. if (OpCCallee && TLI->getLibFunc(OpCCallee->getName(), Func) &&
  914. TLI->has(Func) && (Func == LibFunc_exp || Func == LibFunc_exp2)) {
  915. IRBuilder<>::FastMathFlagGuard Guard(B);
  916. B.setFastMathFlags(CI->getFastMathFlags());
  917. Value *FMul = B.CreateFMul(OpC->getArgOperand(0), Op2, "mul");
  918. return emitUnaryFloatFnCall(FMul, OpCCallee->getName(), B,
  919. OpCCallee->getAttributes());
  920. }
  921. }
  922. ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
  923. if (!Op2C)
  924. return Ret;
  925. if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
  926. return ConstantFP::get(CI->getType(), 1.0);
  927. if (Op2C->isExactlyValue(-0.5) &&
  928. hasUnaryFloatFn(TLI, Op2->getType(), LibFunc_sqrt, LibFunc_sqrtf,
  929. LibFunc_sqrtl)) {
  930. // If -ffast-math:
  931. // pow(x, -0.5) -> 1.0 / sqrt(x)
  932. if (CI->hasUnsafeAlgebra()) {
  933. IRBuilder<>::FastMathFlagGuard Guard(B);
  934. B.setFastMathFlags(CI->getFastMathFlags());
  935. // TODO: If the pow call is an intrinsic, we should lower to the sqrt
  936. // intrinsic, so we match errno semantics. We also should check that the
  937. // target can in fact lower the sqrt intrinsic -- we currently have no way
  938. // to ask this question other than asking whether the target has a sqrt
  939. // libcall, which is a sufficient but not necessary condition.
  940. Value *Sqrt = emitUnaryFloatFnCall(Op1, TLI->getName(LibFunc_sqrt), B,
  941. Callee->getAttributes());
  942. return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Sqrt, "sqrtrecip");
  943. }
  944. }
  945. if (Op2C->isExactlyValue(0.5) &&
  946. hasUnaryFloatFn(TLI, Op2->getType(), LibFunc_sqrt, LibFunc_sqrtf,
  947. LibFunc_sqrtl)) {
  948. // In -ffast-math, pow(x, 0.5) -> sqrt(x).
  949. if (CI->hasUnsafeAlgebra()) {
  950. IRBuilder<>::FastMathFlagGuard Guard(B);
  951. B.setFastMathFlags(CI->getFastMathFlags());
  952. // TODO: As above, we should lower to the sqrt intrinsic if the pow is an
  953. // intrinsic, to match errno semantics.
  954. return emitUnaryFloatFnCall(Op1, TLI->getName(LibFunc_sqrt), B,
  955. Callee->getAttributes());
  956. }
  957. // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
  958. // This is faster than calling pow, and still handles negative zero
  959. // and negative infinity correctly.
  960. // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
  961. Value *Inf = ConstantFP::getInfinity(CI->getType());
  962. Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
  963. // TODO: As above, we should lower to the sqrt intrinsic if the pow is an
  964. // intrinsic, to match errno semantics.
  965. Value *Sqrt = emitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
  966. Module *M = Callee->getParent();
  967. Function *FabsF = Intrinsic::getDeclaration(M, Intrinsic::fabs,
  968. CI->getType());
  969. Value *FAbs = B.CreateCall(FabsF, Sqrt);
  970. Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
  971. Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
  972. return Sel;
  973. }
  974. if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
  975. return Op1;
  976. if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
  977. return B.CreateFMul(Op1, Op1, "pow2");
  978. if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
  979. return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
  980. // In -ffast-math, generate repeated fmul instead of generating pow(x, n).
  981. if (CI->hasUnsafeAlgebra()) {
  982. APFloat V = abs(Op2C->getValueAPF());
  983. // We limit to a max of 7 fmul(s). Thus max exponent is 32.
  984. // This transformation applies to integer exponents only.
  985. if (V.compare(APFloat(V.getSemantics(), 32.0)) == APFloat::cmpGreaterThan ||
  986. !V.isInteger())
  987. return nullptr;
  988. // Propagate fast math flags.
  989. IRBuilder<>::FastMathFlagGuard Guard(B);
  990. B.setFastMathFlags(CI->getFastMathFlags());
  991. // We will memoize intermediate products of the Addition Chain.
  992. Value *InnerChain[33] = {nullptr};
  993. InnerChain[1] = Op1;
  994. InnerChain[2] = B.CreateFMul(Op1, Op1);
  995. // We cannot readily convert a non-double type (like float) to a double.
  996. // So we first convert V to something which could be converted to double.
  997. bool ignored;
  998. V.convert(APFloat::IEEEdouble(), APFloat::rmTowardZero, &ignored);
  999. Value *FMul = getPow(InnerChain, V.convertToDouble(), B);
  1000. // For negative exponents simply compute the reciprocal.
  1001. if (Op2C->isNegative())
  1002. FMul = B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), FMul);
  1003. return FMul;
  1004. }
  1005. return nullptr;
  1006. }
  1007. Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
  1008. Function *Callee = CI->getCalledFunction();
  1009. Value *Ret = nullptr;
  1010. StringRef Name = Callee->getName();
  1011. if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name))
  1012. Ret = optimizeUnaryDoubleFP(CI, B, true);
  1013. Value *Op = CI->getArgOperand(0);
  1014. // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
  1015. // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
  1016. LibFunc LdExp = LibFunc_ldexpl;
  1017. if (Op->getType()->isFloatTy())
  1018. LdExp = LibFunc_ldexpf;
  1019. else if (Op->getType()->isDoubleTy())
  1020. LdExp = LibFunc_ldexp;
  1021. if (TLI->has(LdExp)) {
  1022. Value *LdExpArg = nullptr;
  1023. if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
  1024. if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
  1025. LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
  1026. } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
  1027. if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
  1028. LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
  1029. }
  1030. if (LdExpArg) {
  1031. Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
  1032. if (!Op->getType()->isFloatTy())
  1033. One = ConstantExpr::getFPExtend(One, Op->getType());
  1034. Module *M = CI->getModule();
  1035. Value *NewCallee =
  1036. M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
  1037. Op->getType(), B.getInt32Ty());
  1038. CallInst *CI = B.CreateCall(NewCallee, {One, LdExpArg});
  1039. if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
  1040. CI->setCallingConv(F->getCallingConv());
  1041. return CI;
  1042. }
  1043. }
  1044. return Ret;
  1045. }
  1046. Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
  1047. Function *Callee = CI->getCalledFunction();
  1048. // If we can shrink the call to a float function rather than a double
  1049. // function, do that first.
  1050. StringRef Name = Callee->getName();
  1051. if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name))
  1052. if (Value *Ret = optimizeBinaryDoubleFP(CI, B))
  1053. return Ret;
  1054. IRBuilder<>::FastMathFlagGuard Guard(B);
  1055. FastMathFlags FMF;
  1056. if (CI->hasUnsafeAlgebra()) {
  1057. // Unsafe algebra sets all fast-math-flags to true.
  1058. FMF.setUnsafeAlgebra();
  1059. } else {
  1060. // At a minimum, no-nans-fp-math must be true.
  1061. if (!CI->hasNoNaNs())
  1062. return nullptr;
  1063. // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
  1064. // "Ideally, fmax would be sensitive to the sign of zero, for example
  1065. // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
  1066. // might be impractical."
  1067. FMF.setNoSignedZeros();
  1068. FMF.setNoNaNs();
  1069. }
  1070. B.setFastMathFlags(FMF);
  1071. // We have a relaxed floating-point environment. We can ignore NaN-handling
  1072. // and transform to a compare and select. We do not have to consider errno or
  1073. // exceptions, because fmin/fmax do not have those.
  1074. Value *Op0 = CI->getArgOperand(0);
  1075. Value *Op1 = CI->getArgOperand(1);
  1076. Value *Cmp = Callee->getName().startswith("fmin") ?
  1077. B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
  1078. return B.CreateSelect(Cmp, Op0, Op1);
  1079. }
  1080. Value *LibCallSimplifier::optimizeLog(CallInst *CI, IRBuilder<> &B) {
  1081. Function *Callee = CI->getCalledFunction();
  1082. Value *Ret = nullptr;
  1083. StringRef Name = Callee->getName();
  1084. if (UnsafeFPShrink && hasFloatVersion(Name))
  1085. Ret = optimizeUnaryDoubleFP(CI, B, true);
  1086. if (!CI->hasUnsafeAlgebra())
  1087. return Ret;
  1088. Value *Op1 = CI->getArgOperand(0);
  1089. auto *OpC = dyn_cast<CallInst>(Op1);
  1090. // The earlier call must also be unsafe in order to do these transforms.
  1091. if (!OpC || !OpC->hasUnsafeAlgebra())
  1092. return Ret;
  1093. // log(pow(x,y)) -> y*log(x)
  1094. // This is only applicable to log, log2, log10.
  1095. if (Name != "log" && Name != "log2" && Name != "log10")
  1096. return Ret;
  1097. IRBuilder<>::FastMathFlagGuard Guard(B);
  1098. FastMathFlags FMF;
  1099. FMF.setUnsafeAlgebra();
  1100. B.setFastMathFlags(FMF);
  1101. LibFunc Func;
  1102. Function *F = OpC->getCalledFunction();
  1103. if (F && ((TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
  1104. Func == LibFunc_pow) || F->getIntrinsicID() == Intrinsic::pow))
  1105. return B.CreateFMul(OpC->getArgOperand(1),
  1106. emitUnaryFloatFnCall(OpC->getOperand(0), Callee->getName(), B,
  1107. Callee->getAttributes()), "mul");
  1108. // log(exp2(y)) -> y*log(2)
  1109. if (F && Name == "log" && TLI->getLibFunc(F->getName(), Func) &&
  1110. TLI->has(Func) && Func == LibFunc_exp2)
  1111. return B.CreateFMul(
  1112. OpC->getArgOperand(0),
  1113. emitUnaryFloatFnCall(ConstantFP::get(CI->getType(), 2.0),
  1114. Callee->getName(), B, Callee->getAttributes()),
  1115. "logmul");
  1116. return Ret;
  1117. }
  1118. Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
  1119. Function *Callee = CI->getCalledFunction();
  1120. Value *Ret = nullptr;
  1121. // TODO: Once we have a way (other than checking for the existince of the
  1122. // libcall) to tell whether our target can lower @llvm.sqrt, relax the
  1123. // condition below.
  1124. if (TLI->has(LibFunc_sqrtf) && (Callee->getName() == "sqrt" ||
  1125. Callee->getIntrinsicID() == Intrinsic::sqrt))
  1126. Ret = optimizeUnaryDoubleFP(CI, B, true);
  1127. if (!CI->hasUnsafeAlgebra())
  1128. return Ret;
  1129. Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0));
  1130. if (!I || I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
  1131. return Ret;
  1132. // We're looking for a repeated factor in a multiplication tree,
  1133. // so we can do this fold: sqrt(x * x) -> fabs(x);
  1134. // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
  1135. Value *Op0 = I->getOperand(0);
  1136. Value *Op1 = I->getOperand(1);
  1137. Value *RepeatOp = nullptr;
  1138. Value *OtherOp = nullptr;
  1139. if (Op0 == Op1) {
  1140. // Simple match: the operands of the multiply are identical.
  1141. RepeatOp = Op0;
  1142. } else {
  1143. // Look for a more complicated pattern: one of the operands is itself
  1144. // a multiply, so search for a common factor in that multiply.
  1145. // Note: We don't bother looking any deeper than this first level or for
  1146. // variations of this pattern because instcombine's visitFMUL and/or the
  1147. // reassociation pass should give us this form.
  1148. Value *OtherMul0, *OtherMul1;
  1149. if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
  1150. // Pattern: sqrt((x * y) * z)
  1151. if (OtherMul0 == OtherMul1 &&
  1152. cast<Instruction>(Op0)->hasUnsafeAlgebra()) {
  1153. // Matched: sqrt((x * x) * z)
  1154. RepeatOp = OtherMul0;
  1155. OtherOp = Op1;
  1156. }
  1157. }
  1158. }
  1159. if (!RepeatOp)
  1160. return Ret;
  1161. // Fast math flags for any created instructions should match the sqrt
  1162. // and multiply.
  1163. IRBuilder<>::FastMathFlagGuard Guard(B);
  1164. B.setFastMathFlags(I->getFastMathFlags());
  1165. // If we found a repeated factor, hoist it out of the square root and
  1166. // replace it with the fabs of that factor.
  1167. Module *M = Callee->getParent();
  1168. Type *ArgType = I->getType();
  1169. Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
  1170. Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
  1171. if (OtherOp) {
  1172. // If we found a non-repeated factor, we still need to get its square
  1173. // root. We then multiply that by the value that was simplified out
  1174. // of the square root calculation.
  1175. Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
  1176. Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
  1177. return B.CreateFMul(FabsCall, SqrtCall);
  1178. }
  1179. return FabsCall;
  1180. }
  1181. // TODO: Generalize to handle any trig function and its inverse.
  1182. Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
  1183. Function *Callee = CI->getCalledFunction();
  1184. Value *Ret = nullptr;
  1185. StringRef Name = Callee->getName();
  1186. if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
  1187. Ret = optimizeUnaryDoubleFP(CI, B, true);
  1188. Value *Op1 = CI->getArgOperand(0);
  1189. auto *OpC = dyn_cast<CallInst>(Op1);
  1190. if (!OpC)
  1191. return Ret;
  1192. // Both calls must allow unsafe optimizations in order to remove them.
  1193. if (!CI->hasUnsafeAlgebra() || !OpC->hasUnsafeAlgebra())
  1194. return Ret;
  1195. // tan(atan(x)) -> x
  1196. // tanf(atanf(x)) -> x
  1197. // tanl(atanl(x)) -> x
  1198. LibFunc Func;
  1199. Function *F = OpC->getCalledFunction();
  1200. if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
  1201. ((Func == LibFunc_atan && Callee->getName() == "tan") ||
  1202. (Func == LibFunc_atanf && Callee->getName() == "tanf") ||
  1203. (Func == LibFunc_atanl && Callee->getName() == "tanl")))
  1204. Ret = OpC->getArgOperand(0);
  1205. return Ret;
  1206. }
  1207. static bool isTrigLibCall(CallInst *CI) {
  1208. // We can only hope to do anything useful if we can ignore things like errno
  1209. // and floating-point exceptions.
  1210. // We already checked the prototype.
  1211. return CI->hasFnAttr(Attribute::NoUnwind) &&
  1212. CI->hasFnAttr(Attribute::ReadNone);
  1213. }
  1214. static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
  1215. bool UseFloat, Value *&Sin, Value *&Cos,
  1216. Value *&SinCos) {
  1217. Type *ArgTy = Arg->getType();
  1218. Type *ResTy;
  1219. StringRef Name;
  1220. Triple T(OrigCallee->getParent()->getTargetTriple());
  1221. if (UseFloat) {
  1222. Name = "__sincospif_stret";
  1223. assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
  1224. // x86_64 can't use {float, float} since that would be returned in both
  1225. // xmm0 and xmm1, which isn't what a real struct would do.
  1226. ResTy = T.getArch() == Triple::x86_64
  1227. ? static_cast<Type *>(VectorType::get(ArgTy, 2))
  1228. : static_cast<Type *>(StructType::get(ArgTy, ArgTy));
  1229. } else {
  1230. Name = "__sincospi_stret";
  1231. ResTy = StructType::get(ArgTy, ArgTy);
  1232. }
  1233. Module *M = OrigCallee->getParent();
  1234. Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
  1235. ResTy, ArgTy);
  1236. if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
  1237. // If the argument is an instruction, it must dominate all uses so put our
  1238. // sincos call there.
  1239. B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
  1240. } else {
  1241. // Otherwise (e.g. for a constant) the beginning of the function is as
  1242. // good a place as any.
  1243. BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
  1244. B.SetInsertPoint(&EntryBB, EntryBB.begin());
  1245. }
  1246. SinCos = B.CreateCall(Callee, Arg, "sincospi");
  1247. if (SinCos->getType()->isStructTy()) {
  1248. Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
  1249. Cos = B.CreateExtractValue(SinCos, 1, "cospi");
  1250. } else {
  1251. Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
  1252. "sinpi");
  1253. Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
  1254. "cospi");
  1255. }
  1256. }
  1257. Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
  1258. // Make sure the prototype is as expected, otherwise the rest of the
  1259. // function is probably invalid and likely to abort.
  1260. if (!isTrigLibCall(CI))
  1261. return nullptr;
  1262. Value *Arg = CI->getArgOperand(0);
  1263. SmallVector<CallInst *, 1> SinCalls;
  1264. SmallVector<CallInst *, 1> CosCalls;
  1265. SmallVector<CallInst *, 1> SinCosCalls;
  1266. bool IsFloat = Arg->getType()->isFloatTy();
  1267. // Look for all compatible sinpi, cospi and sincospi calls with the same
  1268. // argument. If there are enough (in some sense) we can make the
  1269. // substitution.
  1270. Function *F = CI->getFunction();
  1271. for (User *U : Arg->users())
  1272. classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls);
  1273. // It's only worthwhile if both sinpi and cospi are actually used.
  1274. if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
  1275. return nullptr;
  1276. Value *Sin, *Cos, *SinCos;
  1277. insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
  1278. auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls,
  1279. Value *Res) {
  1280. for (CallInst *C : Calls)
  1281. replaceAllUsesWith(C, Res);
  1282. };
  1283. replaceTrigInsts(SinCalls, Sin);
  1284. replaceTrigInsts(CosCalls, Cos);
  1285. replaceTrigInsts(SinCosCalls, SinCos);
  1286. return nullptr;
  1287. }
  1288. void LibCallSimplifier::classifyArgUse(
  1289. Value *Val, Function *F, bool IsFloat,
  1290. SmallVectorImpl<CallInst *> &SinCalls,
  1291. SmallVectorImpl<CallInst *> &CosCalls,
  1292. SmallVectorImpl<CallInst *> &SinCosCalls) {
  1293. CallInst *CI = dyn_cast<CallInst>(Val);
  1294. if (!CI)
  1295. return;
  1296. // Don't consider calls in other functions.
  1297. if (CI->getFunction() != F)
  1298. return;
  1299. Function *Callee = CI->getCalledFunction();
  1300. LibFunc Func;
  1301. if (!Callee || !TLI->getLibFunc(*Callee, Func) || !TLI->has(Func) ||
  1302. !isTrigLibCall(CI))
  1303. return;
  1304. if (IsFloat) {
  1305. if (Func == LibFunc_sinpif)
  1306. SinCalls.push_back(CI);
  1307. else if (Func == LibFunc_cospif)
  1308. CosCalls.push_back(CI);
  1309. else if (Func == LibFunc_sincospif_stret)
  1310. SinCosCalls.push_back(CI);
  1311. } else {
  1312. if (Func == LibFunc_sinpi)
  1313. SinCalls.push_back(CI);
  1314. else if (Func == LibFunc_cospi)
  1315. CosCalls.push_back(CI);
  1316. else if (Func == LibFunc_sincospi_stret)
  1317. SinCosCalls.push_back(CI);
  1318. }
  1319. }
  1320. //===----------------------------------------------------------------------===//
  1321. // Integer Library Call Optimizations
  1322. //===----------------------------------------------------------------------===//
  1323. Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
  1324. // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
  1325. Value *Op = CI->getArgOperand(0);
  1326. Type *ArgType = Op->getType();
  1327. Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
  1328. Intrinsic::cttz, ArgType);
  1329. Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
  1330. V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
  1331. V = B.CreateIntCast(V, B.getInt32Ty(), false);
  1332. Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
  1333. return B.CreateSelect(Cond, V, B.getInt32(0));
  1334. }
  1335. Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilder<> &B) {
  1336. // fls(x) -> (i32)(sizeInBits(x) - llvm.ctlz(x, false))
  1337. Value *Op = CI->getArgOperand(0);
  1338. Type *ArgType = Op->getType();
  1339. Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
  1340. Intrinsic::ctlz, ArgType);
  1341. Value *V = B.CreateCall(F, {Op, B.getFalse()}, "ctlz");
  1342. V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()),
  1343. V);
  1344. return B.CreateIntCast(V, CI->getType(), false);
  1345. }
  1346. Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
  1347. // abs(x) -> x >s -1 ? x : -x
  1348. Value *Op = CI->getArgOperand(0);
  1349. Value *Pos =
  1350. B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
  1351. Value *Neg = B.CreateNeg(Op, "neg");
  1352. return B.CreateSelect(Pos, Op, Neg);
  1353. }
  1354. Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
  1355. // isdigit(c) -> (c-'0') <u 10
  1356. Value *Op = CI->getArgOperand(0);
  1357. Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
  1358. Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
  1359. return B.CreateZExt(Op, CI->getType());
  1360. }
  1361. Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
  1362. // isascii(c) -> c <u 128
  1363. Value *Op = CI->getArgOperand(0);
  1364. Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
  1365. return B.CreateZExt(Op, CI->getType());
  1366. }
  1367. Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
  1368. // toascii(c) -> c & 0x7f
  1369. return B.CreateAnd(CI->getArgOperand(0),
  1370. ConstantInt::get(CI->getType(), 0x7F));
  1371. }
  1372. //===----------------------------------------------------------------------===//
  1373. // Formatting and IO Library Call Optimizations
  1374. //===----------------------------------------------------------------------===//
  1375. static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
  1376. Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
  1377. int StreamArg) {
  1378. Function *Callee = CI->getCalledFunction();
  1379. // Error reporting calls should be cold, mark them as such.
  1380. // This applies even to non-builtin calls: it is only a hint and applies to
  1381. // functions that the frontend might not understand as builtins.
  1382. // This heuristic was suggested in:
  1383. // Improving Static Branch Prediction in a Compiler
  1384. // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
  1385. // Proceedings of PACT'98, Oct. 1998, IEEE
  1386. if (!CI->hasFnAttr(Attribute::Cold) &&
  1387. isReportingError(Callee, CI, StreamArg)) {
  1388. CI->addAttribute(AttributeList::FunctionIndex, Attribute::Cold);
  1389. }
  1390. return nullptr;
  1391. }
  1392. static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
  1393. if (!Callee || !Callee->isDeclaration())
  1394. return false;
  1395. if (StreamArg < 0)
  1396. return true;
  1397. // These functions might be considered cold, but only if their stream
  1398. // argument is stderr.
  1399. if (StreamArg >= (int)CI->getNumArgOperands())
  1400. return false;
  1401. LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
  1402. if (!LI)
  1403. return false;
  1404. GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
  1405. if (!GV || !GV->isDeclaration())
  1406. return false;
  1407. return GV->getName() == "stderr";
  1408. }
  1409. Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
  1410. // Check for a fixed format string.
  1411. StringRef FormatStr;
  1412. if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
  1413. return nullptr;
  1414. // Empty format string -> noop.
  1415. if (FormatStr.empty()) // Tolerate printf's declared void.
  1416. return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
  1417. // Do not do any of the following transformations if the printf return value
  1418. // is used, in general the printf return value is not compatible with either
  1419. // putchar() or puts().
  1420. if (!CI->use_empty())
  1421. return nullptr;
  1422. // printf("x") -> putchar('x'), even for "%" and "%%".
  1423. if (FormatStr.size() == 1 || FormatStr == "%%")
  1424. return emitPutChar(B.getInt32(FormatStr[0]), B, TLI);
  1425. // printf("%s", "a") --> putchar('a')
  1426. if (FormatStr == "%s" && CI->getNumArgOperands() > 1) {
  1427. StringRef ChrStr;
  1428. if (!getConstantStringInfo(CI->getOperand(1), ChrStr))
  1429. return nullptr;
  1430. if (ChrStr.size() != 1)
  1431. return nullptr;
  1432. return emitPutChar(B.getInt32(ChrStr[0]), B, TLI);
  1433. }
  1434. // printf("foo\n") --> puts("foo")
  1435. if (FormatStr[FormatStr.size() - 1] == '\n' &&
  1436. FormatStr.find('%') == StringRef::npos) { // No format characters.
  1437. // Create a string literal with no \n on it. We expect the constant merge
  1438. // pass to be run after this pass, to merge duplicate strings.
  1439. FormatStr = FormatStr.drop_back();
  1440. Value *GV = B.CreateGlobalString(FormatStr, "str");
  1441. return emitPutS(GV, B, TLI);
  1442. }
  1443. // Optimize specific format strings.
  1444. // printf("%c", chr) --> putchar(chr)
  1445. if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
  1446. CI->getArgOperand(1)->getType()->isIntegerTy())
  1447. return emitPutChar(CI->getArgOperand(1), B, TLI);
  1448. // printf("%s\n", str) --> puts(str)
  1449. if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
  1450. CI->getArgOperand(1)->getType()->isPointerTy())
  1451. return emitPutS(CI->getArgOperand(1), B, TLI);
  1452. return nullptr;
  1453. }
  1454. Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
  1455. Function *Callee = CI->getCalledFunction();
  1456. FunctionType *FT = Callee->getFunctionType();
  1457. if (Value *V = optimizePrintFString(CI, B)) {
  1458. return V;
  1459. }
  1460. // printf(format, ...) -> iprintf(format, ...) if no floating point
  1461. // arguments.
  1462. if (TLI->has(LibFunc_iprintf) && !callHasFloatingPointArgument(CI)) {
  1463. Module *M = B.GetInsertBlock()->getParent()->getParent();
  1464. Constant *IPrintFFn =
  1465. M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
  1466. CallInst *New = cast<CallInst>(CI->clone());
  1467. New->setCalledFunction(IPrintFFn);
  1468. B.Insert(New);
  1469. return New;
  1470. }
  1471. return nullptr;
  1472. }
  1473. Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
  1474. // Check for a fixed format string.
  1475. StringRef FormatStr;
  1476. if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
  1477. return nullptr;
  1478. // If we just have a format string (nothing else crazy) transform it.
  1479. if (CI->getNumArgOperands() == 2) {
  1480. // Make sure there's no % in the constant array. We could try to handle
  1481. // %% -> % in the future if we cared.
  1482. for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
  1483. if (FormatStr[i] == '%')
  1484. return nullptr; // we found a format specifier, bail out.
  1485. // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
  1486. B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
  1487. ConstantInt::get(DL.getIntPtrType(CI->getContext()),
  1488. FormatStr.size() + 1),
  1489. 1); // Copy the null byte.
  1490. return ConstantInt::get(CI->getType(), FormatStr.size());
  1491. }
  1492. // The remaining optimizations require the format string to be "%s" or "%c"
  1493. // and have an extra operand.
  1494. if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
  1495. CI->getNumArgOperands() < 3)
  1496. return nullptr;
  1497. // Decode the second character of the format string.
  1498. if (FormatStr[1] == 'c') {
  1499. // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
  1500. if (!CI->getArgOperand(2)->getType()->isIntegerTy())
  1501. return nullptr;
  1502. Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
  1503. Value *Ptr = castToCStr(CI->getArgOperand(0), B);
  1504. B.CreateStore(V, Ptr);
  1505. Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
  1506. B.CreateStore(B.getInt8(0), Ptr);
  1507. return ConstantInt::get(CI->getType(), 1);
  1508. }
  1509. if (FormatStr[1] == 's') {
  1510. // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
  1511. if (!CI->getArgOperand(2)->getType()->isPointerTy())
  1512. return nullptr;
  1513. Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI);
  1514. if (!Len)
  1515. return nullptr;
  1516. Value *IncLen =
  1517. B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
  1518. B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
  1519. // The sprintf result is the unincremented number of bytes in the string.
  1520. return B.CreateIntCast(Len, CI->getType(), false);
  1521. }
  1522. return nullptr;
  1523. }
  1524. Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
  1525. Function *Callee = CI->getCalledFunction();
  1526. FunctionType *FT = Callee->getFunctionType();
  1527. if (Value *V = optimizeSPrintFString(CI, B)) {
  1528. return V;
  1529. }
  1530. // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
  1531. // point arguments.
  1532. if (TLI->has(LibFunc_siprintf) && !callHasFloatingPointArgument(CI)) {
  1533. Module *M = B.GetInsertBlock()->getParent()->getParent();
  1534. Constant *SIPrintFFn =
  1535. M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
  1536. CallInst *New = cast<CallInst>(CI->clone());
  1537. New->setCalledFunction(SIPrintFFn);
  1538. B.Insert(New);
  1539. return New;
  1540. }
  1541. return nullptr;
  1542. }
  1543. Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
  1544. optimizeErrorReporting(CI, B, 0);
  1545. // All the optimizations depend on the format string.
  1546. StringRef FormatStr;
  1547. if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
  1548. return nullptr;
  1549. // Do not do any of the following transformations if the fprintf return
  1550. // value is used, in general the fprintf return value is not compatible
  1551. // with fwrite(), fputc() or fputs().
  1552. if (!CI->use_empty())
  1553. return nullptr;
  1554. // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
  1555. if (CI->getNumArgOperands() == 2) {
  1556. for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
  1557. if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
  1558. return nullptr; // We found a format specifier.
  1559. return emitFWrite(
  1560. CI->getArgOperand(1),
  1561. ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
  1562. CI->getArgOperand(0), B, DL, TLI);
  1563. }
  1564. // The remaining optimizations require the format string to be "%s" or "%c"
  1565. // and have an extra operand.
  1566. if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
  1567. CI->getNumArgOperands() < 3)
  1568. return nullptr;
  1569. // Decode the second character of the format string.
  1570. if (FormatStr[1] == 'c') {
  1571. // fprintf(F, "%c", chr) --> fputc(chr, F)
  1572. if (!CI->getArgOperand(2)->getType()->isIntegerTy())
  1573. return nullptr;
  1574. return emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
  1575. }
  1576. if (FormatStr[1] == 's') {
  1577. // fprintf(F, "%s", str) --> fputs(str, F)
  1578. if (!CI->getArgOperand(2)->getType()->isPointerTy())
  1579. return nullptr;
  1580. return emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
  1581. }
  1582. return nullptr;
  1583. }
  1584. Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
  1585. Function *Callee = CI->getCalledFunction();
  1586. FunctionType *FT = Callee->getFunctionType();
  1587. if (Value *V = optimizeFPrintFString(CI, B)) {
  1588. return V;
  1589. }
  1590. // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
  1591. // floating point arguments.
  1592. if (TLI->has(LibFunc_fiprintf) && !callHasFloatingPointArgument(CI)) {
  1593. Module *M = B.GetInsertBlock()->getParent()->getParent();
  1594. Constant *FIPrintFFn =
  1595. M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
  1596. CallInst *New = cast<CallInst>(CI->clone());
  1597. New->setCalledFunction(FIPrintFFn);
  1598. B.Insert(New);
  1599. return New;
  1600. }
  1601. return nullptr;
  1602. }
  1603. Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
  1604. optimizeErrorReporting(CI, B, 3);
  1605. // Get the element size and count.
  1606. ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
  1607. ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
  1608. if (!SizeC || !CountC)
  1609. return nullptr;
  1610. uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
  1611. // If this is writing zero records, remove the call (it's a noop).
  1612. if (Bytes == 0)
  1613. return ConstantInt::get(CI->getType(), 0);
  1614. // If this is writing one byte, turn it into fputc.
  1615. // This optimisation is only valid, if the return value is unused.
  1616. if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
  1617. Value *Char = B.CreateLoad(castToCStr(CI->getArgOperand(0), B), "char");
  1618. Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI);
  1619. return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
  1620. }
  1621. return nullptr;
  1622. }
  1623. Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
  1624. optimizeErrorReporting(CI, B, 1);
  1625. // Don't rewrite fputs to fwrite when optimising for size because fwrite
  1626. // requires more arguments and thus extra MOVs are required.
  1627. if (CI->getParent()->getParent()->optForSize())
  1628. return nullptr;
  1629. // We can't optimize if return value is used.
  1630. if (!CI->use_empty())
  1631. return nullptr;
  1632. // fputs(s,F) --> fwrite(s,1,strlen(s),F)
  1633. uint64_t Len = GetStringLength(CI->getArgOperand(0));
  1634. if (!Len)
  1635. return nullptr;
  1636. // Known to have no uses (see above).
  1637. return emitFWrite(
  1638. CI->getArgOperand(0),
  1639. ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
  1640. CI->getArgOperand(1), B, DL, TLI);
  1641. }
  1642. Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
  1643. // Check for a constant string.
  1644. StringRef Str;
  1645. if (!getConstantStringInfo(CI->getArgOperand(0), Str))
  1646. return nullptr;
  1647. if (Str.empty() && CI->use_empty()) {
  1648. // puts("") -> putchar('\n')
  1649. Value *Res = emitPutChar(B.getInt32('\n'), B, TLI);
  1650. if (CI->use_empty() || !Res)
  1651. return Res;
  1652. return B.CreateIntCast(Res, CI->getType(), true);
  1653. }
  1654. return nullptr;
  1655. }
  1656. bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
  1657. LibFunc Func;
  1658. SmallString<20> FloatFuncName = FuncName;
  1659. FloatFuncName += 'f';
  1660. if (TLI->getLibFunc(FloatFuncName, Func))
  1661. return TLI->has(Func);
  1662. return false;
  1663. }
  1664. Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
  1665. IRBuilder<> &Builder) {
  1666. LibFunc Func;
  1667. Function *Callee = CI->getCalledFunction();
  1668. // Check for string/memory library functions.
  1669. if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
  1670. // Make sure we never change the calling convention.
  1671. assert((ignoreCallingConv(Func) ||
  1672. isCallingConvCCompatible(CI)) &&
  1673. "Optimizing string/memory libcall would change the calling convention");
  1674. switch (Func) {
  1675. case LibFunc_strcat:
  1676. return optimizeStrCat(CI, Builder);
  1677. case LibFunc_strncat:
  1678. return optimizeStrNCat(CI, Builder);
  1679. case LibFunc_strchr:
  1680. return optimizeStrChr(CI, Builder);
  1681. case LibFunc_strrchr:
  1682. return optimizeStrRChr(CI, Builder);
  1683. case LibFunc_strcmp:
  1684. return optimizeStrCmp(CI, Builder);
  1685. case LibFunc_strncmp:
  1686. return optimizeStrNCmp(CI, Builder);
  1687. case LibFunc_strcpy:
  1688. return optimizeStrCpy(CI, Builder);
  1689. case LibFunc_stpcpy:
  1690. return optimizeStpCpy(CI, Builder);
  1691. case LibFunc_strncpy:
  1692. return optimizeStrNCpy(CI, Builder);
  1693. case LibFunc_strlen:
  1694. return optimizeStrLen(CI, Builder);
  1695. case LibFunc_strpbrk:
  1696. return optimizeStrPBrk(CI, Builder);
  1697. case LibFunc_strtol:
  1698. case LibFunc_strtod:
  1699. case LibFunc_strtof:
  1700. case LibFunc_strtoul:
  1701. case LibFunc_strtoll:
  1702. case LibFunc_strtold:
  1703. case LibFunc_strtoull:
  1704. return optimizeStrTo(CI, Builder);
  1705. case LibFunc_strspn:
  1706. return optimizeStrSpn(CI, Builder);
  1707. case LibFunc_strcspn:
  1708. return optimizeStrCSpn(CI, Builder);
  1709. case LibFunc_strstr:
  1710. return optimizeStrStr(CI, Builder);
  1711. case LibFunc_memchr:
  1712. return optimizeMemChr(CI, Builder);
  1713. case LibFunc_memcmp:
  1714. return optimizeMemCmp(CI, Builder);
  1715. case LibFunc_memcpy:
  1716. return optimizeMemCpy(CI, Builder);
  1717. case LibFunc_memmove:
  1718. return optimizeMemMove(CI, Builder);
  1719. case LibFunc_memset:
  1720. return optimizeMemSet(CI, Builder);
  1721. default:
  1722. break;
  1723. }
  1724. }
  1725. return nullptr;
  1726. }
  1727. Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
  1728. if (CI->isNoBuiltin())
  1729. return nullptr;
  1730. LibFunc Func;
  1731. Function *Callee = CI->getCalledFunction();
  1732. StringRef FuncName = Callee->getName();
  1733. SmallVector<OperandBundleDef, 2> OpBundles;
  1734. CI->getOperandBundlesAsDefs(OpBundles);
  1735. IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
  1736. bool isCallingConvC = isCallingConvCCompatible(CI);
  1737. // Command-line parameter overrides instruction attribute.
  1738. if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
  1739. UnsafeFPShrink = EnableUnsafeFPShrink;
  1740. else if (isa<FPMathOperator>(CI) && CI->hasUnsafeAlgebra())
  1741. UnsafeFPShrink = true;
  1742. // First, check for intrinsics.
  1743. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
  1744. if (!isCallingConvC)
  1745. return nullptr;
  1746. switch (II->getIntrinsicID()) {
  1747. case Intrinsic::pow:
  1748. return optimizePow(CI, Builder);
  1749. case Intrinsic::exp2:
  1750. return optimizeExp2(CI, Builder);
  1751. case Intrinsic::log:
  1752. return optimizeLog(CI, Builder);
  1753. case Intrinsic::sqrt:
  1754. return optimizeSqrt(CI, Builder);
  1755. // TODO: Use foldMallocMemset() with memset intrinsic.
  1756. default:
  1757. return nullptr;
  1758. }
  1759. }
  1760. // Also try to simplify calls to fortified library functions.
  1761. if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
  1762. // Try to further simplify the result.
  1763. CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
  1764. if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
  1765. // Use an IR Builder from SimplifiedCI if available instead of CI
  1766. // to guarantee we reach all uses we might replace later on.
  1767. IRBuilder<> TmpBuilder(SimplifiedCI);
  1768. if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
  1769. // If we were able to further simplify, remove the now redundant call.
  1770. SimplifiedCI->replaceAllUsesWith(V);
  1771. SimplifiedCI->eraseFromParent();
  1772. return V;
  1773. }
  1774. }
  1775. return SimplifiedFortifiedCI;
  1776. }
  1777. // Then check for known library functions.
  1778. if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
  1779. // We never change the calling convention.
  1780. if (!ignoreCallingConv(Func) && !isCallingConvC)
  1781. return nullptr;
  1782. if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
  1783. return V;
  1784. switch (Func) {
  1785. case LibFunc_cosf:
  1786. case LibFunc_cos:
  1787. case LibFunc_cosl:
  1788. return optimizeCos(CI, Builder);
  1789. case LibFunc_sinpif:
  1790. case LibFunc_sinpi:
  1791. case LibFunc_cospif:
  1792. case LibFunc_cospi:
  1793. return optimizeSinCosPi(CI, Builder);
  1794. case LibFunc_powf:
  1795. case LibFunc_pow:
  1796. case LibFunc_powl:
  1797. return optimizePow(CI, Builder);
  1798. case LibFunc_exp2l:
  1799. case LibFunc_exp2:
  1800. case LibFunc_exp2f:
  1801. return optimizeExp2(CI, Builder);
  1802. case LibFunc_fabsf:
  1803. case LibFunc_fabs:
  1804. case LibFunc_fabsl:
  1805. return replaceUnaryCall(CI, Builder, Intrinsic::fabs);
  1806. case LibFunc_sqrtf:
  1807. case LibFunc_sqrt:
  1808. case LibFunc_sqrtl:
  1809. return optimizeSqrt(CI, Builder);
  1810. case LibFunc_ffs:
  1811. case LibFunc_ffsl:
  1812. case LibFunc_ffsll:
  1813. return optimizeFFS(CI, Builder);
  1814. case LibFunc_fls:
  1815. case LibFunc_flsl:
  1816. case LibFunc_flsll:
  1817. return optimizeFls(CI, Builder);
  1818. case LibFunc_abs:
  1819. case LibFunc_labs:
  1820. case LibFunc_llabs:
  1821. return optimizeAbs(CI, Builder);
  1822. case LibFunc_isdigit:
  1823. return optimizeIsDigit(CI, Builder);
  1824. case LibFunc_isascii:
  1825. return optimizeIsAscii(CI, Builder);
  1826. case LibFunc_toascii:
  1827. return optimizeToAscii(CI, Builder);
  1828. case LibFunc_printf:
  1829. return optimizePrintF(CI, Builder);
  1830. case LibFunc_sprintf:
  1831. return optimizeSPrintF(CI, Builder);
  1832. case LibFunc_fprintf:
  1833. return optimizeFPrintF(CI, Builder);
  1834. case LibFunc_fwrite:
  1835. return optimizeFWrite(CI, Builder);
  1836. case LibFunc_fputs:
  1837. return optimizeFPuts(CI, Builder);
  1838. case LibFunc_log:
  1839. case LibFunc_log10:
  1840. case LibFunc_log1p:
  1841. case LibFunc_log2:
  1842. case LibFunc_logb:
  1843. return optimizeLog(CI, Builder);
  1844. case LibFunc_puts:
  1845. return optimizePuts(CI, Builder);
  1846. case LibFunc_tan:
  1847. case LibFunc_tanf:
  1848. case LibFunc_tanl:
  1849. return optimizeTan(CI, Builder);
  1850. case LibFunc_perror:
  1851. return optimizeErrorReporting(CI, Builder);
  1852. case LibFunc_vfprintf:
  1853. case LibFunc_fiprintf:
  1854. return optimizeErrorReporting(CI, Builder, 0);
  1855. case LibFunc_fputc:
  1856. return optimizeErrorReporting(CI, Builder, 1);
  1857. case LibFunc_ceil:
  1858. return replaceUnaryCall(CI, Builder, Intrinsic::ceil);
  1859. case LibFunc_floor:
  1860. return replaceUnaryCall(CI, Builder, Intrinsic::floor);
  1861. case LibFunc_round:
  1862. return replaceUnaryCall(CI, Builder, Intrinsic::round);
  1863. case LibFunc_nearbyint:
  1864. return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint);
  1865. case LibFunc_rint:
  1866. return replaceUnaryCall(CI, Builder, Intrinsic::rint);
  1867. case LibFunc_trunc:
  1868. return replaceUnaryCall(CI, Builder, Intrinsic::trunc);
  1869. case LibFunc_acos:
  1870. case LibFunc_acosh:
  1871. case LibFunc_asin:
  1872. case LibFunc_asinh:
  1873. case LibFunc_atan:
  1874. case LibFunc_atanh:
  1875. case LibFunc_cbrt:
  1876. case LibFunc_cosh:
  1877. case LibFunc_exp:
  1878. case LibFunc_exp10:
  1879. case LibFunc_expm1:
  1880. case LibFunc_sin:
  1881. case LibFunc_sinh:
  1882. case LibFunc_tanh:
  1883. if (UnsafeFPShrink && hasFloatVersion(FuncName))
  1884. return optimizeUnaryDoubleFP(CI, Builder, true);
  1885. return nullptr;
  1886. case LibFunc_copysign:
  1887. if (hasFloatVersion(FuncName))
  1888. return optimizeBinaryDoubleFP(CI, Builder);
  1889. return nullptr;
  1890. case LibFunc_fminf:
  1891. case LibFunc_fmin:
  1892. case LibFunc_fminl:
  1893. case LibFunc_fmaxf:
  1894. case LibFunc_fmax:
  1895. case LibFunc_fmaxl:
  1896. return optimizeFMinFMax(CI, Builder);
  1897. default:
  1898. return nullptr;
  1899. }
  1900. }
  1901. return nullptr;
  1902. }
  1903. LibCallSimplifier::LibCallSimplifier(
  1904. const DataLayout &DL, const TargetLibraryInfo *TLI,
  1905. function_ref<void(Instruction *, Value *)> Replacer)
  1906. : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), UnsafeFPShrink(false),
  1907. Replacer(Replacer) {}
  1908. void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
  1909. // Indirect through the replacer used in this instance.
  1910. Replacer(I, With);
  1911. }
  1912. // TODO:
  1913. // Additional cases that we need to add to this file:
  1914. //
  1915. // cbrt:
  1916. // * cbrt(expN(X)) -> expN(x/3)
  1917. // * cbrt(sqrt(x)) -> pow(x,1/6)
  1918. // * cbrt(cbrt(x)) -> pow(x,1/9)
  1919. //
  1920. // exp, expf, expl:
  1921. // * exp(log(x)) -> x
  1922. //
  1923. // log, logf, logl:
  1924. // * log(exp(x)) -> x
  1925. // * log(exp(y)) -> y*log(e)
  1926. // * log(exp10(y)) -> y*log(10)
  1927. // * log(sqrt(x)) -> 0.5*log(x)
  1928. //
  1929. // pow, powf, powl:
  1930. // * pow(sqrt(x),y) -> pow(x,y*0.5)
  1931. // * pow(pow(x,y),z)-> pow(x,y*z)
  1932. //
  1933. // signbit:
  1934. // * signbit(cnst) -> cnst'
  1935. // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
  1936. //
  1937. // sqrt, sqrtf, sqrtl:
  1938. // * sqrt(expN(x)) -> expN(x*0.5)
  1939. // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
  1940. // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
  1941. //
  1942. //===----------------------------------------------------------------------===//
  1943. // Fortified Library Call Optimizations
  1944. //===----------------------------------------------------------------------===//
  1945. bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
  1946. unsigned ObjSizeOp,
  1947. unsigned SizeOp,
  1948. bool isString) {
  1949. if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
  1950. return true;
  1951. if (ConstantInt *ObjSizeCI =
  1952. dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
  1953. if (ObjSizeCI->isAllOnesValue())
  1954. return true;
  1955. // If the object size wasn't -1 (unknown), bail out if we were asked to.
  1956. if (OnlyLowerUnknownSize)
  1957. return false;
  1958. if (isString) {
  1959. uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
  1960. // If the length is 0 we don't know how long it is and so we can't
  1961. // remove the check.
  1962. if (Len == 0)
  1963. return false;
  1964. return ObjSizeCI->getZExtValue() >= Len;
  1965. }
  1966. if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
  1967. return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
  1968. }
  1969. return false;
  1970. }
  1971. Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
  1972. IRBuilder<> &B) {
  1973. if (isFortifiedCallFoldable(CI, 3, 2, false)) {
  1974. B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
  1975. CI->getArgOperand(2), 1);
  1976. return CI->getArgOperand(0);
  1977. }
  1978. return nullptr;
  1979. }
  1980. Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
  1981. IRBuilder<> &B) {
  1982. if (isFortifiedCallFoldable(CI, 3, 2, false)) {
  1983. B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
  1984. CI->getArgOperand(2), 1);
  1985. return CI->getArgOperand(0);
  1986. }
  1987. return nullptr;
  1988. }
  1989. Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
  1990. IRBuilder<> &B) {
  1991. // TODO: Try foldMallocMemset() here.
  1992. if (isFortifiedCallFoldable(CI, 3, 2, false)) {
  1993. Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
  1994. B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
  1995. return CI->getArgOperand(0);
  1996. }
  1997. return nullptr;
  1998. }
  1999. Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
  2000. IRBuilder<> &B,
  2001. LibFunc Func) {
  2002. Function *Callee = CI->getCalledFunction();
  2003. StringRef Name = Callee->getName();
  2004. const DataLayout &DL = CI->getModule()->getDataLayout();
  2005. Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
  2006. *ObjSize = CI->getArgOperand(2);
  2007. // __stpcpy_chk(x,x,...) -> x+strlen(x)
  2008. if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
  2009. Value *StrLen = emitStrLen(Src, B, DL, TLI);
  2010. return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
  2011. }
  2012. // If a) we don't have any length information, or b) we know this will
  2013. // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
  2014. // st[rp]cpy_chk call which may fail at runtime if the size is too long.
  2015. // TODO: It might be nice to get a maximum length out of the possible
  2016. // string lengths for varying.
  2017. if (isFortifiedCallFoldable(CI, 2, 1, true))
  2018. return emitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
  2019. if (OnlyLowerUnknownSize)
  2020. return nullptr;
  2021. // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
  2022. uint64_t Len = GetStringLength(Src);
  2023. if (Len == 0)
  2024. return nullptr;
  2025. Type *SizeTTy = DL.getIntPtrType(CI->getContext());
  2026. Value *LenV = ConstantInt::get(SizeTTy, Len);
  2027. Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
  2028. // If the function was an __stpcpy_chk, and we were able to fold it into
  2029. // a __memcpy_chk, we still need to return the correct end pointer.
  2030. if (Ret && Func == LibFunc_stpcpy_chk)
  2031. return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
  2032. return Ret;
  2033. }
  2034. Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
  2035. IRBuilder<> &B,
  2036. LibFunc Func) {
  2037. Function *Callee = CI->getCalledFunction();
  2038. StringRef Name = Callee->getName();
  2039. if (isFortifiedCallFoldable(CI, 3, 2, false)) {
  2040. Value *Ret = emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
  2041. CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
  2042. return Ret;
  2043. }
  2044. return nullptr;
  2045. }
  2046. Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
  2047. // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
  2048. // Some clang users checked for _chk libcall availability using:
  2049. // __has_builtin(__builtin___memcpy_chk)
  2050. // When compiling with -fno-builtin, this is always true.
  2051. // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
  2052. // end up with fortified libcalls, which isn't acceptable in a freestanding
  2053. // environment which only provides their non-fortified counterparts.
  2054. //
  2055. // Until we change clang and/or teach external users to check for availability
  2056. // differently, disregard the "nobuiltin" attribute and TLI::has.
  2057. //
  2058. // PR23093.
  2059. LibFunc Func;
  2060. Function *Callee = CI->getCalledFunction();
  2061. SmallVector<OperandBundleDef, 2> OpBundles;
  2062. CI->getOperandBundlesAsDefs(OpBundles);
  2063. IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
  2064. bool isCallingConvC = isCallingConvCCompatible(CI);
  2065. // First, check that this is a known library functions and that the prototype
  2066. // is correct.
  2067. if (!TLI->getLibFunc(*Callee, Func))
  2068. return nullptr;
  2069. // We never change the calling convention.
  2070. if (!ignoreCallingConv(Func) && !isCallingConvC)
  2071. return nullptr;
  2072. switch (Func) {
  2073. case LibFunc_memcpy_chk:
  2074. return optimizeMemCpyChk(CI, Builder);
  2075. case LibFunc_memmove_chk:
  2076. return optimizeMemMoveChk(CI, Builder);
  2077. case LibFunc_memset_chk:
  2078. return optimizeMemSetChk(CI, Builder);
  2079. case LibFunc_stpcpy_chk:
  2080. case LibFunc_strcpy_chk:
  2081. return optimizeStrpCpyChk(CI, Builder, Func);
  2082. case LibFunc_stpncpy_chk:
  2083. case LibFunc_strncpy_chk:
  2084. return optimizeStrpNCpyChk(CI, Builder, Func);
  2085. default:
  2086. break;
  2087. }
  2088. return nullptr;
  2089. }
  2090. FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
  2091. const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
  2092. : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}