[llvm] [InstCombine] Retain inbounds when canonicalising add+gep (PR #72244)

John Brawn via llvm-commits llvm-commits at lists.llvm.org
Thu Jan 18 05:47:52 PST 2024


================
@@ -2450,10 +2450,51 @@ Instruction *InstCombinerImpl::visitGetElementPtrInst(GetElementPtrInst &GEP) {
       // as:
       //   %newptr = getelementptr i32, ptr %ptr, i64 %idx1
       //   %newgep = getelementptr i32, ptr %newptr, i64 %idx2
-      auto *NewPtr = Builder.CreateGEP(GEP.getResultElementType(),
-                                       GEP.getPointerOperand(), Idx1);
-      return GetElementPtrInst::Create(GEP.getResultElementType(), NewPtr,
-                                       Idx2);
+      // If %gep is inbounds then %newgep can be inbounds only if %newptr is as
+      // well, as an inbounds gep requires the base pointer to be inbounds. We
+      // can mark %newptr as inbounds if we have a loop like
+      //   for (i = 0; ...)
+      //     ptr[i+x]
+      // If x is the same in each loop iteration then we know that we have a
+      // series of geps starting with ptr[x], which means that ptr[x] must be
+      // inbounds.
----------------
john-brawn-arm wrote:

I've spent some time trying to implement something that can work given the problems you've highlighted, but I didn't get very far. The reason I was doing this was because loop flattening was no longer able to flatten any loops due to the lack of the inbounds qualifier, but I've decided instead to implement loop versioning in loop flattening (which is currently a TODO) as then it can handle the lack of inbounds, which is now #78576.

https://github.com/llvm/llvm-project/pull/72244


More information about the llvm-commits mailing list