blob: e9c089dbd07e99615529935029b0d915365c8b95 [file] [log] [blame]
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001//===- SimplifyLibCalls.cpp - Optimize specific well-known library calls --===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements a simple pass that applies a variety of small
11// optimizations for calls to specific well-known function calls (e.g. runtime
12// library functions). For example, a call to the function "exit(3)" that
13// occurs within the main() function can be transformed into a simple "return 3"
14// instruction. Any optimization that takes this form (replace call to library
15// function with simpler code that provides the same result) belongs in this
16// file.
17//
18//===----------------------------------------------------------------------===//
19
20#define DEBUG_TYPE "simplify-libcalls"
21#include "llvm/Transforms/Scalar.h"
22#include "llvm/Intrinsics.h"
23#include "llvm/Module.h"
24#include "llvm/Pass.h"
25#include "llvm/Support/IRBuilder.h"
26#include "llvm/Target/TargetData.h"
27#include "llvm/ADT/SmallPtrSet.h"
28#include "llvm/ADT/StringMap.h"
29#include "llvm/ADT/Statistic.h"
30#include "llvm/Support/Compiler.h"
Chris Lattner56b4f2b2008-05-01 06:39:12 +000031#include "llvm/Support/Debug.h"
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000032#include "llvm/Config/config.h"
33using namespace llvm;
34
35STATISTIC(NumSimplified, "Number of library calls simplified");
36
37//===----------------------------------------------------------------------===//
38// Optimizer Base Class
39//===----------------------------------------------------------------------===//
40
41/// This class is the abstract base class for the set of optimizations that
42/// corresponds to one library call.
43namespace {
44class VISIBILITY_HIDDEN LibCallOptimization {
45protected:
46 Function *Caller;
47 const TargetData *TD;
48public:
49 LibCallOptimization() { }
50 virtual ~LibCallOptimization() {}
51
52 /// CallOptimizer - This pure virtual method is implemented by base classes to
53 /// do various optimizations. If this returns null then no transformation was
54 /// performed. If it returns CI, then it transformed the call and CI is to be
55 /// deleted. If it returns something else, replace CI with the new value and
56 /// delete CI.
57 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder &B) =0;
58
59 Value *OptimizeCall(CallInst *CI, const TargetData &TD, IRBuilder &B) {
60 Caller = CI->getParent()->getParent();
61 this->TD = &TD;
62 return CallOptimizer(CI->getCalledFunction(), CI, B);
63 }
64
65 /// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
66 Value *CastToCStr(Value *V, IRBuilder &B);
67
68 /// EmitStrLen - Emit a call to the strlen function to the builder, for the
69 /// specified pointer. Ptr is required to be some pointer type, and the
70 /// return value has 'intptr_t' type.
71 Value *EmitStrLen(Value *Ptr, IRBuilder &B);
72
73 /// EmitMemCpy - Emit a call to the memcpy function to the builder. This
74 /// always expects that the size has type 'intptr_t' and Dst/Src are pointers.
75 Value *EmitMemCpy(Value *Dst, Value *Src, Value *Len,
76 unsigned Align, IRBuilder &B);
77
78 /// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is
79 /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
80 Value *EmitMemChr(Value *Ptr, Value *Val, Value *Len, IRBuilder &B);
81
82 /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
83 /// 'floor'). This function is known to take a single of type matching 'Op'
84 /// and returns one value with the same type. If 'Op' is a long double, 'l'
85 /// is added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
86 Value *EmitUnaryFloatFnCall(Value *Op, const char *Name, IRBuilder &B);
87
88 /// EmitPutChar - Emit a call to the putchar function. This assumes that Char
89 /// is an integer.
90 void EmitPutChar(Value *Char, IRBuilder &B);
91
92 /// EmitPutS - Emit a call to the puts function. This assumes that Str is
93 /// some pointer.
94 void EmitPutS(Value *Str, IRBuilder &B);
95
96 /// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
97 /// an i32, and File is a pointer to FILE.
98 void EmitFPutC(Value *Char, Value *File, IRBuilder &B);
99
100 /// EmitFPutS - Emit a call to the puts function. Str is required to be a
101 /// pointer and File is a pointer to FILE.
102 void EmitFPutS(Value *Str, Value *File, IRBuilder &B);
103
104 /// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
105 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
106 void EmitFWrite(Value *Ptr, Value *Size, Value *File, IRBuilder &B);
107
108};
109} // End anonymous namespace.
110
111/// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
112Value *LibCallOptimization::CastToCStr(Value *V, IRBuilder &B) {
113 return B.CreateBitCast(V, PointerType::getUnqual(Type::Int8Ty), "cstr");
114}
115
116/// EmitStrLen - Emit a call to the strlen function to the builder, for the
117/// specified pointer. This always returns an integer value of size intptr_t.
118Value *LibCallOptimization::EmitStrLen(Value *Ptr, IRBuilder &B) {
119 Module *M = Caller->getParent();
120 Constant *StrLen =M->getOrInsertFunction("strlen", TD->getIntPtrType(),
121 PointerType::getUnqual(Type::Int8Ty),
122 NULL);
123 return B.CreateCall(StrLen, CastToCStr(Ptr, B), "strlen");
124}
125
126/// EmitMemCpy - Emit a call to the memcpy function to the builder. This always
127/// expects that the size has type 'intptr_t' and Dst/Src are pointers.
128Value *LibCallOptimization::EmitMemCpy(Value *Dst, Value *Src, Value *Len,
129 unsigned Align, IRBuilder &B) {
130 Module *M = Caller->getParent();
131 Intrinsic::ID IID = TD->getIntPtrType() == Type::Int32Ty ?
132 Intrinsic::memcpy_i32 : Intrinsic::memcpy_i64;
133 Value *MemCpy = Intrinsic::getDeclaration(M, IID);
134 return B.CreateCall4(MemCpy, CastToCStr(Dst, B), CastToCStr(Src, B), Len,
135 ConstantInt::get(Type::Int32Ty, Align));
136}
137
138/// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is
139/// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
140Value *LibCallOptimization::EmitMemChr(Value *Ptr, Value *Val,
141 Value *Len, IRBuilder &B) {
142 Module *M = Caller->getParent();
143 Value *MemChr = M->getOrInsertFunction("memchr",
144 PointerType::getUnqual(Type::Int8Ty),
145 PointerType::getUnqual(Type::Int8Ty),
146 Type::Int32Ty, TD->getIntPtrType(),
147 NULL);
148 return B.CreateCall3(MemChr, CastToCStr(Ptr, B), Val, Len, "memchr");
149}
150
151/// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
152/// 'floor'). This function is known to take a single of type matching 'Op' and
153/// returns one value with the same type. If 'Op' is a long double, 'l' is
154/// added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
155Value *LibCallOptimization::EmitUnaryFloatFnCall(Value *Op, const char *Name,
156 IRBuilder &B) {
157 char NameBuffer[20];
158 if (Op->getType() != Type::DoubleTy) {
159 // If we need to add a suffix, copy into NameBuffer.
160 unsigned NameLen = strlen(Name);
161 assert(NameLen < sizeof(NameBuffer)-2);
162 memcpy(NameBuffer, Name, NameLen);
163 if (Op->getType() == Type::FloatTy)
164 NameBuffer[NameLen] = 'f'; // floorf
165 else
166 NameBuffer[NameLen] = 'l'; // floorl
167 NameBuffer[NameLen+1] = 0;
168 Name = NameBuffer;
169 }
170
171 Module *M = Caller->getParent();
172 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
173 Op->getType(), NULL);
174 return B.CreateCall(Callee, Op, Name);
175}
176
177/// EmitPutChar - Emit a call to the putchar function. This assumes that Char
178/// is an integer.
179void LibCallOptimization::EmitPutChar(Value *Char, IRBuilder &B) {
180 Module *M = Caller->getParent();
181 Value *F = M->getOrInsertFunction("putchar", Type::Int32Ty,
182 Type::Int32Ty, NULL);
183 B.CreateCall(F, B.CreateIntCast(Char, Type::Int32Ty, "chari"), "putchar");
184}
185
186/// EmitPutS - Emit a call to the puts function. This assumes that Str is
187/// some pointer.
188void LibCallOptimization::EmitPutS(Value *Str, IRBuilder &B) {
189 Module *M = Caller->getParent();
190 Value *F = M->getOrInsertFunction("puts", Type::Int32Ty,
191 PointerType::getUnqual(Type::Int8Ty), NULL);
192 B.CreateCall(F, CastToCStr(Str, B), "puts");
193}
194
195/// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
196/// an integer and File is a pointer to FILE.
197void LibCallOptimization::EmitFPutC(Value *Char, Value *File, IRBuilder &B) {
198 Module *M = Caller->getParent();
199 Constant *F = M->getOrInsertFunction("fputc", Type::Int32Ty, Type::Int32Ty,
200 File->getType(), NULL);
201 Char = B.CreateIntCast(Char, Type::Int32Ty, "chari");
202 B.CreateCall2(F, Char, File, "fputc");
203}
204
205/// EmitFPutS - Emit a call to the puts function. Str is required to be a
206/// pointer and File is a pointer to FILE.
207void LibCallOptimization::EmitFPutS(Value *Str, Value *File, IRBuilder &B) {
208 Module *M = Caller->getParent();
209 Constant *F = M->getOrInsertFunction("fputs", Type::Int32Ty,
210 PointerType::getUnqual(Type::Int8Ty),
211 File->getType(), NULL);
212 B.CreateCall2(F, CastToCStr(Str, B), File, "fputs");
213}
214
215/// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
216/// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
217void LibCallOptimization::EmitFWrite(Value *Ptr, Value *Size, Value *File,
218 IRBuilder &B) {
219 Module *M = Caller->getParent();
220 Constant *F = M->getOrInsertFunction("fwrite", TD->getIntPtrType(),
221 PointerType::getUnqual(Type::Int8Ty),
222 TD->getIntPtrType(), TD->getIntPtrType(),
223 File->getType(), NULL);
224 B.CreateCall4(F, CastToCStr(Ptr, B), Size,
225 ConstantInt::get(TD->getIntPtrType(), 1), File);
226}
227
228//===----------------------------------------------------------------------===//
229// Helper Functions
230//===----------------------------------------------------------------------===//
231
232/// GetConstantStringInfo - This function computes the length of a
233/// null-terminated C string pointed to by V. If successful, it returns true
234/// and returns the string in Str. If unsuccessful, it returns false.
235static bool GetConstantStringInfo(Value *V, std::string &Str) {
236 // Look bitcast instructions.
237 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
238 return GetConstantStringInfo(BCI->getOperand(0), Str);
239
240 // If the value is not a GEP instruction nor a constant expression with a
241 // GEP instruction, then return false because ConstantArray can't occur
242 // any other way
243 User *GEP = 0;
244 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
245 GEP = GEPI;
246 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
247 if (CE->getOpcode() != Instruction::GetElementPtr)
248 return false;
249 GEP = CE;
250 } else {
251 return false;
252 }
253
254 // Make sure the GEP has exactly three arguments.
255 if (GEP->getNumOperands() != 3)
256 return false;
257
258 // Check to make sure that the first operand of the GEP is an integer and
259 // has value 0 so that we are sure we're indexing into the initializer.
260 if (ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
261 if (!Idx->isZero())
262 return false;
263 } else
264 return false;
265
266 // If the second index isn't a ConstantInt, then this is a variable index
267 // into the array. If this occurs, we can't say anything meaningful about
268 // the string.
269 uint64_t StartIdx = 0;
270 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
271 StartIdx = CI->getZExtValue();
272 else
273 return false;
274
275 // The GEP instruction, constant or instruction, must reference a global
276 // variable that is a constant and is initialized. The referenced constant
277 // initializer is the array that we'll use for optimization.
278 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
279 if (!GV || !GV->isConstant() || !GV->hasInitializer())
280 return false;
281 Constant *GlobalInit = GV->getInitializer();
282
283 // Handle the ConstantAggregateZero case
284 if (isa<ConstantAggregateZero>(GlobalInit)) {
285 // This is a degenerate case. The initializer is constant zero so the
286 // length of the string must be zero.
287 Str.clear();
288 return true;
289 }
290
291 // Must be a Constant Array
292 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
293 if (Array == 0 || Array->getType()->getElementType() != Type::Int8Ty)
294 return false;
295
296 // Get the number of elements in the array
297 uint64_t NumElts = Array->getType()->getNumElements();
298
299 // Traverse the constant array from StartIdx (derived above) which is
300 // the place the GEP refers to in the array.
301 for (unsigned i = StartIdx; i < NumElts; ++i) {
302 Constant *Elt = Array->getOperand(i);
303 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
304 if (!CI) // This array isn't suitable, non-int initializer.
305 return false;
306 if (CI->isZero())
307 return true; // we found end of string, success!
308 Str += (char)CI->getZExtValue();
309 }
310
311 return false; // The array isn't null terminated.
312}
313
314/// GetStringLengthH - If we can compute the length of the string pointed to by
315/// the specified pointer, return 'len+1'. If we can't, return 0.
316static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
317 // Look through noop bitcast instructions.
318 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
319 return GetStringLengthH(BCI->getOperand(0), PHIs);
320
321 // If this is a PHI node, there are two cases: either we have already seen it
322 // or we haven't.
323 if (PHINode *PN = dyn_cast<PHINode>(V)) {
324 if (!PHIs.insert(PN))
325 return ~0ULL; // already in the set.
326
327 // If it was new, see if all the input strings are the same length.
328 uint64_t LenSoFar = ~0ULL;
329 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
330 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
331 if (Len == 0) return 0; // Unknown length -> unknown.
332
333 if (Len == ~0ULL) continue;
334
335 if (Len != LenSoFar && LenSoFar != ~0ULL)
336 return 0; // Disagree -> unknown.
337 LenSoFar = Len;
338 }
339
340 // Success, all agree.
341 return LenSoFar;
342 }
343
344 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
345 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
346 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
347 if (Len1 == 0) return 0;
348 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
349 if (Len2 == 0) return 0;
350 if (Len1 == ~0ULL) return Len2;
351 if (Len2 == ~0ULL) return Len1;
352 if (Len1 != Len2) return 0;
353 return Len1;
354 }
355
356 // If the value is not a GEP instruction nor a constant expression with a
357 // GEP instruction, then return unknown.
358 User *GEP = 0;
359 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
360 GEP = GEPI;
361 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
362 if (CE->getOpcode() != Instruction::GetElementPtr)
363 return 0;
364 GEP = CE;
365 } else {
366 return 0;
367 }
368
369 // Make sure the GEP has exactly three arguments.
370 if (GEP->getNumOperands() != 3)
371 return 0;
372
373 // Check to make sure that the first operand of the GEP is an integer and
374 // has value 0 so that we are sure we're indexing into the initializer.
375 if (ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
376 if (!Idx->isZero())
377 return 0;
378 } else
379 return 0;
380
381 // If the second index isn't a ConstantInt, then this is a variable index
382 // into the array. If this occurs, we can't say anything meaningful about
383 // the string.
384 uint64_t StartIdx = 0;
385 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
386 StartIdx = CI->getZExtValue();
387 else
388 return 0;
389
390 // The GEP instruction, constant or instruction, must reference a global
391 // variable that is a constant and is initialized. The referenced constant
392 // initializer is the array that we'll use for optimization.
393 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
394 if (!GV || !GV->isConstant() || !GV->hasInitializer())
395 return 0;
396 Constant *GlobalInit = GV->getInitializer();
397
398 // Handle the ConstantAggregateZero case, which is a degenerate case. The
399 // initializer is constant zero so the length of the string must be zero.
400 if (isa<ConstantAggregateZero>(GlobalInit))
401 return 1; // Len = 0 offset by 1.
402
403 // Must be a Constant Array
404 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
405 if (!Array || Array->getType()->getElementType() != Type::Int8Ty)
406 return false;
407
408 // Get the number of elements in the array
409 uint64_t NumElts = Array->getType()->getNumElements();
410
411 // Traverse the constant array from StartIdx (derived above) which is
412 // the place the GEP refers to in the array.
413 for (unsigned i = StartIdx; i != NumElts; ++i) {
414 Constant *Elt = Array->getOperand(i);
415 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
416 if (!CI) // This array isn't suitable, non-int initializer.
417 return 0;
418 if (CI->isZero())
419 return i-StartIdx+1; // We found end of string, success!
420 }
421
422 return 0; // The array isn't null terminated, conservatively return 'unknown'.
423}
424
425/// GetStringLength - If we can compute the length of the string pointed to by
426/// the specified pointer, return 'len+1'. If we can't, return 0.
427static uint64_t GetStringLength(Value *V) {
428 if (!isa<PointerType>(V->getType())) return 0;
429
430 SmallPtrSet<PHINode*, 32> PHIs;
431 uint64_t Len = GetStringLengthH(V, PHIs);
432 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
433 // an empty string as a length.
434 return Len == ~0ULL ? 1 : Len;
435}
436
437/// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
438/// value is equal or not-equal to zero.
439static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
440 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
441 UI != E; ++UI) {
442 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
443 if (IC->isEquality())
444 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
445 if (C->isNullValue())
446 continue;
447 // Unknown instruction.
448 return false;
449 }
450 return true;
451}
452
453//===----------------------------------------------------------------------===//
454// Miscellaneous LibCall Optimizations
455//===----------------------------------------------------------------------===//
456
457//===---------------------------------------===//
458// 'exit' Optimizations
459
460/// ExitOpt - int main() { exit(4); } --> int main() { return 4; }
461struct VISIBILITY_HIDDEN ExitOpt : public LibCallOptimization {
462 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder &B) {
463 // Verify we have a reasonable prototype for exit.
464 if (Callee->arg_size() == 0 || !CI->use_empty())
465 return 0;
466
467 // Verify the caller is main, and that the result type of main matches the
468 // argument type of exit.
469 if (!Caller->isName("main") || !Caller->hasExternalLinkage() ||
470 Caller->getReturnType() != CI->getOperand(1)->getType())
471 return 0;
472
473 TerminatorInst *OldTI = CI->getParent()->getTerminator();
474
475 // Create the return after the call.
476 ReturnInst *RI = B.CreateRet(CI->getOperand(1));
477
478 // Drop all successor phi node entries.
479 for (unsigned i = 0, e = OldTI->getNumSuccessors(); i != e; ++i)
480 OldTI->getSuccessor(i)->removePredecessor(CI->getParent());
481
482 // Erase all instructions from after our return instruction until the end of
483 // the block.
484 BasicBlock::iterator FirstDead = RI; ++FirstDead;
485 CI->getParent()->getInstList().erase(FirstDead, CI->getParent()->end());
486 return CI;
487 }
488};
489
490//===----------------------------------------------------------------------===//
491// String and Memory LibCall Optimizations
492//===----------------------------------------------------------------------===//
493
494//===---------------------------------------===//
495// 'strcat' Optimizations
496
497struct VISIBILITY_HIDDEN StrCatOpt : public LibCallOptimization {
498 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder &B) {
499 // Verify the "strcat" function prototype.
500 const FunctionType *FT = Callee->getFunctionType();
501 if (FT->getNumParams() != 2 ||
502 FT->getReturnType() != PointerType::getUnqual(Type::Int8Ty) ||
503 FT->getParamType(0) != FT->getReturnType() ||
504 FT->getParamType(1) != FT->getReturnType())
505 return 0;
506
507 // Extract some information from the instruction
508 Value *Dst = CI->getOperand(1);
509 Value *Src = CI->getOperand(2);
510
511 // See if we can get the length of the input string.
512 uint64_t Len = GetStringLength(Src);
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000513 if (Len == 0) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000514 --Len; // Unbias length.
515
516 // Handle the simple, do-nothing case: strcat(x, "") -> x
517 if (Len == 0)
518 return Dst;
519
520 // We need to find the end of the destination string. That's where the
521 // memory is to be moved to. We just generate a call to strlen.
522 Value *DstLen = EmitStrLen(Dst, B);
523
524 // Now that we have the destination's length, we must index into the
525 // destination's pointer to get the actual memcpy destination (end of
526 // the string .. we're concatenating).
527 Dst = B.CreateGEP(Dst, DstLen, "endptr");
528
529 // We have enough information to now generate the memcpy call to do the
530 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
531 EmitMemCpy(Dst, Src, ConstantInt::get(TD->getIntPtrType(), Len+1), 1, B);
532 return Dst;
533 }
534};
535
536//===---------------------------------------===//
537// 'strchr' Optimizations
538
539struct VISIBILITY_HIDDEN StrChrOpt : public LibCallOptimization {
540 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder &B) {
541 // Verify the "strchr" function prototype.
542 const FunctionType *FT = Callee->getFunctionType();
543 if (FT->getNumParams() != 2 ||
544 FT->getReturnType() != PointerType::getUnqual(Type::Int8Ty) ||
545 FT->getParamType(0) != FT->getReturnType())
546 return 0;
547
548 Value *SrcStr = CI->getOperand(1);
549
550 // If the second operand is non-constant, see if we can compute the length
551 // of the input string and turn this into memchr.
552 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getOperand(2));
553 if (CharC == 0) {
554 uint64_t Len = GetStringLength(SrcStr);
555 if (Len == 0 || FT->getParamType(1) != Type::Int32Ty) // memchr needs i32.
556 return 0;
557
558 return EmitMemChr(SrcStr, CI->getOperand(2), // include nul.
559 ConstantInt::get(TD->getIntPtrType(), Len), B);
560 }
561
562 // Otherwise, the character is a constant, see if the first argument is
563 // a string literal. If so, we can constant fold.
564 std::string Str;
565 if (!GetConstantStringInfo(SrcStr, Str))
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000566 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000567
568 // strchr can find the nul character.
569 Str += '\0';
570 char CharValue = CharC->getSExtValue();
571
572 // Compute the offset.
573 uint64_t i = 0;
574 while (1) {
575 if (i == Str.size()) // Didn't find the char. strchr returns null.
576 return Constant::getNullValue(CI->getType());
577 // Did we find our match?
578 if (Str[i] == CharValue)
579 break;
580 ++i;
581 }
582
583 // strchr(s+n,c) -> gep(s+n+i,c)
584 Value *Idx = ConstantInt::get(Type::Int64Ty, i);
585 return B.CreateGEP(SrcStr, Idx, "strchr");
586 }
587};
588
589//===---------------------------------------===//
590// 'strcmp' Optimizations
591
592struct VISIBILITY_HIDDEN StrCmpOpt : public LibCallOptimization {
593 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder &B) {
594 // Verify the "strcmp" function prototype.
595 const FunctionType *FT = Callee->getFunctionType();
596 if (FT->getNumParams() != 2 || FT->getReturnType() != Type::Int32Ty ||
597 FT->getParamType(0) != FT->getParamType(1) ||
598 FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty))
599 return 0;
600
601 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
602 if (Str1P == Str2P) // strcmp(x,x) -> 0
603 return ConstantInt::get(CI->getType(), 0);
604
605 std::string Str1, Str2;
606 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
607 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
608
609 if (HasStr1 && Str1.empty()) // strcmp("", x) -> *x
610 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
611
612 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
613 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
614
615 // strcmp(x, y) -> cnst (if both x and y are constant strings)
616 if (HasStr1 && HasStr2)
617 return ConstantInt::get(CI->getType(), strcmp(Str1.c_str(),Str2.c_str()));
618 return 0;
619 }
620};
621
622//===---------------------------------------===//
623// 'strncmp' Optimizations
624
625struct VISIBILITY_HIDDEN StrNCmpOpt : public LibCallOptimization {
626 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder &B) {
627 // Verify the "strncmp" function prototype.
628 const FunctionType *FT = Callee->getFunctionType();
629 if (FT->getNumParams() != 3 || FT->getReturnType() != Type::Int32Ty ||
630 FT->getParamType(0) != FT->getParamType(1) ||
631 FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty) ||
632 !isa<IntegerType>(FT->getParamType(2)))
633 return 0;
634
635 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
636 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
637 return ConstantInt::get(CI->getType(), 0);
638
639 // Get the length argument if it is constant.
640 uint64_t Length;
641 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
642 Length = LengthArg->getZExtValue();
643 else
644 return 0;
645
646 if (Length == 0) // strncmp(x,y,0) -> 0
647 return ConstantInt::get(CI->getType(), 0);
648
649 std::string Str1, Str2;
650 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
651 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
652
653 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> *x
654 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
655
656 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
657 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
658
659 // strncmp(x, y) -> cnst (if both x and y are constant strings)
660 if (HasStr1 && HasStr2)
661 return ConstantInt::get(CI->getType(),
662 strncmp(Str1.c_str(), Str2.c_str(), Length));
663 return 0;
664 }
665};
666
667
668//===---------------------------------------===//
669// 'strcpy' Optimizations
670
671struct VISIBILITY_HIDDEN StrCpyOpt : public LibCallOptimization {
672 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder &B) {
673 // Verify the "strcpy" function prototype.
674 const FunctionType *FT = Callee->getFunctionType();
675 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
676 FT->getParamType(0) != FT->getParamType(1) ||
677 FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty))
678 return 0;
679
680 Value *Dst = CI->getOperand(1), *Src = CI->getOperand(2);
681 if (Dst == Src) // strcpy(x,x) -> x
682 return Src;
683
684 // See if we can get the length of the input string.
685 uint64_t Len = GetStringLength(Src);
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000686 if (Len == 0) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000687
688 // We have enough information to now generate the memcpy call to do the
689 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
690 EmitMemCpy(Dst, Src, ConstantInt::get(TD->getIntPtrType(), Len), 1, B);
691 return Dst;
692 }
693};
694
695
696
697//===---------------------------------------===//
698// 'strlen' Optimizations
699
700struct VISIBILITY_HIDDEN StrLenOpt : public LibCallOptimization {
701 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder &B) {
702 const FunctionType *FT = Callee->getFunctionType();
703 if (FT->getNumParams() != 1 ||
704 FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty) ||
705 !isa<IntegerType>(FT->getReturnType()))
706 return 0;
707
708 Value *Src = CI->getOperand(1);
709
710 // Constant folding: strlen("xyz") -> 3
711 if (uint64_t Len = GetStringLength(Src))
712 return ConstantInt::get(CI->getType(), Len-1);
713
714 // Handle strlen(p) != 0.
715 if (!IsOnlyUsedInZeroEqualityComparison(CI)) return 0;
716
717 // strlen(x) != 0 --> *x != 0
718 // strlen(x) == 0 --> *x == 0
719 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
720 }
721};
722
723//===---------------------------------------===//
724// 'memcmp' Optimizations
725
726struct VISIBILITY_HIDDEN MemCmpOpt : public LibCallOptimization {
727 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder &B) {
728 const FunctionType *FT = Callee->getFunctionType();
729 if (FT->getNumParams() != 3 || !isa<PointerType>(FT->getParamType(0)) ||
730 !isa<PointerType>(FT->getParamType(1)) ||
731 FT->getReturnType() != Type::Int32Ty)
732 return 0;
733
734 Value *LHS = CI->getOperand(1), *RHS = CI->getOperand(2);
735
736 if (LHS == RHS) // memcmp(s,s,x) -> 0
737 return Constant::getNullValue(CI->getType());
738
739 // Make sure we have a constant length.
740 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getOperand(3));
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000741 if (!LenC) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000742 uint64_t Len = LenC->getZExtValue();
743
744 if (Len == 0) // memcmp(s1,s2,0) -> 0
745 return Constant::getNullValue(CI->getType());
746
747 if (Len == 1) { // memcmp(S1,S2,1) -> *LHS - *RHS
748 Value *LHSV = B.CreateLoad(CastToCStr(LHS, B), "lhsv");
749 Value *RHSV = B.CreateLoad(CastToCStr(RHS, B), "rhsv");
750 return B.CreateZExt(B.CreateSub(LHSV, RHSV, "chardiff"), CI->getType());
751 }
752
753 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS ^ *(short*)RHS) != 0
754 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS ^ *(int*)RHS) != 0
755 if ((Len == 2 || Len == 4) && IsOnlyUsedInZeroEqualityComparison(CI)) {
756 LHS = B.CreateBitCast(LHS, PointerType::getUnqual(Type::Int16Ty), "tmp");
757 RHS = B.CreateBitCast(RHS, LHS->getType(), "tmp");
758 LoadInst *LHSV = B.CreateLoad(LHS, "lhsv");
759 LoadInst *RHSV = B.CreateLoad(RHS, "rhsv");
760 LHSV->setAlignment(1); RHSV->setAlignment(1); // Unaligned loads.
761 return B.CreateZExt(B.CreateXor(LHSV, RHSV, "shortdiff"), CI->getType());
762 }
763
764 return 0;
765 }
766};
767
768//===---------------------------------------===//
769// 'memcpy' Optimizations
770
771struct VISIBILITY_HIDDEN MemCpyOpt : public LibCallOptimization {
772 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder &B) {
773 const FunctionType *FT = Callee->getFunctionType();
774 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
775 !isa<PointerType>(FT->getParamType(0)) ||
776 !isa<PointerType>(FT->getParamType(1)) ||
777 FT->getParamType(2) != TD->getIntPtrType())
778 return 0;
779
780 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
781 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
782 return CI->getOperand(1);
783 }
784};
785
786//===----------------------------------------------------------------------===//
787// Math Library Optimizations
788//===----------------------------------------------------------------------===//
789
790//===---------------------------------------===//
791// 'pow*' Optimizations
792
793struct VISIBILITY_HIDDEN PowOpt : public LibCallOptimization {
794 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder &B) {
795 const FunctionType *FT = Callee->getFunctionType();
796 // Just make sure this has 2 arguments of the same FP type, which match the
797 // result type.
798 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
799 FT->getParamType(0) != FT->getParamType(1) ||
800 !FT->getParamType(0)->isFloatingPoint())
801 return 0;
802
803 Value *Op1 = CI->getOperand(1), *Op2 = CI->getOperand(2);
804 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
805 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
806 return Op1C;
807 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
808 return EmitUnaryFloatFnCall(Op2, "exp2", B);
809 }
810
811 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
812 if (Op2C == 0) return 0;
813
814 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
815 return ConstantFP::get(CI->getType(), 1.0);
816
817 if (Op2C->isExactlyValue(0.5)) {
818 // FIXME: This is not safe for -0.0 and -inf. This can only be done when
819 // 'unsafe' math optimizations are allowed.
820 // x pow(x, 0.5) sqrt(x)
821 // ---------------------------------------------
822 // -0.0 +0.0 -0.0
823 // -inf +inf NaN
824#if 0
825 // pow(x, 0.5) -> sqrt(x)
826 return B.CreateCall(get_sqrt(), Op1, "sqrt");
827#endif
828 }
829
830 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
831 return Op1;
832 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
833 return B.CreateMul(Op1, Op1, "pow2");
834 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
835 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
836 return 0;
837 }
838};
839
840//===---------------------------------------===//
841// Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
842
843struct VISIBILITY_HIDDEN UnaryDoubleFPOpt : public LibCallOptimization {
844 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder &B) {
845 const FunctionType *FT = Callee->getFunctionType();
846 if (FT->getNumParams() != 1 || FT->getReturnType() != Type::DoubleTy ||
847 FT->getParamType(0) != Type::DoubleTy)
848 return 0;
849
850 // If this is something like 'floor((double)floatval)', convert to floorf.
851 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getOperand(1));
852 if (Cast == 0 || Cast->getOperand(0)->getType() != Type::FloatTy)
853 return 0;
854
855 // floor((double)floatval) -> (double)floorf(floatval)
856 Value *V = Cast->getOperand(0);
857 V = EmitUnaryFloatFnCall(V, Callee->getNameStart(), B);
858 return B.CreateFPExt(V, Type::DoubleTy);
859 }
860};
861
862//===----------------------------------------------------------------------===//
863// Integer Optimizations
864//===----------------------------------------------------------------------===//
865
866//===---------------------------------------===//
867// 'ffs*' Optimizations
868
869struct VISIBILITY_HIDDEN FFSOpt : public LibCallOptimization {
870 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder &B) {
871 const FunctionType *FT = Callee->getFunctionType();
872 // Just make sure this has 2 arguments of the same FP type, which match the
873 // result type.
874 if (FT->getNumParams() != 1 || FT->getReturnType() != Type::Int32Ty ||
875 !isa<IntegerType>(FT->getParamType(0)))
876 return 0;
877
878 Value *Op = CI->getOperand(1);
879
880 // Constant fold.
881 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
882 if (CI->getValue() == 0) // ffs(0) -> 0.
883 return Constant::getNullValue(CI->getType());
884 return ConstantInt::get(Type::Int32Ty, // ffs(c) -> cttz(c)+1
885 CI->getValue().countTrailingZeros()+1);
886 }
887
888 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
889 const Type *ArgType = Op->getType();
890 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
891 Intrinsic::cttz, &ArgType, 1);
892 Value *V = B.CreateCall(F, Op, "cttz");
893 V = B.CreateAdd(V, ConstantInt::get(Type::Int32Ty, 1), "tmp");
894 V = B.CreateIntCast(V, Type::Int32Ty, false, "tmp");
895
896 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType), "tmp");
897 return B.CreateSelect(Cond, V, ConstantInt::get(Type::Int32Ty, 0));
898 }
899};
900
901//===---------------------------------------===//
902// 'isdigit' Optimizations
903
904struct VISIBILITY_HIDDEN IsDigitOpt : public LibCallOptimization {
905 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder &B) {
906 const FunctionType *FT = Callee->getFunctionType();
907 // We require integer(i32)
908 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
909 FT->getParamType(0) != Type::Int32Ty)
910 return 0;
911
912 // isdigit(c) -> (c-'0') <u 10
913 Value *Op = CI->getOperand(1);
914 Op = B.CreateSub(Op, ConstantInt::get(Type::Int32Ty, '0'), "isdigittmp");
915 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::Int32Ty, 10), "isdigit");
916 return B.CreateZExt(Op, CI->getType());
917 }
918};
919
920//===---------------------------------------===//
921// 'isascii' Optimizations
922
923struct VISIBILITY_HIDDEN IsAsciiOpt : public LibCallOptimization {
924 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder &B) {
925 const FunctionType *FT = Callee->getFunctionType();
926 // We require integer(i32)
927 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
928 FT->getParamType(0) != Type::Int32Ty)
929 return 0;
930
931 // isascii(c) -> c <u 128
932 Value *Op = CI->getOperand(1);
933 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::Int32Ty, 128), "isascii");
934 return B.CreateZExt(Op, CI->getType());
935 }
936};
937
938//===---------------------------------------===//
939// 'toascii' Optimizations
940
941struct VISIBILITY_HIDDEN ToAsciiOpt : public LibCallOptimization {
942 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder &B) {
943 const FunctionType *FT = Callee->getFunctionType();
944 // We require i32(i32)
945 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
946 FT->getParamType(0) != Type::Int32Ty)
947 return 0;
948
949 // isascii(c) -> c & 0x7f
950 return B.CreateAnd(CI->getOperand(1), ConstantInt::get(CI->getType(),0x7F));
951 }
952};
953
954//===----------------------------------------------------------------------===//
955// Formatting and IO Optimizations
956//===----------------------------------------------------------------------===//
957
958//===---------------------------------------===//
959// 'printf' Optimizations
960
961struct VISIBILITY_HIDDEN PrintFOpt : public LibCallOptimization {
962 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder &B) {
963 // Require one fixed pointer argument and an integer/void result.
964 const FunctionType *FT = Callee->getFunctionType();
965 if (FT->getNumParams() < 1 || !isa<PointerType>(FT->getParamType(0)) ||
966 !(isa<IntegerType>(FT->getReturnType()) ||
967 FT->getReturnType() == Type::VoidTy))
968 return 0;
969
970 // Check for a fixed format string.
971 std::string FormatStr;
972 if (!GetConstantStringInfo(CI->getOperand(1), FormatStr))
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000973 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000974
975 // Empty format string -> noop.
976 if (FormatStr.empty()) // Tolerate printf's declared void.
977 return CI->use_empty() ? (Value*)CI : ConstantInt::get(CI->getType(), 0);
978
979 // printf("x") -> putchar('x'), even for '%'.
980 if (FormatStr.size() == 1) {
981 EmitPutChar(ConstantInt::get(Type::Int32Ty, FormatStr[0]), B);
982 return CI->use_empty() ? (Value*)CI : ConstantInt::get(CI->getType(), 1);
983 }
984
985 // printf("foo\n") --> puts("foo")
986 if (FormatStr[FormatStr.size()-1] == '\n' &&
987 FormatStr.find('%') == std::string::npos) { // no format characters.
988 // Create a string literal with no \n on it. We expect the constant merge
989 // pass to be run after this pass, to merge duplicate strings.
990 FormatStr.erase(FormatStr.end()-1);
991 Constant *C = ConstantArray::get(FormatStr, true);
992 C = new GlobalVariable(C->getType(), true,GlobalVariable::InternalLinkage,
993 C, "str", Callee->getParent());
994 EmitPutS(C, B);
995 return CI->use_empty() ? (Value*)CI :
996 ConstantInt::get(CI->getType(), FormatStr.size()+1);
997 }
998
999 // Optimize specific format strings.
1000 // printf("%c", chr) --> putchar(*(i8*)dst)
1001 if (FormatStr == "%c" && CI->getNumOperands() > 2 &&
1002 isa<IntegerType>(CI->getOperand(2)->getType())) {
1003 EmitPutChar(CI->getOperand(2), B);
1004 return CI->use_empty() ? (Value*)CI : ConstantInt::get(CI->getType(), 1);
1005 }
1006
1007 // printf("%s\n", str) --> puts(str)
1008 if (FormatStr == "%s\n" && CI->getNumOperands() > 2 &&
1009 isa<PointerType>(CI->getOperand(2)->getType()) &&
1010 CI->use_empty()) {
1011 EmitPutS(CI->getOperand(2), B);
1012 return CI;
1013 }
1014 return 0;
1015 }
1016};
1017
1018//===---------------------------------------===//
1019// 'sprintf' Optimizations
1020
1021struct VISIBILITY_HIDDEN SPrintFOpt : public LibCallOptimization {
1022 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder &B) {
1023 // Require two fixed pointer arguments and an integer result.
1024 const FunctionType *FT = Callee->getFunctionType();
1025 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1026 !isa<PointerType>(FT->getParamType(1)) ||
1027 !isa<IntegerType>(FT->getReturnType()))
1028 return 0;
1029
1030 // Check for a fixed format string.
1031 std::string FormatStr;
1032 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001033 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001034
1035 // If we just have a format string (nothing else crazy) transform it.
1036 if (CI->getNumOperands() == 3) {
1037 // Make sure there's no % in the constant array. We could try to handle
1038 // %% -> % in the future if we cared.
1039 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1040 if (FormatStr[i] == '%')
1041 return 0; // we found a format specifier, bail out.
1042
1043 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1044 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), // Copy the nul byte.
1045 ConstantInt::get(TD->getIntPtrType(), FormatStr.size()+1),1,B);
1046 return ConstantInt::get(CI->getType(), FormatStr.size());
1047 }
1048
1049 // The remaining optimizations require the format string to be "%s" or "%c"
1050 // and have an extra operand.
1051 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1052 return 0;
1053
1054 // Decode the second character of the format string.
1055 if (FormatStr[1] == 'c') {
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001056 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001057 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1058 Value *V = B.CreateTrunc(CI->getOperand(3), Type::Int8Ty, "char");
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001059 Value *Ptr = CastToCStr(CI->getOperand(1), B);
1060 B.CreateStore(V, Ptr);
1061 Ptr = B.CreateGEP(Ptr, ConstantInt::get(Type::Int32Ty, 1), "nul");
1062 B.CreateStore(Constant::getNullValue(Type::Int8Ty), Ptr);
1063
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001064 return ConstantInt::get(CI->getType(), 1);
1065 }
1066
1067 if (FormatStr[1] == 's') {
1068 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1069 if (!isa<PointerType>(CI->getOperand(3)->getType())) return 0;
1070
1071 Value *Len = EmitStrLen(CI->getOperand(3), B);
1072 Value *IncLen = B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1),
1073 "leninc");
1074 EmitMemCpy(CI->getOperand(1), CI->getOperand(3), IncLen, 1, B);
1075
1076 // The sprintf result is the unincremented number of bytes in the string.
1077 return B.CreateIntCast(Len, CI->getType(), false);
1078 }
1079 return 0;
1080 }
1081};
1082
1083//===---------------------------------------===//
1084// 'fwrite' Optimizations
1085
1086struct VISIBILITY_HIDDEN FWriteOpt : public LibCallOptimization {
1087 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder &B) {
1088 // Require a pointer, an integer, an integer, a pointer, returning integer.
1089 const FunctionType *FT = Callee->getFunctionType();
1090 if (FT->getNumParams() != 4 || !isa<PointerType>(FT->getParamType(0)) ||
1091 !isa<IntegerType>(FT->getParamType(1)) ||
1092 !isa<IntegerType>(FT->getParamType(2)) ||
1093 !isa<PointerType>(FT->getParamType(3)) ||
1094 !isa<IntegerType>(FT->getReturnType()))
1095 return 0;
1096
1097 // Get the element size and count.
1098 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getOperand(2));
1099 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getOperand(3));
1100 if (!SizeC || !CountC) return 0;
1101 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1102
1103 // If this is writing zero records, remove the call (it's a noop).
1104 if (Bytes == 0)
1105 return ConstantInt::get(CI->getType(), 0);
1106
1107 // If this is writing one byte, turn it into fputc.
1108 if (Bytes == 1) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1109 Value *Char = B.CreateLoad(CastToCStr(CI->getOperand(1), B), "char");
1110 EmitFPutC(Char, CI->getOperand(4), B);
1111 return ConstantInt::get(CI->getType(), 1);
1112 }
1113
1114 return 0;
1115 }
1116};
1117
1118//===---------------------------------------===//
1119// 'fputs' Optimizations
1120
1121struct VISIBILITY_HIDDEN FPutsOpt : public LibCallOptimization {
1122 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder &B) {
1123 // Require two pointers. Also, we can't optimize if return value is used.
1124 const FunctionType *FT = Callee->getFunctionType();
1125 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1126 !isa<PointerType>(FT->getParamType(1)) ||
1127 !CI->use_empty())
1128 return 0;
1129
1130 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1131 uint64_t Len = GetStringLength(CI->getOperand(1));
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001132 if (!Len) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001133 EmitFWrite(CI->getOperand(1), ConstantInt::get(TD->getIntPtrType(), Len-1),
1134 CI->getOperand(2), B);
1135 return CI; // Known to have no uses (see above).
1136 }
1137};
1138
1139//===---------------------------------------===//
1140// 'fprintf' Optimizations
1141
1142struct VISIBILITY_HIDDEN FPrintFOpt : public LibCallOptimization {
1143 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder &B) {
1144 // Require two fixed paramters as pointers and integer result.
1145 const FunctionType *FT = Callee->getFunctionType();
1146 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1147 !isa<PointerType>(FT->getParamType(1)) ||
1148 !isa<IntegerType>(FT->getReturnType()))
1149 return 0;
1150
1151 // All the optimizations depend on the format string.
1152 std::string FormatStr;
1153 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001154 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001155
1156 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1157 if (CI->getNumOperands() == 3) {
1158 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1159 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001160 return 0; // We found a format specifier.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001161
1162 EmitFWrite(CI->getOperand(2), ConstantInt::get(TD->getIntPtrType(),
1163 FormatStr.size()),
1164 CI->getOperand(1), B);
1165 return ConstantInt::get(CI->getType(), FormatStr.size());
1166 }
1167
1168 // The remaining optimizations require the format string to be "%s" or "%c"
1169 // and have an extra operand.
1170 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1171 return 0;
1172
1173 // Decode the second character of the format string.
1174 if (FormatStr[1] == 'c') {
1175 // fprintf(F, "%c", chr) --> *(i8*)dst = chr
1176 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1177 EmitFPutC(CI->getOperand(3), CI->getOperand(1), B);
1178 return ConstantInt::get(CI->getType(), 1);
1179 }
1180
1181 if (FormatStr[1] == 's') {
1182 // fprintf(F, "%s", str) -> fputs(str, F)
1183 if (!isa<PointerType>(CI->getOperand(3)->getType()) || !CI->use_empty())
1184 return 0;
1185 EmitFPutS(CI->getOperand(3), CI->getOperand(1), B);
1186 return CI;
1187 }
1188 return 0;
1189 }
1190};
1191
1192
1193//===----------------------------------------------------------------------===//
1194// SimplifyLibCalls Pass Implementation
1195//===----------------------------------------------------------------------===//
1196
1197namespace {
1198 /// This pass optimizes well known library functions from libc and libm.
1199 ///
1200 class VISIBILITY_HIDDEN SimplifyLibCalls : public FunctionPass {
1201 StringMap<LibCallOptimization*> Optimizations;
1202 // Miscellaneous LibCall Optimizations
1203 ExitOpt Exit;
1204 // String and Memory LibCall Optimizations
1205 StrCatOpt StrCat; StrChrOpt StrChr; StrCmpOpt StrCmp; StrNCmpOpt StrNCmp;
1206 StrCpyOpt StrCpy; StrLenOpt StrLen; MemCmpOpt MemCmp; MemCpyOpt MemCpy;
1207 // Math Library Optimizations
1208 PowOpt Pow; UnaryDoubleFPOpt UnaryDoubleFP;
1209 // Integer Optimizations
1210 FFSOpt FFS; IsDigitOpt IsDigit; IsAsciiOpt IsAscii; ToAsciiOpt ToAscii;
1211 // Formatting and IO Optimizations
1212 SPrintFOpt SPrintF; PrintFOpt PrintF;
1213 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
1214 public:
1215 static char ID; // Pass identification
1216 SimplifyLibCalls() : FunctionPass((intptr_t)&ID) {}
1217
1218 void InitOptimizations();
1219 bool runOnFunction(Function &F);
1220
1221 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1222 AU.addRequired<TargetData>();
1223 }
1224 };
1225 char SimplifyLibCalls::ID = 0;
1226} // end anonymous namespace.
1227
1228static RegisterPass<SimplifyLibCalls>
1229X("simplify-libcalls", "Simplify well-known library calls");
1230
1231// Public interface to the Simplify LibCalls pass.
1232FunctionPass *llvm::createSimplifyLibCallsPass() {
1233 return new SimplifyLibCalls();
1234}
1235
1236/// Optimizations - Populate the Optimizations map with all the optimizations
1237/// we know.
1238void SimplifyLibCalls::InitOptimizations() {
1239 // Miscellaneous LibCall Optimizations
1240 Optimizations["exit"] = &Exit;
1241
1242 // String and Memory LibCall Optimizations
1243 Optimizations["strcat"] = &StrCat;
1244 Optimizations["strchr"] = &StrChr;
1245 Optimizations["strcmp"] = &StrCmp;
1246 Optimizations["strncmp"] = &StrNCmp;
1247 Optimizations["strcpy"] = &StrCpy;
1248 Optimizations["strlen"] = &StrLen;
1249 Optimizations["memcmp"] = &MemCmp;
1250 Optimizations["memcpy"] = &MemCpy;
1251
1252 // Math Library Optimizations
1253 Optimizations["powf"] = &Pow;
1254 Optimizations["pow"] = &Pow;
1255 Optimizations["powl"] = &Pow;
1256#ifdef HAVE_FLOORF
1257 Optimizations["floor"] = &UnaryDoubleFP;
1258#endif
1259#ifdef HAVE_CEILF
1260 Optimizations["ceil"] = &UnaryDoubleFP;
1261#endif
1262#ifdef HAVE_ROUNDF
1263 Optimizations["round"] = &UnaryDoubleFP;
1264#endif
1265#ifdef HAVE_RINTF
1266 Optimizations["rint"] = &UnaryDoubleFP;
1267#endif
1268#ifdef HAVE_NEARBYINTF
1269 Optimizations["nearbyint"] = &UnaryDoubleFP;
1270#endif
1271
1272 // Integer Optimizations
1273 Optimizations["ffs"] = &FFS;
1274 Optimizations["ffsl"] = &FFS;
1275 Optimizations["ffsll"] = &FFS;
1276 Optimizations["isdigit"] = &IsDigit;
1277 Optimizations["isascii"] = &IsAscii;
1278 Optimizations["toascii"] = &ToAscii;
1279
1280 // Formatting and IO Optimizations
1281 Optimizations["sprintf"] = &SPrintF;
1282 Optimizations["printf"] = &PrintF;
1283 Optimizations["fwrite"] = &FWrite;
1284 Optimizations["fputs"] = &FPuts;
1285 Optimizations["fprintf"] = &FPrintF;
1286}
1287
1288
1289/// runOnFunction - Top level algorithm.
1290///
1291bool SimplifyLibCalls::runOnFunction(Function &F) {
1292 if (Optimizations.empty())
1293 InitOptimizations();
1294
1295 const TargetData &TD = getAnalysis<TargetData>();
1296
1297 IRBuilder Builder;
1298
1299 bool Changed = false;
1300 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1301 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1302 // Ignore non-calls.
1303 CallInst *CI = dyn_cast<CallInst>(I++);
1304 if (!CI) continue;
1305
1306 // Ignore indirect calls and calls to non-external functions.
1307 Function *Callee = CI->getCalledFunction();
1308 if (Callee == 0 || !Callee->isDeclaration() ||
1309 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1310 continue;
1311
1312 // Ignore unknown calls.
1313 const char *CalleeName = Callee->getNameStart();
1314 StringMap<LibCallOptimization*>::iterator OMI =
1315 Optimizations.find(CalleeName, CalleeName+Callee->getNameLen());
1316 if (OMI == Optimizations.end()) continue;
1317
1318 // Set the builder to the instruction after the call.
1319 Builder.SetInsertPoint(BB, I);
1320
1321 // Try to optimize this call.
1322 Value *Result = OMI->second->OptimizeCall(CI, TD, Builder);
1323 if (Result == 0) continue;
1324
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001325 DEBUG(DOUT << "SimplifyLibCalls simplified: " << *CI;
1326 DOUT << " into: " << *Result << "\n");
1327
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001328 // Something changed!
1329 Changed = true;
1330 ++NumSimplified;
1331
1332 // Inspect the instruction after the call (which was potentially just
1333 // added) next.
1334 I = CI; ++I;
1335
1336 if (CI != Result && !CI->use_empty()) {
1337 CI->replaceAllUsesWith(Result);
1338 if (!Result->hasName())
1339 Result->takeName(CI);
1340 }
1341 CI->eraseFromParent();
1342 }
1343 }
1344 return Changed;
1345}
1346
1347
1348// TODO:
1349// Additional cases that we need to add to this file:
1350//
1351// cbrt:
1352// * cbrt(expN(X)) -> expN(x/3)
1353// * cbrt(sqrt(x)) -> pow(x,1/6)
1354// * cbrt(sqrt(x)) -> pow(x,1/9)
1355//
1356// cos, cosf, cosl:
1357// * cos(-x) -> cos(x)
1358//
1359// exp, expf, expl:
1360// * exp(log(x)) -> x
1361//
1362// log, logf, logl:
1363// * log(exp(x)) -> x
1364// * log(x**y) -> y*log(x)
1365// * log(exp(y)) -> y*log(e)
1366// * log(exp2(y)) -> y*log(2)
1367// * log(exp10(y)) -> y*log(10)
1368// * log(sqrt(x)) -> 0.5*log(x)
1369// * log(pow(x,y)) -> y*log(x)
1370//
1371// lround, lroundf, lroundl:
1372// * lround(cnst) -> cnst'
1373//
1374// memcmp:
1375// * memcmp(x,y,l) -> cnst
1376// (if all arguments are constant and strlen(x) <= l and strlen(y) <= l)
1377//
1378// memmove:
1379// * memmove(d,s,l,a) -> memcpy(d,s,l,a)
1380// (if s is a global constant array)
1381//
1382// pow, powf, powl:
1383// * pow(exp(x),y) -> exp(x*y)
1384// * pow(sqrt(x),y) -> pow(x,y*0.5)
1385// * pow(pow(x,y),z)-> pow(x,y*z)
1386//
1387// puts:
1388// * puts("") -> putchar("\n")
1389//
1390// round, roundf, roundl:
1391// * round(cnst) -> cnst'
1392//
1393// signbit:
1394// * signbit(cnst) -> cnst'
1395// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
1396//
1397// sqrt, sqrtf, sqrtl:
1398// * sqrt(expN(x)) -> expN(x*0.5)
1399// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
1400// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
1401//
1402// stpcpy:
1403// * stpcpy(str, "literal") ->
1404// llvm.memcpy(str,"literal",strlen("literal")+1,1)
1405// strrchr:
1406// * strrchr(s,c) -> reverse_offset_of_in(c,s)
1407// (if c is a constant integer and s is a constant string)
1408// * strrchr(s1,0) -> strchr(s1,0)
1409//
1410// strncat:
1411// * strncat(x,y,0) -> x
1412// * strncat(x,y,0) -> x (if strlen(y) = 0)
1413// * strncat(x,y,l) -> strcat(x,y) (if y and l are constants an l > strlen(y))
1414//
1415// strncpy:
1416// * strncpy(d,s,0) -> d
1417// * strncpy(d,s,l) -> memcpy(d,s,l,1)
1418// (if s and l are constants)
1419//
1420// strpbrk:
1421// * strpbrk(s,a) -> offset_in_for(s,a)
1422// (if s and a are both constant strings)
1423// * strpbrk(s,"") -> 0
1424// * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
1425//
1426// strspn, strcspn:
1427// * strspn(s,a) -> const_int (if both args are constant)
1428// * strspn("",a) -> 0
1429// * strspn(s,"") -> 0
1430// * strcspn(s,a) -> const_int (if both args are constant)
1431// * strcspn("",a) -> 0
1432// * strcspn(s,"") -> strlen(a)
1433//
1434// strstr:
1435// * strstr(x,x) -> x
1436// * strstr(s1,s2) -> offset_of_s2_in(s1)
1437// (if s1 and s2 are constant strings)
1438//
1439// tan, tanf, tanl:
1440// * tan(atan(x)) -> x
1441//
1442// trunc, truncf, truncl:
1443// * trunc(cnst) -> cnst'
1444//
1445//