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/Config/config.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Target/TargetData.h"
31 #include "llvm/Transforms/IPO.h"
37 /// This statistic keeps track of the total number of library calls that have
38 /// been simplified regardless of which call it is.
39 Statistic<> SimplifiedLibCalls("simplify-libcalls",
40 "Number of library calls simplified");
42 // Forward declarations
43 class LibCallOptimization;
44 class SimplifyLibCalls;
46 /// This hash map is populated by the constructor for LibCallOptimization class.
47 /// Therefore all subclasses are registered here at static initialization time
48 /// and this list is what the SimplifyLibCalls pass uses to apply the individual
49 /// optimizations to the call sites.
50 /// @brief The list of optimizations deriving from LibCallOptimization
51 static hash_map<std::string,LibCallOptimization*> optlist;
53 /// This class is the abstract base class for the set of optimizations that
54 /// corresponds to one library call. The SimplifyLibCalls pass will call the
55 /// ValidateCalledFunction method to ask the optimization if a given Function
56 /// is the kind that the optimization can handle. If the subclass returns true,
57 /// then SImplifyLibCalls will also call the OptimizeCall method to perform,
58 /// or attempt to perform, the optimization(s) for the library call. Otherwise,
59 /// OptimizeCall won't be called. Subclasses are responsible for providing the
60 /// name of the library call (strlen, strcpy, etc.) to the LibCallOptimization
61 /// constructor. This is used to efficiently select which call instructions to
62 /// optimize. The criteria for a "lib call" is "anything with well known
63 /// semantics", typically a library function that is defined by an international
64 /// standard. Because the semantics are well known, the optimizations can
65 /// generally short-circuit actually calling the function if there's a simpler
66 /// way (e.g. strlen(X) can be reduced to a constant if X is a constant global).
67 /// @brief Base class for library call optimizations
68 class LibCallOptimization
71 /// The \p fname argument must be the name of the library function being
72 /// optimized by the subclass.
73 /// @brief Constructor that registers the optimization.
74 LibCallOptimization(const char* fname, const char* description )
77 , occurrences("simplify-libcalls",description)
80 // Register this call optimizer in the optlist (a hash_map)
81 optlist[fname] = this;
84 /// @brief Deregister from the optlist
85 virtual ~LibCallOptimization() { optlist.erase(func_name); }
87 /// The implementation of this function in subclasses should determine if
88 /// \p F is suitable for the optimization. This method is called by
89 /// SimplifyLibCalls::runOnModule to short circuit visiting all the call
90 /// sites of such a function if that function is not suitable in the first
91 /// place. If the called function is suitabe, this method should return true;
92 /// false, otherwise. This function should also perform any lazy
93 /// initialization that the LibCallOptimization needs to do, if its to return
94 /// true. This avoids doing initialization until the optimizer is actually
95 /// going to be called upon to do some optimization.
96 /// @brief Determine if the function is suitable for optimization
97 virtual bool ValidateCalledFunction(
98 const Function* F, ///< The function that is the target of call sites
99 SimplifyLibCalls& SLC ///< The pass object invoking us
102 /// The implementations of this function in subclasses is the heart of the
103 /// SimplifyLibCalls algorithm. Sublcasses of this class implement
104 /// OptimizeCall to determine if (a) the conditions are right for optimizing
105 /// the call and (b) to perform the optimization. If an action is taken
106 /// against ci, the subclass is responsible for returning true and ensuring
107 /// that ci is erased from its parent.
108 /// @brief Optimize a call, if possible.
109 virtual bool OptimizeCall(
110 CallInst* ci, ///< The call instruction that should be optimized.
111 SimplifyLibCalls& SLC ///< The pass object invoking us
114 /// @brief Get the name of the library call being optimized
115 const char * getFunctionName() const { return func_name; }
118 /// @brief Called by SimplifyLibCalls to update the occurrences statistic.
119 void succeeded() { DEBUG(++occurrences); }
123 const char* func_name; ///< Name of the library call we optimize
125 Statistic<> occurrences; ///< debug statistic (-debug-only=simplify-libcalls)
129 /// This class is an LLVM Pass that applies each of the LibCallOptimization
130 /// instances to all the call sites in a module, relatively efficiently. The
131 /// purpose of this pass is to provide optimizations for calls to well-known
132 /// functions with well-known semantics, such as those in the c library. The
133 /// class provides the basic infrastructure for handling runOnModule. Whenever
134 /// this pass finds a function call, it asks the appropriate optimizer to
135 /// validate the call (ValidateLibraryCall). If it is validated, then
136 /// the OptimizeCall method is also called.
137 /// @brief A ModulePass for optimizing well-known function calls.
138 class SimplifyLibCalls : public ModulePass
141 /// We need some target data for accurate signature details that are
142 /// target dependent. So we require target data in our AnalysisUsage.
143 /// @brief Require TargetData from AnalysisUsage.
144 virtual void getAnalysisUsage(AnalysisUsage& Info) const
146 // Ask that the TargetData analysis be performed before us so we can use
148 Info.addRequired<TargetData>();
151 /// For this pass, process all of the function calls in the module, calling
152 /// ValidateLibraryCall and OptimizeCall as appropriate.
153 /// @brief Run all the lib call optimizations on a Module.
154 virtual bool runOnModule(Module &M)
160 // The call optimizations can be recursive. That is, the optimization might
161 // generate a call to another function which can also be optimized. This way
162 // we make the LibCallOptimization instances very specific to the case they
163 // handle. It also means we need to keep running over the function calls in
164 // the module until we don't get any more optimizations possible.
165 bool found_optimization = false;
168 found_optimization = false;
169 for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI)
171 // All the "well-known" functions are external and have external linkage
172 // because they live in a runtime library somewhere and were (probably)
173 // not compiled by LLVM. So, we only act on external functions that
174 // have external linkage and non-empty uses.
175 if (!FI->isExternal() || !FI->hasExternalLinkage() || FI->use_empty())
178 // Get the optimization class that pertains to this function
179 LibCallOptimization* CO = optlist[FI->getName().c_str()];
183 // Make sure the called function is suitable for the optimization
184 if (!CO->ValidateCalledFunction(FI,*this))
187 // Loop over each of the uses of the function
188 for (Value::use_iterator UI = FI->use_begin(), UE = FI->use_end();
191 // If the use of the function is a call instruction
192 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
194 // Do the optimization on the LibCallOptimization.
195 if (CO->OptimizeCall(CI,*this))
197 ++SimplifiedLibCalls;
198 found_optimization = result = true;
206 } while (found_optimization);
210 /// @brief Return the *current* module we're working on.
211 Module* getModule() const { return M; }
213 /// @brief Return the *current* target data for the module we're working on.
214 TargetData* getTargetData() const { return TD; }
216 /// @brief Return the size_t type -- syntactic shortcut
217 const Type* getIntPtrType() const { return TD->getIntPtrType(); }
219 /// @brief Return a Function* for the fputc libcall
220 Function* get_fputc(const Type* FILEptr_type)
224 std::vector<const Type*> args;
225 args.push_back(Type::IntTy);
226 args.push_back(FILEptr_type);
227 FunctionType* fputc_type =
228 FunctionType::get(Type::IntTy, args, false);
229 fputc_func = M->getOrInsertFunction("fputc",fputc_type);
234 /// @brief Return a Function* for the fwrite libcall
235 Function* get_fwrite(const Type* FILEptr_type)
239 std::vector<const Type*> args;
240 args.push_back(PointerType::get(Type::SByteTy));
241 args.push_back(TD->getIntPtrType());
242 args.push_back(TD->getIntPtrType());
243 args.push_back(FILEptr_type);
244 FunctionType* fwrite_type =
245 FunctionType::get(TD->getIntPtrType(), args, false);
246 fwrite_func = M->getOrInsertFunction("fwrite",fwrite_type);
251 /// @brief Return a Function* for the sqrt libcall
256 std::vector<const Type*> args;
257 args.push_back(Type::DoubleTy);
258 FunctionType* sqrt_type =
259 FunctionType::get(Type::DoubleTy, args, false);
260 sqrt_func = M->getOrInsertFunction("sqrt",sqrt_type);
265 /// @brief Return a Function* for the strlen libcall
266 Function* get_strcpy()
270 std::vector<const Type*> args;
271 args.push_back(PointerType::get(Type::SByteTy));
272 args.push_back(PointerType::get(Type::SByteTy));
273 FunctionType* strcpy_type =
274 FunctionType::get(PointerType::get(Type::SByteTy), args, false);
275 strcpy_func = M->getOrInsertFunction("strcpy",strcpy_type);
280 /// @brief Return a Function* for the strlen libcall
281 Function* get_strlen()
285 std::vector<const Type*> args;
286 args.push_back(PointerType::get(Type::SByteTy));
287 FunctionType* strlen_type =
288 FunctionType::get(TD->getIntPtrType(), args, false);
289 strlen_func = M->getOrInsertFunction("strlen",strlen_type);
294 /// @brief Return a Function* for the memchr libcall
295 Function* get_memchr()
299 std::vector<const Type*> args;
300 args.push_back(PointerType::get(Type::SByteTy));
301 args.push_back(Type::IntTy);
302 args.push_back(TD->getIntPtrType());
303 FunctionType* memchr_type = FunctionType::get(
304 PointerType::get(Type::SByteTy), args, false);
305 memchr_func = M->getOrInsertFunction("memchr",memchr_type);
310 /// @brief Return a Function* for the memcpy libcall
311 Function* get_memcpy() {
313 const Type *SBP = PointerType::get(Type::SByteTy);
314 memcpy_func = M->getOrInsertFunction("llvm.memcpy", Type::VoidTy,SBP, SBP,
315 Type::UIntTy, Type::UIntTy,
322 Function* get_floorf() {
324 floorf_func = M->getOrInsertFunction("floorf", Type::FloatTy,
325 Type::FloatTy, (Type *)0);
331 /// @brief Reset our cached data for a new Module
332 void reset(Module& mod)
335 TD = &getAnalysis<TargetData>();
349 Function* fputc_func; ///< Cached fputc function
350 Function* fwrite_func; ///< Cached fwrite function
351 Function* memcpy_func; ///< Cached llvm.memcpy function
352 Function* memchr_func; ///< Cached memchr function
353 Function* sqrt_func; ///< Cached sqrt function
354 Function* strcpy_func; ///< Cached strcpy function
355 Function* strlen_func; ///< Cached strlen function
357 Function* floorf_func; ///< Cached floorf function
359 Module* M; ///< Cached Module
360 TargetData* TD; ///< Cached TargetData
364 RegisterOpt<SimplifyLibCalls>
365 X("simplify-libcalls","Simplify well-known library calls");
367 } // anonymous namespace
369 // The only public symbol in this file which just instantiates the pass object
370 ModulePass *llvm::createSimplifyLibCallsPass()
372 return new SimplifyLibCalls();
375 // Classes below here, in the anonymous namespace, are all subclasses of the
376 // LibCallOptimization class, each implementing all optimizations possible for a
377 // single well-known library call. Each has a static singleton instance that
378 // auto registers it into the "optlist" global above.
381 // Forward declare utility functions.
382 bool getConstantStringLength(Value* V, uint64_t& len, ConstantArray** A = 0 );
383 Value *CastToCStr(Value *V, Instruction &IP);
385 /// This LibCallOptimization will find instances of a call to "exit" that occurs
386 /// within the "main" function and change it to a simple "ret" instruction with
387 /// the same value passed to the exit function. When this is done, it splits the
388 /// basic block at the exit(3) call and deletes the call instruction.
389 /// @brief Replace calls to exit in main with a simple return
390 struct ExitInMainOptimization : public LibCallOptimization
392 ExitInMainOptimization() : LibCallOptimization("exit",
393 "Number of 'exit' calls simplified") {}
395 // Make sure the called function looks like exit (int argument, int return
396 // type, external linkage, not varargs).
397 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
399 if (f->arg_size() >= 1)
400 if (f->arg_begin()->getType()->isInteger())
405 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
407 // To be careful, we check that the call to exit is coming from "main", that
408 // main has external linkage, and the return type of main and the argument
409 // to exit have the same type.
410 Function *from = ci->getParent()->getParent();
411 if (from->hasExternalLinkage())
412 if (from->getReturnType() == ci->getOperand(1)->getType())
413 if (from->getName() == "main")
415 // Okay, time to actually do the optimization. First, get the basic
416 // block of the call instruction
417 BasicBlock* bb = ci->getParent();
419 // Create a return instruction that we'll replace the call with.
420 // Note that the argument of the return is the argument of the call
422 ReturnInst* ri = new ReturnInst(ci->getOperand(1), ci);
424 // Split the block at the call instruction which places it in a new
426 bb->splitBasicBlock(ci);
428 // The block split caused a branch instruction to be inserted into
429 // the end of the original block, right after the return instruction
430 // that we put there. That's not a valid block, so delete the branch
432 bb->getInstList().pop_back();
434 // Now we can finally get rid of the call instruction which now lives
435 // in the new basic block.
436 ci->eraseFromParent();
438 // Optimization succeeded, return true.
441 // We didn't pass the criteria for this optimization so return false
444 } ExitInMainOptimizer;
446 /// This LibCallOptimization will simplify a call to the strcat library
447 /// function. The simplification is possible only if the string being
448 /// concatenated is a constant array or a constant expression that results in
449 /// a constant string. In this case we can replace it with strlen + llvm.memcpy
450 /// of the constant string. Both of these calls are further reduced, if possible
451 /// on subsequent passes.
452 /// @brief Simplify the strcat library function.
453 struct StrCatOptimization : public LibCallOptimization
456 /// @brief Default constructor
457 StrCatOptimization() : LibCallOptimization("strcat",
458 "Number of 'strcat' calls simplified") {}
462 /// @brief Make sure that the "strcat" function has the right prototype
463 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
465 if (f->getReturnType() == PointerType::get(Type::SByteTy))
466 if (f->arg_size() == 2)
468 Function::const_arg_iterator AI = f->arg_begin();
469 if (AI++->getType() == PointerType::get(Type::SByteTy))
470 if (AI->getType() == PointerType::get(Type::SByteTy))
472 // Indicate this is a suitable call type.
479 /// @brief Optimize the strcat library function
480 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
482 // Extract some information from the instruction
483 Module* M = ci->getParent()->getParent()->getParent();
484 Value* dest = ci->getOperand(1);
485 Value* src = ci->getOperand(2);
487 // Extract the initializer (while making numerous checks) from the
488 // source operand of the call to strcat. If we get null back, one of
489 // a variety of checks in get_GVInitializer failed
491 if (!getConstantStringLength(src,len))
494 // Handle the simple, do-nothing case
497 ci->replaceAllUsesWith(dest);
498 ci->eraseFromParent();
502 // Increment the length because we actually want to memcpy the null
503 // terminator as well.
506 // We need to find the end of the destination string. That's where the
507 // memory is to be moved to. We just generate a call to strlen (further
508 // optimized in another pass). Note that the SLC.get_strlen() call
509 // caches the Function* for us.
510 CallInst* strlen_inst =
511 new CallInst(SLC.get_strlen(), dest, dest->getName()+".len",ci);
513 // Now that we have the destination's length, we must index into the
514 // destination's pointer to get the actual memcpy destination (end of
515 // the string .. we're concatenating).
516 std::vector<Value*> idx;
517 idx.push_back(strlen_inst);
518 GetElementPtrInst* gep =
519 new GetElementPtrInst(dest,idx,dest->getName()+".indexed",ci);
521 // We have enough information to now generate the memcpy call to
522 // do the concatenation for us.
523 std::vector<Value*> vals;
524 vals.push_back(gep); // destination
525 vals.push_back(ci->getOperand(2)); // source
526 vals.push_back(ConstantUInt::get(Type::UIntTy,len)); // length
527 vals.push_back(ConstantUInt::get(Type::UIntTy,1)); // alignment
528 new CallInst(SLC.get_memcpy(), vals, "", ci);
530 // Finally, substitute the first operand of the strcat call for the
531 // strcat call itself since strcat returns its first operand; and,
532 // kill the strcat CallInst.
533 ci->replaceAllUsesWith(dest);
534 ci->eraseFromParent();
539 /// This LibCallOptimization will simplify a call to the strchr library
540 /// function. It optimizes out cases where the arguments are both constant
541 /// and the result can be determined statically.
542 /// @brief Simplify the strcmp library function.
543 struct StrChrOptimization : public LibCallOptimization
546 StrChrOptimization() : LibCallOptimization("strchr",
547 "Number of 'strchr' calls simplified") {}
549 /// @brief Make sure that the "strchr" function has the right prototype
550 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
552 if (f->getReturnType() == PointerType::get(Type::SByteTy) &&
558 /// @brief Perform the strchr optimizations
559 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
561 // If there aren't three operands, bail
562 if (ci->getNumOperands() != 3)
565 // Check that the first argument to strchr is a constant array of sbyte.
566 // If it is, get the length and data, otherwise return false.
569 if (!getConstantStringLength(ci->getOperand(1),len,&CA))
572 // Check that the second argument to strchr is a constant int, return false
574 ConstantSInt* CSI = dyn_cast<ConstantSInt>(ci->getOperand(2));
577 // Just lower this to memchr since we know the length of the string as
579 Function* f = SLC.get_memchr();
580 std::vector<Value*> args;
581 args.push_back(ci->getOperand(1));
582 args.push_back(ci->getOperand(2));
583 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
584 ci->replaceAllUsesWith( new CallInst(f,args,ci->getName(),ci));
585 ci->eraseFromParent();
589 // Get the character we're looking for
590 int64_t chr = CSI->getValue();
592 // Compute the offset
594 bool char_found = false;
595 for (uint64_t i = 0; i < len; ++i)
597 if (ConstantSInt* CI = dyn_cast<ConstantSInt>(CA->getOperand(i)))
599 // Check for the null terminator
600 if (CI->isNullValue())
601 break; // we found end of string
602 else if (CI->getValue() == chr)
611 // strchr(s,c) -> offset_of_in(c,s)
612 // (if c is a constant integer and s is a constant string)
615 std::vector<Value*> indices;
616 indices.push_back(ConstantUInt::get(Type::ULongTy,offset));
617 GetElementPtrInst* GEP = new GetElementPtrInst(ci->getOperand(1),indices,
618 ci->getOperand(1)->getName()+".strchr",ci);
619 ci->replaceAllUsesWith(GEP);
622 ci->replaceAllUsesWith(
623 ConstantPointerNull::get(PointerType::get(Type::SByteTy)));
625 ci->eraseFromParent();
630 /// This LibCallOptimization will simplify a call to the strcmp library
631 /// function. It optimizes out cases where one or both arguments are constant
632 /// and the result can be determined statically.
633 /// @brief Simplify the strcmp library function.
634 struct StrCmpOptimization : public LibCallOptimization
637 StrCmpOptimization() : LibCallOptimization("strcmp",
638 "Number of 'strcmp' calls simplified") {}
640 /// @brief Make sure that the "strcmp" function has the right prototype
641 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
643 if (f->getReturnType() == Type::IntTy && f->arg_size() == 2)
648 /// @brief Perform the strcmp optimization
649 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
651 // First, check to see if src and destination are the same. If they are,
652 // then the optimization is to replace the CallInst with a constant 0
653 // because the call is a no-op.
654 Value* s1 = ci->getOperand(1);
655 Value* s2 = ci->getOperand(2);
659 ci->replaceAllUsesWith(ConstantInt::get(Type::IntTy,0));
660 ci->eraseFromParent();
664 bool isstr_1 = false;
667 if (getConstantStringLength(s1,len_1,&A1))
672 // strcmp("",x) -> *x
674 new LoadInst(CastToCStr(s2,*ci), ci->getName()+".load",ci);
676 new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
677 ci->replaceAllUsesWith(cast);
678 ci->eraseFromParent();
683 bool isstr_2 = false;
686 if (getConstantStringLength(s2,len_2,&A2))
691 // strcmp(x,"") -> *x
693 new LoadInst(CastToCStr(s1,*ci),ci->getName()+".val",ci);
695 new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
696 ci->replaceAllUsesWith(cast);
697 ci->eraseFromParent();
702 if (isstr_1 && isstr_2)
704 // strcmp(x,y) -> cnst (if both x and y are constant strings)
705 std::string str1 = A1->getAsString();
706 std::string str2 = A2->getAsString();
707 int result = strcmp(str1.c_str(), str2.c_str());
708 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,result));
709 ci->eraseFromParent();
716 /// This LibCallOptimization will simplify a call to the strncmp library
717 /// function. It optimizes out cases where one or both arguments are constant
718 /// and the result can be determined statically.
719 /// @brief Simplify the strncmp library function.
720 struct StrNCmpOptimization : public LibCallOptimization
723 StrNCmpOptimization() : LibCallOptimization("strncmp",
724 "Number of 'strncmp' calls simplified") {}
726 /// @brief Make sure that the "strncmp" function has the right prototype
727 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
729 if (f->getReturnType() == Type::IntTy && f->arg_size() == 3)
734 /// @brief Perform the strncpy optimization
735 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
737 // First, check to see if src and destination are the same. If they are,
738 // then the optimization is to replace the CallInst with a constant 0
739 // because the call is a no-op.
740 Value* s1 = ci->getOperand(1);
741 Value* s2 = ci->getOperand(2);
744 // strncmp(x,x,l) -> 0
745 ci->replaceAllUsesWith(ConstantInt::get(Type::IntTy,0));
746 ci->eraseFromParent();
750 // Check the length argument, if it is Constant zero then the strings are
752 uint64_t len_arg = 0;
753 bool len_arg_is_const = false;
754 if (ConstantInt* len_CI = dyn_cast<ConstantInt>(ci->getOperand(3)))
756 len_arg_is_const = true;
757 len_arg = len_CI->getRawValue();
760 // strncmp(x,y,0) -> 0
761 ci->replaceAllUsesWith(ConstantInt::get(Type::IntTy,0));
762 ci->eraseFromParent();
767 bool isstr_1 = false;
770 if (getConstantStringLength(s1,len_1,&A1))
775 // strncmp("",x) -> *x
776 LoadInst* load = new LoadInst(s1,ci->getName()+".load",ci);
778 new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
779 ci->replaceAllUsesWith(cast);
780 ci->eraseFromParent();
785 bool isstr_2 = false;
788 if (getConstantStringLength(s2,len_2,&A2))
793 // strncmp(x,"") -> *x
794 LoadInst* load = new LoadInst(s2,ci->getName()+".val",ci);
796 new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
797 ci->replaceAllUsesWith(cast);
798 ci->eraseFromParent();
803 if (isstr_1 && isstr_2 && len_arg_is_const)
805 // strncmp(x,y,const) -> constant
806 std::string str1 = A1->getAsString();
807 std::string str2 = A2->getAsString();
808 int result = strncmp(str1.c_str(), str2.c_str(), len_arg);
809 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,result));
810 ci->eraseFromParent();
817 /// This LibCallOptimization will simplify a call to the strcpy library
818 /// function. Two optimizations are possible:
819 /// (1) If src and dest are the same and not volatile, just return dest
820 /// (2) If the src is a constant then we can convert to llvm.memmove
821 /// @brief Simplify the strcpy library function.
822 struct StrCpyOptimization : public LibCallOptimization
825 StrCpyOptimization() : LibCallOptimization("strcpy",
826 "Number of 'strcpy' calls simplified") {}
828 /// @brief Make sure that the "strcpy" function has the right prototype
829 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
831 if (f->getReturnType() == PointerType::get(Type::SByteTy))
832 if (f->arg_size() == 2)
834 Function::const_arg_iterator AI = f->arg_begin();
835 if (AI++->getType() == PointerType::get(Type::SByteTy))
836 if (AI->getType() == PointerType::get(Type::SByteTy))
838 // Indicate this is a suitable call type.
845 /// @brief Perform the strcpy optimization
846 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
848 // First, check to see if src and destination are the same. If they are,
849 // then the optimization is to replace the CallInst with the destination
850 // because the call is a no-op. Note that this corresponds to the
851 // degenerate strcpy(X,X) case which should have "undefined" results
852 // according to the C specification. However, it occurs sometimes and
853 // we optimize it as a no-op.
854 Value* dest = ci->getOperand(1);
855 Value* src = ci->getOperand(2);
858 ci->replaceAllUsesWith(dest);
859 ci->eraseFromParent();
863 // Get the length of the constant string referenced by the second operand,
864 // the "src" parameter. Fail the optimization if we can't get the length
865 // (note that getConstantStringLength does lots of checks to make sure this
868 if (!getConstantStringLength(ci->getOperand(2),len))
871 // If the constant string's length is zero we can optimize this by just
872 // doing a store of 0 at the first byte of the destination
875 new StoreInst(ConstantInt::get(Type::SByteTy,0),ci->getOperand(1),ci);
876 ci->replaceAllUsesWith(dest);
877 ci->eraseFromParent();
881 // Increment the length because we actually want to memcpy the null
882 // terminator as well.
885 // Extract some information from the instruction
886 Module* M = ci->getParent()->getParent()->getParent();
888 // We have enough information to now generate the memcpy call to
889 // do the concatenation for us.
890 std::vector<Value*> vals;
891 vals.push_back(dest); // destination
892 vals.push_back(src); // source
893 vals.push_back(ConstantUInt::get(Type::UIntTy,len)); // length
894 vals.push_back(ConstantUInt::get(Type::UIntTy,1)); // alignment
895 new CallInst(SLC.get_memcpy(), vals, "", ci);
897 // Finally, substitute the first operand of the strcat call for the
898 // strcat call itself since strcat returns its first operand; and,
899 // kill the strcat CallInst.
900 ci->replaceAllUsesWith(dest);
901 ci->eraseFromParent();
906 /// This LibCallOptimization will simplify a call to the strlen library
907 /// function by replacing it with a constant value if the string provided to
908 /// it is a constant array.
909 /// @brief Simplify the strlen library function.
910 struct StrLenOptimization : public LibCallOptimization
912 StrLenOptimization() : LibCallOptimization("strlen",
913 "Number of 'strlen' calls simplified") {}
915 /// @brief Make sure that the "strlen" function has the right prototype
916 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
918 if (f->getReturnType() == SLC.getTargetData()->getIntPtrType())
919 if (f->arg_size() == 1)
920 if (Function::const_arg_iterator AI = f->arg_begin())
921 if (AI->getType() == PointerType::get(Type::SByteTy))
926 /// @brief Perform the strlen optimization
927 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
929 // Make sure we're dealing with an sbyte* here.
930 Value* str = ci->getOperand(1);
931 if (str->getType() != PointerType::get(Type::SByteTy))
934 // Does the call to strlen have exactly one use?
936 // Is that single use a binary operator?
937 if (BinaryOperator* bop = dyn_cast<BinaryOperator>(ci->use_back()))
938 // Is it compared against a constant integer?
939 if (ConstantInt* CI = dyn_cast<ConstantInt>(bop->getOperand(1)))
941 // Get the value the strlen result is compared to
942 uint64_t val = CI->getRawValue();
944 // If its compared against length 0 with == or !=
946 (bop->getOpcode() == Instruction::SetEQ ||
947 bop->getOpcode() == Instruction::SetNE))
949 // strlen(x) != 0 -> *x != 0
950 // strlen(x) == 0 -> *x == 0
951 LoadInst* load = new LoadInst(str,str->getName()+".first",ci);
952 BinaryOperator* rbop = BinaryOperator::create(bop->getOpcode(),
953 load, ConstantSInt::get(Type::SByteTy,0),
954 bop->getName()+".strlen", ci);
955 bop->replaceAllUsesWith(rbop);
956 bop->eraseFromParent();
957 ci->eraseFromParent();
962 // Get the length of the constant string operand
964 if (!getConstantStringLength(ci->getOperand(1),len))
967 // strlen("xyz") -> 3 (for example)
968 const Type *Ty = SLC.getTargetData()->getIntPtrType();
970 ci->replaceAllUsesWith(ConstantSInt::get(Ty, len));
972 ci->replaceAllUsesWith(ConstantUInt::get(Ty, len));
974 ci->eraseFromParent();
979 /// IsOnlyUsedInEqualsComparison - Return true if it only matters that the value
980 /// is equal or not-equal to zero.
981 static bool IsOnlyUsedInEqualsZeroComparison(Instruction *I) {
982 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
984 Instruction *User = cast<Instruction>(*UI);
985 if (User->getOpcode() == Instruction::SetNE ||
986 User->getOpcode() == Instruction::SetEQ) {
987 if (isa<Constant>(User->getOperand(1)) &&
988 cast<Constant>(User->getOperand(1))->isNullValue())
990 } else if (CastInst *CI = dyn_cast<CastInst>(User))
991 if (CI->getType() == Type::BoolTy)
993 // Unknown instruction.
999 /// This memcmpOptimization will simplify a call to the memcmp library
1001 struct memcmpOptimization : public LibCallOptimization {
1002 /// @brief Default Constructor
1003 memcmpOptimization()
1004 : LibCallOptimization("memcmp", "Number of 'memcmp' calls simplified") {}
1006 /// @brief Make sure that the "memcmp" function has the right prototype
1007 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &TD) {
1008 Function::const_arg_iterator AI = F->arg_begin();
1009 if (F->arg_size() != 3 || !isa<PointerType>(AI->getType())) return false;
1010 if (!isa<PointerType>((++AI)->getType())) return false;
1011 if (!(++AI)->getType()->isInteger()) return false;
1012 if (!F->getReturnType()->isInteger()) return false;
1016 /// Because of alignment and instruction information that we don't have, we
1017 /// leave the bulk of this to the code generators.
1019 /// Note that we could do much more if we could force alignment on otherwise
1020 /// small aligned allocas, or if we could indicate that loads have a small
1022 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &TD) {
1023 Value *LHS = CI->getOperand(1), *RHS = CI->getOperand(2);
1025 // If the two operands are the same, return zero.
1027 // memcmp(s,s,x) -> 0
1028 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
1029 CI->eraseFromParent();
1033 // Make sure we have a constant length.
1034 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getOperand(3));
1035 if (!LenC) return false;
1036 uint64_t Len = LenC->getRawValue();
1038 // If the length is zero, this returns 0.
1041 // memcmp(s1,s2,0) -> 0
1042 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
1043 CI->eraseFromParent();
1046 // memcmp(S1,S2,1) -> *(ubyte*)S1 - *(ubyte*)S2
1047 const Type *UCharPtr = PointerType::get(Type::UByteTy);
1048 CastInst *Op1Cast = new CastInst(LHS, UCharPtr, LHS->getName(), CI);
1049 CastInst *Op2Cast = new CastInst(RHS, UCharPtr, RHS->getName(), CI);
1050 Value *S1V = new LoadInst(Op1Cast, LHS->getName()+".val", CI);
1051 Value *S2V = new LoadInst(Op2Cast, RHS->getName()+".val", CI);
1052 Value *RV = BinaryOperator::createSub(S1V, S2V, CI->getName()+".diff",CI);
1053 if (RV->getType() != CI->getType())
1054 RV = new CastInst(RV, CI->getType(), RV->getName(), CI);
1055 CI->replaceAllUsesWith(RV);
1056 CI->eraseFromParent();
1060 if (IsOnlyUsedInEqualsZeroComparison(CI)) {
1061 // TODO: IF both are aligned, use a short load/compare.
1063 // memcmp(S1,S2,2) -> S1[0]-S2[0] | S1[1]-S2[1] iff only ==/!= 0 matters
1064 const Type *UCharPtr = PointerType::get(Type::UByteTy);
1065 CastInst *Op1Cast = new CastInst(LHS, UCharPtr, LHS->getName(), CI);
1066 CastInst *Op2Cast = new CastInst(RHS, UCharPtr, RHS->getName(), CI);
1067 Value *S1V1 = new LoadInst(Op1Cast, LHS->getName()+".val1", CI);
1068 Value *S2V1 = new LoadInst(Op2Cast, RHS->getName()+".val1", CI);
1069 Value *D1 = BinaryOperator::createSub(S1V1, S2V1,
1070 CI->getName()+".d1", CI);
1071 Constant *One = ConstantInt::get(Type::IntTy, 1);
1072 Value *G1 = new GetElementPtrInst(Op1Cast, One, "next1v", CI);
1073 Value *G2 = new GetElementPtrInst(Op2Cast, One, "next2v", CI);
1074 Value *S1V2 = new LoadInst(G1, LHS->getName()+".val2", CI);
1075 Value *S2V2 = new LoadInst(G1, RHS->getName()+".val2", CI);
1076 Value *D2 = BinaryOperator::createSub(S1V2, S2V2,
1077 CI->getName()+".d1", CI);
1078 Value *Or = BinaryOperator::createOr(D1, D2, CI->getName()+".res", CI);
1079 if (Or->getType() != CI->getType())
1080 Or = new CastInst(Or, CI->getType(), Or->getName(), CI);
1081 CI->replaceAllUsesWith(Or);
1082 CI->eraseFromParent();
1100 /// This LibCallOptimization will simplify a call to the memcpy library
1101 /// function by expanding it out to a single store of size 0, 1, 2, 4, or 8
1102 /// bytes depending on the length of the string and the alignment. Additional
1103 /// optimizations are possible in code generation (sequence of immediate store)
1104 /// @brief Simplify the memcpy library function.
1105 struct LLVMMemCpyOptimization : public LibCallOptimization
1107 /// @brief Default Constructor
1108 LLVMMemCpyOptimization() : LibCallOptimization("llvm.memcpy",
1109 "Number of 'llvm.memcpy' calls simplified") {}
1112 /// @brief Subclass Constructor
1113 LLVMMemCpyOptimization(const char* fname, const char* desc)
1114 : LibCallOptimization(fname, desc) {}
1117 /// @brief Make sure that the "memcpy" function has the right prototype
1118 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& TD)
1120 // Just make sure this has 4 arguments per LLVM spec.
1121 return (f->arg_size() == 4);
1124 /// Because of alignment and instruction information that we don't have, we
1125 /// leave the bulk of this to the code generators. The optimization here just
1126 /// deals with a few degenerate cases where the length of the string and the
1127 /// alignment match the sizes of our intrinsic types so we can do a load and
1128 /// store instead of the memcpy call.
1129 /// @brief Perform the memcpy optimization.
1130 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& TD)
1132 // Make sure we have constant int values to work with
1133 ConstantInt* LEN = dyn_cast<ConstantInt>(ci->getOperand(3));
1136 ConstantInt* ALIGN = dyn_cast<ConstantInt>(ci->getOperand(4));
1140 // If the length is larger than the alignment, we can't optimize
1141 uint64_t len = LEN->getRawValue();
1142 uint64_t alignment = ALIGN->getRawValue();
1144 alignment = 1; // Alignment 0 is identity for alignment 1
1145 if (len > alignment)
1148 // Get the type we will cast to, based on size of the string
1149 Value* dest = ci->getOperand(1);
1150 Value* src = ci->getOperand(2);
1155 // memcpy(d,s,0,a) -> noop
1156 ci->eraseFromParent();
1158 case 1: castType = Type::SByteTy; break;
1159 case 2: castType = Type::ShortTy; break;
1160 case 4: castType = Type::IntTy; break;
1161 case 8: castType = Type::LongTy; break;
1166 // Cast source and dest to the right sized primitive and then load/store
1168 new CastInst(src,PointerType::get(castType),src->getName()+".cast",ci);
1169 CastInst* DestCast =
1170 new CastInst(dest,PointerType::get(castType),dest->getName()+".cast",ci);
1171 LoadInst* LI = new LoadInst(SrcCast,SrcCast->getName()+".val",ci);
1172 StoreInst* SI = new StoreInst(LI, DestCast, ci);
1173 ci->eraseFromParent();
1176 } LLVMMemCpyOptimizer;
1178 /// This LibCallOptimization will simplify a call to the memmove library
1179 /// function. It is identical to MemCopyOptimization except for the name of
1181 /// @brief Simplify the memmove library function.
1182 struct LLVMMemMoveOptimization : public LLVMMemCpyOptimization
1184 /// @brief Default Constructor
1185 LLVMMemMoveOptimization() : LLVMMemCpyOptimization("llvm.memmove",
1186 "Number of 'llvm.memmove' calls simplified") {}
1188 } LLVMMemMoveOptimizer;
1190 /// This LibCallOptimization will simplify a call to the memset library
1191 /// function by expanding it out to a single store of size 0, 1, 2, 4, or 8
1192 /// bytes depending on the length argument.
1193 struct LLVMMemSetOptimization : public LibCallOptimization
1195 /// @brief Default Constructor
1196 LLVMMemSetOptimization() : LibCallOptimization("llvm.memset",
1197 "Number of 'llvm.memset' calls simplified") {}
1201 /// @brief Make sure that the "memset" function has the right prototype
1202 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& TD)
1204 // Just make sure this has 3 arguments per LLVM spec.
1205 return (f->arg_size() == 4);
1208 /// Because of alignment and instruction information that we don't have, we
1209 /// leave the bulk of this to the code generators. The optimization here just
1210 /// deals with a few degenerate cases where the length parameter is constant
1211 /// and the alignment matches the sizes of our intrinsic types so we can do
1212 /// store instead of the memcpy call. Other calls are transformed into the
1213 /// llvm.memset intrinsic.
1214 /// @brief Perform the memset optimization.
1215 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& TD)
1217 // Make sure we have constant int values to work with
1218 ConstantInt* LEN = dyn_cast<ConstantInt>(ci->getOperand(3));
1221 ConstantInt* ALIGN = dyn_cast<ConstantInt>(ci->getOperand(4));
1225 // Extract the length and alignment
1226 uint64_t len = LEN->getRawValue();
1227 uint64_t alignment = ALIGN->getRawValue();
1229 // Alignment 0 is identity for alignment 1
1233 // If the length is zero, this is a no-op
1236 // memset(d,c,0,a) -> noop
1237 ci->eraseFromParent();
1241 // If the length is larger than the alignment, we can't optimize
1242 if (len > alignment)
1245 // Make sure we have a constant ubyte to work with so we can extract
1246 // the value to be filled.
1247 ConstantUInt* FILL = dyn_cast<ConstantUInt>(ci->getOperand(2));
1250 if (FILL->getType() != Type::UByteTy)
1253 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
1255 // Extract the fill character
1256 uint64_t fill_char = FILL->getValue();
1257 uint64_t fill_value = fill_char;
1259 // Get the type we will cast to, based on size of memory area to fill, and
1260 // and the value we will store there.
1261 Value* dest = ci->getOperand(1);
1266 castType = Type::UByteTy;
1269 castType = Type::UShortTy;
1270 fill_value |= fill_char << 8;
1273 castType = Type::UIntTy;
1274 fill_value |= fill_char << 8 | fill_char << 16 | fill_char << 24;
1277 castType = Type::ULongTy;
1278 fill_value |= fill_char << 8 | fill_char << 16 | fill_char << 24;
1279 fill_value |= fill_char << 32 | fill_char << 40 | fill_char << 48;
1280 fill_value |= fill_char << 56;
1286 // Cast dest to the right sized primitive and then load/store
1287 CastInst* DestCast =
1288 new CastInst(dest,PointerType::get(castType),dest->getName()+".cast",ci);
1289 new StoreInst(ConstantUInt::get(castType,fill_value),DestCast, ci);
1290 ci->eraseFromParent();
1293 } LLVMMemSetOptimizer;
1295 /// This LibCallOptimization will simplify calls to the "pow" library
1296 /// function. It looks for cases where the result of pow is well known and
1297 /// substitutes the appropriate value.
1298 /// @brief Simplify the pow library function.
1299 struct PowOptimization : public LibCallOptimization
1302 /// @brief Default Constructor
1303 PowOptimization() : LibCallOptimization("pow",
1304 "Number of 'pow' calls simplified") {}
1306 /// @brief Make sure that the "pow" function has the right prototype
1307 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1309 // Just make sure this has 2 arguments
1310 return (f->arg_size() == 2);
1313 /// @brief Perform the pow optimization.
1314 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1316 const Type *Ty = cast<Function>(ci->getOperand(0))->getReturnType();
1317 Value* base = ci->getOperand(1);
1318 Value* expn = ci->getOperand(2);
1319 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(base)) {
1320 double Op1V = Op1->getValue();
1323 // pow(1.0,x) -> 1.0
1324 ci->replaceAllUsesWith(ConstantFP::get(Ty,1.0));
1325 ci->eraseFromParent();
1329 else if (ConstantFP* Op2 = dyn_cast<ConstantFP>(expn))
1331 double Op2V = Op2->getValue();
1334 // pow(x,0.0) -> 1.0
1335 ci->replaceAllUsesWith(ConstantFP::get(Ty,1.0));
1336 ci->eraseFromParent();
1339 else if (Op2V == 0.5)
1341 // pow(x,0.5) -> sqrt(x)
1342 CallInst* sqrt_inst = new CallInst(SLC.get_sqrt(), base,
1343 ci->getName()+".pow",ci);
1344 ci->replaceAllUsesWith(sqrt_inst);
1345 ci->eraseFromParent();
1348 else if (Op2V == 1.0)
1351 ci->replaceAllUsesWith(base);
1352 ci->eraseFromParent();
1355 else if (Op2V == -1.0)
1357 // pow(x,-1.0) -> 1.0/x
1358 BinaryOperator* div_inst= BinaryOperator::createDiv(
1359 ConstantFP::get(Ty,1.0), base, ci->getName()+".pow", ci);
1360 ci->replaceAllUsesWith(div_inst);
1361 ci->eraseFromParent();
1365 return false; // opt failed
1369 /// This LibCallOptimization will simplify calls to the "fprintf" library
1370 /// function. It looks for cases where the result of fprintf is not used and the
1371 /// operation can be reduced to something simpler.
1372 /// @brief Simplify the pow library function.
1373 struct FPrintFOptimization : public LibCallOptimization
1376 /// @brief Default Constructor
1377 FPrintFOptimization() : LibCallOptimization("fprintf",
1378 "Number of 'fprintf' calls simplified") {}
1380 /// @brief Make sure that the "fprintf" function has the right prototype
1381 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1383 // Just make sure this has at least 2 arguments
1384 return (f->arg_size() >= 2);
1387 /// @brief Perform the fprintf optimization.
1388 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1390 // If the call has more than 3 operands, we can't optimize it
1391 if (ci->getNumOperands() > 4 || ci->getNumOperands() <= 2)
1394 // If the result of the fprintf call is used, none of these optimizations
1396 if (!ci->use_empty())
1399 // All the optimizations depend on the length of the second argument and the
1400 // fact that it is a constant string array. Check that now
1402 ConstantArray* CA = 0;
1403 if (!getConstantStringLength(ci->getOperand(2), len, &CA))
1406 if (ci->getNumOperands() == 3)
1408 // Make sure there's no % in the constant array
1409 for (unsigned i = 0; i < len; ++i)
1411 if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(i)))
1413 // Check for the null terminator
1414 if (CI->getRawValue() == '%')
1415 return false; // we found end of string
1421 // fprintf(file,fmt) -> fwrite(fmt,strlen(fmt),file)
1422 const Type* FILEptr_type = ci->getOperand(1)->getType();
1423 Function* fwrite_func = SLC.get_fwrite(FILEptr_type);
1427 // Make sure that the fprintf() and fwrite() functions both take the
1428 // same type of char pointer.
1429 if (ci->getOperand(2)->getType() !=
1430 fwrite_func->getFunctionType()->getParamType(0))
1433 std::vector<Value*> args;
1434 args.push_back(ci->getOperand(2));
1435 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
1436 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),1));
1437 args.push_back(ci->getOperand(1));
1438 new CallInst(fwrite_func,args,ci->getName(),ci);
1439 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,len));
1440 ci->eraseFromParent();
1444 // The remaining optimizations require the format string to be length 2
1449 // The first character has to be a %
1450 if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(0)))
1451 if (CI->getRawValue() != '%')
1454 // Get the second character and switch on its value
1455 ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(1));
1456 switch (CI->getRawValue())
1461 ConstantArray* CA = 0;
1462 if (!getConstantStringLength(ci->getOperand(3), len, &CA))
1465 // fprintf(file,"%s",str) -> fwrite(fmt,strlen(fmt),1,file)
1466 const Type* FILEptr_type = ci->getOperand(1)->getType();
1467 Function* fwrite_func = SLC.get_fwrite(FILEptr_type);
1470 std::vector<Value*> args;
1471 args.push_back(CastToCStr(ci->getOperand(3), *ci));
1472 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
1473 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),1));
1474 args.push_back(ci->getOperand(1));
1475 new CallInst(fwrite_func,args,ci->getName(),ci);
1476 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,len));
1481 ConstantInt* CI = dyn_cast<ConstantInt>(ci->getOperand(3));
1485 const Type* FILEptr_type = ci->getOperand(1)->getType();
1486 Function* fputc_func = SLC.get_fputc(FILEptr_type);
1489 CastInst* cast = new CastInst(CI,Type::IntTy,CI->getName()+".int",ci);
1490 new CallInst(fputc_func,cast,ci->getOperand(1),"",ci);
1491 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,1));
1497 ci->eraseFromParent();
1502 /// This LibCallOptimization will simplify calls to the "sprintf" library
1503 /// function. It looks for cases where the result of sprintf is not used and the
1504 /// operation can be reduced to something simpler.
1505 /// @brief Simplify the pow library function.
1506 struct SPrintFOptimization : public LibCallOptimization
1509 /// @brief Default Constructor
1510 SPrintFOptimization() : LibCallOptimization("sprintf",
1511 "Number of 'sprintf' calls simplified") {}
1513 /// @brief Make sure that the "fprintf" function has the right prototype
1514 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1516 // Just make sure this has at least 2 arguments
1517 return (f->getReturnType() == Type::IntTy && f->arg_size() >= 2);
1520 /// @brief Perform the sprintf optimization.
1521 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1523 // If the call has more than 3 operands, we can't optimize it
1524 if (ci->getNumOperands() > 4 || ci->getNumOperands() < 3)
1527 // All the optimizations depend on the length of the second argument and the
1528 // fact that it is a constant string array. Check that now
1530 ConstantArray* CA = 0;
1531 if (!getConstantStringLength(ci->getOperand(2), len, &CA))
1534 if (ci->getNumOperands() == 3)
1538 // If the length is 0, we just need to store a null byte
1539 new StoreInst(ConstantInt::get(Type::SByteTy,0),ci->getOperand(1),ci);
1540 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,0));
1541 ci->eraseFromParent();
1545 // Make sure there's no % in the constant array
1546 for (unsigned i = 0; i < len; ++i)
1548 if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(i)))
1550 // Check for the null terminator
1551 if (CI->getRawValue() == '%')
1552 return false; // we found a %, can't optimize
1555 return false; // initializer is not constant int, can't optimize
1558 // Increment length because we want to copy the null byte too
1561 // sprintf(str,fmt) -> llvm.memcpy(str,fmt,strlen(fmt),1)
1562 Function* memcpy_func = SLC.get_memcpy();
1565 std::vector<Value*> args;
1566 args.push_back(ci->getOperand(1));
1567 args.push_back(ci->getOperand(2));
1568 args.push_back(ConstantUInt::get(Type::UIntTy,len));
1569 args.push_back(ConstantUInt::get(Type::UIntTy,1));
1570 new CallInst(memcpy_func,args,"",ci);
1571 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,len));
1572 ci->eraseFromParent();
1576 // The remaining optimizations require the format string to be length 2
1581 // The first character has to be a %
1582 if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(0)))
1583 if (CI->getRawValue() != '%')
1586 // Get the second character and switch on its value
1587 ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(1));
1588 switch (CI->getRawValue()) {
1590 // sprintf(dest,"%s",str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1591 Function* strlen_func = SLC.get_strlen();
1592 Function* memcpy_func = SLC.get_memcpy();
1593 if (!strlen_func || !memcpy_func)
1596 Value *Len = new CallInst(strlen_func, CastToCStr(ci->getOperand(3), *ci),
1597 ci->getOperand(3)->getName()+".len", ci);
1598 Value *Len1 = BinaryOperator::createAdd(Len,
1599 ConstantInt::get(Len->getType(), 1),
1600 Len->getName()+"1", ci);
1601 if (Len1->getType() != Type::UIntTy)
1602 Len1 = new CastInst(Len1, Type::UIntTy, Len1->getName(), ci);
1603 std::vector<Value*> args;
1604 args.push_back(CastToCStr(ci->getOperand(1), *ci));
1605 args.push_back(CastToCStr(ci->getOperand(3), *ci));
1606 args.push_back(Len1);
1607 args.push_back(ConstantUInt::get(Type::UIntTy,1));
1608 new CallInst(memcpy_func, args, "", ci);
1610 // The strlen result is the unincremented number of bytes in the string.
1611 if (!ci->use_empty()) {
1612 if (Len->getType() != ci->getType())
1613 Len = new CastInst(Len, ci->getType(), Len->getName(), ci);
1614 ci->replaceAllUsesWith(Len);
1616 ci->eraseFromParent();
1620 // sprintf(dest,"%c",chr) -> store chr, dest
1621 CastInst* cast = new CastInst(ci->getOperand(3),Type::SByteTy,"char",ci);
1622 new StoreInst(cast, ci->getOperand(1), ci);
1623 GetElementPtrInst* gep = new GetElementPtrInst(ci->getOperand(1),
1624 ConstantUInt::get(Type::UIntTy,1),ci->getOperand(1)->getName()+".end",
1626 new StoreInst(ConstantInt::get(Type::SByteTy,0),gep,ci);
1627 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,1));
1628 ci->eraseFromParent();
1636 /// This LibCallOptimization will simplify calls to the "fputs" library
1637 /// function. It looks for cases where the result of fputs is not used and the
1638 /// operation can be reduced to something simpler.
1639 /// @brief Simplify the pow library function.
1640 struct PutsOptimization : public LibCallOptimization
1643 /// @brief Default Constructor
1644 PutsOptimization() : LibCallOptimization("fputs",
1645 "Number of 'fputs' calls simplified") {}
1647 /// @brief Make sure that the "fputs" function has the right prototype
1648 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1650 // Just make sure this has 2 arguments
1651 return (f->arg_size() == 2);
1654 /// @brief Perform the fputs optimization.
1655 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1657 // If the result is used, none of these optimizations work
1658 if (!ci->use_empty())
1661 // All the optimizations depend on the length of the first argument and the
1662 // fact that it is a constant string array. Check that now
1664 if (!getConstantStringLength(ci->getOperand(1), len))
1670 // fputs("",F) -> noop
1674 // fputs(s,F) -> fputc(s[0],F) (if s is constant and strlen(s) == 1)
1675 const Type* FILEptr_type = ci->getOperand(2)->getType();
1676 Function* fputc_func = SLC.get_fputc(FILEptr_type);
1679 LoadInst* loadi = new LoadInst(ci->getOperand(1),
1680 ci->getOperand(1)->getName()+".byte",ci);
1681 CastInst* casti = new CastInst(loadi,Type::IntTy,
1682 loadi->getName()+".int",ci);
1683 new CallInst(fputc_func,casti,ci->getOperand(2),"",ci);
1688 // fputs(s,F) -> fwrite(s,1,len,F) (if s is constant and strlen(s) > 1)
1689 const Type* FILEptr_type = ci->getOperand(2)->getType();
1690 Function* fwrite_func = SLC.get_fwrite(FILEptr_type);
1693 std::vector<Value*> parms;
1694 parms.push_back(ci->getOperand(1));
1695 parms.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
1696 parms.push_back(ConstantUInt::get(SLC.getIntPtrType(),1));
1697 parms.push_back(ci->getOperand(2));
1698 new CallInst(fwrite_func,parms,"",ci);
1702 ci->eraseFromParent();
1703 return true; // success
1707 /// This LibCallOptimization will simplify calls to the "isdigit" library
1708 /// function. It simply does range checks the parameter explicitly.
1709 /// @brief Simplify the isdigit library function.
1710 struct isdigitOptimization : public LibCallOptimization {
1712 isdigitOptimization() : LibCallOptimization("isdigit",
1713 "Number of 'isdigit' calls simplified") {}
1715 /// @brief Make sure that the "isdigit" function has the right prototype
1716 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1718 // Just make sure this has 1 argument
1719 return (f->arg_size() == 1);
1722 /// @brief Perform the toascii optimization.
1723 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1725 if (ConstantInt* CI = dyn_cast<ConstantInt>(ci->getOperand(1)))
1727 // isdigit(c) -> 0 or 1, if 'c' is constant
1728 uint64_t val = CI->getRawValue();
1729 if (val >= '0' && val <='9')
1730 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,1));
1732 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,0));
1733 ci->eraseFromParent();
1737 // isdigit(c) -> (unsigned)c - '0' <= 9
1739 new CastInst(ci->getOperand(1),Type::UIntTy,
1740 ci->getOperand(1)->getName()+".uint",ci);
1741 BinaryOperator* sub_inst = BinaryOperator::createSub(cast,
1742 ConstantUInt::get(Type::UIntTy,0x30),
1743 ci->getOperand(1)->getName()+".sub",ci);
1744 SetCondInst* setcond_inst = new SetCondInst(Instruction::SetLE,sub_inst,
1745 ConstantUInt::get(Type::UIntTy,9),
1746 ci->getOperand(1)->getName()+".cmp",ci);
1748 new CastInst(setcond_inst,Type::IntTy,
1749 ci->getOperand(1)->getName()+".isdigit",ci);
1750 ci->replaceAllUsesWith(c2);
1751 ci->eraseFromParent();
1756 struct isasciiOptimization : public LibCallOptimization {
1758 isasciiOptimization()
1759 : LibCallOptimization("isascii", "Number of 'isascii' calls simplified") {}
1761 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
1762 return F->arg_size() == 1 && F->arg_begin()->getType()->isInteger() &&
1763 F->getReturnType()->isInteger();
1766 /// @brief Perform the isascii optimization.
1767 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1768 // isascii(c) -> (unsigned)c < 128
1769 Value *V = CI->getOperand(1);
1770 if (V->getType()->isSigned())
1771 V = new CastInst(V, V->getType()->getUnsignedVersion(), V->getName(), CI);
1772 Value *Cmp = BinaryOperator::createSetLT(V, ConstantUInt::get(V->getType(),
1774 V->getName()+".isascii", CI);
1775 if (Cmp->getType() != CI->getType())
1776 Cmp = new CastInst(Cmp, CI->getType(), Cmp->getName(), CI);
1777 CI->replaceAllUsesWith(Cmp);
1778 CI->eraseFromParent();
1784 /// This LibCallOptimization will simplify calls to the "toascii" library
1785 /// function. It simply does the corresponding and operation to restrict the
1786 /// range of values to the ASCII character set (0-127).
1787 /// @brief Simplify the toascii library function.
1788 struct ToAsciiOptimization : public LibCallOptimization
1791 /// @brief Default Constructor
1792 ToAsciiOptimization() : LibCallOptimization("toascii",
1793 "Number of 'toascii' calls simplified") {}
1795 /// @brief Make sure that the "fputs" function has the right prototype
1796 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1798 // Just make sure this has 2 arguments
1799 return (f->arg_size() == 1);
1802 /// @brief Perform the toascii optimization.
1803 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1805 // toascii(c) -> (c & 0x7f)
1806 Value* chr = ci->getOperand(1);
1807 BinaryOperator* and_inst = BinaryOperator::createAnd(chr,
1808 ConstantInt::get(chr->getType(),0x7F),ci->getName()+".toascii",ci);
1809 ci->replaceAllUsesWith(and_inst);
1810 ci->eraseFromParent();
1815 /// This LibCallOptimization will simplify calls to the "ffs" library
1816 /// calls which find the first set bit in an int, long, or long long. The
1817 /// optimization is to compute the result at compile time if the argument is
1819 /// @brief Simplify the ffs library function.
1820 struct FFSOptimization : public LibCallOptimization {
1822 /// @brief Subclass Constructor
1823 FFSOptimization(const char* funcName, const char* description)
1824 : LibCallOptimization(funcName, description) {}
1827 /// @brief Default Constructor
1828 FFSOptimization() : LibCallOptimization("ffs",
1829 "Number of 'ffs' calls simplified") {}
1831 /// @brief Make sure that the "ffs" function has the right prototype
1832 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
1833 // Just make sure this has 2 arguments
1834 return F->arg_size() == 1 && F->getReturnType() == Type::IntTy;
1837 /// @brief Perform the ffs optimization.
1838 virtual bool OptimizeCall(CallInst *TheCall, SimplifyLibCalls &SLC) {
1839 if (ConstantInt *CI = dyn_cast<ConstantInt>(TheCall->getOperand(1))) {
1840 // ffs(cnst) -> bit#
1841 // ffsl(cnst) -> bit#
1842 // ffsll(cnst) -> bit#
1843 uint64_t val = CI->getRawValue();
1847 while ((val & 1) == 0) {
1852 TheCall->replaceAllUsesWith(ConstantSInt::get(Type::IntTy, result));
1853 TheCall->eraseFromParent();
1857 // ffs(x) -> x == 0 ? 0 : llvm.cttz(x)+1
1858 // ffsl(x) -> x == 0 ? 0 : llvm.cttz(x)+1
1859 // ffsll(x) -> x == 0 ? 0 : llvm.cttz(x)+1
1860 const Type *ArgType = TheCall->getOperand(1)->getType();
1861 ArgType = ArgType->getUnsignedVersion();
1862 const char *CTTZName;
1863 switch (ArgType->getTypeID()) {
1864 default: assert(0 && "Unknown unsigned type!");
1865 case Type::UByteTyID : CTTZName = "llvm.cttz.i8" ; break;
1866 case Type::UShortTyID: CTTZName = "llvm.cttz.i16"; break;
1867 case Type::UIntTyID : CTTZName = "llvm.cttz.i32"; break;
1868 case Type::ULongTyID : CTTZName = "llvm.cttz.i64"; break;
1871 Function *F = SLC.getModule()->getOrInsertFunction(CTTZName, ArgType,
1873 Value *V = new CastInst(TheCall->getOperand(1), ArgType, "tmp", TheCall);
1874 Value *V2 = new CallInst(F, V, "tmp", TheCall);
1875 V2 = new CastInst(V2, Type::IntTy, "tmp", TheCall);
1876 V2 = BinaryOperator::createAdd(V2, ConstantSInt::get(Type::IntTy, 1),
1879 BinaryOperator::createSetEQ(V, Constant::getNullValue(V->getType()),
1881 V2 = new SelectInst(Cond, ConstantInt::get(Type::IntTy, 0), V2,
1882 TheCall->getName(), TheCall);
1883 TheCall->replaceAllUsesWith(V2);
1884 TheCall->eraseFromParent();
1889 /// This LibCallOptimization will simplify calls to the "ffsl" library
1890 /// calls. It simply uses FFSOptimization for which the transformation is
1892 /// @brief Simplify the ffsl library function.
1893 struct FFSLOptimization : public FFSOptimization
1896 /// @brief Default Constructor
1897 FFSLOptimization() : FFSOptimization("ffsl",
1898 "Number of 'ffsl' calls simplified") {}
1902 /// This LibCallOptimization will simplify calls to the "ffsll" library
1903 /// calls. It simply uses FFSOptimization for which the transformation is
1905 /// @brief Simplify the ffsl library function.
1906 struct FFSLLOptimization : public FFSOptimization
1909 /// @brief Default Constructor
1910 FFSLLOptimization() : FFSOptimization("ffsll",
1911 "Number of 'ffsll' calls simplified") {}
1917 /// This LibCallOptimization will simplify calls to the "floor" library
1919 /// @brief Simplify the floor library function.
1920 struct FloorOptimization : public LibCallOptimization {
1922 : LibCallOptimization("floor", "Number of 'floor' calls simplified") {}
1924 /// @brief Make sure that the "floor" function has the right prototype
1925 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
1926 return F->arg_size() == 1 && F->arg_begin()->getType() == Type::DoubleTy &&
1927 F->getReturnType() == Type::DoubleTy;
1930 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1931 // If this is a float argument passed in, convert to floorf.
1932 // e.g. floor((double)FLT) -> (double)floorf(FLT). There can be no loss of
1933 // precision due to this.
1934 if (CastInst *Cast = dyn_cast<CastInst>(CI->getOperand(1)))
1935 if (Cast->getOperand(0)->getType() == Type::FloatTy) {
1936 Value *New = new CallInst(SLC.get_floorf(), Cast->getOperand(0),
1938 New = new CastInst(New, Type::DoubleTy, CI->getName(), CI);
1939 CI->replaceAllUsesWith(New);
1940 CI->eraseFromParent();
1941 if (Cast->use_empty())
1942 Cast->eraseFromParent();
1945 return false; // opt failed
1952 /// A function to compute the length of a null-terminated constant array of
1953 /// integers. This function can't rely on the size of the constant array
1954 /// because there could be a null terminator in the middle of the array.
1955 /// We also have to bail out if we find a non-integer constant initializer
1956 /// of one of the elements or if there is no null-terminator. The logic
1957 /// below checks each of these conditions and will return true only if all
1958 /// conditions are met. In that case, the \p len parameter is set to the length
1959 /// of the null-terminated string. If false is returned, the conditions were
1960 /// not met and len is set to 0.
1961 /// @brief Get the length of a constant string (null-terminated array).
1962 bool getConstantStringLength(Value* V, uint64_t& len, ConstantArray** CA )
1964 assert(V != 0 && "Invalid args to getConstantStringLength");
1965 len = 0; // make sure we initialize this
1967 // If the value is not a GEP instruction nor a constant expression with a
1968 // GEP instruction, then return false because ConstantArray can't occur
1970 if (GetElementPtrInst* GEPI = dyn_cast<GetElementPtrInst>(V))
1972 else if (ConstantExpr* CE = dyn_cast<ConstantExpr>(V))
1973 if (CE->getOpcode() == Instruction::GetElementPtr)
1980 // Make sure the GEP has exactly three arguments.
1981 if (GEP->getNumOperands() != 3)
1984 // Check to make sure that the first operand of the GEP is an integer and
1985 // has value 0 so that we are sure we're indexing into the initializer.
1986 if (ConstantInt* op1 = dyn_cast<ConstantInt>(GEP->getOperand(1)))
1988 if (!op1->isNullValue())
1994 // Ensure that the second operand is a ConstantInt. If it isn't then this
1995 // GEP is wonky and we're not really sure what were referencing into and
1996 // better of not optimizing it. While we're at it, get the second index
1997 // value. We'll need this later for indexing the ConstantArray.
1998 uint64_t start_idx = 0;
1999 if (ConstantInt* CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
2000 start_idx = CI->getRawValue();
2004 // The GEP instruction, constant or instruction, must reference a global
2005 // variable that is a constant and is initialized. The referenced constant
2006 // initializer is the array that we'll use for optimization.
2007 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2008 if (!GV || !GV->isConstant() || !GV->hasInitializer())
2011 // Get the initializer.
2012 Constant* INTLZR = GV->getInitializer();
2014 // Handle the ConstantAggregateZero case
2015 if (ConstantAggregateZero* CAZ = dyn_cast<ConstantAggregateZero>(INTLZR))
2017 // This is a degenerate case. The initializer is constant zero so the
2018 // length of the string must be zero.
2023 // Must be a Constant Array
2024 ConstantArray* A = dyn_cast<ConstantArray>(INTLZR);
2028 // Get the number of elements in the array
2029 uint64_t max_elems = A->getType()->getNumElements();
2031 // Traverse the constant array from start_idx (derived above) which is
2032 // the place the GEP refers to in the array.
2033 for ( len = start_idx; len < max_elems; len++)
2035 if (ConstantInt* CI = dyn_cast<ConstantInt>(A->getOperand(len)))
2037 // Check for the null terminator
2038 if (CI->isNullValue())
2039 break; // we found end of string
2042 return false; // This array isn't suitable, non-int initializer
2044 if (len >= max_elems)
2045 return false; // This array isn't null terminated
2047 // Subtract out the initial value from the length
2051 return true; // success!
2054 /// CastToCStr - Return V if it is an sbyte*, otherwise cast it to sbyte*,
2055 /// inserting the cast before IP, and return the cast.
2056 /// @brief Cast a value to a "C" string.
2057 Value *CastToCStr(Value *V, Instruction &IP) {
2058 const Type *SBPTy = PointerType::get(Type::SByteTy);
2059 if (V->getType() != SBPTy)
2060 return new CastInst(V, SBPTy, V->getName(), &IP);
2065 // Additional cases that we need to add to this file:
2068 // * cbrt(expN(X)) -> expN(x/3)
2069 // * cbrt(sqrt(x)) -> pow(x,1/6)
2070 // * cbrt(sqrt(x)) -> pow(x,1/9)
2073 // * cos(-x) -> cos(x)
2076 // * exp(log(x)) -> x
2079 // * log(exp(x)) -> x
2080 // * log(x**y) -> y*log(x)
2081 // * log(exp(y)) -> y*log(e)
2082 // * log(exp2(y)) -> y*log(2)
2083 // * log(exp10(y)) -> y*log(10)
2084 // * log(sqrt(x)) -> 0.5*log(x)
2085 // * log(pow(x,y)) -> y*log(x)
2087 // lround, lroundf, lroundl:
2088 // * lround(cnst) -> cnst'
2091 // * memcmp(x,y,l) -> cnst
2092 // (if all arguments are constant and strlen(x) <= l and strlen(y) <= l)
2095 // * memmove(d,s,l,a) -> memcpy(d,s,l,a)
2096 // (if s is a global constant array)
2099 // * pow(exp(x),y) -> exp(x*y)
2100 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2101 // * pow(pow(x,y),z)-> pow(x,y*z)
2104 // * puts("") -> fputc("\n",stdout) (how do we get "stdout"?)
2106 // round, roundf, roundl:
2107 // * round(cnst) -> cnst'
2110 // * signbit(cnst) -> cnst'
2111 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2113 // sqrt, sqrtf, sqrtl:
2114 // * sqrt(expN(x)) -> expN(x*0.5)
2115 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2116 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2119 // * stpcpy(str, "literal") ->
2120 // llvm.memcpy(str,"literal",strlen("literal")+1,1)
2122 // * strrchr(s,c) -> reverse_offset_of_in(c,s)
2123 // (if c is a constant integer and s is a constant string)
2124 // * strrchr(s1,0) -> strchr(s1,0)
2127 // * strncat(x,y,0) -> x
2128 // * strncat(x,y,0) -> x (if strlen(y) = 0)
2129 // * strncat(x,y,l) -> strcat(x,y) (if y and l are constants an l > strlen(y))
2132 // * strncpy(d,s,0) -> d
2133 // * strncpy(d,s,l) -> memcpy(d,s,l,1)
2134 // (if s and l are constants)
2137 // * strpbrk(s,a) -> offset_in_for(s,a)
2138 // (if s and a are both constant strings)
2139 // * strpbrk(s,"") -> 0
2140 // * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
2143 // * strspn(s,a) -> const_int (if both args are constant)
2144 // * strspn("",a) -> 0
2145 // * strspn(s,"") -> 0
2146 // * strcspn(s,a) -> const_int (if both args are constant)
2147 // * strcspn("",a) -> 0
2148 // * strcspn(s,"") -> strlen(a)
2151 // * strstr(x,x) -> x
2152 // * strstr(s1,s2) -> offset_of_s2_in(s1)
2153 // (if s1 and s2 are constant strings)
2156 // * tan(atan(x)) -> x
2158 // trunc, truncf, truncl:
2159 // * trunc(cnst) -> cnst'