• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===- Hello.cpp - Example code from "Writing an LLVM Pass" ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements two versions of the LLVM "Hello World" pass described
11 // in docs/WritingAnLLVMPass.html
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/ADT/Statistic.h"
16 #include "llvm/IR/Function.h"
17 #include "llvm/Pass.h"
18 #include "llvm/Support/raw_ostream.h"
19 using namespace llvm;
20 
21 #define DEBUG_TYPE "hello"
22 
23 STATISTIC(HelloCounter, "Counts number of functions greeted");
24 
25 namespace {
26   // Hello - The first implementation, without getAnalysisUsage.
27   struct Hello : public FunctionPass {
28     static char ID; // Pass identification, replacement for typeid
Hello__anon54d484100111::Hello29     Hello() : FunctionPass(ID) {}
30 
runOnFunction__anon54d484100111::Hello31     bool runOnFunction(Function &F) override {
32       ++HelloCounter;
33       errs() << "Hello: ";
34       errs().write_escaped(F.getName()) << '\n';
35       return false;
36     }
37   };
38 }
39 
40 char Hello::ID = 0;
41 static RegisterPass<Hello> X("hello", "Hello World Pass");
42 
43 namespace {
44   // Hello2 - The second implementation with getAnalysisUsage implemented.
45   struct Hello2 : public FunctionPass {
46     static char ID; // Pass identification, replacement for typeid
Hello2__anon54d484100211::Hello247     Hello2() : FunctionPass(ID) {}
48 
runOnFunction__anon54d484100211::Hello249     bool runOnFunction(Function &F) override {
50       ++HelloCounter;
51       errs() << "Hello: ";
52       errs().write_escaped(F.getName()) << '\n';
53       return false;
54     }
55 
56     // We don't modify the program, so we preserve all analyses.
getAnalysisUsage__anon54d484100211::Hello257     void getAnalysisUsage(AnalysisUsage &AU) const override {
58       AU.setPreservesAll();
59     }
60   };
61 }
62 
63 char Hello2::ID = 0;
64 static RegisterPass<Hello2>
65 Y("hello2", "Hello World Pass (with getAnalysisUsage implemented)");
66