1 //===- FunctionPropertiesAnalysis.cpp - Function properties extraction ----===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements an analysis extracting function properties, which may be
10 // used by ML-driven policies, for example.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Analysis/FunctionPropertiesAnalysis.h"
15 #include "llvm/IR/Instructions.h"
16 
17 using namespace llvm;
18 
19 FunctionPropertiesInfo
20 FunctionPropertiesInfo::getFunctionPropertiesInfo(const Function &F) {
21 
22   FunctionPropertiesInfo FPI;
23 
24   FPI.Uses = ((!F.hasLocalLinkage()) ? 1 : 0) + F.getNumUses();
25 
26   for (const auto &BB : F) {
27     ++FPI.BasicBlockCount;
28 
29     if (const auto *BI = dyn_cast<BranchInst>(BB.getTerminator())) {
30       if (BI->isConditional())
31         FPI.BlocksReachedFromConditionalInstruction += BI->getNumSuccessors();
32     } else if (const auto *SI = dyn_cast<SwitchInst>(BB.getTerminator())) {
33       FPI.BlocksReachedFromConditionalInstruction +=
34           (SI->getNumCases() + (nullptr != SI->getDefaultDest()));
35     }
36 
37     for (const auto &I : BB) {
38       if (auto *CS = dyn_cast<CallBase>(&I)) {
39         const auto *Callee = CS->getCalledFunction();
40         if (Callee && !Callee->isIntrinsic() && !Callee->isDeclaration())
41           ++FPI.DirectCallsToDefinedFunctions;
42       }
43     }
44   }
45   return FPI;
46 }
47 
48 AnalysisKey FunctionPropertiesAnalysis::Key;
49 
50 FunctionPropertiesInfo
51 FunctionPropertiesAnalysis::run(Function &F, FunctionAnalysisManager &FAM) {
52   return FunctionPropertiesInfo::getFunctionPropertiesInfo(F);
53 }