Coverage Report

Created: 2019-07-24 05:18

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