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 module pass that applies a variety of small
11 // optimizations for calls to specific well-known function calls (e.g. runtime
12 // library functions). For example, a call to the function "exit(3)" that
13 // occurs within the main() function can be transformed into a simple "return 3"
14 // instruction. Any optimization that takes this form (replace call to library
15 // function with simpler code that provides the same result) belongs in this
18 //===----------------------------------------------------------------------===//
20 #define DEBUG_TYPE "simplify-libcalls"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/Module.h"
25 #include "llvm/Pass.h"
26 #include "llvm/ADT/hash_map"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Transforms/IPO.h"
36 /// This statistic keeps track of the total number of library calls that have
37 /// been simplified regardless of which call it is.
38 Statistic<> SimplifiedLibCalls("simplify-libcalls",
39 "Number of library calls simplified");
41 // Forward declarations
42 class LibCallOptimization;
43 class SimplifyLibCalls;
45 /// This hash map is populated by the constructor for LibCallOptimization class.
46 /// Therefore all subclasses are registered here at static initialization time
47 /// and this list is what the SimplifyLibCalls pass uses to apply the individual
48 /// optimizations to the call sites.
49 /// @brief The list of optimizations deriving from LibCallOptimization
50 static hash_map<std::string,LibCallOptimization*> optlist;
52 /// This class is the abstract base class for the set of optimizations that
53 /// corresponds to one library call. The SimplifyLibCalls pass will call the
54 /// ValidateCalledFunction method to ask the optimization if a given Function
55 /// is the kind that the optimization can handle. If the subclass returns true,
56 /// then SImplifyLibCalls will also call the OptimizeCall method to perform,
57 /// or attempt to perform, the optimization(s) for the library call. Otherwise,
58 /// OptimizeCall won't be called. Subclasses are responsible for providing the
59 /// name of the library call (strlen, strcpy, etc.) to the LibCallOptimization
60 /// constructor. This is used to efficiently select which call instructions to
61 /// optimize. The criteria for a "lib call" is "anything with well known
62 /// semantics", typically a library function that is defined by an international
63 /// standard. Because the semantics are well known, the optimizations can
64 /// generally short-circuit actually calling the function if there's a simpler
65 /// way (e.g. strlen(X) can be reduced to a constant if X is a constant global).
66 /// @brief Base class for library call optimizations
67 class LibCallOptimization
70 /// The \p fname argument must be the name of the library function being
71 /// optimized by the subclass.
72 /// @brief Constructor that registers the optimization.
73 LibCallOptimization(const char* fname, const char* description )
76 , occurrences("simplify-libcalls",description)
79 // Register this call optimizer in the optlist (a hash_map)
80 optlist[fname] = this;
83 /// @brief Deregister from the optlist
84 virtual ~LibCallOptimization() { optlist.erase(func_name); }
86 /// The implementation of this function in subclasses should determine if
87 /// \p F is suitable for the optimization. This method is called by
88 /// SimplifyLibCalls::runOnModule to short circuit visiting all the call
89 /// sites of such a function if that function is not suitable in the first
90 /// place. If the called function is suitabe, this method should return true;
91 /// false, otherwise. This function should also perform any lazy
92 /// initialization that the LibCallOptimization needs to do, if its to return
93 /// true. This avoids doing initialization until the optimizer is actually
94 /// going to be called upon to do some optimization.
95 /// @brief Determine if the function is suitable for optimization
96 virtual bool ValidateCalledFunction(
97 const Function* F, ///< The function that is the target of call sites
98 SimplifyLibCalls& SLC ///< The pass object invoking us
101 /// The implementations of this function in subclasses is the heart of the
102 /// SimplifyLibCalls algorithm. Sublcasses of this class implement
103 /// OptimizeCall to determine if (a) the conditions are right for optimizing
104 /// the call and (b) to perform the optimization. If an action is taken
105 /// against ci, the subclass is responsible for returning true and ensuring
106 /// that ci is erased from its parent.
107 /// @brief Optimize a call, if possible.
108 virtual bool OptimizeCall(
109 CallInst* ci, ///< The call instruction that should be optimized.
110 SimplifyLibCalls& SLC ///< The pass object invoking us
113 /// @brief Get the name of the library call being optimized
114 const char * getFunctionName() const { return func_name; }
117 /// @brief Called by SimplifyLibCalls to update the occurrences statistic.
118 void succeeded() { DEBUG(++occurrences); }
122 const char* func_name; ///< Name of the library call we optimize
124 Statistic<> occurrences; ///< debug statistic (-debug-only=simplify-libcalls)
128 /// This class is an LLVM Pass that applies each of the LibCallOptimization
129 /// instances to all the call sites in a module, relatively efficiently. The
130 /// purpose of this pass is to provide optimizations for calls to well-known
131 /// functions with well-known semantics, such as those in the c library. The
132 /// class provides the basic infrastructure for handling runOnModule. Whenever
133 /// this pass finds a function call, it asks the appropriate optimizer to
134 /// validate the call (ValidateLibraryCall). If it is validated, then
135 /// the OptimizeCall method is also called.
136 /// @brief A ModulePass for optimizing well-known function calls.
137 class SimplifyLibCalls : public ModulePass
140 /// We need some target data for accurate signature details that are
141 /// target dependent. So we require target data in our AnalysisUsage.
142 /// @brief Require TargetData from AnalysisUsage.
143 virtual void getAnalysisUsage(AnalysisUsage& Info) const
145 // Ask that the TargetData analysis be performed before us so we can use
147 Info.addRequired<TargetData>();
150 /// For this pass, process all of the function calls in the module, calling
151 /// ValidateLibraryCall and OptimizeCall as appropriate.
152 /// @brief Run all the lib call optimizations on a Module.
153 virtual bool runOnModule(Module &M)
159 // The call optimizations can be recursive. That is, the optimization might
160 // generate a call to another function which can also be optimized. This way
161 // we make the LibCallOptimization instances very specific to the case they
162 // handle. It also means we need to keep running over the function calls in
163 // the module until we don't get any more optimizations possible.
164 bool found_optimization = false;
167 found_optimization = false;
168 for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI)
170 // All the "well-known" functions are external and have external linkage
171 // because they live in a runtime library somewhere and were (probably)
172 // not compiled by LLVM. So, we only act on external functions that
173 // have external linkage and non-empty uses.
174 if (!FI->isExternal() || !FI->hasExternalLinkage() || FI->use_empty())
177 // Get the optimization class that pertains to this function
178 LibCallOptimization* CO = optlist[FI->getName().c_str()];
182 // Make sure the called function is suitable for the optimization
183 if (!CO->ValidateCalledFunction(FI,*this))
186 // Loop over each of the uses of the function
187 for (Value::use_iterator UI = FI->use_begin(), UE = FI->use_end();
190 // If the use of the function is a call instruction
191 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
193 // Do the optimization on the LibCallOptimization.
194 if (CO->OptimizeCall(CI,*this))
196 ++SimplifiedLibCalls;
197 found_optimization = result = true;
205 } while (found_optimization);
209 /// @brief Return the *current* module we're working on.
210 Module* getModule() const { return M; }
212 /// @brief Return the *current* target data for the module we're working on.
213 TargetData* getTargetData() const { return TD; }
215 /// @brief Return the size_t type -- syntactic shortcut
216 const Type* getIntPtrType() const { return TD->getIntPtrType(); }
218 /// @brief Return a Function* for the fputc libcall
219 Function* get_fputc(const Type* FILEptr_type)
223 std::vector<const Type*> args;
224 args.push_back(Type::IntTy);
225 args.push_back(FILEptr_type);
226 FunctionType* fputc_type =
227 FunctionType::get(Type::IntTy, args, false);
228 fputc_func = M->getOrInsertFunction("fputc",fputc_type);
233 /// @brief Return a Function* for the fwrite libcall
234 Function* get_fwrite(const Type* FILEptr_type)
238 std::vector<const Type*> args;
239 args.push_back(PointerType::get(Type::SByteTy));
240 args.push_back(TD->getIntPtrType());
241 args.push_back(TD->getIntPtrType());
242 args.push_back(FILEptr_type);
243 FunctionType* fwrite_type =
244 FunctionType::get(TD->getIntPtrType(), args, false);
245 fwrite_func = M->getOrInsertFunction("fwrite",fwrite_type);
250 /// @brief Return a Function* for the sqrt libcall
255 std::vector<const Type*> args;
256 args.push_back(Type::DoubleTy);
257 FunctionType* sqrt_type =
258 FunctionType::get(Type::DoubleTy, args, false);
259 sqrt_func = M->getOrInsertFunction("sqrt",sqrt_type);
264 /// @brief Return a Function* for the strlen libcall
265 Function* get_strcpy()
269 std::vector<const Type*> args;
270 args.push_back(PointerType::get(Type::SByteTy));
271 args.push_back(PointerType::get(Type::SByteTy));
272 FunctionType* strcpy_type =
273 FunctionType::get(PointerType::get(Type::SByteTy), args, false);
274 strcpy_func = M->getOrInsertFunction("strcpy",strcpy_type);
279 /// @brief Return a Function* for the strlen libcall
280 Function* get_strlen()
284 std::vector<const Type*> args;
285 args.push_back(PointerType::get(Type::SByteTy));
286 FunctionType* strlen_type =
287 FunctionType::get(TD->getIntPtrType(), args, false);
288 strlen_func = M->getOrInsertFunction("strlen",strlen_type);
293 /// @brief Return a Function* for the memchr libcall
294 Function* get_memchr()
298 std::vector<const Type*> args;
299 args.push_back(PointerType::get(Type::SByteTy));
300 args.push_back(Type::IntTy);
301 args.push_back(TD->getIntPtrType());
302 FunctionType* memchr_type = FunctionType::get(
303 PointerType::get(Type::SByteTy), args, false);
304 memchr_func = M->getOrInsertFunction("memchr",memchr_type);
309 /// @brief Return a Function* for the memcpy libcall
310 Function* get_memcpy() {
312 const Type *SBP = PointerType::get(Type::SByteTy);
313 memcpy_func = M->getOrInsertFunction("llvm.memcpy", Type::VoidTy,SBP, SBP,
314 Type::UIntTy, Type::UIntTy,
320 Function* get_floorf() {
322 floorf_func = M->getOrInsertFunction("floorf", Type::FloatTy,
323 Type::FloatTy, (Type *)0);
328 /// @brief Reset our cached data for a new Module
329 void reset(Module& mod)
332 TD = &getAnalysis<TargetData>();
344 Function* fputc_func; ///< Cached fputc function
345 Function* fwrite_func; ///< Cached fwrite function
346 Function* memcpy_func; ///< Cached llvm.memcpy function
347 Function* memchr_func; ///< Cached memchr function
348 Function* sqrt_func; ///< Cached sqrt function
349 Function* strcpy_func; ///< Cached strcpy function
350 Function* strlen_func; ///< Cached strlen function
351 Function* floorf_func; ///< Cached floorf function
352 Module* M; ///< Cached Module
353 TargetData* TD; ///< Cached TargetData
357 RegisterOpt<SimplifyLibCalls>
358 X("simplify-libcalls","Simplify well-known library calls");
360 } // anonymous namespace
362 // The only public symbol in this file which just instantiates the pass object
363 ModulePass *llvm::createSimplifyLibCallsPass()
365 return new SimplifyLibCalls();
368 // Classes below here, in the anonymous namespace, are all subclasses of the
369 // LibCallOptimization class, each implementing all optimizations possible for a
370 // single well-known library call. Each has a static singleton instance that
371 // auto registers it into the "optlist" global above.
374 // Forward declare utility functions.
375 bool getConstantStringLength(Value* V, uint64_t& len, ConstantArray** A = 0 );
376 Value *CastToCStr(Value *V, Instruction &IP);
378 /// This LibCallOptimization will find instances of a call to "exit" that occurs
379 /// within the "main" function and change it to a simple "ret" instruction with
380 /// the same value passed to the exit function. When this is done, it splits the
381 /// basic block at the exit(3) call and deletes the call instruction.
382 /// @brief Replace calls to exit in main with a simple return
383 struct ExitInMainOptimization : public LibCallOptimization
385 ExitInMainOptimization() : LibCallOptimization("exit",
386 "Number of 'exit' calls simplified") {}
388 // Make sure the called function looks like exit (int argument, int return
389 // type, external linkage, not varargs).
390 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
392 if (f->arg_size() >= 1)
393 if (f->arg_begin()->getType()->isInteger())
398 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
400 // To be careful, we check that the call to exit is coming from "main", that
401 // main has external linkage, and the return type of main and the argument
402 // to exit have the same type.
403 Function *from = ci->getParent()->getParent();
404 if (from->hasExternalLinkage())
405 if (from->getReturnType() == ci->getOperand(1)->getType())
406 if (from->getName() == "main")
408 // Okay, time to actually do the optimization. First, get the basic
409 // block of the call instruction
410 BasicBlock* bb = ci->getParent();
412 // Create a return instruction that we'll replace the call with.
413 // Note that the argument of the return is the argument of the call
415 ReturnInst* ri = new ReturnInst(ci->getOperand(1), ci);
417 // Split the block at the call instruction which places it in a new
419 bb->splitBasicBlock(ci);
421 // The block split caused a branch instruction to be inserted into
422 // the end of the original block, right after the return instruction
423 // that we put there. That's not a valid block, so delete the branch
425 bb->getInstList().pop_back();
427 // Now we can finally get rid of the call instruction which now lives
428 // in the new basic block.
429 ci->eraseFromParent();
431 // Optimization succeeded, return true.
434 // We didn't pass the criteria for this optimization so return false
437 } ExitInMainOptimizer;
439 /// This LibCallOptimization will simplify a call to the strcat library
440 /// function. The simplification is possible only if the string being
441 /// concatenated is a constant array or a constant expression that results in
442 /// a constant string. In this case we can replace it with strlen + llvm.memcpy
443 /// of the constant string. Both of these calls are further reduced, if possible
444 /// on subsequent passes.
445 /// @brief Simplify the strcat library function.
446 struct StrCatOptimization : public LibCallOptimization
449 /// @brief Default constructor
450 StrCatOptimization() : LibCallOptimization("strcat",
451 "Number of 'strcat' calls simplified") {}
455 /// @brief Make sure that the "strcat" function has the right prototype
456 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
458 if (f->getReturnType() == PointerType::get(Type::SByteTy))
459 if (f->arg_size() == 2)
461 Function::const_arg_iterator AI = f->arg_begin();
462 if (AI++->getType() == PointerType::get(Type::SByteTy))
463 if (AI->getType() == PointerType::get(Type::SByteTy))
465 // Indicate this is a suitable call type.
472 /// @brief Optimize the strcat library function
473 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
475 // Extract some information from the instruction
476 Module* M = ci->getParent()->getParent()->getParent();
477 Value* dest = ci->getOperand(1);
478 Value* src = ci->getOperand(2);
480 // Extract the initializer (while making numerous checks) from the
481 // source operand of the call to strcat. If we get null back, one of
482 // a variety of checks in get_GVInitializer failed
484 if (!getConstantStringLength(src,len))
487 // Handle the simple, do-nothing case
490 ci->replaceAllUsesWith(dest);
491 ci->eraseFromParent();
495 // Increment the length because we actually want to memcpy the null
496 // terminator as well.
499 // We need to find the end of the destination string. That's where the
500 // memory is to be moved to. We just generate a call to strlen (further
501 // optimized in another pass). Note that the SLC.get_strlen() call
502 // caches the Function* for us.
503 CallInst* strlen_inst =
504 new CallInst(SLC.get_strlen(), dest, dest->getName()+".len",ci);
506 // Now that we have the destination's length, we must index into the
507 // destination's pointer to get the actual memcpy destination (end of
508 // the string .. we're concatenating).
509 std::vector<Value*> idx;
510 idx.push_back(strlen_inst);
511 GetElementPtrInst* gep =
512 new GetElementPtrInst(dest,idx,dest->getName()+".indexed",ci);
514 // We have enough information to now generate the memcpy call to
515 // do the concatenation for us.
516 std::vector<Value*> vals;
517 vals.push_back(gep); // destination
518 vals.push_back(ci->getOperand(2)); // source
519 vals.push_back(ConstantUInt::get(Type::UIntTy,len)); // length
520 vals.push_back(ConstantUInt::get(Type::UIntTy,1)); // alignment
521 new CallInst(SLC.get_memcpy(), vals, "", ci);
523 // Finally, substitute the first operand of the strcat call for the
524 // strcat call itself since strcat returns its first operand; and,
525 // kill the strcat CallInst.
526 ci->replaceAllUsesWith(dest);
527 ci->eraseFromParent();
532 /// This LibCallOptimization will simplify a call to the strchr library
533 /// function. It optimizes out cases where the arguments are both constant
534 /// and the result can be determined statically.
535 /// @brief Simplify the strcmp library function.
536 struct StrChrOptimization : public LibCallOptimization
539 StrChrOptimization() : LibCallOptimization("strchr",
540 "Number of 'strchr' calls simplified") {}
542 /// @brief Make sure that the "strchr" function has the right prototype
543 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
545 if (f->getReturnType() == PointerType::get(Type::SByteTy) &&
551 /// @brief Perform the strchr optimizations
552 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
554 // If there aren't three operands, bail
555 if (ci->getNumOperands() != 3)
558 // Check that the first argument to strchr is a constant array of sbyte.
559 // If it is, get the length and data, otherwise return false.
562 if (!getConstantStringLength(ci->getOperand(1),len,&CA))
565 // Check that the second argument to strchr is a constant int, return false
567 ConstantSInt* CSI = dyn_cast<ConstantSInt>(ci->getOperand(2));
570 // Just lower this to memchr since we know the length of the string as
572 Function* f = SLC.get_memchr();
573 std::vector<Value*> args;
574 args.push_back(ci->getOperand(1));
575 args.push_back(ci->getOperand(2));
576 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
577 ci->replaceAllUsesWith( new CallInst(f,args,ci->getName(),ci));
578 ci->eraseFromParent();
582 // Get the character we're looking for
583 int64_t chr = CSI->getValue();
585 // Compute the offset
587 bool char_found = false;
588 for (uint64_t i = 0; i < len; ++i)
590 if (ConstantSInt* CI = dyn_cast<ConstantSInt>(CA->getOperand(i)))
592 // Check for the null terminator
593 if (CI->isNullValue())
594 break; // we found end of string
595 else if (CI->getValue() == chr)
604 // strchr(s,c) -> offset_of_in(c,s)
605 // (if c is a constant integer and s is a constant string)
608 std::vector<Value*> indices;
609 indices.push_back(ConstantUInt::get(Type::ULongTy,offset));
610 GetElementPtrInst* GEP = new GetElementPtrInst(ci->getOperand(1),indices,
611 ci->getOperand(1)->getName()+".strchr",ci);
612 ci->replaceAllUsesWith(GEP);
615 ci->replaceAllUsesWith(
616 ConstantPointerNull::get(PointerType::get(Type::SByteTy)));
618 ci->eraseFromParent();
623 /// This LibCallOptimization will simplify a call to the strcmp library
624 /// function. It optimizes out cases where one or both arguments are constant
625 /// and the result can be determined statically.
626 /// @brief Simplify the strcmp library function.
627 struct StrCmpOptimization : public LibCallOptimization
630 StrCmpOptimization() : LibCallOptimization("strcmp",
631 "Number of 'strcmp' calls simplified") {}
633 /// @brief Make sure that the "strcmp" function has the right prototype
634 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
636 if (f->getReturnType() == Type::IntTy && f->arg_size() == 2)
641 /// @brief Perform the strcmp optimization
642 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
644 // First, check to see if src and destination are the same. If they are,
645 // then the optimization is to replace the CallInst with a constant 0
646 // because the call is a no-op.
647 Value* s1 = ci->getOperand(1);
648 Value* s2 = ci->getOperand(2);
652 ci->replaceAllUsesWith(ConstantInt::get(Type::IntTy,0));
653 ci->eraseFromParent();
657 bool isstr_1 = false;
660 if (getConstantStringLength(s1,len_1,&A1))
665 // strcmp("",x) -> *x
667 new LoadInst(CastToCStr(s2,*ci), ci->getName()+".load",ci);
669 new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
670 ci->replaceAllUsesWith(cast);
671 ci->eraseFromParent();
676 bool isstr_2 = false;
679 if (getConstantStringLength(s2,len_2,&A2))
684 // strcmp(x,"") -> *x
686 new LoadInst(CastToCStr(s1,*ci),ci->getName()+".val",ci);
688 new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
689 ci->replaceAllUsesWith(cast);
690 ci->eraseFromParent();
695 if (isstr_1 && isstr_2)
697 // strcmp(x,y) -> cnst (if both x and y are constant strings)
698 std::string str1 = A1->getAsString();
699 std::string str2 = A2->getAsString();
700 int result = strcmp(str1.c_str(), str2.c_str());
701 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,result));
702 ci->eraseFromParent();
709 /// This LibCallOptimization will simplify a call to the strncmp library
710 /// function. It optimizes out cases where one or both arguments are constant
711 /// and the result can be determined statically.
712 /// @brief Simplify the strncmp library function.
713 struct StrNCmpOptimization : public LibCallOptimization
716 StrNCmpOptimization() : LibCallOptimization("strncmp",
717 "Number of 'strncmp' calls simplified") {}
719 /// @brief Make sure that the "strncmp" function has the right prototype
720 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
722 if (f->getReturnType() == Type::IntTy && f->arg_size() == 3)
727 /// @brief Perform the strncpy optimization
728 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
730 // First, check to see if src and destination are the same. If they are,
731 // then the optimization is to replace the CallInst with a constant 0
732 // because the call is a no-op.
733 Value* s1 = ci->getOperand(1);
734 Value* s2 = ci->getOperand(2);
737 // strncmp(x,x,l) -> 0
738 ci->replaceAllUsesWith(ConstantInt::get(Type::IntTy,0));
739 ci->eraseFromParent();
743 // Check the length argument, if it is Constant zero then the strings are
745 uint64_t len_arg = 0;
746 bool len_arg_is_const = false;
747 if (ConstantInt* len_CI = dyn_cast<ConstantInt>(ci->getOperand(3)))
749 len_arg_is_const = true;
750 len_arg = len_CI->getRawValue();
753 // strncmp(x,y,0) -> 0
754 ci->replaceAllUsesWith(ConstantInt::get(Type::IntTy,0));
755 ci->eraseFromParent();
760 bool isstr_1 = false;
763 if (getConstantStringLength(s1,len_1,&A1))
768 // strncmp("",x) -> *x
769 LoadInst* load = new LoadInst(s1,ci->getName()+".load",ci);
771 new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
772 ci->replaceAllUsesWith(cast);
773 ci->eraseFromParent();
778 bool isstr_2 = false;
781 if (getConstantStringLength(s2,len_2,&A2))
786 // strncmp(x,"") -> *x
787 LoadInst* load = new LoadInst(s2,ci->getName()+".val",ci);
789 new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
790 ci->replaceAllUsesWith(cast);
791 ci->eraseFromParent();
796 if (isstr_1 && isstr_2 && len_arg_is_const)
798 // strncmp(x,y,const) -> constant
799 std::string str1 = A1->getAsString();
800 std::string str2 = A2->getAsString();
801 int result = strncmp(str1.c_str(), str2.c_str(), len_arg);
802 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,result));
803 ci->eraseFromParent();
810 /// This LibCallOptimization will simplify a call to the strcpy library
811 /// function. Two optimizations are possible:
812 /// (1) If src and dest are the same and not volatile, just return dest
813 /// (2) If the src is a constant then we can convert to llvm.memmove
814 /// @brief Simplify the strcpy library function.
815 struct StrCpyOptimization : public LibCallOptimization
818 StrCpyOptimization() : LibCallOptimization("strcpy",
819 "Number of 'strcpy' calls simplified") {}
821 /// @brief Make sure that the "strcpy" function has the right prototype
822 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
824 if (f->getReturnType() == PointerType::get(Type::SByteTy))
825 if (f->arg_size() == 2)
827 Function::const_arg_iterator AI = f->arg_begin();
828 if (AI++->getType() == PointerType::get(Type::SByteTy))
829 if (AI->getType() == PointerType::get(Type::SByteTy))
831 // Indicate this is a suitable call type.
838 /// @brief Perform the strcpy optimization
839 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
841 // First, check to see if src and destination are the same. If they are,
842 // then the optimization is to replace the CallInst with the destination
843 // because the call is a no-op. Note that this corresponds to the
844 // degenerate strcpy(X,X) case which should have "undefined" results
845 // according to the C specification. However, it occurs sometimes and
846 // we optimize it as a no-op.
847 Value* dest = ci->getOperand(1);
848 Value* src = ci->getOperand(2);
851 ci->replaceAllUsesWith(dest);
852 ci->eraseFromParent();
856 // Get the length of the constant string referenced by the second operand,
857 // the "src" parameter. Fail the optimization if we can't get the length
858 // (note that getConstantStringLength does lots of checks to make sure this
861 if (!getConstantStringLength(ci->getOperand(2),len))
864 // If the constant string's length is zero we can optimize this by just
865 // doing a store of 0 at the first byte of the destination
868 new StoreInst(ConstantInt::get(Type::SByteTy,0),ci->getOperand(1),ci);
869 ci->replaceAllUsesWith(dest);
870 ci->eraseFromParent();
874 // Increment the length because we actually want to memcpy the null
875 // terminator as well.
878 // Extract some information from the instruction
879 Module* M = ci->getParent()->getParent()->getParent();
881 // We have enough information to now generate the memcpy call to
882 // do the concatenation for us.
883 std::vector<Value*> vals;
884 vals.push_back(dest); // destination
885 vals.push_back(src); // source
886 vals.push_back(ConstantUInt::get(Type::UIntTy,len)); // length
887 vals.push_back(ConstantUInt::get(Type::UIntTy,1)); // alignment
888 new CallInst(SLC.get_memcpy(), vals, "", ci);
890 // Finally, substitute the first operand of the strcat call for the
891 // strcat call itself since strcat returns its first operand; and,
892 // kill the strcat CallInst.
893 ci->replaceAllUsesWith(dest);
894 ci->eraseFromParent();
899 /// This LibCallOptimization will simplify a call to the strlen library
900 /// function by replacing it with a constant value if the string provided to
901 /// it is a constant array.
902 /// @brief Simplify the strlen library function.
903 struct StrLenOptimization : public LibCallOptimization
905 StrLenOptimization() : LibCallOptimization("strlen",
906 "Number of 'strlen' calls simplified") {}
908 /// @brief Make sure that the "strlen" function has the right prototype
909 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
911 if (f->getReturnType() == SLC.getTargetData()->getIntPtrType())
912 if (f->arg_size() == 1)
913 if (Function::const_arg_iterator AI = f->arg_begin())
914 if (AI->getType() == PointerType::get(Type::SByteTy))
919 /// @brief Perform the strlen optimization
920 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
922 // Make sure we're dealing with an sbyte* here.
923 Value* str = ci->getOperand(1);
924 if (str->getType() != PointerType::get(Type::SByteTy))
927 // Does the call to strlen have exactly one use?
929 // Is that single use a binary operator?
930 if (BinaryOperator* bop = dyn_cast<BinaryOperator>(ci->use_back()))
931 // Is it compared against a constant integer?
932 if (ConstantInt* CI = dyn_cast<ConstantInt>(bop->getOperand(1)))
934 // Get the value the strlen result is compared to
935 uint64_t val = CI->getRawValue();
937 // If its compared against length 0 with == or !=
939 (bop->getOpcode() == Instruction::SetEQ ||
940 bop->getOpcode() == Instruction::SetNE))
942 // strlen(x) != 0 -> *x != 0
943 // strlen(x) == 0 -> *x == 0
944 LoadInst* load = new LoadInst(str,str->getName()+".first",ci);
945 BinaryOperator* rbop = BinaryOperator::create(bop->getOpcode(),
946 load, ConstantSInt::get(Type::SByteTy,0),
947 bop->getName()+".strlen", ci);
948 bop->replaceAllUsesWith(rbop);
949 bop->eraseFromParent();
950 ci->eraseFromParent();
955 // Get the length of the constant string operand
957 if (!getConstantStringLength(ci->getOperand(1),len))
960 // strlen("xyz") -> 3 (for example)
961 const Type *Ty = SLC.getTargetData()->getIntPtrType();
963 ci->replaceAllUsesWith(ConstantSInt::get(Ty, len));
965 ci->replaceAllUsesWith(ConstantUInt::get(Ty, len));
967 ci->eraseFromParent();
972 /// IsOnlyUsedInEqualsComparison - Return true if it only matters that the value
973 /// is equal or not-equal to zero.
974 static bool IsOnlyUsedInEqualsZeroComparison(Instruction *I) {
975 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
977 Instruction *User = cast<Instruction>(*UI);
978 if (User->getOpcode() == Instruction::SetNE ||
979 User->getOpcode() == Instruction::SetEQ) {
980 if (isa<Constant>(User->getOperand(1)) &&
981 cast<Constant>(User->getOperand(1))->isNullValue())
983 } else if (CastInst *CI = dyn_cast<CastInst>(User))
984 if (CI->getType() == Type::BoolTy)
986 // Unknown instruction.
992 /// This memcmpOptimization will simplify a call to the memcmp library
994 struct memcmpOptimization : public LibCallOptimization {
995 /// @brief Default Constructor
997 : LibCallOptimization("memcmp", "Number of 'memcmp' calls simplified") {}
999 /// @brief Make sure that the "memcmp" function has the right prototype
1000 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &TD) {
1001 Function::const_arg_iterator AI = F->arg_begin();
1002 if (F->arg_size() != 3 || !isa<PointerType>(AI->getType())) return false;
1003 if (!isa<PointerType>((++AI)->getType())) return false;
1004 if (!(++AI)->getType()->isInteger()) return false;
1005 if (!F->getReturnType()->isInteger()) return false;
1009 /// Because of alignment and instruction information that we don't have, we
1010 /// leave the bulk of this to the code generators.
1012 /// Note that we could do much more if we could force alignment on otherwise
1013 /// small aligned allocas, or if we could indicate that loads have a small
1015 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &TD) {
1016 Value *LHS = CI->getOperand(1), *RHS = CI->getOperand(2);
1018 // If the two operands are the same, return zero.
1020 // memcmp(s,s,x) -> 0
1021 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
1022 CI->eraseFromParent();
1026 // Make sure we have a constant length.
1027 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getOperand(3));
1028 if (!LenC) return false;
1029 uint64_t Len = LenC->getRawValue();
1031 // If the length is zero, this returns 0.
1034 // memcmp(s1,s2,0) -> 0
1035 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
1036 CI->eraseFromParent();
1039 // memcmp(S1,S2,1) -> *(ubyte*)S1 - *(ubyte*)S2
1040 const Type *UCharPtr = PointerType::get(Type::UByteTy);
1041 CastInst *Op1Cast = new CastInst(LHS, UCharPtr, LHS->getName(), CI);
1042 CastInst *Op2Cast = new CastInst(RHS, UCharPtr, RHS->getName(), CI);
1043 Value *S1V = new LoadInst(Op1Cast, LHS->getName()+".val", CI);
1044 Value *S2V = new LoadInst(Op2Cast, RHS->getName()+".val", CI);
1045 Value *RV = BinaryOperator::createSub(S1V, S2V, CI->getName()+".diff",CI);
1046 if (RV->getType() != CI->getType())
1047 RV = new CastInst(RV, CI->getType(), RV->getName(), CI);
1048 CI->replaceAllUsesWith(RV);
1049 CI->eraseFromParent();
1053 if (IsOnlyUsedInEqualsZeroComparison(CI)) {
1054 // TODO: IF both are aligned, use a short load/compare.
1056 // memcmp(S1,S2,2) -> S1[0]-S2[0] | S1[1]-S2[1] iff only ==/!= 0 matters
1057 const Type *UCharPtr = PointerType::get(Type::UByteTy);
1058 CastInst *Op1Cast = new CastInst(LHS, UCharPtr, LHS->getName(), CI);
1059 CastInst *Op2Cast = new CastInst(RHS, UCharPtr, RHS->getName(), CI);
1060 Value *S1V1 = new LoadInst(Op1Cast, LHS->getName()+".val1", CI);
1061 Value *S2V1 = new LoadInst(Op2Cast, RHS->getName()+".val1", CI);
1062 Value *D1 = BinaryOperator::createSub(S1V1, S2V1,
1063 CI->getName()+".d1", CI);
1064 Constant *One = ConstantInt::get(Type::IntTy, 1);
1065 Value *G1 = new GetElementPtrInst(Op1Cast, One, "next1v", CI);
1066 Value *G2 = new GetElementPtrInst(Op2Cast, One, "next2v", CI);
1067 Value *S1V2 = new LoadInst(G1, LHS->getName()+".val2", CI);
1068 Value *S2V2 = new LoadInst(G1, RHS->getName()+".val2", CI);
1069 Value *D2 = BinaryOperator::createSub(S1V2, S2V2,
1070 CI->getName()+".d1", CI);
1071 Value *Or = BinaryOperator::createOr(D1, D2, CI->getName()+".res", CI);
1072 if (Or->getType() != CI->getType())
1073 Or = new CastInst(Or, CI->getType(), Or->getName(), CI);
1074 CI->replaceAllUsesWith(Or);
1075 CI->eraseFromParent();
1093 /// This LibCallOptimization will simplify a call to the memcpy library
1094 /// function by expanding it out to a single store of size 0, 1, 2, 4, or 8
1095 /// bytes depending on the length of the string and the alignment. Additional
1096 /// optimizations are possible in code generation (sequence of immediate store)
1097 /// @brief Simplify the memcpy library function.
1098 struct LLVMMemCpyOptimization : public LibCallOptimization
1100 /// @brief Default Constructor
1101 LLVMMemCpyOptimization() : LibCallOptimization("llvm.memcpy",
1102 "Number of 'llvm.memcpy' calls simplified") {}
1105 /// @brief Subclass Constructor
1106 LLVMMemCpyOptimization(const char* fname, const char* desc)
1107 : LibCallOptimization(fname, desc) {}
1110 /// @brief Make sure that the "memcpy" function has the right prototype
1111 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& TD)
1113 // Just make sure this has 4 arguments per LLVM spec.
1114 return (f->arg_size() == 4);
1117 /// Because of alignment and instruction information that we don't have, we
1118 /// leave the bulk of this to the code generators. The optimization here just
1119 /// deals with a few degenerate cases where the length of the string and the
1120 /// alignment match the sizes of our intrinsic types so we can do a load and
1121 /// store instead of the memcpy call.
1122 /// @brief Perform the memcpy optimization.
1123 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& TD)
1125 // Make sure we have constant int values to work with
1126 ConstantInt* LEN = dyn_cast<ConstantInt>(ci->getOperand(3));
1129 ConstantInt* ALIGN = dyn_cast<ConstantInt>(ci->getOperand(4));
1133 // If the length is larger than the alignment, we can't optimize
1134 uint64_t len = LEN->getRawValue();
1135 uint64_t alignment = ALIGN->getRawValue();
1137 alignment = 1; // Alignment 0 is identity for alignment 1
1138 if (len > alignment)
1141 // Get the type we will cast to, based on size of the string
1142 Value* dest = ci->getOperand(1);
1143 Value* src = ci->getOperand(2);
1148 // memcpy(d,s,0,a) -> noop
1149 ci->eraseFromParent();
1151 case 1: castType = Type::SByteTy; break;
1152 case 2: castType = Type::ShortTy; break;
1153 case 4: castType = Type::IntTy; break;
1154 case 8: castType = Type::LongTy; break;
1159 // Cast source and dest to the right sized primitive and then load/store
1161 new CastInst(src,PointerType::get(castType),src->getName()+".cast",ci);
1162 CastInst* DestCast =
1163 new CastInst(dest,PointerType::get(castType),dest->getName()+".cast",ci);
1164 LoadInst* LI = new LoadInst(SrcCast,SrcCast->getName()+".val",ci);
1165 StoreInst* SI = new StoreInst(LI, DestCast, ci);
1166 ci->eraseFromParent();
1169 } LLVMMemCpyOptimizer;
1171 /// This LibCallOptimization will simplify a call to the memmove library
1172 /// function. It is identical to MemCopyOptimization except for the name of
1174 /// @brief Simplify the memmove library function.
1175 struct LLVMMemMoveOptimization : public LLVMMemCpyOptimization
1177 /// @brief Default Constructor
1178 LLVMMemMoveOptimization() : LLVMMemCpyOptimization("llvm.memmove",
1179 "Number of 'llvm.memmove' calls simplified") {}
1181 } LLVMMemMoveOptimizer;
1183 /// This LibCallOptimization will simplify a call to the memset library
1184 /// function by expanding it out to a single store of size 0, 1, 2, 4, or 8
1185 /// bytes depending on the length argument.
1186 struct LLVMMemSetOptimization : public LibCallOptimization
1188 /// @brief Default Constructor
1189 LLVMMemSetOptimization() : LibCallOptimization("llvm.memset",
1190 "Number of 'llvm.memset' calls simplified") {}
1194 /// @brief Make sure that the "memset" function has the right prototype
1195 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& TD)
1197 // Just make sure this has 3 arguments per LLVM spec.
1198 return (f->arg_size() == 4);
1201 /// Because of alignment and instruction information that we don't have, we
1202 /// leave the bulk of this to the code generators. The optimization here just
1203 /// deals with a few degenerate cases where the length parameter is constant
1204 /// and the alignment matches the sizes of our intrinsic types so we can do
1205 /// store instead of the memcpy call. Other calls are transformed into the
1206 /// llvm.memset intrinsic.
1207 /// @brief Perform the memset optimization.
1208 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& TD)
1210 // Make sure we have constant int values to work with
1211 ConstantInt* LEN = dyn_cast<ConstantInt>(ci->getOperand(3));
1214 ConstantInt* ALIGN = dyn_cast<ConstantInt>(ci->getOperand(4));
1218 // Extract the length and alignment
1219 uint64_t len = LEN->getRawValue();
1220 uint64_t alignment = ALIGN->getRawValue();
1222 // Alignment 0 is identity for alignment 1
1226 // If the length is zero, this is a no-op
1229 // memset(d,c,0,a) -> noop
1230 ci->eraseFromParent();
1234 // If the length is larger than the alignment, we can't optimize
1235 if (len > alignment)
1238 // Make sure we have a constant ubyte to work with so we can extract
1239 // the value to be filled.
1240 ConstantUInt* FILL = dyn_cast<ConstantUInt>(ci->getOperand(2));
1243 if (FILL->getType() != Type::UByteTy)
1246 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
1248 // Extract the fill character
1249 uint64_t fill_char = FILL->getValue();
1250 uint64_t fill_value = fill_char;
1252 // Get the type we will cast to, based on size of memory area to fill, and
1253 // and the value we will store there.
1254 Value* dest = ci->getOperand(1);
1259 castType = Type::UByteTy;
1262 castType = Type::UShortTy;
1263 fill_value |= fill_char << 8;
1266 castType = Type::UIntTy;
1267 fill_value |= fill_char << 8 | fill_char << 16 | fill_char << 24;
1270 castType = Type::ULongTy;
1271 fill_value |= fill_char << 8 | fill_char << 16 | fill_char << 24;
1272 fill_value |= fill_char << 32 | fill_char << 40 | fill_char << 48;
1273 fill_value |= fill_char << 56;
1279 // Cast dest to the right sized primitive and then load/store
1280 CastInst* DestCast =
1281 new CastInst(dest,PointerType::get(castType),dest->getName()+".cast",ci);
1282 new StoreInst(ConstantUInt::get(castType,fill_value),DestCast, ci);
1283 ci->eraseFromParent();
1286 } LLVMMemSetOptimizer;
1288 /// This LibCallOptimization will simplify calls to the "pow" library
1289 /// function. It looks for cases where the result of pow is well known and
1290 /// substitutes the appropriate value.
1291 /// @brief Simplify the pow library function.
1292 struct PowOptimization : public LibCallOptimization
1295 /// @brief Default Constructor
1296 PowOptimization() : LibCallOptimization("pow",
1297 "Number of 'pow' calls simplified") {}
1299 /// @brief Make sure that the "pow" function has the right prototype
1300 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1302 // Just make sure this has 2 arguments
1303 return (f->arg_size() == 2);
1306 /// @brief Perform the pow optimization.
1307 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1309 const Type *Ty = cast<Function>(ci->getOperand(0))->getReturnType();
1310 Value* base = ci->getOperand(1);
1311 Value* expn = ci->getOperand(2);
1312 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(base)) {
1313 double Op1V = Op1->getValue();
1316 // pow(1.0,x) -> 1.0
1317 ci->replaceAllUsesWith(ConstantFP::get(Ty,1.0));
1318 ci->eraseFromParent();
1322 else if (ConstantFP* Op2 = dyn_cast<ConstantFP>(expn))
1324 double Op2V = Op2->getValue();
1327 // pow(x,0.0) -> 1.0
1328 ci->replaceAllUsesWith(ConstantFP::get(Ty,1.0));
1329 ci->eraseFromParent();
1332 else if (Op2V == 0.5)
1334 // pow(x,0.5) -> sqrt(x)
1335 CallInst* sqrt_inst = new CallInst(SLC.get_sqrt(), base,
1336 ci->getName()+".pow",ci);
1337 ci->replaceAllUsesWith(sqrt_inst);
1338 ci->eraseFromParent();
1341 else if (Op2V == 1.0)
1344 ci->replaceAllUsesWith(base);
1345 ci->eraseFromParent();
1348 else if (Op2V == -1.0)
1350 // pow(x,-1.0) -> 1.0/x
1351 BinaryOperator* div_inst= BinaryOperator::createDiv(
1352 ConstantFP::get(Ty,1.0), base, ci->getName()+".pow", ci);
1353 ci->replaceAllUsesWith(div_inst);
1354 ci->eraseFromParent();
1358 return false; // opt failed
1362 /// This LibCallOptimization will simplify calls to the "fprintf" library
1363 /// function. It looks for cases where the result of fprintf is not used and the
1364 /// operation can be reduced to something simpler.
1365 /// @brief Simplify the pow library function.
1366 struct FPrintFOptimization : public LibCallOptimization
1369 /// @brief Default Constructor
1370 FPrintFOptimization() : LibCallOptimization("fprintf",
1371 "Number of 'fprintf' calls simplified") {}
1373 /// @brief Make sure that the "fprintf" function has the right prototype
1374 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1376 // Just make sure this has at least 2 arguments
1377 return (f->arg_size() >= 2);
1380 /// @brief Perform the fprintf optimization.
1381 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1383 // If the call has more than 3 operands, we can't optimize it
1384 if (ci->getNumOperands() > 4 || ci->getNumOperands() <= 2)
1387 // If the result of the fprintf call is used, none of these optimizations
1389 if (!ci->use_empty())
1392 // All the optimizations depend on the length of the second argument and the
1393 // fact that it is a constant string array. Check that now
1395 ConstantArray* CA = 0;
1396 if (!getConstantStringLength(ci->getOperand(2), len, &CA))
1399 if (ci->getNumOperands() == 3)
1401 // Make sure there's no % in the constant array
1402 for (unsigned i = 0; i < len; ++i)
1404 if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(i)))
1406 // Check for the null terminator
1407 if (CI->getRawValue() == '%')
1408 return false; // we found end of string
1414 // fprintf(file,fmt) -> fwrite(fmt,strlen(fmt),file)
1415 const Type* FILEptr_type = ci->getOperand(1)->getType();
1416 Function* fwrite_func = SLC.get_fwrite(FILEptr_type);
1420 // Make sure that the fprintf() and fwrite() functions both take the
1421 // same type of char pointer.
1422 if (ci->getOperand(2)->getType() !=
1423 fwrite_func->getFunctionType()->getParamType(0))
1426 std::vector<Value*> args;
1427 args.push_back(ci->getOperand(2));
1428 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
1429 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),1));
1430 args.push_back(ci->getOperand(1));
1431 new CallInst(fwrite_func,args,ci->getName(),ci);
1432 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,len));
1433 ci->eraseFromParent();
1437 // The remaining optimizations require the format string to be length 2
1442 // The first character has to be a %
1443 if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(0)))
1444 if (CI->getRawValue() != '%')
1447 // Get the second character and switch on its value
1448 ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(1));
1449 switch (CI->getRawValue())
1454 ConstantArray* CA = 0;
1455 if (!getConstantStringLength(ci->getOperand(3), len, &CA))
1458 // fprintf(file,"%s",str) -> fwrite(fmt,strlen(fmt),1,file)
1459 const Type* FILEptr_type = ci->getOperand(1)->getType();
1460 Function* fwrite_func = SLC.get_fwrite(FILEptr_type);
1463 std::vector<Value*> args;
1464 args.push_back(CastToCStr(ci->getOperand(3), *ci));
1465 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
1466 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),1));
1467 args.push_back(ci->getOperand(1));
1468 new CallInst(fwrite_func,args,ci->getName(),ci);
1469 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,len));
1474 ConstantInt* CI = dyn_cast<ConstantInt>(ci->getOperand(3));
1478 const Type* FILEptr_type = ci->getOperand(1)->getType();
1479 Function* fputc_func = SLC.get_fputc(FILEptr_type);
1482 CastInst* cast = new CastInst(CI,Type::IntTy,CI->getName()+".int",ci);
1483 new CallInst(fputc_func,cast,ci->getOperand(1),"",ci);
1484 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,1));
1490 ci->eraseFromParent();
1495 /// This LibCallOptimization will simplify calls to the "sprintf" library
1496 /// function. It looks for cases where the result of sprintf is not used and the
1497 /// operation can be reduced to something simpler.
1498 /// @brief Simplify the pow library function.
1499 struct SPrintFOptimization : public LibCallOptimization
1502 /// @brief Default Constructor
1503 SPrintFOptimization() : LibCallOptimization("sprintf",
1504 "Number of 'sprintf' calls simplified") {}
1506 /// @brief Make sure that the "fprintf" function has the right prototype
1507 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1509 // Just make sure this has at least 2 arguments
1510 return (f->getReturnType() == Type::IntTy && f->arg_size() >= 2);
1513 /// @brief Perform the sprintf optimization.
1514 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1516 // If the call has more than 3 operands, we can't optimize it
1517 if (ci->getNumOperands() > 4 || ci->getNumOperands() < 3)
1520 // All the optimizations depend on the length of the second argument and the
1521 // fact that it is a constant string array. Check that now
1523 ConstantArray* CA = 0;
1524 if (!getConstantStringLength(ci->getOperand(2), len, &CA))
1527 if (ci->getNumOperands() == 3)
1531 // If the length is 0, we just need to store a null byte
1532 new StoreInst(ConstantInt::get(Type::SByteTy,0),ci->getOperand(1),ci);
1533 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,0));
1534 ci->eraseFromParent();
1538 // Make sure there's no % in the constant array
1539 for (unsigned i = 0; i < len; ++i)
1541 if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(i)))
1543 // Check for the null terminator
1544 if (CI->getRawValue() == '%')
1545 return false; // we found a %, can't optimize
1548 return false; // initializer is not constant int, can't optimize
1551 // Increment length because we want to copy the null byte too
1554 // sprintf(str,fmt) -> llvm.memcpy(str,fmt,strlen(fmt),1)
1555 Function* memcpy_func = SLC.get_memcpy();
1558 std::vector<Value*> args;
1559 args.push_back(ci->getOperand(1));
1560 args.push_back(ci->getOperand(2));
1561 args.push_back(ConstantUInt::get(Type::UIntTy,len));
1562 args.push_back(ConstantUInt::get(Type::UIntTy,1));
1563 new CallInst(memcpy_func,args,"",ci);
1564 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,len));
1565 ci->eraseFromParent();
1569 // The remaining optimizations require the format string to be length 2
1574 // The first character has to be a %
1575 if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(0)))
1576 if (CI->getRawValue() != '%')
1579 // Get the second character and switch on its value
1580 ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(1));
1581 switch (CI->getRawValue()) {
1583 // sprintf(dest,"%s",str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1584 Function* strlen_func = SLC.get_strlen();
1585 Function* memcpy_func = SLC.get_memcpy();
1586 if (!strlen_func || !memcpy_func)
1589 Value *Len = new CallInst(strlen_func, CastToCStr(ci->getOperand(3), *ci),
1590 ci->getOperand(3)->getName()+".len", ci);
1591 Value *Len1 = BinaryOperator::createAdd(Len,
1592 ConstantInt::get(Len->getType(), 1),
1593 Len->getName()+"1", ci);
1594 if (Len1->getType() != Type::UIntTy)
1595 Len1 = new CastInst(Len1, Type::UIntTy, Len1->getName(), ci);
1596 std::vector<Value*> args;
1597 args.push_back(CastToCStr(ci->getOperand(1), *ci));
1598 args.push_back(CastToCStr(ci->getOperand(3), *ci));
1599 args.push_back(Len1);
1600 args.push_back(ConstantUInt::get(Type::UIntTy,1));
1601 new CallInst(memcpy_func, args, "", ci);
1603 // The strlen result is the unincremented number of bytes in the string.
1604 if (!ci->use_empty()) {
1605 if (Len->getType() != ci->getType())
1606 Len = new CastInst(Len, ci->getType(), Len->getName(), ci);
1607 ci->replaceAllUsesWith(Len);
1609 ci->eraseFromParent();
1613 // sprintf(dest,"%c",chr) -> store chr, dest
1614 CastInst* cast = new CastInst(ci->getOperand(3),Type::SByteTy,"char",ci);
1615 new StoreInst(cast, ci->getOperand(1), ci);
1616 GetElementPtrInst* gep = new GetElementPtrInst(ci->getOperand(1),
1617 ConstantUInt::get(Type::UIntTy,1),ci->getOperand(1)->getName()+".end",
1619 new StoreInst(ConstantInt::get(Type::SByteTy,0),gep,ci);
1620 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,1));
1621 ci->eraseFromParent();
1629 /// This LibCallOptimization will simplify calls to the "fputs" library
1630 /// function. It looks for cases where the result of fputs is not used and the
1631 /// operation can be reduced to something simpler.
1632 /// @brief Simplify the pow library function.
1633 struct PutsOptimization : public LibCallOptimization
1636 /// @brief Default Constructor
1637 PutsOptimization() : LibCallOptimization("fputs",
1638 "Number of 'fputs' calls simplified") {}
1640 /// @brief Make sure that the "fputs" function has the right prototype
1641 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1643 // Just make sure this has 2 arguments
1644 return (f->arg_size() == 2);
1647 /// @brief Perform the fputs optimization.
1648 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1650 // If the result is used, none of these optimizations work
1651 if (!ci->use_empty())
1654 // All the optimizations depend on the length of the first argument and the
1655 // fact that it is a constant string array. Check that now
1657 if (!getConstantStringLength(ci->getOperand(1), len))
1663 // fputs("",F) -> noop
1667 // fputs(s,F) -> fputc(s[0],F) (if s is constant and strlen(s) == 1)
1668 const Type* FILEptr_type = ci->getOperand(2)->getType();
1669 Function* fputc_func = SLC.get_fputc(FILEptr_type);
1672 LoadInst* loadi = new LoadInst(ci->getOperand(1),
1673 ci->getOperand(1)->getName()+".byte",ci);
1674 CastInst* casti = new CastInst(loadi,Type::IntTy,
1675 loadi->getName()+".int",ci);
1676 new CallInst(fputc_func,casti,ci->getOperand(2),"",ci);
1681 // fputs(s,F) -> fwrite(s,1,len,F) (if s is constant and strlen(s) > 1)
1682 const Type* FILEptr_type = ci->getOperand(2)->getType();
1683 Function* fwrite_func = SLC.get_fwrite(FILEptr_type);
1686 std::vector<Value*> parms;
1687 parms.push_back(ci->getOperand(1));
1688 parms.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
1689 parms.push_back(ConstantUInt::get(SLC.getIntPtrType(),1));
1690 parms.push_back(ci->getOperand(2));
1691 new CallInst(fwrite_func,parms,"",ci);
1695 ci->eraseFromParent();
1696 return true; // success
1700 /// This LibCallOptimization will simplify calls to the "isdigit" library
1701 /// function. It simply does range checks the parameter explicitly.
1702 /// @brief Simplify the isdigit library function.
1703 struct isdigitOptimization : public LibCallOptimization {
1705 isdigitOptimization() : LibCallOptimization("isdigit",
1706 "Number of 'isdigit' calls simplified") {}
1708 /// @brief Make sure that the "isdigit" function has the right prototype
1709 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1711 // Just make sure this has 1 argument
1712 return (f->arg_size() == 1);
1715 /// @brief Perform the toascii optimization.
1716 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1718 if (ConstantInt* CI = dyn_cast<ConstantInt>(ci->getOperand(1)))
1720 // isdigit(c) -> 0 or 1, if 'c' is constant
1721 uint64_t val = CI->getRawValue();
1722 if (val >= '0' && val <='9')
1723 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,1));
1725 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,0));
1726 ci->eraseFromParent();
1730 // isdigit(c) -> (unsigned)c - '0' <= 9
1732 new CastInst(ci->getOperand(1),Type::UIntTy,
1733 ci->getOperand(1)->getName()+".uint",ci);
1734 BinaryOperator* sub_inst = BinaryOperator::createSub(cast,
1735 ConstantUInt::get(Type::UIntTy,0x30),
1736 ci->getOperand(1)->getName()+".sub",ci);
1737 SetCondInst* setcond_inst = new SetCondInst(Instruction::SetLE,sub_inst,
1738 ConstantUInt::get(Type::UIntTy,9),
1739 ci->getOperand(1)->getName()+".cmp",ci);
1741 new CastInst(setcond_inst,Type::IntTy,
1742 ci->getOperand(1)->getName()+".isdigit",ci);
1743 ci->replaceAllUsesWith(c2);
1744 ci->eraseFromParent();
1749 struct isasciiOptimization : public LibCallOptimization {
1751 isasciiOptimization()
1752 : LibCallOptimization("isascii", "Number of 'isascii' calls simplified") {}
1754 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
1755 return F->arg_size() == 1 && F->arg_begin()->getType()->isInteger() &&
1756 F->getReturnType()->isInteger();
1759 /// @brief Perform the isascii optimization.
1760 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1761 // isascii(c) -> (unsigned)c < 128
1762 Value *V = CI->getOperand(1);
1763 if (V->getType()->isSigned())
1764 V = new CastInst(V, V->getType()->getUnsignedVersion(), V->getName(), CI);
1765 Value *Cmp = BinaryOperator::createSetLT(V, ConstantUInt::get(V->getType(),
1767 V->getName()+".isascii", CI);
1768 if (Cmp->getType() != CI->getType())
1769 Cmp = new CastInst(Cmp, CI->getType(), Cmp->getName(), CI);
1770 CI->replaceAllUsesWith(Cmp);
1771 CI->eraseFromParent();
1777 /// This LibCallOptimization will simplify calls to the "toascii" library
1778 /// function. It simply does the corresponding and operation to restrict the
1779 /// range of values to the ASCII character set (0-127).
1780 /// @brief Simplify the toascii library function.
1781 struct ToAsciiOptimization : public LibCallOptimization
1784 /// @brief Default Constructor
1785 ToAsciiOptimization() : LibCallOptimization("toascii",
1786 "Number of 'toascii' calls simplified") {}
1788 /// @brief Make sure that the "fputs" function has the right prototype
1789 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1791 // Just make sure this has 2 arguments
1792 return (f->arg_size() == 1);
1795 /// @brief Perform the toascii optimization.
1796 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1798 // toascii(c) -> (c & 0x7f)
1799 Value* chr = ci->getOperand(1);
1800 BinaryOperator* and_inst = BinaryOperator::createAnd(chr,
1801 ConstantInt::get(chr->getType(),0x7F),ci->getName()+".toascii",ci);
1802 ci->replaceAllUsesWith(and_inst);
1803 ci->eraseFromParent();
1808 /// This LibCallOptimization will simplify calls to the "ffs" library
1809 /// calls which find the first set bit in an int, long, or long long. The
1810 /// optimization is to compute the result at compile time if the argument is
1812 /// @brief Simplify the ffs library function.
1813 struct FFSOptimization : public LibCallOptimization
1816 /// @brief Subclass Constructor
1817 FFSOptimization(const char* funcName, const char* description)
1818 : LibCallOptimization(funcName, description)
1822 /// @brief Default Constructor
1823 FFSOptimization() : LibCallOptimization("ffs",
1824 "Number of 'ffs' calls simplified") {}
1826 /// @brief Make sure that the "fputs" function has the right prototype
1827 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1829 // Just make sure this has 2 arguments
1830 return (f->arg_size() == 1 && f->getReturnType() == Type::IntTy);
1833 /// @brief Perform the ffs optimization.
1834 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1836 if (ConstantInt* CI = dyn_cast<ConstantInt>(ci->getOperand(1)))
1838 // ffs(cnst) -> bit#
1839 // ffsl(cnst) -> bit#
1840 // ffsll(cnst) -> bit#
1841 uint64_t val = CI->getRawValue();
1849 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy, result));
1850 ci->eraseFromParent();
1854 // ffs(x) -> ( x == 0 ? 0 : llvm.cttz(x)+1)
1855 // ffsl(x) -> ( x == 0 ? 0 : llvm.cttz(x)+1)
1856 // ffsll(x) -> ( x == 0 ? 0 : llvm.cttz(x)+1)
1857 const Type* arg_type = ci->getOperand(1)->getType();
1858 std::vector<const Type*> args;
1859 args.push_back(arg_type);
1860 FunctionType* llvm_cttz_type = FunctionType::get(arg_type,args,false);
1862 SLC.getModule()->getOrInsertFunction("llvm.cttz",llvm_cttz_type);
1863 std::string inst_name(ci->getName()+".ffs");
1865 new CallInst(F, ci->getOperand(1), inst_name, ci);
1866 if (arg_type != Type::IntTy)
1867 call = new CastInst(call, Type::IntTy, inst_name, ci);
1868 BinaryOperator* add = BinaryOperator::createAdd(call,
1869 ConstantSInt::get(Type::IntTy,1), inst_name, ci);
1870 SetCondInst* eq = new SetCondInst(Instruction::SetEQ,ci->getOperand(1),
1871 ConstantSInt::get(ci->getOperand(1)->getType(),0),inst_name,ci);
1872 SelectInst* select = new SelectInst(eq,ConstantSInt::get(Type::IntTy,0),add,
1874 ci->replaceAllUsesWith(select);
1875 ci->eraseFromParent();
1880 /// This LibCallOptimization will simplify calls to the "ffsl" library
1881 /// calls. It simply uses FFSOptimization for which the transformation is
1883 /// @brief Simplify the ffsl library function.
1884 struct FFSLOptimization : public FFSOptimization
1887 /// @brief Default Constructor
1888 FFSLOptimization() : FFSOptimization("ffsl",
1889 "Number of 'ffsl' calls simplified") {}
1893 /// This LibCallOptimization will simplify calls to the "ffsll" library
1894 /// calls. It simply uses FFSOptimization for which the transformation is
1896 /// @brief Simplify the ffsl library function.
1897 struct FFSLLOptimization : public FFSOptimization
1900 /// @brief Default Constructor
1901 FFSLLOptimization() : FFSOptimization("ffsll",
1902 "Number of 'ffsll' calls simplified") {}
1907 /// This LibCallOptimization will simplify calls to the "floor" library
1909 /// @brief Simplify the floor library function.
1910 struct FloorOptimization : public LibCallOptimization {
1912 : LibCallOptimization("floor", "Number of 'floor' calls simplified") {}
1914 /// @brief Make sure that the "floor" function has the right prototype
1915 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
1916 return F->arg_size() == 1 && F->arg_begin()->getType() == Type::DoubleTy &&
1917 F->getReturnType() == Type::DoubleTy;
1920 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1921 // If this is a float argument passed in, convert to floorf.
1922 // e.g. floor((double)FLT) -> (double)floorf(FLT). There can be no loss of
1923 // precision due to this.
1924 if (CastInst *Cast = dyn_cast<CastInst>(CI->getOperand(1)))
1925 if (Cast->getOperand(0)->getType() == Type::FloatTy) {
1926 Value *New = new CallInst(SLC.get_floorf(), Cast->getOperand(0),
1928 New = new CastInst(New, Type::DoubleTy, CI->getName(), CI);
1929 CI->replaceAllUsesWith(New);
1930 CI->eraseFromParent();
1931 if (Cast->use_empty())
1932 Cast->eraseFromParent();
1935 return false; // opt failed
1941 /// A function to compute the length of a null-terminated constant array of
1942 /// integers. This function can't rely on the size of the constant array
1943 /// because there could be a null terminator in the middle of the array.
1944 /// We also have to bail out if we find a non-integer constant initializer
1945 /// of one of the elements or if there is no null-terminator. The logic
1946 /// below checks each of these conditions and will return true only if all
1947 /// conditions are met. In that case, the \p len parameter is set to the length
1948 /// of the null-terminated string. If false is returned, the conditions were
1949 /// not met and len is set to 0.
1950 /// @brief Get the length of a constant string (null-terminated array).
1951 bool getConstantStringLength(Value* V, uint64_t& len, ConstantArray** CA )
1953 assert(V != 0 && "Invalid args to getConstantStringLength");
1954 len = 0; // make sure we initialize this
1956 // If the value is not a GEP instruction nor a constant expression with a
1957 // GEP instruction, then return false because ConstantArray can't occur
1959 if (GetElementPtrInst* GEPI = dyn_cast<GetElementPtrInst>(V))
1961 else if (ConstantExpr* CE = dyn_cast<ConstantExpr>(V))
1962 if (CE->getOpcode() == Instruction::GetElementPtr)
1969 // Make sure the GEP has exactly three arguments.
1970 if (GEP->getNumOperands() != 3)
1973 // Check to make sure that the first operand of the GEP is an integer and
1974 // has value 0 so that we are sure we're indexing into the initializer.
1975 if (ConstantInt* op1 = dyn_cast<ConstantInt>(GEP->getOperand(1)))
1977 if (!op1->isNullValue())
1983 // Ensure that the second operand is a ConstantInt. If it isn't then this
1984 // GEP is wonky and we're not really sure what were referencing into and
1985 // better of not optimizing it. While we're at it, get the second index
1986 // value. We'll need this later for indexing the ConstantArray.
1987 uint64_t start_idx = 0;
1988 if (ConstantInt* CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
1989 start_idx = CI->getRawValue();
1993 // The GEP instruction, constant or instruction, must reference a global
1994 // variable that is a constant and is initialized. The referenced constant
1995 // initializer is the array that we'll use for optimization.
1996 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1997 if (!GV || !GV->isConstant() || !GV->hasInitializer())
2000 // Get the initializer.
2001 Constant* INTLZR = GV->getInitializer();
2003 // Handle the ConstantAggregateZero case
2004 if (ConstantAggregateZero* CAZ = dyn_cast<ConstantAggregateZero>(INTLZR))
2006 // This is a degenerate case. The initializer is constant zero so the
2007 // length of the string must be zero.
2012 // Must be a Constant Array
2013 ConstantArray* A = dyn_cast<ConstantArray>(INTLZR);
2017 // Get the number of elements in the array
2018 uint64_t max_elems = A->getType()->getNumElements();
2020 // Traverse the constant array from start_idx (derived above) which is
2021 // the place the GEP refers to in the array.
2022 for ( len = start_idx; len < max_elems; len++)
2024 if (ConstantInt* CI = dyn_cast<ConstantInt>(A->getOperand(len)))
2026 // Check for the null terminator
2027 if (CI->isNullValue())
2028 break; // we found end of string
2031 return false; // This array isn't suitable, non-int initializer
2033 if (len >= max_elems)
2034 return false; // This array isn't null terminated
2036 // Subtract out the initial value from the length
2040 return true; // success!
2043 /// CastToCStr - Return V if it is an sbyte*, otherwise cast it to sbyte*,
2044 /// inserting the cast before IP, and return the cast.
2045 /// @brief Cast a value to a "C" string.
2046 Value *CastToCStr(Value *V, Instruction &IP) {
2047 const Type *SBPTy = PointerType::get(Type::SByteTy);
2048 if (V->getType() != SBPTy)
2049 return new CastInst(V, SBPTy, V->getName(), &IP);
2054 // Additional cases that we need to add to this file:
2057 // * cbrt(expN(X)) -> expN(x/3)
2058 // * cbrt(sqrt(x)) -> pow(x,1/6)
2059 // * cbrt(sqrt(x)) -> pow(x,1/9)
2062 // * cos(-x) -> cos(x)
2065 // * exp(log(x)) -> x
2068 // * log(exp(x)) -> x
2069 // * log(x**y) -> y*log(x)
2070 // * log(exp(y)) -> y*log(e)
2071 // * log(exp2(y)) -> y*log(2)
2072 // * log(exp10(y)) -> y*log(10)
2073 // * log(sqrt(x)) -> 0.5*log(x)
2074 // * log(pow(x,y)) -> y*log(x)
2076 // lround, lroundf, lroundl:
2077 // * lround(cnst) -> cnst'
2080 // * memcmp(x,y,l) -> cnst
2081 // (if all arguments are constant and strlen(x) <= l and strlen(y) <= l)
2084 // * memmove(d,s,l,a) -> memcpy(d,s,l,a)
2085 // (if s is a global constant array)
2088 // * pow(exp(x),y) -> exp(x*y)
2089 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2090 // * pow(pow(x,y),z)-> pow(x,y*z)
2093 // * puts("") -> fputc("\n",stdout) (how do we get "stdout"?)
2095 // round, roundf, roundl:
2096 // * round(cnst) -> cnst'
2099 // * signbit(cnst) -> cnst'
2100 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2102 // sqrt, sqrtf, sqrtl:
2103 // * sqrt(expN(x)) -> expN(x*0.5)
2104 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2105 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2108 // * stpcpy(str, "literal") ->
2109 // llvm.memcpy(str,"literal",strlen("literal")+1,1)
2111 // * strrchr(s,c) -> reverse_offset_of_in(c,s)
2112 // (if c is a constant integer and s is a constant string)
2113 // * strrchr(s1,0) -> strchr(s1,0)
2116 // * strncat(x,y,0) -> x
2117 // * strncat(x,y,0) -> x (if strlen(y) = 0)
2118 // * strncat(x,y,l) -> strcat(x,y) (if y and l are constants an l > strlen(y))
2121 // * strncpy(d,s,0) -> d
2122 // * strncpy(d,s,l) -> memcpy(d,s,l,1)
2123 // (if s and l are constants)
2126 // * strpbrk(s,a) -> offset_in_for(s,a)
2127 // (if s and a are both constant strings)
2128 // * strpbrk(s,"") -> 0
2129 // * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
2132 // * strspn(s,a) -> const_int (if both args are constant)
2133 // * strspn("",a) -> 0
2134 // * strspn(s,"") -> 0
2135 // * strcspn(s,a) -> const_int (if both args are constant)
2136 // * strcspn("",a) -> 0
2137 // * strcspn(s,"") -> strlen(a)
2140 // * strstr(x,x) -> x
2141 // * strstr(s1,s2) -> offset_of_s2_in(s1)
2142 // (if s1 and s2 are constant strings)
2145 // * tan(atan(x)) -> x
2147 // trunc, truncf, truncl:
2148 // * trunc(cnst) -> cnst'