blob: 2a9da59a6e90dba90a5beacbb4df950bc1800dff [file] [log] [blame]
Meador Ingedf796f82012-10-13 16:45:24 +00001//===------ SimplifyLibCalls.cpp - Library calls simplifier ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Craig Topper2915bc02018-03-01 20:05:09 +000010// This file implements the library calls simplifier. It does not implement
11// any pass, but can't be used by other passes to do simplifications.
Meador Ingedf796f82012-10-13 16:45:24 +000012//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Meador Inge20255ef2013-03-12 00:08:29 +000016#include "llvm/ADT/SmallString.h"
Meador Ingedf796f82012-10-13 16:45:24 +000017#include "llvm/ADT/StringMap.h"
Bob Wilsond8d92d92013-11-03 06:48:38 +000018#include "llvm/ADT/Triple.h"
Sanjay Patel82ec8722017-08-21 19:13:14 +000019#include "llvm/Analysis/ConstantFolding.h"
Adam Nemet0965da22017-10-09 23:19:02 +000020#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000021#include "llvm/Analysis/TargetLibraryInfo.h"
David Blaikie31b98d22018-06-04 21:23:21 +000022#include "llvm/Transforms/Utils/Local.h"
Meador Ingedf796f82012-10-13 16:45:24 +000023#include "llvm/Analysis/ValueTracking.h"
David Bolvanskyca22d422018-05-16 11:39:52 +000024#include "llvm/Analysis/CaptureTracking.h"
David Bolvansky909889b2018-08-10 04:32:54 +000025#include "llvm/Analysis/Loads.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/Function.h"
28#include "llvm/IR/IRBuilder.h"
Meador Inge20255ef2013-03-12 00:08:29 +000029#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/Intrinsics.h"
31#include "llvm/IR/LLVMContext.h"
32#include "llvm/IR/Module.h"
Sanjay Patelc699a612014-10-16 18:48:17 +000033#include "llvm/IR/PatternMatch.h"
Hal Finkel66cd3f12013-11-17 02:06:35 +000034#include "llvm/Support/CommandLine.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000035#include "llvm/Support/KnownBits.h"
Meador Ingedf796f82012-10-13 16:45:24 +000036#include "llvm/Transforms/Utils/BuildLibCalls.h"
37
38using namespace llvm;
Sanjay Patelc699a612014-10-16 18:48:17 +000039using namespace PatternMatch;
Meador Ingedf796f82012-10-13 16:45:24 +000040
Hal Finkel66cd3f12013-11-17 02:06:35 +000041static cl::opt<bool>
Sanjay Patela92fa442014-10-22 15:29:23 +000042 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
Meador Ingedf796f82012-10-13 16:45:24 +000048//===----------------------------------------------------------------------===//
Meador Inged589ac62012-10-31 03:33:06 +000049// Helper Functions
50//===----------------------------------------------------------------------===//
51
David L. Jonesd21529f2017-01-23 23:16:46 +000052static bool ignoreCallingConv(LibFunc Func) {
53 return Func == LibFunc_abs || Func == LibFunc_labs ||
54 Func == LibFunc_llabs || Func == LibFunc_strlen;
Chris Bienemanad070d02014-09-17 20:55:46 +000055}
56
Sam Parker214f7bf2016-09-13 12:10:14 +000057static bool isCallingConvCCompatible(CallInst *CI) {
58 switch(CI->getCallingConv()) {
59 default:
60 return false;
61 case llvm::CallingConv::C:
62 return true;
63 case llvm::CallingConv::ARM_APCS:
64 case llvm::CallingConv::ARM_AAPCS:
65 case llvm::CallingConv::ARM_AAPCS_VFP: {
66
67 // The iOS ABI diverges from the standard in some cases, so for now don't
68 // try to simplify those calls.
69 if (Triple(CI->getModule()->getTargetTriple()).isiOS())
70 return false;
71
72 auto *FuncTy = CI->getFunctionType();
73
74 if (!FuncTy->getReturnType()->isPointerTy() &&
75 !FuncTy->getReturnType()->isIntegerTy() &&
76 !FuncTy->getReturnType()->isVoidTy())
77 return false;
78
79 for (auto Param : FuncTy->params()) {
80 if (!Param->isPointerTy() && !Param->isIntegerTy())
81 return false;
82 }
83 return true;
84 }
85 }
86 return false;
87}
88
Sanjay Pateld707db92015-12-31 16:10:49 +000089/// Return true if it is only used in equality comparisons with With.
Meador Inge56edbc92012-11-11 03:51:48 +000090static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000091 for (User *U : V->users()) {
92 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inge56edbc92012-11-11 03:51:48 +000093 if (IC->isEquality() && IC->getOperand(1) == With)
94 continue;
95 // Unknown instruction.
96 return false;
97 }
98 return true;
99}
100
Meador Inge08ca1152012-11-26 20:37:20 +0000101static bool callHasFloatingPointArgument(const CallInst *CI) {
David Majnemer0a16c222016-08-11 21:15:00 +0000102 return any_of(CI->operands(), [](const Use &OI) {
Davide Italianoda3beeb2015-11-28 22:27:48 +0000103 return OI->getType()->isFloatingPointTy();
104 });
Meador Inge08ca1152012-11-26 20:37:20 +0000105}
106
David Bolvanskycb8ca5f32018-04-25 18:58:53 +0000107static Value *convertStrToNumber(CallInst *CI, StringRef &Str, int64_t Base) {
108 if (Base < 2 || Base > 36)
109 // handle special zero base
110 if (Base != 0)
111 return nullptr;
112
113 char *End;
114 std::string nptr = Str.str();
115 errno = 0;
116 long long int Result = strtoll(nptr.c_str(), &End, Base);
117 if (errno)
118 return nullptr;
119
120 // if we assume all possible target locales are ASCII supersets,
121 // then if strtoll successfully parses a number on the host,
122 // it will also successfully parse the same way on the target
123 if (*End != '\0')
124 return nullptr;
125
126 if (!isIntN(CI->getType()->getPrimitiveSizeInBits(), Result))
127 return nullptr;
128
129 return ConstantInt::get(CI->getType(), Result);
130}
131
David Bolvanskyca22d422018-05-16 11:39:52 +0000132static bool isLocallyOpenedFile(Value *File, CallInst *CI, IRBuilder<> &B,
133 const TargetLibraryInfo *TLI) {
134 CallInst *FOpen = dyn_cast<CallInst>(File);
135 if (!FOpen)
136 return false;
137
138 Function *InnerCallee = FOpen->getCalledFunction();
139 if (!InnerCallee)
140 return false;
141
142 LibFunc Func;
143 if (!TLI->getLibFunc(*InnerCallee, Func) || !TLI->has(Func) ||
144 Func != LibFunc_fopen)
145 return false;
146
147 inferLibFuncAttributes(*CI->getCalledFunction(), *TLI);
148 if (PointerMayBeCaptured(File, true, true))
149 return false;
150
151 return true;
152}
153
David Bolvansky909889b2018-08-10 04:32:54 +0000154static bool isOnlyUsedInComparisonWithZero(Value *V) {
155 for (User *U : V->users()) {
156 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
157 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
158 if (C->isNullValue())
159 continue;
160 // Unknown instruction.
161 return false;
162 }
163 return true;
164}
165
166static bool canTransformToMemCmp(CallInst *CI, Value *Str, uint64_t Len,
167 const DataLayout &DL) {
168 if (!isOnlyUsedInComparisonWithZero(CI))
169 return false;
170
171 if (!isDereferenceableAndAlignedPointer(Str, 1, APInt(64, Len), DL))
172 return false;
173
174 return true;
175}
176
Meador Inged589ac62012-10-31 03:33:06 +0000177//===----------------------------------------------------------------------===//
Meador Inge7fb2f732012-10-13 16:45:32 +0000178// String and Memory Library Call Optimizations
179//===----------------------------------------------------------------------===//
180
Chris Bienemanad070d02014-09-17 20:55:46 +0000181Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000182 // Extract some information from the instruction
183 Value *Dst = CI->getArgOperand(0);
184 Value *Src = CI->getArgOperand(1);
185
186 // See if we can get the length of the input string.
David Bolvansky1f343fa2018-05-22 20:27:36 +0000187 uint64_t Len = GetStringLength(Src);
Chris Bienemanad070d02014-09-17 20:55:46 +0000188 if (Len == 0)
189 return nullptr;
190 --Len; // Unbias length.
191
192 // Handle the simple, do-nothing case: strcat(x, "") -> x
193 if (Len == 0)
194 return Dst;
195
Chris Bienemanad070d02014-09-17 20:55:46 +0000196 return emitStrLenMemCpy(Src, Dst, Len, B);
197}
198
199Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
200 IRBuilder<> &B) {
201 // We need to find the end of the destination string. That's where the
202 // memory is to be moved to. We just generate a call to strlen.
Sanjay Pateld3112a52016-01-19 19:46:10 +0000203 Value *DstLen = emitStrLen(Dst, B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000204 if (!DstLen)
205 return nullptr;
206
207 // Now that we have the destination's length, we must index into the
208 // destination's pointer to get the actual memcpy destination (end of
209 // the string .. we're concatenating).
David Blaikie3909da72015-03-30 20:42:56 +0000210 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000211
212 // We have enough information to now generate the memcpy call to do the
213 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000214 B.CreateMemCpy(CpyDst, 1, Src, 1,
215 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000216 return Dst;
217}
218
219Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
Sanjay Pateld707db92015-12-31 16:10:49 +0000220 // Extract some information from the instruction.
Chris Bienemanad070d02014-09-17 20:55:46 +0000221 Value *Dst = CI->getArgOperand(0);
222 Value *Src = CI->getArgOperand(1);
223 uint64_t Len;
224
Sanjay Pateld707db92015-12-31 16:10:49 +0000225 // We don't do anything if length is not constant.
Chris Bienemanad070d02014-09-17 20:55:46 +0000226 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
227 Len = LengthArg->getZExtValue();
228 else
229 return nullptr;
230
231 // See if we can get the length of the input string.
David Bolvansky1f343fa2018-05-22 20:27:36 +0000232 uint64_t SrcLen = GetStringLength(Src);
Chris Bienemanad070d02014-09-17 20:55:46 +0000233 if (SrcLen == 0)
234 return nullptr;
235 --SrcLen; // Unbias length.
236
237 // Handle the simple, do-nothing cases:
238 // strncat(x, "", c) -> x
239 // strncat(x, c, 0) -> x
240 if (SrcLen == 0 || Len == 0)
241 return Dst;
242
Sanjay Pateld707db92015-12-31 16:10:49 +0000243 // We don't optimize this case.
Chris Bienemanad070d02014-09-17 20:55:46 +0000244 if (Len < SrcLen)
245 return nullptr;
246
247 // strncat(x, s, c) -> strcat(x, s)
Sanjay Pateld707db92015-12-31 16:10:49 +0000248 // s is constant so the strcat can be optimized further.
Chris Bienemanad070d02014-09-17 20:55:46 +0000249 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
250}
251
252Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
253 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000254 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +0000255 Value *SrcStr = CI->getArgOperand(0);
256
257 // If the second operand is non-constant, see if we can compute the length
258 // of the input string and turn this into memchr.
259 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
260 if (!CharC) {
David Bolvansky1f343fa2018-05-22 20:27:36 +0000261 uint64_t Len = GetStringLength(SrcStr);
Chris Bienemanad070d02014-09-17 20:55:46 +0000262 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
263 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000264
Sanjay Pateld3112a52016-01-19 19:46:10 +0000265 return emitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000266 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
267 B, DL, TLI);
Meador Inge7fb2f732012-10-13 16:45:32 +0000268 }
269
Chris Bienemanad070d02014-09-17 20:55:46 +0000270 // Otherwise, the character is a constant, see if the first argument is
271 // a string literal. If so, we can constant fold.
272 StringRef Str;
273 if (!getConstantStringInfo(SrcStr, Str)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000274 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000275 return B.CreateGEP(B.getInt8Ty(), SrcStr, emitStrLen(SrcStr, B, DL, TLI),
Sanjay Pateld707db92015-12-31 16:10:49 +0000276 "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000277 return nullptr;
278 }
279
280 // Compute the offset, make sure to handle the case when we're searching for
281 // zero (a weird way to spell strlen).
282 size_t I = (0xFF & CharC->getSExtValue()) == 0
283 ? Str.size()
284 : Str.find(CharC->getSExtValue());
285 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
286 return Constant::getNullValue(CI->getType());
287
288 // strchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000289 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000290}
291
292Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000293 Value *SrcStr = CI->getArgOperand(0);
294 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
295
296 // Cannot fold anything if we're not looking for a constant.
297 if (!CharC)
298 return nullptr;
299
300 StringRef Str;
301 if (!getConstantStringInfo(SrcStr, Str)) {
302 // strrchr(s, 0) -> strchr(s, 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000303 if (CharC->isZero())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000304 return emitStrChr(SrcStr, '\0', B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000305 return nullptr;
306 }
307
308 // Compute the offset.
309 size_t I = (0xFF & CharC->getSExtValue()) == 0
310 ? Str.size()
311 : Str.rfind(CharC->getSExtValue());
312 if (I == StringRef::npos) // Didn't find the char. Return null.
313 return Constant::getNullValue(CI->getType());
314
315 // strrchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000316 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000317}
318
319Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000320 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
321 if (Str1P == Str2P) // strcmp(x,x) -> 0
322 return ConstantInt::get(CI->getType(), 0);
323
324 StringRef Str1, Str2;
325 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
326 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
327
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
332 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
333 return B.CreateNeg(
334 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
335
336 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
337 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
338
339 // strcmp(P, "x") -> memcmp(P, "x", 2)
David Bolvansky1f343fa2018-05-22 20:27:36 +0000340 uint64_t Len1 = GetStringLength(Str1P);
341 uint64_t Len2 = GetStringLength(Str2P);
Chris Bienemanad070d02014-09-17 20:55:46 +0000342 if (Len1 && Len2) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000343 return emitMemCmp(Str1P, Str2P,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000344 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
Chris Bienemanad070d02014-09-17 20:55:46 +0000345 std::min(Len1, Len2)),
346 B, DL, TLI);
347 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000348
David Bolvansky909889b2018-08-10 04:32:54 +0000349 // strcmp to memcmp
350 if (!HasStr1 && HasStr2) {
351 if (canTransformToMemCmp(CI, Str1P, Len2, DL))
352 return emitMemCmp(
353 Str1P, Str2P,
354 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len2), B, DL,
355 TLI);
356 } else if (HasStr1 && !HasStr2) {
357 if (canTransformToMemCmp(CI, Str2P, Len1, DL))
358 return emitMemCmp(
359 Str1P, Str2P,
360 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len1), B, DL,
361 TLI);
362 }
363
Chris Bienemanad070d02014-09-17 20:55:46 +0000364 return nullptr;
365}
366
367Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000368 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
369 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
370 return ConstantInt::get(CI->getType(), 0);
371
372 // Get the length argument if it is constant.
373 uint64_t Length;
374 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
375 Length = LengthArg->getZExtValue();
376 else
377 return nullptr;
378
379 if (Length == 0) // strncmp(x,y,0) -> 0
380 return ConstantInt::get(CI->getType(), 0);
381
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000382 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000383 return emitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000384
385 StringRef Str1, Str2;
386 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
387 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
388
389 // strncmp(x, y) -> cnst (if both x and y are constant strings)
390 if (HasStr1 && HasStr2) {
391 StringRef SubStr1 = Str1.substr(0, Length);
392 StringRef SubStr2 = Str2.substr(0, Length);
393 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
394 }
395
396 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
397 return B.CreateNeg(
398 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
399
400 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
401 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
402
David Bolvansky909889b2018-08-10 04:32:54 +0000403 uint64_t Len1 = GetStringLength(Str1P);
404 uint64_t Len2 = GetStringLength(Str2P);
405
406 // strncmp to memcmp
407 if (!HasStr1 && HasStr2) {
408 Len2 = std::min(Len2, Length);
409 if (canTransformToMemCmp(CI, Str1P, Len2, DL))
410 return emitMemCmp(
411 Str1P, Str2P,
412 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len2), B, DL,
413 TLI);
414 } else if (HasStr1 && !HasStr2) {
415 Len1 = std::min(Len1, Length);
416 if (canTransformToMemCmp(CI, Str2P, Len1, DL))
417 return emitMemCmp(
418 Str1P, Str2P,
419 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len1), B, DL,
420 TLI);
421 }
422
Chris Bienemanad070d02014-09-17 20:55:46 +0000423 return nullptr;
424}
425
426Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000427 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
428 if (Dst == Src) // strcpy(x,x) -> x
429 return Src;
430
Chris Bienemanad070d02014-09-17 20:55:46 +0000431 // See if we can get the length of the input string.
David Bolvansky1f343fa2018-05-22 20:27:36 +0000432 uint64_t Len = GetStringLength(Src);
Chris Bienemanad070d02014-09-17 20:55:46 +0000433 if (Len == 0)
434 return nullptr;
435
436 // We have enough information to now generate the memcpy call to do the
437 // copy for us. Make a memcpy to copy the nul byte with align = 1.
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000438 B.CreateMemCpy(Dst, 1, Src, 1,
439 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len));
Chris Bienemanad070d02014-09-17 20:55:46 +0000440 return Dst;
441}
442
443Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
444 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000445 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
446 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000447 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +0000448 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000449 }
450
451 // See if we can get the length of the input string.
David Bolvansky1f343fa2018-05-22 20:27:36 +0000452 uint64_t Len = GetStringLength(Src);
Chris Bienemanad070d02014-09-17 20:55:46 +0000453 if (Len == 0)
454 return nullptr;
455
Davide Italianob7487e62015-11-02 23:07:14 +0000456 Type *PT = Callee->getFunctionType()->getParamType(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000457 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
Sanjay Pateld707db92015-12-31 16:10:49 +0000458 Value *DstEnd = B.CreateGEP(B.getInt8Ty(), Dst,
459 ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000460
461 // We have enough information to now generate the memcpy call to do the
462 // copy for us. Make a memcpy to copy the nul byte with align = 1.
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000463 B.CreateMemCpy(Dst, 1, Src, 1, LenV);
Chris Bienemanad070d02014-09-17 20:55:46 +0000464 return DstEnd;
465}
466
467Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
468 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000469 Value *Dst = CI->getArgOperand(0);
470 Value *Src = CI->getArgOperand(1);
471 Value *LenOp = CI->getArgOperand(2);
472
473 // See if we can get the length of the input string.
David Bolvansky1f343fa2018-05-22 20:27:36 +0000474 uint64_t SrcLen = GetStringLength(Src);
Chris Bienemanad070d02014-09-17 20:55:46 +0000475 if (SrcLen == 0)
476 return nullptr;
477 --SrcLen;
478
479 if (SrcLen == 0) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000480 // strncpy(x, "", y) -> memset(align 1 x, '\0', y)
Chris Bienemanad070d02014-09-17 20:55:46 +0000481 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000482 return Dst;
483 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000484
Chris Bienemanad070d02014-09-17 20:55:46 +0000485 uint64_t Len;
486 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
487 Len = LengthArg->getZExtValue();
488 else
489 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000490
Chris Bienemanad070d02014-09-17 20:55:46 +0000491 if (Len == 0)
492 return Dst; // strncpy(x, y, 0) -> x
Meador Inge7fb2f732012-10-13 16:45:32 +0000493
Chris Bienemanad070d02014-09-17 20:55:46 +0000494 // Let strncpy handle the zero padding
495 if (Len > SrcLen + 1)
496 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000497
Davide Italianob7487e62015-11-02 23:07:14 +0000498 Type *PT = Callee->getFunctionType()->getParamType(0);
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000499 // strncpy(x, s, c) -> memcpy(align 1 x, align 1 s, c) [s and c are constant]
500 B.CreateMemCpy(Dst, 1, Src, 1, ConstantInt::get(DL.getIntPtrType(PT), Len));
Meador Inge7fb2f732012-10-13 16:45:32 +0000501
Chris Bienemanad070d02014-09-17 20:55:46 +0000502 return Dst;
503}
Meador Inge7fb2f732012-10-13 16:45:32 +0000504
Matthias Braun50ec0b52017-05-19 22:37:09 +0000505Value *LibCallSimplifier::optimizeStringLength(CallInst *CI, IRBuilder<> &B,
506 unsigned CharSize) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000507 Value *Src = CI->getArgOperand(0);
508
509 // Constant folding: strlen("xyz") -> 3
David Bolvansky1f343fa2018-05-22 20:27:36 +0000510 if (uint64_t Len = GetStringLength(Src, CharSize))
Chris Bienemanad070d02014-09-17 20:55:46 +0000511 return ConstantInt::get(CI->getType(), Len - 1);
512
David L Kreitzer752c1442016-04-13 14:31:06 +0000513 // If s is a constant pointer pointing to a string literal, we can fold
Matthias Braun50ec0b52017-05-19 22:37:09 +0000514 // strlen(s + x) to strlen(s) - x, when x is known to be in the range
David L Kreitzer752c1442016-04-13 14:31:06 +0000515 // [0, strlen(s)] or the string has a single null terminator '\0' at the end.
Matthias Braun50ec0b52017-05-19 22:37:09 +0000516 // We only try to simplify strlen when the pointer s points to an array
David L Kreitzer752c1442016-04-13 14:31:06 +0000517 // of i8. Otherwise, we would need to scale the offset x before doing the
Matthias Braun50ec0b52017-05-19 22:37:09 +0000518 // subtraction. This will make the optimization more complex, and it's not
519 // very useful because calling strlen for a pointer of other types is
David L Kreitzer752c1442016-04-13 14:31:06 +0000520 // very uncommon.
521 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) {
Matthias Braun50ec0b52017-05-19 22:37:09 +0000522 if (!isGEPBasedOnPointerToString(GEP, CharSize))
David L Kreitzer752c1442016-04-13 14:31:06 +0000523 return nullptr;
524
Matthias Braun50ec0b52017-05-19 22:37:09 +0000525 ConstantDataArraySlice Slice;
526 if (getConstantDataArrayInfo(GEP->getOperand(0), Slice, CharSize)) {
527 uint64_t NullTermIdx;
528 if (Slice.Array == nullptr) {
529 NullTermIdx = 0;
530 } else {
531 NullTermIdx = ~((uint64_t)0);
532 for (uint64_t I = 0, E = Slice.Length; I < E; ++I) {
533 if (Slice.Array->getElementAsInteger(I + Slice.Offset) == 0) {
534 NullTermIdx = I;
535 break;
536 }
537 }
538 // If the string does not have '\0', leave it to strlen to compute
539 // its length.
540 if (NullTermIdx == ~((uint64_t)0))
541 return nullptr;
542 }
543
David L Kreitzer752c1442016-04-13 14:31:06 +0000544 Value *Offset = GEP->getOperand(2);
Craig Topper8205a1a2017-05-24 16:53:07 +0000545 KnownBits Known = computeKnownBits(Offset, DL, 0, nullptr, CI, nullptr);
Craig Topperb45eabc2017-04-26 16:39:58 +0000546 Known.Zero.flipAllBits();
Matthias Braun50ec0b52017-05-19 22:37:09 +0000547 uint64_t ArrSize =
David L Kreitzer752c1442016-04-13 14:31:06 +0000548 cast<ArrayType>(GEP->getSourceElementType())->getNumElements();
549
Matthias Braun50ec0b52017-05-19 22:37:09 +0000550 // KnownZero's bits are flipped, so zeros in KnownZero now represent
551 // bits known to be zeros in Offset, and ones in KnowZero represent
David L Kreitzer752c1442016-04-13 14:31:06 +0000552 // bits unknown in Offset. Therefore, Offset is known to be in range
Matthias Braun50ec0b52017-05-19 22:37:09 +0000553 // [0, NullTermIdx] when the flipped KnownZero is non-negative and
David L Kreitzer752c1442016-04-13 14:31:06 +0000554 // unsigned-less-than NullTermIdx.
555 //
Matthias Braun50ec0b52017-05-19 22:37:09 +0000556 // If Offset is not provably in the range [0, NullTermIdx], we can still
557 // optimize if we can prove that the program has undefined behavior when
558 // Offset is outside that range. That is the case when GEP->getOperand(0)
David L Kreitzer752c1442016-04-13 14:31:06 +0000559 // is a pointer to an object whose memory extent is NullTermIdx+1.
Matthias Braun50ec0b52017-05-19 22:37:09 +0000560 if ((Known.Zero.isNonNegative() && Known.Zero.ule(NullTermIdx)) ||
David L Kreitzer752c1442016-04-13 14:31:06 +0000561 (GEP->isInBounds() && isa<GlobalVariable>(GEP->getOperand(0)) &&
Matthias Braun50ec0b52017-05-19 22:37:09 +0000562 NullTermIdx == ArrSize - 1)) {
563 Offset = B.CreateSExtOrTrunc(Offset, CI->getType());
564 return B.CreateSub(ConstantInt::get(CI->getType(), NullTermIdx),
David L Kreitzer752c1442016-04-13 14:31:06 +0000565 Offset);
Matthias Braun50ec0b52017-05-19 22:37:09 +0000566 }
David L Kreitzer752c1442016-04-13 14:31:06 +0000567 }
568
569 return nullptr;
570 }
571
Chris Bienemanad070d02014-09-17 20:55:46 +0000572 // strlen(x?"foo":"bars") --> x ? 3 : 4
573 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
David Bolvansky1f343fa2018-05-22 20:27:36 +0000574 uint64_t LenTrue = GetStringLength(SI->getTrueValue(), CharSize);
575 uint64_t LenFalse = GetStringLength(SI->getFalseValue(), CharSize);
Chris Bienemanad070d02014-09-17 20:55:46 +0000576 if (LenTrue && LenFalse) {
Vivek Pandya95906582017-10-11 17:12:59 +0000577 ORE.emit([&]() {
578 return OptimizationRemark("instcombine", "simplify-libcalls", CI)
579 << "folded strlen(select) to select of constants";
580 });
Chris Bienemanad070d02014-09-17 20:55:46 +0000581 return B.CreateSelect(SI->getCondition(),
582 ConstantInt::get(CI->getType(), LenTrue - 1),
583 ConstantInt::get(CI->getType(), LenFalse - 1));
584 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000585 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000586
Chris Bienemanad070d02014-09-17 20:55:46 +0000587 // strlen(x) != 0 --> *x != 0
588 // strlen(x) == 0 --> *x == 0
589 if (isOnlyUsedInZeroEqualityComparison(CI))
590 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000591
Chris Bienemanad070d02014-09-17 20:55:46 +0000592 return nullptr;
593}
Meador Inge17418502012-10-13 16:45:37 +0000594
Matthias Braun50ec0b52017-05-19 22:37:09 +0000595Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
596 return optimizeStringLength(CI, B, 8);
597}
598
599Value *LibCallSimplifier::optimizeWcslen(CallInst *CI, IRBuilder<> &B) {
David Bolvansky5430b7372018-05-31 16:39:27 +0000600 Module &M = *CI->getModule();
Matthias Braun50ec0b52017-05-19 22:37:09 +0000601 unsigned WCharSize = TLI->getWCharSize(M) * 8;
Matthias Brauncc603ee2017-09-26 02:36:57 +0000602 // We cannot perform this optimization without wchar_size metadata.
603 if (WCharSize == 0)
604 return nullptr;
Matthias Braun50ec0b52017-05-19 22:37:09 +0000605
606 return optimizeStringLength(CI, B, WCharSize);
607}
608
Chris Bienemanad070d02014-09-17 20:55:46 +0000609Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000610 StringRef S1, S2;
611 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
612 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Meador Inge17418502012-10-13 16:45:37 +0000613
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000614 // strpbrk(s, "") -> nullptr
615 // strpbrk("", s) -> nullptr
Chris Bienemanad070d02014-09-17 20:55:46 +0000616 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
617 return Constant::getNullValue(CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000618
Chris Bienemanad070d02014-09-17 20:55:46 +0000619 // Constant folding.
620 if (HasS1 && HasS2) {
621 size_t I = S1.find_first_of(S2);
622 if (I == StringRef::npos) // No match.
Meador Inge17418502012-10-13 16:45:37 +0000623 return Constant::getNullValue(CI->getType());
624
Sanjay Pateld707db92015-12-31 16:10:49 +0000625 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I),
626 "strpbrk");
Meador Inge17418502012-10-13 16:45:37 +0000627 }
Meador Inge17418502012-10-13 16:45:37 +0000628
Chris Bienemanad070d02014-09-17 20:55:46 +0000629 // strpbrk(s, "a") -> strchr(s, 'a')
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000630 if (HasS2 && S2.size() == 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000631 return emitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000632
633 return nullptr;
634}
635
636Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000637 Value *EndPtr = CI->getArgOperand(1);
638 if (isa<ConstantPointerNull>(EndPtr)) {
639 // With a null EndPtr, this function won't capture the main argument.
640 // It would be readonly too, except that it still may write to errno.
Reid Klecknera0b45f42017-05-03 18:17:31 +0000641 CI->addParamAttr(0, Attribute::NoCapture);
Chris Bienemanad070d02014-09-17 20:55:46 +0000642 }
643
644 return nullptr;
645}
646
647Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000648 StringRef S1, S2;
649 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
650 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
651
652 // strspn(s, "") -> 0
653 // strspn("", s) -> 0
654 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
655 return Constant::getNullValue(CI->getType());
656
657 // Constant folding.
658 if (HasS1 && HasS2) {
659 size_t Pos = S1.find_first_not_of(S2);
660 if (Pos == StringRef::npos)
661 Pos = S1.size();
662 return ConstantInt::get(CI->getType(), Pos);
663 }
664
665 return nullptr;
666}
667
668Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000669 StringRef S1, S2;
670 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
671 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
672
673 // strcspn("", s) -> 0
674 if (HasS1 && S1.empty())
675 return Constant::getNullValue(CI->getType());
676
677 // Constant folding.
678 if (HasS1 && HasS2) {
679 size_t Pos = S1.find_first_of(S2);
680 if (Pos == StringRef::npos)
681 Pos = S1.size();
682 return ConstantInt::get(CI->getType(), Pos);
683 }
684
685 // strcspn(s, "") -> strlen(s)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000686 if (HasS2 && S2.empty())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000687 return emitStrLen(CI->getArgOperand(0), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000688
689 return nullptr;
690}
691
692Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000693 // fold strstr(x, x) -> x.
694 if (CI->getArgOperand(0) == CI->getArgOperand(1))
695 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
696
697 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000698 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000699 Value *StrLen = emitStrLen(CI->getArgOperand(1), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000700 if (!StrLen)
Craig Topperf40110f2014-04-25 05:29:35 +0000701 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +0000702 Value *StrNCmp = emitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
Chris Bienemanad070d02014-09-17 20:55:46 +0000703 StrLen, B, DL, TLI);
704 if (!StrNCmp)
Craig Topperf40110f2014-04-25 05:29:35 +0000705 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000706 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
707 ICmpInst *Old = cast<ICmpInst>(*UI++);
708 Value *Cmp =
709 B.CreateICmp(Old->getPredicate(), StrNCmp,
710 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
711 replaceAllUsesWith(Old, Cmp);
Meador Inge17418502012-10-13 16:45:37 +0000712 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000713 return CI;
714 }
Meador Inge17418502012-10-13 16:45:37 +0000715
Chris Bienemanad070d02014-09-17 20:55:46 +0000716 // See if either input string is a constant string.
717 StringRef SearchStr, ToFindStr;
718 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
719 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
720
721 // fold strstr(x, "") -> x.
722 if (HasStr2 && ToFindStr.empty())
723 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
724
725 // If both strings are known, constant fold it.
726 if (HasStr1 && HasStr2) {
727 size_t Offset = SearchStr.find(ToFindStr);
728
729 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
Meador Inge17418502012-10-13 16:45:37 +0000730 return Constant::getNullValue(CI->getType());
731
Chris Bienemanad070d02014-09-17 20:55:46 +0000732 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000733 Value *Result = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +0000734 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
735 return B.CreateBitCast(Result, CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000736 }
Meador Inge17418502012-10-13 16:45:37 +0000737
Chris Bienemanad070d02014-09-17 20:55:46 +0000738 // fold strstr(x, "y") -> strchr(x, 'y').
739 if (HasStr2 && ToFindStr.size() == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000740 Value *StrChr = emitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000741 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
742 }
743 return nullptr;
744}
Meador Inge40b6fac2012-10-15 03:47:37 +0000745
Benjamin Kramer691363e2015-03-21 15:36:21 +0000746Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
Benjamin Kramer691363e2015-03-21 15:36:21 +0000747 Value *SrcStr = CI->getArgOperand(0);
748 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
749 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
750
751 // memchr(x, y, 0) -> null
Craig Topper79ab6432017-07-06 18:39:47 +0000752 if (LenC && LenC->isZero())
Benjamin Kramer691363e2015-03-21 15:36:21 +0000753 return Constant::getNullValue(CI->getType());
754
Benjamin Kramer7857d722015-03-21 21:09:33 +0000755 // From now on we need at least constant length and string.
Benjamin Kramer691363e2015-03-21 15:36:21 +0000756 StringRef Str;
Benjamin Kramer7857d722015-03-21 21:09:33 +0000757 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
Benjamin Kramer691363e2015-03-21 15:36:21 +0000758 return nullptr;
759
760 // Truncate the string to LenC. If Str is smaller than LenC we will still only
761 // scan the string, as reading past the end of it is undefined and we can just
762 // return null if we don't find the char.
763 Str = Str.substr(0, LenC->getZExtValue());
764
Benjamin Kramer7857d722015-03-21 21:09:33 +0000765 // If the char is variable but the input str and length are not we can turn
766 // this memchr call into a simple bit field test. Of course this only works
767 // when the return value is only checked against null.
768 //
769 // It would be really nice to reuse switch lowering here but we can't change
770 // the CFG at this point.
771 //
772 // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
773 // after bounds check.
774 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
Benjamin Kramerd6aa0ec2015-03-21 22:04:26 +0000775 unsigned char Max =
776 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
777 reinterpret_cast<const unsigned char *>(Str.end()));
Benjamin Kramer7857d722015-03-21 21:09:33 +0000778
779 // Make sure the bit field we're about to create fits in a register on the
780 // target.
781 // FIXME: On a 64 bit architecture this prevents us from using the
782 // interesting range of alpha ascii chars. We could do better by emitting
783 // two bitfields or shifting the range by 64 if no lower chars are used.
784 if (!DL.fitsInLegalInteger(Max + 1))
785 return nullptr;
786
787 // For the bit field use a power-of-2 type with at least 8 bits to avoid
788 // creating unnecessary illegal types.
789 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
790
791 // Now build the bit field.
792 APInt Bitfield(Width, 0);
793 for (char C : Str)
794 Bitfield.setBit((unsigned char)C);
795 Value *BitfieldC = B.getInt(Bitfield);
796
797 // First check that the bit field access is within bounds.
798 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
799 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
800 "memchr.bounds");
801
802 // Create code that checks if the given bit is set in the field.
803 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
804 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
805
806 // Finally merge both checks and cast to pointer type. The inttoptr
807 // implicitly zexts the i1 to intptr type.
808 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
809 }
810
811 // Check if all arguments are constants. If so, we can constant fold.
812 if (!CharC)
813 return nullptr;
814
Benjamin Kramer691363e2015-03-21 15:36:21 +0000815 // Compute the offset.
816 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
817 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
818 return Constant::getNullValue(CI->getType());
819
820 // memchr(s+n,c,l) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000821 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
Benjamin Kramer691363e2015-03-21 15:36:21 +0000822}
823
Chris Bienemanad070d02014-09-17 20:55:46 +0000824Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000825 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
Meador Inge40b6fac2012-10-15 03:47:37 +0000826
Chris Bienemanad070d02014-09-17 20:55:46 +0000827 if (LHS == RHS) // memcmp(s,s,x) -> 0
828 return Constant::getNullValue(CI->getType());
Meador Inge40b6fac2012-10-15 03:47:37 +0000829
Chris Bienemanad070d02014-09-17 20:55:46 +0000830 // Make sure we have a constant length.
831 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
832 if (!LenC)
Craig Topperf40110f2014-04-25 05:29:35 +0000833 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000834
Sanjay Patel70db4242017-06-09 14:22:03 +0000835 uint64_t Len = LenC->getZExtValue();
Chris Bienemanad070d02014-09-17 20:55:46 +0000836 if (Len == 0) // memcmp(s1,s2,0) -> 0
837 return Constant::getNullValue(CI->getType());
838
839 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
840 if (Len == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000841 Value *LHSV = B.CreateZExt(B.CreateLoad(castToCStr(LHS, B), "lhsc"),
Chris Bienemanad070d02014-09-17 20:55:46 +0000842 CI->getType(), "lhsv");
Sanjay Pateld3112a52016-01-19 19:46:10 +0000843 Value *RHSV = B.CreateZExt(B.CreateLoad(castToCStr(RHS, B), "rhsc"),
Chris Bienemanad070d02014-09-17 20:55:46 +0000844 CI->getType(), "rhsv");
845 return B.CreateSub(LHSV, RHSV, "chardiff");
Meador Inge40b6fac2012-10-15 03:47:37 +0000846 }
Meador Inge40b6fac2012-10-15 03:47:37 +0000847
Chad Rosierdc655322015-08-28 18:30:18 +0000848 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
Sanjay Patel82ec8722017-08-21 19:13:14 +0000849 // 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.
Chad Rosierdc655322015-08-28 18:30:18 +0000851 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
Chad Rosierdc655322015-08-28 18:30:18 +0000852 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
853 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
854
Sanjay Patel82ec8722017-08-21 19:13:14 +0000855 // First, see if we can fold either argument to a constant.
856 Value *LHSV = nullptr;
857 if (auto *LHSC = dyn_cast<Constant>(LHS)) {
858 LHSC = ConstantExpr::getBitCast(LHSC, IntType->getPointerTo());
859 LHSV = ConstantFoldLoadFromConstPtr(LHSC, IntType, DL);
860 }
861 Value *RHSV = nullptr;
862 if (auto *RHSC = dyn_cast<Constant>(RHS)) {
863 RHSC = ConstantExpr::getBitCast(RHSC, IntType->getPointerTo());
864 RHSV = ConstantFoldLoadFromConstPtr(RHSC, IntType, DL);
865 }
Chad Rosierdc655322015-08-28 18:30:18 +0000866
Sanjay Patel82ec8722017-08-21 19:13:14 +0000867 // Don't generate unaligned loads. If either source is constant data,
868 // alignment doesn't matter for that source because there is no load.
869 if ((LHSV || getKnownAlignment(LHS, DL, CI) >= PrefAlignment) &&
870 (RHSV || getKnownAlignment(RHS, DL, CI) >= PrefAlignment)) {
871 if (!LHSV) {
872 Type *LHSPtrTy =
873 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
874 LHSV = B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy), "lhsv");
875 }
876 if (!RHSV) {
877 Type *RHSPtrTy =
878 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
879 RHSV = B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy), "rhsv");
880 }
Sanjay Patel7756edf2017-08-21 13:55:49 +0000881 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
Sanjay Patel707f7862017-08-21 15:16:25 +0000882 }
Chad Rosierdc655322015-08-28 18:30:18 +0000883 }
884
Sanjay Patel82ec8722017-08-21 19:13:14 +0000885 // Constant folding: memcmp(x, y, Len) -> constant (all arguments are const).
886 // TODO: This is limited to i8 arrays.
Chris Bienemanad070d02014-09-17 20:55:46 +0000887 StringRef LHSStr, RHSStr;
888 if (getConstantStringInfo(LHS, LHSStr) &&
889 getConstantStringInfo(RHS, RHSStr)) {
890 // Make sure we're not reading out-of-bounds memory.
891 if (Len > LHSStr.size() || Len > RHSStr.size())
Craig Topperf40110f2014-04-25 05:29:35 +0000892 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000893 // Fold the memcmp and normalize the result. This way we get consistent
894 // results across multiple platforms.
895 uint64_t Ret = 0;
896 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
897 if (Cmp < 0)
898 Ret = -1;
899 else if (Cmp > 0)
900 Ret = 1;
901 return ConstantInt::get(CI->getType(), Ret);
Meador Inge000dbcc2012-10-18 18:12:40 +0000902 }
Meador Inge000dbcc2012-10-18 18:12:40 +0000903
Chris Bienemanad070d02014-09-17 20:55:46 +0000904 return nullptr;
905}
Meador Inge9a6a1902012-10-31 00:20:56 +0000906
Chris Bienemanad070d02014-09-17 20:55:46 +0000907Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000908 // memcpy(x, y, n) -> llvm.memcpy(align 1 x, align 1 y, n)
909 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
910 CI->getArgOperand(2));
Chris Bienemanad070d02014-09-17 20:55:46 +0000911 return CI->getArgOperand(0);
912}
Meador Inge05a625a2012-10-31 14:58:26 +0000913
Chris Bienemanad070d02014-09-17 20:55:46 +0000914Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000915 // memmove(x, y, n) -> llvm.memmove(align 1 x, align 1 y, n)
916 B.CreateMemMove(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
917 CI->getArgOperand(2));
Chris Bienemanad070d02014-09-17 20:55:46 +0000918 return CI->getArgOperand(0);
919}
Meador Ingebcd88ef72012-11-10 15:16:48 +0000920
Sanjay Patel980b2802016-01-26 16:17:24 +0000921/// Fold memset[_chk](malloc(n), 0, n) --> calloc(1, n).
922static Value *foldMallocMemset(CallInst *Memset, IRBuilder<> &B,
923 const TargetLibraryInfo &TLI) {
924 // This has to be a memset of zeros (bzero).
925 auto *FillValue = dyn_cast<ConstantInt>(Memset->getArgOperand(1));
926 if (!FillValue || FillValue->getZExtValue() != 0)
927 return nullptr;
928
929 // TODO: We should handle the case where the malloc has more than one use.
930 // This is necessary to optimize common patterns such as when the result of
931 // the malloc is checked against null or when a memset intrinsic is used in
932 // place of a memset library call.
933 auto *Malloc = dyn_cast<CallInst>(Memset->getArgOperand(0));
934 if (!Malloc || !Malloc->hasOneUse())
935 return nullptr;
936
937 // Is the inner call really malloc()?
938 Function *InnerCallee = Malloc->getCalledFunction();
Matthias Braunc36a78c2017-04-25 19:44:25 +0000939 if (!InnerCallee)
940 return nullptr;
941
David L. Jonesd21529f2017-01-23 23:16:46 +0000942 LibFunc Func;
Ahmed Bougachad765a822016-04-27 19:04:35 +0000943 if (!TLI.getLibFunc(*InnerCallee, Func) || !TLI.has(Func) ||
David L. Jonesd21529f2017-01-23 23:16:46 +0000944 Func != LibFunc_malloc)
Sanjay Patel980b2802016-01-26 16:17:24 +0000945 return nullptr;
946
Sanjay Patel980b2802016-01-26 16:17:24 +0000947 // The memset must cover the same number of bytes that are malloc'd.
948 if (Memset->getArgOperand(2) != Malloc->getArgOperand(0))
949 return nullptr;
950
951 // Replace the malloc with a calloc. We need the data layout to know what the
Fangrui Songf78650a2018-07-30 19:41:25 +0000952 // actual size of a 'size_t' parameter is.
Sanjay Patel980b2802016-01-26 16:17:24 +0000953 B.SetInsertPoint(Malloc->getParent(), ++Malloc->getIterator());
954 const DataLayout &DL = Malloc->getModule()->getDataLayout();
955 IntegerType *SizeType = DL.getIntPtrType(B.GetInsertBlock()->getContext());
956 Value *Calloc = emitCalloc(ConstantInt::get(SizeType, 1),
957 Malloc->getArgOperand(0), Malloc->getAttributes(),
958 B, TLI);
959 if (!Calloc)
960 return nullptr;
961
962 Malloc->replaceAllUsesWith(Calloc);
963 Malloc->eraseFromParent();
964
965 return Calloc;
966}
967
Chris Bienemanad070d02014-09-17 20:55:46 +0000968Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel980b2802016-01-26 16:17:24 +0000969 if (auto *Calloc = foldMallocMemset(CI, B, *TLI))
970 return Calloc;
971
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000972 // memset(p, v, n) -> llvm.memset(align 1 p, v, n)
Chris Bienemanad070d02014-09-17 20:55:46 +0000973 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
974 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
975 return CI->getArgOperand(0);
976}
Meador Inged4825782012-11-11 06:49:03 +0000977
Sanjay Patelb2ab3f22018-04-18 14:21:31 +0000978Value *LibCallSimplifier::optimizeRealloc(CallInst *CI, IRBuilder<> &B) {
979 if (isa<ConstantPointerNull>(CI->getArgOperand(0)))
980 return emitMalloc(CI->getArgOperand(1), B, DL, TLI);
981
982 return nullptr;
983}
984
Meador Inge193e0352012-11-13 04:16:17 +0000985//===----------------------------------------------------------------------===//
986// Math Library Optimizations
987//===----------------------------------------------------------------------===//
988
Evandro Menezes5aa217a2018-08-03 17:50:16 +0000989// Replace a libcall \p CI with a call to intrinsic \p IID
990static Value *replaceUnaryCall(CallInst *CI, IRBuilder<> &B, Intrinsic::ID IID) {
991 // Propagate fast-math flags from the existing call to the new call.
992 IRBuilder<>::FastMathFlagGuard Guard(B);
993 B.setFastMathFlags(CI->getFastMathFlags());
994
995 Module *M = CI->getModule();
996 Value *V = CI->getArgOperand(0);
997 Function *F = Intrinsic::getDeclaration(M, IID, CI->getType());
998 CallInst *NewCall = B.CreateCall(F, V);
999 NewCall->takeName(CI);
1000 return NewCall;
1001}
1002
Matthias Braund34e4d22014-12-03 21:46:33 +00001003/// Return a variant of Val with float type.
1004/// Currently this works in two cases: If Val is an FPExtension of a float
1005/// value to something bigger, simply return the operand.
1006/// If Val is a ConstantFP but can be converted to a float ConstantFP without
1007/// loss of precision do so.
1008static Value *valueHasFloatPrecision(Value *Val) {
1009 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
1010 Value *Op = Cast->getOperand(0);
1011 if (Op->getType()->isFloatTy())
1012 return Op;
1013 }
1014 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
1015 APFloat F = Const->getValueAPF();
Matthias Braun395a82f2014-12-03 22:10:39 +00001016 bool losesInfo;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001017 (void)F.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
Matthias Braun395a82f2014-12-03 22:10:39 +00001018 &losesInfo);
1019 if (!losesInfo)
Matthias Braund34e4d22014-12-03 21:46:33 +00001020 return ConstantFP::get(Const->getContext(), F);
1021 }
1022 return nullptr;
1023}
1024
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001025/// Shrink double -> float functions.
1026static Value *optimizeDoubleFP(CallInst *CI, IRBuilder<> &B,
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001027 bool isBinary, bool isPrecise = false) {
Ahmed Bougachad765a822016-04-27 19:04:35 +00001028 if (!CI->getType()->isDoubleTy())
Chris Bienemanad070d02014-09-17 20:55:46 +00001029 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001030
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001031 // If not all the uses of the function are converted to float, then bail out.
1032 // This matters if the precision of the result is more important than the
1033 // precision of the arguments.
1034 if (isPrecise)
Chris Bienemanad070d02014-09-17 20:55:46 +00001035 for (User *U : CI->users()) {
1036 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
1037 if (!Cast || !Cast->getType()->isFloatTy())
1038 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001039 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001040
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001041 // If this is something like 'g((double) float)', convert to 'gf(float)'.
1042 Value *V[2];
1043 V[0] = valueHasFloatPrecision(CI->getArgOperand(0));
1044 V[1] = isBinary ? valueHasFloatPrecision(CI->getArgOperand(1)) : nullptr;
1045 if (!V[0] || (isBinary && !V[1]))
Chris Bienemanad070d02014-09-17 20:55:46 +00001046 return nullptr;
Fangrui Songf78650a2018-07-30 19:41:25 +00001047
Andrew Ng1606fc02017-04-25 12:36:14 +00001048 // If call isn't an intrinsic, check that it isn't within a function with the
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001049 // same name as the float version of this call, otherwise the result is an
1050 // infinite loop. For example, from MinGW-w64:
Andrew Ng1606fc02017-04-25 12:36:14 +00001051 //
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001052 // float expf(float val) { return (float) exp((double) val); }
1053 Function *CalleeFn = CI->getCalledFunction();
1054 StringRef CalleeNm = CalleeFn->getName();
1055 AttributeList CalleeAt = CalleeFn->getAttributes();
1056 if (CalleeFn && !CalleeFn->isIntrinsic()) {
1057 const Function *Fn = CI->getFunction();
1058 StringRef FnName = Fn->getName();
1059 if (FnName.back() == 'f' &&
1060 FnName.size() == (CalleeNm.size() + 1) &&
1061 FnName.startswith(CalleeNm))
Andrew Ng1606fc02017-04-25 12:36:14 +00001062 return nullptr;
1063 }
1064
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001065 // Propagate the math semantics from the current function to the new function.
Sanjay Patelaa231142015-12-31 21:52:31 +00001066 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001067 B.setFastMathFlags(CI->getFastMathFlags());
Chris Bienemanad070d02014-09-17 20:55:46 +00001068
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001069 // g((double) float) -> (double) gf(float)
1070 Value *R;
1071 if (CalleeFn->isIntrinsic()) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001072 Module *M = CI->getModule();
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001073 Intrinsic::ID IID = CalleeFn->getIntrinsicID();
1074 Function *Fn = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
1075 R = isBinary ? B.CreateCall(Fn, V) : B.CreateCall(Fn, V[0]);
Sanjay Patel848309d2014-10-23 21:52:45 +00001076 }
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001077 else
1078 R = isBinary ? emitBinaryFloatFnCall(V[0], V[1], CalleeNm, B, CalleeAt)
1079 : emitUnaryFloatFnCall(V[0], CalleeNm, B, CalleeAt);
Sanjay Patel848309d2014-10-23 21:52:45 +00001080
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001081 return B.CreateFPExt(R, B.getDoubleTy());
Chris Bienemanad070d02014-09-17 20:55:46 +00001082}
Meador Inge193e0352012-11-13 04:16:17 +00001083
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001084/// Shrink double -> float for unary functions.
1085static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001086 bool isPrecise = false) {
1087 return optimizeDoubleFP(CI, B, false, isPrecise);
Matt Arsenault954a6242017-01-23 23:55:08 +00001088}
1089
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001090/// Shrink double -> float for binary functions.
1091static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B,
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001092 bool isPrecise = false) {
1093 return optimizeDoubleFP(CI, B, true, isPrecise);
Chris Bienemanad070d02014-09-17 20:55:46 +00001094}
1095
Hal Finkel2ff24732017-12-16 01:26:25 +00001096// cabs(z) -> sqrt((creal(z)*creal(z)) + (cimag(z)*cimag(z)))
1097Value *LibCallSimplifier::optimizeCAbs(CallInst *CI, IRBuilder<> &B) {
1098 if (!CI->isFast())
1099 return nullptr;
1100
1101 // Propagate fast-math flags from the existing call to new instructions.
1102 IRBuilder<>::FastMathFlagGuard Guard(B);
1103 B.setFastMathFlags(CI->getFastMathFlags());
1104
1105 Value *Real, *Imag;
1106 if (CI->getNumArgOperands() == 1) {
1107 Value *Op = CI->getArgOperand(0);
1108 assert(Op->getType()->isArrayTy() && "Unexpected signature for cabs!");
1109 Real = B.CreateExtractValue(Op, 0, "real");
1110 Imag = B.CreateExtractValue(Op, 1, "imag");
1111 } else {
1112 assert(CI->getNumArgOperands() == 2 && "Unexpected signature for cabs!");
1113 Real = CI->getArgOperand(0);
1114 Imag = CI->getArgOperand(1);
1115 }
1116
1117 Value *RealReal = B.CreateFMul(Real, Real);
1118 Value *ImagImag = B.CreateFMul(Imag, Imag);
1119
1120 Function *FSqrt = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::sqrt,
1121 CI->getType());
1122 return B.CreateCall(FSqrt, B.CreateFAdd(RealReal, ImagImag), "cabs");
1123}
1124
Chris Bienemanad070d02014-09-17 20:55:46 +00001125Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1126 Function *Callee = CI->getCalledFunction();
1127 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001128 StringRef Name = Callee->getName();
1129 if (UnsafeFPShrink && Name == "cos" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001130 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001131
Chris Bienemanad070d02014-09-17 20:55:46 +00001132 // cos(-x) -> cos(x)
1133 Value *Op1 = CI->getArgOperand(0);
1134 if (BinaryOperator::isFNeg(Op1)) {
1135 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1136 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1137 }
1138 return Ret;
1139}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001140
Weiming Zhao82130722015-12-04 22:00:47 +00001141static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B) {
1142 // Multiplications calculated using Addition Chains.
1143 // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html
1144
1145 assert(Exp != 0 && "Incorrect exponent 0 not handled");
1146
1147 if (InnerChain[Exp])
1148 return InnerChain[Exp];
1149
1150 static const unsigned AddChain[33][2] = {
1151 {0, 0}, // Unused.
1152 {0, 0}, // Unused (base case = pow1).
1153 {1, 1}, // Unused (pre-computed).
1154 {1, 2}, {2, 2}, {2, 3}, {3, 3}, {2, 5}, {4, 4},
1155 {1, 8}, {5, 5}, {1, 10}, {6, 6}, {4, 9}, {7, 7},
1156 {3, 12}, {8, 8}, {8, 9}, {2, 16}, {1, 18}, {10, 10},
1157 {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13},
1158 {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16},
1159 };
1160
1161 InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B),
1162 getPow(InnerChain, AddChain[Exp][1], B));
1163 return InnerChain[Exp];
1164}
1165
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001166/// Use square root in place of pow(x, +/-0.5).
1167Value *LibCallSimplifier::replacePowWithSqrt(CallInst *Pow, IRBuilder<> &B) {
1168 // TODO: There is some subset of 'fast' under which these transforms should
1169 // be allowed.
1170 if (!Pow->isFast())
1171 return nullptr;
1172
Evandro Menezesa7d48282018-07-30 16:20:04 +00001173 Value *Sqrt, *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1);
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001174 Type *Ty = Pow->getType();
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001175
Evandro Menezesa7d48282018-07-30 16:20:04 +00001176 const APFloat *ExpoF;
1177 if (!match(Expo, m_APFloat(ExpoF)) ||
1178 (!ExpoF->isExactlyValue(0.5) && !ExpoF->isExactlyValue(-0.5)))
1179 return nullptr;
1180
1181 // If errno is never set, then use the intrinsic for sqrt().
1182 if (Pow->hasFnAttr(Attribute::ReadNone)) {
Evandro Menezesa7d48282018-07-30 16:20:04 +00001183 Function *SqrtFn = Intrinsic::getDeclaration(Pow->getModule(),
1184 Intrinsic::sqrt, Ty);
1185 Sqrt = B.CreateCall(SqrtFn, Base);
1186 }
1187 // Otherwise, use the libcall for sqrt().
Evandro Menezes61e4e402018-07-31 22:11:02 +00001188 else if (hasUnaryFloatFn(TLI, Ty, LibFunc_sqrt, LibFunc_sqrtf, LibFunc_sqrtl))
Evandro Menezesa7d48282018-07-30 16:20:04 +00001189 // TODO: We also should check that the target can in fact lower the sqrt()
1190 // libcall. We currently have no way to ask this question, so we ask if
1191 // the target has a sqrt() libcall, which is not exactly the same.
1192 Sqrt = emitUnaryFloatFnCall(Base, TLI->getName(LibFunc_sqrt), B,
1193 Pow->getCalledFunction()->getAttributes());
Evandro Menezes61e4e402018-07-31 22:11:02 +00001194 else
Evandro Menezesa7d48282018-07-30 16:20:04 +00001195 return nullptr;
1196
Evandro Menezes61e4e402018-07-31 22:11:02 +00001197 // If the exponent is negative, then get the reciprocal.
Evandro Menezesa7d48282018-07-30 16:20:04 +00001198 if (ExpoF->isNegative())
1199 Sqrt = B.CreateFDiv(ConstantFP::get(Ty, 1.0), Sqrt, "reciprocal");
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001200
1201 return Sqrt;
1202}
1203
Evandro Menezesa7d48282018-07-30 16:20:04 +00001204Value *LibCallSimplifier::optimizePow(CallInst *Pow, IRBuilder<> &B) {
1205 Value *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1);
1206 Function *Callee = Pow->getCalledFunction();
1207 AttributeList Attrs = Callee->getAttributes();
Davide Italianoa3458772015-11-05 19:18:23 +00001208 StringRef Name = Callee->getName();
Evandro Menezesa7d48282018-07-30 16:20:04 +00001209 Module *Module = Pow->getModule();
1210 Type *Ty = Pow->getType();
1211 Value *Shrunk = nullptr;
1212 bool Ignored;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001213
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001214 // Bail out if simplifying libcalls to pow() is disabled.
1215 if (!hasUnaryFloatFn(TLI, Ty, LibFunc_pow, LibFunc_powf, LibFunc_powl))
1216 return nullptr;
1217
Evandro Menezes61e4e402018-07-31 22:11:02 +00001218 // Propagate the math semantics from the call to any created instructions.
Evandro Menezesa7d48282018-07-30 16:20:04 +00001219 IRBuilder<>::FastMathFlagGuard Guard(B);
1220 B.setFastMathFlags(Pow->getFastMathFlags());
1221
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001222 // Shrink pow() to powf() if the arguments are single precision,
1223 // unless the result is expected to be double precision.
1224 if (UnsafeFPShrink &&
1225 Name == TLI->getName(LibFunc_pow) && hasFloatVersion(Name))
1226 Shrunk = optimizeBinaryDoubleFP(Pow, B, true);
1227
Evandro Menezesa7d48282018-07-30 16:20:04 +00001228 // Evaluate special cases related to the base.
Davide Italiano27da1312016-08-07 20:27:03 +00001229
1230 // pow(1.0, x) -> 1.0
Evandro Menezes84e74362018-08-02 15:43:57 +00001231 if (match(Base, m_FPOne()))
Evandro Menezesa7d48282018-07-30 16:20:04 +00001232 return Base;
1233
1234 // pow(2.0, x) -> exp2(x)
1235 if (match(Base, m_SpecificFP(2.0))) {
1236 Value *Exp2 = Intrinsic::getDeclaration(Module, Intrinsic::exp2, Ty);
1237 return B.CreateCall(Exp2, Expo, "exp2");
Davide Italiano27da1312016-08-07 20:27:03 +00001238 }
1239
Evandro Menezes61e4e402018-07-31 22:11:02 +00001240 // pow(10.0, x) -> exp10(x)
1241 if (ConstantFP *BaseC = dyn_cast<ConstantFP>(Base))
1242 // There's no exp10 intrinsic yet, but, maybe, some day there shall be one.
Evandro Menezesa7d48282018-07-30 16:20:04 +00001243 if (BaseC->isExactlyValue(10.0) &&
1244 hasUnaryFloatFn(TLI, Ty, LibFunc_exp10, LibFunc_exp10f, LibFunc_exp10l))
1245 return emitUnaryFloatFnCall(Expo, TLI->getName(LibFunc_exp10), B, Attrs);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001246
Sanjay Patel6002e782016-01-12 17:30:37 +00001247 // pow(exp(x), y) -> exp(x * y)
Davide Italianoc8a79132015-11-03 20:32:23 +00001248 // pow(exp2(x), y) -> exp2(x * y)
Sanjay Patel6002e782016-01-12 17:30:37 +00001249 // We enable these only with fast-math. Besides rounding differences, the
1250 // transformation changes overflow and underflow behavior quite dramatically.
Davide Italianoc8a79132015-11-03 20:32:23 +00001251 // Example: x = 1000, y = 0.001.
1252 // pow(exp(x), y) = pow(inf, 0.001) = inf, whereas exp(x*y) = exp(1).
Evandro Menezesa7d48282018-07-30 16:20:04 +00001253 auto *BaseFn = dyn_cast<CallInst>(Base);
1254 if (BaseFn && BaseFn->isFast() && Pow->isFast()) {
1255 LibFunc LibFn;
1256 Function *CalleeFn = BaseFn->getCalledFunction();
1257 if (CalleeFn && TLI->getLibFunc(CalleeFn->getName(), LibFn) &&
1258 (LibFn == LibFunc_exp || LibFn == LibFunc_exp2) && TLI->has(LibFn)) {
Evandro Menezesa7d48282018-07-30 16:20:04 +00001259 Value *FMul = B.CreateFMul(BaseFn->getArgOperand(0), Expo, "mul");
1260 return emitUnaryFloatFnCall(FMul, CalleeFn->getName(), B,
1261 CalleeFn->getAttributes());
Davide Italianoc8a79132015-11-03 20:32:23 +00001262 }
1263 }
1264
Evandro Menezesa7d48282018-07-30 16:20:04 +00001265 // Evaluate special cases related to the exponent.
1266
Evandro Menezesa7d48282018-07-30 16:20:04 +00001267 // pow(x, -1.0) -> 1.0 / x
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001268 if (match(Expo, m_SpecificFP(-1.0)))
Evandro Menezesa7d48282018-07-30 16:20:04 +00001269 return B.CreateFDiv(ConstantFP::get(Ty, 1.0), Base, "reciprocal");
1270
1271 // pow(x, 0.0) -> 1.0
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001272 if (match(Expo, m_SpecificFP(0.0)))
1273 return ConstantFP::get(Ty, 1.0);
Evandro Menezesa7d48282018-07-30 16:20:04 +00001274
1275 // pow(x, 1.0) -> x
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001276 if (match(Expo, m_FPOne()))
Evandro Menezesa7d48282018-07-30 16:20:04 +00001277 return Base;
1278
1279 // pow(x, 2.0) -> x * x
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001280 if (match(Expo, m_SpecificFP(2.0)))
Evandro Menezesa7d48282018-07-30 16:20:04 +00001281 return B.CreateFMul(Base, Base, "square");
Chris Bienemanad070d02014-09-17 20:55:46 +00001282
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001283 if (Value *Sqrt = replacePowWithSqrt(Pow, B))
1284 return Sqrt;
1285
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001286 // FIXME: Correct the transforms and pull this into replacePowWithSqrt().
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001287 ConstantFP *ExpoC = dyn_cast<ConstantFP>(Expo);
1288 if (ExpoC && ExpoC->isExactlyValue(0.5) &&
Evandro Menezesa7d48282018-07-30 16:20:04 +00001289 hasUnaryFloatFn(TLI, Ty, LibFunc_sqrt, LibFunc_sqrtf, LibFunc_sqrtl)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001290 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
Evandro Menezes61e4e402018-07-31 22:11:02 +00001291 // This is faster than calling pow(), and still handles -0.0 and
1292 // negative infinity correctly.
Chris Bienemanad070d02014-09-17 20:55:46 +00001293 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
Evandro Menezesa7d48282018-07-30 16:20:04 +00001294 Value *PosInf = ConstantFP::getInfinity(Ty);
1295 Value *NegInf = ConstantFP::getInfinity(Ty, true);
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001296
Evandro Menezesa7d48282018-07-30 16:20:04 +00001297 // TODO: As above, we should lower to the sqrt() intrinsic if the pow() is
1298 // an intrinsic, to match errno semantics.
1299 Value *Sqrt = emitUnaryFloatFnCall(Base, TLI->getName(LibFunc_sqrt),
1300 B, Attrs);
Evandro Menezes61e4e402018-07-31 22:11:02 +00001301 Function *FAbsFn = Intrinsic::getDeclaration(Module, Intrinsic::fabs, Ty);
1302 Value *FAbs = B.CreateCall(FAbsFn, Sqrt, "abs");
Evandro Menezesa7d48282018-07-30 16:20:04 +00001303 Value *FCmp = B.CreateFCmpOEQ(Base, NegInf, "isinf");
Evandro Menezes61e4e402018-07-31 22:11:02 +00001304 Sqrt = B.CreateSelect(FCmp, PosInf, FAbs);
1305 return Sqrt;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001306 }
1307
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001308 // pow(x, n) -> x * x * x * ...
1309 const APFloat *ExpoF;
1310 if (Pow->isFast() && match(Expo, m_APFloat(ExpoF))) {
1311 // We limit to a max of 7 multiplications, thus the maximum exponent is 32.
1312 APFloat LimF(ExpoF->getSemantics(), 33.0),
1313 ExpoA(abs(*ExpoF));
1314 if (ExpoA.isInteger() && ExpoA.compare(LimF) == APFloat::cmpLessThan) {
1315 // We will memoize intermediate products of the Addition Chain.
1316 Value *InnerChain[33] = {nullptr};
1317 InnerChain[1] = Base;
1318 InnerChain[2] = B.CreateFMul(Base, Base, "square");
Weiming Zhao82130722015-12-04 22:00:47 +00001319
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001320 // We cannot readily convert a non-double type (like float) to a double.
1321 // So we first convert it to something which could be converted to double.
1322 ExpoA.convert(APFloat::IEEEdouble(), APFloat::rmTowardZero, &Ignored);
1323 Value *FMul = getPow(InnerChain, ExpoA.convertToDouble(), B);
Weiming Zhao82130722015-12-04 22:00:47 +00001324
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001325 // If the exponent is negative, then get the reciprocal.
1326 if (ExpoF->isNegative())
1327 FMul = B.CreateFDiv(ConstantFP::get(Ty, 1.0), FMul, "reciprocal");
Evandro Menezes61e4e402018-07-31 22:11:02 +00001328
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001329 return FMul;
1330 }
Weiming Zhao82130722015-12-04 22:00:47 +00001331 }
1332
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001333 return Shrunk;
Chris Bienemanad070d02014-09-17 20:55:46 +00001334}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001335
Chris Bienemanad070d02014-09-17 20:55:46 +00001336Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1337 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001338 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001339 StringRef Name = Callee->getName();
1340 if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001341 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001342
Chris Bienemanad070d02014-09-17 20:55:46 +00001343 Value *Op = CI->getArgOperand(0);
1344 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1345 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
David L. Jonesd21529f2017-01-23 23:16:46 +00001346 LibFunc LdExp = LibFunc_ldexpl;
Chris Bienemanad070d02014-09-17 20:55:46 +00001347 if (Op->getType()->isFloatTy())
David L. Jonesd21529f2017-01-23 23:16:46 +00001348 LdExp = LibFunc_ldexpf;
Chris Bienemanad070d02014-09-17 20:55:46 +00001349 else if (Op->getType()->isDoubleTy())
David L. Jonesd21529f2017-01-23 23:16:46 +00001350 LdExp = LibFunc_ldexp;
Chris Bienemanad070d02014-09-17 20:55:46 +00001351
1352 if (TLI->has(LdExp)) {
1353 Value *LdExpArg = nullptr;
1354 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1355 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1356 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1357 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1358 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1359 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1360 }
1361
1362 if (LdExpArg) {
1363 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1364 if (!Op->getType()->isFloatTy())
1365 One = ConstantExpr::getFPExtend(One, Op->getType());
1366
Sanjay Patel0e603fc2016-01-21 22:31:18 +00001367 Module *M = CI->getModule();
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001368 Value *NewCallee =
1369 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001370 Op->getType(), B.getInt32Ty());
Sanjay Patel042aed902016-01-21 22:41:16 +00001371 CallInst *CI = B.CreateCall(NewCallee, {One, LdExpArg});
Chris Bienemanad070d02014-09-17 20:55:46 +00001372 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1373 CI->setCallingConv(F->getCallingConv());
1374
1375 return CI;
1376 }
1377 }
1378 return Ret;
1379}
1380
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001381Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel9beec212016-01-21 22:58:01 +00001382 Function *Callee = CI->getCalledFunction();
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001383 // If we can shrink the call to a float function rather than a double
1384 // function, do that first.
Davide Italianoa3458772015-11-05 19:18:23 +00001385 StringRef Name = Callee->getName();
Sanjay Patelc7ddb7f2016-01-06 00:32:15 +00001386 if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name))
1387 if (Value *Ret = optimizeBinaryDoubleFP(CI, B))
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001388 return Ret;
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001389
Benjamin Kramerbb70d752015-08-16 21:16:37 +00001390 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001391 FastMathFlags FMF;
Sanjay Patel629c4112017-11-06 16:27:15 +00001392 if (CI->isFast()) {
1393 // If the call is 'fast', then anything we create here will also be 'fast'.
1394 FMF.setFast();
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001395 } else {
1396 // At a minimum, no-nans-fp-math must be true.
Sanjay Patel29095ea2016-01-05 20:46:19 +00001397 if (!CI->hasNoNaNs())
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001398 return nullptr;
1399 // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1400 // "Ideally, fmax would be sensitive to the sign of zero, for example
NAKAMURA Takumi0d725392015-09-07 00:26:54 +00001401 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001402 // might be impractical."
1403 FMF.setNoSignedZeros();
1404 FMF.setNoNaNs();
1405 }
Sanjay Patela2528152016-01-12 18:03:37 +00001406 B.setFastMathFlags(FMF);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001407
1408 // We have a relaxed floating-point environment. We can ignore NaN-handling
1409 // and transform to a compare and select. We do not have to consider errno or
1410 // exceptions, because fmin/fmax do not have those.
1411 Value *Op0 = CI->getArgOperand(0);
1412 Value *Op1 = CI->getArgOperand(1);
1413 Value *Cmp = Callee->getName().startswith("fmin") ?
1414 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1415 return B.CreateSelect(Cmp, Op0, Op1);
1416}
1417
Davide Italianob8b71332015-11-29 20:58:04 +00001418Value *LibCallSimplifier::optimizeLog(CallInst *CI, IRBuilder<> &B) {
1419 Function *Callee = CI->getCalledFunction();
1420 Value *Ret = nullptr;
1421 StringRef Name = Callee->getName();
1422 if (UnsafeFPShrink && hasFloatVersion(Name))
1423 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italianob8b71332015-11-29 20:58:04 +00001424
Sanjay Patel629c4112017-11-06 16:27:15 +00001425 if (!CI->isFast())
Davide Italianob8b71332015-11-29 20:58:04 +00001426 return Ret;
1427 Value *Op1 = CI->getArgOperand(0);
1428 auto *OpC = dyn_cast<CallInst>(Op1);
Sanjay Patele896ede2016-01-11 23:31:48 +00001429
Sanjay Patel629c4112017-11-06 16:27:15 +00001430 // The earlier call must also be 'fast' in order to do these transforms.
1431 if (!OpC || !OpC->isFast())
Davide Italianob8b71332015-11-29 20:58:04 +00001432 return Ret;
1433
1434 // log(pow(x,y)) -> y*log(x)
1435 // This is only applicable to log, log2, log10.
1436 if (Name != "log" && Name != "log2" && Name != "log10")
1437 return Ret;
1438
1439 IRBuilder<>::FastMathFlagGuard Guard(B);
1440 FastMathFlags FMF;
Sanjay Patel629c4112017-11-06 16:27:15 +00001441 FMF.setFast();
Sanjay Patela2528152016-01-12 18:03:37 +00001442 B.setFastMathFlags(FMF);
Davide Italianob8b71332015-11-29 20:58:04 +00001443
David L. Jonesd21529f2017-01-23 23:16:46 +00001444 LibFunc Func;
Davide Italianob8b71332015-11-29 20:58:04 +00001445 Function *F = OpC->getCalledFunction();
Davide Italiano0b14f292015-11-29 21:58:56 +00001446 if (F && ((TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001447 Func == LibFunc_pow) || F->getIntrinsicID() == Intrinsic::pow))
Davide Italianob8b71332015-11-29 20:58:04 +00001448 return B.CreateFMul(OpC->getArgOperand(1),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001449 emitUnaryFloatFnCall(OpC->getOperand(0), Callee->getName(), B,
Davide Italianob8b71332015-11-29 20:58:04 +00001450 Callee->getAttributes()), "mul");
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001451
1452 // log(exp2(y)) -> y*log(2)
1453 if (F && Name == "log" && TLI->getLibFunc(F->getName(), Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001454 TLI->has(Func) && Func == LibFunc_exp2)
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001455 return B.CreateFMul(
1456 OpC->getArgOperand(0),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001457 emitUnaryFloatFnCall(ConstantFP::get(CI->getType(), 2.0),
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001458 Callee->getName(), B, Callee->getAttributes()),
1459 "logmul");
Davide Italianob8b71332015-11-29 20:58:04 +00001460 return Ret;
1461}
1462
Sanjay Patelc699a612014-10-16 18:48:17 +00001463Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1464 Function *Callee = CI->getCalledFunction();
Sanjay Patelc699a612014-10-16 18:48:17 +00001465 Value *Ret = nullptr;
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001466 // TODO: Once we have a way (other than checking for the existince of the
1467 // libcall) to tell whether our target can lower @llvm.sqrt, relax the
1468 // condition below.
David L. Jonesd21529f2017-01-23 23:16:46 +00001469 if (TLI->has(LibFunc_sqrtf) && (Callee->getName() == "sqrt" ||
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001470 Callee->getIntrinsicID() == Intrinsic::sqrt))
Sanjay Patelc699a612014-10-16 18:48:17 +00001471 Ret = optimizeUnaryDoubleFP(CI, B, true);
Sanjay Patel683f2972016-01-11 22:34:19 +00001472
Sanjay Patel629c4112017-11-06 16:27:15 +00001473 if (!CI->isFast())
Davide Italianoa904e522015-10-29 02:58:44 +00001474 return Ret;
Sanjay Patelc699a612014-10-16 18:48:17 +00001475
Sanjay Patelc2d64612016-01-06 20:52:21 +00001476 Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0));
Sanjay Patel629c4112017-11-06 16:27:15 +00001477 if (!I || I->getOpcode() != Instruction::FMul || !I->isFast())
Sanjay Patelc2d64612016-01-06 20:52:21 +00001478 return Ret;
1479
1480 // We're looking for a repeated factor in a multiplication tree,
1481 // so we can do this fold: sqrt(x * x) -> fabs(x);
Sanjay Patel683f2972016-01-11 22:34:19 +00001482 // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
Sanjay Patelc2d64612016-01-06 20:52:21 +00001483 Value *Op0 = I->getOperand(0);
1484 Value *Op1 = I->getOperand(1);
1485 Value *RepeatOp = nullptr;
1486 Value *OtherOp = nullptr;
1487 if (Op0 == Op1) {
1488 // Simple match: the operands of the multiply are identical.
1489 RepeatOp = Op0;
1490 } else {
1491 // Look for a more complicated pattern: one of the operands is itself
1492 // a multiply, so search for a common factor in that multiply.
1493 // Note: We don't bother looking any deeper than this first level or for
1494 // variations of this pattern because instcombine's visitFMUL and/or the
1495 // reassociation pass should give us this form.
1496 Value *OtherMul0, *OtherMul1;
1497 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1498 // Pattern: sqrt((x * y) * z)
Sanjay Patel629c4112017-11-06 16:27:15 +00001499 if (OtherMul0 == OtherMul1 && cast<Instruction>(Op0)->isFast()) {
Sanjay Patelc2d64612016-01-06 20:52:21 +00001500 // Matched: sqrt((x * x) * z)
1501 RepeatOp = OtherMul0;
1502 OtherOp = Op1;
Sanjay Patelc699a612014-10-16 18:48:17 +00001503 }
1504 }
1505 }
Sanjay Patelc2d64612016-01-06 20:52:21 +00001506 if (!RepeatOp)
1507 return Ret;
1508
1509 // Fast math flags for any created instructions should match the sqrt
1510 // and multiply.
Sanjay Patelc2d64612016-01-06 20:52:21 +00001511 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001512 B.setFastMathFlags(I->getFastMathFlags());
Sanjay Patel9f67dad2016-01-11 22:35:39 +00001513
Sanjay Patelc2d64612016-01-06 20:52:21 +00001514 // If we found a repeated factor, hoist it out of the square root and
1515 // replace it with the fabs of that factor.
1516 Module *M = Callee->getParent();
1517 Type *ArgType = I->getType();
1518 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1519 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1520 if (OtherOp) {
1521 // If we found a non-repeated factor, we still need to get its square
1522 // root. We then multiply that by the value that was simplified out
1523 // of the square root calculation.
1524 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1525 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1526 return B.CreateFMul(FabsCall, SqrtCall);
1527 }
1528 return FabsCall;
Sanjay Patelc699a612014-10-16 18:48:17 +00001529}
1530
Sanjay Patelcddcd722016-01-06 19:23:35 +00001531// TODO: Generalize to handle any trig function and its inverse.
Davide Italiano51507d22015-11-04 23:36:56 +00001532Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
1533 Function *Callee = CI->getCalledFunction();
1534 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001535 StringRef Name = Callee->getName();
1536 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
Davide Italiano51507d22015-11-04 23:36:56 +00001537 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italiano51507d22015-11-04 23:36:56 +00001538
Davide Italiano51507d22015-11-04 23:36:56 +00001539 Value *Op1 = CI->getArgOperand(0);
1540 auto *OpC = dyn_cast<CallInst>(Op1);
1541 if (!OpC)
1542 return Ret;
1543
Sanjay Patel629c4112017-11-06 16:27:15 +00001544 // Both calls must be 'fast' in order to remove them.
1545 if (!CI->isFast() || !OpC->isFast())
Sanjay Patelcddcd722016-01-06 19:23:35 +00001546 return Ret;
1547
Davide Italiano51507d22015-11-04 23:36:56 +00001548 // tan(atan(x)) -> x
1549 // tanf(atanf(x)) -> x
1550 // tanl(atanl(x)) -> x
David L. Jonesd21529f2017-01-23 23:16:46 +00001551 LibFunc Func;
Davide Italiano51507d22015-11-04 23:36:56 +00001552 Function *F = OpC->getCalledFunction();
Benjamin Kramerfb419e72015-11-26 09:51:17 +00001553 if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001554 ((Func == LibFunc_atan && Callee->getName() == "tan") ||
1555 (Func == LibFunc_atanf && Callee->getName() == "tanf") ||
1556 (Func == LibFunc_atanl && Callee->getName() == "tanl")))
Davide Italiano51507d22015-11-04 23:36:56 +00001557 Ret = OpC->getArgOperand(0);
1558 return Ret;
1559}
1560
Sanjay Patel57747212016-01-21 23:38:43 +00001561static bool isTrigLibCall(CallInst *CI) {
Sanjay Patel57747212016-01-21 23:38:43 +00001562 // We can only hope to do anything useful if we can ignore things like errno
1563 // and floating-point exceptions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00001564 // We already checked the prototype.
1565 return CI->hasFnAttr(Attribute::NoUnwind) &&
1566 CI->hasFnAttr(Attribute::ReadNone);
Sanjay Patel57747212016-01-21 23:38:43 +00001567}
1568
Chris Bienemanad070d02014-09-17 20:55:46 +00001569static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1570 bool UseFloat, Value *&Sin, Value *&Cos,
Sanjay Patel57747212016-01-21 23:38:43 +00001571 Value *&SinCos) {
1572 Type *ArgTy = Arg->getType();
1573 Type *ResTy;
1574 StringRef Name;
1575
1576 Triple T(OrigCallee->getParent()->getTargetTriple());
1577 if (UseFloat) {
1578 Name = "__sincospif_stret";
1579
1580 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1581 // x86_64 can't use {float, float} since that would be returned in both
1582 // xmm0 and xmm1, which isn't what a real struct would do.
1583 ResTy = T.getArch() == Triple::x86_64
Serge Gueltone38003f2017-05-09 19:31:13 +00001584 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1585 : static_cast<Type *>(StructType::get(ArgTy, ArgTy));
Sanjay Patel57747212016-01-21 23:38:43 +00001586 } else {
1587 Name = "__sincospi_stret";
Serge Gueltone38003f2017-05-09 19:31:13 +00001588 ResTy = StructType::get(ArgTy, ArgTy);
Sanjay Patel57747212016-01-21 23:38:43 +00001589 }
1590
1591 Module *M = OrigCallee->getParent();
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001592 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001593 ResTy, ArgTy);
Sanjay Patel57747212016-01-21 23:38:43 +00001594
1595 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1596 // If the argument is an instruction, it must dominate all uses so put our
1597 // sincos call there.
1598 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
1599 } else {
1600 // Otherwise (e.g. for a constant) the beginning of the function is as
1601 // good a place as any.
1602 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1603 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1604 }
1605
1606 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1607
1608 if (SinCos->getType()->isStructTy()) {
1609 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1610 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1611 } else {
1612 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1613 "sinpi");
1614 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1615 "cospi");
1616 }
1617}
Chris Bienemanad070d02014-09-17 20:55:46 +00001618
1619Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001620 // Make sure the prototype is as expected, otherwise the rest of the
1621 // function is probably invalid and likely to abort.
1622 if (!isTrigLibCall(CI))
1623 return nullptr;
1624
1625 Value *Arg = CI->getArgOperand(0);
1626 SmallVector<CallInst *, 1> SinCalls;
1627 SmallVector<CallInst *, 1> CosCalls;
1628 SmallVector<CallInst *, 1> SinCosCalls;
1629
1630 bool IsFloat = Arg->getType()->isFloatTy();
1631
1632 // Look for all compatible sinpi, cospi and sincospi calls with the same
1633 // argument. If there are enough (in some sense) we can make the
1634 // substitution.
David Majnemerabae6b52016-03-19 04:53:02 +00001635 Function *F = CI->getFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001636 for (User *U : Arg->users())
David Majnemerabae6b52016-03-19 04:53:02 +00001637 classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls);
Chris Bienemanad070d02014-09-17 20:55:46 +00001638
1639 // It's only worthwhile if both sinpi and cospi are actually used.
1640 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1641 return nullptr;
1642
1643 Value *Sin, *Cos, *SinCos;
1644 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1645
Davide Italianof024a562016-12-16 02:28:38 +00001646 auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls,
1647 Value *Res) {
1648 for (CallInst *C : Calls)
1649 replaceAllUsesWith(C, Res);
1650 };
1651
Chris Bienemanad070d02014-09-17 20:55:46 +00001652 replaceTrigInsts(SinCalls, Sin);
1653 replaceTrigInsts(CosCalls, Cos);
1654 replaceTrigInsts(SinCosCalls, SinCos);
1655
1656 return nullptr;
1657}
1658
David Majnemerabae6b52016-03-19 04:53:02 +00001659void LibCallSimplifier::classifyArgUse(
1660 Value *Val, Function *F, bool IsFloat,
1661 SmallVectorImpl<CallInst *> &SinCalls,
1662 SmallVectorImpl<CallInst *> &CosCalls,
1663 SmallVectorImpl<CallInst *> &SinCosCalls) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001664 CallInst *CI = dyn_cast<CallInst>(Val);
1665
1666 if (!CI)
1667 return;
1668
David Majnemerabae6b52016-03-19 04:53:02 +00001669 // Don't consider calls in other functions.
1670 if (CI->getFunction() != F)
1671 return;
1672
Chris Bienemanad070d02014-09-17 20:55:46 +00001673 Function *Callee = CI->getCalledFunction();
David L. Jonesd21529f2017-01-23 23:16:46 +00001674 LibFunc Func;
Ahmed Bougachad765a822016-04-27 19:04:35 +00001675 if (!Callee || !TLI->getLibFunc(*Callee, Func) || !TLI->has(Func) ||
Benjamin Kramer89766e52015-11-28 21:43:12 +00001676 !isTrigLibCall(CI))
Chris Bienemanad070d02014-09-17 20:55:46 +00001677 return;
1678
1679 if (IsFloat) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001680 if (Func == LibFunc_sinpif)
Chris Bienemanad070d02014-09-17 20:55:46 +00001681 SinCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001682 else if (Func == LibFunc_cospif)
Chris Bienemanad070d02014-09-17 20:55:46 +00001683 CosCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001684 else if (Func == LibFunc_sincospif_stret)
Chris Bienemanad070d02014-09-17 20:55:46 +00001685 SinCosCalls.push_back(CI);
1686 } else {
David L. Jonesd21529f2017-01-23 23:16:46 +00001687 if (Func == LibFunc_sinpi)
Chris Bienemanad070d02014-09-17 20:55:46 +00001688 SinCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001689 else if (Func == LibFunc_cospi)
Chris Bienemanad070d02014-09-17 20:55:46 +00001690 CosCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001691 else if (Func == LibFunc_sincospi_stret)
Chris Bienemanad070d02014-09-17 20:55:46 +00001692 SinCosCalls.push_back(CI);
1693 }
1694}
1695
Meador Inge7415f842012-11-25 20:45:27 +00001696//===----------------------------------------------------------------------===//
1697// Integer Library Call Optimizations
1698//===----------------------------------------------------------------------===//
1699
Chris Bienemanad070d02014-09-17 20:55:46 +00001700Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001701 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
Davide Italiano890e8502016-12-15 23:11:00 +00001702 Value *Op = CI->getArgOperand(0);
Chris Bienemanad070d02014-09-17 20:55:46 +00001703 Type *ArgType = Op->getType();
Davide Italiano890e8502016-12-15 23:11:00 +00001704 Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1705 Intrinsic::cttz, ArgType);
Davide Italianoa1953862015-08-13 20:34:26 +00001706 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
Chris Bienemanad070d02014-09-17 20:55:46 +00001707 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1708 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Meador Ingea0b6d872012-11-26 00:24:07 +00001709
Chris Bienemanad070d02014-09-17 20:55:46 +00001710 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1711 return B.CreateSelect(Cond, V, B.getInt32(0));
1712}
Meador Ingea0b6d872012-11-26 00:24:07 +00001713
Davide Italiano85ad36b2016-12-15 23:45:11 +00001714Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilder<> &B) {
1715 // fls(x) -> (i32)(sizeInBits(x) - llvm.ctlz(x, false))
1716 Value *Op = CI->getArgOperand(0);
1717 Type *ArgType = Op->getType();
1718 Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1719 Intrinsic::ctlz, ArgType);
1720 Value *V = B.CreateCall(F, {Op, B.getFalse()}, "ctlz");
1721 V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()),
1722 V);
1723 return B.CreateIntCast(V, CI->getType(), false);
1724}
1725
Chris Bienemanad070d02014-09-17 20:55:46 +00001726Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel4b969352018-05-22 23:29:40 +00001727 // abs(x) -> x <s 0 ? -x : x
1728 // The negation has 'nsw' because abs of INT_MIN is undefined.
1729 Value *X = CI->getArgOperand(0);
1730 Value *IsNeg = B.CreateICmpSLT(X, Constant::getNullValue(X->getType()));
1731 Value *NegX = B.CreateNSWNeg(X, "neg");
1732 return B.CreateSelect(IsNeg, NegX, X);
Chris Bienemanad070d02014-09-17 20:55:46 +00001733}
Meador Inge9a59ab62012-11-26 02:31:59 +00001734
Chris Bienemanad070d02014-09-17 20:55:46 +00001735Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001736 // isdigit(c) -> (c-'0') <u 10
1737 Value *Op = CI->getArgOperand(0);
1738 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1739 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1740 return B.CreateZExt(Op, CI->getType());
1741}
Meador Ingea62a39e2012-11-26 03:10:07 +00001742
Chris Bienemanad070d02014-09-17 20:55:46 +00001743Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001744 // isascii(c) -> c <u 128
1745 Value *Op = CI->getArgOperand(0);
1746 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1747 return B.CreateZExt(Op, CI->getType());
1748}
1749
1750Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001751 // toascii(c) -> c & 0x7f
1752 return B.CreateAnd(CI->getArgOperand(0),
1753 ConstantInt::get(CI->getType(), 0x7F));
1754}
Meador Inge604937d2012-11-26 03:38:52 +00001755
David Bolvanskycb8ca5f32018-04-25 18:58:53 +00001756Value *LibCallSimplifier::optimizeAtoi(CallInst *CI, IRBuilder<> &B) {
1757 StringRef Str;
1758 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1759 return nullptr;
1760
1761 return convertStrToNumber(CI, Str, 10);
1762}
1763
1764Value *LibCallSimplifier::optimizeStrtol(CallInst *CI, IRBuilder<> &B) {
1765 StringRef Str;
1766 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1767 return nullptr;
1768
1769 if (!isa<ConstantPointerNull>(CI->getArgOperand(1)))
1770 return nullptr;
1771
1772 if (ConstantInt *CInt = dyn_cast<ConstantInt>(CI->getArgOperand(2))) {
1773 return convertStrToNumber(CI, Str, CInt->getSExtValue());
1774 }
1775
1776 return nullptr;
1777}
1778
Meador Inge08ca1152012-11-26 20:37:20 +00001779//===----------------------------------------------------------------------===//
1780// Formatting and IO Library Call Optimizations
1781//===----------------------------------------------------------------------===//
1782
Chris Bienemanad070d02014-09-17 20:55:46 +00001783static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001784
Chris Bienemanad070d02014-09-17 20:55:46 +00001785Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1786 int StreamArg) {
Ahmed Bougachad765a822016-04-27 19:04:35 +00001787 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001788 // Error reporting calls should be cold, mark them as such.
1789 // This applies even to non-builtin calls: it is only a hint and applies to
1790 // functions that the frontend might not understand as builtins.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001791
Chris Bienemanad070d02014-09-17 20:55:46 +00001792 // This heuristic was suggested in:
1793 // Improving Static Branch Prediction in a Compiler
1794 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1795 // Proceedings of PACT'98, Oct. 1998, IEEE
Chris Bienemanad070d02014-09-17 20:55:46 +00001796 if (!CI->hasFnAttr(Attribute::Cold) &&
1797 isReportingError(Callee, CI, StreamArg)) {
Reid Klecknerb5180542017-03-21 16:57:19 +00001798 CI->addAttribute(AttributeList::FunctionIndex, Attribute::Cold);
Chris Bienemanad070d02014-09-17 20:55:46 +00001799 }
Hal Finkel66cd3f12013-11-17 02:06:35 +00001800
Chris Bienemanad070d02014-09-17 20:55:46 +00001801 return nullptr;
1802}
1803
1804static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
Davide Italiano5b65f122017-04-25 03:48:47 +00001805 if (!Callee || !Callee->isDeclaration())
Chris Bienemanad070d02014-09-17 20:55:46 +00001806 return false;
1807
1808 if (StreamArg < 0)
1809 return true;
1810
1811 // These functions might be considered cold, but only if their stream
1812 // argument is stderr.
1813
1814 if (StreamArg >= (int)CI->getNumArgOperands())
1815 return false;
1816 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1817 if (!LI)
1818 return false;
1819 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1820 if (!GV || !GV->isDeclaration())
1821 return false;
1822 return GV->getName() == "stderr";
1823}
1824
1825Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1826 // Check for a fixed format string.
1827 StringRef FormatStr;
1828 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001829 return nullptr;
Hal Finkel66cd3f12013-11-17 02:06:35 +00001830
Chris Bienemanad070d02014-09-17 20:55:46 +00001831 // Empty format string -> noop.
1832 if (FormatStr.empty()) // Tolerate printf's declared void.
1833 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001834
Chris Bienemanad070d02014-09-17 20:55:46 +00001835 // Do not do any of the following transformations if the printf return value
1836 // is used, in general the printf return value is not compatible with either
1837 // putchar() or puts().
1838 if (!CI->use_empty())
Craig Topperf40110f2014-04-25 05:29:35 +00001839 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001840
Joerg Sonnenberger8ffe7ab2016-05-09 14:36:16 +00001841 // printf("x") -> putchar('x'), even for "%" and "%%".
1842 if (FormatStr.size() == 1 || FormatStr == "%%")
Davide Italianod4f5a052016-04-03 01:46:52 +00001843 return emitPutChar(B.getInt32(FormatStr[0]), B, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001844
Davide Italiano6db1dcb2016-03-28 15:54:01 +00001845 // printf("%s", "a") --> putchar('a')
1846 if (FormatStr == "%s" && CI->getNumArgOperands() > 1) {
1847 StringRef ChrStr;
1848 if (!getConstantStringInfo(CI->getOperand(1), ChrStr))
1849 return nullptr;
1850 if (ChrStr.size() != 1)
1851 return nullptr;
Davide Italianod4f5a052016-04-03 01:46:52 +00001852 return emitPutChar(B.getInt32(ChrStr[0]), B, TLI);
Davide Italiano6db1dcb2016-03-28 15:54:01 +00001853 }
1854
Chris Bienemanad070d02014-09-17 20:55:46 +00001855 // printf("foo\n") --> puts("foo")
1856 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1857 FormatStr.find('%') == StringRef::npos) { // No format characters.
1858 // Create a string literal with no \n on it. We expect the constant merge
1859 // pass to be run after this pass, to merge duplicate strings.
1860 FormatStr = FormatStr.drop_back();
1861 Value *GV = B.CreateGlobalString(FormatStr, "str");
Davide Italianod4f5a052016-04-03 01:46:52 +00001862 return emitPutS(GV, B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001863 }
Meador Inge08ca1152012-11-26 20:37:20 +00001864
Chris Bienemanad070d02014-09-17 20:55:46 +00001865 // Optimize specific format strings.
1866 // printf("%c", chr) --> putchar(chr)
1867 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00001868 CI->getArgOperand(1)->getType()->isIntegerTy())
1869 return emitPutChar(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001870
1871 // printf("%s\n", str) --> puts(str)
1872 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00001873 CI->getArgOperand(1)->getType()->isPointerTy())
Sanjay Pateld3112a52016-01-19 19:46:10 +00001874 return emitPutS(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001875 return nullptr;
1876}
1877
1878Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1879
1880 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001881 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001882 if (Value *V = optimizePrintFString(CI, B)) {
1883 return V;
1884 }
1885
1886 // printf(format, ...) -> iprintf(format, ...) if no floating point
1887 // arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00001888 if (TLI->has(LibFunc_iprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001889 Module *M = B.GetInsertBlock()->getParent()->getParent();
1890 Constant *IPrintFFn =
Meador Inge08ca1152012-11-26 20:37:20 +00001891 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001892 CallInst *New = cast<CallInst>(CI->clone());
1893 New->setCalledFunction(IPrintFFn);
1894 B.Insert(New);
1895 return New;
Meador Inge08ca1152012-11-26 20:37:20 +00001896 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001897 return nullptr;
1898}
Meador Inge08ca1152012-11-26 20:37:20 +00001899
Chris Bienemanad070d02014-09-17 20:55:46 +00001900Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1901 // Check for a fixed format string.
1902 StringRef FormatStr;
1903 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001904 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001905
Chris Bienemanad070d02014-09-17 20:55:46 +00001906 // If we just have a format string (nothing else crazy) transform it.
1907 if (CI->getNumArgOperands() == 2) {
1908 // Make sure there's no % in the constant array. We could try to handle
1909 // %% -> % in the future if we cared.
David Bolvansky5430b7372018-05-31 16:39:27 +00001910 if (FormatStr.find('%') != StringRef::npos)
1911 return nullptr; // we found a format specifier, bail out.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001912
Daniel Neilson8acd8b02018-02-05 21:23:22 +00001913 // sprintf(str, fmt) -> llvm.memcpy(align 1 str, align 1 fmt, strlen(fmt)+1)
1914 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001915 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
Daniel Neilson8acd8b02018-02-05 21:23:22 +00001916 FormatStr.size() + 1)); // Copy the null byte.
Chris Bienemanad070d02014-09-17 20:55:46 +00001917 return ConstantInt::get(CI->getType(), FormatStr.size());
Meador Ingef8e72502012-11-29 15:45:43 +00001918 }
Meador Ingef8e72502012-11-29 15:45:43 +00001919
Chris Bienemanad070d02014-09-17 20:55:46 +00001920 // The remaining optimizations require the format string to be "%s" or "%c"
1921 // and have an extra operand.
1922 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1923 CI->getNumArgOperands() < 3)
Craig Topperf40110f2014-04-25 05:29:35 +00001924 return nullptr;
Meador Inge75798bb2012-11-29 19:15:17 +00001925
Chris Bienemanad070d02014-09-17 20:55:46 +00001926 // Decode the second character of the format string.
1927 if (FormatStr[1] == 'c') {
1928 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1929 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1930 return nullptr;
1931 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
Sanjay Pateld3112a52016-01-19 19:46:10 +00001932 Value *Ptr = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +00001933 B.CreateStore(V, Ptr);
David Blaikie3909da72015-03-30 20:42:56 +00001934 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
Chris Bienemanad070d02014-09-17 20:55:46 +00001935 B.CreateStore(B.getInt8(0), Ptr);
Meador Ingedf796f82012-10-13 16:45:24 +00001936
Chris Bienemanad070d02014-09-17 20:55:46 +00001937 return ConstantInt::get(CI->getType(), 1);
Meador Ingedf796f82012-10-13 16:45:24 +00001938 }
1939
Chris Bienemanad070d02014-09-17 20:55:46 +00001940 if (FormatStr[1] == 's') {
Chris Bienemanad070d02014-09-17 20:55:46 +00001941 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1942 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1943 return nullptr;
1944
Sanjay Pateld3112a52016-01-19 19:46:10 +00001945 Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001946 if (!Len)
1947 return nullptr;
David Majnemerabb9f552016-04-26 21:04:47 +00001948 Value *IncLen =
1949 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
Daniel Neilson8acd8b02018-02-05 21:23:22 +00001950 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(2), 1, IncLen);
Chris Bienemanad070d02014-09-17 20:55:46 +00001951
1952 // The sprintf result is the unincremented number of bytes in the string.
1953 return B.CreateIntCast(Len, CI->getType(), false);
1954 }
1955 return nullptr;
1956}
1957
1958Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1959 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001960 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001961 if (Value *V = optimizeSPrintFString(CI, B)) {
1962 return V;
1963 }
1964
1965 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1966 // point arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00001967 if (TLI->has(LibFunc_siprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001968 Module *M = B.GetInsertBlock()->getParent()->getParent();
1969 Constant *SIPrintFFn =
1970 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1971 CallInst *New = cast<CallInst>(CI->clone());
1972 New->setCalledFunction(SIPrintFFn);
1973 B.Insert(New);
1974 return New;
1975 }
1976 return nullptr;
1977}
1978
David Bolvanskycd93c4e2018-05-11 17:50:49 +00001979Value *LibCallSimplifier::optimizeSnPrintFString(CallInst *CI, IRBuilder<> &B) {
1980 // Check for a fixed format string.
1981 StringRef FormatStr;
1982 if (!getConstantStringInfo(CI->getArgOperand(2), FormatStr))
1983 return nullptr;
1984
1985 // Check for size
1986 ConstantInt *Size = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1987 if (!Size)
1988 return nullptr;
1989
1990 uint64_t N = Size->getZExtValue();
1991
1992 // If we just have a format string (nothing else crazy) transform it.
1993 if (CI->getNumArgOperands() == 3) {
1994 // Make sure there's no % in the constant array. We could try to handle
1995 // %% -> % in the future if we cared.
David Bolvansky5430b7372018-05-31 16:39:27 +00001996 if (FormatStr.find('%') != StringRef::npos)
1997 return nullptr; // we found a format specifier, bail out.
David Bolvanskycd93c4e2018-05-11 17:50:49 +00001998
1999 if (N == 0)
2000 return ConstantInt::get(CI->getType(), FormatStr.size());
2001 else if (N < FormatStr.size() + 1)
2002 return nullptr;
2003
2004 // sprintf(str, size, fmt) -> llvm.memcpy(align 1 str, align 1 fmt,
2005 // strlen(fmt)+1)
2006 B.CreateMemCpy(
2007 CI->getArgOperand(0), 1, CI->getArgOperand(2), 1,
2008 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
2009 FormatStr.size() + 1)); // Copy the null byte.
2010 return ConstantInt::get(CI->getType(), FormatStr.size());
2011 }
2012
2013 // The remaining optimizations require the format string to be "%s" or "%c"
2014 // and have an extra operand.
2015 if (FormatStr.size() == 2 && FormatStr[0] == '%' &&
2016 CI->getNumArgOperands() == 4) {
2017
2018 // Decode the second character of the format string.
2019 if (FormatStr[1] == 'c') {
2020 if (N == 0)
2021 return ConstantInt::get(CI->getType(), 1);
2022 else if (N == 1)
2023 return nullptr;
2024
2025 // snprintf(dst, size, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
2026 if (!CI->getArgOperand(3)->getType()->isIntegerTy())
2027 return nullptr;
2028 Value *V = B.CreateTrunc(CI->getArgOperand(3), B.getInt8Ty(), "char");
2029 Value *Ptr = castToCStr(CI->getArgOperand(0), B);
2030 B.CreateStore(V, Ptr);
2031 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
2032 B.CreateStore(B.getInt8(0), Ptr);
2033
2034 return ConstantInt::get(CI->getType(), 1);
2035 }
2036
2037 if (FormatStr[1] == 's') {
2038 // snprintf(dest, size, "%s", str) to llvm.memcpy(dest, str, len+1, 1)
2039 StringRef Str;
2040 if (!getConstantStringInfo(CI->getArgOperand(3), Str))
2041 return nullptr;
2042
2043 if (N == 0)
2044 return ConstantInt::get(CI->getType(), Str.size());
2045 else if (N < Str.size() + 1)
2046 return nullptr;
2047
2048 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(3), 1,
2049 ConstantInt::get(CI->getType(), Str.size() + 1));
2050
2051 // The snprintf result is the unincremented number of bytes in the string.
2052 return ConstantInt::get(CI->getType(), Str.size());
2053 }
2054 }
2055 return nullptr;
2056}
2057
2058Value *LibCallSimplifier::optimizeSnPrintF(CallInst *CI, IRBuilder<> &B) {
2059 if (Value *V = optimizeSnPrintFString(CI, B)) {
2060 return V;
2061 }
2062
2063 return nullptr;
2064}
2065
Chris Bienemanad070d02014-09-17 20:55:46 +00002066Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
2067 optimizeErrorReporting(CI, B, 0);
2068
2069 // All the optimizations depend on the format string.
2070 StringRef FormatStr;
2071 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
2072 return nullptr;
2073
2074 // Do not do any of the following transformations if the fprintf return
2075 // value is used, in general the fprintf return value is not compatible
2076 // with fwrite(), fputc() or fputs().
2077 if (!CI->use_empty())
2078 return nullptr;
2079
2080 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
2081 if (CI->getNumArgOperands() == 2) {
David Bolvansky5430b7372018-05-31 16:39:27 +00002082 // Could handle %% -> % if we cared.
2083 if (FormatStr.find('%') != StringRef::npos)
2084 return nullptr; // We found a format specifier.
Chris Bienemanad070d02014-09-17 20:55:46 +00002085
Sanjay Pateld3112a52016-01-19 19:46:10 +00002086 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00002087 CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002088 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
Chris Bienemanad070d02014-09-17 20:55:46 +00002089 CI->getArgOperand(0), B, DL, TLI);
2090 }
2091
2092 // The remaining optimizations require the format string to be "%s" or "%c"
2093 // and have an extra operand.
2094 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
2095 CI->getNumArgOperands() < 3)
2096 return nullptr;
2097
2098 // Decode the second character of the format string.
2099 if (FormatStr[1] == 'c') {
2100 // fprintf(F, "%c", chr) --> fputc(chr, F)
2101 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
2102 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00002103 return emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002104 }
2105
2106 if (FormatStr[1] == 's') {
2107 // fprintf(F, "%s", str) --> fputs(str, F)
2108 if (!CI->getArgOperand(2)->getType()->isPointerTy())
2109 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00002110 return emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002111 }
2112 return nullptr;
2113}
2114
2115Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
2116 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00002117 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00002118 if (Value *V = optimizeFPrintFString(CI, B)) {
2119 return V;
2120 }
2121
2122 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
2123 // floating point arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00002124 if (TLI->has(LibFunc_fiprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002125 Module *M = B.GetInsertBlock()->getParent()->getParent();
2126 Constant *FIPrintFFn =
2127 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
2128 CallInst *New = cast<CallInst>(CI->clone());
2129 New->setCalledFunction(FIPrintFFn);
2130 B.Insert(New);
2131 return New;
2132 }
2133 return nullptr;
2134}
2135
2136Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
2137 optimizeErrorReporting(CI, B, 3);
2138
Chris Bienemanad070d02014-09-17 20:55:46 +00002139 // Get the element size and count.
2140 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
2141 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
David Bolvanskyca22d422018-05-16 11:39:52 +00002142 if (SizeC && CountC) {
2143 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
Chris Bienemanad070d02014-09-17 20:55:46 +00002144
David Bolvanskyca22d422018-05-16 11:39:52 +00002145 // If this is writing zero records, remove the call (it's a noop).
2146 if (Bytes == 0)
2147 return ConstantInt::get(CI->getType(), 0);
Chris Bienemanad070d02014-09-17 20:55:46 +00002148
David Bolvanskyca22d422018-05-16 11:39:52 +00002149 // If this is writing one byte, turn it into fputc.
2150 // This optimisation is only valid, if the return value is unused.
2151 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
2152 Value *Char = B.CreateLoad(castToCStr(CI->getArgOperand(0), B), "char");
2153 Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI);
2154 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
2155 }
Chris Bienemanad070d02014-09-17 20:55:46 +00002156 }
2157
David Bolvanskyca22d422018-05-16 11:39:52 +00002158 if (isLocallyOpenedFile(CI->getArgOperand(3), CI, B, TLI))
2159 return emitFWriteUnlocked(CI->getArgOperand(0), CI->getArgOperand(1),
2160 CI->getArgOperand(2), CI->getArgOperand(3), B, DL,
2161 TLI);
2162
Chris Bienemanad070d02014-09-17 20:55:46 +00002163 return nullptr;
2164}
2165
2166Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
2167 optimizeErrorReporting(CI, B, 1);
2168
Sjoerd Meijer7435a912016-07-07 14:31:19 +00002169 // Don't rewrite fputs to fwrite when optimising for size because fwrite
2170 // requires more arguments and thus extra MOVs are required.
David Bolvansky5430b7372018-05-31 16:39:27 +00002171 if (CI->getFunction()->optForSize())
Sjoerd Meijer7435a912016-07-07 14:31:19 +00002172 return nullptr;
2173
David Bolvanskyca22d422018-05-16 11:39:52 +00002174 // Check if has any use
2175 if (!CI->use_empty()) {
2176 if (isLocallyOpenedFile(CI->getArgOperand(1), CI, B, TLI))
2177 return emitFPutSUnlocked(CI->getArgOperand(0), CI->getArgOperand(1), B,
2178 TLI);
2179 else
2180 // We can't optimize if return value is used.
2181 return nullptr;
2182 }
Chris Bienemanad070d02014-09-17 20:55:46 +00002183
2184 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
David Bolvansky1f343fa2018-05-22 20:27:36 +00002185 uint64_t Len = GetStringLength(CI->getArgOperand(0));
Chris Bienemanad070d02014-09-17 20:55:46 +00002186 if (!Len)
2187 return nullptr;
2188
2189 // Known to have no uses (see above).
Sanjay Pateld3112a52016-01-19 19:46:10 +00002190 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00002191 CI->getArgOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002192 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
Chris Bienemanad070d02014-09-17 20:55:46 +00002193 CI->getArgOperand(1), B, DL, TLI);
2194}
2195
David Bolvanskyca22d422018-05-16 11:39:52 +00002196Value *LibCallSimplifier::optimizeFPutc(CallInst *CI, IRBuilder<> &B) {
2197 optimizeErrorReporting(CI, B, 1);
2198
2199 if (isLocallyOpenedFile(CI->getArgOperand(1), CI, B, TLI))
2200 return emitFPutCUnlocked(CI->getArgOperand(0), CI->getArgOperand(1), B,
2201 TLI);
2202
2203 return nullptr;
2204}
2205
2206Value *LibCallSimplifier::optimizeFGetc(CallInst *CI, IRBuilder<> &B) {
2207 if (isLocallyOpenedFile(CI->getArgOperand(0), CI, B, TLI))
2208 return emitFGetCUnlocked(CI->getArgOperand(0), B, TLI);
2209
2210 return nullptr;
2211}
2212
2213Value *LibCallSimplifier::optimizeFGets(CallInst *CI, IRBuilder<> &B) {
2214 if (isLocallyOpenedFile(CI->getArgOperand(2), CI, B, TLI))
2215 return emitFGetSUnlocked(CI->getArgOperand(0), CI->getArgOperand(1),
2216 CI->getArgOperand(2), B, TLI);
2217
2218 return nullptr;
2219}
2220
2221Value *LibCallSimplifier::optimizeFRead(CallInst *CI, IRBuilder<> &B) {
2222 if (isLocallyOpenedFile(CI->getArgOperand(3), CI, B, TLI))
2223 return emitFReadUnlocked(CI->getArgOperand(0), CI->getArgOperand(1),
2224 CI->getArgOperand(2), CI->getArgOperand(3), B, DL,
2225 TLI);
2226
2227 return nullptr;
2228}
2229
Chris Bienemanad070d02014-09-17 20:55:46 +00002230Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002231 // Check for a constant string.
2232 StringRef Str;
2233 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
2234 return nullptr;
2235
2236 if (Str.empty() && CI->use_empty()) {
2237 // puts("") -> putchar('\n')
Sanjay Pateld3112a52016-01-19 19:46:10 +00002238 Value *Res = emitPutChar(B.getInt32('\n'), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002239 if (CI->use_empty() || !Res)
2240 return Res;
2241 return B.CreateIntCast(Res, CI->getType(), true);
2242 }
2243
2244 return nullptr;
2245}
2246
2247bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002248 LibFunc Func;
Meador Inge20255ef2013-03-12 00:08:29 +00002249 SmallString<20> FloatFuncName = FuncName;
2250 FloatFuncName += 'f';
2251 if (TLI->getLibFunc(FloatFuncName, Func))
2252 return TLI->has(Func);
2253 return false;
2254}
Meador Inge7fb2f732012-10-13 16:45:32 +00002255
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002256Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
2257 IRBuilder<> &Builder) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002258 LibFunc Func;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002259 Function *Callee = CI->getCalledFunction();
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002260 // Check for string/memory library functions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002261 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002262 // Make sure we never change the calling convention.
2263 assert((ignoreCallingConv(Func) ||
Sam Parker214f7bf2016-09-13 12:10:14 +00002264 isCallingConvCCompatible(CI)) &&
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002265 "Optimizing string/memory libcall would change the calling convention");
2266 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002267 case LibFunc_strcat:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002268 return optimizeStrCat(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002269 case LibFunc_strncat:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002270 return optimizeStrNCat(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002271 case LibFunc_strchr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002272 return optimizeStrChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002273 case LibFunc_strrchr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002274 return optimizeStrRChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002275 case LibFunc_strcmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002276 return optimizeStrCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002277 case LibFunc_strncmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002278 return optimizeStrNCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002279 case LibFunc_strcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002280 return optimizeStrCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002281 case LibFunc_stpcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002282 return optimizeStpCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002283 case LibFunc_strncpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002284 return optimizeStrNCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002285 case LibFunc_strlen:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002286 return optimizeStrLen(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002287 case LibFunc_strpbrk:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002288 return optimizeStrPBrk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002289 case LibFunc_strtol:
2290 case LibFunc_strtod:
2291 case LibFunc_strtof:
2292 case LibFunc_strtoul:
2293 case LibFunc_strtoll:
2294 case LibFunc_strtold:
2295 case LibFunc_strtoull:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002296 return optimizeStrTo(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002297 case LibFunc_strspn:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002298 return optimizeStrSpn(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002299 case LibFunc_strcspn:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002300 return optimizeStrCSpn(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002301 case LibFunc_strstr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002302 return optimizeStrStr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002303 case LibFunc_memchr:
Benjamin Kramer691363e2015-03-21 15:36:21 +00002304 return optimizeMemChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002305 case LibFunc_memcmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002306 return optimizeMemCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002307 case LibFunc_memcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002308 return optimizeMemCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002309 case LibFunc_memmove:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002310 return optimizeMemMove(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002311 case LibFunc_memset:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002312 return optimizeMemSet(CI, Builder);
Sanjay Patelb2ab3f22018-04-18 14:21:31 +00002313 case LibFunc_realloc:
2314 return optimizeRealloc(CI, Builder);
Matthias Braun50ec0b52017-05-19 22:37:09 +00002315 case LibFunc_wcslen:
2316 return optimizeWcslen(CI, Builder);
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002317 default:
2318 break;
2319 }
2320 }
2321 return nullptr;
2322}
2323
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002324Value *LibCallSimplifier::optimizeFloatingPointLibCall(CallInst *CI,
2325 LibFunc Func,
2326 IRBuilder<> &Builder) {
2327 // Don't optimize calls that require strict floating point semantics.
2328 if (CI->isStrictFP())
2329 return nullptr;
2330
2331 switch (Func) {
2332 case LibFunc_cosf:
2333 case LibFunc_cos:
2334 case LibFunc_cosl:
2335 return optimizeCos(CI, Builder);
2336 case LibFunc_sinpif:
2337 case LibFunc_sinpi:
2338 case LibFunc_cospif:
2339 case LibFunc_cospi:
2340 return optimizeSinCosPi(CI, Builder);
2341 case LibFunc_powf:
2342 case LibFunc_pow:
2343 case LibFunc_powl:
2344 return optimizePow(CI, Builder);
2345 case LibFunc_exp2l:
2346 case LibFunc_exp2:
2347 case LibFunc_exp2f:
2348 return optimizeExp2(CI, Builder);
2349 case LibFunc_fabsf:
2350 case LibFunc_fabs:
2351 case LibFunc_fabsl:
2352 return replaceUnaryCall(CI, Builder, Intrinsic::fabs);
2353 case LibFunc_sqrtf:
2354 case LibFunc_sqrt:
2355 case LibFunc_sqrtl:
2356 return optimizeSqrt(CI, Builder);
2357 case LibFunc_log:
2358 case LibFunc_log10:
2359 case LibFunc_log1p:
2360 case LibFunc_log2:
2361 case LibFunc_logb:
2362 return optimizeLog(CI, Builder);
2363 case LibFunc_tan:
2364 case LibFunc_tanf:
2365 case LibFunc_tanl:
2366 return optimizeTan(CI, Builder);
2367 case LibFunc_ceil:
2368 return replaceUnaryCall(CI, Builder, Intrinsic::ceil);
2369 case LibFunc_floor:
2370 return replaceUnaryCall(CI, Builder, Intrinsic::floor);
2371 case LibFunc_round:
2372 return replaceUnaryCall(CI, Builder, Intrinsic::round);
2373 case LibFunc_nearbyint:
2374 return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint);
2375 case LibFunc_rint:
2376 return replaceUnaryCall(CI, Builder, Intrinsic::rint);
2377 case LibFunc_trunc:
2378 return replaceUnaryCall(CI, Builder, Intrinsic::trunc);
2379 case LibFunc_acos:
2380 case LibFunc_acosh:
2381 case LibFunc_asin:
2382 case LibFunc_asinh:
2383 case LibFunc_atan:
2384 case LibFunc_atanh:
2385 case LibFunc_cbrt:
2386 case LibFunc_cosh:
2387 case LibFunc_exp:
2388 case LibFunc_exp10:
2389 case LibFunc_expm1:
2390 case LibFunc_sin:
2391 case LibFunc_sinh:
2392 case LibFunc_tanh:
2393 if (UnsafeFPShrink && hasFloatVersion(CI->getCalledFunction()->getName()))
2394 return optimizeUnaryDoubleFP(CI, Builder, true);
2395 return nullptr;
2396 case LibFunc_copysign:
2397 if (hasFloatVersion(CI->getCalledFunction()->getName()))
2398 return optimizeBinaryDoubleFP(CI, Builder);
2399 return nullptr;
2400 case LibFunc_fminf:
2401 case LibFunc_fmin:
2402 case LibFunc_fminl:
2403 case LibFunc_fmaxf:
2404 case LibFunc_fmax:
2405 case LibFunc_fmaxl:
2406 return optimizeFMinFMax(CI, Builder);
Hal Finkel2ff24732017-12-16 01:26:25 +00002407 case LibFunc_cabs:
2408 case LibFunc_cabsf:
2409 case LibFunc_cabsl:
2410 return optimizeCAbs(CI, Builder);
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002411 default:
2412 return nullptr;
2413 }
2414}
2415
Chris Bienemanad070d02014-09-17 20:55:46 +00002416Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002417 // TODO: Split out the code below that operates on FP calls so that
2418 // we can all non-FP calls with the StrictFP attribute to be
2419 // optimized.
Chris Bienemanad070d02014-09-17 20:55:46 +00002420 if (CI->isNoBuiltin())
2421 return nullptr;
Meador Inge4d2827c2012-11-11 05:11:20 +00002422
David L. Jonesd21529f2017-01-23 23:16:46 +00002423 LibFunc Func;
Meador Inge20255ef2013-03-12 00:08:29 +00002424 Function *Callee = CI->getCalledFunction();
David Majnemerb70e23c2016-01-06 05:01:34 +00002425
2426 SmallVector<OperandBundleDef, 2> OpBundles;
2427 CI->getOperandBundlesAsDefs(OpBundles);
2428 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Sam Parker214f7bf2016-09-13 12:10:14 +00002429 bool isCallingConvC = isCallingConvCCompatible(CI);
Meador Inge20255ef2013-03-12 00:08:29 +00002430
Sanjay Pateld1f4f032016-01-19 18:38:52 +00002431 // Command-line parameter overrides instruction attribute.
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002432 // This can't be moved to optimizeFloatingPointLibCall() because it may be
Sanjay Patel629c4112017-11-06 16:27:15 +00002433 // used by the intrinsic optimizations.
Sanjay Patela92fa442014-10-22 15:29:23 +00002434 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2435 UnsafeFPShrink = EnableUnsafeFPShrink;
Sanjay Patel629c4112017-11-06 16:27:15 +00002436 else if (isa<FPMathOperator>(CI) && CI->isFast())
Davide Italianoa904e522015-10-29 02:58:44 +00002437 UnsafeFPShrink = true;
Sanjay Patela92fa442014-10-22 15:29:23 +00002438
Sanjay Patel848309d2014-10-23 21:52:45 +00002439 // First, check for intrinsics.
Meador Inge20255ef2013-03-12 00:08:29 +00002440 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002441 if (!isCallingConvC)
2442 return nullptr;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002443 // The FP intrinsics have corresponding constrained versions so we don't
2444 // need to check for the StrictFP attribute here.
Meador Inge20255ef2013-03-12 00:08:29 +00002445 switch (II->getIntrinsicID()) {
2446 case Intrinsic::pow:
Chris Bienemanad070d02014-09-17 20:55:46 +00002447 return optimizePow(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002448 case Intrinsic::exp2:
Chris Bienemanad070d02014-09-17 20:55:46 +00002449 return optimizeExp2(CI, Builder);
Davide Italianob8b71332015-11-29 20:58:04 +00002450 case Intrinsic::log:
2451 return optimizeLog(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002452 case Intrinsic::sqrt:
2453 return optimizeSqrt(CI, Builder);
Sanjay Patel980b2802016-01-26 16:17:24 +00002454 // TODO: Use foldMallocMemset() with memset intrinsic.
Meador Inge20255ef2013-03-12 00:08:29 +00002455 default:
Chris Bienemanad070d02014-09-17 20:55:46 +00002456 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002457 }
2458 }
2459
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002460 // Also try to simplify calls to fortified library functions.
2461 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2462 // Try to further simplify the result.
Ahmed Bougacha71d7b182015-01-14 00:55:05 +00002463 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002464 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2465 // Use an IR Builder from SimplifiedCI if available instead of CI
2466 // to guarantee we reach all uses we might replace later on.
2467 IRBuilder<> TmpBuilder(SimplifiedCI);
2468 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002469 // If we were able to further simplify, remove the now redundant call.
2470 SimplifiedCI->replaceAllUsesWith(V);
2471 SimplifiedCI->eraseFromParent();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002472 return V;
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002473 }
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002474 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002475 return SimplifiedFortifiedCI;
2476 }
2477
Meador Inge20255ef2013-03-12 00:08:29 +00002478 // Then check for known library functions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002479 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002480 // We never change the calling convention.
2481 if (!ignoreCallingConv(Func) && !isCallingConvC)
2482 return nullptr;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002483 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2484 return V;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002485 if (Value *V = optimizeFloatingPointLibCall(CI, Func, Builder))
2486 return V;
Meador Inge20255ef2013-03-12 00:08:29 +00002487 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002488 case LibFunc_ffs:
2489 case LibFunc_ffsl:
2490 case LibFunc_ffsll:
Chris Bienemanad070d02014-09-17 20:55:46 +00002491 return optimizeFFS(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002492 case LibFunc_fls:
2493 case LibFunc_flsl:
2494 case LibFunc_flsll:
Davide Italiano85ad36b2016-12-15 23:45:11 +00002495 return optimizeFls(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002496 case LibFunc_abs:
2497 case LibFunc_labs:
2498 case LibFunc_llabs:
Chris Bienemanad070d02014-09-17 20:55:46 +00002499 return optimizeAbs(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002500 case LibFunc_isdigit:
Chris Bienemanad070d02014-09-17 20:55:46 +00002501 return optimizeIsDigit(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002502 case LibFunc_isascii:
Chris Bienemanad070d02014-09-17 20:55:46 +00002503 return optimizeIsAscii(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002504 case LibFunc_toascii:
Chris Bienemanad070d02014-09-17 20:55:46 +00002505 return optimizeToAscii(CI, Builder);
David Bolvanskycb8ca5f32018-04-25 18:58:53 +00002506 case LibFunc_atoi:
2507 case LibFunc_atol:
2508 case LibFunc_atoll:
2509 return optimizeAtoi(CI, Builder);
2510 case LibFunc_strtol:
2511 case LibFunc_strtoll:
2512 return optimizeStrtol(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002513 case LibFunc_printf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002514 return optimizePrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002515 case LibFunc_sprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002516 return optimizeSPrintF(CI, Builder);
David Bolvanskycd93c4e2018-05-11 17:50:49 +00002517 case LibFunc_snprintf:
2518 return optimizeSnPrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002519 case LibFunc_fprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002520 return optimizeFPrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002521 case LibFunc_fwrite:
Chris Bienemanad070d02014-09-17 20:55:46 +00002522 return optimizeFWrite(CI, Builder);
David Bolvanskyca22d422018-05-16 11:39:52 +00002523 case LibFunc_fread:
2524 return optimizeFRead(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002525 case LibFunc_fputs:
Chris Bienemanad070d02014-09-17 20:55:46 +00002526 return optimizeFPuts(CI, Builder);
David Bolvanskyca22d422018-05-16 11:39:52 +00002527 case LibFunc_fgets:
2528 return optimizeFGets(CI, Builder);
2529 case LibFunc_fputc:
2530 return optimizeFPutc(CI, Builder);
2531 case LibFunc_fgetc:
2532 return optimizeFGetc(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002533 case LibFunc_puts:
Chris Bienemanad070d02014-09-17 20:55:46 +00002534 return optimizePuts(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002535 case LibFunc_perror:
Chris Bienemanad070d02014-09-17 20:55:46 +00002536 return optimizeErrorReporting(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002537 case LibFunc_vfprintf:
2538 case LibFunc_fiprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002539 return optimizeErrorReporting(CI, Builder, 0);
Chris Bienemanad070d02014-09-17 20:55:46 +00002540 default:
2541 return nullptr;
2542 }
Meador Inge20255ef2013-03-12 00:08:29 +00002543 }
Craig Topperf40110f2014-04-25 05:29:35 +00002544 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00002545}
2546
Chandler Carruth92803822015-01-21 02:11:59 +00002547LibCallSimplifier::LibCallSimplifier(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002548 const DataLayout &DL, const TargetLibraryInfo *TLI,
Adam Nemetea06e6e2017-07-26 19:03:18 +00002549 OptimizationRemarkEmitter &ORE,
Chandler Carruth92803822015-01-21 02:11:59 +00002550 function_ref<void(Instruction *, Value *)> Replacer)
Adam Nemetea06e6e2017-07-26 19:03:18 +00002551 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), ORE(ORE),
2552 UnsafeFPShrink(false), Replacer(Replacer) {}
Chandler Carruth92803822015-01-21 02:11:59 +00002553
2554void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2555 // Indirect through the replacer used in this instance.
2556 Replacer(I, With);
Meador Ingedf796f82012-10-13 16:45:24 +00002557}
2558
Meador Ingedfb08a22013-06-20 19:48:07 +00002559// TODO:
2560// Additional cases that we need to add to this file:
2561//
2562// cbrt:
2563// * cbrt(expN(X)) -> expN(x/3)
2564// * cbrt(sqrt(x)) -> pow(x,1/6)
David Majnemer3354fe42015-08-26 18:30:16 +00002565// * cbrt(cbrt(x)) -> pow(x,1/9)
Meador Ingedfb08a22013-06-20 19:48:07 +00002566//
2567// exp, expf, expl:
2568// * exp(log(x)) -> x
2569//
2570// log, logf, logl:
2571// * log(exp(x)) -> x
Meador Ingedfb08a22013-06-20 19:48:07 +00002572// * log(exp(y)) -> y*log(e)
Meador Ingedfb08a22013-06-20 19:48:07 +00002573// * log(exp10(y)) -> y*log(10)
2574// * log(sqrt(x)) -> 0.5*log(x)
Meador Ingedfb08a22013-06-20 19:48:07 +00002575//
Meador Ingedfb08a22013-06-20 19:48:07 +00002576// pow, powf, powl:
Meador Ingedfb08a22013-06-20 19:48:07 +00002577// * pow(sqrt(x),y) -> pow(x,y*0.5)
2578// * pow(pow(x,y),z)-> pow(x,y*z)
2579//
Meador Ingedfb08a22013-06-20 19:48:07 +00002580// signbit:
2581// * signbit(cnst) -> cnst'
2582// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2583//
2584// sqrt, sqrtf, sqrtl:
2585// * sqrt(expN(x)) -> expN(x*0.5)
2586// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2587// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2588//
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002589
2590//===----------------------------------------------------------------------===//
2591// Fortified Library Call Optimizations
2592//===----------------------------------------------------------------------===//
2593
2594bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2595 unsigned ObjSizeOp,
2596 unsigned SizeOp,
2597 bool isString) {
2598 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2599 return true;
2600 if (ConstantInt *ObjSizeCI =
2601 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
Craig Topper79ab6432017-07-06 18:39:47 +00002602 if (ObjSizeCI->isMinusOne())
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002603 return true;
2604 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2605 if (OnlyLowerUnknownSize)
2606 return false;
2607 if (isString) {
David Bolvansky1f343fa2018-05-22 20:27:36 +00002608 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002609 // If the length is 0 we don't know how long it is and so we can't
2610 // remove the check.
2611 if (Len == 0)
2612 return false;
2613 return ObjSizeCI->getZExtValue() >= Len;
2614 }
2615 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2616 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2617 }
2618 return false;
2619}
2620
Sanjay Pateld707db92015-12-31 16:10:49 +00002621Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
2622 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002623 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +00002624 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
2625 CI->getArgOperand(2));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002626 return CI->getArgOperand(0);
2627 }
2628 return nullptr;
2629}
2630
Sanjay Pateld707db92015-12-31 16:10:49 +00002631Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
2632 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002633 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +00002634 B.CreateMemMove(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
2635 CI->getArgOperand(2));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002636 return CI->getArgOperand(0);
2637 }
2638 return nullptr;
2639}
2640
Sanjay Pateld707db92015-12-31 16:10:49 +00002641Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
2642 IRBuilder<> &B) {
Sanjay Patel980b2802016-01-26 16:17:24 +00002643 // TODO: Try foldMallocMemset() here.
2644
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002645 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2646 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2647 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2648 return CI->getArgOperand(0);
2649 }
2650 return nullptr;
2651}
2652
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002653Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2654 IRBuilder<> &B,
David L. Jonesd21529f2017-01-23 23:16:46 +00002655 LibFunc Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002656 Function *Callee = CI->getCalledFunction();
2657 StringRef Name = Callee->getName();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002658 const DataLayout &DL = CI->getModule()->getDataLayout();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002659 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2660 *ObjSize = CI->getArgOperand(2);
2661
2662 // __stpcpy_chk(x,x,...) -> x+strlen(x)
David L. Jonesd21529f2017-01-23 23:16:46 +00002663 if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002664 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +00002665 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002666 }
2667
2668 // If a) we don't have any length information, or b) we know this will
2669 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2670 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2671 // TODO: It might be nice to get a maximum length out of the possible
2672 // string lengths for varying.
David Blaikie65fab6d2015-04-03 21:32:06 +00002673 if (isFortifiedCallFoldable(CI, 2, 1, true))
Sanjay Pateld3112a52016-01-19 19:46:10 +00002674 return emitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002675
David Blaikie65fab6d2015-04-03 21:32:06 +00002676 if (OnlyLowerUnknownSize)
2677 return nullptr;
2678
2679 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
David Bolvansky1f343fa2018-05-22 20:27:36 +00002680 uint64_t Len = GetStringLength(Src);
David Blaikie65fab6d2015-04-03 21:32:06 +00002681 if (Len == 0)
2682 return nullptr;
2683
2684 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2685 Value *LenV = ConstantInt::get(SizeTTy, Len);
Sanjay Pateld3112a52016-01-19 19:46:10 +00002686 Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
David Blaikie65fab6d2015-04-03 21:32:06 +00002687 // If the function was an __stpcpy_chk, and we were able to fold it into
2688 // a __memcpy_chk, we still need to return the correct end pointer.
David L. Jonesd21529f2017-01-23 23:16:46 +00002689 if (Ret && Func == LibFunc_stpcpy_chk)
David Blaikie65fab6d2015-04-03 21:32:06 +00002690 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2691 return Ret;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002692}
2693
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002694Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2695 IRBuilder<> &B,
David L. Jonesd21529f2017-01-23 23:16:46 +00002696 LibFunc Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002697 Function *Callee = CI->getCalledFunction();
2698 StringRef Name = Callee->getName();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002699 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002700 Value *Ret = emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002701 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002702 return Ret;
2703 }
2704 return nullptr;
2705}
2706
2707Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002708 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2709 // Some clang users checked for _chk libcall availability using:
2710 // __has_builtin(__builtin___memcpy_chk)
2711 // When compiling with -fno-builtin, this is always true.
2712 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2713 // end up with fortified libcalls, which isn't acceptable in a freestanding
2714 // environment which only provides their non-fortified counterparts.
2715 //
2716 // Until we change clang and/or teach external users to check for availability
2717 // differently, disregard the "nobuiltin" attribute and TLI::has.
2718 //
2719 // PR23093.
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002720
David L. Jonesd21529f2017-01-23 23:16:46 +00002721 LibFunc Func;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002722 Function *Callee = CI->getCalledFunction();
David Majnemerb70e23c2016-01-06 05:01:34 +00002723
2724 SmallVector<OperandBundleDef, 2> OpBundles;
2725 CI->getOperandBundlesAsDefs(OpBundles);
2726 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Sam Parker214f7bf2016-09-13 12:10:14 +00002727 bool isCallingConvC = isCallingConvCCompatible(CI);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002728
Ahmed Bougachad765a822016-04-27 19:04:35 +00002729 // First, check that this is a known library functions and that the prototype
2730 // is correct.
2731 if (!TLI->getLibFunc(*Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002732 return nullptr;
2733
2734 // We never change the calling convention.
2735 if (!ignoreCallingConv(Func) && !isCallingConvC)
2736 return nullptr;
2737
2738 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002739 case LibFunc_memcpy_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002740 return optimizeMemCpyChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002741 case LibFunc_memmove_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002742 return optimizeMemMoveChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002743 case LibFunc_memset_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002744 return optimizeMemSetChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002745 case LibFunc_stpcpy_chk:
2746 case LibFunc_strcpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002747 return optimizeStrpCpyChk(CI, Builder, Func);
David L. Jonesd21529f2017-01-23 23:16:46 +00002748 case LibFunc_stpncpy_chk:
2749 case LibFunc_strncpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002750 return optimizeStrpNCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002751 default:
2752 break;
2753 }
2754 return nullptr;
2755}
2756
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002757FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2758 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
Sanjay Patel4b969352018-05-22 23:29:40 +00002759 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}