https://github.com/bcardosolopes updated 
https://github.com/llvm/llvm-project/pull/238698

>From 43515a3aba3efb7b84ddb74bb40d358e9986145b Mon Sep 17 00:00:00 2001
From: Bruno Cardoso Lopes <[email protected]>
Date: Tue, 3 Nov 2026 12:08:10 -0800
Subject: [PATCH 1/5] [CIR] Keep CIR global types visible across lowering
 replacements

A lookup after a global is lowered finds the LLVM global, whose type
may have been adjusted during lowering. Stash the CIR type in a
transient cir.preconversion_sym_type attribute on every global
replacement and prefer it in readers; strip it on exit. Build
region-initialized globals beside the root op, swap them in after the
initializer visit, and maintain the cached symbol table explicitly at
every replacement. Read call musttail/inline attributes before the
replace erases the root op.

Fixes order-dependent GEP rejections for self-referential globals and
later globals referencing adjusted globals. No other test changes.
Func/alias upkeep and readers ride with the one-shot flip itself.

Assisted-by: Muse Code (Muse)
---
 clang/include/clang/CIR/Dialect/IR/CIROps.td  |   2 +-
 clang/include/clang/CIR/LoweringHelpers.h     |  14 +++
 .../CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp | 104 ++++++++++++++----
 clang/lib/CIR/Lowering/LoweringHelpers.cpp    |   8 +-
 .../test/CIR/CodeGen/global-self-reference.c  |  36 ++++++
 .../global-view-bulk-after-adjusted.cir       |  26 +++++
 6 files changed, 169 insertions(+), 21 deletions(-)
 create mode 100644 clang/test/CIR/CodeGen/global-self-reference.c
 create mode 100644 clang/test/CIR/Lowering/global-view-bulk-after-adjusted.cir

diff --git a/clang/include/clang/CIR/Dialect/IR/CIROps.td 
b/clang/include/clang/CIR/Dialect/IR/CIROps.td
index bd762aae3e1d7e..439b2308f538a1 100644
--- a/clang/include/clang/CIR/Dialect/IR/CIROps.td
+++ b/clang/include/clang/CIR/Dialect/IR/CIROps.td
@@ -3599,7 +3599,7 @@ def CIR_GlobalOp : CIR_RegionBranchOpBase<"global", [
       cir::GlobalOp op, mlir::Attribute init,
       mlir::ConversionPatternRewriter &rewriter) const;
 
