LLVM API Documentation

Hello.cpp
Go to the documentation of this file.
00001 //===- Hello.cpp - Example code from "Writing an LLVM Pass" ---------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements two versions of the LLVM "Hello World" pass described
00011 // in docs/WritingAnLLVMPass.html
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/ADT/Statistic.h"
00016 #include "llvm/IR/Function.h"
00017 #include "llvm/Pass.h"
00018 #include "llvm/Support/raw_ostream.h"
00019 using namespace llvm;
00020 
00021 #define DEBUG_TYPE "hello"
00022 
00023 STATISTIC(HelloCounter, "Counts number of functions greeted");
00024 
00025 namespace {
00026   // Hello - The first implementation, without getAnalysisUsage.
00027   struct Hello : public FunctionPass {
00028     static char ID; // Pass identification, replacement for typeid
00029     Hello() : FunctionPass(ID) {}
00030 
00031     bool runOnFunction(Function &F) override {
00032       ++HelloCounter;
00033       errs() << "Hello: ";
00034       errs().write_escaped(F.getName()) << '\n';
00035       return false;
00036     }
00037   };
00038 }
00039 
00040 char Hello::ID = 0;
00041 static RegisterPass<Hello> X("hello", "Hello World Pass");
00042 
00043 namespace {
00044   // Hello2 - The second implementation with getAnalysisUsage implemented.
00045   struct Hello2 : public FunctionPass {
00046     static char ID; // Pass identification, replacement for typeid
00047     Hello2() : FunctionPass(ID) {}
00048 
00049     bool runOnFunction(Function &F) override {
00050       ++HelloCounter;
00051       errs() << "Hello: ";
00052       errs().write_escaped(F.getName()) << '\n';
00053       return false;
00054     }
00055 
00056     // We don't modify the program, so we preserve all analyses.
00057     void getAnalysisUsage(AnalysisUsage &AU) const override {
00058       AU.setPreservesAll();
00059     }
00060   };
00061 }
00062 
00063 char Hello2::ID = 0;
00064 static RegisterPass<Hello2>
00065 Y("hello2", "Hello World Pass (with getAnalysisUsage implemented)");