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 #include "llvm/Transforms/IPO.h"
20 #include "llvm/Module.h"
21 #include "llvm/Pass.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Constants.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/hash_map"
27 #include "llvm/Target/TargetData.h"
32 Statistic<> SimplifiedLibCalls("simplified-lib-calls",
33 "Number of well-known library calls simplified");
35 /// This class is the base class for a set of small but important
36 /// optimizations of calls to well-known functions, such as those in the c
37 /// library. This class provides the basic infrastructure for handling
38 /// runOnModule. Subclasses register themselves and provide two methods:
39 /// RecognizeCall and OptimizeCall. Whenever this class finds a function call,
40 /// it asks the subclasses to recognize the call. If it is recognized, then
41 /// the OptimizeCall method is called on that subclass instance. In this way
42 /// the subclasses implement the calling conditions on which they trigger and
43 /// the action to perform, making it easy to add new optimizations of this
45 /// @brief A ModulePass for optimizing well-known function calls
46 struct SimplifyLibCalls : public ModulePass {
48 /// We need some target data for accurate signature details that are
49 /// target dependent. So we require target data in our AnalysisUsage.
50 virtual void getAnalysisUsage(AnalysisUsage& Info) const;
52 /// For this pass, process all of the function calls in the module, calling
53 /// RecognizeCall and OptimizeCall as appropriate.
54 virtual bool runOnModule(Module &M);
58 RegisterOpt<SimplifyLibCalls>
59 X("simplify-libcalls","Simplify well-known library calls");
63 /// @brief Constructor that registers the optimization
64 CallOptimizer(const char * fname );
66 virtual ~CallOptimizer();
68 /// The implementation of this function in subclasses should determine if
69 /// \p F is suitable for the optimization. This method is called by
70 /// runOnModule to short circuit visiting all the call sites of such a
71 /// function if that function is not suitable in the first place.
72 /// If the called function is suitabe, this method should return true;
73 /// false, otherwise. This function should also perform any lazy
74 /// initialization that the CallOptimizer needs to do, if its to return
75 /// true. This avoids doing initialization until the optimizer is actually
76 /// going to be called upon to do some optimization.
77 virtual bool ValidateCalledFunction(
78 const Function* F, ///< The function that is the target of call sites
79 const TargetData& TD ///< Information about the target
82 /// The implementations of this function in subclasses is the heart of the
83 /// SimplifyLibCalls algorithm. Sublcasses of this class implement
84 /// OptimizeCall to determine if (a) the conditions are right for optimizing
85 /// the call and (b) to perform the optimization. If an action is taken
86 /// against ci, the subclass is responsible for returning true and ensuring
87 /// that ci is erased from its parent.
88 /// @param ci the call instruction under consideration
89 /// @param f the function that ci calls.
90 /// @brief Optimize a call, if possible.
91 virtual bool OptimizeCall(
92 CallInst* ci, ///< The call instruction that should be optimized.
93 const TargetData& TD ///< Information about the target
96 const char * getFunctionName() const { return func_name; }
98 const char* func_name;
101 /// @brief The list of optimizations deriving from CallOptimizer
103 hash_map<std::string,CallOptimizer*> optlist;
105 CallOptimizer::CallOptimizer(const char* fname)
108 // Register this call optimizer
109 optlist[func_name] = this;
112 /// Make sure we get our virtual table in this file.
113 CallOptimizer::~CallOptimizer() { }
117 ModulePass *llvm::createSimplifyLibCallsPass()
119 return new SimplifyLibCalls();
122 void SimplifyLibCalls::getAnalysisUsage(AnalysisUsage& Info) const
124 // Ask that the TargetData analysis be performed before us so we can use
126 Info.addRequired<TargetData>();
129 bool SimplifyLibCalls::runOnModule(Module &M)
131 TargetData& TD = getAnalysis<TargetData>();
135 // The call optimizations can be recursive. That is, the optimization might
136 // generate a call to another function which can also be optimized. This way
137 // we make the CallOptimizer instances very specific to the case they handle.
138 // It also means we need to keep running over the function calls in the module
139 // until we don't get any more optimizations possible.
140 bool found_optimization = false;
143 found_optimization = false;
144 for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI)
146 // All the "well-known" functions are external and have external linkage
147 // because they live in a runtime library somewhere and were (probably)
148 // not compiled by LLVM. So, we only act on external functions that have
149 // external linkage and non-empty uses.
150 if (FI->isExternal() && FI->hasExternalLinkage() && !FI->use_empty())
152 // Get the optimization class that pertains to this function
153 if (CallOptimizer* CO = optlist[FI->getName().c_str()] )
155 // Make sure the called function is suitable for the optimization
156 if (CO->ValidateCalledFunction(FI,TD))
158 // Loop over each of the uses of the function
159 for (Value::use_iterator UI = FI->use_begin(), UE = FI->use_end();
162 // If the use of the function is a call instruction
163 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
165 // Do the optimization on the CallOptimizer.
166 if (CO->OptimizeCall(CI,TD))
168 ++SimplifiedLibCalls;
169 found_optimization = result = true;
177 } while (found_optimization);
183 /// Provide some functions for accessing standard library prototypes and
184 /// caching them so we don't have to keep recomputing them
185 FunctionType* get_strlen(const Type* IntPtrTy)
187 static FunctionType* strlen_type = 0;
190 std::vector<const Type*> args;
191 args.push_back(PointerType::get(Type::SByteTy));
192 strlen_type = FunctionType::get(IntPtrTy, args, false);
197 FunctionType* get_memcpy()
199 static FunctionType* memcpy_type = 0;
202 // Note: this is for llvm.memcpy intrinsic
203 std::vector<const Type*> args;
204 args.push_back(PointerType::get(Type::SByteTy));
205 args.push_back(PointerType::get(Type::SByteTy));
206 args.push_back(Type::IntTy);
207 args.push_back(Type::IntTy);
208 memcpy_type = FunctionType::get(Type::VoidTy, args, false);
213 /// A function to compute the length of a null-terminated string of integers.
214 /// This function can't rely on the size of the constant array because there
215 /// could be a null terminator in the middle of the array. We also have to
216 /// bail out if we find a non-integer constant initializer of one of the
217 /// elements or if there is no null-terminator. The logic below checks
218 bool getConstantStringLength(Value* V, uint64_t& len )
220 assert(V != 0 && "Invalid args to getConstantStringLength");
221 len = 0; // make sure we initialize this
223 // If the value is not a GEP instruction nor a constant expression with a
224 // GEP instruction, then return false because ConstantArray can't occur
226 if (GetElementPtrInst* GEPI = dyn_cast<GetElementPtrInst>(V))
228 else if (ConstantExpr* CE = dyn_cast<ConstantExpr>(V))
229 if (CE->getOpcode() == Instruction::GetElementPtr)
236 // Make sure the GEP has exactly three arguments.
237 if (GEP->getNumOperands() != 3)
240 // Check to make sure that the first operand of the GEP is an integer and
241 // has value 0 so that we are sure we're indexing into the initializer.
242 if (ConstantInt* op1 = dyn_cast<ConstantInt>(GEP->getOperand(1)))
244 if (!op1->isNullValue())
250 // Ensure that the second operand is a ConstantInt. If it isn't then this
251 // GEP is wonky and we're not really sure what were referencing into and
252 // better of not optimizing it. While we're at it, get the second index
253 // value. We'll need this later for indexing the ConstantArray.
254 uint64_t start_idx = 0;
255 if (ConstantInt* CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
256 start_idx = CI->getRawValue();
260 // The GEP instruction, constant or instruction, must reference a global
261 // variable that is a constant and is initialized. The referenced constant
262 // initializer is the array that we'll use for optimization.
263 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
264 if (!GV || !GV->isConstant() || !GV->hasInitializer())
267 // Get the initializer.
268 Constant* INTLZR = GV->getInitializer();
270 // Handle the ConstantAggregateZero case
271 if (ConstantAggregateZero* CAZ = dyn_cast<ConstantAggregateZero>(INTLZR))
273 // This is a degenerate case. The initializer is constant zero so the
274 // length of the string must be zero.
279 // Must be a Constant Array
280 ConstantArray* A = dyn_cast<ConstantArray>(INTLZR);
284 // Get the number of elements in the array
285 uint64_t max_elems = A->getType()->getNumElements();
287 // Traverse the constant array from start_idx (derived above) which is
288 // the place the GEP refers to in the array.
289 for ( len = start_idx; len < max_elems; len++)
291 if (ConstantInt* CI = dyn_cast<ConstantInt>(A->getOperand(len)))
293 // Check for the null terminator
294 if (CI->isNullValue())
295 break; // we found end of string
298 return false; // This array isn't suitable, non-int initializer
300 if (len >= max_elems)
301 return false; // This array isn't null terminated
303 // Subtract out the initial value from the length
305 return true; // success!
308 /// This CallOptimizer will find instances of a call to "exit" that occurs
309 /// within the "main" function and change it to a simple "ret" instruction with
310 /// the same value as passed to the exit function. It assumes that the
311 /// instructions after the call to exit(3) can be deleted since they are
312 /// unreachable anyway.
313 /// @brief Replace calls to exit in main with a simple return
314 struct ExitInMainOptimization : public CallOptimizer
316 ExitInMainOptimization() : CallOptimizer("exit") {}
317 virtual ~ExitInMainOptimization() {}
319 // Make sure the called function looks like exit (int argument, int return
320 // type, external linkage, not varargs).
321 virtual bool ValidateCalledFunction(const Function* f, const TargetData& TD)
323 if (f->arg_size() >= 1)
324 if (f->arg_begin()->getType()->isInteger())
329 virtual bool OptimizeCall(CallInst* ci, const TargetData& TD)
331 // To be careful, we check that the call to exit is coming from "main", that
332 // main has external linkage, and the return type of main and the argument
333 // to exit have the same type.
334 Function *from = ci->getParent()->getParent();
335 if (from->hasExternalLinkage())
336 if (from->getReturnType() == ci->getOperand(1)->getType())
337 if (from->getName() == "main")
339 // Okay, time to actually do the optimization. First, get the basic
340 // block of the call instruction
341 BasicBlock* bb = ci->getParent();
343 // Create a return instruction that we'll replace the call with.
344 // Note that the argument of the return is the argument of the call
346 ReturnInst* ri = new ReturnInst(ci->getOperand(1), ci);
348 // Split the block at the call instruction which places it in a new
350 bb->splitBasicBlock(ci);
352 // The block split caused a branch instruction to be inserted into
353 // the end of the original block, right after the return instruction
354 // that we put there. That's not a valid block, so delete the branch
356 bb->getInstList().pop_back();
358 // Now we can finally get rid of the call instruction which now lives
359 // in the new basic block.
360 ci->eraseFromParent();
362 // Optimization succeeded, return true.
365 // We didn't pass the criteria for this optimization so return false
368 } ExitInMainOptimizer;
370 /// This CallOptimizer will simplify a call to the strcat library function. The
371 /// simplification is possible only if the string being concatenated is a
372 /// constant array or a constant expression that results in a constant array. In
373 /// this case, if the array is small, we can generate a series of inline store
374 /// instructions to effect the concatenation without calling strcat.
375 /// @brief Simplify the strcat library function.
376 struct StrCatOptimization : public CallOptimizer
379 Function* strlen_func;
380 Function* memcpy_func;
383 : CallOptimizer("strcat")
387 virtual ~StrCatOptimization() {}
389 inline Function* get_strlen_func(Module*M,const Type* IntPtrTy)
393 return strlen_func = M->getOrInsertFunction("strlen",get_strlen(IntPtrTy));
396 inline Function* get_memcpy_func(Module* M)
400 return memcpy_func = M->getOrInsertFunction("llvm.memcpy",get_memcpy());
403 /// @brief Make sure that the "strcat" function has the right prototype
404 virtual bool ValidateCalledFunction(const Function* f, const TargetData& TD)
406 if (f->getReturnType() == PointerType::get(Type::SByteTy))
407 if (f->arg_size() == 2)
409 Function::const_arg_iterator AI = f->arg_begin();
410 if (AI++->getType() == PointerType::get(Type::SByteTy))
411 if (AI->getType() == PointerType::get(Type::SByteTy))
413 // Invalidate the pre-computed strlen_func and memcpy_func Functions
414 // because, by definition, this method is only called when a new
415 // Module is being traversed. Invalidation causes re-computation for
416 // the new Module (if necessary).
420 // Indicate this is a suitable call type.
427 /// Perform the optimization if the length of the string concatenated
428 /// is reasonably short and it is a constant array.
429 virtual bool OptimizeCall(CallInst* ci, const TargetData& TD)
431 // Extract the initializer (while making numerous checks) from the
432 // source operand of the call to strcat. If we get null back, one of
433 // a variety of checks in get_GVInitializer failed
435 if (!getConstantStringLength(ci->getOperand(2),len))
438 // Handle the simple, do-nothing case
441 ci->replaceAllUsesWith(ci->getOperand(1));
442 ci->eraseFromParent();
446 // Increment the length because we actually want to memcpy the null
447 // terminator as well.
450 // Extract some information from the instruction
451 Module* M = ci->getParent()->getParent()->getParent();
453 // We need to find the end of the destination string. That's where the
454 // memory is to be moved to. We just generate a call to strlen (further
455 // optimized in another pass). Note that the get_strlen_func() call
456 // caches the Function* for us.
457 CallInst* strlen_inst =
458 new CallInst(get_strlen_func(M,TD.getIntPtrType()),
459 ci->getOperand(1),"",ci);
461 // Now that we have the destination's length, we must index into the
462 // destination's pointer to get the actual memcpy destination (end of
463 // the string .. we're concatenating).
464 std::vector<Value*> idx;
465 idx.push_back(strlen_inst);
466 GetElementPtrInst* gep =
467 new GetElementPtrInst(ci->getOperand(1),idx,"",ci);
469 // We have enough information to now generate the memcpy call to
470 // do the concatenation for us.
471 std::vector<Value*> vals;
472 vals.push_back(gep); // destination
473 vals.push_back(ci->getOperand(2)); // source
474 vals.push_back(ConstantSInt::get(Type::IntTy,len)); // length
475 vals.push_back(ConstantSInt::get(Type::IntTy,1)); // alignment
476 CallInst* memcpy_inst = new CallInst(get_memcpy_func(M), vals, "", ci);
478 // Finally, substitute the first operand of the strcat call for the
479 // strcat call itself since strcat returns its first operand; and,
480 // kill the strcat CallInst.
481 ci->replaceAllUsesWith(ci->getOperand(1));
482 ci->eraseFromParent();
487 /// This CallOptimizer will simplify a call to the strlen library function by
488 /// replacing it with a constant value if the string provided to it is a
490 /// @brief Simplify the strlen library function.
491 struct StrLenOptimization : public CallOptimizer
493 StrLenOptimization() : CallOptimizer("strlen") {}
494 virtual ~StrLenOptimization() {}
496 /// @brief Make sure that the "strlen" function has the right prototype
497 virtual bool ValidateCalledFunction(const Function* f, const TargetData& TD)
499 if (f->getReturnType() == TD.getIntPtrType())
500 if (f->arg_size() == 1)
501 if (Function::const_arg_iterator AI = f->arg_begin())
502 if (AI->getType() == PointerType::get(Type::SByteTy))
507 /// @brief Perform the strlen optimization
508 virtual bool OptimizeCall(CallInst* ci, const TargetData& TD)
510 // Get the length of the string
512 if (!getConstantStringLength(ci->getOperand(1),len))
515 ci->replaceAllUsesWith(ConstantInt::get(TD.getIntPtrType(),len));
516 ci->eraseFromParent();
521 /// This CallOptimizer will simplify a call to the memcpy library function by
522 /// expanding it out to a small set of stores if the copy source is a constant
524 /// @brief Simplify the memcpy library function.
525 struct MemCpyOptimization : public CallOptimizer
527 MemCpyOptimization() : CallOptimizer("llvm.memcpy") {}
529 MemCpyOptimization(const char* fname) : CallOptimizer(fname) {}
531 virtual ~MemCpyOptimization() {}
533 /// @brief Make sure that the "memcpy" function has the right prototype
534 virtual bool ValidateCalledFunction(const Function* f, const TargetData& TD)
536 // Just make sure this has 4 arguments per LLVM spec.
537 return (f->arg_size() == 4) &&
538 (f->getReturnType() == Type::VoidTy);
541 /// Because of alignment and instruction information that we don't have, we
542 /// leave the bulk of this to the code generators. The optimization here just
543 /// deals with a few degenerate cases where the length of the string and the
544 /// alignment match the sizes of our intrinsic types so we can do a load and
545 /// store instead of the memcpy call.
546 /// @brief Perform the memcpy optimization.
547 virtual bool OptimizeCall(CallInst* ci, const TargetData& TD)
549 // Make sure we have constant int values to work with
550 ConstantInt* LEN = dyn_cast<ConstantInt>(ci->getOperand(3));
553 ConstantInt* ALIGN = dyn_cast<ConstantInt>(ci->getOperand(4));
557 // If the length is larger than the alignment, we can't optimize
558 uint64_t len = LEN->getRawValue();
559 uint64_t alignment = ALIGN->getRawValue();
563 Value* dest = ci->getOperand(1);
564 Value* src = ci->getOperand(2);
565 CastInst* SrcCast = 0;
566 CastInst* DestCast = 0;
570 // The memcpy is a no-op so just dump its call.
571 ci->eraseFromParent();
574 SrcCast = new CastInst(src,PointerType::get(Type::SByteTy),"",ci);
575 DestCast = new CastInst(dest,PointerType::get(Type::SByteTy),"",ci);
578 SrcCast = new CastInst(src,PointerType::get(Type::ShortTy),"",ci);
579 DestCast = new CastInst(dest,PointerType::get(Type::ShortTy),"",ci);
582 SrcCast = new CastInst(src,PointerType::get(Type::IntTy),"",ci);
583 DestCast = new CastInst(dest,PointerType::get(Type::IntTy),"",ci);
586 SrcCast = new CastInst(src,PointerType::get(Type::LongTy),"",ci);
587 DestCast = new CastInst(dest,PointerType::get(Type::LongTy),"",ci);
592 LoadInst* LI = new LoadInst(SrcCast,"",ci);
593 StoreInst* SI = new StoreInst(LI, DestCast, ci);
594 ci->eraseFromParent();
599 /// This CallOptimizer will simplify a call to the memmove library function. It
600 /// is identical to MemCopyOptimization except for the name of the intrinsic.
601 /// @brief Simplify the memmove library function.
602 struct MemMoveOptimization : public MemCpyOptimization
604 MemMoveOptimization() : MemCpyOptimization("llvm.memmove") {}