SimplifyLibCalls.cpp 83 KB

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