LLVM GEP and store vs load and insertvalue: Storing value to a pointer to an aggregate
<p>What is the difference between <code>getelementptr</code> and <code>store</code> vs. <code>load</code> and <code>insertvalue</code> when storing a value to a pointer to an aggregate type? Is one preferred in certain circumstances? And if so why? Or am I headed entirely in the wrong direction?</p>

<h2>Example:</h2>

<pre><code>; A contrived example
%X = type {i32, i64}

define i32 @main(i32 %argc, i8** %argv) {
entry:
  %sX.0 = alloca %X

  ; change the first value with GEP + store
  %val1 = getelementptr %X, %X* %sX.0, i32 0, i32 0
  store i32 42, i32* %val1

  ; change the second value with load + insertvalue
  %sX.1 = load %X, %X* %sX.0
  %sX.2 = insertvalue %X %sX.1, i64 42, 1
  store %X %sX.2, %X* %sX.0 ; I suppose this could be considered less than ideal
                            ; however in some cases it is nice to have the
                            ; struct `load`ed
  ret i32 0
}
</code></pre>

<p>Interestingly using <code>llc -O=0 ...</code> they both compile to the the same instructions. What amounts to the following, which is what I had hoped.</p>

<pre><code>movl $42, -16(%rsp) # GEP + store
movq $42, -8(%rsp)  # load + insertvalue
</code></pre>

<h2>Background:</h2>

<p>I was reading the <a href="http://llvm.org/releases/3.3/docs/LangRef.html" rel="nofollow noreferrer">LLVM Language Reference</a> and I was reading about <a href="http://llvm.org/releases/3.3/docs/LangRef.html#insertvalue-instruction" rel="nofollow noreferrer">insertvalue</a>. The reference notes the <code>extractvalue</code> instructions similarity with <a href="http://llvm.org/releases/3.3/docs/LangRef.html#getelementptr-instruction" rel="nofollow noreferrer">GEP</a> and the following differences.</p>

<blockquote>
  <p>The major differences to getelementptr indexing are:</p>
  
  <ul>
  <li><p>Since the value being indexed is not a pointer, the first index is omitted and assumed to be zero.</p></li>
  <li><p>At least one index must be specified.</p></li>
  <li><p>Not only struct indices but also array indices must be in bounds.</p></li>
  </ul>
</blockquote>

<p>The following question on StackOverflow also mentions the use of <code>getelementptr</code> and <code>insertvalue</code>, but for different reasons. <a href="https://stackoverflow.com/questions/8948879/llvm-insertvalue-bad-optimized">LLVM insertvalue bad optimized?</a></p>