1 //===- MemDerefPrinter.cpp - Printer for isDereferenceablePointer ---------===//
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 #include "llvm/Analysis/Loads.h"
10 #include "llvm/Analysis/Passes.h"
11 #include "llvm/IR/DataLayout.h"
12 #include "llvm/IR/InstIterator.h"
13 #include "llvm/IR/Instructions.h"
14 #include "llvm/IR/LLVMContext.h"
15 #include "llvm/IR/Module.h"
16 #include "llvm/InitializePasses.h"
17 #include "llvm/Pass.h"
18 #include "llvm/Support/ErrorHandling.h"
19 #include "llvm/Support/raw_ostream.h"
20 using namespace llvm;
21 
22 namespace {
23   struct MemDerefPrinter : public FunctionPass {
24     SmallVector<Value *, 4> Deref;
25     SmallPtrSet<Value *, 4> DerefAndAligned;
26 
27     static char ID; // Pass identification, replacement for typeid
28     MemDerefPrinter() : FunctionPass(ID) {
29       initializeMemDerefPrinterPass(*PassRegistry::getPassRegistry());
30     }
31     void getAnalysisUsage(AnalysisUsage &AU) const override {
32       AU.setPreservesAll();
33     }
34     bool runOnFunction(Function &F) override;
35     void print(raw_ostream &OS, const Module * = nullptr) const override;
36     void releaseMemory() override {
37       Deref.clear();
38       DerefAndAligned.clear();
39     }
40   };
41 }
42 
43 char MemDerefPrinter::ID = 0;
44 INITIALIZE_PASS_BEGIN(MemDerefPrinter, "print-memderefs",
45                       "Memory Dereferenciblity of pointers in function", false, true)
46 INITIALIZE_PASS_END(MemDerefPrinter, "print-memderefs",
47                     "Memory Dereferenciblity of pointers in function", false, true)
48 
49 FunctionPass *llvm::createMemDerefPrinter() {
50   return new MemDerefPrinter();
51 }
52 
53 bool MemDerefPrinter::runOnFunction(Function &F) {
54   const DataLayout &DL = F.getParent()->getDataLayout();
55   for (auto &I: instructions(F)) {
56     if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
57       Value *PO = LI->getPointerOperand();
58       if (isDereferenceablePointer(PO, LI->getType(), DL))
59         Deref.push_back(PO);
60       if (isDereferenceableAndAlignedPointer(
61               PO, LI->getType(), MaybeAlign(LI->getAlignment()), DL))
62         DerefAndAligned.insert(PO);
63     }
64   }
65   return false;
66 }
67 
68 void MemDerefPrinter::print(raw_ostream &OS, const Module *M) const {
69   OS << "The following are dereferenceable:\n";
70   for (Value *V: Deref) {
71     V->print(OS);
72     if (DerefAndAligned.count(V))
73       OS << "\t(aligned)";
74     else
75       OS << "\t(unaligned)";
76     OS << "\n\n";
77   }
78 }
79