title: How to clone function from another module and set it AlwaysInline on LLVM pass?
body: <p>I want to clone a function from another bitcode module and set it AlwaysInline so that it can be inlined.
  But an error occurs when applying such custom pass (It seems that the cause is the use of CloneFunction()). How can I fix it?</p>
  
  <p>I'm using LLVM 3.6.0 on OS X and target is Android armeabi-v7a (It should be same on other target).</p>
  
  <p>callee.cpp (compiled to bitcode module callee.bc)</p>
  
  <pre><code>#include &lt;jni.h&gt;
  #include &lt;android/log.h&gt;
  
  #ifdef __cplusplus
  extern "C" {
  #endif
  
  void callee(char *str, int num)
  {
          __android_log_print(ANDROID_LOG_DEBUG, "target", "%s, 0x%x", str, num);
  }
  
  #ifdef __cplusplus
  }
  #endif
  </code></pre>
  
  <p>test.cpp (a module custom pass is applied)</p>
  
  <pre><code>#include &lt;jni.h&gt;
  
  #ifdef __cplusplus
  extern "C" {
  #endif
  
  void caller()
  {
  }
  
  void Java_com_android_test_TestActivity_test(JNIEnv *env, jobject thiz)
  {
          caller();
  }
  
  #ifdef __cplusplus
  }
  #endif
  </code></pre>
  
  <p>TestPass.cpp (a custom pass)</p>
  
  <pre><code>#include "llvm/IR/Module.h"
  #include "llvm/IR/Function.h"
  #include "llvm/IR/Type.h"
  #include "llvm/IR/InstIterator.h"
  #include "llvm/IR/Instructions.h"
  #include "llvm/IR/GlobalValue.h"
  #include "llvm/IR/IRBuilder.h"
  #include "llvm/Support/SourceMgr.h"
  #include "llvm/IRReader/IRReader.h"
  #include "llvm/Transforms/Utils/Cloning.h"
  #include "llvm/IR/LegacyPassManager.h"
  #include "llvm/Transforms/IPO/PassManagerBuilder.h"
  
  using namespace llvm;
  
  namespace {
          struct TestPass : public ModulePass {
                  static char ID;
  
                  TestPass() : ModulePass(ID) {}
  
                  virtual bool runOnModule(Module &amp;M)
                  {
                          for (Module::iterator F = M.begin(), E = M.end(); F!= E; ++F)
                          {
                                  if (F-&gt;getName() == "caller")
                                  {
                                          inst_iterator I = inst_begin(F);
                                          Instruction *inst = &amp;*I;
  
                                          SMDiagnostic error;
                                          LLVMContext context;
                                          std::unique_ptr&lt;Module&gt; m = parseIRFile("callee.bc", error, context);
                                          for (Module::iterator f = m-&gt;getFunctionList().begin(); f != m-&gt;getFunctionList().end(); f++)
                                          {
                                                  if (f-&gt;getName() == "callee")
                                                  {
                                                          // Copy callee.bc callee function to current module and set AlwaysInline
                                                          ValueToValueMapTy VMap;
                                                          Function* callee_clone = CloneFunction(f, VMap, false);
                                                          /*
                                                          callee_clone-&gt;setName("callee_clone");
                                                          callee_clone-&gt;addFnAttr(Attribute::AlwaysInline);
                                                          M.getFunctionList().push_back(callee_clone);
  
                                                          // Add call to copied callee function
                                                          GlobalVariable* str = new GlobalVariable(M,
                                                                          ArrayType::get(IntegerType::get(M.getContext(), 8), 8),
                                                                          false,
                                                                          GlobalValue::ExternalLinkage,
                                                                          0,
                                                                          "str");
                                                          str-&gt;setAlignment(1);
                                                          Constant* str_init = ConstantDataArray::getString(M.getContext(), "abcdefgh", false);
                                                          str-&gt;setInitializer(str_init);
  
                                                          ConstantInt* param1_indice1 = ConstantInt::get(M.getContext(), APInt(32, StringRef("0"), 10));
                                                          ConstantInt* param1_indice2 = ConstantInt::get(M.getContext(), APInt(32, StringRef("0"), 10));
                                                          std::vector&lt;Constant*&gt; param1_indices;
                                                          param1_indices.push_back(param1_indice1);
                                                          param1_indices.push_back(param1_indice2);
                                                          Constant* param1 = ConstantExpr::getGetElementPtr(str, param1_indices);
  
                                                          GlobalVariable* num = new GlobalVariable(M,
                                                                          IntegerType::get(M.getContext(), 32),
                                                                          false,
                                                                          GlobalValue::ExternalLinkage,
                                                                          0,
                                                                          "num");
                                                          num-&gt;setAlignment(4);
                                                          ConstantInt* num_init = ConstantInt::get(M.getContext(), APInt(32, StringRef("12345"), 10));
                                                          num-&gt;setInitializer(num_init);
  
                                                          LoadInst* param2 = new LoadInst(num, "", false, inst);
                                                          param2-&gt;setAlignment(4);
  
                                                          std::vector&lt;Value*&gt; params;
                                                          params.push_back(param1);
                                                          params.push_back(param2);
  
                                                          CallInst* ci = CallInst::Create(callee_clone, params, "", inst);
                                                          ci-&gt;setCallingConv(CallingConv::C);
                                                          ci-&gt;setTailCall(false);
                                                          */
                                                  }
                                          }
                                  }
                          }
  
                          return true;
                  }
          };
  }
  
  char TestPass::ID = 0;
  static RegisterPass&lt;TestPass&gt; X("TestPass", "TestPass", false, false);
  
  static void registerTestPass(const PassManagerBuilder &amp;, legacy::PassManagerBase &amp;PM)
  {
          PM.add(new TestPass());
  }
  static RegisterStandardPasses RegisterTestPass(PassManagerBuilder::EP_ModuleOptimizerEarly, registerTestPass);
  </code></pre>
  
  <p>Error applying custom pass</p>
  
  <pre><code>[...snip...]
  While deleting: [7 x i8]* %.str
  Use still stuck around after Def is destroyed:@.str = private unnamed_addr constant [7 x i8] &lt;null operand!&gt;, align 1
  Assertion failed: (use_empty() &amp;&amp; "Uses remain when a value is destroyed!"), function ~Value, file /private/tmp/llvm/llvm-3.6.0.src/lib/IR/Value.cpp, line 81.
  0  clang++                  0x000000011154d909 llvm::sys::PrintStackTrace(__sFILE*) + 57
  1  clang++                  0x000000011154e07b SignalHandler(int) + 555
  2  libsystem_platform.dylib 0x00007fffb7debb3a _sigtramp + 26
  3  libsystem_platform.dylib 0x00000000509ff1d0 _sigtramp + 2562799280
  4  clang++                  0x000000011154de36 abort + 22
  5  clang++                  0x000000011154de11 __assert_rtn + 81
  6  clang++                  0x00000001114f2104 llvm::Value::~Value() + 660
  7  clang++                  0x00000001114a63d1 llvm::GlobalVariable::~GlobalVariable() + 97
  8  clang++                  0x00000001114e3ba9 llvm::Module::~Module() + 105
  9  TestPass.dylib           0x000000011254d7dc (anonymous namespace)::TestPass::runOnModule(llvm::Module&amp;) + 524
  10 clang++                  0x00000001114cdc4e llvm::legacy::PassManagerImpl::run(llvm::Module&amp;) + 1054
  11 clang++                  0x000000010f43f49a clang::EmitBackendOutput(clang::DiagnosticsEngine&amp;, clang::CodeGenOptions const&amp;, clang::TargetOptions const&amp;, clang::LangOptions const&amp;, llvm::StringRef, llvm::Module*, clang::BackendAction, llvm::raw_ostream*) + 7098
  12 clang++                  0x000000010f57433d clang::BackendConsumer::HandleTranslationUnit(clang::ASTContext&amp;) + 509
  13 clang++                  0x000000010f609954 clang::ParseAST(clang::Sema&amp;, bool, bool) + 468
  14 clang++                  0x000000010f27aa53 clang::FrontendAction::Execute() + 67
  15 clang++                  0x000000010f24cb2c clang::CompilerInstance::ExecuteAction(clang::FrontendAction&amp;) + 956
  16 clang++                  0x000000010f20763a clang::ExecuteCompilerInvocation(clang::CompilerInstance*) + 4154
  17 clang++                  0x000000010f1fe65c cc1_main(llvm::ArrayRef&lt;char const*&gt;, char const*, void*) + 1068
  18 clang++                  0x000000010f2057ec main + 11660
  19 libdyld.dylib            0x00007fffb7bdc235 start + 1
  20 libdyld.dylib            0x0000000000000066 start + 1212300850
  Stack dump:
  0.      Program arguments: /opt/llvm-3.6.0/build/Release+Asserts/bin/clang++ -cc1 -triple thumbv7-none-linux-androideabi -S -disable-free -main-file-name test.cpp -mrelocation-model pic -pic-level 1 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -no-integrated-as -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu cortex-a8 -target-feature +soft-float-abi -target-feature +vfp3 -target-feature +d16 -target-feature -neon -target-abi aapcs-linux -mfloat-abi soft -target-linker-version 253.3 -g -dwarf-column-info -ffunction-sections -coverage-file /opt/test/obj/local/armeabi-v7a/objs/test/test.o -resource-dir /opt/llvm-3.6.0/build/Release+Asserts/bin/../lib/clang/3.6.0 -dependency-file /opt/test/obj/local/armeabi-v7a/objs/test/test.o.d -MT /opt/test/obj/local/armeabi-v7a/objs/test/test.o -MP -D NDEBUG -D ANDROID -I /Applications/android-ndk-r10e/sources/cxx-stl/llvm-libc++/libcxx/include -I /Applications/android-ndk-r10e/sources/cxx-stl/llvm-libc++/../llvm-libc++abi/libcxxabi/include -I /Applications/android-ndk-r10e/sources/cxx-stl/llvm-libc++/../../android/support/include -I /opt/test/jni -I /Applications/android-ndk-r10e/platforms/android-21/arch-arm/usr/include -internal-isystem /usr/local/include -internal-isystem /opt/llvm-3.6.0/build/Release+Asserts/bin/../lib/clang/3.6.0/include -internal-externc-isystem /include -internal-externc-isystem /usr/include -O1 -Wno-invalid-command-line-argument -Wno-unused-command-line-argument -Wformat -Werror=format-security -std=c++11 -fdeprecated-macro -fno-dwarf-directory-asm -fdebug-compilation-dir /opt/test/jni -ferror-limit 19 -fmessage-length 152 -stack-protector 2 -mstackrealign -fno-rtti -fno-signed-char -fobjc-runtime=gcc -fdiagnostics-show-option -fcolor-diagnostics -load /opt/test/TestPass.dylib -mllvm -debug-pass=Structure -o /var/folders/vq/53lxh89j7ts1rtc9gfg_s7f80000gq/T/test-f2326e.s -x c++ /opt/test/jni/test.cpp
  1.      &lt;eof&gt; parser at end of file
  2.      Per-module optimization passes
  3.      Running pass 'TestPass' on module '/opt/test/jni/test.cpp'.
  clang++: error: unable to execute command: Illegal instruction: 4
  clang++: error: clang frontend command failed due to signal (use -v to see invocation)
  clang version 3.6.0 (tags/RELEASE_360/final)
  Target: armv7-none-linux-androideabi
  Thread model: posix
  clang++: note: diagnostic msg: PLEASE submit a bug report to http://llvm.org/bugs/ and include the crash backtrace, preprocessed source, and associated run script.
  clang++: note: diagnostic msg:
  ********************
  
  PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:
  Preprocessed source(s) and associated run script(s) are located at:
  clang++: note: diagnostic msg: /var/folders/vq/53lxh89j7ts1rtc9gfg_s7f80000gq/T/test-773901.cpp
  clang++: note: diagnostic msg: /var/folders/vq/53lxh89j7ts1rtc9gfg_s7f80000gq/T/test-773901.sh
  clang++: note: diagnostic msg:
  
  ********************
  make: *** [/opt/test/obj/local/armeabi-v7a/objs/test/test.o] Error 254
  </code></pre>