1 //===- SimplifyLibCalls.cpp - Optimize specific well-known library calls --===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Reid Spencer and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements a variety of small optimizations for calls to specific
11 // well-known (e.g. runtime library) function calls. For example, a call to the
12 // function "exit(3)" that occurs within the main() function can be transformed
13 // into a simple "return 3" instruction. Any optimization that takes this form
14 // (replace call to library function with simpler code that provides same
15 // result) belongs in this file.
17 //===----------------------------------------------------------------------===//
19 #define DEBUG_TYPE "simplify-libcalls"
20 #include "llvm/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/Module.h"
24 #include "llvm/Pass.h"
25 #include "llvm/ADT/hash_map"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Transforms/IPO.h"
35 /// This statistic keeps track of the total number of library calls that have
36 /// been simplified regardless of which call it is.
37 Statistic<> SimplifiedLibCalls("simplify-libcalls",
38 "Total number of library calls simplified");
40 // Forward declarations
41 class LibCallOptimization;
42 class SimplifyLibCalls;
44 /// @brief The list of optimizations deriving from LibCallOptimization
45 hash_map<std::string,LibCallOptimization*> optlist;
47 /// This class is the abstract base class for the set of optimizations that
48 /// corresponds to one library call. The SimplifyLibCalls pass will call the
49 /// ValidateCalledFunction method to ask the optimization if a given Function
50 /// is the kind that the optimization can handle. If the subclass returns true,
51 /// then SImplifyLibCalls will also call the OptimizeCall method to perform,
52 /// or attempt to perform, the optimization(s) for the library call. Otherwise,
53 /// OptimizeCall won't be called. Subclasses are responsible for providing the
54 /// name of the library call (strlen, strcpy, etc.) to the LibCallOptimization
55 /// constructor. This is used to efficiently select which call instructions to
56 /// optimize. The criteria for a "lib call" is "anything with well known
57 /// semantics", typically a library function that is defined by an international
58 /// standard. Because the semantics are well known, the optimizations can
59 /// generally short-circuit actually calling the function if there's a simpler
60 /// way (e.g. strlen(X) can be reduced to a constant if X is a constant global).
61 /// @brief Base class for library call optimizations
62 class LibCallOptimization
65 /// The \p fname argument must be the name of the library function being
66 /// optimized by the subclass.
67 /// @brief Constructor that registers the optimization.
68 LibCallOptimization(const char* fname, const char* description )
71 , occurrences("simplify-libcalls",description)
74 // Register this call optimizer in the optlist (a hash_map)
75 optlist[fname] = this;
78 /// @brief Deregister from the optlist
79 virtual ~LibCallOptimization() { optlist.erase(func_name); }
81 /// The implementation of this function in subclasses should determine if
82 /// \p F is suitable for the optimization. This method is called by
83 /// SimplifyLibCalls::runOnModule to short circuit visiting all the call
84 /// sites of such a function if that function is not suitable in the first
85 /// place. If the called function is suitabe, this method should return true;
86 /// false, otherwise. This function should also perform any lazy
87 /// initialization that the LibCallOptimization needs to do, if its to return
88 /// true. This avoids doing initialization until the optimizer is actually
89 /// going to be called upon to do some optimization.
90 /// @brief Determine if the function is suitable for optimization
91 virtual bool ValidateCalledFunction(
92 const Function* F, ///< The function that is the target of call sites
93 SimplifyLibCalls& SLC ///< The pass object invoking us
96 /// The implementations of this function in subclasses is the heart of the
97 /// SimplifyLibCalls algorithm. Sublcasses of this class implement
98 /// OptimizeCall to determine if (a) the conditions are right for optimizing
99 /// the call and (b) to perform the optimization. If an action is taken
100 /// against ci, the subclass is responsible for returning true and ensuring
101 /// that ci is erased from its parent.
102 /// @brief Optimize a call, if possible.
103 virtual bool OptimizeCall(
104 CallInst* ci, ///< The call instruction that should be optimized.
105 SimplifyLibCalls& SLC ///< The pass object invoking us
108 /// @brief Get the name of the library call being optimized
109 const char * getFunctionName() const { return func_name; }
112 /// @brief Called by SimplifyLibCalls to update the occurrences statistic.
113 void succeeded() { DEBUG(++occurrences); }
117 const char* func_name; ///< Name of the library call we optimize
119 Statistic<> occurrences; ///< debug statistic (-debug-only=simplify-libcalls)
123 /// This class is an LLVM Pass that applies each of the LibCallOptimization
124 /// instances to all the call sites in a module, relatively efficiently. The
125 /// purpose of this pass is to provide optimizations for calls to well-known
126 /// functions with well-known semantics, such as those in the c library. The
127 /// class provides the basic infrastructure for handling runOnModule. Whenever /// this pass finds a function call, it asks the appropriate optimizer to
128 /// validate the call (ValidateLibraryCall). If it is validated, then
129 /// the OptimizeCall method is also called.
130 /// @brief A ModulePass for optimizing well-known function calls.
131 class SimplifyLibCalls : public ModulePass
134 /// We need some target data for accurate signature details that are
135 /// target dependent. So we require target data in our AnalysisUsage.
136 /// @brief Require TargetData from AnalysisUsage.
137 virtual void getAnalysisUsage(AnalysisUsage& Info) const
139 // Ask that the TargetData analysis be performed before us so we can use
141 Info.addRequired<TargetData>();
144 /// For this pass, process all of the function calls in the module, calling
145 /// ValidateLibraryCall and OptimizeCall as appropriate.
146 /// @brief Run all the lib call optimizations on a Module.
147 virtual bool runOnModule(Module &M)
153 // The call optimizations can be recursive. That is, the optimization might
154 // generate a call to another function which can also be optimized. This way
155 // we make the LibCallOptimization instances very specific to the case they
156 // handle. It also means we need to keep running over the function calls in
157 // the module until we don't get any more optimizations possible.
158 bool found_optimization = false;
161 found_optimization = false;
162 for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI)
164 // All the "well-known" functions are external and have external linkage
165 // because they live in a runtime library somewhere and were (probably)
166 // not compiled by LLVM. So, we only act on external functions that
167 // have external linkage and non-empty uses.
168 if (!FI->isExternal() || !FI->hasExternalLinkage() || FI->use_empty())
171 // Get the optimization class that pertains to this function
172 LibCallOptimization* CO = optlist[FI->getName().c_str()];
176 // Make sure the called function is suitable for the optimization
177 if (!CO->ValidateCalledFunction(FI,*this))
180 // Loop over each of the uses of the function
181 for (Value::use_iterator UI = FI->use_begin(), UE = FI->use_end();
184 // If the use of the function is a call instruction
185 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
187 // Do the optimization on the LibCallOptimization.
188 if (CO->OptimizeCall(CI,*this))
190 ++SimplifiedLibCalls;
191 found_optimization = result = true;
199 } while (found_optimization);
203 /// @brief Return the *current* module we're working on.
204 Module* getModule() const { return M; }
206 /// @brief Return the *current* target data for the module we're working on.
207 TargetData* getTargetData() const { return TD; }
209 /// @brief Return the size_t type -- syntactic shortcut
210 const Type* getIntPtrType() const { return TD->getIntPtrType(); }
212 /// @brief Return a Function* for the fputc libcall
213 Function* get_fputc(const Type* FILEptr_type)
217 std::vector<const Type*> args;
218 args.push_back(Type::IntTy);
219 args.push_back(FILEptr_type);
220 FunctionType* fputc_type =
221 FunctionType::get(Type::IntTy, args, false);
222 fputc_func = M->getOrInsertFunction("fputc",fputc_type);
227 /// @brief Return a Function* for the fwrite libcall
228 Function* get_fwrite(const Type* FILEptr_type)
232 std::vector<const Type*> args;
233 args.push_back(PointerType::get(Type::SByteTy));
234 args.push_back(TD->getIntPtrType());
235 args.push_back(TD->getIntPtrType());
236 args.push_back(FILEptr_type);
237 FunctionType* fwrite_type =
238 FunctionType::get(TD->getIntPtrType(), args, false);
239 fwrite_func = M->getOrInsertFunction("fwrite",fwrite_type);
244 /// @brief Return a Function* for the sqrt libcall
249 std::vector<const Type*> args;
250 args.push_back(Type::DoubleTy);
251 FunctionType* sqrt_type =
252 FunctionType::get(Type::DoubleTy, args, false);
253 sqrt_func = M->getOrInsertFunction("sqrt",sqrt_type);
258 /// @brief Return a Function* for the strlen libcall
259 Function* get_strcpy()
263 std::vector<const Type*> args;
264 args.push_back(PointerType::get(Type::SByteTy));
265 args.push_back(PointerType::get(Type::SByteTy));
266 FunctionType* strcpy_type =
267 FunctionType::get(PointerType::get(Type::SByteTy), args, false);
268 strcpy_func = M->getOrInsertFunction("strcpy",strcpy_type);
273 /// @brief Return a Function* for the strlen libcall
274 Function* get_strlen()
278 std::vector<const Type*> args;
279 args.push_back(PointerType::get(Type::SByteTy));
280 FunctionType* strlen_type =
281 FunctionType::get(TD->getIntPtrType(), args, false);
282 strlen_func = M->getOrInsertFunction("strlen",strlen_type);
287 /// @brief Return a Function* for the memchr libcall
288 Function* get_memchr()
292 std::vector<const Type*> args;
293 args.push_back(PointerType::get(Type::SByteTy));
294 args.push_back(Type::IntTy);
295 args.push_back(TD->getIntPtrType());
296 FunctionType* memchr_type = FunctionType::get(
297 PointerType::get(Type::SByteTy), args, false);
298 memchr_func = M->getOrInsertFunction("memchr",memchr_type);
303 /// @brief Return a Function* for the memcpy libcall
304 Function* get_memcpy()
308 // Note: this is for llvm.memcpy intrinsic
309 std::vector<const Type*> args;
310 args.push_back(PointerType::get(Type::SByteTy));
311 args.push_back(PointerType::get(Type::SByteTy));
312 args.push_back(Type::UIntTy);
313 args.push_back(Type::UIntTy);
314 FunctionType* memcpy_type = FunctionType::get(Type::VoidTy, args, false);
315 memcpy_func = M->getOrInsertFunction("llvm.memcpy",memcpy_type);
321 /// @brief Reset our cached data for a new Module
322 void reset(Module& mod)
325 TD = &getAnalysis<TargetData>();
336 Function* fputc_func; ///< Cached fputc function
337 Function* fwrite_func; ///< Cached fwrite function
338 Function* memcpy_func; ///< Cached llvm.memcpy function
339 Function* memchr_func; ///< Cached memchr function
340 Function* sqrt_func; ///< Cached sqrt function
341 Function* strcpy_func; ///< Cached strcpy function
342 Function* strlen_func; ///< Cached strlen function
343 Module* M; ///< Cached Module
344 TargetData* TD; ///< Cached TargetData
348 RegisterOpt<SimplifyLibCalls>
349 X("simplify-libcalls","Simplify well-known library calls");
351 } // anonymous namespace
353 // The only public symbol in this file which just instantiates the pass object
354 ModulePass *llvm::createSimplifyLibCallsPass()
356 return new SimplifyLibCalls();
359 // Classes below here, in the anonymous namespace, are all subclasses of the
360 // LibCallOptimization class, each implementing all optimizations possible for a
361 // single well-known library call. Each has a static singleton instance that
362 // auto registers it into the "optlist" global above.
365 // Forward declare a utility function.
366 bool getConstantStringLength(Value* V, uint64_t& len, ConstantArray** A = 0 );
368 /// This LibCallOptimization will find instances of a call to "exit" that occurs
369 /// within the "main" function and change it to a simple "ret" instruction with
370 /// the same value passed to the exit function. When this is done, it splits the
371 /// basic block at the exit(3) call and deletes the call instruction.
372 /// @brief Replace calls to exit in main with a simple return
373 struct ExitInMainOptimization : public LibCallOptimization
375 ExitInMainOptimization() : LibCallOptimization("exit",
376 "Number of 'exit' calls simplified") {}
377 virtual ~ExitInMainOptimization() {}
379 // Make sure the called function looks like exit (int argument, int return
380 // type, external linkage, not varargs).
381 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
383 if (f->arg_size() >= 1)
384 if (f->arg_begin()->getType()->isInteger())
389 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
391 // To be careful, we check that the call to exit is coming from "main", that
392 // main has external linkage, and the return type of main and the argument
393 // to exit have the same type.
394 Function *from = ci->getParent()->getParent();
395 if (from->hasExternalLinkage())
396 if (from->getReturnType() == ci->getOperand(1)->getType())
397 if (from->getName() == "main")
399 // Okay, time to actually do the optimization. First, get the basic
400 // block of the call instruction
401 BasicBlock* bb = ci->getParent();
403 // Create a return instruction that we'll replace the call with.
404 // Note that the argument of the return is the argument of the call
406 ReturnInst* ri = new ReturnInst(ci->getOperand(1), ci);
408 // Split the block at the call instruction which places it in a new
410 bb->splitBasicBlock(ci);
412 // The block split caused a branch instruction to be inserted into
413 // the end of the original block, right after the return instruction
414 // that we put there. That's not a valid block, so delete the branch
416 bb->getInstList().pop_back();
418 // Now we can finally get rid of the call instruction which now lives
419 // in the new basic block.
420 ci->eraseFromParent();
422 // Optimization succeeded, return true.
425 // We didn't pass the criteria for this optimization so return false
428 } ExitInMainOptimizer;
430 /// This LibCallOptimization will simplify a call to the strcat library
431 /// function. The simplification is possible only if the string being
432 /// concatenated is a constant array or a constant expression that results in
433 /// a constant string. In this case we can replace it with strlen + llvm.memcpy
434 /// of the constant string. Both of these calls are further reduced, if possible
435 /// on subsequent passes.
436 /// @brief Simplify the strcat library function.
437 struct StrCatOptimization : public LibCallOptimization
440 /// @brief Default constructor
441 StrCatOptimization() : LibCallOptimization("strcat",
442 "Number of 'strcat' calls simplified") {}
445 /// @breif Destructor
446 virtual ~StrCatOptimization() {}
448 /// @brief Make sure that the "strcat" function has the right prototype
449 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
451 if (f->getReturnType() == PointerType::get(Type::SByteTy))
452 if (f->arg_size() == 2)
454 Function::const_arg_iterator AI = f->arg_begin();
455 if (AI++->getType() == PointerType::get(Type::SByteTy))
456 if (AI->getType() == PointerType::get(Type::SByteTy))
458 // Indicate this is a suitable call type.
465 /// @brief Optimize the strcat library function
466 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
468 // Extract some information from the instruction
469 Module* M = ci->getParent()->getParent()->getParent();
470 Value* dest = ci->getOperand(1);
471 Value* src = ci->getOperand(2);
473 // Extract the initializer (while making numerous checks) from the
474 // source operand of the call to strcat. If we get null back, one of
475 // a variety of checks in get_GVInitializer failed
477 if (!getConstantStringLength(src,len))
480 // Handle the simple, do-nothing case
483 ci->replaceAllUsesWith(dest);
484 ci->eraseFromParent();
488 // Increment the length because we actually want to memcpy the null
489 // terminator as well.
492 // We need to find the end of the destination string. That's where the
493 // memory is to be moved to. We just generate a call to strlen (further
494 // optimized in another pass). Note that the SLC.get_strlen() call
495 // caches the Function* for us.
496 CallInst* strlen_inst =
497 new CallInst(SLC.get_strlen(), dest, dest->getName()+".len",ci);
499 // Now that we have the destination's length, we must index into the
500 // destination's pointer to get the actual memcpy destination (end of
501 // the string .. we're concatenating).
502 std::vector<Value*> idx;
503 idx.push_back(strlen_inst);
504 GetElementPtrInst* gep =
505 new GetElementPtrInst(dest,idx,dest->getName()+".indexed",ci);
507 // We have enough information to now generate the memcpy call to
508 // do the concatenation for us.
509 std::vector<Value*> vals;
510 vals.push_back(gep); // destination
511 vals.push_back(ci->getOperand(2)); // source
512 vals.push_back(ConstantUInt::get(Type::UIntTy,len)); // length
513 vals.push_back(ConstantUInt::get(Type::UIntTy,1)); // alignment
514 new CallInst(SLC.get_memcpy(), vals, "", ci);
516 // Finally, substitute the first operand of the strcat call for the
517 // strcat call itself since strcat returns its first operand; and,
518 // kill the strcat CallInst.
519 ci->replaceAllUsesWith(dest);
520 ci->eraseFromParent();
525 /// This LibCallOptimization will simplify a call to the strchr library
526 /// function. It optimizes out cases where the arguments are both constant
527 /// and the result can be determined statically.
528 /// @brief Simplify the strcmp library function.
529 struct StrChrOptimization : public LibCallOptimization
532 StrChrOptimization() : LibCallOptimization("strchr",
533 "Number of 'strchr' calls simplified") {}
534 virtual ~StrChrOptimization() {}
536 /// @brief Make sure that the "strchr" function has the right prototype
537 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
539 if (f->getReturnType() == PointerType::get(Type::SByteTy) &&
545 /// @brief Perform the strcpy optimization
546 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
548 // If there aren't three operands, bail
549 if (ci->getNumOperands() != 3)
552 // Check that the first argument to strchr is a constant array of sbyte.
553 // If it is, get the length and data, otherwise return false.
556 if (!getConstantStringLength(ci->getOperand(1),len,&CA))
559 // Check that the second argument to strchr is a constant int, return false
561 ConstantSInt* CSI = dyn_cast<ConstantSInt>(ci->getOperand(2));
564 // Just lower this to memchr since we know the length of the string as
566 Function* f = SLC.get_memchr();
567 std::vector<Value*> args;
568 args.push_back(ci->getOperand(1));
569 args.push_back(ci->getOperand(2));
570 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
571 ci->replaceAllUsesWith( new CallInst(f,args,ci->getName(),ci));
572 ci->eraseFromParent();
576 // Get the character we're looking for
577 int64_t chr = CSI->getValue();
579 // Compute the offset
581 bool char_found = false;
582 for (uint64_t i = 0; i < len; ++i)
584 if (ConstantSInt* CI = dyn_cast<ConstantSInt>(CA->getOperand(i)))
586 // Check for the null terminator
587 if (CI->isNullValue())
588 break; // we found end of string
589 else if (CI->getValue() == chr)
598 // strchr(s,c) -> offset_of_in(c,s)
599 // (if c is a constant integer and s is a constant string)
602 std::vector<Value*> indices;
603 indices.push_back(ConstantUInt::get(Type::ULongTy,offset));
604 GetElementPtrInst* GEP = new GetElementPtrInst(ci->getOperand(1),indices,
605 ci->getOperand(1)->getName()+".strchr",ci);
606 ci->replaceAllUsesWith(GEP);
609 ci->replaceAllUsesWith(
610 ConstantPointerNull::get(PointerType::get(Type::SByteTy)));
612 ci->eraseFromParent();
617 /// This LibCallOptimization will simplify a call to the strcmp library
618 /// function. It optimizes out cases where one or both arguments are constant
619 /// and the result can be determined statically.
620 /// @brief Simplify the strcmp library function.
621 struct StrCmpOptimization : public LibCallOptimization
624 StrCmpOptimization() : LibCallOptimization("strcmp",
625 "Number of 'strcmp' calls simplified") {}
626 virtual ~StrCmpOptimization() {}
628 /// @brief Make sure that the "strcpy" function has the right prototype
629 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
631 if (f->getReturnType() == Type::IntTy && f->arg_size() == 2)
636 /// @brief Perform the strcpy optimization
637 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
639 // First, check to see if src and destination are the same. If they are,
640 // then the optimization is to replace the CallInst with a constant 0
641 // because the call is a no-op.
642 Value* s1 = ci->getOperand(1);
643 Value* s2 = ci->getOperand(2);
647 ci->replaceAllUsesWith(ConstantInt::get(Type::IntTy,0));
648 ci->eraseFromParent();
652 bool isstr_1 = false;
655 if (getConstantStringLength(s1,len_1,&A1))
660 // strcmp("",x) -> *x
661 LoadInst* load = new LoadInst(s1,ci->getName()+".load",ci);
663 new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
664 ci->replaceAllUsesWith(cast);
665 ci->eraseFromParent();
670 bool isstr_2 = false;
673 if (getConstantStringLength(s2,len_2,&A2))
678 // strcmp(x,"") -> *x
679 LoadInst* load = new LoadInst(s2,ci->getName()+".val",ci);
681 new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
682 ci->replaceAllUsesWith(cast);
683 ci->eraseFromParent();
688 if (isstr_1 && isstr_2)
690 // strcmp(x,y) -> cnst (if both x and y are constant strings)
691 std::string str1 = A1->getAsString();
692 std::string str2 = A2->getAsString();
693 int result = strcmp(str1.c_str(), str2.c_str());
694 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,result));
695 ci->eraseFromParent();
702 /// This LibCallOptimization will simplify a call to the strncmp library
703 /// function. It optimizes out cases where one or both arguments are constant
704 /// and the result can be determined statically.
705 /// @brief Simplify the strncmp library function.
706 struct StrNCmpOptimization : public LibCallOptimization
709 StrNCmpOptimization() : LibCallOptimization("strncmp",
710 "Number of 'strncmp' calls simplified") {}
711 virtual ~StrNCmpOptimization() {}
713 /// @brief Make sure that the "strcpy" function has the right prototype
714 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
716 if (f->getReturnType() == Type::IntTy && f->arg_size() == 3)
721 /// @brief Perform the strncpy optimization
722 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
724 // First, check to see if src and destination are the same. If they are,
725 // then the optimization is to replace the CallInst with a constant 0
726 // because the call is a no-op.
727 Value* s1 = ci->getOperand(1);
728 Value* s2 = ci->getOperand(2);
731 // strncmp(x,x,l) -> 0
732 ci->replaceAllUsesWith(ConstantInt::get(Type::IntTy,0));
733 ci->eraseFromParent();
737 // Check the length argument, if it is Constant zero then the strings are
739 uint64_t len_arg = 0;
740 bool len_arg_is_const = false;
741 if (ConstantInt* len_CI = dyn_cast<ConstantInt>(ci->getOperand(3)))
743 len_arg_is_const = true;
744 len_arg = len_CI->getRawValue();
747 // strncmp(x,y,0) -> 0
748 ci->replaceAllUsesWith(ConstantInt::get(Type::IntTy,0));
749 ci->eraseFromParent();
754 bool isstr_1 = false;
757 if (getConstantStringLength(s1,len_1,&A1))
762 // strncmp("",x) -> *x
763 LoadInst* load = new LoadInst(s1,ci->getName()+".load",ci);
765 new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
766 ci->replaceAllUsesWith(cast);
767 ci->eraseFromParent();
772 bool isstr_2 = false;
775 if (getConstantStringLength(s2,len_2,&A2))
780 // strncmp(x,"") -> *x
781 LoadInst* load = new LoadInst(s2,ci->getName()+".val",ci);
783 new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
784 ci->replaceAllUsesWith(cast);
785 ci->eraseFromParent();
790 if (isstr_1 && isstr_2 && len_arg_is_const)
792 // strncmp(x,y,const) -> constant
793 std::string str1 = A1->getAsString();
794 std::string str2 = A2->getAsString();
795 int result = strncmp(str1.c_str(), str2.c_str(), len_arg);
796 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,result));
797 ci->eraseFromParent();
804 /// This LibCallOptimization will simplify a call to the strcpy library
805 /// function. Two optimizations are possible:
806 /// (1) If src and dest are the same and not volatile, just return dest
807 /// (2) If the src is a constant then we can convert to llvm.memmove
808 /// @brief Simplify the strcpy library function.
809 struct StrCpyOptimization : public LibCallOptimization
812 StrCpyOptimization() : LibCallOptimization("strcpy",
813 "Number of 'strcpy' calls simplified") {}
814 virtual ~StrCpyOptimization() {}
816 /// @brief Make sure that the "strcpy" function has the right prototype
817 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
819 if (f->getReturnType() == PointerType::get(Type::SByteTy))
820 if (f->arg_size() == 2)
822 Function::const_arg_iterator AI = f->arg_begin();
823 if (AI++->getType() == PointerType::get(Type::SByteTy))
824 if (AI->getType() == PointerType::get(Type::SByteTy))
826 // Indicate this is a suitable call type.
833 /// @brief Perform the strcpy optimization
834 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
836 // First, check to see if src and destination are the same. If they are,
837 // then the optimization is to replace the CallInst with the destination
838 // because the call is a no-op. Note that this corresponds to the
839 // degenerate strcpy(X,X) case which should have "undefined" results
840 // according to the C specification. However, it occurs sometimes and
841 // we optimize it as a no-op.
842 Value* dest = ci->getOperand(1);
843 Value* src = ci->getOperand(2);
846 ci->replaceAllUsesWith(dest);
847 ci->eraseFromParent();
851 // Get the length of the constant string referenced by the second operand,
852 // the "src" parameter. Fail the optimization if we can't get the length
853 // (note that getConstantStringLength does lots of checks to make sure this
856 if (!getConstantStringLength(ci->getOperand(2),len))
859 // If the constant string's length is zero we can optimize this by just
860 // doing a store of 0 at the first byte of the destination
863 new StoreInst(ConstantInt::get(Type::SByteTy,0),ci->getOperand(1),ci);
864 ci->replaceAllUsesWith(dest);
865 ci->eraseFromParent();
869 // Increment the length because we actually want to memcpy the null
870 // terminator as well.
873 // Extract some information from the instruction
874 Module* M = ci->getParent()->getParent()->getParent();
876 // We have enough information to now generate the memcpy call to
877 // do the concatenation for us.
878 std::vector<Value*> vals;
879 vals.push_back(dest); // destination
880 vals.push_back(src); // source
881 vals.push_back(ConstantUInt::get(Type::UIntTy,len)); // length
882 vals.push_back(ConstantUInt::get(Type::UIntTy,1)); // alignment
883 new CallInst(SLC.get_memcpy(), vals, "", ci);
885 // Finally, substitute the first operand of the strcat call for the
886 // strcat call itself since strcat returns its first operand; and,
887 // kill the strcat CallInst.
888 ci->replaceAllUsesWith(dest);
889 ci->eraseFromParent();
894 /// This LibCallOptimization will simplify a call to the strlen library
895 /// function by replacing it with a constant value if the string provided to
896 /// it is a constant array.
897 /// @brief Simplify the strlen library function.
898 struct StrLenOptimization : public LibCallOptimization
900 StrLenOptimization() : LibCallOptimization("strlen",
901 "Number of 'strlen' calls simplified") {}
902 virtual ~StrLenOptimization() {}
904 /// @brief Make sure that the "strlen" function has the right prototype
905 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
907 if (f->getReturnType() == SLC.getTargetData()->getIntPtrType())
908 if (f->arg_size() == 1)
909 if (Function::const_arg_iterator AI = f->arg_begin())
910 if (AI->getType() == PointerType::get(Type::SByteTy))
915 /// @brief Perform the strlen optimization
916 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
918 // Make sure we're dealing with an sbyte* here.
919 Value* str = ci->getOperand(1);
920 if (str->getType() != PointerType::get(Type::SByteTy))
923 // Does the call to strlen have exactly one use?
925 // Is that single use a binary operator?
926 if (BinaryOperator* bop = dyn_cast<BinaryOperator>(ci->use_back()))
927 // Is it compared against a constant integer?
928 if (ConstantInt* CI = dyn_cast<ConstantInt>(bop->getOperand(1)))
930 // Get the value the strlen result is compared to
931 uint64_t val = CI->getRawValue();
933 // If its compared against length 0 with == or !=
935 (bop->getOpcode() == Instruction::SetEQ ||
936 bop->getOpcode() == Instruction::SetNE))
938 // strlen(x) != 0 -> *x != 0
939 // strlen(x) == 0 -> *x == 0
940 LoadInst* load = new LoadInst(str,str->getName()+".first",ci);
941 BinaryOperator* rbop = BinaryOperator::create(bop->getOpcode(),
942 load, ConstantSInt::get(Type::SByteTy,0),
943 bop->getName()+".strlen", ci);
944 bop->replaceAllUsesWith(rbop);
945 bop->eraseFromParent();
946 ci->eraseFromParent();
951 // Get the length of the constant string operand
953 if (!getConstantStringLength(ci->getOperand(1),len))
956 // strlen("xyz") -> 3 (for example)
957 ci->replaceAllUsesWith(
958 ConstantInt::get(SLC.getTargetData()->getIntPtrType(),len));
959 ci->eraseFromParent();
964 /// This LibCallOptimization will simplify a call to the memcpy library
965 /// function by expanding it out to a single store of size 0, 1, 2, 4, or 8
966 /// bytes depending on the length of the string and the alignment. Additional
967 /// optimizations are possible in code generation (sequence of immediate store)
968 /// @brief Simplify the memcpy library function.
969 struct LLVMMemCpyOptimization : public LibCallOptimization
971 /// @brief Default Constructor
972 LLVMMemCpyOptimization() : LibCallOptimization("llvm.memcpy",
973 "Number of 'llvm.memcpy' calls simplified") {}
976 /// @brief Subclass Constructor
977 LLVMMemCpyOptimization(const char* fname, const char* desc)
978 : LibCallOptimization(fname, desc) {}
980 /// @brief Destructor
981 virtual ~LLVMMemCpyOptimization() {}
983 /// @brief Make sure that the "memcpy" function has the right prototype
984 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& TD)
986 // Just make sure this has 4 arguments per LLVM spec.
987 return (f->arg_size() == 4);
990 /// Because of alignment and instruction information that we don't have, we
991 /// leave the bulk of this to the code generators. The optimization here just
992 /// deals with a few degenerate cases where the length of the string and the
993 /// alignment match the sizes of our intrinsic types so we can do a load and
994 /// store instead of the memcpy call.
995 /// @brief Perform the memcpy optimization.
996 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& TD)
998 // Make sure we have constant int values to work with
999 ConstantInt* LEN = dyn_cast<ConstantInt>(ci->getOperand(3));
1002 ConstantInt* ALIGN = dyn_cast<ConstantInt>(ci->getOperand(4));
1006 // If the length is larger than the alignment, we can't optimize
1007 uint64_t len = LEN->getRawValue();
1008 uint64_t alignment = ALIGN->getRawValue();
1010 alignment = 1; // Alignment 0 is identity for alignment 1
1011 if (len > alignment)
1014 // Get the type we will cast to, based on size of the string
1015 Value* dest = ci->getOperand(1);
1016 Value* src = ci->getOperand(2);
1021 // memcpy(d,s,0,a) -> noop
1022 ci->eraseFromParent();
1024 case 1: castType = Type::SByteTy; break;
1025 case 2: castType = Type::ShortTy; break;
1026 case 4: castType = Type::IntTy; break;
1027 case 8: castType = Type::LongTy; break;
1032 // Cast source and dest to the right sized primitive and then load/store
1034 new CastInst(src,PointerType::get(castType),src->getName()+".cast",ci);
1035 CastInst* DestCast =
1036 new CastInst(dest,PointerType::get(castType),dest->getName()+".cast",ci);
1037 LoadInst* LI = new LoadInst(SrcCast,SrcCast->getName()+".val",ci);
1038 StoreInst* SI = new StoreInst(LI, DestCast, ci);
1039 ci->eraseFromParent();
1042 } LLVMMemCpyOptimizer;
1044 /// This LibCallOptimization will simplify a call to the memmove library
1045 /// function. It is identical to MemCopyOptimization except for the name of
1047 /// @brief Simplify the memmove library function.
1048 struct LLVMMemMoveOptimization : public LLVMMemCpyOptimization
1050 /// @brief Default Constructor
1051 LLVMMemMoveOptimization() : LLVMMemCpyOptimization("llvm.memmove",
1052 "Number of 'llvm.memmove' calls simplified") {}
1054 } LLVMMemMoveOptimizer;
1056 /// This LibCallOptimization will simplify a call to the memset library
1057 /// function by expanding it out to a single store of size 0, 1, 2, 4, or 8
1058 /// bytes depending on the length argument.
1059 struct LLVMMemSetOptimization : public LibCallOptimization
1061 /// @brief Default Constructor
1062 LLVMMemSetOptimization() : LibCallOptimization("llvm.memset",
1063 "Number of 'llvm.memset' calls simplified") {}
1066 /// @brief Destructor
1067 virtual ~LLVMMemSetOptimization() {}
1069 /// @brief Make sure that the "memset" function has the right prototype
1070 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& TD)
1072 // Just make sure this has 3 arguments per LLVM spec.
1073 return (f->arg_size() == 4);
1076 /// Because of alignment and instruction information that we don't have, we
1077 /// leave the bulk of this to the code generators. The optimization here just
1078 /// deals with a few degenerate cases where the length parameter is constant
1079 /// and the alignment matches the sizes of our intrinsic types so we can do
1080 /// store instead of the memcpy call. Other calls are transformed into the
1081 /// llvm.memset intrinsic.
1082 /// @brief Perform the memset optimization.
1083 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& TD)
1085 // Make sure we have constant int values to work with
1086 ConstantInt* LEN = dyn_cast<ConstantInt>(ci->getOperand(3));
1089 ConstantInt* ALIGN = dyn_cast<ConstantInt>(ci->getOperand(4));
1093 // Extract the length and alignment
1094 uint64_t len = LEN->getRawValue();
1095 uint64_t alignment = ALIGN->getRawValue();
1097 // Alignment 0 is identity for alignment 1
1101 // If the length is zero, this is a no-op
1104 // memset(d,c,0,a) -> noop
1105 ci->eraseFromParent();
1109 // If the length is larger than the alignment, we can't optimize
1110 if (len > alignment)
1113 // Make sure we have a constant ubyte to work with so we can extract
1114 // the value to be filled.
1115 ConstantUInt* FILL = dyn_cast<ConstantUInt>(ci->getOperand(2));
1118 if (FILL->getType() != Type::UByteTy)
1121 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
1123 // Extract the fill character
1124 uint64_t fill_char = FILL->getValue();
1125 uint64_t fill_value = fill_char;
1127 // Get the type we will cast to, based on size of memory area to fill, and
1128 // and the value we will store there.
1129 Value* dest = ci->getOperand(1);
1134 castType = Type::UByteTy;
1137 castType = Type::UShortTy;
1138 fill_value |= fill_char << 8;
1141 castType = Type::UIntTy;
1142 fill_value |= fill_char << 8 | fill_char << 16 | fill_char << 24;
1145 castType = Type::ULongTy;
1146 fill_value |= fill_char << 8 | fill_char << 16 | fill_char << 24;
1147 fill_value |= fill_char << 32 | fill_char << 40 | fill_char << 48;
1148 fill_value |= fill_char << 56;
1154 // Cast dest to the right sized primitive and then load/store
1155 CastInst* DestCast =
1156 new CastInst(dest,PointerType::get(castType),dest->getName()+".cast",ci);
1157 new StoreInst(ConstantUInt::get(castType,fill_value),DestCast, ci);
1158 ci->eraseFromParent();
1161 } LLVMMemSetOptimizer;
1163 /// This LibCallOptimization will simplify calls to the "pow" library
1164 /// function. It looks for cases where the result of pow is well known and
1165 /// substitutes the appropriate value.
1166 /// @brief Simplify the pow library function.
1167 struct PowOptimization : public LibCallOptimization
1170 /// @brief Default Constructor
1171 PowOptimization() : LibCallOptimization("pow",
1172 "Number of 'pow' calls simplified") {}
1174 /// @brief Destructor
1175 virtual ~PowOptimization() {}
1177 /// @brief Make sure that the "pow" function has the right prototype
1178 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1180 // Just make sure this has 2 arguments
1181 return (f->arg_size() == 2);
1184 /// @brief Perform the pow optimization.
1185 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1187 const Type *Ty = cast<Function>(ci->getOperand(0))->getReturnType();
1188 Value* base = ci->getOperand(1);
1189 Value* expn = ci->getOperand(2);
1190 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(base)) {
1191 double Op1V = Op1->getValue();
1194 // pow(1.0,x) -> 1.0
1195 ci->replaceAllUsesWith(ConstantFP::get(Ty,1.0));
1196 ci->eraseFromParent();
1200 else if (ConstantFP* Op2 = dyn_cast<ConstantFP>(expn))
1202 double Op2V = Op2->getValue();
1205 // pow(x,0.0) -> 1.0
1206 ci->replaceAllUsesWith(ConstantFP::get(Ty,1.0));
1207 ci->eraseFromParent();
1210 else if (Op2V == 0.5)
1212 // pow(x,0.5) -> sqrt(x)
1213 CallInst* sqrt_inst = new CallInst(SLC.get_sqrt(), base,
1214 ci->getName()+".pow",ci);
1215 ci->replaceAllUsesWith(sqrt_inst);
1216 ci->eraseFromParent();
1219 else if (Op2V == 1.0)
1222 ci->replaceAllUsesWith(base);
1223 ci->eraseFromParent();
1226 else if (Op2V == -1.0)
1228 // pow(x,-1.0) -> 1.0/x
1229 BinaryOperator* div_inst= BinaryOperator::create(Instruction::Div,
1230 ConstantFP::get(Ty,1.0), base, ci->getName()+".pow", ci);
1231 ci->replaceAllUsesWith(div_inst);
1232 ci->eraseFromParent();
1236 return false; // opt failed
1240 /// This LibCallOptimization will simplify calls to the "fprintf" library
1241 /// function. It looks for cases where the result of fprintf is not used and the
1242 /// operation can be reduced to something simpler.
1243 /// @brief Simplify the pow library function.
1244 struct FPrintFOptimization : public LibCallOptimization
1247 /// @brief Default Constructor
1248 FPrintFOptimization() : LibCallOptimization("fprintf",
1249 "Number of 'fprintf' calls simplified") {}
1251 /// @brief Destructor
1252 virtual ~FPrintFOptimization() {}
1254 /// @brief Make sure that the "fprintf" function has the right prototype
1255 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1257 // Just make sure this has at least 2 arguments
1258 return (f->arg_size() >= 2);
1261 /// @brief Perform the fprintf optimization.
1262 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1264 // If the call has more than 3 operands, we can't optimize it
1265 if (ci->getNumOperands() > 4 || ci->getNumOperands() <= 2)
1268 // If the result of the fprintf call is used, none of these optimizations
1270 if (!ci->hasNUses(0))
1273 // All the optimizations depend on the length of the second argument and the
1274 // fact that it is a constant string array. Check that now
1276 ConstantArray* CA = 0;
1277 if (!getConstantStringLength(ci->getOperand(2), len, &CA))
1280 if (ci->getNumOperands() == 3)
1282 // Make sure there's no % in the constant array
1283 for (unsigned i = 0; i < len; ++i)
1285 if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(i)))
1287 // Check for the null terminator
1288 if (CI->getRawValue() == '%')
1289 return false; // we found end of string
1295 // fprintf(file,fmt) -> fwrite(fmt,strlen(fmt),1file)
1296 const Type* FILEptr_type = ci->getOperand(1)->getType();
1297 Function* fwrite_func = SLC.get_fwrite(FILEptr_type);
1300 std::vector<Value*> args;
1301 args.push_back(ci->getOperand(2));
1302 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
1303 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),1));
1304 args.push_back(ci->getOperand(1));
1305 new CallInst(fwrite_func,args,ci->getName(),ci);
1306 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,len));
1307 ci->eraseFromParent();
1311 // The remaining optimizations require the format string to be length 2
1316 // The first character has to be a %
1317 if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(0)))
1318 if (CI->getRawValue() != '%')
1321 // Get the second character and switch on its value
1322 ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(1));
1323 switch (CI->getRawValue())
1328 ConstantArray* CA = 0;
1329 if (!getConstantStringLength(ci->getOperand(3), len, &CA))
1332 // fprintf(file,"%s",str) -> fwrite(fmt,strlen(fmt),1,file)
1333 const Type* FILEptr_type = ci->getOperand(1)->getType();
1334 Function* fwrite_func = SLC.get_fwrite(FILEptr_type);
1337 std::vector<Value*> args;
1338 args.push_back(ci->getOperand(3));
1339 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
1340 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),1));
1341 args.push_back(ci->getOperand(1));
1342 new CallInst(fwrite_func,args,ci->getName(),ci);
1343 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,len));
1348 ConstantInt* CI = dyn_cast<ConstantInt>(ci->getOperand(3));
1352 const Type* FILEptr_type = ci->getOperand(1)->getType();
1353 Function* fputc_func = SLC.get_fputc(FILEptr_type);
1356 CastInst* cast = new CastInst(CI,Type::IntTy,CI->getName()+".int",ci);
1357 new CallInst(fputc_func,cast,ci->getOperand(1),"",ci);
1358 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,1));
1364 ci->eraseFromParent();
1370 /// This LibCallOptimization will simplify calls to the "sprintf" library
1371 /// function. It looks for cases where the result of sprintf is not used and the
1372 /// operation can be reduced to something simpler.
1373 /// @brief Simplify the pow library function.
1374 struct SPrintFOptimization : public LibCallOptimization
1377 /// @brief Default Constructor
1378 SPrintFOptimization() : LibCallOptimization("sprintf",
1379 "Number of 'sprintf' calls simplified") {}
1381 /// @brief Destructor
1382 virtual ~SPrintFOptimization() {}
1384 /// @brief Make sure that the "fprintf" function has the right prototype
1385 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1387 // Just make sure this has at least 2 arguments
1388 return (f->getReturnType() == Type::IntTy && f->arg_size() >= 2);
1391 /// @brief Perform the sprintf optimization.
1392 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1394 // If the call has more than 3 operands, we can't optimize it
1395 if (ci->getNumOperands() > 4 || ci->getNumOperands() < 3)
1398 // All the optimizations depend on the length of the second argument and the
1399 // fact that it is a constant string array. Check that now
1401 ConstantArray* CA = 0;
1402 if (!getConstantStringLength(ci->getOperand(2), len, &CA))
1405 if (ci->getNumOperands() == 3)
1409 // If the length is 0, we just need to store a null byte
1410 new StoreInst(ConstantInt::get(Type::SByteTy,0),ci->getOperand(1),ci);
1411 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,0));
1412 ci->eraseFromParent();
1416 // Make sure there's no % in the constant array
1417 for (unsigned i = 0; i < len; ++i)
1419 if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(i)))
1421 // Check for the null terminator
1422 if (CI->getRawValue() == '%')
1423 return false; // we found a %, can't optimize
1426 return false; // initializer is not constant int, can't optimize
1429 // Increment length because we want to copy the null byte too
1432 // sprintf(str,fmt) -> llvm.memcpy(str,fmt,strlen(fmt),1)
1433 Function* memcpy_func = SLC.get_memcpy();
1436 std::vector<Value*> args;
1437 args.push_back(ci->getOperand(1));
1438 args.push_back(ci->getOperand(2));
1439 args.push_back(ConstantUInt::get(Type::UIntTy,len));
1440 args.push_back(ConstantUInt::get(Type::UIntTy,1));
1441 new CallInst(memcpy_func,args,"",ci);
1442 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,len));
1443 ci->eraseFromParent();
1447 // The remaining optimizations require the format string to be length 2
1452 // The first character has to be a %
1453 if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(0)))
1454 if (CI->getRawValue() != '%')
1457 // Get the second character and switch on its value
1458 ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(1));
1459 switch (CI->getRawValue())
1464 if (ci->hasNUses(0))
1466 // sprintf(dest,"%s",str) -> strcpy(dest,str)
1467 Function* strcpy_func = SLC.get_strcpy();
1470 std::vector<Value*> args;
1471 args.push_back(ci->getOperand(1));
1472 args.push_back(ci->getOperand(3));
1473 new CallInst(strcpy_func,args,"",ci);
1475 else if (getConstantStringLength(ci->getOperand(3),len))
1477 // sprintf(dest,"%s",cstr) -> llvm.memcpy(dest,str,strlen(str),1)
1478 len++; // get the null-terminator
1479 Function* memcpy_func = SLC.get_memcpy();
1482 std::vector<Value*> args;
1483 args.push_back(ci->getOperand(1));
1484 args.push_back(ci->getOperand(3));
1485 args.push_back(ConstantUInt::get(Type::UIntTy,len));
1486 args.push_back(ConstantUInt::get(Type::UIntTy,1));
1487 new CallInst(memcpy_func,args,"",ci);
1488 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,len));
1494 // sprintf(dest,"%c",chr) -> store chr, dest
1496 new CastInst(ci->getOperand(3),Type::SByteTy,"char",ci);
1497 new StoreInst(cast, ci->getOperand(1), ci);
1498 GetElementPtrInst* gep = new GetElementPtrInst(ci->getOperand(1),
1499 ConstantUInt::get(Type::UIntTy,1),ci->getOperand(1)->getName()+".end",
1501 new StoreInst(ConstantInt::get(Type::SByteTy,0),gep,ci);
1502 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,1));
1508 ci->eraseFromParent();
1513 /// This LibCallOptimization will simplify calls to the "fputs" library
1514 /// function. It looks for cases where the result of fputs is not used and the
1515 /// operation can be reduced to something simpler.
1516 /// @brief Simplify the pow library function.
1517 struct PutsOptimization : public LibCallOptimization
1520 /// @brief Default Constructor
1521 PutsOptimization() : LibCallOptimization("fputs",
1522 "Number of 'fputs' calls simplified") {}
1524 /// @brief Destructor
1525 virtual ~PutsOptimization() {}
1527 /// @brief Make sure that the "fputs" function has the right prototype
1528 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1530 // Just make sure this has 2 arguments
1531 return (f->arg_size() == 2);
1534 /// @brief Perform the fputs optimization.
1535 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1537 // If the result is used, none of these optimizations work
1538 if (!ci->hasNUses(0))
1541 // All the optimizations depend on the length of the first argument and the
1542 // fact that it is a constant string array. Check that now
1544 if (!getConstantStringLength(ci->getOperand(1), len))
1550 // fputs("",F) -> noop
1554 // fputs(s,F) -> fputc(s[0],F) (if s is constant and strlen(s) == 1)
1555 const Type* FILEptr_type = ci->getOperand(2)->getType();
1556 Function* fputc_func = SLC.get_fputc(FILEptr_type);
1559 LoadInst* loadi = new LoadInst(ci->getOperand(1),
1560 ci->getOperand(1)->getName()+".byte",ci);
1561 CastInst* casti = new CastInst(loadi,Type::IntTy,
1562 loadi->getName()+".int",ci);
1563 new CallInst(fputc_func,casti,ci->getOperand(2),"",ci);
1568 // fputs(s,F) -> fwrite(s,1,len,F) (if s is constant and strlen(s) > 1)
1569 const Type* FILEptr_type = ci->getOperand(2)->getType();
1570 Function* fwrite_func = SLC.get_fwrite(FILEptr_type);
1573 std::vector<Value*> parms;
1574 parms.push_back(ci->getOperand(1));
1575 parms.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
1576 parms.push_back(ConstantUInt::get(SLC.getIntPtrType(),1));
1577 parms.push_back(ci->getOperand(2));
1578 new CallInst(fwrite_func,parms,"",ci);
1582 ci->eraseFromParent();
1583 return true; // success
1587 /// This LibCallOptimization will simplify calls to the "isdigit" library
1588 /// function. It simply does range checks the parameter explicitly.
1589 /// @brief Simplify the isdigit library function.
1590 struct IsDigitOptimization : public LibCallOptimization
1593 /// @brief Default Constructor
1594 IsDigitOptimization() : LibCallOptimization("isdigit",
1595 "Number of 'isdigit' calls simplified") {}
1597 /// @brief Destructor
1598 virtual ~IsDigitOptimization() {}
1600 /// @brief Make sure that the "fputs" function has the right prototype
1601 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1603 // Just make sure this has 1 argument
1604 return (f->arg_size() == 1);
1607 /// @brief Perform the toascii optimization.
1608 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1610 if (ConstantInt* CI = dyn_cast<ConstantInt>(ci->getOperand(1)))
1612 // isdigit(c) -> 0 or 1, if 'c' is constant
1613 uint64_t val = CI->getRawValue();
1614 if (val >= '0' && val <='9')
1615 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,1));
1617 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,0));
1618 ci->eraseFromParent();
1622 // isdigit(c) -> (unsigned)c - '0' <= 9
1624 new CastInst(ci->getOperand(1),Type::UIntTy,
1625 ci->getOperand(1)->getName()+".uint",ci);
1626 BinaryOperator* sub_inst = BinaryOperator::create(Instruction::Sub,cast,
1627 ConstantUInt::get(Type::UIntTy,0x30),
1628 ci->getOperand(1)->getName()+".sub",ci);
1629 SetCondInst* setcond_inst = new SetCondInst(Instruction::SetLE,sub_inst,
1630 ConstantUInt::get(Type::UIntTy,9),
1631 ci->getOperand(1)->getName()+".cmp",ci);
1633 new CastInst(setcond_inst,Type::IntTy,
1634 ci->getOperand(1)->getName()+".isdigit",ci);
1635 ci->replaceAllUsesWith(c2);
1636 ci->eraseFromParent();
1641 /// This LibCallOptimization will simplify calls to the "toascii" library
1642 /// function. It simply does the corresponding and operation to restrict the
1643 /// range of values to the ASCII character set (0-127).
1644 /// @brief Simplify the toascii library function.
1645 struct ToAsciiOptimization : public LibCallOptimization
1648 /// @brief Default Constructor
1649 ToAsciiOptimization() : LibCallOptimization("toascii",
1650 "Number of 'toascii' calls simplified") {}
1652 /// @brief Destructor
1653 virtual ~ToAsciiOptimization() {}
1655 /// @brief Make sure that the "fputs" function has the right prototype
1656 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1658 // Just make sure this has 2 arguments
1659 return (f->arg_size() == 1);
1662 /// @brief Perform the toascii optimization.
1663 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1665 // toascii(c) -> (c & 0x7f)
1666 Value* chr = ci->getOperand(1);
1667 BinaryOperator* and_inst = BinaryOperator::create(Instruction::And,chr,
1668 ConstantInt::get(chr->getType(),0x7F),ci->getName()+".toascii",ci);
1669 ci->replaceAllUsesWith(and_inst);
1670 ci->eraseFromParent();
1675 /// This LibCallOptimization will simplify calls to the "ffs" library
1676 /// calls which find the first set bit in an int, long, or long long. The
1677 /// optimization is to compute the result at compile time if the argument is
1679 /// @brief Simplify the ffs library function.
1680 struct FFSOptimization : public LibCallOptimization
1683 /// @brief Subclass Constructor
1684 FFSOptimization(const char* funcName, const char* description)
1685 : LibCallOptimization(funcName, description)
1689 /// @brief Default Constructor
1690 FFSOptimization() : LibCallOptimization("ffs",
1691 "Number of 'ffs' calls simplified") {}
1693 /// @brief Destructor
1694 virtual ~FFSOptimization() {}
1696 /// @brief Make sure that the "fputs" function has the right prototype
1697 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1699 // Just make sure this has 2 arguments
1700 return (f->arg_size() == 1 && f->getReturnType() == Type::IntTy);
1703 /// @brief Perform the ffs optimization.
1704 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1706 if (ConstantInt* CI = dyn_cast<ConstantInt>(ci->getOperand(1)))
1708 // ffs(cnst) -> bit#
1709 // ffsl(cnst) -> bit#
1710 // ffsll(cnst) -> bit#
1711 uint64_t val = CI->getRawValue();
1719 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy, result));
1720 ci->eraseFromParent();
1724 // ffs(x) -> ( x == 0 ? 0 : llvm.cttz(x)+1)
1725 // ffsl(x) -> ( x == 0 ? 0 : llvm.cttz(x)+1)
1726 // ffsll(x) -> ( x == 0 ? 0 : llvm.cttz(x)+1)
1727 const Type* arg_type = ci->getOperand(1)->getType();
1728 std::vector<const Type*> args;
1729 args.push_back(arg_type);
1730 FunctionType* llvm_cttz_type = FunctionType::get(arg_type,args,false);
1732 SLC.getModule()->getOrInsertFunction("llvm.cttz",llvm_cttz_type);
1733 std::string inst_name(ci->getName()+".ffs");
1735 new CallInst(F, ci->getOperand(1), inst_name, ci);
1736 if (arg_type != Type::IntTy)
1737 call = new CastInst(call, Type::IntTy, inst_name, ci);
1738 BinaryOperator* add = BinaryOperator::create(Instruction::Add, call,
1739 ConstantSInt::get(Type::IntTy,1), inst_name, ci);
1740 SetCondInst* eq = new SetCondInst(Instruction::SetEQ,ci->getOperand(1),
1741 ConstantSInt::get(ci->getOperand(1)->getType(),0),inst_name,ci);
1742 SelectInst* select = new SelectInst(eq,ConstantSInt::get(Type::IntTy,0),add,
1744 ci->replaceAllUsesWith(select);
1745 ci->eraseFromParent();
1750 /// This LibCallOptimization will simplify calls to the "ffsl" library
1751 /// calls. It simply uses FFSOptimization for which the transformation is
1753 /// @brief Simplify the ffsl library function.
1754 struct FFSLOptimization : public FFSOptimization
1757 /// @brief Default Constructor
1758 FFSLOptimization() : FFSOptimization("ffsl",
1759 "Number of 'ffsl' calls simplified") {}
1763 /// This LibCallOptimization will simplify calls to the "ffsll" library
1764 /// calls. It simply uses FFSOptimization for which the transformation is
1766 /// @brief Simplify the ffsl library function.
1767 struct FFSLLOptimization : public FFSOptimization
1770 /// @brief Default Constructor
1771 FFSLLOptimization() : FFSOptimization("ffsll",
1772 "Number of 'ffsll' calls simplified") {}
1776 /// This LibCallOptimization will simplify calls to the "__builtin_ffs"
1777 /// function which is generated by the CFE (its GCC specific).
1778 /// It simply uses FFSOptimization for which the transformation is
1780 /// @brief Simplify the ffsl library function.
1781 struct BuiltinFFSOptimization : public FFSOptimization
1784 /// @brief Default Constructor
1785 BuiltinFFSOptimization() : FFSOptimization("__builtin_ffs",
1786 "Number of '__builtin_ffs' calls simplified") {}
1788 } BuiltinFFSOptimization;
1790 /// A function to compute the length of a null-terminated constant array of
1791 /// integers. This function can't rely on the size of the constant array
1792 /// because there could be a null terminator in the middle of the array.
1793 /// We also have to bail out if we find a non-integer constant initializer
1794 /// of one of the elements or if there is no null-terminator. The logic
1795 /// below checks each of these conditions and will return true only if all
1796 /// conditions are met. In that case, the \p len parameter is set to the length
1797 /// of the null-terminated string. If false is returned, the conditions were
1798 /// not met and len is set to 0.
1799 /// @brief Get the length of a constant string (null-terminated array).
1800 bool getConstantStringLength(Value* V, uint64_t& len, ConstantArray** CA )
1802 assert(V != 0 && "Invalid args to getConstantStringLength");
1803 len = 0; // make sure we initialize this
1805 // If the value is not a GEP instruction nor a constant expression with a
1806 // GEP instruction, then return false because ConstantArray can't occur
1808 if (GetElementPtrInst* GEPI = dyn_cast<GetElementPtrInst>(V))
1810 else if (ConstantExpr* CE = dyn_cast<ConstantExpr>(V))
1811 if (CE->getOpcode() == Instruction::GetElementPtr)
1818 // Make sure the GEP has exactly three arguments.
1819 if (GEP->getNumOperands() != 3)
1822 // Check to make sure that the first operand of the GEP is an integer and
1823 // has value 0 so that we are sure we're indexing into the initializer.
1824 if (ConstantInt* op1 = dyn_cast<ConstantInt>(GEP->getOperand(1)))
1826 if (!op1->isNullValue())
1832 // Ensure that the second operand is a ConstantInt. If it isn't then this
1833 // GEP is wonky and we're not really sure what were referencing into and
1834 // better of not optimizing it. While we're at it, get the second index
1835 // value. We'll need this later for indexing the ConstantArray.
1836 uint64_t start_idx = 0;
1837 if (ConstantInt* CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
1838 start_idx = CI->getRawValue();
1842 // The GEP instruction, constant or instruction, must reference a global
1843 // variable that is a constant and is initialized. The referenced constant
1844 // initializer is the array that we'll use for optimization.
1845 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1846 if (!GV || !GV->isConstant() || !GV->hasInitializer())
1849 // Get the initializer.
1850 Constant* INTLZR = GV->getInitializer();
1852 // Handle the ConstantAggregateZero case
1853 if (ConstantAggregateZero* CAZ = dyn_cast<ConstantAggregateZero>(INTLZR))
1855 // This is a degenerate case. The initializer is constant zero so the
1856 // length of the string must be zero.
1861 // Must be a Constant Array
1862 ConstantArray* A = dyn_cast<ConstantArray>(INTLZR);
1866 // Get the number of elements in the array
1867 uint64_t max_elems = A->getType()->getNumElements();
1869 // Traverse the constant array from start_idx (derived above) which is
1870 // the place the GEP refers to in the array.
1871 for ( len = start_idx; len < max_elems; len++)
1873 if (ConstantInt* CI = dyn_cast<ConstantInt>(A->getOperand(len)))
1875 // Check for the null terminator
1876 if (CI->isNullValue())
1877 break; // we found end of string
1880 return false; // This array isn't suitable, non-int initializer
1882 if (len >= max_elems)
1883 return false; // This array isn't null terminated
1885 // Subtract out the initial value from the length
1889 return true; // success!
1893 // Additional cases that we need to add to this file:
1896 // * cbrt(expN(X)) -> expN(x/3)
1897 // * cbrt(sqrt(x)) -> pow(x,1/6)
1898 // * cbrt(sqrt(x)) -> pow(x,1/9)
1901 // * cos(-x) -> cos(x)
1904 // * exp(log(x)) -> x
1907 // * isascii(c) -> ((c & ~0x7f) == 0)
1910 // * isdigit(c) -> (unsigned)(c) - '0' <= 9
1913 // * log(exp(x)) -> x
1914 // * log(x**y) -> y*log(x)
1915 // * log(exp(y)) -> y*log(e)
1916 // * log(exp2(y)) -> y*log(2)
1917 // * log(exp10(y)) -> y*log(10)
1918 // * log(sqrt(x)) -> 0.5*log(x)
1919 // * log(pow(x,y)) -> y*log(x)
1921 // lround, lroundf, lroundl:
1922 // * lround(cnst) -> cnst'
1925 // * memcmp(s1,s2,0) -> 0
1926 // * memcmp(x,x,l) -> 0
1927 // * memcmp(x,y,l) -> cnst
1928 // (if all arguments are constant and strlen(x) <= l and strlen(y) <= l)
1929 // * memcmp(x,y,1) -> *x - *y
1932 // * memmove(d,s,l,a) -> memcpy(d,s,l,a)
1933 // (if s is a global constant array)
1936 // * pow(exp(x),y) -> exp(x*y)
1937 // * pow(sqrt(x),y) -> pow(x,y*0.5)
1938 // * pow(pow(x,y),z)-> pow(x,y*z)
1941 // * puts("") -> fputc("\n",stdout) (how do we get "stdout"?)
1943 // round, roundf, roundl:
1944 // * round(cnst) -> cnst'
1947 // * signbit(cnst) -> cnst'
1948 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
1950 // sqrt, sqrtf, sqrtl:
1951 // * sqrt(expN(x)) -> expN(x*0.5)
1952 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
1953 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
1956 // * stpcpy(str, "literal") ->
1957 // llvm.memcpy(str,"literal",strlen("literal")+1,1)
1959 // * strrchr(s,c) -> reverse_offset_of_in(c,s)
1960 // (if c is a constant integer and s is a constant string)
1961 // * strrchr(s1,0) -> strchr(s1,0)
1964 // * strncat(x,y,0) -> x
1965 // * strncat(x,y,0) -> x (if strlen(y) = 0)
1966 // * strncat(x,y,l) -> strcat(x,y) (if y and l are constants an l > strlen(y))
1969 // * strncpy(d,s,0) -> d
1970 // * strncpy(d,s,l) -> memcpy(d,s,l,1)
1971 // (if s and l are constants)
1974 // * strpbrk(s,a) -> offset_in_for(s,a)
1975 // (if s and a are both constant strings)
1976 // * strpbrk(s,"") -> 0
1977 // * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
1980 // * strspn(s,a) -> const_int (if both args are constant)
1981 // * strspn("",a) -> 0
1982 // * strspn(s,"") -> 0
1983 // * strcspn(s,a) -> const_int (if both args are constant)
1984 // * strcspn("",a) -> 0
1985 // * strcspn(s,"") -> strlen(a)
1988 // * strstr(x,x) -> x
1989 // * strstr(s1,s2) -> offset_of_s2_in(s1)
1990 // (if s1 and s2 are constant strings)
1993 // * tan(atan(x)) -> x
1995 // trunc, truncf, truncl:
1996 // * trunc(cnst) -> cnst'