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()
221 std::vector<const Type*> args;
222 args.push_back(Type::IntTy);
223 const Type* FILE_type = M->getTypeByName("struct._IO_FILE");
225 FILE_type = M->getTypeByName("struct._FILE");
228 args.push_back(PointerType::get(FILE_type));
229 FunctionType* fputc_type =
230 FunctionType::get(Type::IntTy, args, false);
231 fputc_func = M->getOrInsertFunction("fputc",fputc_type);
236 /// @brief Return a Function* for the fwrite libcall
237 Function* get_fwrite()
241 std::vector<const Type*> args;
242 args.push_back(PointerType::get(Type::SByteTy));
243 args.push_back(TD->getIntPtrType());
244 args.push_back(TD->getIntPtrType());
245 const Type* FILE_type = M->getTypeByName("struct._IO_FILE");
247 FILE_type = M->getTypeByName("struct._FILE");
250 args.push_back(PointerType::get(FILE_type));
251 FunctionType* fwrite_type =
252 FunctionType::get(TD->getIntPtrType(), args, false);
253 fwrite_func = M->getOrInsertFunction("fwrite",fwrite_type);
258 /// @brief Return a Function* for the sqrt libcall
263 std::vector<const Type*> args;
264 args.push_back(Type::DoubleTy);
265 FunctionType* sqrt_type =
266 FunctionType::get(Type::DoubleTy, args, false);
267 sqrt_func = M->getOrInsertFunction("sqrt",sqrt_type);
272 /// @brief Return a Function* for the strlen libcall
273 Function* get_strlen()
277 std::vector<const Type*> args;
278 args.push_back(PointerType::get(Type::SByteTy));
279 FunctionType* strlen_type =
280 FunctionType::get(TD->getIntPtrType(), args, false);
281 strlen_func = M->getOrInsertFunction("strlen",strlen_type);
286 /// @brief Return a Function* for the memcpy libcall
287 Function* get_memcpy()
291 // Note: this is for llvm.memcpy intrinsic
292 std::vector<const Type*> args;
293 args.push_back(PointerType::get(Type::SByteTy));
294 args.push_back(PointerType::get(Type::SByteTy));
295 args.push_back(Type::IntTy);
296 args.push_back(Type::IntTy);
297 FunctionType* memcpy_type = FunctionType::get(Type::VoidTy, args, false);
298 memcpy_func = M->getOrInsertFunction("llvm.memcpy",memcpy_type);
304 /// @brief Reset our cached data for a new Module
305 void reset(Module& mod)
308 TD = &getAnalysis<TargetData>();
317 Function* fputc_func; ///< Cached fputc function
318 Function* fwrite_func; ///< Cached fwrite function
319 Function* memcpy_func; ///< Cached llvm.memcpy function
320 Function* sqrt_func; ///< Cached sqrt function
321 Function* strlen_func; ///< Cached strlen function
322 Module* M; ///< Cached Module
323 TargetData* TD; ///< Cached TargetData
327 RegisterOpt<SimplifyLibCalls>
328 X("simplify-libcalls","Simplify well-known library calls");
330 } // anonymous namespace
332 // The only public symbol in this file which just instantiates the pass object
333 ModulePass *llvm::createSimplifyLibCallsPass()
335 return new SimplifyLibCalls();
338 // Classes below here, in the anonymous namespace, are all subclasses of the
339 // LibCallOptimization class, each implementing all optimizations possible for a
340 // single well-known library call. Each has a static singleton instance that
341 // auto registers it into the "optlist" global above.
344 // Forward declare a utility function.
345 bool getConstantStringLength(Value* V, uint64_t& len );
347 /// This LibCallOptimization will find instances of a call to "exit" that occurs
348 /// within the "main" function and change it to a simple "ret" instruction with
349 /// the same value passed to the exit function. When this is done, it splits the
350 /// basic block at the exit(3) call and deletes the call instruction.
351 /// @brief Replace calls to exit in main with a simple return
352 struct ExitInMainOptimization : public LibCallOptimization
354 ExitInMainOptimization() : LibCallOptimization("exit") {}
355 virtual ~ExitInMainOptimization() {}
357 // Make sure the called function looks like exit (int argument, int return
358 // type, external linkage, not varargs).
359 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
361 if (f->arg_size() >= 1)
362 if (f->arg_begin()->getType()->isInteger())
367 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
369 // To be careful, we check that the call to exit is coming from "main", that
370 // main has external linkage, and the return type of main and the argument
371 // to exit have the same type.
372 Function *from = ci->getParent()->getParent();
373 if (from->hasExternalLinkage())
374 if (from->getReturnType() == ci->getOperand(1)->getType())
375 if (from->getName() == "main")
377 // Okay, time to actually do the optimization. First, get the basic
378 // block of the call instruction
379 BasicBlock* bb = ci->getParent();
381 // Create a return instruction that we'll replace the call with.
382 // Note that the argument of the return is the argument of the call
384 ReturnInst* ri = new ReturnInst(ci->getOperand(1), ci);
386 // Split the block at the call instruction which places it in a new
388 bb->splitBasicBlock(ci);
390 // The block split caused a branch instruction to be inserted into
391 // the end of the original block, right after the return instruction
392 // that we put there. That's not a valid block, so delete the branch
394 bb->getInstList().pop_back();
396 // Now we can finally get rid of the call instruction which now lives
397 // in the new basic block.
398 ci->eraseFromParent();
400 // Optimization succeeded, return true.
403 // We didn't pass the criteria for this optimization so return false
406 } ExitInMainOptimizer;
408 /// This LibCallOptimization will simplify a call to the strcat library
409 /// function. The simplification is possible only if the string being
410 /// concatenated is a constant array or a constant expression that results in
411 /// a constant string. In this case we can replace it with strlen + llvm.memcpy
412 /// of the constant string. Both of these calls are further reduced, if possible
413 /// on subsequent passes.
414 /// @brief Simplify the strcat library function.
415 struct StrCatOptimization : public LibCallOptimization
418 /// @brief Default constructor
419 StrCatOptimization() : LibCallOptimization("strcat") {}
422 /// @breif Destructor
423 virtual ~StrCatOptimization() {}
425 /// @brief Make sure that the "strcat" function has the right prototype
426 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
428 if (f->getReturnType() == PointerType::get(Type::SByteTy))
429 if (f->arg_size() == 2)
431 Function::const_arg_iterator AI = f->arg_begin();
432 if (AI++->getType() == PointerType::get(Type::SByteTy))
433 if (AI->getType() == PointerType::get(Type::SByteTy))
435 // Indicate this is a suitable call type.
442 /// @brief Optimize the strcat library function
443 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
445 // Extract some information from the instruction
446 Module* M = ci->getParent()->getParent()->getParent();
447 Value* dest = ci->getOperand(1);
448 Value* src = ci->getOperand(2);
450 // Extract the initializer (while making numerous checks) from the
451 // source operand of the call to strcat. If we get null back, one of
452 // a variety of checks in get_GVInitializer failed
454 if (!getConstantStringLength(src,len))
457 // Handle the simple, do-nothing case
460 ci->replaceAllUsesWith(dest);
461 ci->eraseFromParent();
465 // Increment the length because we actually want to memcpy the null
466 // terminator as well.
469 // We need to find the end of the destination string. That's where the
470 // memory is to be moved to. We just generate a call to strlen (further
471 // optimized in another pass). Note that the SLC.get_strlen() call
472 // caches the Function* for us.
473 CallInst* strlen_inst =
474 new CallInst(SLC.get_strlen(), dest, dest->getName()+".len",ci);
476 // Now that we have the destination's length, we must index into the
477 // destination's pointer to get the actual memcpy destination (end of
478 // the string .. we're concatenating).
479 std::vector<Value*> idx;
480 idx.push_back(strlen_inst);
481 GetElementPtrInst* gep =
482 new GetElementPtrInst(dest,idx,dest->getName()+".indexed",ci);
484 // We have enough information to now generate the memcpy call to
485 // do the concatenation for us.
486 std::vector<Value*> vals;
487 vals.push_back(gep); // destination
488 vals.push_back(ci->getOperand(2)); // source
489 vals.push_back(ConstantSInt::get(Type::IntTy,len)); // length
490 vals.push_back(ConstantSInt::get(Type::IntTy,1)); // alignment
491 new CallInst(SLC.get_memcpy(), vals, "", ci);
493 // Finally, substitute the first operand of the strcat call for the
494 // strcat call itself since strcat returns its first operand; and,
495 // kill the strcat CallInst.
496 ci->replaceAllUsesWith(dest);
497 ci->eraseFromParent();
502 /// This LibCallOptimization will simplify a call to the strcpy library
503 /// function. Two optimizations are possible:
504 /// (1) If src and dest are the same and not volatile, just return dest
505 /// (2) If the src is a constant then we can convert to llvm.memmove
506 /// @brief Simplify the strcpy library function.
507 struct StrCpyOptimization : public LibCallOptimization
510 StrCpyOptimization() : LibCallOptimization("strcpy") {}
511 virtual ~StrCpyOptimization() {}
513 /// @brief Make sure that the "strcpy" function has the right prototype
514 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
516 if (f->getReturnType() == PointerType::get(Type::SByteTy))
517 if (f->arg_size() == 2)
519 Function::const_arg_iterator AI = f->arg_begin();
520 if (AI++->getType() == PointerType::get(Type::SByteTy))
521 if (AI->getType() == PointerType::get(Type::SByteTy))
523 // Indicate this is a suitable call type.
530 /// @brief Perform the strcpy optimization
531 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
533 // First, check to see if src and destination are the same. If they are,
534 // then the optimization is to replace the CallInst with the destination
535 // because the call is a no-op. Note that this corresponds to the
536 // degenerate strcpy(X,X) case which should have "undefined" results
537 // according to the C specification. However, it occurs sometimes and
538 // we optimize it as a no-op.
539 Value* dest = ci->getOperand(1);
540 Value* src = ci->getOperand(2);
543 ci->replaceAllUsesWith(dest);
544 ci->eraseFromParent();
548 // Get the length of the constant string referenced by the second operand,
549 // the "src" parameter. Fail the optimization if we can't get the length
550 // (note that getConstantStringLength does lots of checks to make sure this
553 if (!getConstantStringLength(ci->getOperand(2),len))
556 // If the constant string's length is zero we can optimize this by just
557 // doing a store of 0 at the first byte of the destination
560 new StoreInst(ConstantInt::get(Type::SByteTy,0),ci->getOperand(1),ci);
561 ci->replaceAllUsesWith(dest);
562 ci->eraseFromParent();
566 // Increment the length because we actually want to memcpy the null
567 // terminator as well.
570 // Extract some information from the instruction
571 Module* M = ci->getParent()->getParent()->getParent();
573 // We have enough information to now generate the memcpy call to
574 // do the concatenation for us.
575 std::vector<Value*> vals;
576 vals.push_back(dest); // destination
577 vals.push_back(src); // source
578 vals.push_back(ConstantSInt::get(Type::IntTy,len)); // length
579 vals.push_back(ConstantSInt::get(Type::IntTy,1)); // alignment
580 new CallInst(SLC.get_memcpy(), vals, "", ci);
582 // Finally, substitute the first operand of the strcat call for the
583 // strcat call itself since strcat returns its first operand; and,
584 // kill the strcat CallInst.
585 ci->replaceAllUsesWith(dest);
586 ci->eraseFromParent();
591 /// This LibCallOptimization will simplify a call to the strlen library
592 /// function by replacing it with a constant value if the string provided to
593 /// it is a constant array.
594 /// @brief Simplify the strlen library function.
595 struct StrLenOptimization : public LibCallOptimization
597 StrLenOptimization() : LibCallOptimization("strlen") {}
598 virtual ~StrLenOptimization() {}
600 /// @brief Make sure that the "strlen" function has the right prototype
601 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
603 if (f->getReturnType() == SLC.getTargetData()->getIntPtrType())
604 if (f->arg_size() == 1)
605 if (Function::const_arg_iterator AI = f->arg_begin())
606 if (AI->getType() == PointerType::get(Type::SByteTy))
611 /// @brief Perform the strlen optimization
612 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
614 // Get the length of the string
616 if (!getConstantStringLength(ci->getOperand(1),len))
619 ci->replaceAllUsesWith(
620 ConstantInt::get(SLC.getTargetData()->getIntPtrType(),len));
621 ci->eraseFromParent();
626 /// This LibCallOptimization will simplify a call to the memcpy library
627 /// function by expanding it out to a single store of size 0, 1, 2, 4, or 8
628 /// bytes depending on the length of the string and the alignment. Additional
629 /// optimizations are possible in code generation (sequence of immediate store)
630 /// @brief Simplify the memcpy library function.
631 struct MemCpyOptimization : public LibCallOptimization
633 /// @brief Default Constructor
634 MemCpyOptimization() : LibCallOptimization("llvm.memcpy") {}
636 /// @brief Subclass Constructor
637 MemCpyOptimization(const char* fname) : LibCallOptimization(fname) {}
639 /// @brief Destructor
640 virtual ~MemCpyOptimization() {}
642 /// @brief Make sure that the "memcpy" function has the right prototype
643 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& TD)
645 // Just make sure this has 4 arguments per LLVM spec.
646 return (f->arg_size() == 4);
649 /// Because of alignment and instruction information that we don't have, we
650 /// leave the bulk of this to the code generators. The optimization here just
651 /// deals with a few degenerate cases where the length of the string and the
652 /// alignment match the sizes of our intrinsic types so we can do a load and
653 /// store instead of the memcpy call.
654 /// @brief Perform the memcpy optimization.
655 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& TD)
657 // Make sure we have constant int values to work with
658 ConstantInt* LEN = dyn_cast<ConstantInt>(ci->getOperand(3));
661 ConstantInt* ALIGN = dyn_cast<ConstantInt>(ci->getOperand(4));
665 // If the length is larger than the alignment, we can't optimize
666 uint64_t len = LEN->getRawValue();
667 uint64_t alignment = ALIGN->getRawValue();
671 // Get the type we will cast to, based on size of the string
672 Value* dest = ci->getOperand(1);
673 Value* src = ci->getOperand(2);
678 // memcpy(d,s,0,a) -> noop
679 ci->eraseFromParent();
681 case 1: castType = Type::SByteTy; break;
682 case 2: castType = Type::ShortTy; break;
683 case 4: castType = Type::IntTy; break;
684 case 8: castType = Type::LongTy; break;
689 // Cast source and dest to the right sized primitive and then load/store
691 new CastInst(src,PointerType::get(castType),src->getName()+".cast",ci);
693 new CastInst(dest,PointerType::get(castType),dest->getName()+".cast",ci);
694 LoadInst* LI = new LoadInst(SrcCast,SrcCast->getName()+".val",ci);
695 StoreInst* SI = new StoreInst(LI, DestCast, ci);
696 ci->eraseFromParent();
701 /// This LibCallOptimization will simplify a call to the memmove library
702 /// function. It is identical to MemCopyOptimization except for the name of
704 /// @brief Simplify the memmove library function.
705 struct MemMoveOptimization : public MemCpyOptimization
707 /// @brief Default Constructor
708 MemMoveOptimization() : MemCpyOptimization("llvm.memmove") {}
712 /// This LibCallOptimization will simplify calls to the "pow" library
713 /// function. It looks for cases where the result of pow is well known and
714 /// substitutes the appropriate value.
715 /// @brief Simplify the pow library function.
716 struct PowOptimization : public LibCallOptimization
719 /// @brief Default Constructor
720 PowOptimization() : LibCallOptimization("pow") {}
721 /// @brief Destructor
722 virtual ~PowOptimization() {}
724 /// @brief Make sure that the "pow" function has the right prototype
725 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
727 // Just make sure this has 2 arguments
728 return (f->arg_size() == 2);
731 /// @brief Perform the pow optimization.
732 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
734 const Type *Ty = cast<Function>(ci->getOperand(0))->getReturnType();
735 Value* base = ci->getOperand(1);
736 Value* expn = ci->getOperand(2);
737 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(base)) {
738 double Op1V = Op1->getValue();
742 ci->replaceAllUsesWith(ConstantFP::get(Ty,1.0));
743 ci->eraseFromParent();
747 else if (ConstantFP* Op2 = dyn_cast<ConstantFP>(expn))
749 double Op2V = Op2->getValue();
753 ci->replaceAllUsesWith(ConstantFP::get(Ty,1.0));
754 ci->eraseFromParent();
757 else if (Op2V == 0.5)
759 // pow(x,0.5) -> sqrt(x)
760 CallInst* sqrt_inst = new CallInst(SLC.get_sqrt(), base,
761 ci->getName()+".pow",ci);
762 ci->replaceAllUsesWith(sqrt_inst);
763 ci->eraseFromParent();
766 else if (Op2V == 1.0)
769 ci->replaceAllUsesWith(base);
770 ci->eraseFromParent();
773 else if (Op2V == -1.0)
775 // pow(x,-1.0) -> 1.0/x
776 BinaryOperator* div_inst= BinaryOperator::create(Instruction::Div,
777 ConstantFP::get(Ty,1.0), base, ci->getName()+".pow", ci);
778 ci->replaceAllUsesWith(div_inst);
779 ci->eraseFromParent();
783 return false; // opt failed
787 /// This LibCallOptimization will simplify calls to the "fputs" library
788 /// function. It looks for cases where the result of fputs is not used and the
789 /// operation can be reduced to something simpler.
790 /// @brief Simplify the pow library function.
791 struct PutsOptimization : public LibCallOptimization
794 /// @brief Default Constructor
795 PutsOptimization() : LibCallOptimization("fputs") {}
797 /// @brief Destructor
798 virtual ~PutsOptimization() {}
800 /// @brief Make sure that the "fputs" function has the right prototype
801 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
803 // Just make sure this has 2 arguments
804 return (f->arg_size() == 2);
807 /// @brief Perform the fputs optimization.
808 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
810 // If the result is used, none of these optimizations work
811 if (!ci->hasNUses(0))
814 // All the optimizations depend on the length of the first argument and the
815 // fact that it is a constant string array. Check that now
817 if (!getConstantStringLength(ci->getOperand(1), len))
823 // fputs("",F) -> noop
827 // fputs(s,F) -> fputc(s[0],F) (if s is constant and strlen(s) == 1)
828 Function* fputc_func = SLC.get_fputc();
831 LoadInst* loadi = new LoadInst(ci->getOperand(1),
832 ci->getOperand(1)->getName()+".byte",ci);
833 CastInst* casti = new CastInst(loadi,Type::IntTy,
834 loadi->getName()+".int",ci);
835 new CallInst(fputc_func,casti,ci->getOperand(2),"",ci);
840 // fputs(s,F) -> fwrite(s,1,len,F) (if s is constant and strlen(s) > 1)
841 Function* fwrite_func = SLC.get_fwrite();
844 std::vector<Value*> parms;
845 parms.push_back(ci->getOperand(1));
846 parms.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
847 parms.push_back(ConstantUInt::get(SLC.getIntPtrType(),1));
848 parms.push_back(ci->getOperand(2));
849 new CallInst(fwrite_func,parms,"",ci);
853 ci->eraseFromParent();
854 return true; // success
858 /// A function to compute the length of a null-terminated constant array of
859 /// integers. This function can't rely on the size of the constant array
860 /// because there could be a null terminator in the middle of the array.
861 /// We also have to bail out if we find a non-integer constant initializer
862 /// of one of the elements or if there is no null-terminator. The logic
863 /// below checks each of these conditions and will return true only if all
864 /// conditions are met. In that case, the \p len parameter is set to the length
865 /// of the null-terminated string. If false is returned, the conditions were
866 /// not met and len is set to 0.
867 /// @brief Get the length of a constant string (null-terminated array).
868 bool getConstantStringLength(Value* V, uint64_t& len )
870 assert(V != 0 && "Invalid args to getConstantStringLength");
871 len = 0; // make sure we initialize this
873 // If the value is not a GEP instruction nor a constant expression with a
874 // GEP instruction, then return false because ConstantArray can't occur
876 if (GetElementPtrInst* GEPI = dyn_cast<GetElementPtrInst>(V))
878 else if (ConstantExpr* CE = dyn_cast<ConstantExpr>(V))
879 if (CE->getOpcode() == Instruction::GetElementPtr)
886 // Make sure the GEP has exactly three arguments.
887 if (GEP->getNumOperands() != 3)
890 // Check to make sure that the first operand of the GEP is an integer and
891 // has value 0 so that we are sure we're indexing into the initializer.
892 if (ConstantInt* op1 = dyn_cast<ConstantInt>(GEP->getOperand(1)))
894 if (!op1->isNullValue())
900 // Ensure that the second operand is a ConstantInt. If it isn't then this
901 // GEP is wonky and we're not really sure what were referencing into and
902 // better of not optimizing it. While we're at it, get the second index
903 // value. We'll need this later for indexing the ConstantArray.
904 uint64_t start_idx = 0;
905 if (ConstantInt* CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
906 start_idx = CI->getRawValue();
910 // The GEP instruction, constant or instruction, must reference a global
911 // variable that is a constant and is initialized. The referenced constant
912 // initializer is the array that we'll use for optimization.
913 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
914 if (!GV || !GV->isConstant() || !GV->hasInitializer())
917 // Get the initializer.
918 Constant* INTLZR = GV->getInitializer();
920 // Handle the ConstantAggregateZero case
921 if (ConstantAggregateZero* CAZ = dyn_cast<ConstantAggregateZero>(INTLZR))
923 // This is a degenerate case. The initializer is constant zero so the
924 // length of the string must be zero.
929 // Must be a Constant Array
930 ConstantArray* A = dyn_cast<ConstantArray>(INTLZR);
934 // Get the number of elements in the array
935 uint64_t max_elems = A->getType()->getNumElements();
937 // Traverse the constant array from start_idx (derived above) which is
938 // the place the GEP refers to in the array.
939 for ( len = start_idx; len < max_elems; len++)
941 if (ConstantInt* CI = dyn_cast<ConstantInt>(A->getOperand(len)))
943 // Check for the null terminator
944 if (CI->isNullValue())
945 break; // we found end of string
948 return false; // This array isn't suitable, non-int initializer
950 if (len >= max_elems)
951 return false; // This array isn't null terminated
953 // Subtract out the initial value from the length
955 return true; // success!
959 // Additional cases that we need to add to this file:
962 // * cbrt(expN(X)) -> expN(x/3)
963 // * cbrt(sqrt(x)) -> pow(x,1/6)
964 // * cbrt(sqrt(x)) -> pow(x,1/9)
967 // * cos(-x) -> cos(x)
970 // * exp(log(x)) -> x
973 // * ffs(cnst) -> cnst'
976 // * fprintf(file,fmt) -> fputs(fmt,file)
977 // (if fmt is constant and constains no % characters)
978 // * fprintf(file,"%s",str) -> fputs(orig,str)
979 // (only if the fprintf result is not used)
980 // * fprintf(file,"%c",chr) -> fputc(chr,file)
983 // * isascii(c) -> ((c & ~0x7f) == 0)
986 // * isdigit(c) -> (unsigned)(c) - '0' <= 9
989 // * log(exp(x)) -> x
990 // * log(x**y) -> y*log(x)
991 // * log(exp(y)) -> y*log(e)
992 // * log(exp2(y)) -> y*log(2)
993 // * log(exp10(y)) -> y*log(10)
994 // * log(sqrt(x)) -> 0.5*log(x)
995 // * log(pow(x,y)) -> y*log(x)
997 // lround, lroundf, lroundl:
998 // * lround(cnst) -> cnst'
1001 // * memcmp(s1,s2,0) -> 0
1002 // * memcmp(x,x,l) -> 0
1003 // * memcmp(x,y,l) -> cnst
1004 // (if all arguments are constant and strlen(x) <= l and strlen(y) <= l)
1005 // * memcpy(x,y,1) -> *x - *y
1008 // * memmove(d,s,l,a) -> memcpy(d,s,l,a)
1009 // (if s is a global constant array)
1012 // * memset(s,c,0) -> noop
1013 // * memset(s,c,n) -> store s, c
1017 // * pow(exp(x),y) -> exp(x*y)
1018 // * pow(sqrt(x),y) -> pow(x,y*0.5)
1019 // * pow(pow(x,y),z)-> pow(x,y*z)
1022 // * puts("") -> fputc("\n",stdout) (how do we get "stdout"?)
1024 // round, roundf, roundl:
1025 // * round(cnst) -> cnst'
1028 // * signbit(cnst) -> cnst'
1029 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
1032 // * sprintf(dest,fmt) -> strcpy(dest,fmt)
1033 // (if fmt is constant and constains no % characters)
1034 // * sprintf(dest,"%s",orig) -> strcpy(dest,orig)
1035 // (only if the sprintf result is not used)
1037 // sqrt, sqrtf, sqrtl:
1038 // * sqrt(expN(x)) -> expN(x*0.5)
1039 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
1040 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
1043 // * strchr(s,c) -> offset_of_in(c,s)
1044 // (if c is a constant integer and s is a constant string)
1045 // * strrchr(s,c) -> reverse_offset_of_in(c,s)
1046 // (if c is a constant integer and s is a constant string)
1047 // * strrchr(s1,0) -> strchr(s1,0)
1050 // * strcmp(x,x) -> 0
1051 // * strcmp(x,"") -> *x
1052 // * strcmp("",x) -> *x
1053 // * strcmp(x,y) -> cnst (if both x and y are constant strings)
1056 // * strncat(x,y,0) -> x
1057 // * strncat(x,y,0) -> x (if strlen(y) = 0)
1058 // * strncat(x,y,l) -> strcat(x,y) (if y and l are constants an l > strlen(y))
1061 // * strncmp(x,y,0) -> 0
1062 // * strncmp(x,x,l) -> 0
1063 // * strncmp(x,"",l) -> *x
1064 // * strncmp("",x,l) -> *x
1065 // * strncmp(x,y,1) -> *x - *y
1068 // * strncpy(d,s,0) -> d
1069 // * strncpy(d,s,l) -> memcpy(d,s,l,1)
1070 // (if s and l are constants)
1073 // * strpbrk(s,a) -> offset_in_for(s,a)
1074 // (if s and a are both constant strings)
1075 // * strpbrk(s,"") -> 0
1076 // * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
1079 // * strspn(s,a) -> const_int (if both args are constant)
1080 // * strspn("",a) -> 0
1081 // * strspn(s,"") -> 0
1082 // * strcspn(s,a) -> const_int (if both args are constant)
1083 // * strcspn("",a) -> 0
1084 // * strcspn(s,"") -> strlen(a)
1087 // * strstr(x,x) -> x
1088 // * strstr(s1,s2) -> offset_of_s2_in(s1)
1089 // (if s1 and s2 are constant strings)
1092 // * tan(atan(x)) -> x
1095 // * toascii(c) -> (c & 0x7f)
1097 // trunc, truncf, truncl:
1098 // * trunc(cnst) -> cnst'