[Mlir-commits] [mlir] [WIP][mlir][EmitC] Model lvalues as a type in EmitC (PR #91475)

Simon Camphausen llvmlistbot at llvm.org
Thu Jun 6 00:47:44 PDT 2024


https://github.com/simon-camp updated https://github.com/llvm/llvm-project/pull/91475

>From 6d085d7372f7fbf1d9cd4e974026bea6d42c3ed6 Mon Sep 17 00:00:00 2001
From: Simon Camphausen <simon.camphausen at iml.fraunhofer.de>
Date: Tue, 4 Jun 2024 11:55:43 +0000
Subject: [PATCH 1/2] Add lvalue type

---
 mlir/include/mlir/Dialect/EmitC/IR/EmitC.td   |  43 +++++--
 .../mlir/Dialect/EmitC/IR/EmitCTypes.td       |  18 +++
 .../MemRefToEmitC/MemRefToEmitC.cpp           |   7 +-
 mlir/lib/Conversion/SCFToEmitC/SCFToEmitC.cpp |  38 +++++--
 mlir/lib/Dialect/EmitC/IR/EmitC.cpp           | 107 ++++++++++++++----
 .../EmitC/Transforms/FormExpressions.cpp      |   3 +-
 mlir/lib/Target/Cpp/TranslateToCpp.cpp        |  21 +++-
 .../MemRefToEmitC/memref-to-emitc.mlir        |  24 ++--
 mlir/test/Conversion/SCFToEmitC/for.mlir      |  54 ++++-----
 mlir/test/Conversion/SCFToEmitC/if.mlir       |  22 ++--
 mlir/test/Dialect/EmitC/invalid_ops.mlir      |  61 +++++-----
 mlir/test/Dialect/EmitC/invalid_types.mlir    |  66 ++++++++---
 mlir/test/Dialect/EmitC/ops.mlir              |  21 ++--
 mlir/test/Dialect/EmitC/transforms.mlir       |  48 ++------
 mlir/test/Dialect/EmitC/types.mlir            |  19 +++-
 mlir/test/Target/Cpp/common-cpp.mlir          |  19 +++-
 mlir/test/Target/Cpp/expressions.mlir         |  84 ++++++++------
 mlir/test/Target/Cpp/for.mlir                 |  88 ++++++++------
 mlir/test/Target/Cpp/global.mlir              |  96 +++++++++++++---
 mlir/test/Target/Cpp/if.mlir                  |  12 +-
 mlir/test/Target/Cpp/invalid.mlir             |   2 +-
 mlir/test/Target/Cpp/lvalue.mlir              |  22 ++++
 mlir/test/Target/Cpp/subscript.mlir           | 106 ++++++++++++-----
 mlir/test/Target/Cpp/variable.mlir            |  16 +--
 24 files changed, 672 insertions(+), 325 deletions(-)
 create mode 100644 mlir/test/Target/Cpp/lvalue.mlir

diff --git a/mlir/include/mlir/Dialect/EmitC/IR/EmitC.td b/mlir/include/mlir/Dialect/EmitC/IR/EmitC.td
index 5da8593f59563..cc91af6fbe818 100644
--- a/mlir/include/mlir/Dialect/EmitC/IR/EmitC.td
+++ b/mlir/include/mlir/Dialect/EmitC/IR/EmitC.td
@@ -97,9 +97,9 @@ def EmitC_ApplyOp : EmitC_Op<"apply", [CExpression]> {
   }];
   let arguments = (ins
     Arg<StrAttr, "the operator to apply">:$applicableOperator,
-    EmitCType:$operand
+    AnyTypeOf<[EmitCType, EmitC_LValueType]>:$operand
   );
-  let results = (outs EmitCType:$result);
+  let results = (outs AnyTypeOf<[EmitCType, EmitC_LValueType]>:$result);
   let assemblyFormat = [{
     $applicableOperator `(` $operand `)` attr-dict `:` functional-type($operand, results)
   }];
@@ -835,6 +835,20 @@ def EmitC_LogicalOrOp : EmitC_BinaryOp<"logical_or", [CExpression]> {
   let assemblyFormat = "operands attr-dict `:` type(operands)";
 }
 
+def EmitC_LValueLoadOp : EmitC_Op<"lvalue_load", [
+  TypesMatchWith<"result type matches value type of 'operand'",
+                  "operand", "result",
+                  "::llvm::cast<LValueType>($_self).getValue()">
+]> {
+  let summary = "load an lvalue by assigning it to a local variable";
+  let description = [{}];
+
+  let arguments = (ins EmitC_LValueType:$operand);
+  let results = (outs AnyType:$result);
+
+  let assemblyFormat = "$operand attr-dict `:` type($operand)"; 
+}
+
 def EmitC_MulOp : EmitC_BinaryOp<"mul", [CExpression]> {
   let summary = "Multiplication operation";
   let description = [{
@@ -1009,7 +1023,7 @@ def EmitC_VariableOp : EmitC_Op<"variable", []> {
   }];
 
   let arguments = (ins EmitC_OpaqueOrTypedAttr:$value);
-  let results = (outs EmitCType);
+  let results = (outs AnyTypeOf<[EmitC_ArrayType, EmitC_LValueType]>);
 
   let hasVerifier = 1;
 }
@@ -1079,7 +1093,7 @@ def EmitC_GetGlobalOp : EmitC_Op<"get_global",
   }];
 
   let arguments = (ins FlatSymbolRefAttr:$name);
-  let results = (outs EmitCType:$result);
+  let results = (outs AnyTypeOf<[EmitC_ArrayType, EmitC_LValueType]>:$result);
   let assemblyFormat = "$name `:` type($result) attr-dict";
 }
 
