QCOR
qcor_base_llvm_pass.hpp
1 #include "llvm/IR/Constants.h"
2 #include "llvm/IR/Function.h"
3 #include "llvm/IR/Instructions.h"
4 #include "llvm/IR/LegacyPassManager.h"
5 #include "llvm/IR/Module.h"
6 #include "llvm/Pass.h"
7 #include "llvm/Support/raw_ostream.h"
8 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
9 #include <cxxabi.h>
10 #include <iostream>
11 #include <set>
12 
13 using namespace llvm;
14 
15 namespace qcor {
16 
17 // This class provides some base functionality for all
18 // qcor FunctionPasses, specifically, a mechanism for only
19 // operating on Functions that are annotated quantum
20 class QCORBaseFunctionPass : public FunctionPass {
21 protected:
22  const char *AnnotationString = "quantum";
23 
24  QCORBaseFunctionPass(char pid) : FunctionPass(pid) {}
25 
26  std::set<Function *> annotFuncs;
27  bool shouldInstrumentFunc(Function &F) {
28  return annotFuncs.find(&F) != annotFuncs.end();
29  }
30 
31  auto demangle(const char *name) {
32  int status = -1;
33  std::unique_ptr<char, void (*)(void *)> res{
34  abi::__cxa_demangle(name, NULL, NULL, &status), std::free};
35  return (status == 0) ? res.get() : std::string(name);
36  }
37 
38 public:
39  virtual bool doInitialization(Module &M) override {
40  getAnnotatedFunctions(&M);
41  return false;
42  }
43 
44  void getAnnotatedFunctions(Module *M) {
45  for (Module::global_iterator I = M->global_begin(), E = M->global_end();
46  I != E; ++I) {
47 
48  if (I->getName() == "llvm.global.annotations") {
49  ConstantArray *CA = dyn_cast<ConstantArray>(I->getOperand(0));
50  for (auto OI = CA->op_begin(); OI != CA->op_end(); ++OI) {
51  ConstantStruct *CS = dyn_cast<ConstantStruct>(OI->get());
52  Function *FUNC = dyn_cast<Function>(CS->getOperand(0)->getOperand(0));
53  GlobalVariable *AnnotationGL =
54  dyn_cast<GlobalVariable>(CS->getOperand(1)->getOperand(0));
55  StringRef annotation =
56  dyn_cast<ConstantDataArray>(AnnotationGL->getInitializer())
57  ->getAsCString();
58  if (annotation.compare(AnnotationString) == 0) {
59  annotFuncs.insert(FUNC);
60  }
61  }
62  }
63  }
64  }
65 };
66 } // namespace qcor
qcor::QCORBaseFunctionPass
Definition: qcor_base_llvm_pass.hpp:20
qcor
Definition: qcor_syntax_handler.cpp:15