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 )
71 , stat_name(std::string("simplify-libcalls:")+fname)
72 , stat_desc(std::string("Number of ")+fname+"(...) calls simplified")
73 , occurrences(stat_name.c_str(),stat_desc.c_str())
76 // Register this call optimizer in the optlist (a hash_map)
77 optlist[func_name] = this;
80 /// @brief Deregister from the optlist
81 virtual ~LibCallOptimization() { optlist.erase(func_name); }
83 /// The implementation of this function in subclasses should determine if
84 /// \p F is suitable for the optimization. This method is called by
85 /// SimplifyLibCalls::runOnModule to short circuit visiting all the call
86 /// sites of such a function if that function is not suitable in the first
87 /// place. If the called function is suitabe, this method should return true;
88 /// false, otherwise. This function should also perform any lazy
89 /// initialization that the LibCallOptimization needs to do, if its to return
90 /// true. This avoids doing initialization until the optimizer is actually
91 /// going to be called upon to do some optimization.
92 /// @brief Determine if the function is suitable for optimization
93 virtual bool ValidateCalledFunction(
94 const Function* F, ///< The function that is the target of call sites
95 SimplifyLibCalls& SLC ///< The pass object invoking us
98 /// The implementations of this function in subclasses is the heart of the
99 /// SimplifyLibCalls algorithm. Sublcasses of this class implement
100 /// OptimizeCall to determine if (a) the conditions are right for optimizing
101 /// the call and (b) to perform the optimization. If an action is taken
102 /// against ci, the subclass is responsible for returning true and ensuring
103 /// that ci is erased from its parent.
104 /// @brief Optimize a call, if possible.
105 virtual bool OptimizeCall(
106 CallInst* ci, ///< The call instruction that should be optimized.
107 SimplifyLibCalls& SLC ///< The pass object invoking us
110 /// @brief Get the name of the library call being optimized
111 const char * getFunctionName() const { return func_name; }
114 /// @brief Called by SimplifyLibCalls to update the occurrences statistic.
115 void succeeded() { ++occurrences; }
119 const char* func_name; ///< Name of the library call we optimize
121 std::string stat_name; ///< Holder for debug statistic name
122 std::string stat_desc; ///< Holder for debug statistic description
123 Statistic<> occurrences; ///< debug statistic (-debug-only=simplify-libcalls)
127 /// This class is an LLVM Pass that applies each of the LibCallOptimization
128 /// instances to all the call sites in a module, relatively efficiently. The
129 /// purpose of this pass is to provide optimizations for calls to well-known
130 /// functions with well-known semantics, such as those in the c library. The
131 /// class provides the basic infrastructure for handling runOnModule. Whenever /// this pass finds a function call, it asks the appropriate optimizer to
132 /// validate the call (ValidateLibraryCall). If it is validated, then
133 /// the OptimizeCall method is also called.
134 /// @brief A ModulePass for optimizing well-known function calls.
135 class SimplifyLibCalls : public ModulePass
138 /// We need some target data for accurate signature details that are
139 /// target dependent. So we require target data in our AnalysisUsage.
140 /// @brief Require TargetData from AnalysisUsage.
141 virtual void getAnalysisUsage(AnalysisUsage& Info) const
143 // Ask that the TargetData analysis be performed before us so we can use
145 Info.addRequired<TargetData>();
148 /// For this pass, process all of the function calls in the module, calling
149 /// ValidateLibraryCall and OptimizeCall as appropriate.
150 /// @brief Run all the lib call optimizations on a Module.
151 virtual bool runOnModule(Module &M)
157 // The call optimizations can be recursive. That is, the optimization might
158 // generate a call to another function which can also be optimized. This way
159 // we make the LibCallOptimization instances very specific to the case they
160 // handle. It also means we need to keep running over the function calls in
161 // the module until we don't get any more optimizations possible.
162 bool found_optimization = false;
165 found_optimization = false;
166 for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI)
168 // All the "well-known" functions are external and have external linkage
169 // because they live in a runtime library somewhere and were (probably)
170 // not compiled by LLVM. So, we only act on external functions that have
171 // external linkage and non-empty uses.
172 if (!FI->isExternal() || !FI->hasExternalLinkage() || FI->use_empty())
175 // Get the optimization class that pertains to this function
176 LibCallOptimization* CO = optlist[FI->getName().c_str()];
180 // Make sure the called function is suitable for the optimization
181 if (!CO->ValidateCalledFunction(FI,*this))
184 // Loop over each of the uses of the function
185 for (Value::use_iterator UI = FI->use_begin(), UE = FI->use_end();
188 // If the use of the function is a call instruction
189 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
191 // Do the optimization on the LibCallOptimization.
192 if (CO->OptimizeCall(CI,*this))
194 ++SimplifiedLibCalls;
195 found_optimization = result = true;
203 } while (found_optimization);
207 /// @brief Return the *current* module we're working on.
208 Module* getModule() const { return M; }
210 /// @brief Return the *current* target data for the module we're working on.
211 TargetData* getTargetData() const { return TD; }
213 /// @brief Return the size_t type -- syntactic shortcut
214 const Type* getIntPtrType() const { return TD->getIntPtrType(); }
216 /// @brief Return a Function* for the fputc libcall
217 Function* get_fputc(const Type* FILEptr_type)
221 std::vector<const Type*> args;
222 args.push_back(Type::IntTy);
223 args.push_back(FILEptr_type);
224 FunctionType* fputc_type =
225 FunctionType::get(Type::IntTy, args, false);
226 fputc_func = M->getOrInsertFunction("fputc",fputc_type);
231 /// @brief Return a Function* for the fwrite libcall
232 Function* get_fwrite(const Type* FILEptr_type)
236 std::vector<const Type*> args;
237 args.push_back(PointerType::get(Type::SByteTy));
238 args.push_back(TD->getIntPtrType());
239 args.push_back(TD->getIntPtrType());
240 args.push_back(FILEptr_type);
241 FunctionType* fwrite_type =
242 FunctionType::get(TD->getIntPtrType(), args, false);
243 fwrite_func = M->getOrInsertFunction("fwrite",fwrite_type);
248 /// @brief Return a Function* for the sqrt libcall
253 std::vector<const Type*> args;
254 args.push_back(Type::DoubleTy);
255 FunctionType* sqrt_type =
256 FunctionType::get(Type::DoubleTy, args, false);
257 sqrt_func = M->getOrInsertFunction("sqrt",sqrt_type);
262 /// @brief Return a Function* for the strlen libcall
263 Function* get_strlen()
267 std::vector<const Type*> args;
268 args.push_back(PointerType::get(Type::SByteTy));
269 FunctionType* strlen_type =
270 FunctionType::get(TD->getIntPtrType(), args, false);
271 strlen_func = M->getOrInsertFunction("strlen",strlen_type);
276 /// @brief Return a Function* for the memcpy libcall
277 Function* get_memcpy()
281 // Note: this is for llvm.memcpy intrinsic
282 std::vector<const Type*> args;
283 args.push_back(PointerType::get(Type::SByteTy));
284 args.push_back(PointerType::get(Type::SByteTy));
285 args.push_back(Type::IntTy);
286 args.push_back(Type::IntTy);
287 FunctionType* memcpy_type = FunctionType::get(Type::VoidTy, args, false);
288 memcpy_func = M->getOrInsertFunction("llvm.memcpy",memcpy_type);
294 /// @brief Reset our cached data for a new Module
295 void reset(Module& mod)
298 TD = &getAnalysis<TargetData>();
307 Function* fputc_func; ///< Cached fputc function
308 Function* fwrite_func; ///< Cached fwrite function
309 Function* memcpy_func; ///< Cached llvm.memcpy function
310 Function* sqrt_func; ///< Cached sqrt function
311 Function* strlen_func; ///< Cached strlen function
312 Module* M; ///< Cached Module
313 TargetData* TD; ///< Cached TargetData
317 RegisterOpt<SimplifyLibCalls>
318 X("simplify-libcalls","Simplify well-known library calls");
320 } // anonymous namespace
322 // The only public symbol in this file which just instantiates the pass object
323 ModulePass *llvm::createSimplifyLibCallsPass()
325 return new SimplifyLibCalls();
328 // Classes below here, in the anonymous namespace, are all subclasses of the
329 // LibCallOptimization class, each implementing all optimizations possible for a
330 // single well-known library call. Each has a static singleton instance that
331 // auto registers it into the "optlist" global above.
334 // Forward declare a utility function.
335 bool getConstantStringLength(Value* V, uint64_t& len, ConstantArray** A = 0 );
337 /// This LibCallOptimization will find instances of a call to "exit" that occurs
338 /// within the "main" function and change it to a simple "ret" instruction with
339 /// the same value passed to the exit function. When this is done, it splits the
340 /// basic block at the exit(3) call and deletes the call instruction.
341 /// @brief Replace calls to exit in main with a simple return
342 struct ExitInMainOptimization : public LibCallOptimization
344 ExitInMainOptimization() : LibCallOptimization("exit") {}
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") {}
412 /// @breif Destructor
413 virtual ~StrCatOptimization() {}
415 /// @brief Make sure that the "strcat" function has the right prototype
416 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
418 if (f->getReturnType() == PointerType::get(Type::SByteTy))
419 if (f->arg_size() == 2)
421 Function::const_arg_iterator AI = f->arg_begin();
422 if (AI++->getType() == PointerType::get(Type::SByteTy))
423 if (AI->getType() == PointerType::get(Type::SByteTy))
425 // Indicate this is a suitable call type.
432 /// @brief Optimize the strcat library function
433 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
435 // Extract some information from the instruction
436 Module* M = ci->getParent()->getParent()->getParent();
437 Value* dest = ci->getOperand(1);
438 Value* src = ci->getOperand(2);
440 // Extract the initializer (while making numerous checks) from the
441 // source operand of the call to strcat. If we get null back, one of
442 // a variety of checks in get_GVInitializer failed
444 if (!getConstantStringLength(src,len))
447 // Handle the simple, do-nothing case
450 ci->replaceAllUsesWith(dest);
451 ci->eraseFromParent();
455 // Increment the length because we actually want to memcpy the null
456 // terminator as well.
459 // We need to find the end of the destination string. That's where the
460 // memory is to be moved to. We just generate a call to strlen (further
461 // optimized in another pass). Note that the SLC.get_strlen() call
462 // caches the Function* for us.
463 CallInst* strlen_inst =
464 new CallInst(SLC.get_strlen(), dest, dest->getName()+".len",ci);
466 // Now that we have the destination's length, we must index into the
467 // destination's pointer to get the actual memcpy destination (end of
468 // the string .. we're concatenating).
469 std::vector<Value*> idx;
470 idx.push_back(strlen_inst);
471 GetElementPtrInst* gep =
472 new GetElementPtrInst(dest,idx,dest->getName()+".indexed",ci);
474 // We have enough information to now generate the memcpy call to
475 // do the concatenation for us.
476 std::vector<Value*> vals;
477 vals.push_back(gep); // destination
478 vals.push_back(ci->getOperand(2)); // source
479 vals.push_back(ConstantSInt::get(Type::IntTy,len)); // length
480 vals.push_back(ConstantSInt::get(Type::IntTy,1)); // alignment
481 new CallInst(SLC.get_memcpy(), vals, "", ci);
483 // Finally, substitute the first operand of the strcat call for the
484 // strcat call itself since strcat returns its first operand; and,
485 // kill the strcat CallInst.
486 ci->replaceAllUsesWith(dest);
487 ci->eraseFromParent();
492 /// This LibCallOptimization will simplify a call to the strcmp library
493 /// function. It optimizes out cases where one or both arguments are constant
494 /// and the result can be determined statically.
495 /// @brief Simplify the strcmp library function.
496 struct StrCmpOptimization : public LibCallOptimization
499 StrCmpOptimization() : LibCallOptimization("strcmp") {}
500 virtual ~StrCmpOptimization() {}
502 /// @brief Make sure that the "strcpy" function has the right prototype
503 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
505 if (f->getReturnType() == Type::IntTy && f->arg_size() == 2)
510 /// @brief Perform the strcpy optimization
511 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
513 // First, check to see if src and destination are the same. If they are,
514 // then the optimization is to replace the CallInst with a constant 0
515 // because the call is a no-op.
516 Value* s1 = ci->getOperand(1);
517 Value* s2 = ci->getOperand(2);
521 ci->replaceAllUsesWith(ConstantInt::get(Type::IntTy,0));
522 ci->eraseFromParent();
526 bool isstr_1 = false;
529 if (getConstantStringLength(s1,len_1,&A1))
534 // strcmp("",x) -> *x
535 LoadInst* load = new LoadInst(s1,ci->getName()+".load",ci);
537 new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
538 ci->replaceAllUsesWith(cast);
539 ci->eraseFromParent();
544 bool isstr_2 = false;
547 if (getConstantStringLength(s2,len_2,&A2))
552 // strcmp(x,"") -> *x
553 LoadInst* load = new LoadInst(s2,ci->getName()+".val",ci);
555 new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
556 ci->replaceAllUsesWith(cast);
557 ci->eraseFromParent();
562 if (isstr_1 && isstr_2)
564 // strcmp(x,y) -> cnst (if both x and y are constant strings)
565 std::string str1 = A1->getAsString();
566 std::string str2 = A2->getAsString();
567 int result = strcmp(str1.c_str(), str2.c_str());
568 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,result));
569 ci->eraseFromParent();
576 /// This LibCallOptimization will simplify a call to the strncmp library
577 /// function. It optimizes out cases where one or both arguments are constant
578 /// and the result can be determined statically.
579 /// @brief Simplify the strncmp library function.
580 struct StrNCmpOptimization : public LibCallOptimization
583 StrNCmpOptimization() : LibCallOptimization("strncmp") {}
584 virtual ~StrNCmpOptimization() {}
586 /// @brief Make sure that the "strcpy" function has the right prototype
587 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
589 if (f->getReturnType() == Type::IntTy && f->arg_size() == 3)
594 /// @brief Perform the strncpy optimization
595 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
597 // First, check to see if src and destination are the same. If they are,
598 // then the optimization is to replace the CallInst with a constant 0
599 // because the call is a no-op.
600 Value* s1 = ci->getOperand(1);
601 Value* s2 = ci->getOperand(2);
604 // strncmp(x,x,l) -> 0
605 ci->replaceAllUsesWith(ConstantInt::get(Type::IntTy,0));
606 ci->eraseFromParent();
610 // Check the length argument, if it is Constant zero then the strings are
612 uint64_t len_arg = 0;
613 bool len_arg_is_const = false;
614 if (ConstantInt* len_CI = dyn_cast<ConstantInt>(ci->getOperand(3)))
616 len_arg_is_const = true;
617 len_arg = len_CI->getRawValue();
620 // strncmp(x,y,0) -> 0
621 ci->replaceAllUsesWith(ConstantInt::get(Type::IntTy,0));
622 ci->eraseFromParent();
627 bool isstr_1 = false;
630 if (getConstantStringLength(s1,len_1,&A1))
635 // strncmp("",x) -> *x
636 LoadInst* load = new LoadInst(s1,ci->getName()+".load",ci);
638 new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
639 ci->replaceAllUsesWith(cast);
640 ci->eraseFromParent();
645 bool isstr_2 = false;
648 if (getConstantStringLength(s2,len_2,&A2))
653 // strncmp(x,"") -> *x
654 LoadInst* load = new LoadInst(s2,ci->getName()+".val",ci);
656 new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
657 ci->replaceAllUsesWith(cast);
658 ci->eraseFromParent();
663 if (isstr_1 && isstr_2 && len_arg_is_const)
665 // strncmp(x,y,const) -> constant
666 std::string str1 = A1->getAsString();
667 std::string str2 = A2->getAsString();
668 int result = strncmp(str1.c_str(), str2.c_str(), len_arg);
669 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,result));
670 ci->eraseFromParent();
677 /// This LibCallOptimization will simplify a call to the strcpy library
678 /// function. Two optimizations are possible:
679 /// (1) If src and dest are the same and not volatile, just return dest
680 /// (2) If the src is a constant then we can convert to llvm.memmove
681 /// @brief Simplify the strcpy library function.
682 struct StrCpyOptimization : public LibCallOptimization
685 StrCpyOptimization() : LibCallOptimization("strcpy") {}
686 virtual ~StrCpyOptimization() {}
688 /// @brief Make sure that the "strcpy" function has the right prototype
689 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
691 if (f->getReturnType() == PointerType::get(Type::SByteTy))
692 if (f->arg_size() == 2)
694 Function::const_arg_iterator AI = f->arg_begin();
695 if (AI++->getType() == PointerType::get(Type::SByteTy))
696 if (AI->getType() == PointerType::get(Type::SByteTy))
698 // Indicate this is a suitable call type.
705 /// @brief Perform the strcpy optimization
706 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
708 // First, check to see if src and destination are the same. If they are,
709 // then the optimization is to replace the CallInst with the destination
710 // because the call is a no-op. Note that this corresponds to the
711 // degenerate strcpy(X,X) case which should have "undefined" results
712 // according to the C specification. However, it occurs sometimes and
713 // we optimize it as a no-op.
714 Value* dest = ci->getOperand(1);
715 Value* src = ci->getOperand(2);
718 ci->replaceAllUsesWith(dest);
719 ci->eraseFromParent();
723 // Get the length of the constant string referenced by the second operand,
724 // the "src" parameter. Fail the optimization if we can't get the length
725 // (note that getConstantStringLength does lots of checks to make sure this
728 if (!getConstantStringLength(ci->getOperand(2),len))
731 // If the constant string's length is zero we can optimize this by just
732 // doing a store of 0 at the first byte of the destination
735 new StoreInst(ConstantInt::get(Type::SByteTy,0),ci->getOperand(1),ci);
736 ci->replaceAllUsesWith(dest);
737 ci->eraseFromParent();
741 // Increment the length because we actually want to memcpy the null
742 // terminator as well.
745 // Extract some information from the instruction
746 Module* M = ci->getParent()->getParent()->getParent();
748 // We have enough information to now generate the memcpy call to
749 // do the concatenation for us.
750 std::vector<Value*> vals;
751 vals.push_back(dest); // destination
752 vals.push_back(src); // source
753 vals.push_back(ConstantSInt::get(Type::IntTy,len)); // length
754 vals.push_back(ConstantSInt::get(Type::IntTy,1)); // alignment
755 new CallInst(SLC.get_memcpy(), vals, "", ci);
757 // Finally, substitute the first operand of the strcat call for the
758 // strcat call itself since strcat returns its first operand; and,
759 // kill the strcat CallInst.
760 ci->replaceAllUsesWith(dest);
761 ci->eraseFromParent();
766 /// This LibCallOptimization will simplify a call to the strlen library
767 /// function by replacing it with a constant value if the string provided to
768 /// it is a constant array.
769 /// @brief Simplify the strlen library function.
770 struct StrLenOptimization : public LibCallOptimization
772 StrLenOptimization() : LibCallOptimization("strlen") {}
773 virtual ~StrLenOptimization() {}
775 /// @brief Make sure that the "strlen" function has the right prototype
776 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
778 if (f->getReturnType() == SLC.getTargetData()->getIntPtrType())
779 if (f->arg_size() == 1)
780 if (Function::const_arg_iterator AI = f->arg_begin())
781 if (AI->getType() == PointerType::get(Type::SByteTy))
786 /// @brief Perform the strlen optimization
787 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
789 // Get the length of the string
791 if (!getConstantStringLength(ci->getOperand(1),len))
794 ci->replaceAllUsesWith(
795 ConstantInt::get(SLC.getTargetData()->getIntPtrType(),len));
796 ci->eraseFromParent();
801 /// This LibCallOptimization will simplify a call to the memcpy library
802 /// function by expanding it out to a single store of size 0, 1, 2, 4, or 8
803 /// bytes depending on the length of the string and the alignment. Additional
804 /// optimizations are possible in code generation (sequence of immediate store)
805 /// @brief Simplify the memcpy library function.
806 struct MemCpyOptimization : public LibCallOptimization
808 /// @brief Default Constructor
809 MemCpyOptimization() : LibCallOptimization("llvm.memcpy") {}
811 /// @brief Subclass Constructor
812 MemCpyOptimization(const char* fname) : LibCallOptimization(fname) {}
814 /// @brief Destructor
815 virtual ~MemCpyOptimization() {}
817 /// @brief Make sure that the "memcpy" function has the right prototype
818 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& TD)
820 // Just make sure this has 4 arguments per LLVM spec.
821 return (f->arg_size() == 4);
824 /// Because of alignment and instruction information that we don't have, we
825 /// leave the bulk of this to the code generators. The optimization here just
826 /// deals with a few degenerate cases where the length of the string and the
827 /// alignment match the sizes of our intrinsic types so we can do a load and
828 /// store instead of the memcpy call.
829 /// @brief Perform the memcpy optimization.
830 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& TD)
832 // Make sure we have constant int values to work with
833 ConstantInt* LEN = dyn_cast<ConstantInt>(ci->getOperand(3));
836 ConstantInt* ALIGN = dyn_cast<ConstantInt>(ci->getOperand(4));
840 // If the length is larger than the alignment, we can't optimize
841 uint64_t len = LEN->getRawValue();
842 uint64_t alignment = ALIGN->getRawValue();
846 // Get the type we will cast to, based on size of the string
847 Value* dest = ci->getOperand(1);
848 Value* src = ci->getOperand(2);
853 // memcpy(d,s,0,a) -> noop
854 ci->eraseFromParent();
856 case 1: castType = Type::SByteTy; break;
857 case 2: castType = Type::ShortTy; break;
858 case 4: castType = Type::IntTy; break;
859 case 8: castType = Type::LongTy; break;
864 // Cast source and dest to the right sized primitive and then load/store
866 new CastInst(src,PointerType::get(castType),src->getName()+".cast",ci);
868 new CastInst(dest,PointerType::get(castType),dest->getName()+".cast",ci);
869 LoadInst* LI = new LoadInst(SrcCast,SrcCast->getName()+".val",ci);
870 StoreInst* SI = new StoreInst(LI, DestCast, ci);
871 ci->eraseFromParent();
876 /// This LibCallOptimization will simplify a call to the memmove library
877 /// function. It is identical to MemCopyOptimization except for the name of
879 /// @brief Simplify the memmove library function.
880 struct MemMoveOptimization : public MemCpyOptimization
882 /// @brief Default Constructor
883 MemMoveOptimization() : MemCpyOptimization("llvm.memmove") {}
887 /// This LibCallOptimization will simplify calls to the "pow" library
888 /// function. It looks for cases where the result of pow is well known and
889 /// substitutes the appropriate value.
890 /// @brief Simplify the pow library function.
891 struct PowOptimization : public LibCallOptimization
894 /// @brief Default Constructor
895 PowOptimization() : LibCallOptimization("pow") {}
896 /// @brief Destructor
897 virtual ~PowOptimization() {}
899 /// @brief Make sure that the "pow" function has the right prototype
900 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
902 // Just make sure this has 2 arguments
903 return (f->arg_size() == 2);
906 /// @brief Perform the pow optimization.
907 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
909 const Type *Ty = cast<Function>(ci->getOperand(0))->getReturnType();
910 Value* base = ci->getOperand(1);
911 Value* expn = ci->getOperand(2);
912 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(base)) {
913 double Op1V = Op1->getValue();
917 ci->replaceAllUsesWith(ConstantFP::get(Ty,1.0));
918 ci->eraseFromParent();
922 else if (ConstantFP* Op2 = dyn_cast<ConstantFP>(expn))
924 double Op2V = Op2->getValue();
928 ci->replaceAllUsesWith(ConstantFP::get(Ty,1.0));
929 ci->eraseFromParent();
932 else if (Op2V == 0.5)
934 // pow(x,0.5) -> sqrt(x)
935 CallInst* sqrt_inst = new CallInst(SLC.get_sqrt(), base,
936 ci->getName()+".pow",ci);
937 ci->replaceAllUsesWith(sqrt_inst);
938 ci->eraseFromParent();
941 else if (Op2V == 1.0)
944 ci->replaceAllUsesWith(base);
945 ci->eraseFromParent();
948 else if (Op2V == -1.0)
950 // pow(x,-1.0) -> 1.0/x
951 BinaryOperator* div_inst= BinaryOperator::create(Instruction::Div,
952 ConstantFP::get(Ty,1.0), base, ci->getName()+".pow", ci);
953 ci->replaceAllUsesWith(div_inst);
954 ci->eraseFromParent();
958 return false; // opt failed
962 /// This LibCallOptimization will simplify calls to the "fprintf" library
963 /// function. It looks for cases where the result of fprintf is not used and the
964 /// operation can be reduced to something simpler.
965 /// @brief Simplify the pow library function.
966 struct FPrintFOptimization : public LibCallOptimization
969 /// @brief Default Constructor
970 FPrintFOptimization() : LibCallOptimization("fprintf") {}
972 /// @brief Destructor
973 virtual ~FPrintFOptimization() {}
975 /// @brief Make sure that the "fprintf" function has the right prototype
976 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
978 // Just make sure this has at least 2 arguments
979 return (f->arg_size() >= 2);
982 /// @brief Perform the fprintf optimization.
983 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
985 // If the call has more than 3 operands, we can't optimize it
986 if (ci->getNumOperands() > 4 || ci->getNumOperands() <= 2)
989 // If the result of the fprintf call is used, none of these optimizations
991 if (!ci->hasNUses(0))
994 // All the optimizations depend on the length of the second argument and the
995 // fact that it is a constant string array. Check that now
997 ConstantArray* CA = 0;
998 if (!getConstantStringLength(ci->getOperand(2), len, &CA))
1001 if (ci->getNumOperands() == 3)
1003 // Make sure there's no % in the constant array
1004 for (unsigned i = 0; i < len; ++i)
1006 if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(i)))
1008 // Check for the null terminator
1009 if (CI->getRawValue() == '%')
1010 return false; // we found end of string
1016 // fprintf(file,fmt) -> fwrite(fmt,strlen(fmt),1file)
1017 const Type* FILEptr_type = ci->getOperand(1)->getType();
1018 Function* fwrite_func = SLC.get_fwrite(FILEptr_type);
1021 std::vector<Value*> args;
1022 args.push_back(ci->getOperand(2));
1023 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
1024 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),1));
1025 args.push_back(ci->getOperand(1));
1026 new CallInst(fwrite_func,args,"",ci);
1027 ci->eraseFromParent();
1031 // The remaining optimizations require the format string to be length 2
1036 // The first character has to be a %
1037 if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(0)))
1038 if (CI->getRawValue() != '%')
1041 // Get the second character and switch on its value
1042 ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(1));
1043 switch (CI->getRawValue())
1048 ConstantArray* CA = 0;
1049 if (!getConstantStringLength(ci->getOperand(3), len, &CA))
1052 // fprintf(file,fmt) -> fwrite(fmt,strlen(fmt),1,file)
1053 const Type* FILEptr_type = ci->getOperand(1)->getType();
1054 Function* fwrite_func = SLC.get_fwrite(FILEptr_type);
1057 std::vector<Value*> args;
1058 args.push_back(ci->getOperand(3));
1059 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
1060 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),1));
1061 args.push_back(ci->getOperand(1));
1062 new CallInst(fwrite_func,args,"",ci);
1067 ConstantInt* CI = dyn_cast<ConstantInt>(ci->getOperand(3));
1071 const Type* FILEptr_type = ci->getOperand(1)->getType();
1072 Function* fputc_func = SLC.get_fputc(FILEptr_type);
1075 CastInst* cast = new CastInst(CI,Type::IntTy,CI->getName()+".int",ci);
1076 new CallInst(fputc_func,cast,ci->getOperand(1),"",ci);
1082 ci->eraseFromParent();
1088 /// This LibCallOptimization will simplify calls to the "fputs" library
1089 /// function. It looks for cases where the result of fputs is not used and the
1090 /// operation can be reduced to something simpler.
1091 /// @brief Simplify the pow library function.
1092 struct PutsOptimization : public LibCallOptimization
1095 /// @brief Default Constructor
1096 PutsOptimization() : LibCallOptimization("fputs") {}
1098 /// @brief Destructor
1099 virtual ~PutsOptimization() {}
1101 /// @brief Make sure that the "fputs" function has the right prototype
1102 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1104 // Just make sure this has 2 arguments
1105 return (f->arg_size() == 2);
1108 /// @brief Perform the fputs optimization.
1109 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1111 // If the result is used, none of these optimizations work
1112 if (!ci->hasNUses(0))
1115 // All the optimizations depend on the length of the first argument and the
1116 // fact that it is a constant string array. Check that now
1118 if (!getConstantStringLength(ci->getOperand(1), len))
1124 // fputs("",F) -> noop
1128 // fputs(s,F) -> fputc(s[0],F) (if s is constant and strlen(s) == 1)
1129 const Type* FILEptr_type = ci->getOperand(2)->getType();
1130 Function* fputc_func = SLC.get_fputc(FILEptr_type);
1133 LoadInst* loadi = new LoadInst(ci->getOperand(1),
1134 ci->getOperand(1)->getName()+".byte",ci);
1135 CastInst* casti = new CastInst(loadi,Type::IntTy,
1136 loadi->getName()+".int",ci);
1137 new CallInst(fputc_func,casti,ci->getOperand(2),"",ci);
1142 // fputs(s,F) -> fwrite(s,1,len,F) (if s is constant and strlen(s) > 1)
1143 const Type* FILEptr_type = ci->getOperand(2)->getType();
1144 Function* fwrite_func = SLC.get_fwrite(FILEptr_type);
1147 std::vector<Value*> parms;
1148 parms.push_back(ci->getOperand(1));
1149 parms.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
1150 parms.push_back(ConstantUInt::get(SLC.getIntPtrType(),1));
1151 parms.push_back(ci->getOperand(2));
1152 new CallInst(fwrite_func,parms,"",ci);
1156 ci->eraseFromParent();
1157 return true; // success
1161 /// This LibCallOptimization will simplify calls to the "toascii" library
1162 /// function. It simply does the corresponding and operation to restrict the
1163 /// range of values to the ASCII character set (0-127).
1164 /// @brief Simplify the toascii library function.
1165 struct ToAsciiOptimization : public LibCallOptimization
1168 /// @brief Default Constructor
1169 ToAsciiOptimization() : LibCallOptimization("toascii") {}
1171 /// @brief Destructor
1172 virtual ~ToAsciiOptimization() {}
1174 /// @brief Make sure that the "fputs" function has the right prototype
1175 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1177 // Just make sure this has 2 arguments
1178 return (f->arg_size() == 1);
1181 /// @brief Perform the toascii optimization.
1182 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1184 // toascii(c) -> (c & 0x7f)
1185 Value* chr = ci->getOperand(1);
1186 BinaryOperator* and_inst = BinaryOperator::create(Instruction::And,chr,
1187 ConstantInt::get(chr->getType(),0x7F),ci->getName()+".toascii",ci);
1188 ci->replaceAllUsesWith(and_inst);
1189 ci->eraseFromParent();
1194 /// A function to compute the length of a null-terminated constant array of
1195 /// integers. This function can't rely on the size of the constant array
1196 /// because there could be a null terminator in the middle of the array.
1197 /// We also have to bail out if we find a non-integer constant initializer
1198 /// of one of the elements or if there is no null-terminator. The logic
1199 /// below checks each of these conditions and will return true only if all
1200 /// conditions are met. In that case, the \p len parameter is set to the length
1201 /// of the null-terminated string. If false is returned, the conditions were
1202 /// not met and len is set to 0.
1203 /// @brief Get the length of a constant string (null-terminated array).
1204 bool getConstantStringLength(Value* V, uint64_t& len, ConstantArray** CA )
1206 assert(V != 0 && "Invalid args to getConstantStringLength");
1207 len = 0; // make sure we initialize this
1209 // If the value is not a GEP instruction nor a constant expression with a
1210 // GEP instruction, then return false because ConstantArray can't occur
1212 if (GetElementPtrInst* GEPI = dyn_cast<GetElementPtrInst>(V))
1214 else if (ConstantExpr* CE = dyn_cast<ConstantExpr>(V))
1215 if (CE->getOpcode() == Instruction::GetElementPtr)
1222 // Make sure the GEP has exactly three arguments.
1223 if (GEP->getNumOperands() != 3)
1226 // Check to make sure that the first operand of the GEP is an integer and
1227 // has value 0 so that we are sure we're indexing into the initializer.
1228 if (ConstantInt* op1 = dyn_cast<ConstantInt>(GEP->getOperand(1)))
1230 if (!op1->isNullValue())
1236 // Ensure that the second operand is a ConstantInt. If it isn't then this
1237 // GEP is wonky and we're not really sure what were referencing into and
1238 // better of not optimizing it. While we're at it, get the second index
1239 // value. We'll need this later for indexing the ConstantArray.
1240 uint64_t start_idx = 0;
1241 if (ConstantInt* CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
1242 start_idx = CI->getRawValue();
1246 // The GEP instruction, constant or instruction, must reference a global
1247 // variable that is a constant and is initialized. The referenced constant
1248 // initializer is the array that we'll use for optimization.
1249 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1250 if (!GV || !GV->isConstant() || !GV->hasInitializer())
1253 // Get the initializer.
1254 Constant* INTLZR = GV->getInitializer();
1256 // Handle the ConstantAggregateZero case
1257 if (ConstantAggregateZero* CAZ = dyn_cast<ConstantAggregateZero>(INTLZR))
1259 // This is a degenerate case. The initializer is constant zero so the
1260 // length of the string must be zero.
1265 // Must be a Constant Array
1266 ConstantArray* A = dyn_cast<ConstantArray>(INTLZR);
1270 // Get the number of elements in the array
1271 uint64_t max_elems = A->getType()->getNumElements();
1273 // Traverse the constant array from start_idx (derived above) which is
1274 // the place the GEP refers to in the array.
1275 for ( len = start_idx; len < max_elems; len++)
1277 if (ConstantInt* CI = dyn_cast<ConstantInt>(A->getOperand(len)))
1279 // Check for the null terminator
1280 if (CI->isNullValue())
1281 break; // we found end of string
1284 return false; // This array isn't suitable, non-int initializer
1286 if (len >= max_elems)
1287 return false; // This array isn't null terminated
1289 // Subtract out the initial value from the length
1293 return true; // success!
1297 // Additional cases that we need to add to this file:
1300 // * cbrt(expN(X)) -> expN(x/3)
1301 // * cbrt(sqrt(x)) -> pow(x,1/6)
1302 // * cbrt(sqrt(x)) -> pow(x,1/9)
1305 // * cos(-x) -> cos(x)
1308 // * exp(log(x)) -> x
1310 // ffs, ffsl, ffsll:
1311 // * ffs(cnst) -> cnst'
1314 // * isascii(c) -> ((c & ~0x7f) == 0)
1317 // * isdigit(c) -> (unsigned)(c) - '0' <= 9
1320 // * log(exp(x)) -> x
1321 // * log(x**y) -> y*log(x)
1322 // * log(exp(y)) -> y*log(e)
1323 // * log(exp2(y)) -> y*log(2)
1324 // * log(exp10(y)) -> y*log(10)
1325 // * log(sqrt(x)) -> 0.5*log(x)
1326 // * log(pow(x,y)) -> y*log(x)
1328 // lround, lroundf, lroundl:
1329 // * lround(cnst) -> cnst'
1332 // * memcmp(s1,s2,0) -> 0
1333 // * memcmp(x,x,l) -> 0
1334 // * memcmp(x,y,l) -> cnst
1335 // (if all arguments are constant and strlen(x) <= l and strlen(y) <= l)
1336 // * memcpy(x,y,1) -> *x - *y
1339 // * memmove(d,s,l,a) -> memcpy(d,s,l,a)
1340 // (if s is a global constant array)
1343 // * memset(s,c,0) -> noop
1344 // * memset(s,c,n) -> store s, c
1348 // * pow(exp(x),y) -> exp(x*y)
1349 // * pow(sqrt(x),y) -> pow(x,y*0.5)
1350 // * pow(pow(x,y),z)-> pow(x,y*z)
1353 // * puts("") -> fputc("\n",stdout) (how do we get "stdout"?)
1355 // round, roundf, roundl:
1356 // * round(cnst) -> cnst'
1359 // * signbit(cnst) -> cnst'
1360 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
1363 // * sprintf(dest,fmt) -> strcpy(dest,fmt)
1364 // (if fmt is constant and constains no % characters)
1365 // * sprintf(dest,"%s",orig) -> strcpy(dest,orig)
1366 // (only if the sprintf result is not used)
1368 // sqrt, sqrtf, sqrtl:
1369 // * sqrt(expN(x)) -> expN(x*0.5)
1370 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
1371 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
1374 // * strchr(s,c) -> offset_of_in(c,s)
1375 // (if c is a constant integer and s is a constant string)
1376 // * strrchr(s,c) -> reverse_offset_of_in(c,s)
1377 // (if c is a constant integer and s is a constant string)
1378 // * strrchr(s1,0) -> strchr(s1,0)
1381 // * strncat(x,y,0) -> x
1382 // * strncat(x,y,0) -> x (if strlen(y) = 0)
1383 // * strncat(x,y,l) -> strcat(x,y) (if y and l are constants an l > strlen(y))
1386 // * strncpy(d,s,0) -> d
1387 // * strncpy(d,s,l) -> memcpy(d,s,l,1)
1388 // (if s and l are constants)
1391 // * strpbrk(s,a) -> offset_in_for(s,a)
1392 // (if s and a are both constant strings)
1393 // * strpbrk(s,"") -> 0
1394 // * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
1397 // * strspn(s,a) -> const_int (if both args are constant)
1398 // * strspn("",a) -> 0
1399 // * strspn(s,"") -> 0
1400 // * strcspn(s,a) -> const_int (if both args are constant)
1401 // * strcspn("",a) -> 0
1402 // * strcspn(s,"") -> strlen(a)
1405 // * strstr(x,x) -> x
1406 // * strstr(s1,s2) -> offset_of_s2_in(s1)
1407 // (if s1 and s2 are constant strings)
1410 // * tan(atan(x)) -> x
1412 // trunc, truncf, truncl:
1413 // * trunc(cnst) -> cnst'