title: How to dynamically allocate and access an array using LLVM API?
body: <p>I'd like to generate LLVM IR for a C++ code like this:</p>
  
  <pre><code>T *arr = (T*) malloc(sizeof(T) * 100);
  arr[0] = somevalue;
  </code></pre>
  
  <p>Here's my code:</p>
  
  <pre><code>llvm::Type* element_type = /... some T type .../;
  llvm::Type* int32type = llvm::Type::getInt32Ty(context);
  
  auto element_size = llvm::ConstantInt::get(int32type, data_layout.getTypeAllocSize(element_type));
  auto array_size = llvm::ConstantInt::get(int32type, 100);
  
  // malloc:
  auto malloc_inst = llvm::CallInst::CreateMalloc(
      ir_builder.GetInsertBlock(), 
      element_type-&gt;getPointerTo(), // T*
      element_type,                 // T
      element_size,                 // sizeof(T)
      array_size,                   // 100
      nullptr, 
      "")
  ir_builder.Insert(malloc_inst);
  
  // cast to T*:
  auto arr = ir_builder.CreatePointerCast(malloc_inst, element_type-&gt;getPointerTo());
  
  // arr[0] = somevalue:
  llvm::Value *value = /... some value of type T .../
  auto element_ptr = ir_builder.CreateInBoundsGEP(
      arr, { 
          llvm::ConstantInt::get(llvm::Type::getInt32Ty(context), 0),
          llvm::ConstantInt::get(llvm::Type::getInt32Ty(context), 0)
      });
  ir_builder.CreateStore(value, element_ptr)
  </code></pre>
  
  <p>However, when running generated IR I'm getting:</p>
  
  <pre><code>Assertion failed: (Ty &amp;&amp; "Invalid GetElementPtrInst indices for type!"), function checkGEPType, file /usr/local/opt/llvm/include/llvm/IR/Instructions.h, line 847
  </code></pre>
  
  <p>I tried different combinations of types passed to the GEP instruction, but it's obvious I'm missing something basic.
  Can someone point me to a working example for this?</p>