SimplifyLibCalls.cpp 127 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563
  1. //===------ SimplifyLibCalls.cpp - Library calls simplifier ---------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the library calls simplifier. It does not implement
  10. // any pass, but can't be used by other passes to do simplifications.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
  14. #include "llvm/ADT/APSInt.h"
  15. #include "llvm/ADT/SmallString.h"
  16. #include "llvm/ADT/StringMap.h"
  17. #include "llvm/ADT/Triple.h"
  18. #include "llvm/Analysis/BlockFrequencyInfo.h"
  19. #include "llvm/Analysis/ConstantFolding.h"
  20. #include "llvm/Analysis/OptimizationRemarkEmitter.h"
  21. #include "llvm/Analysis/ProfileSummaryInfo.h"
  22. #include "llvm/Transforms/Utils/Local.h"
  23. #include "llvm/Analysis/ValueTracking.h"
  24. #include "llvm/Analysis/CaptureTracking.h"
  25. #include "llvm/Analysis/Loads.h"
  26. #include "llvm/IR/DataLayout.h"
  27. #include "llvm/IR/Function.h"
  28. #include "llvm/IR/IRBuilder.h"
  29. #include "llvm/IR/IntrinsicInst.h"
  30. #include "llvm/IR/Intrinsics.h"
  31. #include "llvm/IR/LLVMContext.h"
  32. #include "llvm/IR/Module.h"
  33. #include "llvm/IR/PatternMatch.h"
  34. #include "llvm/Support/CommandLine.h"
  35. #include "llvm/Support/KnownBits.h"
  36. #include "llvm/Support/MathExtras.h"
  37. #include "llvm/Transforms/Utils/BuildLibCalls.h"
  38. #include "llvm/Transforms/Utils/SizeOpts.h"
  39. using namespace llvm;
  40. using namespace PatternMatch;
  41. static cl::opt<bool>
  42. EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
  43. cl::init(false),
  44. cl::desc("Enable unsafe double to float "
  45. "shrinking for math lib calls"));
  46. //===----------------------------------------------------------------------===//
  47. // Helper Functions
  48. //===----------------------------------------------------------------------===//
  49. static bool ignoreCallingConv(LibFunc Func) {
  50. return Func == LibFunc_abs || Func == LibFunc_labs ||
  51. Func == LibFunc_llabs || Func == LibFunc_strlen;
  52. }
  53. /// Return true if it is only used in equality comparisons with With.
  54. static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
  55. for (User *U : V->users()) {
  56. if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
  57. if (IC->isEquality() && IC->getOperand(1) == With)
  58. continue;
  59. // Unknown instruction.
  60. return false;
  61. }
  62. return true;
  63. }
  64. static bool callHasFloatingPointArgument(const CallInst *CI) {
  65. return any_of(CI->operands(), [](const Use &OI) {
  66. return OI->getType()->isFloatingPointTy();
  67. });
  68. }
  69. static bool callHasFP128Argument(const CallInst *CI) {
  70. return any_of(CI->operands(), [](const Use &OI) {
  71. return OI->getType()->isFP128Ty();
  72. });
  73. }
  74. static Value *convertStrToNumber(CallInst *CI, StringRef &Str, int64_t Base) {
  75. if (Base < 2 || Base > 36)
  76. // handle special zero base
  77. if (Base != 0)
  78. return nullptr;
  79. char *End;
  80. std::string nptr = Str.str();
  81. errno = 0;
  82. long long int Result = strtoll(nptr.c_str(), &End, Base);
  83. if (errno)
  84. return nullptr;
  85. // if we assume all possible target locales are ASCII supersets,
  86. // then if strtoll successfully parses a number on the host,
  87. // it will also successfully parse the same way on the target
  88. if (*End != '\0')
  89. return nullptr;
  90. if (!isIntN(CI->getType()->getPrimitiveSizeInBits(), Result))
  91. return nullptr;
  92. return ConstantInt::get(CI->getType(), Result);
  93. }
  94. static bool isOnlyUsedInComparisonWithZero(Value *V) {
  95. for (User *U : V->users()) {
  96. if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
  97. if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
  98. if (C->isNullValue())
  99. continue;
  100. // Unknown instruction.
  101. return false;
  102. }
  103. return true;
  104. }
  105. static bool canTransformToMemCmp(CallInst *CI, Value *Str, uint64_t Len,
  106. const DataLayout &DL) {
  107. if (!isOnlyUsedInComparisonWithZero(CI))
  108. return false;
  109. if (!isDereferenceableAndAlignedPointer(Str, Align(1), APInt(64, Len), DL))
  110. return false;
  111. if (CI->getFunction()->hasFnAttribute(Attribute::SanitizeMemory))
  112. return false;
  113. return true;
  114. }
  115. static void annotateDereferenceableBytes(CallInst *CI,
  116. ArrayRef<unsigned> ArgNos,
  117. uint64_t DereferenceableBytes) {
  118. const Function *F = CI->getCaller();
  119. if (!F)
  120. return;
  121. for (unsigned ArgNo : ArgNos) {
  122. uint64_t DerefBytes = DereferenceableBytes;
  123. unsigned AS = CI->getArgOperand(ArgNo)->getType()->getPointerAddressSpace();
  124. if (!llvm::NullPointerIsDefined(F, AS) ||
  125. CI->paramHasAttr(ArgNo, Attribute::NonNull))
  126. DerefBytes = std::max(CI->getParamDereferenceableOrNullBytes(ArgNo),
  127. DereferenceableBytes);
  128. if (CI->getParamDereferenceableBytes(ArgNo) < DerefBytes) {
  129. CI->removeParamAttr(ArgNo, Attribute::Dereferenceable);
  130. if (!llvm::NullPointerIsDefined(F, AS) ||
  131. CI->paramHasAttr(ArgNo, Attribute::NonNull))
  132. CI->removeParamAttr(ArgNo, Attribute::DereferenceableOrNull);
  133. CI->addParamAttr(ArgNo, Attribute::getWithDereferenceableBytes(
  134. CI->getContext(), DerefBytes));
  135. }
  136. }
  137. }
  138. static void annotateNonNullNoUndefBasedOnAccess(CallInst *CI,
  139. ArrayRef<unsigned> ArgNos) {
  140. Function *F = CI->getCaller();
  141. if (!F)
  142. return;
  143. for (unsigned ArgNo : ArgNos) {
  144. if (!CI->paramHasAttr(ArgNo, Attribute::NoUndef))
  145. CI->addParamAttr(ArgNo, Attribute::NoUndef);
  146. if (CI->paramHasAttr(ArgNo, Attribute::NonNull))
  147. continue;
  148. unsigned AS = CI->getArgOperand(ArgNo)->getType()->getPointerAddressSpace();
  149. if (llvm::NullPointerIsDefined(F, AS))
  150. continue;
  151. CI->addParamAttr(ArgNo, Attribute::NonNull);
  152. annotateDereferenceableBytes(CI, ArgNo, 1);
  153. }
  154. }
  155. static void annotateNonNullAndDereferenceable(CallInst *CI, ArrayRef<unsigned> ArgNos,
  156. Value *Size, const DataLayout &DL) {
  157. if (ConstantInt *LenC = dyn_cast<ConstantInt>(Size)) {
  158. annotateNonNullNoUndefBasedOnAccess(CI, ArgNos);
  159. annotateDereferenceableBytes(CI, ArgNos, LenC->getZExtValue());
  160. } else if (isKnownNonZero(Size, DL)) {
  161. annotateNonNullNoUndefBasedOnAccess(CI, ArgNos);
  162. const APInt *X, *Y;
  163. uint64_t DerefMin = 1;
  164. if (match(Size, m_Select(m_Value(), m_APInt(X), m_APInt(Y)))) {
  165. DerefMin = std::min(X->getZExtValue(), Y->getZExtValue());
  166. annotateDereferenceableBytes(CI, ArgNos, DerefMin);
  167. }
  168. }
  169. }
  170. // Copy CallInst "flags" like musttail, notail, and tail. Return New param for
  171. // easier chaining. Calls to emit* and B.createCall should probably be wrapped
  172. // in this function when New is created to replace Old. Callers should take
  173. // care to check Old.isMustTailCall() if they aren't replacing Old directly
  174. // with New.
  175. static Value *copyFlags(const CallInst &Old, Value *New) {
  176. assert(!Old.isMustTailCall() && "do not copy musttail call flags");
  177. assert(!Old.isNoTailCall() && "do not copy notail call flags");
  178. if (auto *NewCI = dyn_cast_or_null<CallInst>(New))
  179. NewCI->setTailCallKind(Old.getTailCallKind());
  180. return New;
  181. }
  182. //===----------------------------------------------------------------------===//
  183. // String and Memory Library Call Optimizations
  184. //===----------------------------------------------------------------------===//
  185. Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilderBase &B) {
  186. // Extract some information from the instruction
  187. Value *Dst = CI->getArgOperand(0);
  188. Value *Src = CI->getArgOperand(1);
  189. annotateNonNullNoUndefBasedOnAccess(CI, {0, 1});
  190. // See if we can get the length of the input string.
  191. uint64_t Len = GetStringLength(Src);
  192. if (Len)
  193. annotateDereferenceableBytes(CI, 1, Len);
  194. else
  195. return nullptr;
  196. --Len; // Unbias length.
  197. // Handle the simple, do-nothing case: strcat(x, "") -> x
  198. if (Len == 0)
  199. return Dst;
  200. return copyFlags(*CI, emitStrLenMemCpy(Src, Dst, Len, B));
  201. }
  202. Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
  203. IRBuilderBase &B) {
  204. // We need to find the end of the destination string. That's where the
  205. // memory is to be moved to. We just generate a call to strlen.
  206. Value *DstLen = emitStrLen(Dst, B, DL, TLI);
  207. if (!DstLen)
  208. return nullptr;
  209. // Now that we have the destination's length, we must index into the
  210. // destination's pointer to get the actual memcpy destination (end of
  211. // the string .. we're concatenating).
  212. Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
  213. // We have enough information to now generate the memcpy call to do the
  214. // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
  215. B.CreateMemCpy(
  216. CpyDst, Align(1), Src, Align(1),
  217. ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1));
  218. return Dst;
  219. }
  220. Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilderBase &B) {
  221. // Extract some information from the instruction.
  222. Value *Dst = CI->getArgOperand(0);
  223. Value *Src = CI->getArgOperand(1);
  224. Value *Size = CI->getArgOperand(2);
  225. uint64_t Len;
  226. annotateNonNullNoUndefBasedOnAccess(CI, 0);
  227. if (isKnownNonZero(Size, DL))
  228. annotateNonNullNoUndefBasedOnAccess(CI, 1);
  229. // We don't do anything if length is not constant.
  230. ConstantInt *LengthArg = dyn_cast<ConstantInt>(Size);
  231. if (LengthArg) {
  232. Len = LengthArg->getZExtValue();
  233. // strncat(x, c, 0) -> x
  234. if (!Len)
  235. return Dst;
  236. } else {
  237. return nullptr;
  238. }
  239. // See if we can get the length of the input string.
  240. uint64_t SrcLen = GetStringLength(Src);
  241. if (SrcLen) {
  242. annotateDereferenceableBytes(CI, 1, SrcLen);
  243. --SrcLen; // Unbias length.
  244. } else {
  245. return nullptr;
  246. }
  247. // strncat(x, "", c) -> x
  248. if (SrcLen == 0)
  249. return Dst;
  250. // We don't optimize this case.
  251. if (Len < SrcLen)
  252. return nullptr;
  253. // strncat(x, s, c) -> strcat(x, s)
  254. // s is constant so the strcat can be optimized further.
  255. return copyFlags(*CI, emitStrLenMemCpy(Src, Dst, SrcLen, B));
  256. }
  257. Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilderBase &B) {
  258. Function *Callee = CI->getCalledFunction();
  259. FunctionType *FT = Callee->getFunctionType();
  260. Value *SrcStr = CI->getArgOperand(0);
  261. annotateNonNullNoUndefBasedOnAccess(CI, 0);
  262. // If the second operand is non-constant, see if we can compute the length
  263. // of the input string and turn this into memchr.
  264. ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
  265. if (!CharC) {
  266. uint64_t Len = GetStringLength(SrcStr);
  267. if (Len)
  268. annotateDereferenceableBytes(CI, 0, Len);
  269. else
  270. return nullptr;
  271. if (!FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
  272. return nullptr;
  273. return copyFlags(
  274. *CI,
  275. emitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
  276. ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), B,
  277. DL, TLI));
  278. }
  279. // Otherwise, the character is a constant, see if the first argument is
  280. // a string literal. If so, we can constant fold.
  281. StringRef Str;
  282. if (!getConstantStringInfo(SrcStr, Str)) {
  283. if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
  284. if (Value *StrLen = emitStrLen(SrcStr, B, DL, TLI))
  285. return B.CreateGEP(B.getInt8Ty(), SrcStr, StrLen, "strchr");
  286. return nullptr;
  287. }
  288. // Compute the offset, make sure to handle the case when we're searching for
  289. // zero (a weird way to spell strlen).
  290. size_t I = (0xFF & CharC->getSExtValue()) == 0
  291. ? Str.size()
  292. : Str.find(CharC->getSExtValue());
  293. if (I == StringRef::npos) // Didn't find the char. strchr returns null.
  294. return Constant::getNullValue(CI->getType());
  295. // strchr(s+n,c) -> gep(s+n+i,c)
  296. return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
  297. }
  298. Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilderBase &B) {
  299. Value *SrcStr = CI->getArgOperand(0);
  300. ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
  301. annotateNonNullNoUndefBasedOnAccess(CI, 0);
  302. // Cannot fold anything if we're not looking for a constant.
  303. if (!CharC)
  304. return nullptr;
  305. StringRef Str;
  306. if (!getConstantStringInfo(SrcStr, Str)) {
  307. // strrchr(s, 0) -> strchr(s, 0)
  308. if (CharC->isZero())
  309. return copyFlags(*CI, emitStrChr(SrcStr, '\0', B, TLI));
  310. return nullptr;
  311. }
  312. // Compute the offset.
  313. size_t I = (0xFF & CharC->getSExtValue()) == 0
  314. ? Str.size()
  315. : Str.rfind(CharC->getSExtValue());
  316. if (I == StringRef::npos) // Didn't find the char. Return null.
  317. return Constant::getNullValue(CI->getType());
  318. // strrchr(s+n,c) -> gep(s+n+i,c)
  319. return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
  320. }
  321. Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilderBase &B) {
  322. Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
  323. if (Str1P == Str2P) // strcmp(x,x) -> 0
  324. return ConstantInt::get(CI->getType(), 0);
  325. StringRef Str1, Str2;
  326. bool HasStr1 = getConstantStringInfo(Str1P, Str1);
  327. bool HasStr2 = getConstantStringInfo(Str2P, Str2);
  328. // strcmp(x, y) -> cnst (if both x and y are constant strings)
  329. if (HasStr1 && HasStr2)
  330. return ConstantInt::get(CI->getType(), Str1.compare(Str2));
  331. if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
  332. return B.CreateNeg(B.CreateZExt(
  333. B.CreateLoad(B.getInt8Ty(), Str2P, "strcmpload"), CI->getType()));
  334. if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
  335. return B.CreateZExt(B.CreateLoad(B.getInt8Ty(), Str1P, "strcmpload"),
  336. CI->getType());
  337. // strcmp(P, "x") -> memcmp(P, "x", 2)
  338. uint64_t Len1 = GetStringLength(Str1P);
  339. if (Len1)
  340. annotateDereferenceableBytes(CI, 0, Len1);
  341. uint64_t Len2 = GetStringLength(Str2P);
  342. if (Len2)
  343. annotateDereferenceableBytes(CI, 1, Len2);
  344. if (Len1 && Len2) {
  345. return copyFlags(
  346. *CI, emitMemCmp(Str1P, Str2P,
  347. ConstantInt::get(DL.getIntPtrType(CI->getContext()),
  348. std::min(Len1, Len2)),
  349. B, DL, TLI));
  350. }
  351. // strcmp to memcmp
  352. if (!HasStr1 && HasStr2) {
  353. if (canTransformToMemCmp(CI, Str1P, Len2, DL))
  354. return copyFlags(
  355. *CI,
  356. emitMemCmp(Str1P, Str2P,
  357. ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len2),
  358. B, DL, TLI));
  359. } else if (HasStr1 && !HasStr2) {
  360. if (canTransformToMemCmp(CI, Str2P, Len1, DL))
  361. return copyFlags(
  362. *CI,
  363. emitMemCmp(Str1P, Str2P,
  364. ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len1),
  365. B, DL, TLI));
  366. }
  367. annotateNonNullNoUndefBasedOnAccess(CI, {0, 1});
  368. return nullptr;
  369. }
  370. Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilderBase &B) {
  371. Value *Str1P = CI->getArgOperand(0);
  372. Value *Str2P = CI->getArgOperand(1);
  373. Value *Size = CI->getArgOperand(2);
  374. if (Str1P == Str2P) // strncmp(x,x,n) -> 0
  375. return ConstantInt::get(CI->getType(), 0);
  376. if (isKnownNonZero(Size, DL))
  377. annotateNonNullNoUndefBasedOnAccess(CI, {0, 1});
  378. // Get the length argument if it is constant.
  379. uint64_t Length;
  380. if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(Size))
  381. Length = LengthArg->getZExtValue();
  382. else
  383. return nullptr;
  384. if (Length == 0) // strncmp(x,y,0) -> 0
  385. return ConstantInt::get(CI->getType(), 0);
  386. if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
  387. return copyFlags(*CI, emitMemCmp(Str1P, Str2P, Size, B, DL, TLI));
  388. StringRef Str1, Str2;
  389. bool HasStr1 = getConstantStringInfo(Str1P, Str1);
  390. bool HasStr2 = getConstantStringInfo(Str2P, Str2);
  391. // strncmp(x, y) -> cnst (if both x and y are constant strings)
  392. if (HasStr1 && HasStr2) {
  393. StringRef SubStr1 = Str1.substr(0, Length);
  394. StringRef SubStr2 = Str2.substr(0, Length);
  395. return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
  396. }
  397. if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
  398. return B.CreateNeg(B.CreateZExt(
  399. B.CreateLoad(B.getInt8Ty(), Str2P, "strcmpload"), CI->getType()));
  400. if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
  401. return B.CreateZExt(B.CreateLoad(B.getInt8Ty(), Str1P, "strcmpload"),
  402. CI->getType());
  403. uint64_t Len1 = GetStringLength(Str1P);
  404. if (Len1)
  405. annotateDereferenceableBytes(CI, 0, Len1);
  406. uint64_t Len2 = GetStringLength(Str2P);
  407. if (Len2)
  408. annotateDereferenceableBytes(CI, 1, Len2);
  409. // strncmp to memcmp
  410. if (!HasStr1 && HasStr2) {
  411. Len2 = std::min(Len2, Length);
  412. if (canTransformToMemCmp(CI, Str1P, Len2, DL))
  413. return copyFlags(
  414. *CI,
  415. emitMemCmp(Str1P, Str2P,
  416. ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len2),
  417. B, DL, TLI));
  418. } else if (HasStr1 && !HasStr2) {
  419. Len1 = std::min(Len1, Length);
  420. if (canTransformToMemCmp(CI, Str2P, Len1, DL))
  421. return copyFlags(
  422. *CI,
  423. emitMemCmp(Str1P, Str2P,
  424. ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len1),
  425. B, DL, TLI));
  426. }
  427. return nullptr;
  428. }
  429. Value *LibCallSimplifier::optimizeStrNDup(CallInst *CI, IRBuilderBase &B) {
  430. Value *Src = CI->getArgOperand(0);
  431. ConstantInt *Size = dyn_cast<ConstantInt>(CI->getArgOperand(1));
  432. uint64_t SrcLen = GetStringLength(Src);
  433. if (SrcLen && Size) {
  434. annotateDereferenceableBytes(CI, 0, SrcLen);
  435. if (SrcLen <= Size->getZExtValue() + 1)
  436. return copyFlags(*CI, emitStrDup(Src, B, TLI));
  437. }
  438. return nullptr;
  439. }
  440. Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilderBase &B) {
  441. Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
  442. if (Dst == Src) // strcpy(x,x) -> x
  443. return Src;
  444. annotateNonNullNoUndefBasedOnAccess(CI, {0, 1});
  445. // See if we can get the length of the input string.
  446. uint64_t Len = GetStringLength(Src);
  447. if (Len)
  448. annotateDereferenceableBytes(CI, 1, Len);
  449. else
  450. return nullptr;
  451. // We have enough information to now generate the memcpy call to do the
  452. // copy for us. Make a memcpy to copy the nul byte with align = 1.
  453. CallInst *NewCI =
  454. B.CreateMemCpy(Dst, Align(1), Src, Align(1),
  455. ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len));
  456. NewCI->setAttributes(CI->getAttributes());
  457. NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(NewCI->getType()));
  458. copyFlags(*CI, NewCI);
  459. return Dst;
  460. }
  461. Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilderBase &B) {
  462. Function *Callee = CI->getCalledFunction();
  463. Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
  464. // stpcpy(d,s) -> strcpy(d,s) if the result is not used.
  465. if (CI->use_empty())
  466. return copyFlags(*CI, emitStrCpy(Dst, Src, B, TLI));
  467. if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
  468. Value *StrLen = emitStrLen(Src, B, DL, TLI);
  469. return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
  470. }
  471. // See if we can get the length of the input string.
  472. uint64_t Len = GetStringLength(Src);
  473. if (Len)
  474. annotateDereferenceableBytes(CI, 1, Len);
  475. else
  476. return nullptr;
  477. Type *PT = Callee->getFunctionType()->getParamType(0);
  478. Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
  479. Value *DstEnd = B.CreateGEP(B.getInt8Ty(), Dst,
  480. ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
  481. // We have enough information to now generate the memcpy call to do the
  482. // copy for us. Make a memcpy to copy the nul byte with align = 1.
  483. CallInst *NewCI = B.CreateMemCpy(Dst, Align(1), Src, Align(1), LenV);
  484. NewCI->setAttributes(CI->getAttributes());
  485. NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(NewCI->getType()));
  486. copyFlags(*CI, NewCI);
  487. return DstEnd;
  488. }
  489. Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilderBase &B) {
  490. Function *Callee = CI->getCalledFunction();
  491. Value *Dst = CI->getArgOperand(0);
  492. Value *Src = CI->getArgOperand(1);
  493. Value *Size = CI->getArgOperand(2);
  494. annotateNonNullNoUndefBasedOnAccess(CI, 0);
  495. if (isKnownNonZero(Size, DL))
  496. annotateNonNullNoUndefBasedOnAccess(CI, 1);
  497. uint64_t Len;
  498. if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(Size))
  499. Len = LengthArg->getZExtValue();
  500. else
  501. return nullptr;
  502. // strncpy(x, y, 0) -> x
  503. if (Len == 0)
  504. return Dst;
  505. // See if we can get the length of the input string.
  506. uint64_t SrcLen = GetStringLength(Src);
  507. if (SrcLen) {
  508. annotateDereferenceableBytes(CI, 1, SrcLen);
  509. --SrcLen; // Unbias length.
  510. } else {
  511. return nullptr;
  512. }
  513. if (SrcLen == 0) {
  514. // strncpy(x, "", y) -> memset(x, '\0', y)
  515. Align MemSetAlign =
  516. CI->getAttributes().getParamAttrs(0).getAlignment().valueOrOne();
  517. CallInst *NewCI = B.CreateMemSet(Dst, B.getInt8('\0'), Size, MemSetAlign);
  518. AttrBuilder ArgAttrs(CI->getContext(), CI->getAttributes().getParamAttrs(0));
  519. NewCI->setAttributes(NewCI->getAttributes().addParamAttributes(
  520. CI->getContext(), 0, ArgAttrs));
  521. copyFlags(*CI, NewCI);
  522. return Dst;
  523. }
  524. // strncpy(a, "a", 4) - > memcpy(a, "a\0\0\0", 4)
  525. if (Len > SrcLen + 1) {
  526. if (Len <= 128) {
  527. StringRef Str;
  528. if (!getConstantStringInfo(Src, Str))
  529. return nullptr;
  530. std::string SrcStr = Str.str();
  531. SrcStr.resize(Len, '\0');
  532. Src = B.CreateGlobalString(SrcStr, "str");
  533. } else {
  534. return nullptr;
  535. }
  536. }
  537. Type *PT = Callee->getFunctionType()->getParamType(0);
  538. // strncpy(x, s, c) -> memcpy(align 1 x, align 1 s, c) [s and c are constant]
  539. CallInst *NewCI = B.CreateMemCpy(Dst, Align(1), Src, Align(1),
  540. ConstantInt::get(DL.getIntPtrType(PT), Len));
  541. NewCI->setAttributes(CI->getAttributes());
  542. NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(NewCI->getType()));
  543. copyFlags(*CI, NewCI);
  544. return Dst;
  545. }
  546. Value *LibCallSimplifier::optimizeStringLength(CallInst *CI, IRBuilderBase &B,
  547. unsigned CharSize) {
  548. Value *Src = CI->getArgOperand(0);
  549. // Constant folding: strlen("xyz") -> 3
  550. if (uint64_t Len = GetStringLength(Src, CharSize))
  551. return ConstantInt::get(CI->getType(), Len - 1);
  552. // If s is a constant pointer pointing to a string literal, we can fold
  553. // strlen(s + x) to strlen(s) - x, when x is known to be in the range
  554. // [0, strlen(s)] or the string has a single null terminator '\0' at the end.
  555. // We only try to simplify strlen when the pointer s points to an array
  556. // of i8. Otherwise, we would need to scale the offset x before doing the
  557. // subtraction. This will make the optimization more complex, and it's not
  558. // very useful because calling strlen for a pointer of other types is
  559. // very uncommon.
  560. if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) {
  561. if (!isGEPBasedOnPointerToString(GEP, CharSize))
  562. return nullptr;
  563. ConstantDataArraySlice Slice;
  564. if (getConstantDataArrayInfo(GEP->getOperand(0), Slice, CharSize)) {
  565. uint64_t NullTermIdx;
  566. if (Slice.Array == nullptr) {
  567. NullTermIdx = 0;
  568. } else {
  569. NullTermIdx = ~((uint64_t)0);
  570. for (uint64_t I = 0, E = Slice.Length; I < E; ++I) {
  571. if (Slice.Array->getElementAsInteger(I + Slice.Offset) == 0) {
  572. NullTermIdx = I;
  573. break;
  574. }
  575. }
  576. // If the string does not have '\0', leave it to strlen to compute
  577. // its length.
  578. if (NullTermIdx == ~((uint64_t)0))
  579. return nullptr;
  580. }
  581. Value *Offset = GEP->getOperand(2);
  582. KnownBits Known = computeKnownBits(Offset, DL, 0, nullptr, CI, nullptr);
  583. Known.Zero.flipAllBits();
  584. uint64_t ArrSize =
  585. cast<ArrayType>(GEP->getSourceElementType())->getNumElements();
  586. // KnownZero's bits are flipped, so zeros in KnownZero now represent
  587. // bits known to be zeros in Offset, and ones in KnowZero represent
  588. // bits unknown in Offset. Therefore, Offset is known to be in range
  589. // [0, NullTermIdx] when the flipped KnownZero is non-negative and
  590. // unsigned-less-than NullTermIdx.
  591. //
  592. // If Offset is not provably in the range [0, NullTermIdx], we can still
  593. // optimize if we can prove that the program has undefined behavior when
  594. // Offset is outside that range. That is the case when GEP->getOperand(0)
  595. // is a pointer to an object whose memory extent is NullTermIdx+1.
  596. if ((Known.Zero.isNonNegative() && Known.Zero.ule(NullTermIdx)) ||
  597. (GEP->isInBounds() && isa<GlobalVariable>(GEP->getOperand(0)) &&
  598. NullTermIdx == ArrSize - 1)) {
  599. Offset = B.CreateSExtOrTrunc(Offset, CI->getType());
  600. return B.CreateSub(ConstantInt::get(CI->getType(), NullTermIdx),
  601. Offset);
  602. }
  603. }
  604. }
  605. // strlen(x?"foo":"bars") --> x ? 3 : 4
  606. if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
  607. uint64_t LenTrue = GetStringLength(SI->getTrueValue(), CharSize);
  608. uint64_t LenFalse = GetStringLength(SI->getFalseValue(), CharSize);
  609. if (LenTrue && LenFalse) {
  610. ORE.emit([&]() {
  611. return OptimizationRemark("instcombine", "simplify-libcalls", CI)
  612. << "folded strlen(select) to select of constants";
  613. });
  614. return B.CreateSelect(SI->getCondition(),
  615. ConstantInt::get(CI->getType(), LenTrue - 1),
  616. ConstantInt::get(CI->getType(), LenFalse - 1));
  617. }
  618. }
  619. // strlen(x) != 0 --> *x != 0
  620. // strlen(x) == 0 --> *x == 0
  621. if (isOnlyUsedInZeroEqualityComparison(CI))
  622. return B.CreateZExt(B.CreateLoad(B.getIntNTy(CharSize), Src, "strlenfirst"),
  623. CI->getType());
  624. return nullptr;
  625. }
  626. Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilderBase &B) {
  627. if (Value *V = optimizeStringLength(CI, B, 8))
  628. return V;
  629. annotateNonNullNoUndefBasedOnAccess(CI, 0);
  630. return nullptr;
  631. }
  632. Value *LibCallSimplifier::optimizeWcslen(CallInst *CI, IRBuilderBase &B) {
  633. Module &M = *CI->getModule();
  634. unsigned WCharSize = TLI->getWCharSize(M) * 8;
  635. // We cannot perform this optimization without wchar_size metadata.
  636. if (WCharSize == 0)
  637. return nullptr;
  638. return optimizeStringLength(CI, B, WCharSize);
  639. }
  640. Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilderBase &B) {
  641. StringRef S1, S2;
  642. bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
  643. bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
  644. // strpbrk(s, "") -> nullptr
  645. // strpbrk("", s) -> nullptr
  646. if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
  647. return Constant::getNullValue(CI->getType());
  648. // Constant folding.
  649. if (HasS1 && HasS2) {
  650. size_t I = S1.find_first_of(S2);
  651. if (I == StringRef::npos) // No match.
  652. return Constant::getNullValue(CI->getType());
  653. return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I),
  654. "strpbrk");
  655. }
  656. // strpbrk(s, "a") -> strchr(s, 'a')
  657. if (HasS2 && S2.size() == 1)
  658. return copyFlags(*CI, emitStrChr(CI->getArgOperand(0), S2[0], B, TLI));
  659. return nullptr;
  660. }
  661. Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilderBase &B) {
  662. Value *EndPtr = CI->getArgOperand(1);
  663. if (isa<ConstantPointerNull>(EndPtr)) {
  664. // With a null EndPtr, this function won't capture the main argument.
  665. // It would be readonly too, except that it still may write to errno.
  666. CI->addParamAttr(0, Attribute::NoCapture);
  667. }
  668. return nullptr;
  669. }
  670. Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilderBase &B) {
  671. StringRef S1, S2;
  672. bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
  673. bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
  674. // strspn(s, "") -> 0
  675. // strspn("", s) -> 0
  676. if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
  677. return Constant::getNullValue(CI->getType());
  678. // Constant folding.
  679. if (HasS1 && HasS2) {
  680. size_t Pos = S1.find_first_not_of(S2);
  681. if (Pos == StringRef::npos)
  682. Pos = S1.size();
  683. return ConstantInt::get(CI->getType(), Pos);
  684. }
  685. return nullptr;
  686. }
  687. Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilderBase &B) {
  688. StringRef S1, S2;
  689. bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
  690. bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
  691. // strcspn("", s) -> 0
  692. if (HasS1 && S1.empty())
  693. return Constant::getNullValue(CI->getType());
  694. // Constant folding.
  695. if (HasS1 && HasS2) {
  696. size_t Pos = S1.find_first_of(S2);
  697. if (Pos == StringRef::npos)
  698. Pos = S1.size();
  699. return ConstantInt::get(CI->getType(), Pos);
  700. }
  701. // strcspn(s, "") -> strlen(s)
  702. if (HasS2 && S2.empty())
  703. return copyFlags(*CI, emitStrLen(CI->getArgOperand(0), B, DL, TLI));
  704. return nullptr;
  705. }
  706. Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilderBase &B) {
  707. // fold strstr(x, x) -> x.
  708. if (CI->getArgOperand(0) == CI->getArgOperand(1))
  709. return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
  710. // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
  711. if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
  712. Value *StrLen = emitStrLen(CI->getArgOperand(1), B, DL, TLI);
  713. if (!StrLen)
  714. return nullptr;
  715. Value *StrNCmp = emitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
  716. StrLen, B, DL, TLI);
  717. if (!StrNCmp)
  718. return nullptr;
  719. for (User *U : llvm::make_early_inc_range(CI->users())) {
  720. ICmpInst *Old = cast<ICmpInst>(U);
  721. Value *Cmp =
  722. B.CreateICmp(Old->getPredicate(), StrNCmp,
  723. ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
  724. replaceAllUsesWith(Old, Cmp);
  725. }
  726. return CI;
  727. }
  728. // See if either input string is a constant string.
  729. StringRef SearchStr, ToFindStr;
  730. bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
  731. bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
  732. // fold strstr(x, "") -> x.
  733. if (HasStr2 && ToFindStr.empty())
  734. return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
  735. // If both strings are known, constant fold it.
  736. if (HasStr1 && HasStr2) {
  737. size_t Offset = SearchStr.find(ToFindStr);
  738. if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
  739. return Constant::getNullValue(CI->getType());
  740. // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
  741. Value *Result = castToCStr(CI->getArgOperand(0), B);
  742. Result =
  743. B.CreateConstInBoundsGEP1_64(B.getInt8Ty(), Result, Offset, "strstr");
  744. return B.CreateBitCast(Result, CI->getType());
  745. }
  746. // fold strstr(x, "y") -> strchr(x, 'y').
  747. if (HasStr2 && ToFindStr.size() == 1) {
  748. Value *StrChr = emitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
  749. return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
  750. }
  751. annotateNonNullNoUndefBasedOnAccess(CI, {0, 1});
  752. return nullptr;
  753. }
  754. Value *LibCallSimplifier::optimizeMemRChr(CallInst *CI, IRBuilderBase &B) {
  755. if (isKnownNonZero(CI->getOperand(2), DL))
  756. annotateNonNullNoUndefBasedOnAccess(CI, 0);
  757. return nullptr;
  758. }
  759. Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilderBase &B) {
  760. Value *SrcStr = CI->getArgOperand(0);
  761. Value *Size = CI->getArgOperand(2);
  762. annotateNonNullAndDereferenceable(CI, 0, Size, DL);
  763. ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
  764. ConstantInt *LenC = dyn_cast<ConstantInt>(Size);
  765. // memchr(x, y, 0) -> null
  766. if (LenC) {
  767. if (LenC->isZero())
  768. return Constant::getNullValue(CI->getType());
  769. } else {
  770. // From now on we need at least constant length and string.
  771. return nullptr;
  772. }
  773. StringRef Str;
  774. if (!getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
  775. return nullptr;
  776. // Truncate the string to LenC. If Str is smaller than LenC we will still only
  777. // scan the string, as reading past the end of it is undefined and we can just
  778. // return null if we don't find the char.
  779. Str = Str.substr(0, LenC->getZExtValue());
  780. // If the char is variable but the input str and length are not we can turn
  781. // this memchr call into a simple bit field test. Of course this only works
  782. // when the return value is only checked against null.
  783. //
  784. // It would be really nice to reuse switch lowering here but we can't change
  785. // the CFG at this point.
  786. //
  787. // memchr("\r\n", C, 2) != nullptr -> (1 << C & ((1 << '\r') | (1 << '\n')))
  788. // != 0
  789. // after bounds check.
  790. if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
  791. unsigned char Max =
  792. *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
  793. reinterpret_cast<const unsigned char *>(Str.end()));
  794. // Make sure the bit field we're about to create fits in a register on the
  795. // target.
  796. // FIXME: On a 64 bit architecture this prevents us from using the
  797. // interesting range of alpha ascii chars. We could do better by emitting
  798. // two bitfields or shifting the range by 64 if no lower chars are used.
  799. if (!DL.fitsInLegalInteger(Max + 1))
  800. return nullptr;
  801. // For the bit field use a power-of-2 type with at least 8 bits to avoid
  802. // creating unnecessary illegal types.
  803. unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
  804. // Now build the bit field.
  805. APInt Bitfield(Width, 0);
  806. for (char C : Str)
  807. Bitfield.setBit((unsigned char)C);
  808. Value *BitfieldC = B.getInt(Bitfield);
  809. // Adjust width of "C" to the bitfield width, then mask off the high bits.
  810. Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
  811. C = B.CreateAnd(C, B.getIntN(Width, 0xFF));
  812. // First check that the bit field access is within bounds.
  813. Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
  814. "memchr.bounds");
  815. // Create code that checks if the given bit is set in the field.
  816. Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
  817. Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
  818. // Finally merge both checks and cast to pointer type. The inttoptr
  819. // implicitly zexts the i1 to intptr type.
  820. return B.CreateIntToPtr(B.CreateLogicalAnd(Bounds, Bits, "memchr"),
  821. CI->getType());
  822. }
  823. // Check if all arguments are constants. If so, we can constant fold.
  824. if (!CharC)
  825. return nullptr;
  826. // Compute the offset.
  827. size_t I = Str.find(CharC->getSExtValue() & 0xFF);
  828. if (I == StringRef::npos) // Didn't find the char. memchr returns null.
  829. return Constant::getNullValue(CI->getType());
  830. // memchr(s+n,c,l) -> gep(s+n+i,c)
  831. return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
  832. }
  833. static Value *optimizeMemCmpConstantSize(CallInst *CI, Value *LHS, Value *RHS,
  834. uint64_t Len, IRBuilderBase &B,
  835. const DataLayout &DL) {
  836. if (Len == 0) // memcmp(s1,s2,0) -> 0
  837. return Constant::getNullValue(CI->getType());
  838. // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
  839. if (Len == 1) {
  840. Value *LHSV =
  841. B.CreateZExt(B.CreateLoad(B.getInt8Ty(), castToCStr(LHS, B), "lhsc"),
  842. CI->getType(), "lhsv");
  843. Value *RHSV =
  844. B.CreateZExt(B.CreateLoad(B.getInt8Ty(), castToCStr(RHS, B), "rhsc"),
  845. CI->getType(), "rhsv");
  846. return B.CreateSub(LHSV, RHSV, "chardiff");
  847. }
  848. // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
  849. // TODO: The case where both inputs are constants does not need to be limited
  850. // to legal integers or equality comparison. See block below this.
  851. if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
  852. IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
  853. unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
  854. // First, see if we can fold either argument to a constant.
  855. Value *LHSV = nullptr;
  856. if (auto *LHSC = dyn_cast<Constant>(LHS)) {
  857. LHSC = ConstantExpr::getBitCast(LHSC, IntType->getPointerTo());
  858. LHSV = ConstantFoldLoadFromConstPtr(LHSC, IntType, DL);
  859. }
  860. Value *RHSV = nullptr;
  861. if (auto *RHSC = dyn_cast<Constant>(RHS)) {
  862. RHSC = ConstantExpr::getBitCast(RHSC, IntType->getPointerTo());
  863. RHSV = ConstantFoldLoadFromConstPtr(RHSC, IntType, DL);
  864. }
  865. // Don't generate unaligned loads. If either source is constant data,
  866. // alignment doesn't matter for that source because there is no load.
  867. if ((LHSV || getKnownAlignment(LHS, DL, CI) >= PrefAlignment) &&
  868. (RHSV || getKnownAlignment(RHS, DL, CI) >= PrefAlignment)) {
  869. if (!LHSV) {
  870. Type *LHSPtrTy =
  871. IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
  872. LHSV = B.CreateLoad(IntType, B.CreateBitCast(LHS, LHSPtrTy), "lhsv");
  873. }
  874. if (!RHSV) {
  875. Type *RHSPtrTy =
  876. IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
  877. RHSV = B.CreateLoad(IntType, B.CreateBitCast(RHS, RHSPtrTy), "rhsv");
  878. }
  879. return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
  880. }
  881. }
  882. // Constant folding: memcmp(x, y, Len) -> constant (all arguments are const).
  883. // TODO: This is limited to i8 arrays.
  884. StringRef LHSStr, RHSStr;
  885. if (getConstantStringInfo(LHS, LHSStr) &&
  886. getConstantStringInfo(RHS, RHSStr)) {
  887. // Make sure we're not reading out-of-bounds memory.
  888. if (Len > LHSStr.size() || Len > RHSStr.size())
  889. return nullptr;
  890. // Fold the memcmp and normalize the result. This way we get consistent
  891. // results across multiple platforms.
  892. uint64_t Ret = 0;
  893. int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
  894. if (Cmp < 0)
  895. Ret = -1;
  896. else if (Cmp > 0)
  897. Ret = 1;
  898. return ConstantInt::get(CI->getType(), Ret);
  899. }
  900. return nullptr;
  901. }
  902. // Most simplifications for memcmp also apply to bcmp.
  903. Value *LibCallSimplifier::optimizeMemCmpBCmpCommon(CallInst *CI,
  904. IRBuilderBase &B) {
  905. Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
  906. Value *Size = CI->getArgOperand(2);
  907. if (LHS == RHS) // memcmp(s,s,x) -> 0
  908. return Constant::getNullValue(CI->getType());
  909. annotateNonNullAndDereferenceable(CI, {0, 1}, Size, DL);
  910. // Handle constant lengths.
  911. ConstantInt *LenC = dyn_cast<ConstantInt>(Size);
  912. if (!LenC)
  913. return nullptr;
  914. // memcmp(d,s,0) -> 0
  915. if (LenC->getZExtValue() == 0)
  916. return Constant::getNullValue(CI->getType());
  917. if (Value *Res =
  918. optimizeMemCmpConstantSize(CI, LHS, RHS, LenC->getZExtValue(), B, DL))
  919. return Res;
  920. return nullptr;
  921. }
  922. Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilderBase &B) {
  923. if (Value *V = optimizeMemCmpBCmpCommon(CI, B))
  924. return V;
  925. // memcmp(x, y, Len) == 0 -> bcmp(x, y, Len) == 0
  926. // bcmp can be more efficient than memcmp because it only has to know that
  927. // there is a difference, not how different one is to the other.
  928. if (TLI->has(LibFunc_bcmp) && isOnlyUsedInZeroEqualityComparison(CI)) {
  929. Value *LHS = CI->getArgOperand(0);
  930. Value *RHS = CI->getArgOperand(1);
  931. Value *Size = CI->getArgOperand(2);
  932. return copyFlags(*CI, emitBCmp(LHS, RHS, Size, B, DL, TLI));
  933. }
  934. return nullptr;
  935. }
  936. Value *LibCallSimplifier::optimizeBCmp(CallInst *CI, IRBuilderBase &B) {
  937. return optimizeMemCmpBCmpCommon(CI, B);
  938. }
  939. Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilderBase &B) {
  940. Value *Size = CI->getArgOperand(2);
  941. annotateNonNullAndDereferenceable(CI, {0, 1}, Size, DL);
  942. if (isa<IntrinsicInst>(CI))
  943. return nullptr;
  944. // memcpy(x, y, n) -> llvm.memcpy(align 1 x, align 1 y, n)
  945. CallInst *NewCI = B.CreateMemCpy(CI->getArgOperand(0), Align(1),
  946. CI->getArgOperand(1), Align(1), Size);
  947. NewCI->setAttributes(CI->getAttributes());
  948. NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(NewCI->getType()));
  949. copyFlags(*CI, NewCI);
  950. return CI->getArgOperand(0);
  951. }
  952. Value *LibCallSimplifier::optimizeMemCCpy(CallInst *CI, IRBuilderBase &B) {
  953. Value *Dst = CI->getArgOperand(0);
  954. Value *Src = CI->getArgOperand(1);
  955. ConstantInt *StopChar = dyn_cast<ConstantInt>(CI->getArgOperand(2));
  956. ConstantInt *N = dyn_cast<ConstantInt>(CI->getArgOperand(3));
  957. StringRef SrcStr;
  958. if (CI->use_empty() && Dst == Src)
  959. return Dst;
  960. // memccpy(d, s, c, 0) -> nullptr
  961. if (N) {
  962. if (N->isNullValue())
  963. return Constant::getNullValue(CI->getType());
  964. if (!getConstantStringInfo(Src, SrcStr, /*Offset=*/0,
  965. /*TrimAtNul=*/false) ||
  966. !StopChar)
  967. return nullptr;
  968. } else {
  969. return nullptr;
  970. }
  971. // Wrap arg 'c' of type int to char
  972. size_t Pos = SrcStr.find(StopChar->getSExtValue() & 0xFF);
  973. if (Pos == StringRef::npos) {
  974. if (N->getZExtValue() <= SrcStr.size()) {
  975. copyFlags(*CI, B.CreateMemCpy(Dst, Align(1), Src, Align(1),
  976. CI->getArgOperand(3)));
  977. return Constant::getNullValue(CI->getType());
  978. }
  979. return nullptr;
  980. }
  981. Value *NewN =
  982. ConstantInt::get(N->getType(), std::min(uint64_t(Pos + 1), N->getZExtValue()));
  983. // memccpy -> llvm.memcpy
  984. copyFlags(*CI, B.CreateMemCpy(Dst, Align(1), Src, Align(1), NewN));
  985. return Pos + 1 <= N->getZExtValue()
  986. ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, NewN)
  987. : Constant::getNullValue(CI->getType());
  988. }
  989. Value *LibCallSimplifier::optimizeMemPCpy(CallInst *CI, IRBuilderBase &B) {
  990. Value *Dst = CI->getArgOperand(0);
  991. Value *N = CI->getArgOperand(2);
  992. // mempcpy(x, y, n) -> llvm.memcpy(align 1 x, align 1 y, n), x + n
  993. CallInst *NewCI =
  994. B.CreateMemCpy(Dst, Align(1), CI->getArgOperand(1), Align(1), N);
  995. // Propagate attributes, but memcpy has no return value, so make sure that
  996. // any return attributes are compliant.
  997. // TODO: Attach return value attributes to the 1st operand to preserve them?
  998. NewCI->setAttributes(CI->getAttributes());
  999. NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(NewCI->getType()));
  1000. copyFlags(*CI, NewCI);
  1001. return B.CreateInBoundsGEP(B.getInt8Ty(), Dst, N);
  1002. }
  1003. Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilderBase &B) {
  1004. Value *Size = CI->getArgOperand(2);
  1005. annotateNonNullAndDereferenceable(CI, {0, 1}, Size, DL);
  1006. if (isa<IntrinsicInst>(CI))
  1007. return nullptr;
  1008. // memmove(x, y, n) -> llvm.memmove(align 1 x, align 1 y, n)
  1009. CallInst *NewCI = B.CreateMemMove(CI->getArgOperand(0), Align(1),
  1010. CI->getArgOperand(1), Align(1), Size);
  1011. NewCI->setAttributes(CI->getAttributes());
  1012. NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(NewCI->getType()));
  1013. copyFlags(*CI, NewCI);
  1014. return CI->getArgOperand(0);
  1015. }
  1016. Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilderBase &B) {
  1017. Value *Size = CI->getArgOperand(2);
  1018. annotateNonNullAndDereferenceable(CI, 0, Size, DL);
  1019. if (isa<IntrinsicInst>(CI))
  1020. return nullptr;
  1021. // memset(p, v, n) -> llvm.memset(align 1 p, v, n)
  1022. Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
  1023. CallInst *NewCI = B.CreateMemSet(CI->getArgOperand(0), Val, Size, Align(1));
  1024. NewCI->setAttributes(CI->getAttributes());
  1025. NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(NewCI->getType()));
  1026. copyFlags(*CI, NewCI);
  1027. return CI->getArgOperand(0);
  1028. }
  1029. Value *LibCallSimplifier::optimizeRealloc(CallInst *CI, IRBuilderBase &B) {
  1030. if (isa<ConstantPointerNull>(CI->getArgOperand(0)))
  1031. return copyFlags(*CI, emitMalloc(CI->getArgOperand(1), B, DL, TLI));
  1032. return nullptr;
  1033. }
  1034. //===----------------------------------------------------------------------===//
  1035. // Math Library Optimizations
  1036. //===----------------------------------------------------------------------===//
  1037. // Replace a libcall \p CI with a call to intrinsic \p IID
  1038. static Value *replaceUnaryCall(CallInst *CI, IRBuilderBase &B,
  1039. Intrinsic::ID IID) {
  1040. // Propagate fast-math flags from the existing call to the new call.
  1041. IRBuilderBase::FastMathFlagGuard Guard(B);
  1042. B.setFastMathFlags(CI->getFastMathFlags());
  1043. Module *M = CI->getModule();
  1044. Value *V = CI->getArgOperand(0);
  1045. Function *F = Intrinsic::getDeclaration(M, IID, CI->getType());
  1046. CallInst *NewCall = B.CreateCall(F, V);
  1047. NewCall->takeName(CI);
  1048. return copyFlags(*CI, NewCall);
  1049. }
  1050. /// Return a variant of Val with float type.
  1051. /// Currently this works in two cases: If Val is an FPExtension of a float
  1052. /// value to something bigger, simply return the operand.
  1053. /// If Val is a ConstantFP but can be converted to a float ConstantFP without
  1054. /// loss of precision do so.
  1055. static Value *valueHasFloatPrecision(Value *Val) {
  1056. if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
  1057. Value *Op = Cast->getOperand(0);
  1058. if (Op->getType()->isFloatTy())
  1059. return Op;
  1060. }
  1061. if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
  1062. APFloat F = Const->getValueAPF();
  1063. bool losesInfo;
  1064. (void)F.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
  1065. &losesInfo);
  1066. if (!losesInfo)
  1067. return ConstantFP::get(Const->getContext(), F);
  1068. }
  1069. return nullptr;
  1070. }
  1071. /// Shrink double -> float functions.
  1072. static Value *optimizeDoubleFP(CallInst *CI, IRBuilderBase &B,
  1073. bool isBinary, bool isPrecise = false) {
  1074. Function *CalleeFn = CI->getCalledFunction();
  1075. if (!CI->getType()->isDoubleTy() || !CalleeFn)
  1076. return nullptr;
  1077. // If not all the uses of the function are converted to float, then bail out.
  1078. // This matters if the precision of the result is more important than the
  1079. // precision of the arguments.
  1080. if (isPrecise)
  1081. for (User *U : CI->users()) {
  1082. FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
  1083. if (!Cast || !Cast->getType()->isFloatTy())
  1084. return nullptr;
  1085. }
  1086. // If this is something like 'g((double) float)', convert to 'gf(float)'.
  1087. Value *V[2];
  1088. V[0] = valueHasFloatPrecision(CI->getArgOperand(0));
  1089. V[1] = isBinary ? valueHasFloatPrecision(CI->getArgOperand(1)) : nullptr;
  1090. if (!V[0] || (isBinary && !V[1]))
  1091. return nullptr;
  1092. // If call isn't an intrinsic, check that it isn't within a function with the
  1093. // same name as the float version of this call, otherwise the result is an
  1094. // infinite loop. For example, from MinGW-w64:
  1095. //
  1096. // float expf(float val) { return (float) exp((double) val); }
  1097. StringRef CalleeName = CalleeFn->getName();
  1098. bool IsIntrinsic = CalleeFn->isIntrinsic();
  1099. if (!IsIntrinsic) {
  1100. StringRef CallerName = CI->getFunction()->getName();
  1101. if (!CallerName.empty() && CallerName.back() == 'f' &&
  1102. CallerName.size() == (CalleeName.size() + 1) &&
  1103. CallerName.startswith(CalleeName))
  1104. return nullptr;
  1105. }
  1106. // Propagate the math semantics from the current function to the new function.
  1107. IRBuilderBase::FastMathFlagGuard Guard(B);
  1108. B.setFastMathFlags(CI->getFastMathFlags());
  1109. // g((double) float) -> (double) gf(float)
  1110. Value *R;
  1111. if (IsIntrinsic) {
  1112. Module *M = CI->getModule();
  1113. Intrinsic::ID IID = CalleeFn->getIntrinsicID();
  1114. Function *Fn = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
  1115. R = isBinary ? B.CreateCall(Fn, V) : B.CreateCall(Fn, V[0]);
  1116. } else {
  1117. AttributeList CalleeAttrs = CalleeFn->getAttributes();
  1118. R = isBinary ? emitBinaryFloatFnCall(V[0], V[1], CalleeName, B, CalleeAttrs)
  1119. : emitUnaryFloatFnCall(V[0], CalleeName, B, CalleeAttrs);
  1120. }
  1121. return B.CreateFPExt(R, B.getDoubleTy());
  1122. }
  1123. /// Shrink double -> float for unary functions.
  1124. static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilderBase &B,
  1125. bool isPrecise = false) {
  1126. return optimizeDoubleFP(CI, B, false, isPrecise);
  1127. }
  1128. /// Shrink double -> float for binary functions.
  1129. static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilderBase &B,
  1130. bool isPrecise = false) {
  1131. return optimizeDoubleFP(CI, B, true, isPrecise);
  1132. }
  1133. // cabs(z) -> sqrt((creal(z)*creal(z)) + (cimag(z)*cimag(z)))
  1134. Value *LibCallSimplifier::optimizeCAbs(CallInst *CI, IRBuilderBase &B) {
  1135. if (!CI->isFast())
  1136. return nullptr;
  1137. // Propagate fast-math flags from the existing call to new instructions.
  1138. IRBuilderBase::FastMathFlagGuard Guard(B);
  1139. B.setFastMathFlags(CI->getFastMathFlags());
  1140. Value *Real, *Imag;
  1141. if (CI->arg_size() == 1) {
  1142. Value *Op = CI->getArgOperand(0);
  1143. assert(Op->getType()->isArrayTy() && "Unexpected signature for cabs!");
  1144. Real = B.CreateExtractValue(Op, 0, "real");
  1145. Imag = B.CreateExtractValue(Op, 1, "imag");
  1146. } else {
  1147. assert(CI->arg_size() == 2 && "Unexpected signature for cabs!");
  1148. Real = CI->getArgOperand(0);
  1149. Imag = CI->getArgOperand(1);
  1150. }
  1151. Value *RealReal = B.CreateFMul(Real, Real);
  1152. Value *ImagImag = B.CreateFMul(Imag, Imag);
  1153. Function *FSqrt = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::sqrt,
  1154. CI->getType());
  1155. return copyFlags(
  1156. *CI, B.CreateCall(FSqrt, B.CreateFAdd(RealReal, ImagImag), "cabs"));
  1157. }
  1158. static Value *optimizeTrigReflections(CallInst *Call, LibFunc Func,
  1159. IRBuilderBase &B) {
  1160. if (!isa<FPMathOperator>(Call))
  1161. return nullptr;
  1162. IRBuilderBase::FastMathFlagGuard Guard(B);
  1163. B.setFastMathFlags(Call->getFastMathFlags());
  1164. // TODO: Can this be shared to also handle LLVM intrinsics?
  1165. Value *X;
  1166. switch (Func) {
  1167. case LibFunc_sin:
  1168. case LibFunc_sinf:
  1169. case LibFunc_sinl:
  1170. case LibFunc_tan:
  1171. case LibFunc_tanf:
  1172. case LibFunc_tanl:
  1173. // sin(-X) --> -sin(X)
  1174. // tan(-X) --> -tan(X)
  1175. if (match(Call->getArgOperand(0), m_OneUse(m_FNeg(m_Value(X)))))
  1176. return B.CreateFNeg(
  1177. copyFlags(*Call, B.CreateCall(Call->getCalledFunction(), X)));
  1178. break;
  1179. case LibFunc_cos:
  1180. case LibFunc_cosf:
  1181. case LibFunc_cosl:
  1182. // cos(-X) --> cos(X)
  1183. if (match(Call->getArgOperand(0), m_FNeg(m_Value(X))))
  1184. return copyFlags(*Call,
  1185. B.CreateCall(Call->getCalledFunction(), X, "cos"));
  1186. break;
  1187. default:
  1188. break;
  1189. }
  1190. return nullptr;
  1191. }
  1192. static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilderBase &B) {
  1193. // Multiplications calculated using Addition Chains.
  1194. // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html
  1195. assert(Exp != 0 && "Incorrect exponent 0 not handled");
  1196. if (InnerChain[Exp])
  1197. return InnerChain[Exp];
  1198. static const unsigned AddChain[33][2] = {
  1199. {0, 0}, // Unused.
  1200. {0, 0}, // Unused (base case = pow1).
  1201. {1, 1}, // Unused (pre-computed).
  1202. {1, 2}, {2, 2}, {2, 3}, {3, 3}, {2, 5}, {4, 4},
  1203. {1, 8}, {5, 5}, {1, 10}, {6, 6}, {4, 9}, {7, 7},
  1204. {3, 12}, {8, 8}, {8, 9}, {2, 16}, {1, 18}, {10, 10},
  1205. {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13},
  1206. {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16},
  1207. };
  1208. InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B),
  1209. getPow(InnerChain, AddChain[Exp][1], B));
  1210. return InnerChain[Exp];
  1211. }
  1212. // Return a properly extended integer (DstWidth bits wide) if the operation is
  1213. // an itofp.
  1214. static Value *getIntToFPVal(Value *I2F, IRBuilderBase &B, unsigned DstWidth) {
  1215. if (isa<SIToFPInst>(I2F) || isa<UIToFPInst>(I2F)) {
  1216. Value *Op = cast<Instruction>(I2F)->getOperand(0);
  1217. // Make sure that the exponent fits inside an "int" of size DstWidth,
  1218. // thus avoiding any range issues that FP has not.
  1219. unsigned BitWidth = Op->getType()->getPrimitiveSizeInBits();
  1220. if (BitWidth < DstWidth ||
  1221. (BitWidth == DstWidth && isa<SIToFPInst>(I2F)))
  1222. return isa<SIToFPInst>(I2F) ? B.CreateSExt(Op, B.getIntNTy(DstWidth))
  1223. : B.CreateZExt(Op, B.getIntNTy(DstWidth));
  1224. }
  1225. return nullptr;
  1226. }
  1227. /// Use exp{,2}(x * y) for pow(exp{,2}(x), y);
  1228. /// ldexp(1.0, x) for pow(2.0, itofp(x)); exp2(n * x) for pow(2.0 ** n, x);
  1229. /// exp10(x) for pow(10.0, x); exp2(log2(n) * x) for pow(n, x).
  1230. Value *LibCallSimplifier::replacePowWithExp(CallInst *Pow, IRBuilderBase &B) {
  1231. Value *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1);
  1232. AttributeList Attrs; // Attributes are only meaningful on the original call
  1233. Module *Mod = Pow->getModule();
  1234. Type *Ty = Pow->getType();
  1235. bool Ignored;
  1236. // Evaluate special cases related to a nested function as the base.
  1237. // pow(exp(x), y) -> exp(x * y)
  1238. // pow(exp2(x), y) -> exp2(x * y)
  1239. // If exp{,2}() is used only once, it is better to fold two transcendental
  1240. // math functions into one. If used again, exp{,2}() would still have to be
  1241. // called with the original argument, then keep both original transcendental
  1242. // functions. However, this transformation is only safe with fully relaxed
  1243. // math semantics, since, besides rounding differences, it changes overflow
  1244. // and underflow behavior quite dramatically. For example:
  1245. // pow(exp(1000), 0.001) = pow(inf, 0.001) = inf
  1246. // Whereas:
  1247. // exp(1000 * 0.001) = exp(1)
  1248. // TODO: Loosen the requirement for fully relaxed math semantics.
  1249. // TODO: Handle exp10() when more targets have it available.
  1250. CallInst *BaseFn = dyn_cast<CallInst>(Base);
  1251. if (BaseFn && BaseFn->hasOneUse() && BaseFn->isFast() && Pow->isFast()) {
  1252. LibFunc LibFn;
  1253. Function *CalleeFn = BaseFn->getCalledFunction();
  1254. if (CalleeFn &&
  1255. TLI->getLibFunc(CalleeFn->getName(), LibFn) && TLI->has(LibFn)) {
  1256. StringRef ExpName;
  1257. Intrinsic::ID ID;
  1258. Value *ExpFn;
  1259. LibFunc LibFnFloat, LibFnDouble, LibFnLongDouble;
  1260. switch (LibFn) {
  1261. default:
  1262. return nullptr;
  1263. case LibFunc_expf: case LibFunc_exp: case LibFunc_expl:
  1264. ExpName = TLI->getName(LibFunc_exp);
  1265. ID = Intrinsic::exp;
  1266. LibFnFloat = LibFunc_expf;
  1267. LibFnDouble = LibFunc_exp;
  1268. LibFnLongDouble = LibFunc_expl;
  1269. break;
  1270. case LibFunc_exp2f: case LibFunc_exp2: case LibFunc_exp2l:
  1271. ExpName = TLI->getName(LibFunc_exp2);
  1272. ID = Intrinsic::exp2;
  1273. LibFnFloat = LibFunc_exp2f;
  1274. LibFnDouble = LibFunc_exp2;
  1275. LibFnLongDouble = LibFunc_exp2l;
  1276. break;
  1277. }
  1278. // Create new exp{,2}() with the product as its argument.
  1279. Value *FMul = B.CreateFMul(BaseFn->getArgOperand(0), Expo, "mul");
  1280. ExpFn = BaseFn->doesNotAccessMemory()
  1281. ? B.CreateCall(Intrinsic::getDeclaration(Mod, ID, Ty),
  1282. FMul, ExpName)
  1283. : emitUnaryFloatFnCall(FMul, TLI, LibFnDouble, LibFnFloat,
  1284. LibFnLongDouble, B,
  1285. BaseFn->getAttributes());
  1286. // Since the new exp{,2}() is different from the original one, dead code
  1287. // elimination cannot be trusted to remove it, since it may have side
  1288. // effects (e.g., errno). When the only consumer for the original
  1289. // exp{,2}() is pow(), then it has to be explicitly erased.
  1290. substituteInParent(BaseFn, ExpFn);
  1291. return ExpFn;
  1292. }
  1293. }
  1294. // Evaluate special cases related to a constant base.
  1295. const APFloat *BaseF;
  1296. if (!match(Pow->getArgOperand(0), m_APFloat(BaseF)))
  1297. return nullptr;
  1298. // pow(2.0, itofp(x)) -> ldexp(1.0, x)
  1299. if (match(Base, m_SpecificFP(2.0)) &&
  1300. (isa<SIToFPInst>(Expo) || isa<UIToFPInst>(Expo)) &&
  1301. hasFloatFn(TLI, Ty, LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl)) {
  1302. if (Value *ExpoI = getIntToFPVal(Expo, B, TLI->getIntSize()))
  1303. return copyFlags(*Pow,
  1304. emitBinaryFloatFnCall(ConstantFP::get(Ty, 1.0), ExpoI,
  1305. TLI, LibFunc_ldexp, LibFunc_ldexpf,
  1306. LibFunc_ldexpl, B, Attrs));
  1307. }
  1308. // pow(2.0 ** n, x) -> exp2(n * x)
  1309. if (hasFloatFn(TLI, Ty, LibFunc_exp2, LibFunc_exp2f, LibFunc_exp2l)) {
  1310. APFloat BaseR = APFloat(1.0);
  1311. BaseR.convert(BaseF->getSemantics(), APFloat::rmTowardZero, &Ignored);
  1312. BaseR = BaseR / *BaseF;
  1313. bool IsInteger = BaseF->isInteger(), IsReciprocal = BaseR.isInteger();
  1314. const APFloat *NF = IsReciprocal ? &BaseR : BaseF;
  1315. APSInt NI(64, false);
  1316. if ((IsInteger || IsReciprocal) &&
  1317. NF->convertToInteger(NI, APFloat::rmTowardZero, &Ignored) ==
  1318. APFloat::opOK &&
  1319. NI > 1 && NI.isPowerOf2()) {
  1320. double N = NI.logBase2() * (IsReciprocal ? -1.0 : 1.0);
  1321. Value *FMul = B.CreateFMul(Expo, ConstantFP::get(Ty, N), "mul");
  1322. if (Pow->doesNotAccessMemory())
  1323. return copyFlags(*Pow, B.CreateCall(Intrinsic::getDeclaration(
  1324. Mod, Intrinsic::exp2, Ty),
  1325. FMul, "exp2"));
  1326. else
  1327. return copyFlags(*Pow, emitUnaryFloatFnCall(FMul, TLI, LibFunc_exp2,
  1328. LibFunc_exp2f,
  1329. LibFunc_exp2l, B, Attrs));
  1330. }
  1331. }
  1332. // pow(10.0, x) -> exp10(x)
  1333. // TODO: There is no exp10() intrinsic yet, but some day there shall be one.
  1334. if (match(Base, m_SpecificFP(10.0)) &&
  1335. hasFloatFn(TLI, Ty, LibFunc_exp10, LibFunc_exp10f, LibFunc_exp10l))
  1336. return copyFlags(*Pow, emitUnaryFloatFnCall(Expo, TLI, LibFunc_exp10,
  1337. LibFunc_exp10f, LibFunc_exp10l,
  1338. B, Attrs));
  1339. // pow(x, y) -> exp2(log2(x) * y)
  1340. if (Pow->hasApproxFunc() && Pow->hasNoNaNs() && BaseF->isFiniteNonZero() &&
  1341. !BaseF->isNegative()) {
  1342. // pow(1, inf) is defined to be 1 but exp2(log2(1) * inf) evaluates to NaN.
  1343. // Luckily optimizePow has already handled the x == 1 case.
  1344. assert(!match(Base, m_FPOne()) &&
  1345. "pow(1.0, y) should have been simplified earlier!");
  1346. Value *Log = nullptr;
  1347. if (Ty->isFloatTy())
  1348. Log = ConstantFP::get(Ty, std::log2(BaseF->convertToFloat()));
  1349. else if (Ty->isDoubleTy())
  1350. Log = ConstantFP::get(Ty, std::log2(BaseF->convertToDouble()));
  1351. if (Log) {
  1352. Value *FMul = B.CreateFMul(Log, Expo, "mul");
  1353. if (Pow->doesNotAccessMemory())
  1354. return copyFlags(*Pow, B.CreateCall(Intrinsic::getDeclaration(
  1355. Mod, Intrinsic::exp2, Ty),
  1356. FMul, "exp2"));
  1357. else if (hasFloatFn(TLI, Ty, LibFunc_exp2, LibFunc_exp2f, LibFunc_exp2l))
  1358. return copyFlags(*Pow, emitUnaryFloatFnCall(FMul, TLI, LibFunc_exp2,
  1359. LibFunc_exp2f,
  1360. LibFunc_exp2l, B, Attrs));
  1361. }
  1362. }
  1363. return nullptr;
  1364. }
  1365. static Value *getSqrtCall(Value *V, AttributeList Attrs, bool NoErrno,
  1366. Module *M, IRBuilderBase &B,
  1367. const TargetLibraryInfo *TLI) {
  1368. // If errno is never set, then use the intrinsic for sqrt().
  1369. if (NoErrno) {
  1370. Function *SqrtFn =
  1371. Intrinsic::getDeclaration(M, Intrinsic::sqrt, V->getType());
  1372. return B.CreateCall(SqrtFn, V, "sqrt");
  1373. }
  1374. // Otherwise, use the libcall for sqrt().
  1375. if (hasFloatFn(TLI, V->getType(), LibFunc_sqrt, LibFunc_sqrtf, LibFunc_sqrtl))
  1376. // TODO: We also should check that the target can in fact lower the sqrt()
  1377. // libcall. We currently have no way to ask this question, so we ask if
  1378. // the target has a sqrt() libcall, which is not exactly the same.
  1379. return emitUnaryFloatFnCall(V, TLI, LibFunc_sqrt, LibFunc_sqrtf,
  1380. LibFunc_sqrtl, B, Attrs);
  1381. return nullptr;
  1382. }
  1383. /// Use square root in place of pow(x, +/-0.5).
  1384. Value *LibCallSimplifier::replacePowWithSqrt(CallInst *Pow, IRBuilderBase &B) {
  1385. Value *Sqrt, *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1);
  1386. AttributeList Attrs; // Attributes are only meaningful on the original call
  1387. Module *Mod = Pow->getModule();
  1388. Type *Ty = Pow->getType();
  1389. const APFloat *ExpoF;
  1390. if (!match(Expo, m_APFloat(ExpoF)) ||
  1391. (!ExpoF->isExactlyValue(0.5) && !ExpoF->isExactlyValue(-0.5)))
  1392. return nullptr;
  1393. // Converting pow(X, -0.5) to 1/sqrt(X) may introduce an extra rounding step,
  1394. // so that requires fast-math-flags (afn or reassoc).
  1395. if (ExpoF->isNegative() && (!Pow->hasApproxFunc() && !Pow->hasAllowReassoc()))
  1396. return nullptr;
  1397. // If we have a pow() library call (accesses memory) and we can't guarantee
  1398. // that the base is not an infinity, give up:
  1399. // pow(-Inf, 0.5) is optionally required to have a result of +Inf (not setting
  1400. // errno), but sqrt(-Inf) is required by various standards to set errno.
  1401. if (!Pow->doesNotAccessMemory() && !Pow->hasNoInfs() &&
  1402. !isKnownNeverInfinity(Base, TLI))
  1403. return nullptr;
  1404. Sqrt = getSqrtCall(Base, Attrs, Pow->doesNotAccessMemory(), Mod, B, TLI);
  1405. if (!Sqrt)
  1406. return nullptr;
  1407. // Handle signed zero base by expanding to fabs(sqrt(x)).
  1408. if (!Pow->hasNoSignedZeros()) {
  1409. Function *FAbsFn = Intrinsic::getDeclaration(Mod, Intrinsic::fabs, Ty);
  1410. Sqrt = B.CreateCall(FAbsFn, Sqrt, "abs");
  1411. }
  1412. Sqrt = copyFlags(*Pow, Sqrt);
  1413. // Handle non finite base by expanding to
  1414. // (x == -infinity ? +infinity : sqrt(x)).
  1415. if (!Pow->hasNoInfs()) {
  1416. Value *PosInf = ConstantFP::getInfinity(Ty),
  1417. *NegInf = ConstantFP::getInfinity(Ty, true);
  1418. Value *FCmp = B.CreateFCmpOEQ(Base, NegInf, "isinf");
  1419. Sqrt = B.CreateSelect(FCmp, PosInf, Sqrt);
  1420. }
  1421. // If the exponent is negative, then get the reciprocal.
  1422. if (ExpoF->isNegative())
  1423. Sqrt = B.CreateFDiv(ConstantFP::get(Ty, 1.0), Sqrt, "reciprocal");
  1424. return Sqrt;
  1425. }
  1426. static Value *createPowWithIntegerExponent(Value *Base, Value *Expo, Module *M,
  1427. IRBuilderBase &B) {
  1428. Value *Args[] = {Base, Expo};
  1429. Type *Types[] = {Base->getType(), Expo->getType()};
  1430. Function *F = Intrinsic::getDeclaration(M, Intrinsic::powi, Types);
  1431. return B.CreateCall(F, Args);
  1432. }
  1433. Value *LibCallSimplifier::optimizePow(CallInst *Pow, IRBuilderBase &B) {
  1434. Value *Base = Pow->getArgOperand(0);
  1435. Value *Expo = Pow->getArgOperand(1);
  1436. Function *Callee = Pow->getCalledFunction();
  1437. StringRef Name = Callee->getName();
  1438. Type *Ty = Pow->getType();
  1439. Module *M = Pow->getModule();
  1440. bool AllowApprox = Pow->hasApproxFunc();
  1441. bool Ignored;
  1442. // Propagate the math semantics from the call to any created instructions.
  1443. IRBuilderBase::FastMathFlagGuard Guard(B);
  1444. B.setFastMathFlags(Pow->getFastMathFlags());
  1445. // Evaluate special cases related to the base.
  1446. // pow(1.0, x) -> 1.0
  1447. if (match(Base, m_FPOne()))
  1448. return Base;
  1449. if (Value *Exp = replacePowWithExp(Pow, B))
  1450. return Exp;
  1451. // Evaluate special cases related to the exponent.
  1452. // pow(x, -1.0) -> 1.0 / x
  1453. if (match(Expo, m_SpecificFP(-1.0)))
  1454. return B.CreateFDiv(ConstantFP::get(Ty, 1.0), Base, "reciprocal");
  1455. // pow(x, +/-0.0) -> 1.0
  1456. if (match(Expo, m_AnyZeroFP()))
  1457. return ConstantFP::get(Ty, 1.0);
  1458. // pow(x, 1.0) -> x
  1459. if (match(Expo, m_FPOne()))
  1460. return Base;
  1461. // pow(x, 2.0) -> x * x
  1462. if (match(Expo, m_SpecificFP(2.0)))
  1463. return B.CreateFMul(Base, Base, "square");
  1464. if (Value *Sqrt = replacePowWithSqrt(Pow, B))
  1465. return Sqrt;
  1466. // pow(x, n) -> x * x * x * ...
  1467. const APFloat *ExpoF;
  1468. if (AllowApprox && match(Expo, m_APFloat(ExpoF)) &&
  1469. !ExpoF->isExactlyValue(0.5) && !ExpoF->isExactlyValue(-0.5)) {
  1470. // We limit to a max of 7 multiplications, thus the maximum exponent is 32.
  1471. // If the exponent is an integer+0.5 we generate a call to sqrt and an
  1472. // additional fmul.
  1473. // TODO: This whole transformation should be backend specific (e.g. some
  1474. // backends might prefer libcalls or the limit for the exponent might
  1475. // be different) and it should also consider optimizing for size.
  1476. APFloat LimF(ExpoF->getSemantics(), 33),
  1477. ExpoA(abs(*ExpoF));
  1478. if (ExpoA < LimF) {
  1479. // This transformation applies to integer or integer+0.5 exponents only.
  1480. // For integer+0.5, we create a sqrt(Base) call.
  1481. Value *Sqrt = nullptr;
  1482. if (!ExpoA.isInteger()) {
  1483. APFloat Expo2 = ExpoA;
  1484. // To check if ExpoA is an integer + 0.5, we add it to itself. If there
  1485. // is no floating point exception and the result is an integer, then
  1486. // ExpoA == integer + 0.5
  1487. if (Expo2.add(ExpoA, APFloat::rmNearestTiesToEven) != APFloat::opOK)
  1488. return nullptr;
  1489. if (!Expo2.isInteger())
  1490. return nullptr;
  1491. Sqrt = getSqrtCall(Base, Pow->getCalledFunction()->getAttributes(),
  1492. Pow->doesNotAccessMemory(), M, B, TLI);
  1493. if (!Sqrt)
  1494. return nullptr;
  1495. }
  1496. // We will memoize intermediate products of the Addition Chain.
  1497. Value *InnerChain[33] = {nullptr};
  1498. InnerChain[1] = Base;
  1499. InnerChain[2] = B.CreateFMul(Base, Base, "square");
  1500. // We cannot readily convert a non-double type (like float) to a double.
  1501. // So we first convert it to something which could be converted to double.
  1502. ExpoA.convert(APFloat::IEEEdouble(), APFloat::rmTowardZero, &Ignored);
  1503. Value *FMul = getPow(InnerChain, ExpoA.convertToDouble(), B);
  1504. // Expand pow(x, y+0.5) to pow(x, y) * sqrt(x).
  1505. if (Sqrt)
  1506. FMul = B.CreateFMul(FMul, Sqrt);
  1507. // If the exponent is negative, then get the reciprocal.
  1508. if (ExpoF->isNegative())
  1509. FMul = B.CreateFDiv(ConstantFP::get(Ty, 1.0), FMul, "reciprocal");
  1510. return FMul;
  1511. }
  1512. APSInt IntExpo(TLI->getIntSize(), /*isUnsigned=*/false);
  1513. // powf(x, n) -> powi(x, n) if n is a constant signed integer value
  1514. if (ExpoF->isInteger() &&
  1515. ExpoF->convertToInteger(IntExpo, APFloat::rmTowardZero, &Ignored) ==
  1516. APFloat::opOK) {
  1517. return copyFlags(
  1518. *Pow,
  1519. createPowWithIntegerExponent(
  1520. Base, ConstantInt::get(B.getIntNTy(TLI->getIntSize()), IntExpo),
  1521. M, B));
  1522. }
  1523. }
  1524. // powf(x, itofp(y)) -> powi(x, y)
  1525. if (AllowApprox && (isa<SIToFPInst>(Expo) || isa<UIToFPInst>(Expo))) {
  1526. if (Value *ExpoI = getIntToFPVal(Expo, B, TLI->getIntSize()))
  1527. return copyFlags(*Pow, createPowWithIntegerExponent(Base, ExpoI, M, B));
  1528. }
  1529. // Shrink pow() to powf() if the arguments are single precision,
  1530. // unless the result is expected to be double precision.
  1531. if (UnsafeFPShrink && Name == TLI->getName(LibFunc_pow) &&
  1532. hasFloatVersion(Name)) {
  1533. if (Value *Shrunk = optimizeBinaryDoubleFP(Pow, B, true))
  1534. return Shrunk;
  1535. }
  1536. return nullptr;
  1537. }
  1538. Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilderBase &B) {
  1539. Function *Callee = CI->getCalledFunction();
  1540. AttributeList Attrs; // Attributes are only meaningful on the original call
  1541. StringRef Name = Callee->getName();
  1542. Value *Ret = nullptr;
  1543. if (UnsafeFPShrink && Name == TLI->getName(LibFunc_exp2) &&
  1544. hasFloatVersion(Name))
  1545. Ret = optimizeUnaryDoubleFP(CI, B, true);
  1546. Type *Ty = CI->getType();
  1547. Value *Op = CI->getArgOperand(0);
  1548. // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= IntSize
  1549. // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < IntSize
  1550. if ((isa<SIToFPInst>(Op) || isa<UIToFPInst>(Op)) &&
  1551. hasFloatFn(TLI, Ty, LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl)) {
  1552. if (Value *Exp = getIntToFPVal(Op, B, TLI->getIntSize()))
  1553. return emitBinaryFloatFnCall(ConstantFP::get(Ty, 1.0), Exp, TLI,
  1554. LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl,
  1555. B, Attrs);
  1556. }
  1557. return Ret;
  1558. }
  1559. Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilderBase &B) {
  1560. // If we can shrink the call to a float function rather than a double
  1561. // function, do that first.
  1562. Function *Callee = CI->getCalledFunction();
  1563. StringRef Name = Callee->getName();
  1564. if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name))
  1565. if (Value *Ret = optimizeBinaryDoubleFP(CI, B))
  1566. return Ret;
  1567. // The LLVM intrinsics minnum/maxnum correspond to fmin/fmax. Canonicalize to
  1568. // the intrinsics for improved optimization (for example, vectorization).
  1569. // No-signed-zeros is implied by the definitions of fmax/fmin themselves.
  1570. // From the C standard draft WG14/N1256:
  1571. // "Ideally, fmax would be sensitive to the sign of zero, for example
  1572. // fmax(-0.0, +0.0) would return +0; however, implementation in software
  1573. // might be impractical."
  1574. IRBuilderBase::FastMathFlagGuard Guard(B);
  1575. FastMathFlags FMF = CI->getFastMathFlags();
  1576. FMF.setNoSignedZeros();
  1577. B.setFastMathFlags(FMF);
  1578. Intrinsic::ID IID = Callee->getName().startswith("fmin") ? Intrinsic::minnum
  1579. : Intrinsic::maxnum;
  1580. Function *F = Intrinsic::getDeclaration(CI->getModule(), IID, CI->getType());
  1581. return copyFlags(
  1582. *CI, B.CreateCall(F, {CI->getArgOperand(0), CI->getArgOperand(1)}));
  1583. }
  1584. Value *LibCallSimplifier::optimizeLog(CallInst *Log, IRBuilderBase &B) {
  1585. Function *LogFn = Log->getCalledFunction();
  1586. AttributeList Attrs; // Attributes are only meaningful on the original call
  1587. StringRef LogNm = LogFn->getName();
  1588. Intrinsic::ID LogID = LogFn->getIntrinsicID();
  1589. Module *Mod = Log->getModule();
  1590. Type *Ty = Log->getType();
  1591. Value *Ret = nullptr;
  1592. if (UnsafeFPShrink && hasFloatVersion(LogNm))
  1593. Ret = optimizeUnaryDoubleFP(Log, B, true);
  1594. // The earlier call must also be 'fast' in order to do these transforms.
  1595. CallInst *Arg = dyn_cast<CallInst>(Log->getArgOperand(0));
  1596. if (!Log->isFast() || !Arg || !Arg->isFast() || !Arg->hasOneUse())
  1597. return Ret;
  1598. LibFunc LogLb, ExpLb, Exp2Lb, Exp10Lb, PowLb;
  1599. // This is only applicable to log(), log2(), log10().
  1600. if (TLI->getLibFunc(LogNm, LogLb))
  1601. switch (LogLb) {
  1602. case LibFunc_logf:
  1603. LogID = Intrinsic::log;
  1604. ExpLb = LibFunc_expf;
  1605. Exp2Lb = LibFunc_exp2f;
  1606. Exp10Lb = LibFunc_exp10f;
  1607. PowLb = LibFunc_powf;
  1608. break;
  1609. case LibFunc_log:
  1610. LogID = Intrinsic::log;
  1611. ExpLb = LibFunc_exp;
  1612. Exp2Lb = LibFunc_exp2;
  1613. Exp10Lb = LibFunc_exp10;
  1614. PowLb = LibFunc_pow;
  1615. break;
  1616. case LibFunc_logl:
  1617. LogID = Intrinsic::log;
  1618. ExpLb = LibFunc_expl;
  1619. Exp2Lb = LibFunc_exp2l;
  1620. Exp10Lb = LibFunc_exp10l;
  1621. PowLb = LibFunc_powl;
  1622. break;
  1623. case LibFunc_log2f:
  1624. LogID = Intrinsic::log2;
  1625. ExpLb = LibFunc_expf;
  1626. Exp2Lb = LibFunc_exp2f;
  1627. Exp10Lb = LibFunc_exp10f;
  1628. PowLb = LibFunc_powf;
  1629. break;
  1630. case LibFunc_log2:
  1631. LogID = Intrinsic::log2;
  1632. ExpLb = LibFunc_exp;
  1633. Exp2Lb = LibFunc_exp2;
  1634. Exp10Lb = LibFunc_exp10;
  1635. PowLb = LibFunc_pow;
  1636. break;
  1637. case LibFunc_log2l:
  1638. LogID = Intrinsic::log2;
  1639. ExpLb = LibFunc_expl;
  1640. Exp2Lb = LibFunc_exp2l;
  1641. Exp10Lb = LibFunc_exp10l;
  1642. PowLb = LibFunc_powl;
  1643. break;
  1644. case LibFunc_log10f:
  1645. LogID = Intrinsic::log10;
  1646. ExpLb = LibFunc_expf;
  1647. Exp2Lb = LibFunc_exp2f;
  1648. Exp10Lb = LibFunc_exp10f;
  1649. PowLb = LibFunc_powf;
  1650. break;
  1651. case LibFunc_log10:
  1652. LogID = Intrinsic::log10;
  1653. ExpLb = LibFunc_exp;
  1654. Exp2Lb = LibFunc_exp2;
  1655. Exp10Lb = LibFunc_exp10;
  1656. PowLb = LibFunc_pow;
  1657. break;
  1658. case LibFunc_log10l:
  1659. LogID = Intrinsic::log10;
  1660. ExpLb = LibFunc_expl;
  1661. Exp2Lb = LibFunc_exp2l;
  1662. Exp10Lb = LibFunc_exp10l;
  1663. PowLb = LibFunc_powl;
  1664. break;
  1665. default:
  1666. return Ret;
  1667. }
  1668. else if (LogID == Intrinsic::log || LogID == Intrinsic::log2 ||
  1669. LogID == Intrinsic::log10) {
  1670. if (Ty->getScalarType()->isFloatTy()) {
  1671. ExpLb = LibFunc_expf;
  1672. Exp2Lb = LibFunc_exp2f;
  1673. Exp10Lb = LibFunc_exp10f;
  1674. PowLb = LibFunc_powf;
  1675. } else if (Ty->getScalarType()->isDoubleTy()) {
  1676. ExpLb = LibFunc_exp;
  1677. Exp2Lb = LibFunc_exp2;
  1678. Exp10Lb = LibFunc_exp10;
  1679. PowLb = LibFunc_pow;
  1680. } else
  1681. return Ret;
  1682. } else
  1683. return Ret;
  1684. IRBuilderBase::FastMathFlagGuard Guard(B);
  1685. B.setFastMathFlags(FastMathFlags::getFast());
  1686. Intrinsic::ID ArgID = Arg->getIntrinsicID();
  1687. LibFunc ArgLb = NotLibFunc;
  1688. TLI->getLibFunc(*Arg, ArgLb);
  1689. // log(pow(x,y)) -> y*log(x)
  1690. if (ArgLb == PowLb || ArgID == Intrinsic::pow) {
  1691. Value *LogX =
  1692. Log->doesNotAccessMemory()
  1693. ? B.CreateCall(Intrinsic::getDeclaration(Mod, LogID, Ty),
  1694. Arg->getOperand(0), "log")
  1695. : emitUnaryFloatFnCall(Arg->getOperand(0), LogNm, B, Attrs);
  1696. Value *MulY = B.CreateFMul(Arg->getArgOperand(1), LogX, "mul");
  1697. // Since pow() may have side effects, e.g. errno,
  1698. // dead code elimination may not be trusted to remove it.
  1699. substituteInParent(Arg, MulY);
  1700. return MulY;
  1701. }
  1702. // log(exp{,2,10}(y)) -> y*log({e,2,10})
  1703. // TODO: There is no exp10() intrinsic yet.
  1704. if (ArgLb == ExpLb || ArgLb == Exp2Lb || ArgLb == Exp10Lb ||
  1705. ArgID == Intrinsic::exp || ArgID == Intrinsic::exp2) {
  1706. Constant *Eul;
  1707. if (ArgLb == ExpLb || ArgID == Intrinsic::exp)
  1708. // FIXME: Add more precise value of e for long double.
  1709. Eul = ConstantFP::get(Log->getType(), numbers::e);
  1710. else if (ArgLb == Exp2Lb || ArgID == Intrinsic::exp2)
  1711. Eul = ConstantFP::get(Log->getType(), 2.0);
  1712. else
  1713. Eul = ConstantFP::get(Log->getType(), 10.0);
  1714. Value *LogE = Log->doesNotAccessMemory()
  1715. ? B.CreateCall(Intrinsic::getDeclaration(Mod, LogID, Ty),
  1716. Eul, "log")
  1717. : emitUnaryFloatFnCall(Eul, LogNm, B, Attrs);
  1718. Value *MulY = B.CreateFMul(Arg->getArgOperand(0), LogE, "mul");
  1719. // Since exp() may have side effects, e.g. errno,
  1720. // dead code elimination may not be trusted to remove it.
  1721. substituteInParent(Arg, MulY);
  1722. return MulY;
  1723. }
  1724. return Ret;
  1725. }
  1726. Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilderBase &B) {
  1727. Function *Callee = CI->getCalledFunction();
  1728. Value *Ret = nullptr;
  1729. // TODO: Once we have a way (other than checking for the existince of the
  1730. // libcall) to tell whether our target can lower @llvm.sqrt, relax the
  1731. // condition below.
  1732. if (TLI->has(LibFunc_sqrtf) && (Callee->getName() == "sqrt" ||
  1733. Callee->getIntrinsicID() == Intrinsic::sqrt))
  1734. Ret = optimizeUnaryDoubleFP(CI, B, true);
  1735. if (!CI->isFast())
  1736. return Ret;
  1737. Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0));
  1738. if (!I || I->getOpcode() != Instruction::FMul || !I->isFast())
  1739. return Ret;
  1740. // We're looking for a repeated factor in a multiplication tree,
  1741. // so we can do this fold: sqrt(x * x) -> fabs(x);
  1742. // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
  1743. Value *Op0 = I->getOperand(0);
  1744. Value *Op1 = I->getOperand(1);
  1745. Value *RepeatOp = nullptr;
  1746. Value *OtherOp = nullptr;
  1747. if (Op0 == Op1) {
  1748. // Simple match: the operands of the multiply are identical.
  1749. RepeatOp = Op0;
  1750. } else {
  1751. // Look for a more complicated pattern: one of the operands is itself
  1752. // a multiply, so search for a common factor in that multiply.
  1753. // Note: We don't bother looking any deeper than this first level or for
  1754. // variations of this pattern because instcombine's visitFMUL and/or the
  1755. // reassociation pass should give us this form.
  1756. Value *OtherMul0, *OtherMul1;
  1757. if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
  1758. // Pattern: sqrt((x * y) * z)
  1759. if (OtherMul0 == OtherMul1 && cast<Instruction>(Op0)->isFast()) {
  1760. // Matched: sqrt((x * x) * z)
  1761. RepeatOp = OtherMul0;
  1762. OtherOp = Op1;
  1763. }
  1764. }
  1765. }
  1766. if (!RepeatOp)
  1767. return Ret;
  1768. // Fast math flags for any created instructions should match the sqrt
  1769. // and multiply.
  1770. IRBuilderBase::FastMathFlagGuard Guard(B);
  1771. B.setFastMathFlags(I->getFastMathFlags());
  1772. // If we found a repeated factor, hoist it out of the square root and
  1773. // replace it with the fabs of that factor.
  1774. Module *M = Callee->getParent();
  1775. Type *ArgType = I->getType();
  1776. Function *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
  1777. Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
  1778. if (OtherOp) {
  1779. // If we found a non-repeated factor, we still need to get its square
  1780. // root. We then multiply that by the value that was simplified out
  1781. // of the square root calculation.
  1782. Function *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
  1783. Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
  1784. return copyFlags(*CI, B.CreateFMul(FabsCall, SqrtCall));
  1785. }
  1786. return copyFlags(*CI, FabsCall);
  1787. }
  1788. // TODO: Generalize to handle any trig function and its inverse.
  1789. Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilderBase &B) {
  1790. Function *Callee = CI->getCalledFunction();
  1791. Value *Ret = nullptr;
  1792. StringRef Name = Callee->getName();
  1793. if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
  1794. Ret = optimizeUnaryDoubleFP(CI, B, true);
  1795. Value *Op1 = CI->getArgOperand(0);
  1796. auto *OpC = dyn_cast<CallInst>(Op1);
  1797. if (!OpC)
  1798. return Ret;
  1799. // Both calls must be 'fast' in order to remove them.
  1800. if (!CI->isFast() || !OpC->isFast())
  1801. return Ret;
  1802. // tan(atan(x)) -> x
  1803. // tanf(atanf(x)) -> x
  1804. // tanl(atanl(x)) -> x
  1805. LibFunc Func;
  1806. Function *F = OpC->getCalledFunction();
  1807. if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
  1808. ((Func == LibFunc_atan && Callee->getName() == "tan") ||
  1809. (Func == LibFunc_atanf && Callee->getName() == "tanf") ||
  1810. (Func == LibFunc_atanl && Callee->getName() == "tanl")))
  1811. Ret = OpC->getArgOperand(0);
  1812. return Ret;
  1813. }
  1814. static bool isTrigLibCall(CallInst *CI) {
  1815. // We can only hope to do anything useful if we can ignore things like errno
  1816. // and floating-point exceptions.
  1817. // We already checked the prototype.
  1818. return CI->hasFnAttr(Attribute::NoUnwind) &&
  1819. CI->hasFnAttr(Attribute::ReadNone);
  1820. }
  1821. static void insertSinCosCall(IRBuilderBase &B, Function *OrigCallee, Value *Arg,
  1822. bool UseFloat, Value *&Sin, Value *&Cos,
  1823. Value *&SinCos) {
  1824. Type *ArgTy = Arg->getType();
  1825. Type *ResTy;
  1826. StringRef Name;
  1827. Triple T(OrigCallee->getParent()->getTargetTriple());
  1828. if (UseFloat) {
  1829. Name = "__sincospif_stret";
  1830. assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
  1831. // x86_64 can't use {float, float} since that would be returned in both
  1832. // xmm0 and xmm1, which isn't what a real struct would do.
  1833. ResTy = T.getArch() == Triple::x86_64
  1834. ? static_cast<Type *>(FixedVectorType::get(ArgTy, 2))
  1835. : static_cast<Type *>(StructType::get(ArgTy, ArgTy));
  1836. } else {
  1837. Name = "__sincospi_stret";
  1838. ResTy = StructType::get(ArgTy, ArgTy);
  1839. }
  1840. Module *M = OrigCallee->getParent();
  1841. FunctionCallee Callee =
  1842. M->getOrInsertFunction(Name, OrigCallee->getAttributes(), ResTy, ArgTy);
  1843. if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
  1844. // If the argument is an instruction, it must dominate all uses so put our
  1845. // sincos call there.
  1846. B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
  1847. } else {
  1848. // Otherwise (e.g. for a constant) the beginning of the function is as
  1849. // good a place as any.
  1850. BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
  1851. B.SetInsertPoint(&EntryBB, EntryBB.begin());
  1852. }
  1853. SinCos = B.CreateCall(Callee, Arg, "sincospi");
  1854. if (SinCos->getType()->isStructTy()) {
  1855. Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
  1856. Cos = B.CreateExtractValue(SinCos, 1, "cospi");
  1857. } else {
  1858. Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
  1859. "sinpi");
  1860. Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
  1861. "cospi");
  1862. }
  1863. }
  1864. Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilderBase &B) {
  1865. // Make sure the prototype is as expected, otherwise the rest of the
  1866. // function is probably invalid and likely to abort.
  1867. if (!isTrigLibCall(CI))
  1868. return nullptr;
  1869. Value *Arg = CI->getArgOperand(0);
  1870. SmallVector<CallInst *, 1> SinCalls;
  1871. SmallVector<CallInst *, 1> CosCalls;
  1872. SmallVector<CallInst *, 1> SinCosCalls;
  1873. bool IsFloat = Arg->getType()->isFloatTy();
  1874. // Look for all compatible sinpi, cospi and sincospi calls with the same
  1875. // argument. If there are enough (in some sense) we can make the
  1876. // substitution.
  1877. Function *F = CI->getFunction();
  1878. for (User *U : Arg->users())
  1879. classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls);
  1880. // It's only worthwhile if both sinpi and cospi are actually used.
  1881. if (SinCalls.empty() || CosCalls.empty())
  1882. return nullptr;
  1883. Value *Sin, *Cos, *SinCos;
  1884. insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
  1885. auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls,
  1886. Value *Res) {
  1887. for (CallInst *C : Calls)
  1888. replaceAllUsesWith(C, Res);
  1889. };
  1890. replaceTrigInsts(SinCalls, Sin);
  1891. replaceTrigInsts(CosCalls, Cos);
  1892. replaceTrigInsts(SinCosCalls, SinCos);
  1893. return nullptr;
  1894. }
  1895. void LibCallSimplifier::classifyArgUse(
  1896. Value *Val, Function *F, bool IsFloat,
  1897. SmallVectorImpl<CallInst *> &SinCalls,
  1898. SmallVectorImpl<CallInst *> &CosCalls,
  1899. SmallVectorImpl<CallInst *> &SinCosCalls) {
  1900. CallInst *CI = dyn_cast<CallInst>(Val);
  1901. if (!CI || CI->use_empty())
  1902. return;
  1903. // Don't consider calls in other functions.
  1904. if (CI->getFunction() != F)
  1905. return;
  1906. Function *Callee = CI->getCalledFunction();
  1907. LibFunc Func;
  1908. if (!Callee || !TLI->getLibFunc(*Callee, Func) || !TLI->has(Func) ||
  1909. !isTrigLibCall(CI))
  1910. return;
  1911. if (IsFloat) {
  1912. if (Func == LibFunc_sinpif)
  1913. SinCalls.push_back(CI);
  1914. else if (Func == LibFunc_cospif)
  1915. CosCalls.push_back(CI);
  1916. else if (Func == LibFunc_sincospif_stret)
  1917. SinCosCalls.push_back(CI);
  1918. } else {
  1919. if (Func == LibFunc_sinpi)
  1920. SinCalls.push_back(CI);
  1921. else if (Func == LibFunc_cospi)
  1922. CosCalls.push_back(CI);
  1923. else if (Func == LibFunc_sincospi_stret)
  1924. SinCosCalls.push_back(CI);
  1925. }
  1926. }
  1927. //===----------------------------------------------------------------------===//
  1928. // Integer Library Call Optimizations
  1929. //===----------------------------------------------------------------------===//
  1930. Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilderBase &B) {
  1931. // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
  1932. Value *Op = CI->getArgOperand(0);
  1933. Type *ArgType = Op->getType();
  1934. Function *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
  1935. Intrinsic::cttz, ArgType);
  1936. Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
  1937. V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
  1938. V = B.CreateIntCast(V, B.getInt32Ty(), false);
  1939. Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
  1940. return B.CreateSelect(Cond, V, B.getInt32(0));
  1941. }
  1942. Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilderBase &B) {
  1943. // fls(x) -> (i32)(sizeInBits(x) - llvm.ctlz(x, false))
  1944. Value *Op = CI->getArgOperand(0);
  1945. Type *ArgType = Op->getType();
  1946. Function *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
  1947. Intrinsic::ctlz, ArgType);
  1948. Value *V = B.CreateCall(F, {Op, B.getFalse()}, "ctlz");
  1949. V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()),
  1950. V);
  1951. return B.CreateIntCast(V, CI->getType(), false);
  1952. }
  1953. Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilderBase &B) {
  1954. // abs(x) -> x <s 0 ? -x : x
  1955. // The negation has 'nsw' because abs of INT_MIN is undefined.
  1956. Value *X = CI->getArgOperand(0);
  1957. Value *IsNeg = B.CreateICmpSLT(X, Constant::getNullValue(X->getType()));
  1958. Value *NegX = B.CreateNSWNeg(X, "neg");
  1959. return B.CreateSelect(IsNeg, NegX, X);
  1960. }
  1961. Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilderBase &B) {
  1962. // isdigit(c) -> (c-'0') <u 10
  1963. Value *Op = CI->getArgOperand(0);
  1964. Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
  1965. Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
  1966. return B.CreateZExt(Op, CI->getType());
  1967. }
  1968. Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilderBase &B) {
  1969. // isascii(c) -> c <u 128
  1970. Value *Op = CI->getArgOperand(0);
  1971. Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
  1972. return B.CreateZExt(Op, CI->getType());
  1973. }
  1974. Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilderBase &B) {
  1975. // toascii(c) -> c & 0x7f
  1976. return B.CreateAnd(CI->getArgOperand(0),
  1977. ConstantInt::get(CI->getType(), 0x7F));
  1978. }
  1979. Value *LibCallSimplifier::optimizeAtoi(CallInst *CI, IRBuilderBase &B) {
  1980. StringRef Str;
  1981. if (!getConstantStringInfo(CI->getArgOperand(0), Str))
  1982. return nullptr;
  1983. return convertStrToNumber(CI, Str, 10);
  1984. }
  1985. Value *LibCallSimplifier::optimizeStrtol(CallInst *CI, IRBuilderBase &B) {
  1986. StringRef Str;
  1987. if (!getConstantStringInfo(CI->getArgOperand(0), Str))
  1988. return nullptr;
  1989. if (!isa<ConstantPointerNull>(CI->getArgOperand(1)))
  1990. return nullptr;
  1991. if (ConstantInt *CInt = dyn_cast<ConstantInt>(CI->getArgOperand(2))) {
  1992. return convertStrToNumber(CI, Str, CInt->getSExtValue());
  1993. }
  1994. return nullptr;
  1995. }
  1996. //===----------------------------------------------------------------------===//
  1997. // Formatting and IO Library Call Optimizations
  1998. //===----------------------------------------------------------------------===//
  1999. static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
  2000. Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilderBase &B,
  2001. int StreamArg) {
  2002. Function *Callee = CI->getCalledFunction();
  2003. // Error reporting calls should be cold, mark them as such.
  2004. // This applies even to non-builtin calls: it is only a hint and applies to
  2005. // functions that the frontend might not understand as builtins.
  2006. // This heuristic was suggested in:
  2007. // Improving Static Branch Prediction in a Compiler
  2008. // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
  2009. // Proceedings of PACT'98, Oct. 1998, IEEE
  2010. if (!CI->hasFnAttr(Attribute::Cold) &&
  2011. isReportingError(Callee, CI, StreamArg)) {
  2012. CI->addFnAttr(Attribute::Cold);
  2013. }
  2014. return nullptr;
  2015. }
  2016. static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
  2017. if (!Callee || !Callee->isDeclaration())
  2018. return false;
  2019. if (StreamArg < 0)
  2020. return true;
  2021. // These functions might be considered cold, but only if their stream
  2022. // argument is stderr.
  2023. if (StreamArg >= (int)CI->arg_size())
  2024. return false;
  2025. LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
  2026. if (!LI)
  2027. return false;
  2028. GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
  2029. if (!GV || !GV->isDeclaration())
  2030. return false;
  2031. return GV->getName() == "stderr";
  2032. }
  2033. Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilderBase &B) {
  2034. // Check for a fixed format string.
  2035. StringRef FormatStr;
  2036. if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
  2037. return nullptr;
  2038. // Empty format string -> noop.
  2039. if (FormatStr.empty()) // Tolerate printf's declared void.
  2040. return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
  2041. // Do not do any of the following transformations if the printf return value
  2042. // is used, in general the printf return value is not compatible with either
  2043. // putchar() or puts().
  2044. if (!CI->use_empty())
  2045. return nullptr;
  2046. // printf("x") -> putchar('x'), even for "%" and "%%".
  2047. if (FormatStr.size() == 1 || FormatStr == "%%")
  2048. return copyFlags(*CI, emitPutChar(B.getInt32(FormatStr[0]), B, TLI));
  2049. // Try to remove call or emit putchar/puts.
  2050. if (FormatStr == "%s" && CI->arg_size() > 1) {
  2051. StringRef OperandStr;
  2052. if (!getConstantStringInfo(CI->getOperand(1), OperandStr))
  2053. return nullptr;
  2054. // printf("%s", "") --> NOP
  2055. if (OperandStr.empty())
  2056. return (Value *)CI;
  2057. // printf("%s", "a") --> putchar('a')
  2058. if (OperandStr.size() == 1)
  2059. return copyFlags(*CI, emitPutChar(B.getInt32(OperandStr[0]), B, TLI));
  2060. // printf("%s", str"\n") --> puts(str)
  2061. if (OperandStr.back() == '\n') {
  2062. OperandStr = OperandStr.drop_back();
  2063. Value *GV = B.CreateGlobalString(OperandStr, "str");
  2064. return copyFlags(*CI, emitPutS(GV, B, TLI));
  2065. }
  2066. return nullptr;
  2067. }
  2068. // printf("foo\n") --> puts("foo")
  2069. if (FormatStr.back() == '\n' &&
  2070. !FormatStr.contains('%')) { // No format characters.
  2071. // Create a string literal with no \n on it. We expect the constant merge
  2072. // pass to be run after this pass, to merge duplicate strings.
  2073. FormatStr = FormatStr.drop_back();
  2074. Value *GV = B.CreateGlobalString(FormatStr, "str");
  2075. return copyFlags(*CI, emitPutS(GV, B, TLI));
  2076. }
  2077. // Optimize specific format strings.
  2078. // printf("%c", chr) --> putchar(chr)
  2079. if (FormatStr == "%c" && CI->arg_size() > 1 &&
  2080. CI->getArgOperand(1)->getType()->isIntegerTy())
  2081. return copyFlags(*CI, emitPutChar(CI->getArgOperand(1), B, TLI));
  2082. // printf("%s\n", str) --> puts(str)
  2083. if (FormatStr == "%s\n" && CI->arg_size() > 1 &&
  2084. CI->getArgOperand(1)->getType()->isPointerTy())
  2085. return copyFlags(*CI, emitPutS(CI->getArgOperand(1), B, TLI));
  2086. return nullptr;
  2087. }
  2088. Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilderBase &B) {
  2089. Function *Callee = CI->getCalledFunction();
  2090. FunctionType *FT = Callee->getFunctionType();
  2091. if (Value *V = optimizePrintFString(CI, B)) {
  2092. return V;
  2093. }
  2094. // printf(format, ...) -> iprintf(format, ...) if no floating point
  2095. // arguments.
  2096. if (TLI->has(LibFunc_iprintf) && !callHasFloatingPointArgument(CI)) {
  2097. Module *M = B.GetInsertBlock()->getParent()->getParent();
  2098. FunctionCallee IPrintFFn =
  2099. M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
  2100. CallInst *New = cast<CallInst>(CI->clone());
  2101. New->setCalledFunction(IPrintFFn);
  2102. B.Insert(New);
  2103. return New;
  2104. }
  2105. // printf(format, ...) -> __small_printf(format, ...) if no 128-bit floating point
  2106. // arguments.
  2107. if (TLI->has(LibFunc_small_printf) && !callHasFP128Argument(CI)) {
  2108. Module *M = B.GetInsertBlock()->getParent()->getParent();
  2109. auto SmallPrintFFn =
  2110. M->getOrInsertFunction(TLI->getName(LibFunc_small_printf),
  2111. FT, Callee->getAttributes());
  2112. CallInst *New = cast<CallInst>(CI->clone());
  2113. New->setCalledFunction(SmallPrintFFn);
  2114. B.Insert(New);
  2115. return New;
  2116. }
  2117. annotateNonNullNoUndefBasedOnAccess(CI, 0);
  2118. return nullptr;
  2119. }
  2120. Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI,
  2121. IRBuilderBase &B) {
  2122. // Check for a fixed format string.
  2123. StringRef FormatStr;
  2124. if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
  2125. return nullptr;
  2126. // If we just have a format string (nothing else crazy) transform it.
  2127. Value *Dest = CI->getArgOperand(0);
  2128. if (CI->arg_size() == 2) {
  2129. // Make sure there's no % in the constant array. We could try to handle
  2130. // %% -> % in the future if we cared.
  2131. if (FormatStr.contains('%'))
  2132. return nullptr; // we found a format specifier, bail out.
  2133. // sprintf(str, fmt) -> llvm.memcpy(align 1 str, align 1 fmt, strlen(fmt)+1)
  2134. B.CreateMemCpy(
  2135. Dest, Align(1), CI->getArgOperand(1), Align(1),
  2136. ConstantInt::get(DL.getIntPtrType(CI->getContext()),
  2137. FormatStr.size() + 1)); // Copy the null byte.
  2138. return ConstantInt::get(CI->getType(), FormatStr.size());
  2139. }
  2140. // The remaining optimizations require the format string to be "%s" or "%c"
  2141. // and have an extra operand.
  2142. if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->arg_size() < 3)
  2143. return nullptr;
  2144. // Decode the second character of the format string.
  2145. if (FormatStr[1] == 'c') {
  2146. // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
  2147. if (!CI->getArgOperand(2)->getType()->isIntegerTy())
  2148. return nullptr;
  2149. Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
  2150. Value *Ptr = castToCStr(Dest, B);
  2151. B.CreateStore(V, Ptr);
  2152. Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
  2153. B.CreateStore(B.getInt8(0), Ptr);
  2154. return ConstantInt::get(CI->getType(), 1);
  2155. }
  2156. if (FormatStr[1] == 's') {
  2157. // sprintf(dest, "%s", str) -> llvm.memcpy(align 1 dest, align 1 str,
  2158. // strlen(str)+1)
  2159. if (!CI->getArgOperand(2)->getType()->isPointerTy())
  2160. return nullptr;
  2161. if (CI->use_empty())
  2162. // sprintf(dest, "%s", str) -> strcpy(dest, str)
  2163. return copyFlags(*CI, emitStrCpy(Dest, CI->getArgOperand(2), B, TLI));
  2164. uint64_t SrcLen = GetStringLength(CI->getArgOperand(2));
  2165. if (SrcLen) {
  2166. B.CreateMemCpy(
  2167. Dest, Align(1), CI->getArgOperand(2), Align(1),
  2168. ConstantInt::get(DL.getIntPtrType(CI->getContext()), SrcLen));
  2169. // Returns total number of characters written without null-character.
  2170. return ConstantInt::get(CI->getType(), SrcLen - 1);
  2171. } else if (Value *V = emitStpCpy(Dest, CI->getArgOperand(2), B, TLI)) {
  2172. // sprintf(dest, "%s", str) -> stpcpy(dest, str) - dest
  2173. // Handle mismatched pointer types (goes away with typeless pointers?).
  2174. V = B.CreatePointerCast(V, B.getInt8PtrTy());
  2175. Dest = B.CreatePointerCast(Dest, B.getInt8PtrTy());
  2176. Value *PtrDiff = B.CreatePtrDiff(B.getInt8Ty(), V, Dest);
  2177. return B.CreateIntCast(PtrDiff, CI->getType(), false);
  2178. }
  2179. bool OptForSize = CI->getFunction()->hasOptSize() ||
  2180. llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI,
  2181. PGSOQueryType::IRPass);
  2182. if (OptForSize)
  2183. return nullptr;
  2184. Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI);
  2185. if (!Len)
  2186. return nullptr;
  2187. Value *IncLen =
  2188. B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
  2189. B.CreateMemCpy(Dest, Align(1), CI->getArgOperand(2), Align(1), IncLen);
  2190. // The sprintf result is the unincremented number of bytes in the string.
  2191. return B.CreateIntCast(Len, CI->getType(), false);
  2192. }
  2193. return nullptr;
  2194. }
  2195. Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilderBase &B) {
  2196. Function *Callee = CI->getCalledFunction();
  2197. FunctionType *FT = Callee->getFunctionType();
  2198. if (Value *V = optimizeSPrintFString(CI, B)) {
  2199. return V;
  2200. }
  2201. // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
  2202. // point arguments.
  2203. if (TLI->has(LibFunc_siprintf) && !callHasFloatingPointArgument(CI)) {
  2204. Module *M = B.GetInsertBlock()->getParent()->getParent();
  2205. FunctionCallee SIPrintFFn =
  2206. M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
  2207. CallInst *New = cast<CallInst>(CI->clone());
  2208. New->setCalledFunction(SIPrintFFn);
  2209. B.Insert(New);
  2210. return New;
  2211. }
  2212. // sprintf(str, format, ...) -> __small_sprintf(str, format, ...) if no 128-bit
  2213. // floating point arguments.
  2214. if (TLI->has(LibFunc_small_sprintf) && !callHasFP128Argument(CI)) {
  2215. Module *M = B.GetInsertBlock()->getParent()->getParent();
  2216. auto SmallSPrintFFn =
  2217. M->getOrInsertFunction(TLI->getName(LibFunc_small_sprintf),
  2218. FT, Callee->getAttributes());
  2219. CallInst *New = cast<CallInst>(CI->clone());
  2220. New->setCalledFunction(SmallSPrintFFn);
  2221. B.Insert(New);
  2222. return New;
  2223. }
  2224. annotateNonNullNoUndefBasedOnAccess(CI, {0, 1});
  2225. return nullptr;
  2226. }
  2227. Value *LibCallSimplifier::optimizeSnPrintFString(CallInst *CI,
  2228. IRBuilderBase &B) {
  2229. // Check for size
  2230. ConstantInt *Size = dyn_cast<ConstantInt>(CI->getArgOperand(1));
  2231. if (!Size)
  2232. return nullptr;
  2233. uint64_t N = Size->getZExtValue();
  2234. // Check for a fixed format string.
  2235. StringRef FormatStr;
  2236. if (!getConstantStringInfo(CI->getArgOperand(2), FormatStr))
  2237. return nullptr;
  2238. // If we just have a format string (nothing else crazy) transform it.
  2239. if (CI->arg_size() == 3) {
  2240. // Make sure there's no % in the constant array. We could try to handle
  2241. // %% -> % in the future if we cared.
  2242. if (FormatStr.contains('%'))
  2243. return nullptr; // we found a format specifier, bail out.
  2244. if (N == 0)
  2245. return ConstantInt::get(CI->getType(), FormatStr.size());
  2246. else if (N < FormatStr.size() + 1)
  2247. return nullptr;
  2248. // snprintf(dst, size, fmt) -> llvm.memcpy(align 1 dst, align 1 fmt,
  2249. // strlen(fmt)+1)
  2250. copyFlags(
  2251. *CI,
  2252. B.CreateMemCpy(
  2253. CI->getArgOperand(0), Align(1), CI->getArgOperand(2), Align(1),
  2254. ConstantInt::get(DL.getIntPtrType(CI->getContext()),
  2255. FormatStr.size() + 1))); // Copy the null byte.
  2256. return ConstantInt::get(CI->getType(), FormatStr.size());
  2257. }
  2258. // The remaining optimizations require the format string to be "%s" or "%c"
  2259. // and have an extra operand.
  2260. if (FormatStr.size() == 2 && FormatStr[0] == '%' && CI->arg_size() == 4) {
  2261. // Decode the second character of the format string.
  2262. if (FormatStr[1] == 'c') {
  2263. if (N == 0)
  2264. return ConstantInt::get(CI->getType(), 1);
  2265. else if (N == 1)
  2266. return nullptr;
  2267. // snprintf(dst, size, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
  2268. if (!CI->getArgOperand(3)->getType()->isIntegerTy())
  2269. return nullptr;
  2270. Value *V = B.CreateTrunc(CI->getArgOperand(3), B.getInt8Ty(), "char");
  2271. Value *Ptr = castToCStr(CI->getArgOperand(0), B);
  2272. B.CreateStore(V, Ptr);
  2273. Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
  2274. B.CreateStore(B.getInt8(0), Ptr);
  2275. return ConstantInt::get(CI->getType(), 1);
  2276. }
  2277. if (FormatStr[1] == 's') {
  2278. // snprintf(dest, size, "%s", str) to llvm.memcpy(dest, str, len+1, 1)
  2279. StringRef Str;
  2280. if (!getConstantStringInfo(CI->getArgOperand(3), Str))
  2281. return nullptr;
  2282. if (N == 0)
  2283. return ConstantInt::get(CI->getType(), Str.size());
  2284. else if (N < Str.size() + 1)
  2285. return nullptr;
  2286. copyFlags(
  2287. *CI, B.CreateMemCpy(CI->getArgOperand(0), Align(1),
  2288. CI->getArgOperand(3), Align(1),
  2289. ConstantInt::get(CI->getType(), Str.size() + 1)));
  2290. // The snprintf result is the unincremented number of bytes in the string.
  2291. return ConstantInt::get(CI->getType(), Str.size());
  2292. }
  2293. }
  2294. return nullptr;
  2295. }
  2296. Value *LibCallSimplifier::optimizeSnPrintF(CallInst *CI, IRBuilderBase &B) {
  2297. if (Value *V = optimizeSnPrintFString(CI, B)) {
  2298. return V;
  2299. }
  2300. if (isKnownNonZero(CI->getOperand(1), DL))
  2301. annotateNonNullNoUndefBasedOnAccess(CI, 0);
  2302. return nullptr;
  2303. }
  2304. Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI,
  2305. IRBuilderBase &B) {
  2306. optimizeErrorReporting(CI, B, 0);
  2307. // All the optimizations depend on the format string.
  2308. StringRef FormatStr;
  2309. if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
  2310. return nullptr;
  2311. // Do not do any of the following transformations if the fprintf return
  2312. // value is used, in general the fprintf return value is not compatible
  2313. // with fwrite(), fputc() or fputs().
  2314. if (!CI->use_empty())
  2315. return nullptr;
  2316. // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
  2317. if (CI->arg_size() == 2) {
  2318. // Could handle %% -> % if we cared.
  2319. if (FormatStr.contains('%'))
  2320. return nullptr; // We found a format specifier.
  2321. return copyFlags(
  2322. *CI, emitFWrite(CI->getArgOperand(1),
  2323. ConstantInt::get(DL.getIntPtrType(CI->getContext()),
  2324. FormatStr.size()),
  2325. CI->getArgOperand(0), B, DL, TLI));
  2326. }
  2327. // The remaining optimizations require the format string to be "%s" or "%c"
  2328. // and have an extra operand.
  2329. if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->arg_size() < 3)
  2330. return nullptr;
  2331. // Decode the second character of the format string.
  2332. if (FormatStr[1] == 'c') {
  2333. // fprintf(F, "%c", chr) --> fputc(chr, F)
  2334. if (!CI->getArgOperand(2)->getType()->isIntegerTy())
  2335. return nullptr;
  2336. return copyFlags(
  2337. *CI, emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI));
  2338. }
  2339. if (FormatStr[1] == 's') {
  2340. // fprintf(F, "%s", str) --> fputs(str, F)
  2341. if (!CI->getArgOperand(2)->getType()->isPointerTy())
  2342. return nullptr;
  2343. return copyFlags(
  2344. *CI, emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI));
  2345. }
  2346. return nullptr;
  2347. }
  2348. Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilderBase &B) {
  2349. Function *Callee = CI->getCalledFunction();
  2350. FunctionType *FT = Callee->getFunctionType();
  2351. if (Value *V = optimizeFPrintFString(CI, B)) {
  2352. return V;
  2353. }
  2354. // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
  2355. // floating point arguments.
  2356. if (TLI->has(LibFunc_fiprintf) && !callHasFloatingPointArgument(CI)) {
  2357. Module *M = B.GetInsertBlock()->getParent()->getParent();
  2358. FunctionCallee FIPrintFFn =
  2359. M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
  2360. CallInst *New = cast<CallInst>(CI->clone());
  2361. New->setCalledFunction(FIPrintFFn);
  2362. B.Insert(New);
  2363. return New;
  2364. }
  2365. // fprintf(stream, format, ...) -> __small_fprintf(stream, format, ...) if no
  2366. // 128-bit floating point arguments.
  2367. if (TLI->has(LibFunc_small_fprintf) && !callHasFP128Argument(CI)) {
  2368. Module *M = B.GetInsertBlock()->getParent()->getParent();
  2369. auto SmallFPrintFFn =
  2370. M->getOrInsertFunction(TLI->getName(LibFunc_small_fprintf),
  2371. FT, Callee->getAttributes());
  2372. CallInst *New = cast<CallInst>(CI->clone());
  2373. New->setCalledFunction(SmallFPrintFFn);
  2374. B.Insert(New);
  2375. return New;
  2376. }
  2377. return nullptr;
  2378. }
  2379. Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilderBase &B) {
  2380. optimizeErrorReporting(CI, B, 3);
  2381. // Get the element size and count.
  2382. ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
  2383. ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
  2384. if (SizeC && CountC) {
  2385. uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
  2386. // If this is writing zero records, remove the call (it's a noop).
  2387. if (Bytes == 0)
  2388. return ConstantInt::get(CI->getType(), 0);
  2389. // If this is writing one byte, turn it into fputc.
  2390. // This optimisation is only valid, if the return value is unused.
  2391. if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
  2392. Value *Char = B.CreateLoad(B.getInt8Ty(),
  2393. castToCStr(CI->getArgOperand(0), B), "char");
  2394. Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI);
  2395. return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
  2396. }
  2397. }
  2398. return nullptr;
  2399. }
  2400. Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilderBase &B) {
  2401. optimizeErrorReporting(CI, B, 1);
  2402. // Don't rewrite fputs to fwrite when optimising for size because fwrite
  2403. // requires more arguments and thus extra MOVs are required.
  2404. bool OptForSize = CI->getFunction()->hasOptSize() ||
  2405. llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI,
  2406. PGSOQueryType::IRPass);
  2407. if (OptForSize)
  2408. return nullptr;
  2409. // We can't optimize if return value is used.
  2410. if (!CI->use_empty())
  2411. return nullptr;
  2412. // fputs(s,F) --> fwrite(s,strlen(s),1,F)
  2413. uint64_t Len = GetStringLength(CI->getArgOperand(0));
  2414. if (!Len)
  2415. return nullptr;
  2416. // Known to have no uses (see above).
  2417. return copyFlags(
  2418. *CI,
  2419. emitFWrite(CI->getArgOperand(0),
  2420. ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
  2421. CI->getArgOperand(1), B, DL, TLI));
  2422. }
  2423. Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilderBase &B) {
  2424. annotateNonNullNoUndefBasedOnAccess(CI, 0);
  2425. if (!CI->use_empty())
  2426. return nullptr;
  2427. // Check for a constant string.
  2428. // puts("") -> putchar('\n')
  2429. StringRef Str;
  2430. if (getConstantStringInfo(CI->getArgOperand(0), Str) && Str.empty())
  2431. return copyFlags(*CI, emitPutChar(B.getInt32('\n'), B, TLI));
  2432. return nullptr;
  2433. }
  2434. Value *LibCallSimplifier::optimizeBCopy(CallInst *CI, IRBuilderBase &B) {
  2435. // bcopy(src, dst, n) -> llvm.memmove(dst, src, n)
  2436. return copyFlags(*CI, B.CreateMemMove(CI->getArgOperand(1), Align(1),
  2437. CI->getArgOperand(0), Align(1),
  2438. CI->getArgOperand(2)));
  2439. }
  2440. bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
  2441. LibFunc Func;
  2442. SmallString<20> FloatFuncName = FuncName;
  2443. FloatFuncName += 'f';
  2444. if (TLI->getLibFunc(FloatFuncName, Func))
  2445. return TLI->has(Func);
  2446. return false;
  2447. }
  2448. Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
  2449. IRBuilderBase &Builder) {
  2450. LibFunc Func;
  2451. Function *Callee = CI->getCalledFunction();
  2452. // Check for string/memory library functions.
  2453. if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
  2454. // Make sure we never change the calling convention.
  2455. assert(
  2456. (ignoreCallingConv(Func) ||
  2457. TargetLibraryInfoImpl::isCallingConvCCompatible(CI)) &&
  2458. "Optimizing string/memory libcall would change the calling convention");
  2459. switch (Func) {
  2460. case LibFunc_strcat:
  2461. return optimizeStrCat(CI, Builder);
  2462. case LibFunc_strncat:
  2463. return optimizeStrNCat(CI, Builder);
  2464. case LibFunc_strchr:
  2465. return optimizeStrChr(CI, Builder);
  2466. case LibFunc_strrchr:
  2467. return optimizeStrRChr(CI, Builder);
  2468. case LibFunc_strcmp:
  2469. return optimizeStrCmp(CI, Builder);
  2470. case LibFunc_strncmp:
  2471. return optimizeStrNCmp(CI, Builder);
  2472. case LibFunc_strcpy:
  2473. return optimizeStrCpy(CI, Builder);
  2474. case LibFunc_stpcpy:
  2475. return optimizeStpCpy(CI, Builder);
  2476. case LibFunc_strncpy:
  2477. return optimizeStrNCpy(CI, Builder);
  2478. case LibFunc_strlen:
  2479. return optimizeStrLen(CI, Builder);
  2480. case LibFunc_strpbrk:
  2481. return optimizeStrPBrk(CI, Builder);
  2482. case LibFunc_strndup:
  2483. return optimizeStrNDup(CI, Builder);
  2484. case LibFunc_strtol:
  2485. case LibFunc_strtod:
  2486. case LibFunc_strtof:
  2487. case LibFunc_strtoul:
  2488. case LibFunc_strtoll:
  2489. case LibFunc_strtold:
  2490. case LibFunc_strtoull:
  2491. return optimizeStrTo(CI, Builder);
  2492. case LibFunc_strspn:
  2493. return optimizeStrSpn(CI, Builder);
  2494. case LibFunc_strcspn:
  2495. return optimizeStrCSpn(CI, Builder);
  2496. case LibFunc_strstr:
  2497. return optimizeStrStr(CI, Builder);
  2498. case LibFunc_memchr:
  2499. return optimizeMemChr(CI, Builder);
  2500. case LibFunc_memrchr:
  2501. return optimizeMemRChr(CI, Builder);
  2502. case LibFunc_bcmp:
  2503. return optimizeBCmp(CI, Builder);
  2504. case LibFunc_memcmp:
  2505. return optimizeMemCmp(CI, Builder);
  2506. case LibFunc_memcpy:
  2507. return optimizeMemCpy(CI, Builder);
  2508. case LibFunc_memccpy:
  2509. return optimizeMemCCpy(CI, Builder);
  2510. case LibFunc_mempcpy:
  2511. return optimizeMemPCpy(CI, Builder);
  2512. case LibFunc_memmove:
  2513. return optimizeMemMove(CI, Builder);
  2514. case LibFunc_memset:
  2515. return optimizeMemSet(CI, Builder);
  2516. case LibFunc_realloc:
  2517. return optimizeRealloc(CI, Builder);
  2518. case LibFunc_wcslen:
  2519. return optimizeWcslen(CI, Builder);
  2520. case LibFunc_bcopy:
  2521. return optimizeBCopy(CI, Builder);
  2522. default:
  2523. break;
  2524. }
  2525. }
  2526. return nullptr;
  2527. }
  2528. Value *LibCallSimplifier::optimizeFloatingPointLibCall(CallInst *CI,
  2529. LibFunc Func,
  2530. IRBuilderBase &Builder) {
  2531. // Don't optimize calls that require strict floating point semantics.
  2532. if (CI->isStrictFP())
  2533. return nullptr;
  2534. if (Value *V = optimizeTrigReflections(CI, Func, Builder))
  2535. return V;
  2536. switch (Func) {
  2537. case LibFunc_sinpif:
  2538. case LibFunc_sinpi:
  2539. case LibFunc_cospif:
  2540. case LibFunc_cospi:
  2541. return optimizeSinCosPi(CI, Builder);
  2542. case LibFunc_powf:
  2543. case LibFunc_pow:
  2544. case LibFunc_powl:
  2545. return optimizePow(CI, Builder);
  2546. case LibFunc_exp2l:
  2547. case LibFunc_exp2:
  2548. case LibFunc_exp2f:
  2549. return optimizeExp2(CI, Builder);
  2550. case LibFunc_fabsf:
  2551. case LibFunc_fabs:
  2552. case LibFunc_fabsl:
  2553. return replaceUnaryCall(CI, Builder, Intrinsic::fabs);
  2554. case LibFunc_sqrtf:
  2555. case LibFunc_sqrt:
  2556. case LibFunc_sqrtl:
  2557. return optimizeSqrt(CI, Builder);
  2558. case LibFunc_logf:
  2559. case LibFunc_log:
  2560. case LibFunc_logl:
  2561. case LibFunc_log10f:
  2562. case LibFunc_log10:
  2563. case LibFunc_log10l:
  2564. case LibFunc_log1pf:
  2565. case LibFunc_log1p:
  2566. case LibFunc_log1pl:
  2567. case LibFunc_log2f:
  2568. case LibFunc_log2:
  2569. case LibFunc_log2l:
  2570. case LibFunc_logbf:
  2571. case LibFunc_logb:
  2572. case LibFunc_logbl:
  2573. return optimizeLog(CI, Builder);
  2574. case LibFunc_tan:
  2575. case LibFunc_tanf:
  2576. case LibFunc_tanl:
  2577. return optimizeTan(CI, Builder);
  2578. case LibFunc_ceil:
  2579. return replaceUnaryCall(CI, Builder, Intrinsic::ceil);
  2580. case LibFunc_floor:
  2581. return replaceUnaryCall(CI, Builder, Intrinsic::floor);
  2582. case LibFunc_round:
  2583. return replaceUnaryCall(CI, Builder, Intrinsic::round);
  2584. case LibFunc_roundeven:
  2585. return replaceUnaryCall(CI, Builder, Intrinsic::roundeven);
  2586. case LibFunc_nearbyint:
  2587. return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint);
  2588. case LibFunc_rint:
  2589. return replaceUnaryCall(CI, Builder, Intrinsic::rint);
  2590. case LibFunc_trunc:
  2591. return replaceUnaryCall(CI, Builder, Intrinsic::trunc);
  2592. case LibFunc_acos:
  2593. case LibFunc_acosh:
  2594. case LibFunc_asin:
  2595. case LibFunc_asinh:
  2596. case LibFunc_atan:
  2597. case LibFunc_atanh:
  2598. case LibFunc_cbrt:
  2599. case LibFunc_cosh:
  2600. case LibFunc_exp:
  2601. case LibFunc_exp10:
  2602. case LibFunc_expm1:
  2603. case LibFunc_cos:
  2604. case LibFunc_sin:
  2605. case LibFunc_sinh:
  2606. case LibFunc_tanh:
  2607. if (UnsafeFPShrink && hasFloatVersion(CI->getCalledFunction()->getName()))
  2608. return optimizeUnaryDoubleFP(CI, Builder, true);
  2609. return nullptr;
  2610. case LibFunc_copysign:
  2611. if (hasFloatVersion(CI->getCalledFunction()->getName()))
  2612. return optimizeBinaryDoubleFP(CI, Builder);
  2613. return nullptr;
  2614. case LibFunc_fminf:
  2615. case LibFunc_fmin:
  2616. case LibFunc_fminl:
  2617. case LibFunc_fmaxf:
  2618. case LibFunc_fmax:
  2619. case LibFunc_fmaxl:
  2620. return optimizeFMinFMax(CI, Builder);
  2621. case LibFunc_cabs:
  2622. case LibFunc_cabsf:
  2623. case LibFunc_cabsl:
  2624. return optimizeCAbs(CI, Builder);
  2625. default:
  2626. return nullptr;
  2627. }
  2628. }
  2629. Value *LibCallSimplifier::optimizeCall(CallInst *CI, IRBuilderBase &Builder) {
  2630. assert(!CI->isMustTailCall() && "These transforms aren't musttail safe.");
  2631. // TODO: Split out the code below that operates on FP calls so that
  2632. // we can all non-FP calls with the StrictFP attribute to be
  2633. // optimized.
  2634. if (CI->isNoBuiltin())
  2635. return nullptr;
  2636. LibFunc Func;
  2637. Function *Callee = CI->getCalledFunction();
  2638. bool IsCallingConvC = TargetLibraryInfoImpl::isCallingConvCCompatible(CI);
  2639. SmallVector<OperandBundleDef, 2> OpBundles;
  2640. CI->getOperandBundlesAsDefs(OpBundles);
  2641. IRBuilderBase::OperandBundlesGuard Guard(Builder);
  2642. Builder.setDefaultOperandBundles(OpBundles);
  2643. // Command-line parameter overrides instruction attribute.
  2644. // This can't be moved to optimizeFloatingPointLibCall() because it may be
  2645. // used by the intrinsic optimizations.
  2646. if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
  2647. UnsafeFPShrink = EnableUnsafeFPShrink;
  2648. else if (isa<FPMathOperator>(CI) && CI->isFast())
  2649. UnsafeFPShrink = true;
  2650. // First, check for intrinsics.
  2651. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
  2652. if (!IsCallingConvC)
  2653. return nullptr;
  2654. // The FP intrinsics have corresponding constrained versions so we don't
  2655. // need to check for the StrictFP attribute here.
  2656. switch (II->getIntrinsicID()) {
  2657. case Intrinsic::pow:
  2658. return optimizePow(CI, Builder);
  2659. case Intrinsic::exp2:
  2660. return optimizeExp2(CI, Builder);
  2661. case Intrinsic::log:
  2662. case Intrinsic::log2:
  2663. case Intrinsic::log10:
  2664. return optimizeLog(CI, Builder);
  2665. case Intrinsic::sqrt:
  2666. return optimizeSqrt(CI, Builder);
  2667. case Intrinsic::memset:
  2668. return optimizeMemSet(CI, Builder);
  2669. case Intrinsic::memcpy:
  2670. return optimizeMemCpy(CI, Builder);
  2671. case Intrinsic::memmove:
  2672. return optimizeMemMove(CI, Builder);
  2673. default:
  2674. return nullptr;
  2675. }
  2676. }
  2677. // Also try to simplify calls to fortified library functions.
  2678. if (Value *SimplifiedFortifiedCI =
  2679. FortifiedSimplifier.optimizeCall(CI, Builder)) {
  2680. // Try to further simplify the result.
  2681. CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
  2682. if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
  2683. // Ensure that SimplifiedCI's uses are complete, since some calls have
  2684. // their uses analyzed.
  2685. replaceAllUsesWith(CI, SimplifiedCI);
  2686. // Set insertion point to SimplifiedCI to guarantee we reach all uses
  2687. // we might replace later on.
  2688. IRBuilderBase::InsertPointGuard Guard(Builder);
  2689. Builder.SetInsertPoint(SimplifiedCI);
  2690. if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, Builder)) {
  2691. // If we were able to further simplify, remove the now redundant call.
  2692. substituteInParent(SimplifiedCI, V);
  2693. return V;
  2694. }
  2695. }
  2696. return SimplifiedFortifiedCI;
  2697. }
  2698. // Then check for known library functions.
  2699. if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
  2700. // We never change the calling convention.
  2701. if (!ignoreCallingConv(Func) && !IsCallingConvC)
  2702. return nullptr;
  2703. if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
  2704. return V;
  2705. if (Value *V = optimizeFloatingPointLibCall(CI, Func, Builder))
  2706. return V;
  2707. switch (Func) {
  2708. case LibFunc_ffs:
  2709. case LibFunc_ffsl:
  2710. case LibFunc_ffsll:
  2711. return optimizeFFS(CI, Builder);
  2712. case LibFunc_fls:
  2713. case LibFunc_flsl:
  2714. case LibFunc_flsll:
  2715. return optimizeFls(CI, Builder);
  2716. case LibFunc_abs:
  2717. case LibFunc_labs:
  2718. case LibFunc_llabs:
  2719. return optimizeAbs(CI, Builder);
  2720. case LibFunc_isdigit:
  2721. return optimizeIsDigit(CI, Builder);
  2722. case LibFunc_isascii:
  2723. return optimizeIsAscii(CI, Builder);
  2724. case LibFunc_toascii:
  2725. return optimizeToAscii(CI, Builder);
  2726. case LibFunc_atoi:
  2727. case LibFunc_atol:
  2728. case LibFunc_atoll:
  2729. return optimizeAtoi(CI, Builder);
  2730. case LibFunc_strtol:
  2731. case LibFunc_strtoll:
  2732. return optimizeStrtol(CI, Builder);
  2733. case LibFunc_printf:
  2734. return optimizePrintF(CI, Builder);
  2735. case LibFunc_sprintf:
  2736. return optimizeSPrintF(CI, Builder);
  2737. case LibFunc_snprintf:
  2738. return optimizeSnPrintF(CI, Builder);
  2739. case LibFunc_fprintf:
  2740. return optimizeFPrintF(CI, Builder);
  2741. case LibFunc_fwrite:
  2742. return optimizeFWrite(CI, Builder);
  2743. case LibFunc_fputs:
  2744. return optimizeFPuts(CI, Builder);
  2745. case LibFunc_puts:
  2746. return optimizePuts(CI, Builder);
  2747. case LibFunc_perror:
  2748. return optimizeErrorReporting(CI, Builder);
  2749. case LibFunc_vfprintf:
  2750. case LibFunc_fiprintf:
  2751. return optimizeErrorReporting(CI, Builder, 0);
  2752. default:
  2753. return nullptr;
  2754. }
  2755. }
  2756. return nullptr;
  2757. }
  2758. LibCallSimplifier::LibCallSimplifier(
  2759. const DataLayout &DL, const TargetLibraryInfo *TLI,
  2760. OptimizationRemarkEmitter &ORE,
  2761. BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
  2762. function_ref<void(Instruction *, Value *)> Replacer,
  2763. function_ref<void(Instruction *)> Eraser)
  2764. : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), ORE(ORE), BFI(BFI), PSI(PSI),
  2765. UnsafeFPShrink(false), Replacer(Replacer), Eraser(Eraser) {}
  2766. void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
  2767. // Indirect through the replacer used in this instance.
  2768. Replacer(I, With);
  2769. }
  2770. void LibCallSimplifier::eraseFromParent(Instruction *I) {
  2771. Eraser(I);
  2772. }
  2773. // TODO:
  2774. // Additional cases that we need to add to this file:
  2775. //
  2776. // cbrt:
  2777. // * cbrt(expN(X)) -> expN(x/3)
  2778. // * cbrt(sqrt(x)) -> pow(x,1/6)
  2779. // * cbrt(cbrt(x)) -> pow(x,1/9)
  2780. //
  2781. // exp, expf, expl:
  2782. // * exp(log(x)) -> x
  2783. //
  2784. // log, logf, logl:
  2785. // * log(exp(x)) -> x
  2786. // * log(exp(y)) -> y*log(e)
  2787. // * log(exp10(y)) -> y*log(10)
  2788. // * log(sqrt(x)) -> 0.5*log(x)
  2789. //
  2790. // pow, powf, powl:
  2791. // * pow(sqrt(x),y) -> pow(x,y*0.5)
  2792. // * pow(pow(x,y),z)-> pow(x,y*z)
  2793. //
  2794. // signbit:
  2795. // * signbit(cnst) -> cnst'
  2796. // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
  2797. //
  2798. // sqrt, sqrtf, sqrtl:
  2799. // * sqrt(expN(x)) -> expN(x*0.5)
  2800. // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
  2801. // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
  2802. //
  2803. //===----------------------------------------------------------------------===//
  2804. // Fortified Library Call Optimizations
  2805. //===----------------------------------------------------------------------===//
  2806. bool
  2807. FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
  2808. unsigned ObjSizeOp,
  2809. Optional<unsigned> SizeOp,
  2810. Optional<unsigned> StrOp,
  2811. Optional<unsigned> FlagOp) {
  2812. // If this function takes a flag argument, the implementation may use it to
  2813. // perform extra checks. Don't fold into the non-checking variant.
  2814. if (FlagOp) {
  2815. ConstantInt *Flag = dyn_cast<ConstantInt>(CI->getArgOperand(*FlagOp));
  2816. if (!Flag || !Flag->isZero())
  2817. return false;
  2818. }
  2819. if (SizeOp && CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(*SizeOp))
  2820. return true;
  2821. if (ConstantInt *ObjSizeCI =
  2822. dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
  2823. if (ObjSizeCI->isMinusOne())
  2824. return true;
  2825. // If the object size wasn't -1 (unknown), bail out if we were asked to.
  2826. if (OnlyLowerUnknownSize)
  2827. return false;
  2828. if (StrOp) {
  2829. uint64_t Len = GetStringLength(CI->getArgOperand(*StrOp));
  2830. // If the length is 0 we don't know how long it is and so we can't
  2831. // remove the check.
  2832. if (Len)
  2833. annotateDereferenceableBytes(CI, *StrOp, Len);
  2834. else
  2835. return false;
  2836. return ObjSizeCI->getZExtValue() >= Len;
  2837. }
  2838. if (SizeOp) {
  2839. if (ConstantInt *SizeCI =
  2840. dyn_cast<ConstantInt>(CI->getArgOperand(*SizeOp)))
  2841. return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
  2842. }
  2843. }
  2844. return false;
  2845. }
  2846. Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
  2847. IRBuilderBase &B) {
  2848. if (isFortifiedCallFoldable(CI, 3, 2)) {
  2849. CallInst *NewCI =
  2850. B.CreateMemCpy(CI->getArgOperand(0), Align(1), CI->getArgOperand(1),
  2851. Align(1), CI->getArgOperand(2));
  2852. NewCI->setAttributes(CI->getAttributes());
  2853. NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(NewCI->getType()));
  2854. copyFlags(*CI, NewCI);
  2855. return CI->getArgOperand(0);
  2856. }
  2857. return nullptr;
  2858. }
  2859. Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
  2860. IRBuilderBase &B) {
  2861. if (isFortifiedCallFoldable(CI, 3, 2)) {
  2862. CallInst *NewCI =
  2863. B.CreateMemMove(CI->getArgOperand(0), Align(1), CI->getArgOperand(1),
  2864. Align(1), CI->getArgOperand(2));
  2865. NewCI->setAttributes(CI->getAttributes());
  2866. NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(NewCI->getType()));
  2867. copyFlags(*CI, NewCI);
  2868. return CI->getArgOperand(0);
  2869. }
  2870. return nullptr;
  2871. }
  2872. Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
  2873. IRBuilderBase &B) {
  2874. if (isFortifiedCallFoldable(CI, 3, 2)) {
  2875. Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
  2876. CallInst *NewCI = B.CreateMemSet(CI->getArgOperand(0), Val,
  2877. CI->getArgOperand(2), Align(1));
  2878. NewCI->setAttributes(CI->getAttributes());
  2879. NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(NewCI->getType()));
  2880. copyFlags(*CI, NewCI);
  2881. return CI->getArgOperand(0);
  2882. }
  2883. return nullptr;
  2884. }
  2885. Value *FortifiedLibCallSimplifier::optimizeMemPCpyChk(CallInst *CI,
  2886. IRBuilderBase &B) {
  2887. const DataLayout &DL = CI->getModule()->getDataLayout();
  2888. if (isFortifiedCallFoldable(CI, 3, 2))
  2889. if (Value *Call = emitMemPCpy(CI->getArgOperand(0), CI->getArgOperand(1),
  2890. CI->getArgOperand(2), B, DL, TLI)) {
  2891. CallInst *NewCI = cast<CallInst>(Call);
  2892. NewCI->setAttributes(CI->getAttributes());
  2893. NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(NewCI->getType()));
  2894. return copyFlags(*CI, NewCI);
  2895. }
  2896. return nullptr;
  2897. }
  2898. Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
  2899. IRBuilderBase &B,
  2900. LibFunc Func) {
  2901. const DataLayout &DL = CI->getModule()->getDataLayout();
  2902. Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
  2903. *ObjSize = CI->getArgOperand(2);
  2904. // __stpcpy_chk(x,x,...) -> x+strlen(x)
  2905. if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
  2906. Value *StrLen = emitStrLen(Src, B, DL, TLI);
  2907. return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
  2908. }
  2909. // If a) we don't have any length information, or b) we know this will
  2910. // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
  2911. // st[rp]cpy_chk call which may fail at runtime if the size is too long.
  2912. // TODO: It might be nice to get a maximum length out of the possible
  2913. // string lengths for varying.
  2914. if (isFortifiedCallFoldable(CI, 2, None, 1)) {
  2915. if (Func == LibFunc_strcpy_chk)
  2916. return copyFlags(*CI, emitStrCpy(Dst, Src, B, TLI));
  2917. else
  2918. return copyFlags(*CI, emitStpCpy(Dst, Src, B, TLI));
  2919. }
  2920. if (OnlyLowerUnknownSize)
  2921. return nullptr;
  2922. // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
  2923. uint64_t Len = GetStringLength(Src);
  2924. if (Len)
  2925. annotateDereferenceableBytes(CI, 1, Len);
  2926. else
  2927. return nullptr;
  2928. // FIXME: There is really no guarantee that sizeof(size_t) is equal to
  2929. // sizeof(int*) for every target. So the assumption used here to derive the
  2930. // SizeTBits based on the size of an integer pointer in address space zero
  2931. // isn't always valid.
  2932. Type *SizeTTy = DL.getIntPtrType(CI->getContext(), /*AddressSpace=*/0);
  2933. Value *LenV = ConstantInt::get(SizeTTy, Len);
  2934. Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
  2935. // If the function was an __stpcpy_chk, and we were able to fold it into
  2936. // a __memcpy_chk, we still need to return the correct end pointer.
  2937. if (Ret && Func == LibFunc_stpcpy_chk)
  2938. return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
  2939. return copyFlags(*CI, cast<CallInst>(Ret));
  2940. }
  2941. Value *FortifiedLibCallSimplifier::optimizeStrLenChk(CallInst *CI,
  2942. IRBuilderBase &B) {
  2943. if (isFortifiedCallFoldable(CI, 1, None, 0))
  2944. return copyFlags(*CI, emitStrLen(CI->getArgOperand(0), B,
  2945. CI->getModule()->getDataLayout(), TLI));
  2946. return nullptr;
  2947. }
  2948. Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
  2949. IRBuilderBase &B,
  2950. LibFunc Func) {
  2951. if (isFortifiedCallFoldable(CI, 3, 2)) {
  2952. if (Func == LibFunc_strncpy_chk)
  2953. return copyFlags(*CI,
  2954. emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
  2955. CI->getArgOperand(2), B, TLI));
  2956. else
  2957. return copyFlags(*CI,
  2958. emitStpNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
  2959. CI->getArgOperand(2), B, TLI));
  2960. }
  2961. return nullptr;
  2962. }
  2963. Value *FortifiedLibCallSimplifier::optimizeMemCCpyChk(CallInst *CI,
  2964. IRBuilderBase &B) {
  2965. if (isFortifiedCallFoldable(CI, 4, 3))
  2966. return copyFlags(
  2967. *CI, emitMemCCpy(CI->getArgOperand(0), CI->getArgOperand(1),
  2968. CI->getArgOperand(2), CI->getArgOperand(3), B, TLI));
  2969. return nullptr;
  2970. }
  2971. Value *FortifiedLibCallSimplifier::optimizeSNPrintfChk(CallInst *CI,
  2972. IRBuilderBase &B) {
  2973. if (isFortifiedCallFoldable(CI, 3, 1, None, 2)) {
  2974. SmallVector<Value *, 8> VariadicArgs(drop_begin(CI->args(), 5));
  2975. return copyFlags(*CI,
  2976. emitSNPrintf(CI->getArgOperand(0), CI->getArgOperand(1),
  2977. CI->getArgOperand(4), VariadicArgs, B, TLI));
  2978. }
  2979. return nullptr;
  2980. }
  2981. Value *FortifiedLibCallSimplifier::optimizeSPrintfChk(CallInst *CI,
  2982. IRBuilderBase &B) {
  2983. if (isFortifiedCallFoldable(CI, 2, None, None, 1)) {
  2984. SmallVector<Value *, 8> VariadicArgs(drop_begin(CI->args(), 4));
  2985. return copyFlags(*CI,
  2986. emitSPrintf(CI->getArgOperand(0), CI->getArgOperand(3),
  2987. VariadicArgs, B, TLI));
  2988. }
  2989. return nullptr;
  2990. }
  2991. Value *FortifiedLibCallSimplifier::optimizeStrCatChk(CallInst *CI,
  2992. IRBuilderBase &B) {
  2993. if (isFortifiedCallFoldable(CI, 2))
  2994. return copyFlags(
  2995. *CI, emitStrCat(CI->getArgOperand(0), CI->getArgOperand(1), B, TLI));
  2996. return nullptr;
  2997. }
  2998. Value *FortifiedLibCallSimplifier::optimizeStrLCat(CallInst *CI,
  2999. IRBuilderBase &B) {
  3000. if (isFortifiedCallFoldable(CI, 3))
  3001. return copyFlags(*CI,
  3002. emitStrLCat(CI->getArgOperand(0), CI->getArgOperand(1),
  3003. CI->getArgOperand(2), B, TLI));
  3004. return nullptr;
  3005. }
  3006. Value *FortifiedLibCallSimplifier::optimizeStrNCatChk(CallInst *CI,
  3007. IRBuilderBase &B) {
  3008. if (isFortifiedCallFoldable(CI, 3))
  3009. return copyFlags(*CI,
  3010. emitStrNCat(CI->getArgOperand(0), CI->getArgOperand(1),
  3011. CI->getArgOperand(2), B, TLI));
  3012. return nullptr;
  3013. }
  3014. Value *FortifiedLibCallSimplifier::optimizeStrLCpyChk(CallInst *CI,
  3015. IRBuilderBase &B) {
  3016. if (isFortifiedCallFoldable(CI, 3))
  3017. return copyFlags(*CI,
  3018. emitStrLCpy(CI->getArgOperand(0), CI->getArgOperand(1),
  3019. CI->getArgOperand(2), B, TLI));
  3020. return nullptr;
  3021. }
  3022. Value *FortifiedLibCallSimplifier::optimizeVSNPrintfChk(CallInst *CI,
  3023. IRBuilderBase &B) {
  3024. if (isFortifiedCallFoldable(CI, 3, 1, None, 2))
  3025. return copyFlags(
  3026. *CI, emitVSNPrintf(CI->getArgOperand(0), CI->getArgOperand(1),
  3027. CI->getArgOperand(4), CI->getArgOperand(5), B, TLI));
  3028. return nullptr;
  3029. }
  3030. Value *FortifiedLibCallSimplifier::optimizeVSPrintfChk(CallInst *CI,
  3031. IRBuilderBase &B) {
  3032. if (isFortifiedCallFoldable(CI, 2, None, None, 1))
  3033. return copyFlags(*CI,
  3034. emitVSPrintf(CI->getArgOperand(0), CI->getArgOperand(3),
  3035. CI->getArgOperand(4), B, TLI));
  3036. return nullptr;
  3037. }
  3038. Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI,
  3039. IRBuilderBase &Builder) {
  3040. // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
  3041. // Some clang users checked for _chk libcall availability using:
  3042. // __has_builtin(__builtin___memcpy_chk)
  3043. // When compiling with -fno-builtin, this is always true.
  3044. // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
  3045. // end up with fortified libcalls, which isn't acceptable in a freestanding
  3046. // environment which only provides their non-fortified counterparts.
  3047. //
  3048. // Until we change clang and/or teach external users to check for availability
  3049. // differently, disregard the "nobuiltin" attribute and TLI::has.
  3050. //
  3051. // PR23093.
  3052. LibFunc Func;
  3053. Function *Callee = CI->getCalledFunction();
  3054. bool IsCallingConvC = TargetLibraryInfoImpl::isCallingConvCCompatible(CI);
  3055. SmallVector<OperandBundleDef, 2> OpBundles;
  3056. CI->getOperandBundlesAsDefs(OpBundles);
  3057. IRBuilderBase::OperandBundlesGuard Guard(Builder);
  3058. Builder.setDefaultOperandBundles(OpBundles);
  3059. // First, check that this is a known library functions and that the prototype
  3060. // is correct.
  3061. if (!TLI->getLibFunc(*Callee, Func))
  3062. return nullptr;
  3063. // We never change the calling convention.
  3064. if (!ignoreCallingConv(Func) && !IsCallingConvC)
  3065. return nullptr;
  3066. switch (Func) {
  3067. case LibFunc_memcpy_chk:
  3068. return optimizeMemCpyChk(CI, Builder);
  3069. case LibFunc_mempcpy_chk:
  3070. return optimizeMemPCpyChk(CI, Builder);
  3071. case LibFunc_memmove_chk:
  3072. return optimizeMemMoveChk(CI, Builder);
  3073. case LibFunc_memset_chk:
  3074. return optimizeMemSetChk(CI, Builder);
  3075. case LibFunc_stpcpy_chk:
  3076. case LibFunc_strcpy_chk:
  3077. return optimizeStrpCpyChk(CI, Builder, Func);
  3078. case LibFunc_strlen_chk:
  3079. return optimizeStrLenChk(CI, Builder);
  3080. case LibFunc_stpncpy_chk:
  3081. case LibFunc_strncpy_chk:
  3082. return optimizeStrpNCpyChk(CI, Builder, Func);
  3083. case LibFunc_memccpy_chk:
  3084. return optimizeMemCCpyChk(CI, Builder);
  3085. case LibFunc_snprintf_chk:
  3086. return optimizeSNPrintfChk(CI, Builder);
  3087. case LibFunc_sprintf_chk:
  3088. return optimizeSPrintfChk(CI, Builder);
  3089. case LibFunc_strcat_chk:
  3090. return optimizeStrCatChk(CI, Builder);
  3091. case LibFunc_strlcat_chk:
  3092. return optimizeStrLCat(CI, Builder);
  3093. case LibFunc_strncat_chk:
  3094. return optimizeStrNCatChk(CI, Builder);
  3095. case LibFunc_strlcpy_chk:
  3096. return optimizeStrLCpyChk(CI, Builder);
  3097. case LibFunc_vsnprintf_chk:
  3098. return optimizeVSNPrintfChk(CI, Builder);
  3099. case LibFunc_vsprintf_chk:
  3100. return optimizeVSPrintfChk(CI, Builder);
  3101. default:
  3102. break;
  3103. }
  3104. return nullptr;
  3105. }
  3106. FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
  3107. const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
  3108. : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}