@@ -1137,7 +1151,7 @@ def EmitC_AssignOp : EmitC_Op<"assign", []> {
     ```
   }];
 
-  let arguments = (ins EmitCType:$var, EmitCType:$value);
+  let arguments = (ins EmitC_LValueType:$var, EmitCType:$value);
   let results = (outs);
 
   let hasVerifier = 1;
@@ -1243,15 +1257,26 @@ def EmitC_SubscriptOp : EmitC_Op<"subscript", []> {
       EmitC_PointerType]>,
     "the value to subscript">:$value,
     Variadic<EmitCType>:$indices);
-  let results = (outs EmitCType:$result);
+  let results = (outs EmitC_LValueType:$result);
 
   let builders = [
     OpBuilder<(ins "TypedValue<ArrayType>":$array, "ValueRange":$indices), [{
-      build($_builder, $_state, array.getType().getElementType(), array, indices);
+      build(
+        $_builder,
+        $_state,
+        emitc::LValueType::get(array.getType().getElementType()),
+        array,
+        indices
+      );
     }]>,
     OpBuilder<(ins "TypedValue<PointerType>":$pointer, "Value":$index), [{
-      build($_builder, $_state, pointer.getType().getPointee(), pointer,
-            ValueRange{index});
+      build(
+        $_builder,
+        $_state,
+        emitc::LValueType::get(pointer.getType().getPointee()),
+        pointer,
+        ValueRange{index}
+      );
     }]>
   ];
 
diff --git a/mlir/include/mlir/Dialect/EmitC/IR/EmitCTypes.td b/mlir/include/mlir/Dialect/EmitC/IR/EmitCTypes.td
index 444395b915e25..fc795962a3e5b 100644
--- a/mlir/include/mlir/Dialect/EmitC/IR/EmitCTypes.td
+++ b/mlir/include/mlir/Dialect/EmitC/IR/EmitCTypes.td
@@ -83,6 +83,23 @@ def EmitC_ArrayType : EmitC_Type<"Array", "array", [ShapedTypeInterface]> {
   let hasCustomAssemblyFormat = 1;
 }
 
+def EmitC_LValueType : EmitC_Type<"LValue", "lvalue"> {
+  let summary = "EmitC lvalue type";
+
+  let description = [{
+    Values of this type can be assigned to and their address can be taken.
+  }];
+
+  let parameters = (ins "Type":$value);
+  let builders = [
+    TypeBuilderWithInferredContext<(ins "Type":$value), [{
+      return $_get(value.getContext(), value);
+    }]>
+  ];
+  let assemblyFormat = "`<` qualified($value) `>`";
+  let genVerifyDecl = 1;
+}
+
 def EmitC_OpaqueType : EmitC_Type<"Opaque", "opaque"> {
   let summary = "EmitC opaque type";
 
@@ -128,6 +145,7 @@ def EmitC_PointerType : EmitC_Type<"Pointer", "ptr"> {
     }]>
   ];
   let assemblyFormat = "`<` qualified($pointee) `>`";
+  let genVerifyDecl = 1;
 }
 
 #endif // MLIR_DIALECT_EMITC_IR_EMITCTYPES
diff --git a/mlir/lib/Conversion/MemRefToEmitC/MemRefToEmitC.cpp b/mlir/lib/Conversion/MemRefToEmitC/MemRefToEmitC.cpp
index e0c421741b305..2e8fbbad14d40 100644
--- a/mlir/lib/Conversion/MemRefToEmitC/MemRefToEmitC.cpp
+++ b/mlir/lib/Conversion/MemRefToEmitC/MemRefToEmitC.cpp
@@ -137,12 +137,7 @@ struct ConvertLoad final : public OpConversionPattern<memref::LoadOp> {
     auto subscript = rewriter.create<emitc::SubscriptOp>(
         op.getLoc(), arrayValue, operands.getIndices());
 
-    auto noInit = emitc::OpaqueAttr::get(getContext(), "");
-    auto var =
-        rewriter.create<emitc::VariableOp>(op.getLoc(), resultTy, noInit);
-
-    rewriter.create<emitc::AssignOp>(op.getLoc(), var, subscript);
-    rewriter.replaceOp(op, var);
+    rewriter.replaceOpWithNewOp<emitc::LValueLoadOp>(op, resultTy, subscript);
     return success();
   }
 };
diff --git a/mlir/lib/Conversion/SCFToEmitC/SCFToEmitC.cpp b/mlir/lib/Conversion/SCFToEmitC/SCFToEmitC.cpp
index 367142a520742..c9b5775bc9eec 100644
--- a/mlir/lib/Conversion/SCFToEmitC/SCFToEmitC.cpp
+++ b/mlir/lib/Conversion/SCFToEmitC/SCFToEmitC.cpp
@@ -63,9 +63,10 @@ static SmallVector<Value> createVariablesForResults(T op,
 
   for (OpResult result : op.getResults()) {
     Type resultType = result.getType();
+    Type varType = emitc::LValueType::get(resultType);
     emitc::OpaqueAttr noInit = emitc::OpaqueAttr::get(context, "");
     emitc::VariableOp var =
-        rewriter.create<emitc::VariableOp>(loc, resultType, noInit);
+        rewriter.create<emitc::VariableOp>(loc, varType, noInit);
     resultVariables.push_back(var);
   }
 
@@ -100,8 +101,6 @@ LogicalResult ForLowering::matchAndRewrite(ForOp forOp,
 
   // Create an emitc::variable op for each result. These variables will be
   // assigned to by emitc::assign ops within the loop body.
-  SmallVector<Value> resultVariables =
-      createVariablesForResults(forOp, rewriter);
   SmallVector<Value> iterArgsVariables =
       createVariablesForResults(forOp, rewriter);
 
@@ -115,18 +114,36 @@ LogicalResult ForLowering::matchAndRewrite(ForOp forOp,
   // Erase the auto-generated terminator for the lowered for op.
   rewriter.eraseOp(loweredBody->getTerminator());
 
+  SmallVector<Value> iterArgsValues;
+  {
+    PatternRewriter::InsertionGuard guard(rewriter);
+    rewriter.setInsertionPointToEnd(loweredBody);
+
+    for (auto &arg : iterArgsVariables) {
+      Type type = cast<emitc::LValueType>(arg.getType()).getValue();
+      iterArgsValues.push_back(
+          rewriter.create<emitc::LValueLoadOp>(loc, type, arg));
+    }
+  }
+
   SmallVector<Value> replacingValues;
   replacingValues.push_back(loweredFor.getInductionVar());
-  replacingValues.append(iterArgsVariables.begin(), iterArgsVariables.end());
+  replacingValues.append(iterArgsValues.begin(), iterArgsValues.end());
 
   rewriter.mergeBlocks(forOp.getBody(), loweredBody, replacingValues);
   lowerYield(iterArgsVariables, rewriter,
              cast<scf::YieldOp>(loweredBody->getTerminator()));
 
   // Copy iterArgs into results after the for loop.
-  assignValues(iterArgsVariables, resultVariables, rewriter, loc);
+  SmallVector<Value> resultValues;
 
-  rewriter.replaceOp(forOp, resultVariables);
+  for (auto &arg : iterArgsVariables) {
+    Type type = cast<emitc::LValueType>(arg.getType()).getValue();
+    resultValues.push_back(
+        rewriter.create<emitc::LValueLoadOp>(loc, type, arg));
+  }
+
+  rewriter.replaceOp(forOp, resultValues);
   return success();
 }
 
@@ -178,7 +195,14 @@ LogicalResult IfLowering::matchAndRewrite(IfOp ifOp,
     lowerRegion(elseRegion, loweredElseRegion);
   }
 
-  rewriter.replaceOp(ifOp, resultVariables);
+  rewriter.setInsertionPointAfter(ifOp);
+  SmallVector<Value> results;
+  for (auto &resVar : resultVariables) {
+    Type type = cast<emitc::LValueType>(resVar.getType()).getValue();
+    results.push_back(rewriter.create<emitc::LValueLoadOp>(loc, type, resVar));
+  }
+
+  rewriter.replaceOp(ifOp, results);
   return success();
 }
 
diff --git a/mlir/lib/Dialect/EmitC/IR/EmitC.cpp b/mlir/lib/Dialect/EmitC/IR/EmitC.cpp
index 20f47574b25ad..43cf410e8889c 100644
--- a/mlir/lib/Dialect/EmitC/IR/EmitC.cpp
+++ b/mlir/lib/Dialect/EmitC/IR/EmitC.cpp
@@ -61,6 +61,9 @@ void mlir::emitc::buildTerminatedBody(OpBuilder &builder, Location loc) {
 bool mlir::emitc::isSupportedEmitCType(Type type) {
   if (llvm::isa<emitc::OpaqueType>(type))
     return true;
+  if (auto lType = llvm::dyn_cast<emitc::LValueType>(type))
+    // lvalue types are only allowed in a few places.
+    return false;
   if (auto ptrType = llvm::dyn_cast<emitc::PointerType>(type))
     return isSupportedEmitCType(ptrType.getPointee());
   if (auto arrayType = llvm::dyn_cast<emitc::ArrayType>(type)) {
@@ -140,6 +143,8 @@ static LogicalResult verifyInitializationAttribute(Operation *op,
            << "string attributes are not supported, use #emitc.opaque instead";
 
   Type resultType = op->getResult(0).getType();
+  if (auto lType = dyn_cast<LValueType>(resultType))
+    resultType = lType.getValue();
   Type attrType = cast<TypedAttr>(value).getType();
 
   if (resultType != attrType)
@@ -188,9 +193,19 @@ LogicalResult ApplyOp::verify() {
   if (applicableOperatorStr != "&" && applicableOperatorStr != "*")
     return emitOpError("applicable operator is illegal");
 
-  Operation *op = getOperand().getDefiningOp();
-  if (op && dyn_cast<ConstantOp>(op))
-    return emitOpError("cannot apply to constant");
+  Type operandType = getOperand().getType();
+  Type resultType = getResult().getType();
+  if (applicableOperatorStr == "&") {
+    if (!llvm::isa<emitc::LValueType>(operandType))
+      return emitOpError("operand type must be an lvalue when applying `&`");
+    if (!llvm::isa<emitc::PointerType>(resultType))
+      return emitOpError("result type must be a pointer when applying `&`");
+  } else {
+    if (!llvm::isa<emitc::PointerType>(operandType))
+      return emitOpError("operand type must be a pointer when applying `*`");
+    if (!llvm::isa<emitc::LValueType>(resultType))
+      return emitOpError("result type must be an lvalue when applying `*`");
+  }
 
   return success();
 }
@@ -202,20 +217,18 @@ LogicalResult ApplyOp::verify() {
 /// The assign op requires that the assigned value's type matches the
 /// assigned-to variable type.
 LogicalResult emitc::AssignOp::verify() {
-  Value variable = getVar();
-  Operation *variableDef = variable.getDefiningOp();
-  if (!variableDef ||
-      !llvm::isa<emitc::VariableOp, emitc::SubscriptOp>(variableDef))
-    return emitOpError() << "requires first operand (" << variable
-                         << ") to be a Variable or subscript";
-
-  Value value = getValue();
-  if (variable.getType() != value.getType())
-    return emitOpError() << "requires value's type (" << value.getType()
-                         << ") to match variable's type (" << variable.getType()
-                         << ")";
-  if (isa<ArrayType>(variable.getType()))
-    return emitOpError() << "cannot assign to array type";
+  TypedValue<emitc::LValueType> variable = getVar();
+
+  if (!variable.getDefiningOp())
+    return emitOpError() << "cannot assign to block argument";
+
+  Type valueType = getValue().getType();
+  Type variableType = variable.getType().getValue();
+  if (variableType != valueType)
+    return emitOpError() << "requires value's type (" << valueType
+                         << ") to match variable's type (" << variableType
+                         << ")\n  variable: " << variable
+                         << "\n  value: " << getValue() << "\n";
   return success();
 }
 
@@ -842,9 +855,10 @@ LogicalResult emitc::SubscriptOp::verify() {
     }
     // Check element type.
     Type elementType = arrayType.getElementType();
-    if (elementType != getType()) {
+    Type resultType = getType().getValue();
+    if (elementType != resultType) {
       return emitOpError() << "on array operand requires element type ("
-                           << elementType << ") and result type (" << getType()
+                           << elementType << ") and result type (" << resultType
                            << ") to match";
     }
     return success();
@@ -868,9 +882,10 @@ LogicalResult emitc::SubscriptOp::verify() {
     }
     // Check pointee type.
     Type pointeeType = pointerType.getPointee();
-    if (pointeeType != getType()) {
+    Type resultType = getType().getValue();
+    if (pointeeType != resultType) {
       return emitOpError() << "on pointer operand requires pointee type ("
-                           << pointeeType << ") and result type (" << getType()
+                           << pointeeType << ") and result type (" << resultType
                            << ") to match";
     }
     return success();
@@ -964,6 +979,25 @@ emitc::ArrayType::cloneWith(std::optional<ArrayRef<int64_t>> shape,
   return emitc::ArrayType::get(*shape, elementType);
 }
 
+//===----------------------------------------------------------------------===//
+// LValueType
+//===----------------------------------------------------------------------===//
+
+LogicalResult mlir::emitc::LValueType::verify(
+    llvm::function_ref<mlir::InFlightDiagnostic()> emitError,
+    mlir::Type value) {
+  // Check that the wrapped type is valid. This especially forbids nested lvalue
+  // types.
+  if (!isSupportedEmitCType(value))
+    return emitError()
+           << "!emitc.lvalue must wrap supported emitc type, but got " << value;
+
+  if (llvm::isa<emitc::ArrayType>(value))
+    return emitError() << "!emitc.lvalue cannot wrap !emitc.array type";
+
+  return success();
+}
+
 //===----------------------------------------------------------------------===//
 // OpaqueType
 //===----------------------------------------------------------------------===//
@@ -981,6 +1015,18 @@ LogicalResult mlir::emitc::OpaqueType::verify(
   return success();
 }
 
+//===----------------------------------------------------------------------===//
+// PointerType
+//===----------------------------------------------------------------------===//
+
+LogicalResult mlir::emitc::PointerType::verify(
+    llvm::function_ref<mlir::InFlightDiagnostic()> emitError, Type value) {
+  if (llvm::isa<emitc::LValueType>(value))
+    return emitError() << "pointers to lvalues are not allowed";
+
+  return success();
+}
+
 //===----------------------------------------------------------------------===//
 // GlobalOp
 //===----------------------------------------------------------------------===//
@@ -1078,9 +1124,22 @@ GetGlobalOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
            << getName() << "' does not reference a valid emitc.global";
 
   Type resultType = getResult().getType();
-  if (global.getType() != resultType)
-    return emitOpError("result type ")
-           << resultType << " does not match type " << global.getType()
+  Type globalType = global.getType();
+
+  // global has array type
+  if (llvm::isa<ArrayType>(globalType)) {
+    if (globalType != resultType)
+      return emitOpError("on array type expects result type ")
+             << resultType << " to match type " << globalType
+             << " of the global @" << getName();
+    return success();
+  }
+
+  // global has non-array type
+  auto lvalueType = dyn_cast<LValueType>(resultType);
+  if (!lvalueType || lvalueType.getValue() != globalType)
+    return emitOpError("on non-array type expects result inner type ")
+           << lvalueType.getValue() << " to match type " << globalType
            << " of the global @" << getName();
   return success();
 }
diff --git a/mlir/lib/Dialect/EmitC/Transforms/FormExpressions.cpp b/mlir/lib/Dialect/EmitC/Transforms/FormExpressions.cpp
index 82bd031430d36..758b8527c2fa5 100644
--- a/mlir/lib/Dialect/EmitC/Transforms/FormExpressions.cpp
+++ b/mlir/lib/Dialect/EmitC/Transforms/FormExpressions.cpp
@@ -38,7 +38,8 @@ struct FormExpressionsPass
     auto matchFun = [&](Operation *op) {
       if (op->hasTrait<OpTrait::emitc::CExpression>() &&
           !op->getParentOfType<emitc::ExpressionOp>() &&
-          op->getNumResults() == 1)
+          op->getNumResults() == 1 &&
+          isSupportedEmitCType(op->getResult(0).getType()))
         createExpression(op, builder);
     };
     rootOp->walk(matchFun);
diff --git a/mlir/lib/Target/Cpp/TranslateToCpp.cpp b/mlir/lib/Target/Cpp/TranslateToCpp.cpp
index 202df89025f26..66808289e79f7 100644
--- a/mlir/lib/Target/Cpp/TranslateToCpp.cpp
+++ b/mlir/lib/Target/Cpp/TranslateToCpp.cpp
@@ -298,7 +298,7 @@ static bool shouldBeInlined(ExpressionOp expressionOp) {
   // Do not inline expressions used by subscript operations, since the
   // way the subscript operation translation is implemented requires that
   // variables be materialized.
-  if (isa<emitc::SubscriptOp>(user))
+  if (isa<emitc::SubscriptOp, emitc::GetGlobalOp>(user))
     return false;
 
   // Do not inline expressions used by ops with the CExpression trait. If this
@@ -377,6 +377,14 @@ static LogicalResult printOperation(CppEmitter &emitter,
   return success();
 }
 
+static LogicalResult printOperation(CppEmitter &emitter,
+                                    emitc::LValueLoadOp lValueLoadOp) {
+  if (failed(emitter.emitAssignPrefix(*lValueLoadOp)))
+    return failure();
+
+  return emitter.emitOperand(lValueLoadOp.getOperand());
+}
+
 static LogicalResult printOperation(CppEmitter &emitter,
                                     emitc::SubscriptOp subscriptOp) {
   // Add name to cache so that `hasValueInScope` works.
@@ -1399,7 +1407,7 @@ LogicalResult CppEmitter::emitVariableAssignment(OpResult result) {
 
 LogicalResult CppEmitter::emitVariableDeclaration(OpResult result,
                                                   bool trailingSemicolon) {
-  if (isa<emitc::SubscriptOp>(result.getDefiningOp()))
+  if (isa<emitc::SubscriptOp, emitc::GetGlobalOp>(result.getDefiningOp()))
     return success();
   if (hasValueInScope(result)) {
     return result.getDefiningOp()->emitError(
@@ -1500,9 +1508,10 @@ LogicalResult CppEmitter::emitOperation(Operation &op, bool trailingSemicolon) {
                 emitc::DivOp, emitc::ExpressionOp, emitc::ForOp, emitc::FuncOp,
                 emitc::GlobalOp, emitc::GetGlobalOp, emitc::IfOp,
                 emitc::IncludeOp, emitc::LogicalAndOp, emitc::LogicalNotOp,
-                emitc::LogicalOrOp, emitc::MulOp, emitc::RemOp, emitc::ReturnOp,
-                emitc::SubOp, emitc::SubscriptOp, emitc::UnaryMinusOp,
-                emitc::UnaryPlusOp, emitc::VariableOp, emitc::VerbatimOp>(
+                emitc::LogicalOrOp, emitc::LValueLoadOp, emitc::MulOp,
+                emitc::RemOp, emitc::ReturnOp, emitc::SubOp, emitc::SubscriptOp,
+                emitc::UnaryMinusOp, emitc::UnaryPlusOp, emitc::VariableOp,
+                emitc::VerbatimOp>(
               [&](auto op) { return printOperation(*this, op); })
           // Func ops.
           .Case<func::CallOp, func::FuncOp, func::ReturnOp>(
@@ -1605,6 +1614,8 @@ LogicalResult CppEmitter::emitType(Location loc, Type type) {
       os << "[" << dim << "]";
     return success();
   }
+  if (auto lType = dyn_cast<emitc::LValueType>(type))
+    return emitType(loc, lType.getValue());
   if (auto pType = dyn_cast<emitc::PointerType>(type)) {
     if (isa<ArrayType>(pType.getPointee()))
       return emitError(loc, "cannot emit pointer to array type ") << type;
diff --git a/mlir/test/Conversion/MemRefToEmitC/memref-to-emitc.mlir b/mlir/test/Conversion/MemRefToEmitC/memref-to-emitc.mlir
index bc40ef48268eb..15ffd815250d2 100644
--- a/mlir/test/Conversion/MemRefToEmitC/memref-to-emitc.mlir
+++ b/mlir/test/Conversion/MemRefToEmitC/memref-to-emitc.mlir
@@ -3,11 +3,11 @@
 // CHECK-LABEL: memref_store
 // CHECK-SAME:  %[[v:.*]]: f32, %[[i:.*]]: index, %[[j:.*]]: index
 func.func @memref_store(%v : f32, %i: index, %j: index) {
-  // CHECK: %[[ALLOCA:.*]] = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> !emitc.array<4x8xf32>
+  // CHECK-NEXT: %[[ALLOCA:.*]] = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> !emitc.array<4x8xf32>
   %0 = memref.alloca() : memref<4x8xf32>
 
-  // CHECK: %[[SUBSCRIPT:.*]] = emitc.subscript %[[ALLOCA]][%[[i]], %[[j]]] : (!emitc.array<4x8xf32>, index, index) -> f32
-  // CHECK: emitc.assign %[[v]] : f32 to %[[SUBSCRIPT:.*]] : f32
+  // CHECK-NEXT: %[[SUBSCRIPT:.*]] = emitc.subscript %[[ALLOCA]][%[[i]], %[[j]]] : (!emitc.array<4x8xf32>, index, index) -> !emitc.lvalue<f32>
+  // CHECK-NEXT: emitc.assign %[[v]] : f32 to %[[SUBSCRIPT]] : <f32>
   memref.store %v, %0[%i, %j] : memref<4x8xf32>
   return
 }
@@ -17,14 +17,13 @@ func.func @memref_store(%v : f32, %i: index, %j: index) {
 // CHECK-LABEL: memref_load
 // CHECK-SAME:  %[[i:.*]]: index, %[[j:.*]]: index
 func.func @memref_load(%i: index, %j: index) -> f32 {
-  // CHECK: %[[ALLOCA:.*]] = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> !emitc.array<4x8xf32>
+  // CHECK-NEXT: %[[ALLOCA:.*]] = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> !emitc.array<4x8xf32>
   %0 = memref.alloca() : memref<4x8xf32>
 
-  // CHECK: %[[LOAD:.*]] = emitc.subscript %[[ALLOCA]][%[[i]], %[[j]]] : (!emitc.array<4x8xf32>, index, index) -> f32
-  // CHECK: %[[VAR:.*]] = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> f32
-  // CHECK: emitc.assign %[[LOAD]] : f32 to %[[VAR]] : f32
+  // CHECK-NEXT: %[[SUBSCRIPT:.*]] = emitc.subscript %[[ALLOCA]][%[[i]], %[[j]]] : (!emitc.array<4x8xf32>, index, index) -> !emitc.lvalue<f32>
+  // CHECK-NEXT: %[[LOAD:.*]] = emitc.lvalue_load %[[SUBSCRIPT]] : <f32>
   %1 = memref.load %0[%i, %j] : memref<4x8xf32>
-  // CHECK: return %[[VAR]] : f32
+  // CHECK-NEXT: return %[[LOAD]] : f32
   return %1 : f32
 }
 
@@ -33,14 +32,15 @@ func.func @memref_load(%i: index, %j: index) -> f32 {
 // CHECK-LABEL: globals
 module @globals {
   memref.global "private" constant @internal_global : memref<3x7xf32> = dense<4.0>
-  // CHECK: emitc.global static const @internal_global : !emitc.array<3x7xf32> = dense<4.000000e+00>
+  // CHECK-NEXT: emitc.global static const @internal_global : !emitc.array<3x7xf32> = dense<4.000000e+00>
   memref.global @public_global : memref<3x7xf32>
-  // CHECK: emitc.global extern @public_global : !emitc.array<3x7xf32>
+  // CHECK-NEXT: emitc.global extern @public_global : !emitc.array<3x7xf32>
   memref.global @uninitialized_global : memref<3x7xf32> = uninitialized
-  // CHECK: emitc.global extern @uninitialized_global : !emitc.array<3x7xf32>
+  // CHECK-NEXT: emitc.global extern @uninitialized_global : !emitc.array<3x7xf32>
 
+  // CHECK-LABEL: use_global
   func.func @use_global() {
-    // CHECK: emitc.get_global @public_global : !emitc.array<3x7xf32>
+    // CHECK-NEXT: emitc.get_global @public_global : !emitc.array<3x7xf32>
     %0 = memref.get_global @public_global : memref<3x7xf32>
     return
   }
diff --git a/mlir/test/Conversion/SCFToEmitC/for.mlir b/mlir/test/Conversion/SCFToEmitC/for.mlir
index 7f90310af2189..32a9dfce7f4e6 100644
--- a/mlir/test/Conversion/SCFToEmitC/for.mlir
+++ b/mlir/test/Conversion/SCFToEmitC/for.mlir
@@ -47,20 +47,20 @@ func.func @for_yield(%arg0 : index, %arg1 : index, %arg2 : index) -> (f32, f32)
 // CHECK-SAME:      %[[VAL_0:.*]]: index, %[[VAL_1:.*]]: index, %[[VAL_2:.*]]: index) -> (f32, f32) {
 // CHECK-NEXT:    %[[VAL_3:.*]] = arith.constant 0.000000e+00 : f32
 // CHECK-NEXT:    %[[VAL_4:.*]] = arith.constant 1.000000e+00 : f32
-// CHECK-NEXT:    %[[VAL_5:.*]] = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> f32
-// CHECK-NEXT:    %[[VAL_6:.*]] = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> f32
-// CHECK-NEXT:    %[[VAL_7:.*]] = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> f32
-// CHECK-NEXT:    %[[VAL_8:.*]] = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> f32
-// CHECK-NEXT:    emitc.assign %[[VAL_3]] : f32 to %[[VAL_7]] : f32
-// CHECK-NEXT:    emitc.assign %[[VAL_4]] : f32 to %[[VAL_8]] : f32
-// CHECK-NEXT:    emitc.for %[[VAL_9:.*]] = %[[VAL_0]] to %[[VAL_1]] step %[[VAL_2]] {
-// CHECK-NEXT:      %[[VAL_10:.*]] = arith.addf %[[VAL_7]], %[[VAL_8]] : f32
-// CHECK-NEXT:      emitc.assign %[[VAL_10]] : f32 to %[[VAL_7]] : f32
-// CHECK-NEXT:      emitc.assign %[[VAL_10]] : f32 to %[[VAL_8]] : f32
+// CHECK-NEXT:    %[[VAL_5:.*]] = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> !emitc.lvalue<f32>
+// CHECK-NEXT:    %[[VAL_6:.*]] = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> !emitc.lvalue<f32>
+// CHECK-NEXT:    emitc.assign %[[VAL_3]] : f32 to %[[VAL_5]] : <f32>
+// CHECK-NEXT:    emitc.assign %[[VAL_4]] : f32 to %[[VAL_6]] : <f32>
+// CHECK-NEXT:    emitc.for %[[VAL_7:.*]] = %[[VAL_0]] to %[[VAL_1]] step %[[VAL_2]] {
+// CHECK-NEXT:      %[[VAL_8:.*]] = emitc.lvalue_load %[[VAL_5]] : <f32>
+// CHECK-NEXT:      %[[VAL_9:.*]] = emitc.lvalue_load %[[VAL_6]] : <f32>
+// CHECK-NEXT:      %[[VAL_10:.*]] = arith.addf %[[VAL_8]], %[[VAL_9]] : f32
+// CHECK-NEXT:      emitc.assign %[[VAL_10]] : f32 to %[[VAL_5]] : <f32>
+// CHECK-NEXT:      emitc.assign %[[VAL_10]] : f32 to %[[VAL_6]] : <f32>
 // CHECK-NEXT:    }
-// CHECK-NEXT:    emitc.assign %[[VAL_7]] : f32 to %[[VAL_5]] : f32
-// CHECK-NEXT:    emitc.assign %[[VAL_8]] : f32 to %[[VAL_6]] : f32
-// CHECK-NEXT:    return %[[VAL_5]], %[[VAL_6]] : f32, f32
+// CHECK-NEXT:    %[[VAL_11:.*]] = emitc.lvalue_load %[[VAL_5]] : <f32>
+// CHECK-NEXT:    %[[VAL_12:.*]] = emitc.lvalue_load %[[VAL_6]] : <f32>
+// CHECK-NEXT:    return %[[VAL_11]], %[[VAL_12]] : f32, f32
 // CHECK-NEXT:  }
 
 func.func @nested_for_yield(%arg0 : index, %arg1 : index, %arg2 : index) -> f32 {
@@ -77,20 +77,20 @@ func.func @nested_for_yield(%arg0 : index, %arg1 : index, %arg2 : index) -> f32
 // CHECK-LABEL: func.func @nested_for_yield(
 // CHECK-SAME:      %[[VAL_0:.*]]: index, %[[VAL_1:.*]]: index, %[[VAL_2:.*]]: index) -> f32 {
 // CHECK-NEXT:    %[[VAL_3:.*]] = arith.constant 1.000000e+00 : f32
-// CHECK-NEXT:    %[[VAL_4:.*]] = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> f32
-// CHECK-NEXT:    %[[VAL_5:.*]] = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> f32
-// CHECK-NEXT:    emitc.assign %[[VAL_3]] : f32 to %[[VAL_5]] : f32
-// CHECK-NEXT:    emitc.for %[[VAL_6:.*]] = %[[VAL_0]] to %[[VAL_1]] step %[[VAL_2]] {
-// CHECK-NEXT:      %[[VAL_7:.*]] = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> f32
-// CHECK-NEXT:      %[[VAL_8:.*]] = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> f32
-// CHECK-NEXT:      emitc.assign %[[VAL_5]] : f32 to %[[VAL_8]] : f32
-// CHECK-NEXT:      emitc.for %[[VAL_9:.*]] = %[[VAL_0]] to %[[VAL_1]] step %[[VAL_2]] {
-// CHECK-NEXT:        %[[VAL_10:.*]] = arith.addf %[[VAL_8]], %[[VAL_8]] : f32
-// CHECK-NEXT:        emitc.assign %[[VAL_10]] : f32 to %[[VAL_8]] : f32
+// CHECK-NEXT:    %[[VAL_4:.*]] = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> !emitc.lvalue<f32>
+// CHECK-NEXT:    emitc.assign %[[VAL_3]] : f32 to %[[VAL_4]] : <f32>
+// CHECK-NEXT:    emitc.for %[[VAL_5:.*]] = %[[VAL_0]] to %[[VAL_1]] step %[[VAL_2]] {
+// CHECK-NEXT:      %[[VAL_6:.*]] = emitc.lvalue_load %[[VAL_4]] : <f32>
+// CHECK-NEXT:      %[[VAL_7:.*]] = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> !emitc.lvalue<f32>
+// CHECK-NEXT:      emitc.assign %[[VAL_6]] : f32 to %[[VAL_7]] : <f32>
+// CHECK-NEXT:      emitc.for %[[VAL_8:.*]] = %[[VAL_0]] to %[[VAL_1]] step %[[VAL_2]] {
+// CHECK-NEXT:        %[[VAL_9:.*]] = emitc.lvalue_load %[[VAL_7]] : <f32>  
+// CHECK-NEXT:        %[[VAL_10:.*]] = arith.addf %[[VAL_9]], %[[VAL_9]] : f32
+// CHECK-NEXT:        emitc.assign %[[VAL_10]] : f32 to %[[VAL_7]] : <f32>
 // CHECK-NEXT:      }
-// CHECK-NEXT:      emitc.assign %[[VAL_8]] : f32 to %[[VAL_7]] : f32
-// CHECK-NEXT:      emitc.assign %[[VAL_7]] : f32 to %[[VAL_5]] : f32
+// CHECK-NEXT:      %[[VAL_11:.*]] = emitc.lvalue_load %[[VAL_7]] : <f32>  
+// CHECK-NEXT:      emitc.assign %[[VAL_11]] : f32 to %[[VAL_4]] : <f32>
 // CHECK-NEXT:    }
-// CHECK-NEXT:    emitc.assign %[[VAL_5]] : f32 to %[[VAL_4]] : f32
-// CHECK-NEXT:    return %[[VAL_4]] : f32
+// CHECK-NEXT:    %[[VAL_12:.*]] = emitc.lvalue_load %[[VAL_4]] : <f32>  
+// CHECK-NEXT:    return %[[VAL_12]] : f32
 // CHECK-NEXT:  }
diff --git a/mlir/test/Conversion/SCFToEmitC/if.mlir b/mlir/test/Conversion/SCFToEmitC/if.mlir
index afc9abc761eb4..463cf1d3d9645 100644
--- a/mlir/test/Conversion/SCFToEmitC/if.mlir
+++ b/mlir/test/Conversion/SCFToEmitC/if.mlir
@@ -36,7 +36,7 @@ func.func @test_if_else(%arg0: i1, %arg1: f32) {
 // CHECK-NEXT:  }
 
 
-func.func @test_if_yield(%arg0: i1, %arg1: f32) {
+func.func @test_if_yield(%arg0: i1, %arg1: f32) -> (i32, f64) {
   %0 = arith.constant 0 : i8
   %x, %y = scf.if %arg0 -> (i32, f64) {
     %1 = emitc.call_opaque "func_true_1"(%arg1) : (f32) -> i32
@@ -47,24 +47,26 @@ func.func @test_if_yield(%arg0: i1, %arg1: f32) {
     %2 = emitc.call_opaque "func_false_2"(%arg1) : (f32) -> f64
     scf.yield %1, %2 : i32, f64
   }
-  return
+  return %x, %y : i32, f64
 }
 // CHECK-LABEL: func.func @test_if_yield(
 // CHECK-SAME:                           %[[VAL_0:.*]]: i1,
-// CHECK-SAME:                           %[[VAL_1:.*]]: f32) {
+// CHECK-SAME:                           %[[VAL_1:.*]]: f32) -> (i32, f64) {
 // CHECK-NEXT:    %[[VAL_2:.*]] = arith.constant 0 : i8
-// CHECK-NEXT:    %[[VAL_3:.*]] = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> i32
-// CHECK-NEXT:    %[[VAL_4:.*]] = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> f64
+// CHECK-NEXT:    %[[VAL_3:.*]] = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> !emitc.lvalue<i32>
+// CHECK-NEXT:    %[[VAL_4:.*]] = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> !emitc.lvalue<f64>
 // CHECK-NEXT:    emitc.if %[[VAL_0]] {
 // CHECK-NEXT:      %[[VAL_5:.*]] = emitc.call_opaque "func_true_1"(%[[VAL_1]]) : (f32) -> i32
 // CHECK-NEXT:      %[[VAL_6:.*]] = emitc.call_opaque "func_true_2"(%[[VAL_1]]) : (f32) -> f64
-// CHECK-NEXT:      emitc.assign %[[VAL_5]] : i32 to %[[VAL_3]] : i32
-// CHECK-NEXT:      emitc.assign %[[VAL_6]] : f64 to %[[VAL_4]] : f64
+// CHECK-NEXT:      emitc.assign %[[VAL_5]] : i32 to %[[VAL_3]] : <i32>
+// CHECK-NEXT:      emitc.assign %[[VAL_6]] : f64 to %[[VAL_4]] : <f64>
 // CHECK-NEXT:    } else {
 // CHECK-NEXT:      %[[VAL_7:.*]] = emitc.call_opaque "func_false_1"(%[[VAL_1]]) : (f32) -> i32
 // CHECK-NEXT:      %[[VAL_8:.*]] = emitc.call_opaque "func_false_2"(%[[VAL_1]]) : (f32) -> f64
-// CHECK-NEXT:      emitc.assign %[[VAL_7]] : i32 to %[[VAL_3]] : i32
-// CHECK-NEXT:      emitc.assign %[[VAL_8]] : f64 to %[[VAL_4]] : f64
+// CHECK-NEXT:      emitc.assign %[[VAL_7]] : i32 to %[[VAL_3]] : <i32>
+// CHECK-NEXT:      emitc.assign %[[VAL_8]] : f64 to %[[VAL_4]] : <f64>
 // CHECK-NEXT:    }
-// CHECK-NEXT:    return
+// CHECK-NEXT:    %[[VAL_9:.*]] = emitc.lvalue_load %[[VAL_3]] : <i32>
+// CHECK-NEXT:    %[[VAL_10:.*]] = emitc.lvalue_load %[[VAL_4]] : <f64>
+// CHECK-NEXT:    return %[[VAL_9]], %[[VAL_10]] : i32, f64
 // CHECK-NEXT:  }
diff --git a/mlir/test/Dialect/EmitC/invalid_ops.mlir b/mlir/test/Dialect/EmitC/invalid_ops.mlir
index 21ea6a5df91b9..261e67607fc4f 100644
--- a/mlir/test/Dialect/EmitC/invalid_ops.mlir
+++ b/mlir/test/Dialect/EmitC/invalid_ops.mlir
@@ -88,26 +88,17 @@ func.func @array_result() {
 
 // -----
 
-func.func @empty_operator(%arg : i32) {
+func.func @empty_operator(%arg : !emitc.lvalue<i32>) {
     // expected-error @+1 {{'emitc.apply' op applicable operator must not be empty}}
-    %2 = emitc.apply ""(%arg) : (i32) -> !emitc.ptr<i32>
+    %2 = emitc.apply ""(%arg) : (!emitc.lvalue<i32>) -> !emitc.ptr<i32>
     return
 }
 
 // -----
 
-func.func @illegal_operator(%arg : i32) {
+func.func @illegal_operator(%arg : !emitc.lvalue<i32>) {
     // expected-error @+1 {{'emitc.apply' op applicable operator is illegal}}
-    %2 = emitc.apply "+"(%arg) : (i32) -> !emitc.ptr<i32>
-    return
-}
-
-// -----
-
-func.func @illegal_operand() {
-    %1 = "emitc.constant"(){value = 42: i32} : () -> i32
-    // expected-error @+1 {{'emitc.apply' op cannot apply to constant}}
-    %2 = emitc.apply "&"(%1) : (i32) -> !emitc.ptr<i32>
+    %2 = emitc.apply "+"(%arg) : (!emitc.lvalue<i32>) -> !emitc.ptr<i32>
     return
 }
 
@@ -115,7 +106,7 @@ func.func @illegal_operand() {
 
 func.func @var_attribute_return_type_1() {
     // expected-error @+1 {{'emitc.variable' op requires attribute to either be an #emitc.opaque attribute or it's type ('i64') to match the op's result type ('i32')}}
-    %c0 = "emitc.variable"(){value = 42: i64} : () -> i32
+    %c0 = "emitc.variable"(){value = 42: i64} : () -> !emitc.lvalue<i32>
     return
 }
 
@@ -123,7 +114,7 @@ func.func @var_attribute_return_type_1() {
 
 func.func @var_attribute_return_type_2() {
     // expected-error @+1 {{'emitc.variable' op attribute 'value' failed to satisfy constraint: An opaque attribute or TypedAttr instance}}
-    %c0 = "emitc.variable"(){value = unit} : () -> i32
+    %c0 = "emitc.variable"(){value = unit} : () -> !emitc.lvalue<i32>
     return
 }
 
@@ -234,18 +225,18 @@ func.func @test_misplaced_yield() {
 
 // -----
 
-func.func @test_assign_to_non_variable(%arg1: f32, %arg2: f32) {
-  // expected-error @+1 {{'emitc.assign' op requires first operand (<block argument> of type 'f32' at index: 1) to be a Variable or subscript}}
-  emitc.assign %arg1 : f32 to %arg2 : f32
+func.func @test_assign_to_non_variable(%arg1: f32, %arg2: !emitc.lvalue<f32>) {
+  // expected-error @+1 {{'emitc.assign' op cannot assign to block argument}}
+  emitc.assign %arg1 : f32 to %arg2 : !emitc.lvalue<f32>
   return
 }
 
 // -----
 
 func.func @test_assign_type_mismatch(%arg1: f32) {
-  %v = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> i32
+  %v = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> !emitc.lvalue<i32>
   // expected-error @+1 {{'emitc.assign' op requires value's type ('f32') to match variable's type ('i32')}}
-  emitc.assign %arg1 : f32 to %v : i32
+  emitc.assign %arg1 : f32 to %v : !emitc.lvalue<i32>
   return
 }
 
@@ -253,7 +244,7 @@ func.func @test_assign_type_mismatch(%arg1: f32) {
 
 func.func @test_assign_to_array(%arg1: !emitc.array<4xi32>) {
   %v = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> !emitc.array<4xi32>
-  // expected-error @+1 {{'emitc.assign' op cannot assign to array type}}
+  // expected-error @+1 {{invalid kind of Type specified}}
   emitc.assign %arg1 : !emitc.array<4xi32> to %v : !emitc.array<4xi32>
   return
 }
@@ -392,7 +383,7 @@ func.func @logical_or_resulterror(%arg0: i32, %arg1: i32) {
 
 func.func @test_subscript_array_indices_mismatch(%arg0: !emitc.array<4x8xf32>, %arg1: index) {
   // expected-error @+1 {{'emitc.subscript' op on array operand requires number of indices (1) to match the rank of the array type (2)}}
-  %0 = emitc.subscript %arg0[%arg1] : (!emitc.array<4x8xf32>, index) -> f32
+  %0 = emitc.subscript %arg0[%arg1] : (!emitc.array<4x8xf32>, index) -> !emitc.lvalue<f32>
   return
 }
 
@@ -400,7 +391,7 @@ func.func @test_subscript_array_indices_mismatch(%arg0: !emitc.array<4x8xf32>, %
 
 func.func @test_subscript_array_index_type_mismatch(%arg0: !emitc.array<4x8xf32>, %arg1: index, %arg2: f32) {
   // expected-error @+1 {{'emitc.subscript' op on array operand requires index operand 1 to be integer-like, but got 'f32'}}
-  %0 = emitc.subscript %arg0[%arg1, %arg2] : (!emitc.array<4x8xf32>, index, f32) -> f32
+  %0 = emitc.subscript %arg0[%arg1, %arg2] : (!emitc.array<4x8xf32>, index, f32) -> !emitc.lvalue<f32>
   return
 }
 
@@ -408,7 +399,7 @@ func.func @test_subscript_array_index_type_mismatch(%arg0: !emitc.array<4x8xf32>
 
 func.func @test_subscript_array_type_mismatch(%arg0: !emitc.array<4x8xf32>, %arg1: index, %arg2: index) {
   // expected-error @+1 {{'emitc.subscript' op on array operand requires element type ('f32') and result type ('i32') to match}}
-  %0 = emitc.subscript %arg0[%arg1, %arg2] : (!emitc.array<4x8xf32>, index, index) -> i32
+  %0 = emitc.subscript %arg0[%arg1, %arg2] : (!emitc.array<4x8xf32>, index, index) -> !emitc.lvalue<i32>
   return
 }
 
@@ -416,7 +407,7 @@ func.func @test_subscript_array_type_mismatch(%arg0: !emitc.array<4x8xf32>, %arg
 
 func.func @test_subscript_ptr_indices_mismatch(%arg0: !emitc.ptr<f32>, %arg1: index) {
   // expected-error @+1 {{'emitc.subscript' op on pointer operand requires one index operand, but got 2}}
-  %0 = emitc.subscript %arg0[%arg1, %arg1] : (!emitc.ptr<f32>, index, index) -> f32
+  %0 = emitc.subscript %arg0[%arg1, %arg1] : (!emitc.ptr<f32>, index, index) -> !emitc.lvalue<f32>
   return
 }
 
@@ -424,7 +415,7 @@ func.func @test_subscript_ptr_indices_mismatch(%arg0: !emitc.ptr<f32>, %arg1: in
 
 func.func @test_subscript_ptr_index_type_mismatch(%arg0: !emitc.ptr<f32>, %arg1: f64) {
   // expected-error @+1 {{'emitc.subscript' op on pointer operand requires index operand to be integer-like, but got 'f64'}}
-  %0 = emitc.subscript %arg0[%arg1] : (!emitc.ptr<f32>, f64) -> f32
+  %0 = emitc.subscript %arg0[%arg1] : (!emitc.ptr<f32>, f64) -> !emitc.lvalue<f32>
   return
 }
 
@@ -432,7 +423,7 @@ func.func @test_subscript_ptr_index_type_mismatch(%arg0: !emitc.ptr<f32>, %arg1:
 
 func.func @test_subscript_ptr_type_mismatch(%arg0: !emitc.ptr<f32>, %arg1: index) {
   // expected-error @+1 {{'emitc.subscript' op on pointer operand requires pointee type ('f32') and result type ('f64') to match}}
-  %0 = emitc.subscript %arg0[%arg1] : (!emitc.ptr<f32>, index) -> f64
+  %0 = emitc.subscript %arg0[%arg1] : (!emitc.ptr<f32>, index) -> !emitc.lvalue<f64>
   return
 }
 
@@ -443,10 +434,20 @@ emitc.global extern static @uninit : i32
 
 // -----
 
-emitc.global @myglobal : !emitc.array<2xf32>
+emitc.global @myglobal_array : !emitc.array<2xf32>
+
+func.func @use_global() {
+  // expected-error @+1 {{'emitc.get_global' op on array type expects result type '!emitc.array<3xf32>' to match type '!emitc.array<2xf32>' of the global @myglobal_array}}
+  %0 = emitc.get_global @myglobal_array : !emitc.array<3xf32>
+  return
+}
+
+// -----
+
+emitc.global @myglobal_scalar : f32
 
 func.func @use_global() {
-  // expected-error @+1 {{'emitc.get_global' op result type 'f32' does not match type '!emitc.array<2xf32>' of the global @myglobal}}
-  %0 = emitc.get_global @myglobal : f32
+  // expected-error @+1 {{'emitc.get_global' op on non-array type expects result inner type 'i32' to match type 'f32' of the global @myglobal_scalar}}
+  %0 = emitc.get_global @myglobal_scalar : !emitc.lvalue<i32>
   return
 }
diff --git a/mlir/test/Dialect/EmitC/invalid_types.mlir b/mlir/test/Dialect/EmitC/invalid_types.mlir
index 0ad8d4eabe6b8..07f2dfe583c3d 100644
--- a/mlir/test/Dialect/EmitC/invalid_types.mlir
+++ b/mlir/test/Dialect/EmitC/invalid_types.mlir
@@ -84,6 +84,14 @@ func.func @illegal_array_with_tensor_element_type(
 
 // -----
 
+func.func @illegal_array_with_lvalue_element_type(
+    // expected-error @+1 {{invalid array element type}}
+    %arg0: !emitc.array<4x!emitc.lvalue<i32>>
+) {
+}
+
+// -----
+
 func.func @illegal_integer_type(%arg0: i11, %arg1: i11) -> i11 {
     // expected-error @+1 {{'emitc.mul' op operand #0 must be floating-point type supported by EmitC or integer type supported by EmitC or index or EmitC opaque type, but got 'i11'}}
     %mul = "emitc.mul" (%arg0, %arg1) : (i11, i11) -> i11
@@ -100,48 +108,80 @@ func.func @illegal_float_type(%arg0: f80, %arg1: f80) {
 
 // -----
 
-func.func @illegal_pointee_type() {
-    // expected-error @+1 {{'emitc.variable' op result #0 must be type supported by EmitC, but got '!emitc.ptr<i11>'}}
-    %v = "emitc.variable"(){value = #emitc.opaque<"">} : () -> !emitc.ptr<i11>
+func.func @illegal_lvalue_type_1() {
+    // expected-error @+1 {{!emitc.lvalue cannot wrap !emitc.array type}}
+    %v = "emitc.variable"(){value = #emitc.opaque<"">} : () -> !emitc.lvalue<!emitc.array<1xi32>>
+    return
+}
+
+// -----
+
+func.func @illegal_lvalue_type_2() {
+    // expected-error @+1 {{!emitc.lvalue must wrap supported emitc type, but got '!emitc.lvalue<i32>'}}
+    %v = "emitc.variable"(){value = #emitc.opaque<"">} : () -> !emitc.lvalue<!emitc.lvalue<i32>>
+    return
+}
+
+// -----
+
+func.func @illegal_lvalue_type_3() {
+    // expected-error @+1 {{!emitc.lvalue must wrap supported emitc type, but got 'i17'}}
+    %v = "emitc.variable"(){value = #emitc.opaque<"">} : () -> !emitc.lvalue<i17>
+    return
+}
+
+// -----
+
+func.func @illegal_pointee_type_1() {
+    // expected-error @+1 {{'emitc.constant' op result #0 must be type supported by EmitC, but got '!emitc.ptr<i11>'}}
+    %v = "emitc.constant"(){value = #emitc.opaque<"{}">} : () -> !emitc.ptr<i11>
+    return
+}
+
+// -----
+
+func.func @illegal_pointee_type_2() {
+    // expected-error @+1 {{pointers to lvalues are not allowed}}
+    %v = "emitc.constant"(){value = #emitc.opaque<"NULL">} : () -> !emitc.ptr<!emitc.lvalue<i32>>
     return
 }
 
 // -----
 
 func.func @illegal_non_static_tensor_shape_type() {
-    // expected-error @+1 {{'emitc.variable' op result #0 must be type supported by EmitC, but got 'tensor<?xf32>'}}
-    %v = "emitc.variable"(){value = #emitc.opaque<"">} : () -> tensor<?xf32>
+    // expected-error @+1 {{'emitc.constant' op result #0 must be type supported by EmitC, but got 'tensor<?xf32>'}}
+    %v = "emitc.constant"(){value = #emitc.opaque<"{}">} : () -> tensor<?xf32>
     return
 }
 
 // -----
 
 func.func @illegal_tensor_array_element_type() {
-    // expected-error @+1 {{'emitc.variable' op result #0 must be type supported by EmitC, but got 'tensor<!emitc.array<9xi16>>'}}
-    %v = "emitc.variable"(){value = #emitc.opaque<"">} : () -> tensor<!emitc.array<9xi16>>
+    // expected-error @+1 {{'emitc.constant' op result #0 must be type supported by EmitC, but got 'tensor<!emitc.array<9xi16>>'}}
+    %v = "emitc.constant"(){value = #emitc.opaque<"{}">} : () -> tensor<!emitc.array<9xi16>>
     return
 }
 
 // -----
 
 func.func @illegal_tensor_integer_element_type() {
-    // expected-error @+1 {{'emitc.variable' op result #0 must be type supported by EmitC, but got 'tensor<9xi11>'}}
-    %v = "emitc.variable"(){value = #emitc.opaque<"">} : () -> tensor<9xi11>
+    // expected-error @+1 {{'emitc.constant' op result #0 must be type supported by EmitC, but got 'tensor<9xi11>'}}
+    %v = "emitc.constant"(){value = #emitc.opaque<"{}">} : () -> tensor<9xi11>
     return
 }
 
 // -----
 
 func.func @illegal_tuple_array_element_type() {
-    // expected-error @+1 {{'emitc.variable' op result #0 must be type supported by EmitC, but got 'tuple<!emitc.array<9xf32>, f32>'}}
-    %v = "emitc.variable"(){value = #emitc.opaque<"">} : () -> tuple<!emitc.array<9xf32>, f32>
+    // expected-error @+1 {{'emitc.constant' op result #0 must be type supported by EmitC, but got 'tuple<!emitc.array<9xf32>, f32>'}}
+    %v = "emitc.constant"(){value = #emitc.opaque<"{}">} : () -> tuple<!emitc.array<9xf32>, f32>
     return
 }
 
 // -----
 
 func.func @illegal_tuple_float_element_type() {
-    // expected-error @+1 {{'emitc.variable' op result #0 must be type supported by EmitC, but got 'tuple<i32, f80>'}}
-    %v = "emitc.variable"(){value = #emitc.opaque<"">} : () -> tuple<i32, f80>
+    // expected-error @+1 {{'emitc.constant' op result #0 must be type supported by EmitC, but got 'tuple<i32, f80>'}}
+    %v = "emitc.constant"(){value = #emitc.opaque<"{}">} : () -> tuple<i32, f80>
     return
 }
diff --git a/mlir/test/Dialect/EmitC/ops.mlir b/mlir/test/Dialect/EmitC/ops.mlir
index 05510e6dddbf5..616a7ddbbf672 100644
--- a/mlir/test/Dialect/EmitC/ops.mlir
+++ b/mlir/test/Dialect/EmitC/ops.mlir
@@ -44,9 +44,9 @@ func.func @c() {
   return
 }
 
-func.func @a(%arg0: i32, %arg1: i32) {
-  %1 = "emitc.apply"(%arg0) {applicableOperator = "&"} : (i32) -> !emitc.ptr<i32>
-  %2 = emitc.apply "&"(%arg1) : (i32) -> !emitc.ptr<i32>
+func.func @a(%arg0: !emitc.lvalue<i32>, %arg1: !emitc.lvalue<i32>) {
+  %1 = "emitc.apply"(%arg0) {applicableOperator = "&"} : (!emitc.lvalue<i32>) -> !emitc.ptr<i32>
+  %2 = emitc.apply "&"(%arg1) : (!emitc.lvalue<i32>) -> !emitc.ptr<i32>
   return
 }
 
@@ -170,8 +170,8 @@ func.func @test_if_else(%arg0: i1, %arg1: f32) {
 }
 
 func.func @test_assign(%arg1: f32) {
-  %v = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> f32
-  emitc.assign %arg1 : f32 to %v : f32
+  %v = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> !emitc.lvalue<f32>
+  emitc.assign %arg1 : f32 to %v : !emitc.lvalue<f32>
   return
 }
 
@@ -215,9 +215,9 @@ func.func @test_for_not_index_induction(%arg0 : i16, %arg1 : i16, %arg2 : i16) {
 }
 
 func.func @test_subscript(%arg0 : !emitc.array<2x3xf32>, %arg1 : !emitc.ptr<i32>, %arg2 : !emitc.opaque<"std::map<char, int>">, %idx0 : index, %idx1 : i32, %idx2 : !emitc.opaque<"char">) {
-  %0 = emitc.subscript %arg0[%idx0, %idx1] : (!emitc.array<2x3xf32>, index, i32) -> f32
-  %1 = emitc.subscript %arg1[%idx0] : (!emitc.ptr<i32>, index) -> i32
-  %2 = emitc.subscript %arg2[%idx2] : (!emitc.opaque<"std::map<char, int>">, !emitc.opaque<"char">) -> !emitc.opaque<"int">
+  %0 = emitc.subscript %arg0[%idx0, %idx1] : (!emitc.array<2x3xf32>, index, i32) -> !emitc.lvalue<f32>
+  %1 = emitc.subscript %arg1[%idx0] : (!emitc.ptr<i32>, index) -> !emitc.lvalue<i32>
+  %2 = emitc.subscript %arg2[%idx2] : (!emitc.opaque<"std::map<char, int>">, !emitc.opaque<"char">) -> !emitc.lvalue<!emitc.opaque<"int">>
   return
 }
 
@@ -242,6 +242,7 @@ emitc.global const @myconstant : !emitc.array<2xi16> = dense<2>
 
 func.func @use_global(%i: index) -> f32 {
   %0 = emitc.get_global @myglobal : !emitc.array<2xf32>
-  %1 = emitc.subscript %0[%i] : (!emitc.array<2xf32>, index) -> f32
-  return %1 : f32
+  %1 = emitc.subscript %0[%i] : (!emitc.array<2xf32>, index) -> !emitc.lvalue<f32>
+  %2 = emitc.lvalue_load %1 : <f32>
+  return %2 : f32
 }
diff --git a/mlir/test/Dialect/EmitC/transforms.mlir b/mlir/test/Dialect/EmitC/transforms.mlir
index a5c582be4aa7f..996fd327f7af7 100644
--- a/mlir/test/Dialect/EmitC/transforms.mlir
+++ b/mlir/test/Dialect/EmitC/transforms.mlir
@@ -64,50 +64,24 @@ func.func @expression_with_call(%arg0: i32, %arg1: i32, %arg2: i32, %arg3: i32)
   return %c : i1
 }
 
-// CHECK-LABEL: func.func @expression_with_dereference(
-// CHECK-SAME:      %[[VAL_0:.*]]: i32, %[[VAL_1:.*]]: i32, %[[VAL_2:.*]]: !emitc.ptr<i32>) -> i1 {
-// CHECK:         %[[VAL_3:.*]] = emitc.expression : i32 {
-// CHECK:           %[[VAL_4:.*]] = emitc.apply "*"(%[[VAL_2]]) : (!emitc.ptr<i32>) -> i32
-// CHECK:           emitc.yield %[[VAL_4]] : i32
-// CHECK:         }
-// CHECK:         %[[VAL_5:.*]] = emitc.expression : i1 {
-// CHECK:           %[[VAL_6:.*]] = emitc.mul %[[VAL_0]], %[[VAL_1]] : (i32, i32) -> i32
-// CHECK:           %[[VAL_7:.*]] = emitc.cmp lt, %[[VAL_6]], %[[VAL_3]] : (i32, i32) -> i1
+// CHECK-LABEL: func.func @expression_with_address_taken(
+// CHECK-SAME:      %[[VAL_0:.*]]: i32, %[[VAL_1:.*]]: i32, %[[VAL_2:.*]]: !emitc.ptr<i32>, %[[VAL_3:.*]]: !emitc.lvalue<i32>) -> i1 {
+// CHECK:         %[[VAL_4:.*]] = emitc.expression : i1 {
+// CHECK:           %[[VAL_5:.*]] = emitc.apply "&"(%[[VAL_3]]) : (!emitc.lvalue<i32>) -> !emitc.ptr<i32>
+// CHECK:           %[[VAL_6:.*]] = emitc.add %[[VAL_5]], %[[VAL_1]] : (!emitc.ptr<i32>, i32) -> !emitc.ptr<i32>
+// CHECK:           %[[VAL_7:.*]] = emitc.cmp lt, %[[VAL_6]], %[[VAL_2]] : (!emitc.ptr<i32>, !emitc.ptr<i32>) -> i1
 // CHECK:           emitc.yield %[[VAL_7]] : i1
 // CHECK:         }
-// CHECK:         return %[[VAL_5]] : i1
+// CHECK:         return %[[VAL_4]] : i1
 // CHECK:       }
 
-func.func @expression_with_dereference(%arg0: i32, %arg1: i32, %arg2: !emitc.ptr<i32>) -> i1 {
-  %a = emitc.mul %arg0, %arg1 : (i32, i32) -> i32
-  %b = emitc.apply "*"(%arg2) : (!emitc.ptr<i32>) -> (i32)
-  %c = emitc.cmp lt, %a, %b :(i32, i32) -> i1
+func.func @expression_with_address_taken(%arg0: i32, %arg1: i32, %arg2: !emitc.ptr<i32>, %arg3: !emitc.lvalue<i32>) -> i1 {
+  %a = emitc.apply "&"(%arg3) : (!emitc.lvalue<i32>) -> !emitc.ptr<i32>
+  %b = emitc.add %a, %arg1 : (!emitc.ptr<i32>, i32) -> !emitc.ptr<i32>
+  %c = emitc.cmp lt, %b, %arg2 :(!emitc.ptr<i32>, !emitc.ptr<i32>) -> i1
   return %c : i1
 }
 
-// CHECK-LABEL: func.func @expression_with_address_taken(
-// CHECK-SAME:      %[[VAL_0:.*]]: i32, %[[VAL_1:.*]]: i32, %[[VAL_2:.*]]: !emitc.ptr<i32>) -> i1 {
-// CHECK:         %[[VAL_3:.*]] = emitc.expression : i32 {
-// CHECK:           %[[VAL_4:.*]] = emitc.rem %[[VAL_0]], %[[VAL_1]] : (i32, i32) -> i32
-// CHECK:           emitc.yield %[[VAL_4]] : i32
-// CHECK:         }
-// CHECK:         %[[VAL_5:.*]] = emitc.expression : i1 {
-// CHECK:           %[[VAL_6:.*]] = emitc.apply "&"(%[[VAL_3]]) : (i32) -> !emitc.ptr<i32>
-// CHECK:           %[[VAL_7:.*]] = emitc.add %[[VAL_6]], %[[VAL_1]] : (!emitc.ptr<i32>, i32) -> !emitc.ptr<i32>
-// CHECK:           %[[VAL_8:.*]] = emitc.cmp lt, %[[VAL_7]], %[[VAL_2]] : (!emitc.ptr<i32>, !emitc.ptr<i32>) -> i1
-// CHECK:           emitc.yield %[[VAL_8]] : i1
-// CHECK:         }
-// CHECK:         return %[[VAL_5]] : i1
-// CHECK:       }
-
-func.func @expression_with_address_taken(%arg0: i32, %arg1: i32, %arg2: !emitc.ptr<i32>) -> i1 {
-  %a = emitc.rem %arg0, %arg1 : (i32, i32) -> (i32)
-  %b = emitc.apply "&"(%a) : (i32) -> !emitc.ptr<i32>
-  %c = emitc.add %b, %arg1 : (!emitc.ptr<i32>, i32) -> !emitc.ptr<i32>
-  %d = emitc.cmp lt, %c, %arg2 :(!emitc.ptr<i32>, !emitc.ptr<i32>) -> i1
-  return %d : i1
-}
-
 // CHECK-LABEL: func.func @no_nested_expression(
 // CHECK-SAME:      %[[VAL_0:.*]]: i32, %[[VAL_1:.*]]: i32) -> i1 {
 // CHECK:         %[[VAL_2:.*]] = emitc.expression : i1 {
diff --git a/mlir/test/Dialect/EmitC/types.mlir b/mlir/test/Dialect/EmitC/types.mlir
index 752f2c10c17be..a81c3703af23b 100644
--- a/mlir/test/Dialect/EmitC/types.mlir
+++ b/mlir/test/Dialect/EmitC/types.mlir
@@ -1,6 +1,6 @@
-// RUN: mlir-opt -verify-diagnostics %s | FileCheck %s
+// RUN: mlir-opt -verify-diagnostics -allow-unregistered-dialect %s | FileCheck %s
 // check parser
-// RUN: mlir-opt -verify-diagnostics %s | mlir-opt -verify-diagnostics | FileCheck %s
+// RUN: mlir-opt -verify-diagnostics -allow-unregistered-dialect %s | mlir-opt -verify-diagnostics --allow-unregistered-dialect | FileCheck %s
 
 // CHECK-LABEL: func @array_types(
 func.func @array_types(
@@ -16,6 +16,21 @@ func.func @array_types(
   return
 }
 
+// CHECK-LABEL: func @lvalue_types(
+func.func @lvalue_types() {
+  // CHECK-NEXT: !emitc.lvalue<i32>
+  %0 = "typed.result"() : () -> (!emitc.lvalue<i32>)
+  // CHECK-NEXT: !emitc.lvalue<f64>
+  %2 = "typed.result"() : () -> (!emitc.lvalue<f64>)
+  // CHECK-NEXT: !emitc.lvalue<index>
+  %3 = "typed.result"() : () -> (!emitc.lvalue<index>)
+  // CHECK-NEXT: !emitc.lvalue<!emitc.ptr<i32>>
+  %4 = "typed.result"() : () -> (!emitc.lvalue<!emitc.ptr<i32>>)
+  // CHECK-NEXT: !emitc.lvalue<!emitc.opaque<"int">>
+  %5 = "typed.result"() : () -> (!emitc.lvalue<!emitc.opaque<"int">>)
+  return
+}
+
 // CHECK-LABEL: func @opaque_types() {
 func.func @opaque_types() {
   // CHECK-NEXT: !emitc.opaque<"int">
diff --git a/mlir/test/Target/Cpp/common-cpp.mlir b/mlir/test/Target/Cpp/common-cpp.mlir
index 0e24bdd19993f..c1d12eec6d17b 100644
--- a/mlir/test/Target/Cpp/common-cpp.mlir
+++ b/mlir/test/Target/Cpp/common-cpp.mlir
@@ -82,11 +82,20 @@ func.func @opaque_types(%arg0: !emitc.opaque<"bool">, %arg1: !emitc.opaque<"char
   return %2 : !emitc.opaque<"status_t">
 }
 
-func.func @apply(%arg0: i32) -> !emitc.ptr<i32> {
-  // CHECK: int32_t* [[V2]] = &[[V1]];
-  %0 = emitc.apply "&"(%arg0) : (i32) -> !emitc.ptr<i32>
-  // CHECK: int32_t [[V3]] = *[[V2]];
-  %1 = emitc.apply "*"(%0) : (!emitc.ptr<i32>) -> (i32)
+// CHECK-LABEL: int32_t* apply(
+// CHECK-SAME: int32_t [[V1:[^ ]*]]) {
+func.func @apply(%arg0: !emitc.lvalue<i32>) -> !emitc.ptr<i32> {
+  // CHECK-NEXT: int32_t* [[V2:[^ ]*]] = &[[V1]];
+  %0 = emitc.apply "&"(%arg0) : (!emitc.lvalue<i32>) -> !emitc.ptr<i32>
+  // CHECK-NEXT: int32_t [[V3:[^ ]*]];
+  %2 = "emitc.variable"() {value = #emitc.opaque<"">} : () -> !emitc.lvalue<i32>
+  // CHECK-NEXT: int32_t [[V4:[^ ]*]] = *[[V2]];
+  %1 = emitc.apply "*"(%0) : (!emitc.ptr<i32>) -> !emitc.lvalue<i32>
+  // CHECK-NEXT: int32_t [[V5:[^ ]*]] = [[V4]];
+  %3 = emitc.lvalue_load %1 : !emitc.lvalue<i32>
+  // CHECK-NEXT: [[V3]] = [[V5]];
+  emitc.assign %3 : i32 to %2 : !emitc.lvalue<i32>
+  // CHECK-NEXT: return [[V2]];
   return %0 : !emitc.ptr<i32>
 }
 
diff --git a/mlir/test/Target/Cpp/expressions.mlir b/mlir/test/Target/Cpp/expressions.mlir
index caa0a340d3e0a..d9455e8e98177 100644
--- a/mlir/test/Target/Cpp/expressions.mlir
+++ b/mlir/test/Target/Cpp/expressions.mlir
@@ -9,12 +9,14 @@
 // CPP-DEFAULT-NEXT:   } else {
 // CPP-DEFAULT-NEXT:     [[VAL_6]] = [[VAL_1]];
 // CPP-DEFAULT-NEXT:   }
-// CPP-DEFAULT-NEXT:   return [[VAL_6]];
+// CPP-DEFAULT-NEXT:   int32_t [[VAL_7:v[0-9]+]] = [[VAL_6]];
+// CPP-DEFAULT-NEXT:   return [[VAL_7]];
 // CPP-DEFAULT-NEXT: }
 
 // CPP-DECLTOP:      int32_t single_use(int32_t [[VAL_1:v[0-9]+]], int32_t [[VAL_2:v[0-9]+]], int32_t [[VAL_3:v[0-9]+]], int32_t [[VAL_4:v[0-9]+]]) {
 // CPP-DECLTOP-NEXT:   bool [[VAL_5:v[0-9]+]];
 // CPP-DECLTOP-NEXT:   int32_t [[VAL_6:v[0-9]+]];
+// CPP-DECLTOP-NEXT:   int32_t [[VAL_7:v[0-9]+]];
 // CPP-DECLTOP-NEXT:   [[VAL_5]] = bar([[VAL_1]] * M_PI, [[VAL_3]]) - [[VAL_4]] < [[VAL_2]];
 // CPP-DECLTOP-NEXT:   ;
 // CPP-DECLTOP-NEXT:   if ([[VAL_5]]) {
@@ -22,7 +24,8 @@
 // CPP-DECLTOP-NEXT:   } else {
 // CPP-DECLTOP-NEXT:     [[VAL_6]] = [[VAL_1]];
 // CPP-DECLTOP-NEXT:   }
-// CPP-DECLTOP-NEXT:   return [[VAL_6]];
+// CPP-DECLTOP-NEXT:   [[VAL_7]] = [[VAL_6]];
+// CPP-DECLTOP-NEXT:   return [[VAL_7]];
 // CPP-DECLTOP-NEXT: }
 
 func.func @single_use(%arg0: i32, %arg1: i32, %arg2: i32, %arg3: i32) -> i32 {
@@ -34,15 +37,16 @@ func.func @single_use(%arg0: i32, %arg1: i32, %arg2: i32, %arg3: i32) -> i32 {
     %d = emitc.cmp lt, %c, %arg1 :(i32, i32) -> i1
     emitc.yield %d : i1
   }
-  %v = "emitc.variable"(){value = #emitc.opaque<"">} : () -> i32
+  %v = "emitc.variable"(){value = #emitc.opaque<"">} : () -> !emitc.lvalue<i32>
   emitc.if %e {
-    emitc.assign %arg0 : i32 to %v : i32
+    emitc.assign %arg0 : i32 to %v : !emitc.lvalue<i32>
     emitc.yield
   } else {
-    emitc.assign %arg0 : i32 to %v : i32
+    emitc.assign %arg0 : i32 to %v : !emitc.lvalue<i32>
     emitc.yield
   }
-  return %v : i32
+  %v_load = emitc.lvalue_load %v : !emitc.lvalue<i32>
+  return %v_load : i32
 }
 
 // CPP-DEFAULT: int32_t do_not_inline(int32_t [[VAL_1:v[0-9]+]], int32_t [[VAL_2:v[0-9]+]], int32_t [[VAL_3:v[0-9]+]]) {
@@ -175,8 +179,8 @@ func.func @user_with_expression_trait(%arg0: i32, %arg1: i32, %arg2: i32) -> i32
   %add = emitc.add %e1, %c0 : (i32, i32) -> i32
   %call = emitc.call_opaque "bar" (%e2, %c0) : (i32, i32) -> (i32)
   %cond = emitc.conditional %cast, %e3, %c0 : i32
-  %var = "emitc.variable"() {value = #emitc.opaque<"">} : () -> i32
-  emitc.assign %e4 : i32 to %var : i32
+  %var = "emitc.variable"() {value = #emitc.opaque<"">} : () -> !emitc.lvalue<i32>
+  emitc.assign %e4 : i32 to %var : !emitc.lvalue<i32>
   return %e5 : i32
 }
 
@@ -190,13 +194,15 @@ func.func @user_with_expression_trait(%arg0: i32, %arg1: i32, %arg2: i32) -> i32
 // CPP-DEFAULT-NEXT:   }
 // CPP-DEFAULT-NEXT:   bool [[VAL_7:v[0-9]+]];
 // CPP-DEFAULT-NEXT:   [[VAL_7]] = [[VAL_5]];
-// CPP-DEFAULT-NEXT:   return [[VAL_6]];
+// CPP-DEFAULT-NEXT:   int32_t [[VAL_8:v[0-9]+]] = [[VAL_6]];
+// CPP-DEFAULT-NEXT:   return [[VAL_8]];
 // CPP-DEFAULT-NEXT: }
 
 // CPP-DECLTOP:      int32_t multiple_uses(int32_t [[VAL_1:v[0-9]+]], int32_t [[VAL_2:v[0-9]+]], int32_t [[VAL_3:v[0-9]+]], int32_t [[VAL_4:v[0-9]+]]) {
 // CPP-DECLTOP-NEXT:   bool [[VAL_5:v[0-9]+]];
 // CPP-DECLTOP-NEXT:   int32_t [[VAL_6:v[0-9]+]];
 // CPP-DECLTOP-NEXT:   bool [[VAL_7:v[0-9]+]];
+// CPP-DECLTOP-NEXT:   int32_t [[VAL_8:v[0-9]+]];
 // CPP-DECLTOP-NEXT:   [[VAL_5]] = bar([[VAL_1]] * [[VAL_2]], [[VAL_3]]) - [[VAL_4]] < [[VAL_2]];
 // CPP-DECLTOP-NEXT:   ;
 // CPP-DECLTOP-NEXT:   if ([[VAL_5]]) {
@@ -206,7 +212,8 @@ func.func @user_with_expression_trait(%arg0: i32, %arg1: i32, %arg2: i32) -> i32
 // CPP-DECLTOP-NEXT:   }
 // CPP-DECLTOP-NEXT:   ;
 // CPP-DECLTOP-NEXT:   [[VAL_7]] = [[VAL_5]];
-// CPP-DECLTOP-NEXT:   return [[VAL_6]];
+// CPP-DECLTOP-NEXT:   [[VAL_8]] = [[VAL_6]];
+// CPP-DECLTOP-NEXT:   return [[VAL_8]];
 // CPP-DECLTOP-NEXT: }
 
 func.func @multiple_uses(%arg0: i32, %arg1: i32, %arg2: i32, %arg3: i32) -> i32 {
@@ -217,17 +224,18 @@ func.func @multiple_uses(%arg0: i32, %arg1: i32, %arg2: i32, %arg3: i32) -> i32
     %d = emitc.cmp lt, %c, %arg1 :(i32, i32) -> i1
     emitc.yield %d : i1
   }
-  %v = "emitc.variable"(){value = #emitc.opaque<"">} : () -> i32
+  %v = "emitc.variable"(){value = #emitc.opaque<"">} : () -> !emitc.lvalue<i32>
   emitc.if %e {
-    emitc.assign %arg0 : i32 to %v : i32
+    emitc.assign %arg0 : i32 to %v : !emitc.lvalue<i32>
     emitc.yield
   } else {
-    emitc.assign %arg0 : i32 to %v : i32
+    emitc.assign %arg0 : i32 to %v : !emitc.lvalue<i32>
     emitc.yield
   }
-  %q = "emitc.variable"(){value = #emitc.opaque<"">} : () -> i1
-  emitc.assign %e : i1 to %q : i1
-  return %v : i32
+  %q = "emitc.variable"(){value = #emitc.opaque<"">} : () -> !emitc.lvalue<i1>
+  emitc.assign %e : i1 to %q : !emitc.lvalue<i1>
+  %v_load = emitc.lvalue_load %v : !emitc.lvalue<i32>
+  return %v_load : i32
 }
 
 // CPP-DEFAULT:      int32_t different_expressions(int32_t [[VAL_1:v[0-9]+]], int32_t [[VAL_2:v[0-9]+]], int32_t [[VAL_3:v[0-9]+]], int32_t [[VAL_4:v[0-9]+]]) {
@@ -239,13 +247,15 @@ func.func @multiple_uses(%arg0: i32, %arg1: i32, %arg2: i32, %arg3: i32) -> i32
 // CPP-DEFAULT-NEXT:   } else {
 // CPP-DEFAULT-NEXT:     [[VAL_7]] = [[VAL_1]];
 // CPP-DEFAULT-NEXT:   }
-// CPP-DEFAULT-NEXT:   return [[VAL_7]];
+// CPP-DEFAULT-NEXT:   int32_t [[VAL_8:v[0-9]+]] = [[VAL_7]];
+// CPP-DEFAULT-NEXT:   return [[VAL_8]];
 // CPP-DEFAULT-NEXT: }
 
 // CPP-DECLTOP:      int32_t different_expressions(int32_t [[VAL_1:v[0-9]+]], int32_t [[VAL_2:v[0-9]+]], int32_t [[VAL_3:v[0-9]+]], int32_t [[VAL_4:v[0-9]+]]) {
 // CPP-DECLTOP-NEXT:   int32_t [[VAL_5:v[0-9]+]];
 // CPP-DECLTOP-NEXT:   int32_t [[VAL_6:v[0-9]+]];
 // CPP-DECLTOP-NEXT:   int32_t [[VAL_7:v[0-9]+]];
+// CPP-DECLTOP-NEXT:   int32_t [[VAL_8:v[0-9]+]];
 // CPP-DECLTOP-NEXT:   [[VAL_5]] = [[VAL_3]] % [[VAL_4]];
 // CPP-DECLTOP-NEXT:   [[VAL_6]] = bar([[VAL_5]], [[VAL_1]] * [[VAL_2]]);
 // CPP-DECLTOP-NEXT:   ;
@@ -254,7 +264,8 @@ func.func @multiple_uses(%arg0: i32, %arg1: i32, %arg2: i32, %arg3: i32) -> i32
 // CPP-DECLTOP-NEXT:   } else {
 // CPP-DECLTOP-NEXT:     [[VAL_7]] = [[VAL_1]];
 // CPP-DECLTOP-NEXT:   }
-// CPP-DECLTOP-NEXT:   return [[VAL_7]];
+// CPP-DECLTOP-NEXT:   [[VAL_8]] = [[VAL_7]];
+// CPP-DECLTOP-NEXT:   return [[VAL_8]];
 // CPP-DECLTOP-NEXT: }
 
 func.func @different_expressions(%arg0: i32, %arg1: i32, %arg2: i32, %arg3: i32) -> i32 {
@@ -272,35 +283,33 @@ func.func @different_expressions(%arg0: i32, %arg1: i32, %arg2: i32, %arg3: i32)
     %d = emitc.cmp lt, %c, %arg1 :(i32, i32) -> i1
     emitc.yield %d : i1
   }
-  %v = "emitc.variable"(){value = #emitc.opaque<"">} : () -> i32
+  %v = "emitc.variable"(){value = #emitc.opaque<"">} : () -> !emitc.lvalue<i32>
   emitc.if %e3 {
-    emitc.assign %arg0 : i32 to %v : i32
+    emitc.assign %arg0 : i32 to %v : !emitc.lvalue<i32>
     emitc.yield
   } else {
-    emitc.assign %arg0 : i32 to %v : i32
+    emitc.assign %arg0 : i32 to %v : !emitc.lvalue<i32>
     emitc.yield
   }
-  return %v : i32
+  %v_load = emitc.lvalue_load %v : !emitc.lvalue<i32>
+  return %v_load : i32
 }
 
 // CPP-DEFAULT:      bool expression_with_address_taken(int32_t [[VAL_1:v[0-9]+]], int32_t [[VAL_2:v[0-9]+]], int32_t* [[VAL_3]]) {
-// CPP-DEFAULT-NEXT:   int32_t [[VAL_4:v[0-9]+]] = [[VAL_1]] % [[VAL_2]];
+// CPP-DEFAULT-NEXT:   int32_t [[VAL_4:v[0-9]+]] = 42;
 // CPP-DEFAULT-NEXT:   return &[[VAL_4]] - [[VAL_2]] < [[VAL_3]];
 // CPP-DEFAULT-NEXT: }
 
 // CPP-DECLTOP:      bool expression_with_address_taken(int32_t [[VAL_1:v[0-9]+]], int32_t [[VAL_2:v[0-9]+]], int32_t* [[VAL_3]]) {
 // CPP-DECLTOP-NEXT:   int32_t [[VAL_4:v[0-9]+]];
-// CPP-DECLTOP-NEXT:   [[VAL_4]] = [[VAL_1]] % [[VAL_2]];
+// CPP-DECLTOP-NEXT:   [[VAL_4]] = 42;
 // CPP-DECLTOP-NEXT:   return &[[VAL_4]] - [[VAL_2]] < [[VAL_3]];
 // CPP-DECLTOP-NEXT: }
 
 func.func @expression_with_address_taken(%arg0: i32, %arg1: i32, %arg2: !emitc.ptr<i32>) -> i1 {
-  %a = emitc.expression : i32 {
-    %b = emitc.rem %arg0, %arg1 : (i32, i32) -> i32
-    emitc.yield %b : i32
-  }
+  %a = "emitc.variable"(){value = 42 : i32} : () -> !emitc.lvalue<i32>
   %c = emitc.expression : i1 {
-    %d = emitc.apply "&"(%a) : (i32) -> !emitc.ptr<i32>
+    %d = emitc.apply "&"(%a) : (!emitc.lvalue<i32>) -> !emitc.ptr<i32>
     %e = emitc.sub %d, %arg1 : (!emitc.ptr<i32>, i32) -> !emitc.ptr<i32>
     %f = emitc.cmp lt, %e, %arg2 : (!emitc.ptr<i32>, !emitc.ptr<i32>) -> i1
     emitc.yield %f : i1
@@ -311,7 +320,17 @@ func.func @expression_with_address_taken(%arg0: i32, %arg1: i32, %arg2: !emitc.p
 // CPP-DEFAULT: int32_t expression_with_subscript_user(void* [[VAL_1:v.+]])
 // CPP-DEFAULT-NEXT:   int64_t [[VAL_2:v.+]] = 0;
 // CPP-DEFAULT-NEXT:   int32_t* [[VAL_3:v.+]] = (int32_t*) [[VAL_1]];
-// CPP-DEFAULT-NEXT:   return [[VAL_3]][[[VAL_2]]];
+// CPP-DEFAULT-NEXT:   int32_t [[VAL_4:v.+]] = [[VAL_3]][[[VAL_2]]];
+// CPP-DEFAULT-NEXT:   return [[VAL_4]];
+
+// CPP-DECLTOP: int32_t expression_with_subscript_user(void* [[VAL_1:v.+]])
+// CPP-DECLTOP-NEXT:   int64_t [[VAL_2:v.+]];
+// CPP-DECLTOP-NEXT:   int32_t* [[VAL_3:v.+]];
+// CPP-DECLTOP-NEXT:   int32_t [[VAL_4:v.+]];
+// CPP-DECLTOP-NEXT:   [[VAL_2]] = 0;
+// CPP-DECLTOP-NEXT:   [[VAL_3]] = (int32_t*) [[VAL_1]];
+// CPP-DECLTOP-NEXT:   [[VAL_4]] = [[VAL_3]][[[VAL_2]]];
+// CPP-DECLTOP-NEXT:   return [[VAL_4]];
 
 func.func @expression_with_subscript_user(%arg0: !emitc.ptr<!emitc.opaque<"void">>) -> i32 {
   %c0 = "emitc.constant"() {value = 0 : i64} : () -> i64
@@ -319,6 +338,7 @@ func.func @expression_with_subscript_user(%arg0: !emitc.ptr<!emitc.opaque<"void"
     %0 = emitc.cast %arg0 : !emitc.ptr<!emitc.opaque<"void">> to !emitc.ptr<i32>
     emitc.yield %0 : !emitc.ptr<i32>
   }
-  %1 = emitc.subscript %0[%c0] : (!emitc.ptr<i32>, i64) -> i32
-  return %1 : i32
+  %res = emitc.subscript %0[%c0] : (!emitc.ptr<i32>, i64) -> !emitc.lvalue<i32>
+  %res_load = emitc.lvalue_load %res : !emitc.lvalue<i32>
+  return %res_load : i32
 }
diff --git a/mlir/test/Target/Cpp/for.mlir b/mlir/test/Target/Cpp/for.mlir
index 60988bcb46556..14d3f05d6a08e 100644
--- a/mlir/test/Target/Cpp/for.mlir
+++ b/mlir/test/Target/Cpp/for.mlir
@@ -40,21 +40,25 @@ func.func @test_for_yield() {
   %s0 = "emitc.constant"() <{value = 0 : i32}> : () -> i32
   %p0 = "emitc.constant"() <{value = 1.0 : f32}> : () -> f32
 
-  %0 = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> i32
-  %1 = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> f32
-  %2 = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> i32
-  %3 = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> f32
-  emitc.assign %s0 : i32 to %2 : i32
-  emitc.assign %p0 : f32 to %3 : f32
+  %0 = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> !emitc.lvalue<i32>
+  %1 = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> !emitc.lvalue<f32>
+  %2 = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> !emitc.lvalue<i32>
+  %3 = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> !emitc.lvalue<f32>
+  emitc.assign %s0 : i32 to %2 : !emitc.lvalue<i32>
+  emitc.assign %p0 : f32 to %3 : !emitc.lvalue<f32>
   emitc.for %iter = %start to %stop step %step {
-    %sn = emitc.call_opaque "add"(%2, %iter) : (i32, index) -> i32
-    %pn = emitc.call_opaque "mul"(%3, %iter) : (f32, index) -> f32
-    emitc.assign %sn : i32 to %2 : i32
-    emitc.assign %pn : f32 to %3 : f32
+    %4 = emitc.lvalue_load %2 : !emitc.lvalue<i32>
+    %sn = emitc.call_opaque "add"(%4, %iter) : (i32, index) -> i32
+    %5 = emitc.lvalue_load %3 : !emitc.lvalue<f32>
+    %pn = emitc.call_opaque "mul"(%5, %iter) : (f32, index) -> f32
+    emitc.assign %sn : i32 to %2 : !emitc.lvalue<i32>
+    emitc.assign %pn : f32 to %3 : !emitc.lvalue<f32>
     emitc.yield
   }
-  emitc.assign %2 : i32 to %0 : i32
-  emitc.assign %3 : f32 to %1 : f32
+  %6 = emitc.lvalue_load %2 : !emitc.lvalue<i32>
+  emitc.assign %6 : i32 to %0 : !emitc.lvalue<i32>
+  %7 = emitc.lvalue_load %3 : !emitc.lvalue<f32>
+  emitc.assign %7 : f32 to %1 : !emitc.lvalue<f32>
 
   return
 }
@@ -71,13 +75,17 @@ func.func @test_for_yield() {
 // CPP-DEFAULT-NEXT: [[SI:[^ ]*]] = [[S0]];
 // CPP-DEFAULT-NEXT: [[PI:[^ ]*]] = [[P0]];
 // CPP-DEFAULT-NEXT: for (size_t [[ITER:[^ ]*]] = [[START]]; [[ITER]] < [[STOP]]; [[ITER]] += [[STEP]]) {
-// CPP-DEFAULT-NEXT: int32_t [[SN:[^ ]*]] = add([[SI]], [[ITER]]);
-// CPP-DEFAULT-NEXT: float [[PN:[^ ]*]] = mul([[PI]], [[ITER]]);
+// CPP-DEFAULT-NEXT: int32_t [[SI_LOAD:[^ ]*]] = [[SI]];
+// CPP-DEFAULT-NEXT: int32_t [[SN:[^ ]*]] = add([[SI_LOAD]], [[ITER]]);
+// CPP-DEFAULT-NEXT: float [[PI_LOAD:[^ ]*]] = [[PI]];
+// CPP-DEFAULT-NEXT: float [[PN:[^ ]*]] = mul([[PI_LOAD]], [[ITER]]);
 // CPP-DEFAULT-NEXT: [[SI]] = [[SN]];
 // CPP-DEFAULT-NEXT: [[PI]] = [[PN]];
 // CPP-DEFAULT-NEXT: }
-// CPP-DEFAULT-NEXT: [[SE]] = [[SI]];
-// CPP-DEFAULT-NEXT: [[PE]] = [[PI]];
+// CPP-DEFAULT-NEXT: int32_t [[SI_LOAD2:[^ ]*]] = [[SI]];
+// CPP-DEFAULT-NEXT: [[SE]] = [[SI_LOAD2]];
+// CPP-DEFAULT-NEXT: float [[PI_LOAD2:[^ ]*]] = [[PI]];
+// CPP-DEFAULT-NEXT: [[PE]] = [[PI_LOAD2]];
 // CPP-DEFAULT-NEXT: return;
 
 // CPP-DECLTOP: void test_for_yield() {
@@ -90,8 +98,12 @@ func.func @test_for_yield() {
 // CPP-DECLTOP-NEXT: float [[PE:[^ ]*]];
 // CPP-DECLTOP-NEXT: int32_t [[SI:[^ ]*]];
 // CPP-DECLTOP-NEXT: float [[PI:[^ ]*]];
+// CPP-DECLTOP-NEXT: int32_t [[SI_LOAD:[^ ]*]];
 // CPP-DECLTOP-NEXT: int32_t [[SN:[^ ]*]];
+// CPP-DECLTOP-NEXT: float [[PI_LOAD:[^ ]*]];
 // CPP-DECLTOP-NEXT: float [[PN:[^ ]*]];
+// CPP-DECLTOP-NEXT: int32_t [[SI_LOAD2:[^ ]*]];
+// CPP-DECLTOP-NEXT: float [[PI_LOAD2:[^ ]*]];
 // CPP-DECLTOP-NEXT: [[START]] = 0;
 // CPP-DECLTOP-NEXT: [[STOP]] = 10;
 // CPP-DECLTOP-NEXT: [[STEP]] = 1;
@@ -101,16 +113,20 @@ func.func @test_for_yield() {
 // CPP-DECLTOP-NEXT: ;
 // CPP-DECLTOP-NEXT: ;
 // CPP-DECLTOP-NEXT: ;
-// CPP-DECLTOP-NEXT: [[SI:[^ ]*]] = [[S0]];
-// CPP-DECLTOP-NEXT: [[PI:[^ ]*]] = [[P0]];
+// CPP-DECLTOP-NEXT: [[SI]] = [[S0]];
+// CPP-DECLTOP-NEXT: [[PI]] = [[P0]];
 // CPP-DECLTOP-NEXT: for (size_t [[ITER:[^ ]*]] = [[START]]; [[ITER]] < [[STOP]]; [[ITER]] += [[STEP]]) {
-// CPP-DECLTOP-NEXT: [[SN]] = add([[SI]], [[ITER]]);
-// CPP-DECLTOP-NEXT: [[PN]] = mul([[PI]], [[ITER]]);
+// CPP-DECLTOP-NEXT: [[SI_LOAD]] = [[SI]];
+// CPP-DECLTOP-NEXT: [[SN]] = add([[SI_LOAD]], [[ITER]]);
+// CPP-DECLTOP-NEXT: [[PI_LOAD]] = [[PI]];
+// CPP-DECLTOP-NEXT: [[PN]] = mul([[PI_LOAD]], [[ITER]]);
 // CPP-DECLTOP-NEXT: [[SI]] = [[SN]];
 // CPP-DECLTOP-NEXT: [[PI]] = [[PN]];
 // CPP-DECLTOP-NEXT: }
-// CPP-DECLTOP-NEXT: [[SE]] = [[SI]];
-// CPP-DECLTOP-NEXT: [[PE]] = [[PI]];
+// CPP-DECLTOP-NEXT: [[SI_LOAD2]] = [[SI]];
+// CPP-DECLTOP-NEXT: [[SE]] = [[SI_LOAD2]];
+// CPP-DECLTOP-NEXT: [[PI_LOAD2]] = [[PI]];
+// CPP-DECLTOP-NEXT: [[PE]] = [[PI_LOAD2]];
 // CPP-DECLTOP-NEXT: return;
 
 func.func @test_for_yield_2() {
@@ -121,21 +137,25 @@ func.func @test_for_yield_2() {
   %s0 = emitc.literal "0" : i32
   %p0 = emitc.literal "M_PI" : f32
 
-  %0 = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> i32
-  %1 = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> f32
-  %2 = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> i32
-  %3 = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> f32
-  emitc.assign %s0 : i32 to %2 : i32
-  emitc.assign %p0 : f32 to %3 : f32
+  %0 = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> !emitc.lvalue<i32>
+  %1 = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> !emitc.lvalue<f32>
+  %2 = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> !emitc.lvalue<i32>
+  %3 = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> !emitc.lvalue<f32>
+  emitc.assign %s0 : i32 to %2 : !emitc.lvalue<i32>
+  emitc.assign %p0 : f32 to %3 : !emitc.lvalue<f32>
   emitc.for %iter = %start to %stop step %step {
-    %sn = emitc.call_opaque "add"(%2, %iter) : (i32, index) -> i32
-    %pn = emitc.call_opaque "mul"(%3, %iter) : (f32, index) -> f32
-    emitc.assign %sn : i32 to %2 : i32
-    emitc.assign %pn : f32 to %3 : f32
+    %4 = emitc.lvalue_load %2 : !emitc.lvalue<i32>
+    %sn = emitc.call_opaque "add"(%4, %iter) : (i32, index) -> i32
+    %5 = emitc.lvalue_load %3 : !emitc.lvalue<f32>
+    %pn = emitc.call_opaque "mul"(%5, %iter) : (f32, index) -> f32
+    emitc.assign %sn : i32 to %2 : !emitc.lvalue<i32>
+    emitc.assign %pn : f32 to %3 : !emitc.lvalue<f32>
     emitc.yield
   }
-  emitc.assign %2 : i32 to %0 : i32
-  emitc.assign %3 : f32 to %1 : f32
+  %6 = emitc.lvalue_load %2 : !emitc.lvalue<i32>
+  emitc.assign %6 : i32 to %0 : !emitc.lvalue<i32>
+  %7 = emitc.lvalue_load %3 : !emitc.lvalue<f32>
+  emitc.assign %7 : f32 to %1 : !emitc.lvalue<f32>
 
   return
 }
diff --git a/mlir/test/Target/Cpp/global.mlir b/mlir/test/Target/Cpp/global.mlir
index f0d92e862ae32..32eb8c6cf6f87 100644
--- a/mlir/test/Target/Cpp/global.mlir
+++ b/mlir/test/Target/Cpp/global.mlir
@@ -1,38 +1,100 @@
-// RUN: mlir-translate -mlir-to-cpp %s | FileCheck %s
-// RUN: mlir-translate -mlir-to-cpp -declare-variables-at-top %s | FileCheck %s
+// RUN: mlir-translate -mlir-to-cpp %s | FileCheck %s -check-prefix=CPP-DEFAULT
+// RUN: mlir-translate -mlir-to-cpp -declare-variables-at-top %s | FileCheck %s -check-prefix=CPP-DECLTOP
 
 emitc.global extern @decl : i8
-// CHECK: extern int8_t decl;
+// CPP-DEFAULT: extern int8_t decl;
+// CPP-DECLTOP: extern int8_t decl;
 
 emitc.global @uninit : i32
-// CHECK: int32_t uninit;
+// CPP-DEFAULT: int32_t uninit;
+// CPP-DECLTOP: int32_t uninit;
 
 emitc.global @myglobal_int : i32 = 4
-// CHECK: int32_t myglobal_int = 4;
+// CPP-DEFAULT: int32_t myglobal_int = 4;
+// CPP-DECLTOP: int32_t myglobal_int = 4;
 
 emitc.global @myglobal : !emitc.array<2xf32> = dense<4.000000e+00>
-// CHECK: float myglobal[2] = {4.000000000e+00f, 4.000000000e+00f};
+// CPP-DEFAULT: float myglobal[2] = {4.000000000e+00f, 4.000000000e+00f};
+// CPP-DECLTOP: float myglobal[2] = {4.000000000e+00f, 4.000000000e+00f};
 
 emitc.global const @myconstant : !emitc.array<2xi16> = dense<2>
-// CHECK: const int16_t myconstant[2] = {2, 2};
+// CPP-DEFAULT: const int16_t myconstant[2] = {2, 2};
+// CPP-DECLTOP: const int16_t myconstant[2] = {2, 2};
 
 emitc.global extern const @extern_constant : !emitc.array<2xi16>
-// CHECK: extern const int16_t extern_constant[2];
+// CPP-DEFAULT: extern const int16_t extern_constant[2];
+// CPP-DECLTOP: extern const int16_t extern_constant[2];
 
 emitc.global static @static_var : f32
-// CHECK: static float static_var;
+// CPP-DEFAULT: static float static_var;
+// CPP-DECLTOP: static float static_var;
 
 emitc.global static @static_const : f32 = 3.0
-// CHECK: static float static_const = 3.000000000e+00f;
+// CPP-DEFAULT: static float static_const = 3.000000000e+00f;
+// CPP-DECLTOP: static float static_const = 3.000000000e+00f;
 
 emitc.global @opaque_init : !emitc.opaque<"char"> = #emitc.opaque<"CHAR_MIN">
-// CHECK: char opaque_init = CHAR_MIN;
+// CPP-DEFAULT: char opaque_init = CHAR_MIN;
+// CPP-DECLTOP: char opaque_init = CHAR_MIN;
 
-func.func @use_global(%i: index) -> f32 {
+func.func @use_global_scalar_read() -> i32 {
+  %0 = emitc.get_global @myglobal_int : !emitc.lvalue<i32>
+  %1 = emitc.lvalue_load %0 : !emitc.lvalue<i32>
+  return %1 : i32
+}
+// CPP-DEFAULT-LABEL: int32_t use_global_scalar_read()
+// CPP-DEFAULT-NEXT: int32_t [[V1:[^ ]*]] = myglobal_int;
+// CPP-DEFAULT-NEXT: return [[V1]];
+
+// CPP-DECLTOP-LABEL: int32_t use_global_scalar_read()
+// CPP-DECLTOP-NEXT: int32_t [[V1:[^ ]*]];
+// CPP-DECLTOP-NEXT: [[V1]] = myglobal_int;
+// CPP-DECLTOP-NEXT: return [[V1]];
+
+func.func @use_global_scalar_write(%arg0 : i32) {
+  %0 = emitc.get_global @myglobal_int : !emitc.lvalue<i32>
+  emitc.assign %arg0 : i32 to %0 : !emitc.lvalue<i32> 
+  return
+}
+// CPP-DEFAULT-LABEL: void use_global_scalar_write
+// CPP-DEFAULT-SAME: (int32_t [[V1:.*]])
+// CPP-DEFAULT-NEXT: myglobal_int = [[V1]];
+// CPP-DEFAULT-NEXT: return;
+
+// CPP-DECLTOP-LABEL: void use_global_scalar_write
+// CPP-DECLTOP-SAME: (int32_t [[V1:.*]])
+// CPP-DECLTOP-NEXT: myglobal_int = [[V1]];
+// CPP-DECLTOP-NEXT: return;
+
+func.func @use_global_array_read(%i: index) -> f32 {
   %0 = emitc.get_global @myglobal : !emitc.array<2xf32>
-  %1 = emitc.subscript %0[%i] : (!emitc.array<2xf32>, index) -> f32
-  return %1 : f32
-  // CHECK-LABEL: use_global
-  // CHECK-SAME: (size_t [[V1:.*]])
-  // CHECK:   return myglobal[[[V1]]];
+  %1 = emitc.subscript %0[%i] : (!emitc.array<2xf32>, index) -> !emitc.lvalue<f32>
+  %2 = emitc.lvalue_load %1 : <f32>
+  return %2 : f32
 }
+// CPP-DEFAULT-LABEL: float use_global_array_read
+// CPP-DEFAULT-SAME: (size_t [[V1:.*]])
+// CPP-DEFAULT-NEXT: float [[V2:[^ ]*]] = myglobal[[[V1]]];
+// CPP-DEFAULT-NEXT: return [[V2]];
+
+// CPP-DECLTOP-LABEL: float use_global_array_read
+// CPP-DECLTOP-SAME: (size_t [[V1:.*]])
+// CPP-DECLTOP-NEXT: float [[V2:[^ ]*]];
+// CPP-DECLTOP-NEXT: [[V2]] = myglobal[[[V1]]];
+// CPP-DECLTOP-NEXT: return [[V2]];
+
+func.func @use_global_array_write(%i: index, %val : f32) {
+  %0 = emitc.get_global @myglobal : !emitc.array<2xf32>
+  %1 = emitc.subscript %0[%i] : (!emitc.array<2xf32>, index) -> !emitc.lvalue<f32>
+  emitc.assign %val : f32 to %1 : !emitc.lvalue<f32> 
+  return
+}
+// CPP-DEFAULT-LABEL: void use_global_array_write
+// CPP-DEFAULT-SAME: (size_t [[V1:.*]], float [[V2:.*]])
+// CPP-DEFAULT-NEXT: myglobal[[[V1]]] = [[V2]];
+// CPP-DEFAULT-NEXT: return;
+
+// CPP-DECLTOP-LABEL: void use_global_array_write
+// CPP-DECLTOP-SAME: (size_t [[V1:.*]], float [[V2:.*]])
+// CPP-DECLTOP-NEXT: myglobal[[[V1]]] = [[V2]];
+// CPP-DECLTOP-NEXT: return;
diff --git a/mlir/test/Target/Cpp/if.mlir b/mlir/test/Target/Cpp/if.mlir
index 7b0e2da85d0eb..d3b792192c8b1 100644
--- a/mlir/test/Target/Cpp/if.mlir
+++ b/mlir/test/Target/Cpp/if.mlir
@@ -50,18 +50,18 @@ func.func @test_if_else(%arg0: i1, %arg1: f32) {
 
 func.func @test_if_yield(%arg0: i1, %arg1: f32) {
   %0 = "emitc.constant"() <{value = 0 : i8}> : () -> i8
-  %x = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> i32
-  %y = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> f64
+  %x = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> !emitc.lvalue<i32>
+  %y = "emitc.variable"() <{value = #emitc.opaque<"">}> : () -> !emitc.lvalue<f64>
   emitc.if %arg0 {
     %1 = emitc.call_opaque "func_true_1"(%arg1) : (f32) -> i32
     %2 = emitc.call_opaque "func_true_2"(%arg1) : (f32) -> f64
-    emitc.assign %1 : i32 to %x : i32
-    emitc.assign %2 : f64 to %y : f64
+    emitc.assign %1 : i32 to %x : !emitc.lvalue<i32>
+    emitc.assign %2 : f64 to %y : !emitc.lvalue<f64>
   } else {
     %1 = emitc.call_opaque "func_false_1"(%arg1) : (f32) -> i32
     %2 = emitc.call_opaque "func_false_2"(%arg1) : (f32) -> f64
-    emitc.assign %1 : i32 to %x : i32
-    emitc.assign %2 : f64 to %y : f64
+    emitc.assign %1 : i32 to %x : !emitc.lvalue<i32>
+    emitc.assign %2 : f64 to %y : !emitc.lvalue<f64>
   }
   return
 }
diff --git a/mlir/test/Target/Cpp/invalid.mlir b/mlir/test/Target/Cpp/invalid.mlir
index 513371a09cde1..14fd0cd56170b 100644
--- a/mlir/test/Target/Cpp/invalid.mlir
+++ b/mlir/test/Target/Cpp/invalid.mlir
@@ -82,6 +82,6 @@ func.func @array_as_result(%arg: !emitc.array<4xi8>) -> (!emitc.array<4xi8>) {
 // -----
 func.func @ptr_to_array() {
   // expected-error at +1 {{cannot emit pointer to array type '!emitc.ptr<!emitc.array<9xi16>>'}}
-  %v = "emitc.variable"(){value = #emitc.opaque<"NULL">} : () -> !emitc.ptr<!emitc.array<9xi16>>
+  %v = "emitc.variable"(){value = #emitc.opaque<"NULL">} : () -> !emitc.lvalue<!emitc.ptr<!emitc.array<9xi16>>>
   return
 }
diff --git a/mlir/test/Target/Cpp/lvalue.mlir b/mlir/test/Target/Cpp/lvalue.mlir
new file mode 100644
index 0000000000000..5c370117f4387
--- /dev/null
+++ b/mlir/test/Target/Cpp/lvalue.mlir
@@ -0,0 +1,22 @@
+// RUN: mlir-translate -mlir-to-cpp %s | FileCheck %s
+
+// CHECK: int32_t lvalue_variables(
+emitc.func @lvalue_variables(%v1: i32, %v2: i32) -> i32 {
+  %val = emitc.mul %v1, %v2 : (i32, i32) -> i32
+  %variable = "emitc.variable"() {value = #emitc.opaque<"">} : () -> !emitc.lvalue<i32> // alloc effect
+  emitc.assign %val : i32 to %variable : !emitc.lvalue<i32> // write effect
+  %addr = emitc.apply "&"(%variable) : (!emitc.lvalue<i32>) -> !emitc.ptr<i32>
+  emitc.call @zero (%addr) : (!emitc.ptr<i32>) -> ()
+  %updated_val = emitc.lvalue_load %variable : !emitc.lvalue<i32> // read effect, (noop in emitter?)
+  %neg_one = "emitc.constant"() {value = -1 : i32} : () -> i32
+  emitc.assign %neg_one : i32 to %variable : !emitc.lvalue<i32> // invalidates %updated_val
+  emitc.return %updated_val : i32
+  // dealloc effect through automatic allocation scope
+}
+
+emitc.func @zero(%arg0: !emitc.ptr<i32>) {
+    %0 =  "emitc.constant"() {value = 0 : i32} : () -> i32
+    %1 = emitc.apply "*"(%arg0) : (!emitc.ptr<i32>) -> !emitc.lvalue<i32>
+    emitc.assign %0 : i32 to %1 : !emitc.lvalue<i32>
+    emitc.return
+}
\ No newline at end of file
diff --git a/mlir/test/Target/Cpp/subscript.mlir b/mlir/test/Target/Cpp/subscript.mlir
index 0b388953c80d3..b5c94c146712e 100644
--- a/mlir/test/Target/Cpp/subscript.mlir
+++ b/mlir/test/Target/Cpp/subscript.mlir
@@ -1,35 +1,59 @@
-// RUN: mlir-translate -mlir-to-cpp %s | FileCheck %s
-// RUN: mlir-translate -mlir-to-cpp -declare-variables-at-top %s | FileCheck %s
+// RUN: mlir-translate -mlir-to-cpp %s | FileCheck %s -check-prefix=CPP-DEFAULT
+// RUN: mlir-translate -mlir-to-cpp -declare-variables-at-top %s | FileCheck %s -check-prefix=CPP-DECLTOP
 
 func.func @load_store_array(%arg0: !emitc.array<4x8xf32>, %arg1: !emitc.array<3x5xf32>, %arg2: index, %arg3: index) {
-  %0 = emitc.subscript %arg0[%arg2, %arg3] : (!emitc.array<4x8xf32>, index, index) -> f32
-  %1 = emitc.subscript %arg1[%arg2, %arg3] : (!emitc.array<3x5xf32>, index, index) -> f32
-  emitc.assign %0 : f32 to %1 : f32
+  %0 = emitc.subscript %arg0[%arg2, %arg3] : (!emitc.array<4x8xf32>, index, index) -> !emitc.lvalue<f32>
+  %1 = emitc.subscript %arg1[%arg2, %arg3] : (!emitc.array<3x5xf32>, index, index) -> !emitc.lvalue<f32>
+  %2 = emitc.lvalue_load %0 : <f32>
+  emitc.assign %2 : f32 to %1 : !emitc.lvalue<f32>
   return
 }
-// CHECK: void load_store_array(float [[ARR1:[^ ]*]][4][8], float [[ARR2:[^ ]*]][3][5],
-// CHECK-SAME:            size_t [[I:[^ ]*]], size_t [[J:[^ ]*]])
-// CHECK-NEXT: [[ARR2]][[[I]]][[[J]]] = [[ARR1]][[[I]]][[[J]]];
+// CPP-DEFAULT: void load_store_array(float [[ARR1:[^ ]*]][4][8], float [[ARR2:[^ ]*]][3][5],
+// CPP-DEFAULT-SAME:            size_t [[I:[^ ]*]], size_t [[J:[^ ]*]])
+// CPP-DEFAULT-NEXT: float [[VAL:[^ ]*]] = [[ARR1]][[[I]]][[[J]]];
+// CPP-DEFAULT-NEXT: [[ARR2]][[[I]]][[[J]]] = [[VAL]];
+
+// CPP-DECLTOP: void load_store_array(float [[ARR1:[^ ]*]][4][8], float [[ARR2:[^ ]*]][3][5],
+// CPP-DECLTOP-SAME:            size_t [[I:[^ ]*]], size_t [[J:[^ ]*]])
+// CPP-DECLTOP-NEXT: float [[VAL:[^ ]*]];
+// CPP-DECLTOP-NEXT: [[VAL]] = [[ARR1]][[[I]]][[[J]]];
+// CPP-DECLTOP-NEXT: [[ARR2]][[[I]]][[[J]]] = [[VAL]];
 
 func.func @load_store_pointer(%arg0: !emitc.ptr<f32>, %arg1: !emitc.ptr<f32>, %arg2: index, %arg3: index) {
-  %0 = emitc.subscript %arg0[%arg2] : (!emitc.ptr<f32>, index) -> f32
-  %1 = emitc.subscript %arg1[%arg3] : (!emitc.ptr<f32>, index) -> f32
-  emitc.assign %0 : f32 to %1 : f32
+  %0 = emitc.subscript %arg0[%arg2] : (!emitc.ptr<f32>, index) -> !emitc.lvalue<f32>
+  %1 = emitc.subscript %arg1[%arg3] : (!emitc.ptr<f32>, index) -> !emitc.lvalue<f32>
+  %2 = emitc.lvalue_load %0 : <f32>
+  emitc.assign %2 : f32 to %1 : <f32>
   return
 }
-// CHECK: void load_store_pointer(float* [[PTR1:[^ ]*]], float* [[PTR2:[^ ]*]],
-// CHECK-SAME:            size_t [[I:[^ ]*]], size_t [[J:[^ ]*]])
-// CHECK-NEXT: [[PTR2]][[[J]]] = [[PTR1]][[[I]]];
+// CPP-DEFAULT: void load_store_pointer(float* [[PTR1:[^ ]*]], float* [[PTR2:[^ ]*]],
+// CPP-DEFAULT-SAME:            size_t [[I:[^ ]*]], size_t [[J:[^ ]*]])
+// CPP-DEFAULT-NEXT: float [[VAL:[^ ]*]] = [[PTR1]][[[I]]];
+// CPP-DEFAULT-NEXT: [[PTR2]][[[J]]] = [[VAL]];
+
+// CPP-DECLTOP: void load_store_pointer(float* [[PTR1:[^ ]*]], float* [[PTR2:[^ ]*]],
+// CPP-DECLTOP-SAME:            size_t [[I:[^ ]*]], size_t [[J:[^ ]*]])
+// CPP-DECLTOP-NEXT: float [[VAL:[^ ]*]];
+// CPP-DECLTOP-NEXT: [[VAL]] = [[PTR1]][[[I]]];
+// CPP-DECLTOP-NEXT: [[PTR2]][[[J]]] = [[VAL]];
 
 func.func @load_store_opaque(%arg0: !emitc.opaque<"std::map<char, int>">, %arg1: !emitc.opaque<"std::map<char, int>">, %arg2: !emitc.opaque<"char">, %arg3: !emitc.opaque<"char">) {
-  %0 = emitc.subscript %arg0[%arg2] : (!emitc.opaque<"std::map<char, int>">, !emitc.opaque<"char">) -> !emitc.opaque<"int">
-  %1 = emitc.subscript %arg1[%arg3] : (!emitc.opaque<"std::map<char, int>">, !emitc.opaque<"char">) -> !emitc.opaque<"int">
-  emitc.assign %0 : !emitc.opaque<"int"> to %1 : !emitc.opaque<"int">
+  %0 = emitc.subscript %arg0[%arg2] : (!emitc.opaque<"std::map<char, int>">, !emitc.opaque<"char">) -> !emitc.lvalue<!emitc.opaque<"int">>
+  %1 = emitc.subscript %arg1[%arg3] : (!emitc.opaque<"std::map<char, int>">, !emitc.opaque<"char">) -> !emitc.lvalue<!emitc.opaque<"int">>
+  %2 = emitc.lvalue_load %0 : <!emitc.opaque<"int">>
+  emitc.assign %2 : !emitc.opaque<"int"> to %1 : <!emitc.opaque<"int">>
   return
 }
-// CHECK: void load_store_opaque(std::map<char, int> [[MAP1:[^ ]*]], std::map<char, int> [[MAP2:[^ ]*]],
-// CHECK-SAME:            char [[I:[^ ]*]], char [[J:[^ ]*]])
-// CHECK-NEXT: [[MAP2]][[[J]]] = [[MAP1]][[[I]]];
+// CPP-DEFAULT: void load_store_opaque(std::map<char, int> [[MAP1:[^ ]*]], std::map<char, int> [[MAP2:[^ ]*]],
+// CPP-DEFAULT-SAME:            char [[I:[^ ]*]], char [[J:[^ ]*]])
+// CPP-DEFAULT-NEXT: int [[VAL:[^ ]*]] = [[MAP1]][[[I]]];
+// CPP-DEFAULT-NEXT: [[MAP2]][[[J]]] = [[VAL]];
+
+// CPP-DECLTOP: void load_store_opaque(std::map<char, int> [[MAP1:[^ ]*]], std::map<char, int> [[MAP2:[^ ]*]],
+// CPP-DECLTOP-SAME:            char [[I:[^ ]*]], char [[J:[^ ]*]])
+// CPP-DECLTOP-NEXT: int [[VAL:[^ ]*]];
+// CPP-DECLTOP-NEXT: [[VAL]] = [[MAP1]][[[I]]];
+// CPP-DECLTOP-NEXT: [[MAP2]][[[J]]] = [[VAL]];
 
 emitc.func @func1(%arg0 : f32) {
   emitc.return
@@ -37,16 +61,38 @@ emitc.func @func1(%arg0 : f32) {
 
 emitc.func @call_arg(%arg0: !emitc.array<4x8xf32>, %i: i32, %j: i16,
                      %k: i8) {
-  %0 = emitc.subscript %arg0[%i, %j] : (!emitc.array<4x8xf32>, i32, i16) -> f32
-  %1 = emitc.subscript %arg0[%j, %k] : (!emitc.array<4x8xf32>, i16, i8) -> f32
+  %0 = emitc.subscript %arg0[%i, %j] : (!emitc.array<4x8xf32>, i32, i16) -> !emitc.lvalue<f32>
+  %1 = emitc.subscript %arg0[%j, %k] : (!emitc.array<4x8xf32>, i16, i8) -> !emitc.lvalue<f32>
 
-  emitc.call @func1 (%0) : (f32) -> ()
-  emitc.call_opaque "func2" (%1) : (f32) -> ()
-  emitc.call_opaque "func3" (%0, %1) { args = [1 : index, 0 : index] } : (f32, f32) -> ()
+  %2 = emitc.lvalue_load %0 : <f32>
+  emitc.call @func1 (%2) : (f32) -> ()
+  %3 = emitc.lvalue_load %1 : <f32>
+  emitc.call_opaque "func2" (%3) : (f32) -> ()
+  %4 = emitc.lvalue_load %0 : <f32>
+  %5 = emitc.lvalue_load %1 : <f32>
+  emitc.call_opaque "func3" (%4, %5) { args = [1 : index, 0 : index] } : (f32, f32) -> ()
   emitc.return
 }
-// CHECK: void call_arg(float [[ARR1:[^ ]*]][4][8], int32_t [[I:[^ ]*]],
-// CHECK-SAME:          int16_t [[J:[^ ]*]], int8_t [[K:[^ ]*]])
-// CHECK-NEXT: func1([[ARR1]][[[I]]][[[J]]]);
-// CHECK-NEXT: func2([[ARR1]][[[J]]][[[K]]]);
-// CHECK-NEXT: func3([[ARR1]][[[J]]][[[K]]], [[ARR1]][[[I]]][[[J]]]);
+// CPP-DEFAULT: void call_arg(float [[ARR1:[^ ]*]][4][8], int32_t [[I:[^ ]*]],
+// CPP-DEFAULT-SAME:          int16_t [[J:[^ ]*]], int8_t [[K:[^ ]*]])
+// CPP-DEFAULT-NEXT: float [[VAL0:[^ ]*]] = [[ARR1]][[[I]]][[[J]]];
+// CPP-DEFAULT-NEXT: func1([[VAL0]]);
+// CPP-DEFAULT-NEXT: float [[VAL1:[^ ]*]] = [[ARR1]][[[J]]][[[K]]];
+// CPP-DEFAULT-NEXT: func2([[VAL1]]);
+// CPP-DEFAULT-NEXT: float [[VAL2:[^ ]*]] = [[ARR1]][[[I]]][[[J]]];
+// CPP-DEFAULT-NEXT: float [[VAL3:[^ ]*]] = [[ARR1]][[[J]]][[[K]]];
+// CPP-DEFAULT-NEXT: func3([[VAL3]], [[VAL2]]);
+
+// CPP-DECLTOP: void call_arg(float [[ARR1:[^ ]*]][4][8], int32_t [[I:[^ ]*]],
+// CPP-DECLTOP-SAME:          int16_t [[J:[^ ]*]], int8_t [[K:[^ ]*]])
+// CPP-DECLTOP-NEXT: float [[VAL0:[^ ]*]];
+// CPP-DECLTOP-NEXT: float [[VAL1:[^ ]*]];
+// CPP-DECLTOP-NEXT: float [[VAL2:[^ ]*]];
+// CPP-DECLTOP-NEXT: float [[VAL3:[^ ]*]];
+// CPP-DECLTOP-NEXT: [[VAL0]] = [[ARR1]][[[I]]][[[J]]];
+// CPP-DECLTOP-NEXT: func1([[VAL0]]);
+// CPP-DECLTOP-NEXT: [[VAL1]] = [[ARR1]][[[J]]][[[K]]];
+// CPP-DECLTOP-NEXT: func2([[VAL1]]);
+// CPP-DECLTOP-NEXT: [[VAL2]] = [[ARR1]][[[I]]][[[J]]];
+// CPP-DECLTOP-NEXT: [[VAL3]] = [[ARR1]][[[J]]][[[K]]];
+// CPP-DECLTOP-NEXT: func3([[VAL3]], [[VAL2]]);
diff --git a/mlir/test/Target/Cpp/variable.mlir b/mlir/test/Target/Cpp/variable.mlir
index 126dd384b47a2..a26d724127cf2 100644
--- a/mlir/test/Target/Cpp/variable.mlir
+++ b/mlir/test/Target/Cpp/variable.mlir
@@ -2,13 +2,13 @@
 // RUN: mlir-translate -mlir-to-cpp -declare-variables-at-top %s | FileCheck %s -check-prefix=CPP-DECLTOP
 
 func.func @emitc_variable() {
-  %c0 = "emitc.variable"(){value = #emitc.opaque<"">} : () -> i32
-  %c1 = "emitc.variable"(){value = 42 : i32} : () -> i32
-  %c2 = "emitc.variable"(){value = -1 : i32} : () -> i32
-  %c3 = "emitc.variable"(){value = -1 : si8} : () -> si8
-  %c4 = "emitc.variable"(){value = 255 : ui8} : () -> ui8
-  %c5 = "emitc.variable"(){value = #emitc.opaque<"">} : () -> !emitc.ptr<i32>
-  %c6 = "emitc.variable"(){value = #emitc.opaque<"NULL">} : () -> !emitc.ptr<i32>
+  %c0 = "emitc.variable"(){value = #emitc.opaque<"">} : () -> !emitc.lvalue<i32>
+  %c1 = "emitc.variable"(){value = 42 : i32} : () -> !emitc.lvalue<i32>
+  %c2 = "emitc.variable"(){value = -1 : i32} : () -> !emitc.lvalue<i32>
+  %c3 = "emitc.variable"(){value = -1 : si8} : () -> !emitc.lvalue<si8>
+  %c4 = "emitc.variable"(){value = 255 : ui8} : () -> !emitc.lvalue<ui8>
+  %c5 = "emitc.variable"(){value = #emitc.opaque<"">} : () -> !emitc.lvalue<!emitc.ptr<i32>>
+  %c6 = "emitc.variable"(){value = #emitc.opaque<"NULL">} : () -> !emitc.lvalue<!emitc.ptr<i32>>
   %c7 = "emitc.variable"(){value = #emitc.opaque<"">} : () -> !emitc.array<3x7xi32>
   %c8 = "emitc.variable"(){value = #emitc.opaque<"">} : () -> !emitc.array<5x!emitc.ptr<i8>>
   return
@@ -41,3 +41,5 @@ func.func @emitc_variable() {
 // CPP-DECLTOP-NEXT: [[V4]] = 255;
 // CPP-DECLTOP-NEXT: ;
 // CPP-DECLTOP-NEXT: [[V6]] = NULL;
+// CPP-DECLTOP-NEXT: ;
+// CPP-DECLTOP-NEXT: ;

>From a30c983e16cc9db5eba9ce896801112fd799a34e Mon Sep 17 00:00:00 2001
From: Simon Camphausen <simon.camphausen at iml.fraunhofer.de>
Date: Thu, 6 Jun 2024 07:46:53 +0000
Subject: [PATCH 2/2] Emit emitc.apply "*" in a deferred way to allow
 assignment through pointers.

---
 mlir/lib/Target/Cpp/TranslateToCpp.cpp | 122 +++++++++++++++----------
 mlir/test/Target/Cpp/common-cpp.mlir   |   3 +-
 2 files changed, 76 insertions(+), 49 deletions(-)

diff --git a/mlir/lib/Target/Cpp/TranslateToCpp.cpp b/mlir/lib/Target/Cpp/TranslateToCpp.cpp
index 66808289e79f7..7d9bd0df8d05d 100644
--- a/mlir/lib/Target/Cpp/TranslateToCpp.cpp
+++ b/mlir/lib/Target/Cpp/TranslateToCpp.cpp
@@ -174,6 +174,9 @@ struct CppEmitter {
   /// Emit an expression as a C expression.
   LogicalResult emitExpression(ExpressionOp expressionOp);
 
+  /// Insert the expression representing the operation into the value cache.
+  LogicalResult cacheDeferredOpResult(Operation *op);
+
   /// Return the existing or a new name for a Value.
   StringRef getOrCreateName(Value val);
 
@@ -273,6 +276,18 @@ struct CppEmitter {
 };
 } // namespace
 
+/// Determine whether expression \p op should be emitted in a deferred way.
+static bool hasDeferredEmission(Operation *op) {
+  if (isa_and_nonnull<emitc::GetGlobalOp, emitc::LiteralOp, emitc::SubscriptOp>(
+          op))
+    return true;
+
+  if (auto applyOp = dyn_cast_or_null<emitc::ApplyOp>(op))
+    return applyOp.getApplicableOperator() == "*";
+
+  return false;
+}
+
 /// Determine whether expression \p expressionOp should be emitted inline, i.e.
 /// as part of its user. This function recommends inlining of any expressions
 /// that can be inlined unless it is used by another expression, under the
@@ -295,10 +310,10 @@ static bool shouldBeInlined(ExpressionOp expressionOp) {
 
   Operation *user = *result.getUsers().begin();
 
-  // Do not inline expressions used by subscript operations, since the
-  // way the subscript operation translation is implemented requires that
-  // variables be materialized.
-  if (isa<emitc::SubscriptOp, emitc::GetGlobalOp>(user))
+  // Do not inline expressions used by operations with deferred emission, since
+  // the way their translation is implemented requires that variables be
+  // materialized.
+  if (hasDeferredEmission(user))
     return false;
 
   // Do not inline expressions used by ops with the CExpression trait. If this
@@ -370,13 +385,6 @@ static LogicalResult printOperation(CppEmitter &emitter,
   return emitter.emitOperand(assignOp.getValue());
 }
 
-static LogicalResult printOperation(CppEmitter &emitter,
-                                    emitc::GetGlobalOp op) {
-  // Add name to cache so that `hasValueInScope` works.
-  emitter.getOrCreateName(op.getResult());
-  return success();
-}
-
 static LogicalResult printOperation(CppEmitter &emitter,
                                     emitc::LValueLoadOp lValueLoadOp) {
   if (failed(emitter.emitAssignPrefix(*lValueLoadOp)))
@@ -385,13 +393,6 @@ static LogicalResult printOperation(CppEmitter &emitter,
   return emitter.emitOperand(lValueLoadOp.getOperand());
 }
 
-static LogicalResult printOperation(CppEmitter &emitter,
-                                    emitc::SubscriptOp subscriptOp) {
-  // Add name to cache so that `hasValueInScope` works.
-  emitter.getOrCreateName(subscriptOp.getResult());
-  return success();
-}
-
 static LogicalResult printBinaryOperation(CppEmitter &emitter,
                                           Operation *operation,
                                           StringRef binaryOperator) {
@@ -629,9 +630,7 @@ static LogicalResult printOperation(CppEmitter &emitter,
       if (t.getType().isIndex()) {
         int64_t idx = t.getInt();
         Value operand = op.getOperand(idx);
-        auto literalDef =
-            dyn_cast_if_present<LiteralOp>(operand.getDefiningOp());
-        if (!literalDef && !emitter.hasValueInScope(operand))
+        if (!emitter.hasValueInScope(operand))
           return op.emitOpError("operand ")
                  << idx << "'s value not defined in scope";
         os << emitter.getOrCreateName(operand);
@@ -668,6 +667,10 @@ static LogicalResult printOperation(CppEmitter &emitter,
                                     emitc::ApplyOp applyOp) {
   raw_ostream &os = emitter.ostream();
   Operation &op = *applyOp.getOperation();
+  StringRef applicableOp = applyOp.getApplicableOperator();
+
+  if (applicableOp == "*")
+    return emitter.cacheDeferredOpResult(applyOp);
 
   if (failed(emitter.emitAssignPrefix(op)))
     return failure();
@@ -956,8 +959,7 @@ static LogicalResult printFunctionBody(CppEmitter &emitter,
     // regions.
     WalkResult result =
         functionOp->walk<WalkOrder::PreOrder>([&](Operation *op) -> WalkResult {
-          if (isa<emitc::LiteralOp>(op) ||
-              isa<emitc::ExpressionOp>(op->getParentOp()) ||
+          if (isa<emitc::ExpressionOp>(op->getParentOp()) ||
               (isa<emitc::ExpressionOp>(op) &&
                shouldBeInlined(cast<emitc::ExpressionOp>(op))))
             return WalkResult::skip();
@@ -1009,7 +1011,8 @@ static LogicalResult printFunctionBody(CppEmitter &emitter,
       // trailing semicolon is handled within the printOperation function.
       bool trailingSemicolon =
           !isa<cf::CondBranchOp, emitc::DeclareFuncOp, emitc::ForOp,
-               emitc::IfOp, emitc::LiteralOp, emitc::VerbatimOp>(op);
+               emitc::IfOp, emitc::VerbatimOp>(op) ||
+          hasDeferredEmission(&op);
 
       if (failed(emitter.emitOperation(
               op, /*trailingSemicolon=*/trailingSemicolon)))
@@ -1142,20 +1145,48 @@ std::string CppEmitter::getSubscriptName(emitc::SubscriptOp op) {
   return out;
 }
 
+LogicalResult CppEmitter::cacheDeferredOpResult(Operation *op) {
+  if (op->getNumResults() != 1)
+    return op->emitError("Adding deferred ops into value cahce only works for "
+                         "single results operations, got ")
+           << op->getNumResults() << " results";
+
+  Value result = op->getResult(0);
+  if (valueMapper.count(result))
+    return success();
+
+  if (auto applyOp = dyn_cast<emitc::ApplyOp>(op)) {
+    assert(applyOp.getApplicableOperator() == "*" && "expected derefernce");
+    valueMapper.insert(result, std::string("*") +
+                                   getOrCreateName(applyOp.getOperand()).str());
+    return success();
+  }
+
+  if (auto getGlobal = dyn_cast<emitc::GetGlobalOp>(op)) {
+    valueMapper.insert(result, getGlobal.getName().str());
+    return success();
+  }
+
+  if (auto literal = dyn_cast<emitc::LiteralOp>(op)) {
+    valueMapper.insert(result, literal.getValue().str());
+    return success();
+  }
+
+  if (auto subscript = dyn_cast<emitc::SubscriptOp>(op)) {
+    valueMapper.insert(result, getSubscriptName(subscript));
+    return success();
+  }
+
+  return op->emitError("cacheDeferredOpResult not implemented");
+}
+
 /// Return the existing or a new name for a Value.
 StringRef CppEmitter::getOrCreateName(Value val) {
-  if (auto literal = dyn_cast_if_present<emitc::LiteralOp>(val.getDefiningOp()))
-    return literal.getValue();
   if (!valueMapper.count(val)) {
-    if (auto subscript =
-            dyn_cast_if_present<emitc::SubscriptOp>(val.getDefiningOp())) {
-      valueMapper.insert(val, getSubscriptName(subscript));
-    } else if (auto getGlobal = dyn_cast_if_present<emitc::GetGlobalOp>(
-                   val.getDefiningOp())) {
-      valueMapper.insert(val, getGlobal.getName().str());
-    } else {
-      valueMapper.insert(val, formatv("v{0}", ++valueInScopeCount.top()));
-    }
+    assert(!hasDeferredEmission(val.getDefiningOp()) &&
+           "cacheDeferredOpResult should have been called on this value, "
+           "update the emitOperation function.");
+    valueMapper.insert(val, formatv("v{0}", ++valueInScopeCount.top()));
   }
   return *valueMapper.begin(val);
 }
@@ -1349,9 +1380,6 @@ LogicalResult CppEmitter::emitOperand(Value value) {
   if (expressionOp && shouldBeInlined(expressionOp))
     return emitExpression(expressionOp);
 
-  auto literalOp = dyn_cast_if_present<LiteralOp>(value.getDefiningOp());
-  if (!literalOp && !hasValueInScope(value))
-    return failure();
   os << getOrCreateName(value);
   return success();
 }
@@ -1407,7 +1435,7 @@ LogicalResult CppEmitter::emitVariableAssignment(OpResult result) {
 
 LogicalResult CppEmitter::emitVariableDeclaration(OpResult result,
                                                   bool trailingSemicolon) {
-  if (isa<emitc::SubscriptOp, emitc::GetGlobalOp>(result.getDefiningOp()))
+  if (hasDeferredEmission(result.getDefiningOp()))
     return success();
   if (hasValueInScope(result)) {
     return result.getDefiningOp()->emitError(
@@ -1506,17 +1534,17 @@ LogicalResult CppEmitter::emitOperation(Operation &op, bool trailingSemicolon) {
                 emitc::CallOpaqueOp, emitc::CastOp, emitc::CmpOp,
                 emitc::ConditionalOp, emitc::ConstantOp, emitc::DeclareFuncOp,
                 emitc::DivOp, emitc::ExpressionOp, emitc::ForOp, emitc::FuncOp,
-                emitc::GlobalOp, emitc::GetGlobalOp, emitc::IfOp,
-                emitc::IncludeOp, emitc::LogicalAndOp, emitc::LogicalNotOp,
-                emitc::LogicalOrOp, emitc::LValueLoadOp, emitc::MulOp,
-                emitc::RemOp, emitc::ReturnOp, emitc::SubOp, emitc::SubscriptOp,
-                emitc::UnaryMinusOp, emitc::UnaryPlusOp, emitc::VariableOp,
-                emitc::VerbatimOp>(
+                emitc::GlobalOp, emitc::IfOp, emitc::IncludeOp,
+                emitc::LogicalAndOp, emitc::LogicalNotOp, emitc::LogicalOrOp,
+                emitc::LValueLoadOp, emitc::MulOp, emitc::RemOp,
+                emitc::ReturnOp, emitc::SubOp, emitc::UnaryMinusOp,
+                emitc::UnaryPlusOp, emitc::VariableOp, emitc::VerbatimOp>(
               [&](auto op) { return printOperation(*this, op); })
           // Func ops.
           .Case<func::CallOp, func::FuncOp, func::ReturnOp>(
               [&](auto op) { return printOperation(*this, op); })
-          .Case<emitc::LiteralOp>([&](auto op) { return success(); })
+          .Case<emitc::GetGlobalOp, emitc::LiteralOp, emitc::SubscriptOp>(
+              [&](Operation *op) { return cacheDeferredOpResult(op); })
           .Default([&](Operation *) {
             return op.emitOpError("unable to find printer for op");
           });
@@ -1524,7 +1552,7 @@ LogicalResult CppEmitter::emitOperation(Operation &op, bool trailingSemicolon) {
   if (failed(status))
     return failure();
 
-  if (isa<emitc::LiteralOp, emitc::SubscriptOp, emitc::GetGlobalOp>(op))
+  if (hasDeferredEmission(&op))
     return success();
 
   if (getEmittedExpression() ||
diff --git a/mlir/test/Target/Cpp/common-cpp.mlir b/mlir/test/Target/Cpp/common-cpp.mlir
index c1d12eec6d17b..f56e42f1024d3 100644
--- a/mlir/test/Target/Cpp/common-cpp.mlir
+++ b/mlir/test/Target/Cpp/common-cpp.mlir
@@ -91,9 +91,8 @@ func.func @apply(%arg0: !emitc.lvalue<i32>) -> !emitc.ptr<i32> {
   %2 = "emitc.variable"() {value = #emitc.opaque<"">} : () -> !emitc.lvalue<i32>
   // CHECK-NEXT: int32_t [[V4:[^ ]*]] = *[[V2]];
   %1 = emitc.apply "*"(%0) : (!emitc.ptr<i32>) -> !emitc.lvalue<i32>
-  // CHECK-NEXT: int32_t [[V5:[^ ]*]] = [[V4]];
   %3 = emitc.lvalue_load %1 : !emitc.lvalue<i32>
-  // CHECK-NEXT: [[V3]] = [[V5]];
+  // CHECK-NEXT: [[V3]] = [[V4]];
   emitc.assign %3 : i32 to %2 : !emitc.lvalue<i32>
   // CHECK-NEXT: return [[V2]];
   return %0 : !emitc.ptr<i32>



More information about the Mlir-commits mailing list