title: LLVM BasicBlock pass
body: <p>I am a beginner of LLVM. I am trying to move among the instructions of a BasicBlock and I cannot. In this particular example, I try to get the previous instruction of the end instruction. I am trying 2 methods:</p>
  
  <ol>
  <li><p>I have the following sequence of code:</p>
  
  <pre><code>bool patternDC::runOnBasicBlock(BasicBlock &amp;BB) {
  ...
  if (BB.getTerminator())
    {
              Instruction* current = BB.getTerminator();
              errs() &lt;&lt; "\n LAST: "&lt;&lt;*current&lt;&lt;"\n";
  
          Instruction* prev = &amp;BB.back();
          errs() &lt;&lt; "\n PENULTIMATE: "&lt;&lt;*prev&lt;&lt;"\n";         
         ...
  </code></pre></li>
  </ol>
  
  <p>The terminal prints the SAME instruction. I don't know how back() works. (Definition at line 199 of file BasicBlock.h.)</p>
  
  <ol>
  <li><p>I also tried :</p>
  
  <pre><code>bool patternDC::runOnBasicBlock(BasicBlock &amp;BB) {
  ...
  BasicBlock::const_iterator I = BB.begin();
  BasicBlock::const_iterator E = BB.end();
  BasicBlock::const_iterator prev_iter,last_iter;
  prev_iter = NULL; last_iter = NULL;
  for(;I!=E;I++){
      prev_iter = last_iter;
      last_iter = I;
  }
  if(prev_iter){
      errs() &lt;&lt; "prev_iter: " &lt;&lt; *(dyn_cast&lt;Instruction&gt;(prev_iter)) &lt;&lt; "\n";
  }
  if(last_iter){
      errs() &lt;&lt; "last_iter: " &lt;&lt; *(dyn_cast&lt;Instruction&gt;(last_iter)) &lt;&lt; "\n";
  }
   // not related to the main question: uncomment the next line for an unusual      
  //behavior: lastlast is DIFFERENT from last.lastlast=section(BasicBlock)
    // errs() &lt;&lt; "lastlast: " &lt;&lt; *(dyn_cast&lt;Instruction&gt;(I)) &lt;&lt; "\n";
    ...
     Instruction* prev = *(dyn_cast&lt;Instruction*&gt;(prev_iter));
      errs() &lt;&lt; "\n prev: "&lt;&lt;*prev&lt;&lt;"\n";
  </code></pre></li>
  </ol>
  
  <p>The terminal prints out well prev and last, but I have compilation errors when trying to assign to Instruction* prev
  The Clang error is:
  ".....
  /home/alex/llvm/include/llvm/Support/Casting.h:51:28: error: ‘classof’ is not a member of ‘llvm::Instruction*’"</p>
  
  <p>If someone knows a better way to use any element from the basic block or knows why these are not working, please let me know :)</p>
  
  <p>Thank you,
  Alex</p>