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 "Number of well-known 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,
69 const char* stat_name, const char* description )
72 , occurrences(stat_name,description)
75 // Register this call optimizer in the optlist (a hash_map)
76 optlist[fname] = this;
79 /// @brief Deregister from the optlist
80 virtual ~LibCallOptimization() { optlist.erase(func_name); }
82 /// The implementation of this function in subclasses should determine if
83 /// \p F is suitable for the optimization. This method is called by
84 /// SimplifyLibCalls::runOnModule to short circuit visiting all the call
85 /// sites of such a function if that function is not suitable in the first
86 /// place. If the called function is suitabe, this method should return true;
87 /// false, otherwise. This function should also perform any lazy
88 /// initialization that the LibCallOptimization needs to do, if its to return
89 /// true. This avoids doing initialization until the optimizer is actually
90 /// going to be called upon to do some optimization.
91 /// @brief Determine if the function is suitable for optimization
92 virtual bool ValidateCalledFunction(
93 const Function* F, ///< The function that is the target of call sites
94 SimplifyLibCalls& SLC ///< The pass object invoking us
97 /// The implementations of this function in subclasses is the heart of the
98 /// SimplifyLibCalls algorithm. Sublcasses of this class implement
99 /// OptimizeCall to determine if (a) the conditions are right for optimizing
100 /// the call and (b) to perform the optimization. If an action is taken
101 /// against ci, the subclass is responsible for returning true and ensuring
102 /// that ci is erased from its parent.
103 /// @brief Optimize a call, if possible.
104 virtual bool OptimizeCall(
105 CallInst* ci, ///< The call instruction that should be optimized.
106 SimplifyLibCalls& SLC ///< The pass object invoking us
109 /// @brief Get the name of the library call being optimized
110 const char * getFunctionName() const { return func_name; }
113 /// @brief Called by SimplifyLibCalls to update the occurrences statistic.
114 void succeeded() { ++occurrences; }
118 const char* func_name; ///< Name of the library call we optimize
120 std::string stat_name; ///< Holder for debug statistic name
121 std::string stat_desc; ///< Holder for debug statistic description
122 Statistic<> occurrences; ///< debug statistic (-debug-only=simplify-libcalls)
126 /// This class is an LLVM Pass that applies each of the LibCallOptimization
127 /// instances to all the call sites in a module, relatively efficiently. The
128 /// purpose of this pass is to provide optimizations for calls to well-known
129 /// functions with well-known semantics, such as those in the c library. The
130 /// class provides the basic infrastructure for handling runOnModule. Whenever /// this pass finds a function call, it asks the appropriate optimizer to
131 /// validate the call (ValidateLibraryCall). If it is validated, then
132 /// the OptimizeCall method is also called.
133 /// @brief A ModulePass for optimizing well-known function calls.
134 class SimplifyLibCalls : public ModulePass
137 /// We need some target data for accurate signature details that are
138 /// target dependent. So we require target data in our AnalysisUsage.
139 /// @brief Require TargetData from AnalysisUsage.
140 virtual void getAnalysisUsage(AnalysisUsage& Info) const
142 // Ask that the TargetData analysis be performed before us so we can use
144 Info.addRequired<TargetData>();
147 /// For this pass, process all of the function calls in the module, calling
148 /// ValidateLibraryCall and OptimizeCall as appropriate.
149 /// @brief Run all the lib call optimizations on a Module.
150 virtual bool runOnModule(Module &M)
156 // The call optimizations can be recursive. That is, the optimization might
157 // generate a call to another function which can also be optimized. This way
158 // we make the LibCallOptimization instances very specific to the case they
159 // handle. It also means we need to keep running over the function calls in
160 // the module until we don't get any more optimizations possible.
161 bool found_optimization = false;
164 found_optimization = false;
165 for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI)
167 // All the "well-known" functions are external and have external linkage
168 // because they live in a runtime library somewhere and were (probably)
169 // not compiled by LLVM. So, we only act on external functions that have
170 // external linkage and non-empty uses.
171 if (!FI->isExternal() || !FI->hasExternalLinkage() || FI->use_empty())
174 // Get the optimization class that pertains to this function
175 LibCallOptimization* CO = optlist[FI->getName().c_str()];
179 // Make sure the called function is suitable for the optimization
180 if (!CO->ValidateCalledFunction(FI,*this))
183 // Loop over each of the uses of the function
184 for (Value::use_iterator UI = FI->use_begin(), UE = FI->use_end();
187 // If the use of the function is a call instruction
188 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
190 // Do the optimization on the LibCallOptimization.
191 if (CO->OptimizeCall(CI,*this))
193 ++SimplifiedLibCalls;
194 found_optimization = result = true;
202 } while (found_optimization);
206 /// @brief Return the *current* module we're working on.
207 Module* getModule() const { return M; }
209 /// @brief Return the *current* target data for the module we're working on.
210 TargetData* getTargetData() const { return TD; }
212 /// @brief Return the size_t type -- syntactic shortcut
213 const Type* getIntPtrType() const { return TD->getIntPtrType(); }
215 /// @brief Return a Function* for the fputc libcall
216 Function* get_fputc(const Type* FILEptr_type)
220 std::vector<const Type*> args;
221 args.push_back(Type::IntTy);
222 args.push_back(FILEptr_type);
223 FunctionType* fputc_type =
224 FunctionType::get(Type::IntTy, args, false);
225 fputc_func = M->getOrInsertFunction("fputc",fputc_type);
230 /// @brief Return a Function* for the fwrite libcall
231 Function* get_fwrite(const Type* FILEptr_type)
235 std::vector<const Type*> args;
236 args.push_back(PointerType::get(Type::SByteTy));
237 args.push_back(TD->getIntPtrType());
238 args.push_back(TD->getIntPtrType());
239 args.push_back(FILEptr_type);
240 FunctionType* fwrite_type =
241 FunctionType::get(TD->getIntPtrType(), args, false);
242 fwrite_func = M->getOrInsertFunction("fwrite",fwrite_type);
247 /// @brief Return a Function* for the sqrt libcall
252 std::vector<const Type*> args;
253 args.push_back(Type::DoubleTy);
254 FunctionType* sqrt_type =
255 FunctionType::get(Type::DoubleTy, args, false);
256 sqrt_func = M->getOrInsertFunction("sqrt",sqrt_type);
261 /// @brief Return a Function* for the strlen libcall
262 Function* get_strlen()
266 std::vector<const Type*> args;
267 args.push_back(PointerType::get(Type::SByteTy));
268 FunctionType* strlen_type =
269 FunctionType::get(TD->getIntPtrType(), args, false);
270 strlen_func = M->getOrInsertFunction("strlen",strlen_type);
275 /// @brief Return a Function* for the memcpy libcall
276 Function* get_memcpy()
280 // Note: this is for llvm.memcpy intrinsic
281 std::vector<const Type*> args;
282 args.push_back(PointerType::get(Type::SByteTy));
283 args.push_back(PointerType::get(Type::SByteTy));
284 args.push_back(Type::IntTy);
285 args.push_back(Type::IntTy);
286 FunctionType* memcpy_type = FunctionType::get(Type::VoidTy, args, false);
287 memcpy_func = M->getOrInsertFunction("llvm.memcpy",memcpy_type);
293 /// @brief Reset our cached data for a new Module
294 void reset(Module& mod)
297 TD = &getAnalysis<TargetData>();
306 Function* fputc_func; ///< Cached fputc function
307 Function* fwrite_func; ///< Cached fwrite function
308 Function* memcpy_func; ///< Cached llvm.memcpy function
309 Function* sqrt_func; ///< Cached sqrt function
310 Function* strlen_func; ///< Cached strlen function
311 Module* M; ///< Cached Module
312 TargetData* TD; ///< Cached TargetData
316 RegisterOpt<SimplifyLibCalls>
317 X("simplify-libcalls","Simplify well-known library calls");
319 } // anonymous namespace
321 // The only public symbol in this file which just instantiates the pass object
322 ModulePass *llvm::createSimplifyLibCallsPass()
324 return new SimplifyLibCalls();
327 // Classes below here, in the anonymous namespace, are all subclasses of the
328 // LibCallOptimization class, each implementing all optimizations possible for a
329 // single well-known library call. Each has a static singleton instance that
330 // auto registers it into the "optlist" global above.
333 // Forward declare a utility function.
334 bool getConstantStringLength(Value* V, uint64_t& len, ConstantArray** A = 0 );
336 /// This LibCallOptimization will find instances of a call to "exit" that occurs
337 /// within the "main" function and change it to a simple "ret" instruction with
338 /// the same value passed to the exit function. When this is done, it splits the
339 /// basic block at the exit(3) call and deletes the call instruction.
340 /// @brief Replace calls to exit in main with a simple return
341 struct ExitInMainOptimization : public LibCallOptimization
343 ExitInMainOptimization() : LibCallOptimization("exit",
344 "simplify-libcalls:exit","Number of 'exit' calls simplified") {}
345 virtual ~ExitInMainOptimization() {}
347 // Make sure the called function looks like exit (int argument, int return
348 // type, external linkage, not varargs).
349 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
351 if (f->arg_size() >= 1)
352 if (f->arg_begin()->getType()->isInteger())
357 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
359 // To be careful, we check that the call to exit is coming from "main", that
360 // main has external linkage, and the return type of main and the argument
361 // to exit have the same type.
362 Function *from = ci->getParent()->getParent();
363 if (from->hasExternalLinkage())
364 if (from->getReturnType() == ci->getOperand(1)->getType())
365 if (from->getName() == "main")
367 // Okay, time to actually do the optimization. First, get the basic
368 // block of the call instruction
369 BasicBlock* bb = ci->getParent();
371 // Create a return instruction that we'll replace the call with.
372 // Note that the argument of the return is the argument of the call
374 ReturnInst* ri = new ReturnInst(ci->getOperand(1), ci);
376 // Split the block at the call instruction which places it in a new
378 bb->splitBasicBlock(ci);
380 // The block split caused a branch instruction to be inserted into
381 // the end of the original block, right after the return instruction
382 // that we put there. That's not a valid block, so delete the branch
384 bb->getInstList().pop_back();
386 // Now we can finally get rid of the call instruction which now lives
387 // in the new basic block.
388 ci->eraseFromParent();
390 // Optimization succeeded, return true.
393 // We didn't pass the criteria for this optimization so return false
396 } ExitInMainOptimizer;
398 /// This LibCallOptimization will simplify a call to the strcat library
399 /// function. The simplification is possible only if the string being
400 /// concatenated is a constant array or a constant expression that results in
401 /// a constant string. In this case we can replace it with strlen + llvm.memcpy
402 /// of the constant string. Both of these calls are further reduced, if possible
403 /// on subsequent passes.
404 /// @brief Simplify the strcat library function.
405 struct StrCatOptimization : public LibCallOptimization
408 /// @brief Default constructor
409 StrCatOptimization() : LibCallOptimization("strcat",
410 "simplify-libcalls:strcat","Number of 'strcat' calls simplified") {}
413 /// @breif Destructor
414 virtual ~StrCatOptimization() {}
416 /// @brief Make sure that the "strcat" function has the right prototype
417 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
419 if (f->getReturnType() == PointerType::get(Type::SByteTy))
420 if (f->arg_size() == 2)
422 Function::const_arg_iterator AI = f->arg_begin();
423 if (AI++->getType() == PointerType::get(Type::SByteTy))
424 if (AI->getType() == PointerType::get(Type::SByteTy))
426 // Indicate this is a suitable call type.
433 /// @brief Optimize the strcat library function
434 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
436 // Extract some information from the instruction
437 Module* M = ci->getParent()->getParent()->getParent();
438 Value* dest = ci->getOperand(1);
439 Value* src = ci->getOperand(2);
441 // Extract the initializer (while making numerous checks) from the
442 // source operand of the call to strcat. If we get null back, one of
443 // a variety of checks in get_GVInitializer failed
445 if (!getConstantStringLength(src,len))
448 // Handle the simple, do-nothing case
451 ci->replaceAllUsesWith(dest);
452 ci->eraseFromParent();
456 // Increment the length because we actually want to memcpy the null
457 // terminator as well.
460 // We need to find the end of the destination string. That's where the
461 // memory is to be moved to. We just generate a call to strlen (further
462 // optimized in another pass). Note that the SLC.get_strlen() call
463 // caches the Function* for us.
464 CallInst* strlen_inst =
465 new CallInst(SLC.get_strlen(), dest, dest->getName()+".len",ci);
467 // Now that we have the destination's length, we must index into the
468 // destination's pointer to get the actual memcpy destination (end of
469 // the string .. we're concatenating).
470 std::vector<Value*> idx;
471 idx.push_back(strlen_inst);
472 GetElementPtrInst* gep =
473 new GetElementPtrInst(dest,idx,dest->getName()+".indexed",ci);
475 // We have enough information to now generate the memcpy call to
476 // do the concatenation for us.
477 std::vector<Value*> vals;
478 vals.push_back(gep); // destination
479 vals.push_back(ci->getOperand(2)); // source
480 vals.push_back(ConstantSInt::get(Type::IntTy,len)); // length
481 vals.push_back(ConstantSInt::get(Type::IntTy,1)); // alignment
482 new CallInst(SLC.get_memcpy(), vals, "", ci);
484 // Finally, substitute the first operand of the strcat call for the
485 // strcat call itself since strcat returns its first operand; and,
486 // kill the strcat CallInst.
487 ci->replaceAllUsesWith(dest);
488 ci->eraseFromParent();
493 /// This LibCallOptimization will simplify a call to the strcmp library
494 /// function. It optimizes out cases where one or both arguments are constant
495 /// and the result can be determined statically.
496 /// @brief Simplify the strcmp library function.
497 struct StrCmpOptimization : public LibCallOptimization
500 StrCmpOptimization() : LibCallOptimization("strcmp",
501 "simplify-libcalls:strcmp","Number of 'strcmp' calls simplified") {}
502 virtual ~StrCmpOptimization() {}
504 /// @brief Make sure that the "strcpy" function has the right prototype
505 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
507 if (f->getReturnType() == Type::IntTy && f->arg_size() == 2)
512 /// @brief Perform the strcpy optimization
513 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
515 // First, check to see if src and destination are the same. If they are,
516 // then the optimization is to replace the CallInst with a constant 0
517 // because the call is a no-op.
518 Value* s1 = ci->getOperand(1);
519 Value* s2 = ci->getOperand(2);
523 ci->replaceAllUsesWith(ConstantInt::get(Type::IntTy,0));
524 ci->eraseFromParent();
528 bool isstr_1 = false;
531 if (getConstantStringLength(s1,len_1,&A1))
536 // strcmp("",x) -> *x
537 LoadInst* load = new LoadInst(s1,ci->getName()+".load",ci);
539 new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
540 ci->replaceAllUsesWith(cast);
541 ci->eraseFromParent();
546 bool isstr_2 = false;
549 if (getConstantStringLength(s2,len_2,&A2))
554 // strcmp(x,"") -> *x
555 LoadInst* load = new LoadInst(s2,ci->getName()+".val",ci);
557 new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
558 ci->replaceAllUsesWith(cast);
559 ci->eraseFromParent();
564 if (isstr_1 && isstr_2)
566 // strcmp(x,y) -> cnst (if both x and y are constant strings)
567 std::string str1 = A1->getAsString();
568 std::string str2 = A2->getAsString();
569 int result = strcmp(str1.c_str(), str2.c_str());
570 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,result));
571 ci->eraseFromParent();
578 /// This LibCallOptimization will simplify a call to the strncmp library
579 /// function. It optimizes out cases where one or both arguments are constant
580 /// and the result can be determined statically.
581 /// @brief Simplify the strncmp library function.
582 struct StrNCmpOptimization : public LibCallOptimization
585 StrNCmpOptimization() : LibCallOptimization("strncmp",
586 "simplify-libcalls:strncmp","Number of 'strncmp' calls simplified") {}
587 virtual ~StrNCmpOptimization() {}
589 /// @brief Make sure that the "strcpy" function has the right prototype
590 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
592 if (f->getReturnType() == Type::IntTy && f->arg_size() == 3)
597 /// @brief Perform the strncpy optimization
598 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
600 // First, check to see if src and destination are the same. If they are,
601 // then the optimization is to replace the CallInst with a constant 0
602 // because the call is a no-op.
603 Value* s1 = ci->getOperand(1);
604 Value* s2 = ci->getOperand(2);
607 // strncmp(x,x,l) -> 0
608 ci->replaceAllUsesWith(ConstantInt::get(Type::IntTy,0));
609 ci->eraseFromParent();
613 // Check the length argument, if it is Constant zero then the strings are
615 uint64_t len_arg = 0;
616 bool len_arg_is_const = false;
617 if (ConstantInt* len_CI = dyn_cast<ConstantInt>(ci->getOperand(3)))
619 len_arg_is_const = true;
620 len_arg = len_CI->getRawValue();
623 // strncmp(x,y,0) -> 0
624 ci->replaceAllUsesWith(ConstantInt::get(Type::IntTy,0));
625 ci->eraseFromParent();
630 bool isstr_1 = false;
633 if (getConstantStringLength(s1,len_1,&A1))
638 // strncmp("",x) -> *x
639 LoadInst* load = new LoadInst(s1,ci->getName()+".load",ci);
641 new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
642 ci->replaceAllUsesWith(cast);
643 ci->eraseFromParent();
648 bool isstr_2 = false;
651 if (getConstantStringLength(s2,len_2,&A2))
656 // strncmp(x,"") -> *x
657 LoadInst* load = new LoadInst(s2,ci->getName()+".val",ci);
659 new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
660 ci->replaceAllUsesWith(cast);
661 ci->eraseFromParent();
666 if (isstr_1 && isstr_2 && len_arg_is_const)
668 // strncmp(x,y,const) -> constant
669 std::string str1 = A1->getAsString();
670 std::string str2 = A2->getAsString();
671 int result = strncmp(str1.c_str(), str2.c_str(), len_arg);
672 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,result));
673 ci->eraseFromParent();
680 /// This LibCallOptimization will simplify a call to the strcpy library
681 /// function. Two optimizations are possible:
682 /// (1) If src and dest are the same and not volatile, just return dest
683 /// (2) If the src is a constant then we can convert to llvm.memmove
684 /// @brief Simplify the strcpy library function.
685 struct StrCpyOptimization : public LibCallOptimization
688 StrCpyOptimization() : LibCallOptimization("strcpy",
689 "simplify-libcalls:strcpy","Number of 'strcpy' calls simplified") {}
690 virtual ~StrCpyOptimization() {}
692 /// @brief Make sure that the "strcpy" function has the right prototype
693 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
695 if (f->getReturnType() == PointerType::get(Type::SByteTy))
696 if (f->arg_size() == 2)
698 Function::const_arg_iterator AI = f->arg_begin();
699 if (AI++->getType() == PointerType::get(Type::SByteTy))
700 if (AI->getType() == PointerType::get(Type::SByteTy))
702 // Indicate this is a suitable call type.
709 /// @brief Perform the strcpy optimization
710 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
712 // First, check to see if src and destination are the same. If they are,
713 // then the optimization is to replace the CallInst with the destination
714 // because the call is a no-op. Note that this corresponds to the
715 // degenerate strcpy(X,X) case which should have "undefined" results
716 // according to the C specification. However, it occurs sometimes and
717 // we optimize it as a no-op.
718 Value* dest = ci->getOperand(1);
719 Value* src = ci->getOperand(2);
722 ci->replaceAllUsesWith(dest);
723 ci->eraseFromParent();
727 // Get the length of the constant string referenced by the second operand,
728 // the "src" parameter. Fail the optimization if we can't get the length
729 // (note that getConstantStringLength does lots of checks to make sure this
732 if (!getConstantStringLength(ci->getOperand(2),len))
735 // If the constant string's length is zero we can optimize this by just
736 // doing a store of 0 at the first byte of the destination
739 new StoreInst(ConstantInt::get(Type::SByteTy,0),ci->getOperand(1),ci);
740 ci->replaceAllUsesWith(dest);
741 ci->eraseFromParent();
745 // Increment the length because we actually want to memcpy the null
746 // terminator as well.
749 // Extract some information from the instruction
750 Module* M = ci->getParent()->getParent()->getParent();
752 // We have enough information to now generate the memcpy call to
753 // do the concatenation for us.
754 std::vector<Value*> vals;
755 vals.push_back(dest); // destination
756 vals.push_back(src); // source
757 vals.push_back(ConstantSInt::get(Type::IntTy,len)); // length
758 vals.push_back(ConstantSInt::get(Type::IntTy,1)); // alignment
759 new CallInst(SLC.get_memcpy(), vals, "", ci);
761 // Finally, substitute the first operand of the strcat call for the
762 // strcat call itself since strcat returns its first operand; and,
763 // kill the strcat CallInst.
764 ci->replaceAllUsesWith(dest);
765 ci->eraseFromParent();
770 /// This LibCallOptimization will simplify a call to the strlen library
771 /// function by replacing it with a constant value if the string provided to
772 /// it is a constant array.
773 /// @brief Simplify the strlen library function.
774 struct StrLenOptimization : public LibCallOptimization
776 StrLenOptimization() : LibCallOptimization("strlen",
777 "simplify-libcalls:strlen","Number of 'strlen' calls simplified") {}
778 virtual ~StrLenOptimization() {}
780 /// @brief Make sure that the "strlen" function has the right prototype
781 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
783 if (f->getReturnType() == SLC.getTargetData()->getIntPtrType())
784 if (f->arg_size() == 1)
785 if (Function::const_arg_iterator AI = f->arg_begin())
786 if (AI->getType() == PointerType::get(Type::SByteTy))
791 /// @brief Perform the strlen optimization
792 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
794 // Get the length of the string
796 if (!getConstantStringLength(ci->getOperand(1),len))
799 ci->replaceAllUsesWith(
800 ConstantInt::get(SLC.getTargetData()->getIntPtrType(),len));
801 ci->eraseFromParent();
806 /// This LibCallOptimization will simplify a call to the memcpy library
807 /// function by expanding it out to a single store of size 0, 1, 2, 4, or 8
808 /// bytes depending on the length of the string and the alignment. Additional
809 /// optimizations are possible in code generation (sequence of immediate store)
810 /// @brief Simplify the memcpy library function.
811 struct MemCpyOptimization : public LibCallOptimization
813 /// @brief Default Constructor
814 MemCpyOptimization() : LibCallOptimization("llvm.memcpy",
815 "simplify-libcalls:llvm.memcpy",
816 "Number of 'llvm.memcpy' calls simplified") {}
819 /// @brief Subclass Constructor
820 MemCpyOptimization(const char* fname, const char* sname, const char* desc)
821 : LibCallOptimization(fname, sname, desc) {}
823 /// @brief Destructor
824 virtual ~MemCpyOptimization() {}
826 /// @brief Make sure that the "memcpy" function has the right prototype
827 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& TD)
829 // Just make sure this has 4 arguments per LLVM spec.
830 return (f->arg_size() == 4);
833 /// Because of alignment and instruction information that we don't have, we
834 /// leave the bulk of this to the code generators. The optimization here just
835 /// deals with a few degenerate cases where the length of the string and the
836 /// alignment match the sizes of our intrinsic types so we can do a load and
837 /// store instead of the memcpy call.
838 /// @brief Perform the memcpy optimization.
839 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& TD)
841 // Make sure we have constant int values to work with
842 ConstantInt* LEN = dyn_cast<ConstantInt>(ci->getOperand(3));
845 ConstantInt* ALIGN = dyn_cast<ConstantInt>(ci->getOperand(4));
849 // If the length is larger than the alignment, we can't optimize
850 uint64_t len = LEN->getRawValue();
851 uint64_t alignment = ALIGN->getRawValue();
855 // Get the type we will cast to, based on size of the string
856 Value* dest = ci->getOperand(1);
857 Value* src = ci->getOperand(2);
862 // memcpy(d,s,0,a) -> noop
863 ci->eraseFromParent();
865 case 1: castType = Type::SByteTy; break;
866 case 2: castType = Type::ShortTy; break;
867 case 4: castType = Type::IntTy; break;
868 case 8: castType = Type::LongTy; break;
873 // Cast source and dest to the right sized primitive and then load/store
875 new CastInst(src,PointerType::get(castType),src->getName()+".cast",ci);
877 new CastInst(dest,PointerType::get(castType),dest->getName()+".cast",ci);
878 LoadInst* LI = new LoadInst(SrcCast,SrcCast->getName()+".val",ci);
879 StoreInst* SI = new StoreInst(LI, DestCast, ci);
880 ci->eraseFromParent();
885 /// This LibCallOptimization will simplify a call to the memmove library
886 /// function. It is identical to MemCopyOptimization except for the name of
888 /// @brief Simplify the memmove library function.
889 struct MemMoveOptimization : public MemCpyOptimization
891 /// @brief Default Constructor
892 MemMoveOptimization() : MemCpyOptimization("llvm.memmove",
893 "simplify-libcalls:llvm.memmove",
894 "Number of 'llvm.memmove' calls simplified") {}
898 /// This LibCallOptimization will simplify calls to the "pow" library
899 /// function. It looks for cases where the result of pow is well known and
900 /// substitutes the appropriate value.
901 /// @brief Simplify the pow library function.
902 struct PowOptimization : public LibCallOptimization
905 /// @brief Default Constructor
906 PowOptimization() : LibCallOptimization("pow",
907 "simplify-libcalls:pow", "Number of 'pow' calls simplified") {}
909 /// @brief Destructor
910 virtual ~PowOptimization() {}
912 /// @brief Make sure that the "pow" function has the right prototype
913 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
915 // Just make sure this has 2 arguments
916 return (f->arg_size() == 2);
919 /// @brief Perform the pow optimization.
920 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
922 const Type *Ty = cast<Function>(ci->getOperand(0))->getReturnType();
923 Value* base = ci->getOperand(1);
924 Value* expn = ci->getOperand(2);
925 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(base)) {
926 double Op1V = Op1->getValue();
930 ci->replaceAllUsesWith(ConstantFP::get(Ty,1.0));
931 ci->eraseFromParent();
935 else if (ConstantFP* Op2 = dyn_cast<ConstantFP>(expn))
937 double Op2V = Op2->getValue();
941 ci->replaceAllUsesWith(ConstantFP::get(Ty,1.0));
942 ci->eraseFromParent();
945 else if (Op2V == 0.5)
947 // pow(x,0.5) -> sqrt(x)
948 CallInst* sqrt_inst = new CallInst(SLC.get_sqrt(), base,
949 ci->getName()+".pow",ci);
950 ci->replaceAllUsesWith(sqrt_inst);
951 ci->eraseFromParent();
954 else if (Op2V == 1.0)
957 ci->replaceAllUsesWith(base);
958 ci->eraseFromParent();
961 else if (Op2V == -1.0)
963 // pow(x,-1.0) -> 1.0/x
964 BinaryOperator* div_inst= BinaryOperator::create(Instruction::Div,
965 ConstantFP::get(Ty,1.0), base, ci->getName()+".pow", ci);
966 ci->replaceAllUsesWith(div_inst);
967 ci->eraseFromParent();
971 return false; // opt failed
975 /// This LibCallOptimization will simplify calls to the "fprintf" library
976 /// function. It looks for cases where the result of fprintf is not used and the
977 /// operation can be reduced to something simpler.
978 /// @brief Simplify the pow library function.
979 struct FPrintFOptimization : public LibCallOptimization
982 /// @brief Default Constructor
983 FPrintFOptimization() : LibCallOptimization("fprintf",
984 "simplify-libcalls:fprintf", "Number of 'fprintf' calls simplified") {}
986 /// @brief Destructor
987 virtual ~FPrintFOptimization() {}
989 /// @brief Make sure that the "fprintf" function has the right prototype
990 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
992 // Just make sure this has at least 2 arguments
993 return (f->arg_size() >= 2);
996 /// @brief Perform the fprintf optimization.
997 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
999 // If the call has more than 3 operands, we can't optimize it
1000 if (ci->getNumOperands() > 4 || ci->getNumOperands() <= 2)
1003 // If the result of the fprintf call is used, none of these optimizations
1005 if (!ci->hasNUses(0))
1008 // All the optimizations depend on the length of the second argument and the
1009 // fact that it is a constant string array. Check that now
1011 ConstantArray* CA = 0;
1012 if (!getConstantStringLength(ci->getOperand(2), len, &CA))
1015 if (ci->getNumOperands() == 3)
1017 // Make sure there's no % in the constant array
1018 for (unsigned i = 0; i < len; ++i)
1020 if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(i)))
1022 // Check for the null terminator
1023 if (CI->getRawValue() == '%')
1024 return false; // we found end of string
1030 // fprintf(file,fmt) -> fwrite(fmt,strlen(fmt),1file)
1031 const Type* FILEptr_type = ci->getOperand(1)->getType();
1032 Function* fwrite_func = SLC.get_fwrite(FILEptr_type);
1035 std::vector<Value*> args;
1036 args.push_back(ci->getOperand(2));
1037 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
1038 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),1));
1039 args.push_back(ci->getOperand(1));
1040 new CallInst(fwrite_func,args,"",ci);
1041 ci->eraseFromParent();
1045 // The remaining optimizations require the format string to be length 2
1050 // The first character has to be a %
1051 if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(0)))
1052 if (CI->getRawValue() != '%')
1055 // Get the second character and switch on its value
1056 ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(1));
1057 switch (CI->getRawValue())
1062 ConstantArray* CA = 0;
1063 if (!getConstantStringLength(ci->getOperand(3), len, &CA))
1066 // fprintf(file,fmt) -> fwrite(fmt,strlen(fmt),1,file)
1067 const Type* FILEptr_type = ci->getOperand(1)->getType();
1068 Function* fwrite_func = SLC.get_fwrite(FILEptr_type);
1071 std::vector<Value*> args;
1072 args.push_back(ci->getOperand(3));
1073 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
1074 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),1));
1075 args.push_back(ci->getOperand(1));
1076 new CallInst(fwrite_func,args,"",ci);
1081 ConstantInt* CI = dyn_cast<ConstantInt>(ci->getOperand(3));
1085 const Type* FILEptr_type = ci->getOperand(1)->getType();
1086 Function* fputc_func = SLC.get_fputc(FILEptr_type);
1089 CastInst* cast = new CastInst(CI,Type::IntTy,CI->getName()+".int",ci);
1090 new CallInst(fputc_func,cast,ci->getOperand(1),"",ci);
1096 ci->eraseFromParent();
1102 /// This LibCallOptimization will simplify calls to the "fputs" library
1103 /// function. It looks for cases where the result of fputs is not used and the
1104 /// operation can be reduced to something simpler.
1105 /// @brief Simplify the pow library function.
1106 struct PutsOptimization : public LibCallOptimization
1109 /// @brief Default Constructor
1110 PutsOptimization() : LibCallOptimization("fputs",
1111 "simplify-libcalls:fputs", "Number of 'fputs' calls simplified") {}
1113 /// @brief Destructor
1114 virtual ~PutsOptimization() {}
1116 /// @brief Make sure that the "fputs" function has the right prototype
1117 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1119 // Just make sure this has 2 arguments
1120 return (f->arg_size() == 2);
1123 /// @brief Perform the fputs optimization.
1124 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1126 // If the result is used, none of these optimizations work
1127 if (!ci->hasNUses(0))
1130 // All the optimizations depend on the length of the first argument and the
1131 // fact that it is a constant string array. Check that now
1133 if (!getConstantStringLength(ci->getOperand(1), len))
1139 // fputs("",F) -> noop
1143 // fputs(s,F) -> fputc(s[0],F) (if s is constant and strlen(s) == 1)
1144 const Type* FILEptr_type = ci->getOperand(2)->getType();
1145 Function* fputc_func = SLC.get_fputc(FILEptr_type);
1148 LoadInst* loadi = new LoadInst(ci->getOperand(1),
1149 ci->getOperand(1)->getName()+".byte",ci);
1150 CastInst* casti = new CastInst(loadi,Type::IntTy,
1151 loadi->getName()+".int",ci);
1152 new CallInst(fputc_func,casti,ci->getOperand(2),"",ci);
1157 // fputs(s,F) -> fwrite(s,1,len,F) (if s is constant and strlen(s) > 1)
1158 const Type* FILEptr_type = ci->getOperand(2)->getType();
1159 Function* fwrite_func = SLC.get_fwrite(FILEptr_type);
1162 std::vector<Value*> parms;
1163 parms.push_back(ci->getOperand(1));
1164 parms.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
1165 parms.push_back(ConstantUInt::get(SLC.getIntPtrType(),1));
1166 parms.push_back(ci->getOperand(2));
1167 new CallInst(fwrite_func,parms,"",ci);
1171 ci->eraseFromParent();
1172 return true; // success
1176 /// This LibCallOptimization will simplify calls to the "toascii" library
1177 /// function. It simply does the corresponding and operation to restrict the
1178 /// range of values to the ASCII character set (0-127).
1179 /// @brief Simplify the toascii library function.
1180 struct ToAsciiOptimization : public LibCallOptimization
1183 /// @brief Default Constructor
1184 ToAsciiOptimization() : LibCallOptimization("toascii",
1185 "simplify-libcalls:toascii", "Number of 'toascii' calls simplified") {}
1187 /// @brief Destructor
1188 virtual ~ToAsciiOptimization() {}
1190 /// @brief Make sure that the "fputs" function has the right prototype
1191 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1193 // Just make sure this has 2 arguments
1194 return (f->arg_size() == 1);
1197 /// @brief Perform the toascii optimization.
1198 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1200 // toascii(c) -> (c & 0x7f)
1201 Value* chr = ci->getOperand(1);
1202 BinaryOperator* and_inst = BinaryOperator::create(Instruction::And,chr,
1203 ConstantInt::get(chr->getType(),0x7F),ci->getName()+".toascii",ci);
1204 ci->replaceAllUsesWith(and_inst);
1205 ci->eraseFromParent();
1210 /// A function to compute the length of a null-terminated constant array of
1211 /// integers. This function can't rely on the size of the constant array
1212 /// because there could be a null terminator in the middle of the array.
1213 /// We also have to bail out if we find a non-integer constant initializer
1214 /// of one of the elements or if there is no null-terminator. The logic
1215 /// below checks each of these conditions and will return true only if all
1216 /// conditions are met. In that case, the \p len parameter is set to the length
1217 /// of the null-terminated string. If false is returned, the conditions were
1218 /// not met and len is set to 0.
1219 /// @brief Get the length of a constant string (null-terminated array).
1220 bool getConstantStringLength(Value* V, uint64_t& len, ConstantArray** CA )
1222 assert(V != 0 && "Invalid args to getConstantStringLength");
1223 len = 0; // make sure we initialize this
1225 // If the value is not a GEP instruction nor a constant expression with a
1226 // GEP instruction, then return false because ConstantArray can't occur
1228 if (GetElementPtrInst* GEPI = dyn_cast<GetElementPtrInst>(V))
1230 else if (ConstantExpr* CE = dyn_cast<ConstantExpr>(V))
1231 if (CE->getOpcode() == Instruction::GetElementPtr)
1238 // Make sure the GEP has exactly three arguments.
1239 if (GEP->getNumOperands() != 3)
1242 // Check to make sure that the first operand of the GEP is an integer and
1243 // has value 0 so that we are sure we're indexing into the initializer.
1244 if (ConstantInt* op1 = dyn_cast<ConstantInt>(GEP->getOperand(1)))
1246 if (!op1->isNullValue())
1252 // Ensure that the second operand is a ConstantInt. If it isn't then this
1253 // GEP is wonky and we're not really sure what were referencing into and
1254 // better of not optimizing it. While we're at it, get the second index
1255 // value. We'll need this later for indexing the ConstantArray.
1256 uint64_t start_idx = 0;
1257 if (ConstantInt* CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
1258 start_idx = CI->getRawValue();
1262 // The GEP instruction, constant or instruction, must reference a global
1263 // variable that is a constant and is initialized. The referenced constant
1264 // initializer is the array that we'll use for optimization.
1265 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1266 if (!GV || !GV->isConstant() || !GV->hasInitializer())
1269 // Get the initializer.
1270 Constant* INTLZR = GV->getInitializer();
1272 // Handle the ConstantAggregateZero case
1273 if (ConstantAggregateZero* CAZ = dyn_cast<ConstantAggregateZero>(INTLZR))
1275 // This is a degenerate case. The initializer is constant zero so the
1276 // length of the string must be zero.
1281 // Must be a Constant Array
1282 ConstantArray* A = dyn_cast<ConstantArray>(INTLZR);
1286 // Get the number of elements in the array
1287 uint64_t max_elems = A->getType()->getNumElements();
1289 // Traverse the constant array from start_idx (derived above) which is
1290 // the place the GEP refers to in the array.
1291 for ( len = start_idx; len < max_elems; len++)
1293 if (ConstantInt* CI = dyn_cast<ConstantInt>(A->getOperand(len)))
1295 // Check for the null terminator
1296 if (CI->isNullValue())
1297 break; // we found end of string
1300 return false; // This array isn't suitable, non-int initializer
1302 if (len >= max_elems)
1303 return false; // This array isn't null terminated
1305 // Subtract out the initial value from the length
1309 return true; // success!
1313 // Additional cases that we need to add to this file:
1316 // * cbrt(expN(X)) -> expN(x/3)
1317 // * cbrt(sqrt(x)) -> pow(x,1/6)
1318 // * cbrt(sqrt(x)) -> pow(x,1/9)
1321 // * cos(-x) -> cos(x)
1324 // * exp(log(x)) -> x
1326 // ffs, ffsl, ffsll:
1327 // * ffs(cnst) -> cnst'
1330 // * isascii(c) -> ((c & ~0x7f) == 0)
1333 // * isdigit(c) -> (unsigned)(c) - '0' <= 9
1336 // * log(exp(x)) -> x
1337 // * log(x**y) -> y*log(x)
1338 // * log(exp(y)) -> y*log(e)
1339 // * log(exp2(y)) -> y*log(2)
1340 // * log(exp10(y)) -> y*log(10)
1341 // * log(sqrt(x)) -> 0.5*log(x)
1342 // * log(pow(x,y)) -> y*log(x)
1344 // lround, lroundf, lroundl:
1345 // * lround(cnst) -> cnst'
1348 // * memcmp(s1,s2,0) -> 0
1349 // * memcmp(x,x,l) -> 0
1350 // * memcmp(x,y,l) -> cnst
1351 // (if all arguments are constant and strlen(x) <= l and strlen(y) <= l)
1352 // * memcpy(x,y,1) -> *x - *y
1355 // * memmove(d,s,l,a) -> memcpy(d,s,l,a)
1356 // (if s is a global constant array)
1359 // * memset(s,c,0) -> noop
1360 // * memset(s,c,n) -> store s, c
1364 // * pow(exp(x),y) -> exp(x*y)
1365 // * pow(sqrt(x),y) -> pow(x,y*0.5)
1366 // * pow(pow(x,y),z)-> pow(x,y*z)
1369 // * puts("") -> fputc("\n",stdout) (how do we get "stdout"?)
1371 // round, roundf, roundl:
1372 // * round(cnst) -> cnst'
1375 // * signbit(cnst) -> cnst'
1376 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
1379 // * sprintf(dest,fmt) -> strcpy(dest,fmt)
1380 // (if fmt is constant and constains no % characters)
1381 // * sprintf(dest,"%s",orig) -> strcpy(dest,orig)
1382 // (only if the sprintf result is not used)
1384 // sqrt, sqrtf, sqrtl:
1385 // * sqrt(expN(x)) -> expN(x*0.5)
1386 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
1387 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
1390 // * strchr(s,c) -> offset_of_in(c,s)
1391 // (if c is a constant integer and s is a constant string)
1392 // * strrchr(s,c) -> reverse_offset_of_in(c,s)
1393 // (if c is a constant integer and s is a constant string)
1394 // * strrchr(s1,0) -> strchr(s1,0)
1397 // * strncat(x,y,0) -> x
1398 // * strncat(x,y,0) -> x (if strlen(y) = 0)
1399 // * strncat(x,y,l) -> strcat(x,y) (if y and l are constants an l > strlen(y))
1402 // * strncpy(d,s,0) -> d
1403 // * strncpy(d,s,l) -> memcpy(d,s,l,1)
1404 // (if s and l are constants)
1407 // * strpbrk(s,a) -> offset_in_for(s,a)
1408 // (if s and a are both constant strings)
1409 // * strpbrk(s,"") -> 0
1410 // * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
1413 // * strspn(s,a) -> const_int (if both args are constant)
1414 // * strspn("",a) -> 0
1415 // * strspn(s,"") -> 0
1416 // * strcspn(s,a) -> const_int (if both args are constant)
1417 // * strcspn("",a) -> 0
1418 // * strcspn(s,"") -> strlen(a)
1421 // * strstr(x,x) -> x
1422 // * strstr(s1,s2) -> offset_of_s2_in(s1)
1423 // (if s1 and s2 are constant strings)
1426 // * tan(atan(x)) -> x
1428 // trunc, truncf, truncl:
1429 // * trunc(cnst) -> cnst'