-    mlir::LogicalResult setupRegionInitializedLLVMGlobalOp(
+    mlir::LLVM::GlobalOp setupRegionInitializedLLVMGlobalOp(
         cir::GlobalOp op, mlir::ConversionPatternRewriter &rewriter) const;
 
     llvm::SmallVector<mlir::NamedAttribute> lowerGlobalAttributes(
diff --git a/clang/include/clang/CIR/LoweringHelpers.h 
b/clang/include/clang/CIR/LoweringHelpers.h
index 18e4c5cd31a62e..1090318e1906bd 100644
--- a/clang/include/clang/CIR/LoweringHelpers.h
+++ b/clang/include/clang/CIR/LoweringHelpers.h
@@ -100,4 +100,18 @@ mlir::Type convertTypeForLoadStore(const 
mlir::TypeConverter &converter,
 mlir::Attribute getBitIntStorageAttr(mlir::ConversionPatternRewriter &rewriter,
                                      cir::IntAttr attr,
                                      const mlir::DataLayout &dataLayout);
+
+// Transient attribute holding a symbol's CIR type before lowering. Lookups
+// mid-conversion can find the already-lowered LLVM symbol instead of the
+// CIR op. Its type may have been adjusted during lowering (split rows,
+// flexible array), so readers that need the unadjusted CIR view use this
+// stash. The pass strips it at the end, so it never reaches the output.
+inline constexpr const char *kPreConversionSymType =
+    "cir.preconversion_sym_type";
+
+inline mlir::Type getPreConversionSymType(mlir::Operation *op) {
+  if (auto typeAttr = op->getAttrOfType<mlir::TypeAttr>(kPreConversionSymType))
+    return typeAttr.getValue();
+  return {};
+}
 #endif
diff --git a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp 
b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
index a48dbd04de84ac..61eb83180e7db8 100644
--- a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
+++ b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
@@ -51,6 +51,7 @@
 #include "clang/CIR/MissingFeatures.h"
 #include "clang/CIR/Passes.h"
 #include "llvm/ADT/MapVector.h"
+#include "llvm/ADT/ScopeExit.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/TypeSwitch.h"
 #include "llvm/IR/Module.h"
@@ -1079,7 +1080,14 @@ 
CIRAttrToValue::getAddressOfSymbol(mlir::FlatSymbolRefAttr symbol) {
   mlir::Operation *sourceSymbol =
       symbolTables.lookupSymbolIn(parentModule, symbol);
   if (auto llvmSymbol = dyn_cast<mlir::LLVM::GlobalOp>(sourceSymbol)) {
-    sourceType = llvmSymbol.getType();
+    // Prefer the stashed pre-conversion type: the LLVM global's type may
+    // have been adjusted (split rows, flexible array).
+    if (mlir::Type preType = getPreConversionSymType(llvmSymbol)) {
+      originalType = preType;
+      sourceType = convertTypeForMemory(*converter, dataLayout, originalType);
+    } else {
+      sourceType = llvmSymbol.getType();
+    }
     symName = llvmSymbol.getSymName();
     addrSpace = llvmSymbol.getAddrSpace();
   } else if (auto cirSymbol = dyn_cast<cir::GlobalOp>(sourceSymbol)) {
@@ -2623,6 +2631,10 @@ static mlir::LogicalResult rewriteCallOrInvoke(
 
   mlir::LLVM::CConv cconv = convertCallingConv(call.getCallingConv());
 
+  // The replace below erases the root op, so read what the CallOp branch
+  // needs first.
+  const bool mustTail = op->hasAttr(CIRDialect::getMustTailAttrName());
+  const std::optional<cir::InlineKind> inlineKind = call.getInlineKind();
   if (landingPadBlock) {
     assert(!cir::MissingFeatures::opCallInvokeAttrs());
     auto newOp = rewriter.replaceOpWithNewOp<mlir::LLVM::InvokeOp>(
@@ -2640,10 +2652,10 @@ static mlir::LogicalResult rewriteCallOrInvoke(
     newOp.setNoUnwind(noUnwind);
     newOp.setWillReturn(willReturn);
     newOp.setNoreturn(noReturn);
-    if (op->hasAttr(CIRDialect::getMustTailAttrName()))
+    if (mustTail)
       newOp.setTailCallKind(mlir::LLVM::TailCallKind::MustTail);
 
-    if (std::optional<cir::InlineKind> inlineKind = call.getInlineKind()) {
+    if (inlineKind) {
       newOp.setNoInline(*inlineKind == cir::InlineKind::NoInline);
       newOp.setInlineHint(*inlineKind == cir::InlineKind::InlineHint);
       newOp.setAlwaysInline(*inlineKind == cir::InlineKind::AlwaysInline);
@@ -3359,9 +3371,12 @@ convertTlsModelAttrToLLVM(TLSModelAttr attr) {
   return static_cast<mlir::LLVM::ThreadLocalMode>(attr.getValue());
 }
 
-/// Replace CIR global with a region initialized LLVM global and update
-/// insertion point to the end of the initializer block.
-mlir::LogicalResult
+/// Create the region-initialized LLVM global beside the CIR op and update
+/// insertion point to the end of the initializer block. Returns the new op,
+/// or null on failure. The caller owns the replacement: it runs the
+/// initializer visit with the old op still in the table, then swaps the
+/// table and erases the old op on success.
+mlir::LLVM::GlobalOp
 CIRToLLVMGlobalOpLowering::setupRegionInitializedLLVMGlobalOp(
     cir::GlobalOp op, mlir::ConversionPatternRewriter &rewriter) const {
   mlir::Type llvmType =
@@ -3373,7 +3388,7 @@ 
CIRToLLVMGlobalOpLowering::setupRegionInitializedLLVMGlobalOp(
     llvmType = adjustGlobalTypeForInit(llvmType, *init, *getTypeConverter(),
                                        dataLayout);
   if (!llvmType)
-    return mlir::failure();
+    return {};
 
   // FIXME: These default values are placeholders until the the equivalent
   //        attributes are available on cir.global ops. This duplicates code
@@ -3390,18 +3405,20 @@ 
CIRToLLVMGlobalOpLowering::setupRegionInitializedLLVMGlobalOp(
   const uint64_t alignment = op.getAlignment().value_or(0);
   const mlir::LLVM::Linkage linkage = convertLinkage(op.getLinkage());
   const StringRef symbol = op.getSymName();
-  mlir::SymbolRefAttr comdatAttr = getComdatAttr(op, rewriter);
 
   SmallVector<mlir::NamedAttribute> attributes =
       lowerGlobalAttributes(op, rewriter);
 
-  mlir::LLVM::GlobalOp newGlobalOp =
-      rewriter.replaceOpWithNewOp<mlir::LLVM::GlobalOp>(
-          op, llvmType, isConst, linkage, symbol, nullptr, alignment, 
addrSpace,
-          isDsoLocal, threadLocalMode, comdatAttr, attributes);
+  mlir::Type preConversionType = op.getSymType();
+  mlir::LLVM::GlobalOp newGlobalOp = mlir::LLVM::GlobalOp::create(
+      rewriter, op.getLoc(), llvmType, isConst, linkage, symbol, nullptr,
+      alignment, addrSpace, isDsoLocal, threadLocalMode, mlir::SymbolRefAttr{},
+      attributes);
+  newGlobalOp->setAttr(kPreConversionSymType,
+                       mlir::TypeAttr::get(preConversionType));
   rewriter.createBlock(&newGlobalOp.getRegion());
   rewriter.setInsertionPointToEnd(newGlobalOp.getInitializerBlock());
-  return mlir::success();
+  return newGlobalOp;
 }
 
 mlir::LogicalResult
@@ -3420,18 +3437,38 @@ 
CIRToLLVMGlobalOpLowering::matchAndRewriteRegionInitializedGlobal(
   // to the appropriate value.
   const mlir::Location loc = op.getLoc();
   mlir::ModuleOp moduleOp = op->getParentOfType<mlir::ModuleOp>();
-  if (failed(setupRegionInitializedLLVMGlobalOp(op, rewriter)))
+  // Build the cached table before the replacement exists, so the swap below
+  // drops a real entry instead of depending on duplicate tolerance.
+  auto &symbolTable = symbolTables.getSymbolTable(moduleOp);
+  // Create the replacement beside the root op, not via replaceOp: the table
+  // swap below and the visit both need the old op alive.
+  rewriter.setInsertionPoint(op);
+  mlir::LLVM::GlobalOp newGlobalOp =
+      setupRegionInitializedLLVMGlobalOp(op, rewriter);
+  if (!newGlobalOp)
     return mlir::failure();
-
+  // Keep the old op in the table during the visit so self-references
+  // resolve to the CIR type, not the possibly adjusted LLVM type.
   // Pass blockInfoAddr so that block address initializers (either as the whole
   // initializer or nested inside an aggregate) can be resolved by the
   // BlockAddrInfoAttr visitor.
   CIRAttrToValue valueConverter(loc, moduleOp, rewriter, symbolTables,
                                 typeConverter, &blockInfoAddr);
   mlir::Value value = valueConverter.visit(init);
-  if (!value)
+  if (!value) {
+    // Drop the speculative replacement; the table still holds the live
+    // root op for the driver to report on.
+    rewriter.eraseOp(newGlobalOp);
     return mlir::failure();
+  }
   mlir::LLVM::ReturnOp::create(rewriter, loc, value);
+  // Attach comdat only after the visit succeeds: creating it earlier would
+  // leave module-level ops behind on a failing compile.
+  if (mlir::SymbolRefAttr comdatAttr = getComdatAttr(op, rewriter))
+    newGlobalOp.setComdatAttr(comdatAttr);
+  symbolTable.remove(op);
+  symbolTable.insert(newGlobalOp);
+  rewriter.eraseOp(op);
   return mlir::success();
 }
 
@@ -3531,10 +3568,17 @@ mlir::LogicalResult 
CIRToLLVMGlobalOpLowering::matchAndRewrite(
         if (std::optional<mlir::Attribute> bulkInit = lowerConstArrayAttr(
                 constArr, symbolTables, typeConverter, modOp)) {
           mlir::SymbolRefAttr comdatAttr = getComdatAttr(op, rewriter);
-          rewriter.replaceOpWithNewOp<mlir::LLVM::GlobalOp>(
+          // The driver does not invalidate the cached symbol table, so
+          // maintain it explicitly: drop the old entry before replacement
+          // and register the new op after.
+          symbolTables.getSymbolTable(modOp).remove(op);
+          auto newGlobalOp = rewriter.replaceOpWithNewOp<mlir::LLVM::GlobalOp>(
               op, llvmType, isConst, linkage, symbol, bulkInit.value(),
               alignment, addrSpace, isDsoLocal, threadLocalMode, comdatAttr,
               attributes);
+          newGlobalOp->setAttr(kPreConversionSymType,
+                               mlir::TypeAttr::get(cirSymType));
+          symbolTables.getSymbolTable(modOp).insert(newGlobalOp);
           return mlir::success();
         }
       }
@@ -3550,9 +3594,16 @@ mlir::LogicalResult 
CIRToLLVMGlobalOpLowering::matchAndRewrite(
       if (std::optional<mlir::Attribute> bulkInit = lowerConstRecordAttr(
               constRecord, symbolTables, typeConverter, modOp)) {
         mlir::SymbolRefAttr comdatAttr = getComdatAttr(op, rewriter);
-        rewriter.replaceOpWithNewOp<mlir::LLVM::GlobalOp>(
+        // The driver does not invalidate the cached symbol table, so
+        // maintain it explicitly: drop the old entry before replacement
+        // and register the new op after.
+        symbolTables.getSymbolTable(modOp).remove(op);
+        auto newGlobalOp = rewriter.replaceOpWithNewOp<mlir::LLVM::GlobalOp>(
             op, llvmType, isConst, linkage, symbol, bulkInit.value(), 
alignment,
             addrSpace, isDsoLocal, threadLocalMode, comdatAttr, attributes);
+        newGlobalOp->setAttr(kPreConversionSymType,
+                             mlir::TypeAttr::get(cirSymType));
+        symbolTables.getSymbolTable(modOp).insert(newGlobalOp);
         return mlir::success();
       }
       return matchAndRewriteRegionInitializedGlobal(op, init.value(), 
rewriter);
@@ -3575,10 +3626,17 @@ mlir::LogicalResult 
CIRToLLVMGlobalOpLowering::matchAndRewrite(
   }
 
   mlir::SymbolRefAttr comdatAttr = getComdatAttr(op, rewriter);
-  rewriter.replaceOpWithNewOp<mlir::LLVM::GlobalOp>(
+  // The driver does not invalidate the cached symbol table, so
+  // maintain it explicitly: drop the old entry before replacement
+  // and register the new op after.
+  mlir::ModuleOp modOp = op->getParentOfType<mlir::ModuleOp>();
+  symbolTables.getSymbolTable(modOp).remove(op);
+  auto newGlobalOp = rewriter.replaceOpWithNewOp<mlir::LLVM::GlobalOp>(
       op, llvmType, isConst, linkage, symbol, init.value_or(mlir::Attribute()),
       alignment, addrSpace, isDsoLocal, threadLocalMode, comdatAttr,
       attributes);
+  newGlobalOp->setAttr(kPreConversionSymType, mlir::TypeAttr::get(cirSymType));
+  symbolTables.getSymbolTable(modOp).insert(newGlobalOp);
 
   return mlir::success();
 }
@@ -4879,6 +4937,14 @@ void ConvertCIRToLLVMPass::runOnOperation() {
   llvm::TimeTraceScope scope("Convert CIR to LLVM Pass");
 
   mlir::ModuleOp module = getOperation();
+  // The pre-conversion type snapshots never reach the output, however the
+  // pass exits. Snapshots only ever sit on module-level symbols.
+  mlir::StringAttr stashName =
+      mlir::StringAttr::get(&getContext(), kPreConversionSymType);
+  llvm::scope_exit stripPreConversionTypes([&] {
+    for (mlir::Operation &op : module.getBody()->getOperations())
+      op.removeAttr(stashName);
+  });
   mlir::DataLayout dl(module);
   mlir::LLVMTypeConverter converter(&getContext());
   prepareTypeConverter(converter, dl);
diff --git a/clang/lib/CIR/Lowering/LoweringHelpers.cpp 
b/clang/lib/CIR/Lowering/LoweringHelpers.cpp
index 1ab147c0f96396..693e73a70ec537 100644
--- a/clang/lib/CIR/Lowering/LoweringHelpers.cpp
+++ b/clang/lib/CIR/Lowering/LoweringHelpers.cpp
@@ -290,7 +290,13 @@ globalViewMatchesPointerLeaf(cir::GlobalViewAttr gv, 
mlir::ModuleOp moduleOp,
   mlir::Type sourceType;
   auto sourceSymbol = symbolTables.lookupSymbolIn(moduleOp, gv.getSymbol());
   if (auto llvmSymbol = mlir::dyn_cast<mlir::LLVM::GlobalOp>(sourceSymbol)) {
-    sourceType = llvmSymbol.getType();
+    // Prefer the stashed pre-conversion type: the lowered type may have been
+    // adjusted, which would answer differently depending on lowering order.
+    // Globals that were never CIR (no stash) keep the converted-type view.
+    if (mlir::Type preType = getPreConversionSymType(llvmSymbol))
+      sourceType = converter->convertType(preType);
+    else
+      sourceType = llvmSymbol.getType();
     sourceAddrSpace = llvmSymbol.getAddrSpace();
   } else if (auto cirSymbol = mlir::dyn_cast<cir::GlobalOp>(sourceSymbol)) {
     sourceType = converter->convertType(cirSymbol.getSymType());
diff --git a/clang/test/CIR/CodeGen/global-self-reference.c 
b/clang/test/CIR/CodeGen/global-self-reference.c
new file mode 100644
index 00000000000000..1848f3c50b950a
--- /dev/null
+++ b/clang/test/CIR/CodeGen/global-self-reference.c
@@ -0,0 +1,36 @@
+// RUN: split-file %s %t
+
+// A global whose initializer refers to itself must resolve the
+// self-reference to the CIR type. Warm and cold table cases are
+// separate TUs below, with different symbol names.
+
+//--- warm.c
+
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fclangir -emit-llvm 
%t/warm.c -o %t/warm-cir.ll
+// RUN: FileCheck --input-file=%t/warm-cir.ll %t/warm.c -check-prefix=LLVM
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -emit-llvm %t/warm.c -o 
%t/warm.ll
+// RUN: FileCheck --input-file=%t/warm.ll %t/warm.c -check-prefix=LLVM
+
+// LLVM: @arr = {{.*}}global <{ ptr, ptr, [98 x ptr] }> <{ ptr getelementptr 
{{.*}} i64 40), ptr getelementptr {{.*}} i64 56),
+// LLVM: @later = {{.*}}global ptr getelementptr {{.*}} @arr, i64 56)
+
+// Preceding globals so the module symbol table is cached.
+int x;
+int *px = &x;
+void *arr[100] = {&arr[5], &arr[7], 0};
+void **later = &arr[7];
+
+//--- cold.c
+
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fclangir -emit-llvm 
%t/cold.c -o %t/cold-cir.ll
+// RUN: FileCheck --input-file=%t/cold-cir.ll %t/cold.c -check-prefix=LLVM
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -emit-llvm %t/cold.c -o 
%t/cold.ll
+// RUN: FileCheck --input-file=%t/cold.ll %t/cold.c -check-prefix=LLVM
+
+// LLVM: @solo = {{.*}}global <{ ptr, ptr, [98 x ptr] }> <{ ptr getelementptr 
{{.*}} i64 40), ptr getelementptr {{.*}} i64 56),
+// LLVM: @follower = {{.*}}global ptr getelementptr {{.*}} @solo, i64 56)
+
+// The self-referential global is the first symbol: in the old code the
+// table was still cold here and the lowering failed.
+void *solo[100] = {&solo[5], &solo[7], 0};
+void **follower = &solo[7];
diff --git a/clang/test/CIR/Lowering/global-view-bulk-after-adjusted.cir 
b/clang/test/CIR/Lowering/global-view-bulk-after-adjusted.cir
new file mode 100644
index 00000000000000..4a64a3d1cfb798
--- /dev/null
+++ b/clang/test/CIR/Lowering/global-view-bulk-after-adjusted.cir
@@ -0,0 +1,26 @@
+// RUN: cir-opt %s --cir-to-llvm -o - | FileCheck %s
+
+!void = !cir.void
+!arr_ty = !cir.array<!cir.ptr<!void> x 100>
+!bulk_ty = !cir.array<!cir.ptr<!cir.array<!cir.ptr<!void> x 100>> x 2>
+
+module attributes {cir.triple = "x86_64-unknown-linux-gnu"} {
+  // Region-initialized, so its LLVM type is adjusted (grouped struct).
+  cir.global external dso_local @arr = #cir.const_array<[
+      #cir.global_view<@arr, [5 : i32]> : !cir.ptr<!void>,
+      #cir.global_view<@arr, [7 : i32]> : !cir.ptr<!void>
+  ], trailing_zeros> : !arr_ty
+
+  // Unindexed views of @arr: bulk lowering must see the CIR array type
+  // via the stash, not the adjusted LLVM struct type.
+  cir.global external dso_local @bulk = #cir.const_array<[
+      #cir.global_view<@arr> : !cir.ptr<!cir.array<!cir.ptr<!void> x 100>>,
+      #cir.global_view<@arr> : !cir.ptr<!cir.array<!cir.ptr<!void> x 100>>
+  ]> : !bulk_ty
+}
+
+// CHECK: llvm.mlir.global external @arr
+// CHECK: llvm.insertvalue
+// CHECK: llvm.mlir.global external @bulk([@arr, @arr])
+// CHECK-NOT: llvm.insertvalue
+// CHECK-NOT: llvm.return

>From 5b428660eb63f8aa6c68846040b48ca80533df31 Mon Sep 17 00:00:00 2001
From: Bruno Cardoso Lopes <[email protected]>
Date: Wed, 4 Nov 2026 10:49:22 -0800
Subject: [PATCH 2/5] Address review: stash and upkeep for aliases, vtable
 reader

Function and variable alias replacements now maintain the cached
symbol table and stash the pre-conversion type, like the global
replacements. getAddressOfSymbol reads the stash on alias lookups.
getValueForVTableSymbol prefers the stashed type over the possibly
adjusted LLVM global type.
---
 .../CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp | 44 +++++++++++++++++--
 1 file changed, 40 insertions(+), 4 deletions(-)

diff --git a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp 
b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
index 61eb83180e7db8..285640c77429b3 100644
--- a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
+++ b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
@@ -1107,8 +1107,17 @@ 
CIRAttrToValue::getAddressOfSymbol(mlir::FlatSymbolRefAttr symbol) {
     symName = fun.getSymName();
     addrSpace = cirDataLayout.getProgramAddressSpace();
   } else if (auto alias = dyn_cast<mlir::LLVM::AliasOp>(sourceSymbol)) {
-    sourceType = alias.getType();
+    if (mlir::Type preType = getPreConversionSymType(alias)) {
+      originalType = preType;
+      if (mlir::isa<cir::FuncType>(preType))
+        sourceType = converter->convertType(originalType);
+      else
+        sourceType = convertTypeForMemory(*converter, dataLayout, 
originalType);
+    } else {
+      sourceType = alias.getType();
+    }
     symName = alias.getSymName();
+    addrSpace = alias.getAddrSpace();
   } else {
     llvm_unreachable("Unexpected GlobalOp type");
   }
@@ -3149,11 +3158,18 @@ mlir::LogicalResult 
CIRToLLVMFuncOpLowering::matchAndRewriteAlias(
 
   mlir::Location loc = op.getLoc();
   // Create the alias before replacing: without pattern rollback the
-  // replace erases the root op immediately.
+  // replace erases the root op immediately. The driver does not
+  // invalidate the cached symbol table either, so build it before the
+  // replacement exists and maintain it explicitly below.
+  mlir::ModuleOp modOp = op->getParentOfType<mlir::ModuleOp>();
+  mlir::Type preConversionType = op.getFunctionType();
+  symbolTables.getSymbolTable(modOp);
   auto aliasOp = mlir::LLVM::AliasOp::create(
       rewriter, loc, ty, convertLinkage(op.getLinkage()), op.getName(),
       op.getDsoLocal(), mlir::LLVM::ThreadLocalMode::NotThreadLocal,
       attributes);
+  aliasOp->setAttr(kPreConversionSymType,
+                   mlir::TypeAttr::get(preConversionType));
   aliasOp.setVisibility_(
       lowerCIRVisibilityToLLVMVisibility(op.getGlobalVisibility()));
   {
@@ -3167,7 +3183,9 @@ mlir::LogicalResult 
CIRToLLVMFuncOpLowering::matchAndRewriteAlias(
         mlir::LLVM::AddressOfOp::create(rewriter, loc, ptrTy, aliasee);
     mlir::LLVM::ReturnOp::create(rewriter, loc, addrOp);
   }
+  symbolTables.getSymbolTable(modOp).remove(op);
   rewriter.replaceOp(op, aliasOp);
+  symbolTables.getSymbolTable(modOp).insert(aliasOp);
 
   return mlir::success();
 }
@@ -3526,10 +3544,15 @@ mlir::LogicalResult 
CIRToLLVMGlobalOpLowering::matchAndRewrite(
   if (std::optional<llvm::StringRef> aliasee = op.getAliasee()) {
     mlir::Location loc = op.getLoc();
     // Create the alias before replacing: without pattern rollback the
-    // replace erases the root op immediately.
+    // replace erases the root op immediately. The driver does not
+    // invalidate the cached symbol table either, so build it before the
+    // replacement exists and maintain it explicitly below.
+    mlir::ModuleOp modOp = op->getParentOfType<mlir::ModuleOp>();
+    symbolTables.getSymbolTable(modOp);
     auto aliasOp =
         mlir::LLVM::AliasOp::create(rewriter, loc, llvmType, linkage, symbol,
                                     isDsoLocal, threadLocalMode, attributes);
+    aliasOp->setAttr(kPreConversionSymType, mlir::TypeAttr::get(cirSymType));
     {
       mlir::OpBuilder::InsertionGuard guard(rewriter);
       rewriter.createBlock(&aliasOp.getInitializerRegion());
@@ -3539,7 +3562,9 @@ mlir::LogicalResult 
CIRToLLVMGlobalOpLowering::matchAndRewrite(
           mlir::LLVM::AddressOfOp::create(rewriter, loc, ptrTy, *aliasee);
       mlir::LLVM::ReturnOp::create(rewriter, loc, addrOp);
     }
+    symbolTables.getSymbolTable(modOp).remove(op);
     rewriter.replaceOp(op, aliasOp);
+    symbolTables.getSymbolTable(modOp).insert(aliasOp);
     return mlir::success();
   }
 
@@ -5386,7 +5411,18 @@ getValueForVTableSymbol(mlir::Operation *op,
   auto module = op->getParentOfType<mlir::ModuleOp>();
   mlir::Operation *symbol = symbolTables.lookupSymbolIn(module, nameAttr);
   if (auto llvmSymbol = mlir::dyn_cast<mlir::LLVM::GlobalOp>(symbol)) {
-    eltType = llvmSymbol.getType();
+    // Prefer the stashed pre-conversion type: the LLVM global's type may
+    // have been adjusted (split rows, flexible array).
+    if (mlir::Type preType = getPreConversionSymType(llvmSymbol)) {
+      eltType = converter->convertType(preType);
+      if (!eltType) {
+        emitTypeConversionError(op, preType)
+            << " for vtable symbol " << nameAttr;
+        return {};
+      }
+    } else {
+      eltType = llvmSymbol.getType();
+    }
   } else if (auto cirSymbol = mlir::dyn_cast<cir::GlobalOp>(symbol)) {
     eltType = converter->convertType(cirSymbol.getSymType());
     if (!eltType) {

>From a6f12aa1c4df1bec4e375553b6c9205790316805 Mon Sep 17 00:00:00 2001
From: Bruno Cardoso Lopes <[email protected]>
Date: Wed, 4 Nov 2026 10:52:27 -0800
Subject: [PATCH 3/5] Address review: replaceCirGlobal helper for global
 replacements

The remove/replace/stash/insert sequence was repeated at three sites.
One helper enforces the ordering (table entry dropped before creation
so the replacement reuses the name). No behavior change.
---
 .../CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp | 65 ++++++++++---------
 1 file changed, 33 insertions(+), 32 deletions(-)

diff --git a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp 
b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
index 285640c77429b3..5c6a4225e6f917 100644
--- a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
+++ b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
@@ -3490,6 +3490,29 @@ 
CIRToLLVMGlobalOpLowering::matchAndRewriteRegionInitializedGlobal(
   return mlir::success();
 }
 
+// Replace a CIR global with an LLVM global, maintaining the cached symbol
+// table and stashing the CIR type for later lookups. The table entry is
+// dropped before creation so the replacement reuses the name.
+static mlir::LLVM::GlobalOp
+replaceCirGlobal(mlir::SymbolTableCollection &symbolTables, cir::GlobalOp op,
+                 mlir::Type llvmType, bool isConst, mlir::LLVM::Linkage 
linkage,
+                 llvm::StringRef symbol, mlir::Attribute init,
+                 uint64_t alignment, unsigned addrSpace, bool isDsoLocal,
+                 mlir::LLVM::ThreadLocalMode threadLocalMode,
+                 mlir::SymbolRefAttr comdatAttr,
+                 llvm::ArrayRef<mlir::NamedAttribute> attributes,
+                 mlir::ConversionPatternRewriter &rewriter) {
+  mlir::ModuleOp modOp = op->getParentOfType<mlir::ModuleOp>();
+  symbolTables.getSymbolTable(modOp).remove(op);
+  auto newGlobalOp = rewriter.replaceOpWithNewOp<mlir::LLVM::GlobalOp>(
+      op, llvmType, isConst, linkage, symbol, init, alignment, addrSpace,
+      isDsoLocal, threadLocalMode, comdatAttr, attributes);
+  newGlobalOp->setAttr(kPreConversionSymType,
+                       mlir::TypeAttr::get(op.getSymType()));
+  symbolTables.getSymbolTable(modOp).insert(newGlobalOp);
+  return newGlobalOp;
+}
+
 mlir::LogicalResult CIRToLLVMGlobalOpLowering::matchAndRewrite(
     cir::GlobalOp op, OpAdaptor adaptor,
     mlir::ConversionPatternRewriter &rewriter) const {
@@ -3593,17 +3616,9 @@ mlir::LogicalResult 
CIRToLLVMGlobalOpLowering::matchAndRewrite(
         if (std::optional<mlir::Attribute> bulkInit = lowerConstArrayAttr(
                 constArr, symbolTables, typeConverter, modOp)) {
           mlir::SymbolRefAttr comdatAttr = getComdatAttr(op, rewriter);
-          // The driver does not invalidate the cached symbol table, so
-          // maintain it explicitly: drop the old entry before replacement
-          // and register the new op after.
-          symbolTables.getSymbolTable(modOp).remove(op);
-          auto newGlobalOp = rewriter.replaceOpWithNewOp<mlir::LLVM::GlobalOp>(
-              op, llvmType, isConst, linkage, symbol, bulkInit.value(),
-              alignment, addrSpace, isDsoLocal, threadLocalMode, comdatAttr,
-              attributes);
-          newGlobalOp->setAttr(kPreConversionSymType,
-                               mlir::TypeAttr::get(cirSymType));
-          symbolTables.getSymbolTable(modOp).insert(newGlobalOp);
+          replaceCirGlobal(symbolTables, op, llvmType, isConst, linkage, 
symbol,
+                           bulkInit.value(), alignment, addrSpace, isDsoLocal,
+                           threadLocalMode, comdatAttr, attributes, rewriter);
           return mlir::success();
         }
       }
@@ -3619,16 +3634,9 @@ mlir::LogicalResult 
CIRToLLVMGlobalOpLowering::matchAndRewrite(
       if (std::optional<mlir::Attribute> bulkInit = lowerConstRecordAttr(
               constRecord, symbolTables, typeConverter, modOp)) {
         mlir::SymbolRefAttr comdatAttr = getComdatAttr(op, rewriter);
-        // The driver does not invalidate the cached symbol table, so
-        // maintain it explicitly: drop the old entry before replacement
-        // and register the new op after.
-        symbolTables.getSymbolTable(modOp).remove(op);
-        auto newGlobalOp = rewriter.replaceOpWithNewOp<mlir::LLVM::GlobalOp>(
-            op, llvmType, isConst, linkage, symbol, bulkInit.value(), 
alignment,
-            addrSpace, isDsoLocal, threadLocalMode, comdatAttr, attributes);
-        newGlobalOp->setAttr(kPreConversionSymType,
-                             mlir::TypeAttr::get(cirSymType));
-        symbolTables.getSymbolTable(modOp).insert(newGlobalOp);
+        replaceCirGlobal(symbolTables, op, llvmType, isConst, linkage, symbol,
+                         bulkInit.value(), alignment, addrSpace, isDsoLocal,
+                         threadLocalMode, comdatAttr, attributes, rewriter);
         return mlir::success();
       }
       return matchAndRewriteRegionInitializedGlobal(op, init.value(), 
rewriter);
@@ -3651,17 +3659,10 @@ mlir::LogicalResult 
CIRToLLVMGlobalOpLowering::matchAndRewrite(
   }
 
   mlir::SymbolRefAttr comdatAttr = getComdatAttr(op, rewriter);
-  // The driver does not invalidate the cached symbol table, so
-  // maintain it explicitly: drop the old entry before replacement
-  // and register the new op after.
-  mlir::ModuleOp modOp = op->getParentOfType<mlir::ModuleOp>();
-  symbolTables.getSymbolTable(modOp).remove(op);
-  auto newGlobalOp = rewriter.replaceOpWithNewOp<mlir::LLVM::GlobalOp>(
-      op, llvmType, isConst, linkage, symbol, init.value_or(mlir::Attribute()),
-      alignment, addrSpace, isDsoLocal, threadLocalMode, comdatAttr,
-      attributes);
-  newGlobalOp->setAttr(kPreConversionSymType, mlir::TypeAttr::get(cirSymType));
-  symbolTables.getSymbolTable(modOp).insert(newGlobalOp);
+  replaceCirGlobal(symbolTables, op, llvmType, isConst, linkage, symbol,
+                   init.value_or(mlir::Attribute()), alignment, addrSpace,
+                   isDsoLocal, threadLocalMode, comdatAttr, attributes,
+                   rewriter);
 
   return mlir::success();
 }

>From f0236f1a719410f43d982ea0afb7508602f4119b Mon Sep 17 00:00:00 2001
From: Bruno Cardoso Lopes <[email protected]>
Date: Wed, 4 Nov 2026 10:53:43 -0800
Subject: [PATCH 4/5] Address review: test nits and comdat comment

Describe the cold-table case directly instead of via old-code
behavior, drop the redundant CHECK-NOT, and scope the comdat comment
to what deferring it delivers.
---
 clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp         | 4 ++--
 clang/test/CIR/CodeGen/global-self-reference.c              | 3 +--
 clang/test/CIR/Lowering/global-view-bulk-after-adjusted.cir | 1 -
 3 files changed, 3 insertions(+), 5 deletions(-)

diff --git a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp 
b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
index 5c6a4225e6f917..b2dc3c313c99a2 100644
--- a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
+++ b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
@@ -3480,8 +3480,8 @@ 
CIRToLLVMGlobalOpLowering::matchAndRewriteRegionInitializedGlobal(
     return mlir::failure();
   }
   mlir::LLVM::ReturnOp::create(rewriter, loc, value);
-  // Attach comdat only after the visit succeeds: creating it earlier would
-  // leave module-level ops behind on a failing compile.
+  // Attach comdat only after the visit succeeds, so the failure path
+  // above only has the new global itself to drop.
   if (mlir::SymbolRefAttr comdatAttr = getComdatAttr(op, rewriter))
     newGlobalOp.setComdatAttr(comdatAttr);
   symbolTable.remove(op);
diff --git a/clang/test/CIR/CodeGen/global-self-reference.c 
b/clang/test/CIR/CodeGen/global-self-reference.c
index 1848f3c50b950a..cccbbfa5c1ed3e 100644
--- a/clang/test/CIR/CodeGen/global-self-reference.c
+++ b/clang/test/CIR/CodeGen/global-self-reference.c
@@ -30,7 +30,6 @@ void **later = &arr[7];
 // LLVM: @solo = {{.*}}global <{ ptr, ptr, [98 x ptr] }> <{ ptr getelementptr 
{{.*}} i64 40), ptr getelementptr {{.*}} i64 56),
 // LLVM: @follower = {{.*}}global ptr getelementptr {{.*}} @solo, i64 56)
 
-// The self-referential global is the first symbol: in the old code the
-// table was still cold here and the lowering failed.
+// Cold table: the self-referential global is the first symbol in the TU.
 void *solo[100] = {&solo[5], &solo[7], 0};
 void **follower = &solo[7];
diff --git a/clang/test/CIR/Lowering/global-view-bulk-after-adjusted.cir 
b/clang/test/CIR/Lowering/global-view-bulk-after-adjusted.cir
index 4a64a3d1cfb798..59403ca54f5aae 100644
--- a/clang/test/CIR/Lowering/global-view-bulk-after-adjusted.cir
+++ b/clang/test/CIR/Lowering/global-view-bulk-after-adjusted.cir
@@ -23,4 +23,3 @@ module attributes {cir.triple = "x86_64-unknown-linux-gnu"} {
 // CHECK: llvm.insertvalue
 // CHECK: llvm.mlir.global external @bulk([@arr, @arr])
 // CHECK-NOT: llvm.insertvalue
-// CHECK-NOT: llvm.return

>From ae9a7fc8db8137799a63d8d1c03ea6a88691f2c3 Mon Sep 17 00:00:00 2001
From: Bruno Cardoso Lopes <[email protected]>
Date: Wed, 4 Nov 2026 10:59:49 -0800
Subject: [PATCH 5/5] Address review: read the CIR type before replacing in
 replaceCirGlobal

The helper read op.getSymType() after replaceOpWithNewOp, which erases
the root op without rollback. Harmless today, UAF under one-shot.
Capture it first, like the sites it replaced.
---
 clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp 
b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
index b2dc3c313c99a2..db8673f476a69f 100644
--- a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
+++ b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
@@ -3503,12 +3503,13 @@ replaceCirGlobal(mlir::SymbolTableCollection 
&symbolTables, cir::GlobalOp op,
                  llvm::ArrayRef<mlir::NamedAttribute> attributes,
                  mlir::ConversionPatternRewriter &rewriter) {
   mlir::ModuleOp modOp = op->getParentOfType<mlir::ModuleOp>();
+  // Read before the replace erases the root op.
+  mlir::Type cirSymType = op.getSymType();
   symbolTables.getSymbolTable(modOp).remove(op);
   auto newGlobalOp = rewriter.replaceOpWithNewOp<mlir::LLVM::GlobalOp>(
       op, llvmType, isConst, linkage, symbol, init, alignment, addrSpace,
       isDsoLocal, threadLocalMode, comdatAttr, attributes);
-  newGlobalOp->setAttr(kPreConversionSymType,
-                       mlir::TypeAttr::get(op.getSymType()));
+  newGlobalOp->setAttr(kPreConversionSymType, mlir::TypeAttr::get(cirSymType));
   symbolTables.getSymbolTable(modOp).insert(newGlobalOp);
   return newGlobalOp;
 }

_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to