title: How to get LLVM global variable constant value?
body: <p>I'm trying to get the float value from a global variable and set it as an instruction's operand.</p>
  
  <p>Here is what I want to do:</p>
  
  <pre><code>@a = private constant float 0x3FB99999A0000000
  
  ...
  %1 = load float, float* @a ---&gt; removed
  
  %3 = fmul fast %1, %2  ---&gt; %3 = fmul fast float 0x3FB99999A0000000, %2
  </code></pre>
  
  <p>Below is what I haved tried so far:</p>
  
  <pre><code>for (auto gv_iter = llvm_module.global_begin();gv_iter != llvm_module.global_end(); gv_iter++){ 
  
      llvm::GlobalVariable* gv = &amp;*gv_iter;
  
      for(auto user_of_gv : gv-&gt;users()){
  
          llvm::Instruction *instr_ld_gv = llvm::dyn_cast&lt;llvm::Instruction&gt;(user_of_gv);
          llvm::Value *val_gv = llvm::cast&lt;llvm::Value&gt;(instr_ld_gv);
  
          llvm::Constant *const_gv = gv-&gt;getInitializer();    
          llvm::ConstantFP *constfp_gv = llvm::dyn_cast&lt;llvm::ConstantFP&gt;(const_gv);
          float gv_fpval = (constfp_gv-&gt;getValueAPF()).convertToFloat(); 
  
          llvm::Constant *const_gv_opd = llvm::ConstantFP::get(llvm::Type::getFloatTy(llvm_context),gv_fpval); 
  
          for(auto user_of_load : val_gv-&gt;users()){ 
  
              llvm::Instruction *instr_exe_gv = llvm::dyn_cast&lt;llvm::Instruction&gt;(user_of_load);
  
              //P
              for(int operand_num = 0;operand_num &lt; instr_exe_gv-&gt;getNumOperands();operand_num++){ 
  
                  llvm::Value *val_instr_op =  instr_exe_gv-&gt;getOperand(operand_num);
  
                  if(val_instr_op == val_gv){
  
                      instr_exe_gv-&gt;setOperand(operand_num,const_gv_opd);
                      instr_ld_gv-&gt;removeFromParent();
  
                  }            
              }
          }
      }
  }
  </code></pre>
  
  <p>However, it'll cause segmentation fault when I tried to run my code.</p>
  
  <p>I'm sure that I have accessed the global variable and instruction I wanted
  by printing the value of </p>
  
  <p><code>gv_fpval</code> which is <code>0.1</code> because 0x3FB99999A0000000 equals  0.10000000149011612 in double </p>
  
  <p>precision. It seems that the program crashes at <code>setOperand()</code>.</p>