[MLIR] Correct linkage of lowered globalop
authorWilliam S. Moses <gh@wsmoses.com>
Tue, 17 Aug 2021 22:22:04 +0000 (18:22 -0400)
committerWilliam S. Moses <gh@wsmoses.com>
Wed, 18 Aug 2021 15:09:43 +0000 (11:09 -0400)
LLVM considers global variables marked as externals to be defined within the module if it is initialized (including to an undef). Other external globals are considered as being defined externally and imported into the current translation unit. Lowering of MLIR Global Ops does not properly propagate undefined initializers, resulting in a global which is expected to be defined within the current TU, not being defined.

Differential Revision: https://reviews.llvm.org/D108252

mlir/lib/Conversion/MemRefToLLVM/MemRefToLLVM.cpp
mlir/test/Conversion/MemRefToLLVM/memref-to-llvm.mlir

index 2327fa0..e3aaef5 100644 (file)
@@ -454,9 +454,17 @@ struct GlobalMemrefOpLowering
         initialValue = elementsAttr.getValue({});
     }
 
-    rewriter.replaceOpWithNewOp<LLVM::GlobalOp>(
+    auto newGlobal = rewriter.replaceOpWithNewOp<LLVM::GlobalOp>(
         global, arrayTy, global.constant(), linkage, global.sym_name(),
         initialValue, /*alignment=*/0, type.getMemorySpaceAsInt());
+    if (!global.isExternal() && global.isUninitialized()) {
+      Block *blk = new Block();
+      newGlobal.getInitializerRegion().push_back(blk);
+      rewriter.setInsertionPointToStart(blk);
+      Value undef[] = {
+          rewriter.create<LLVM::UndefOp>(global.getLoc(), arrayTy)};
+      rewriter.create<LLVM::ReturnOp>(global.getLoc(), undef);
+    }
     return success();
   }
 };
index 4344f88..8e5f3dd 100644 (file)
@@ -623,7 +623,10 @@ func @transpose(%arg0: memref<?x?x?xf32, offset: ?, strides: [?, ?, 1]>) {
 
 // -----
 
-// CHECK: llvm.mlir.global external @gv0() : !llvm.array<2 x f32>
+// CHECK:   llvm.mlir.global external @gv0() : !llvm.array<2 x f32> {
+// CHECK-NEXT:     %0 = llvm.mlir.undef : !llvm.array<2 x f32>
+// CHECK-NEXT:     llvm.return %0 : !llvm.array<2 x f32>
+// CHECK-NEXT:   }
 memref.global @gv0 : memref<2xf32> = uninitialized
 
 // CHECK: llvm.mlir.global private @gv1() : !llvm.array<2 x f32>