[clang] [CIR] Unify alignment representation (PR #249266)

Robert Konicar via cfe-commits cfe-commits at lists.llvm.org
Sat Dec 5 09:59:54 PST 2026


https://github.com/Jezurko created https://github.com/llvm/llvm-project/pull/249266

Introduce cir::AlignmentAttr as the single alignment attribute on CIR ops, replacing the various I64Attr forms. It unifies verification (the value must be a positive power of two) and access across ops via the setAlignment / getAlignmentValue helpers.

>From dbf0e5ca6fbbebff99c78c94bf0d27a8de860879 Mon Sep 17 00:00:00 2001
From: Robert Konicar <rkonicar at mail.muni.cz>
Date: Fri, 27 Nov 2026 17:15:20 +0100
Subject: [PATCH] [CIR] Unify alignment representation

Introduce cir::AlignmentAttr as the single alignment attribute on CIR
ops, replacing the various I64Attr forms. It unifies verification (the
value must be a positive power of two) and access across ops via the
setAlignment / getAlignmentValue helpers.

Co-Authored-By: Mistral Vibe <vibe at mistral.ai>
---
 .../CIR/Dialect/Builder/CIRBaseBuilder.h      |  22 ++--
 .../include/clang/CIR/Dialect/IR/CIRAttrs.td  |  35 +++++-
 clang/include/clang/CIR/Dialect/IR/CIROps.td  | 107 ++++++++++++------
 clang/lib/CIR/CodeGen/CIRGenAtomic.cpp        |  13 ++-
 clang/lib/CIR/CodeGen/CIRGenBuilder.h         |  33 +++---
 clang/lib/CIR/CodeGen/CIRGenBuiltin.cpp       |   7 +-
 clang/lib/CIR/CodeGen/CIRGenBuiltinNVPTX.cpp  |   6 +-
 clang/lib/CIR/CodeGen/CIRGenCUDANV.cpp        |  11 +-
 clang/lib/CIR/CodeGen/CIRGenDecl.cpp          |   2 +-
 clang/lib/CIR/CodeGen/CIRGenExpr.cpp          |  22 ++--
 clang/lib/CIR/CodeGen/CIRGenExprCXX.cpp       |   3 +-
 clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp    |   9 +-
 clang/lib/CIR/CodeGen/CIRGenFunction.h        |   4 +-
 clang/lib/CIR/CodeGen/CIRGenItaniumCXXABI.cpp |   2 +-
 clang/lib/CIR/CodeGen/CIRGenModule.cpp        |  22 ++--
 clang/lib/CIR/CodeGen/CIRGenOpenACCRecipe.cpp |  20 ++--
 clang/lib/CIR/CodeGen/CIRGenStmtOpenACC.cpp   |   6 +-
 clang/lib/CIR/Dialect/IR/CIRAttrs.cpp         |  12 ++
 clang/lib/CIR/Dialect/IR/CIRDialect.cpp       |  19 ++--
 .../CIR/Dialect/Transforms/EHABILowering.cpp  |   6 +-
 .../lib/CIR/Dialect/Transforms/FlattenCFG.cpp |   8 +-
 .../Dialect/Transforms/LoweringPrepare.cpp    |  25 ++--
 .../TargetLowering/CIRABIRewriteContext.cpp   |  91 ++++++++-------
 .../TargetLowering/LowerItaniumCXXABI.cpp     |   6 +-
 .../CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp |  88 ++++++++------
 clang/test/CIR/IR/func.cir                    |  12 +-
 clang/test/CIR/IR/invalid-alignment.cir       |  23 ++++
 clang/unittests/CIR/PointerLikeTest.cpp       |   4 +-
 28 files changed, 393 insertions(+), 225 deletions(-)
 create mode 100644 clang/test/CIR/IR/invalid-alignment.cir

diff --git a/clang/include/clang/CIR/Dialect/Builder/CIRBaseBuilder.h b/clang/include/clang/CIR/Dialect/Builder/CIRBaseBuilder.h
index 0d831af4eb54ec..eac1396bef29fd 100644
--- a/clang/include/clang/CIR/Dialect/Builder/CIRBaseBuilder.h
+++ b/clang/include/clang/CIR/Dialect/Builder/CIRBaseBuilder.h
@@ -378,7 +378,7 @@ class CIRBaseBuilderTy : public mlir::OpBuilder {
   cir::LoadOp createLoad(mlir::Location loc, mlir::Value ptr,
                          bool isVolatile = false, uint64_t alignment = 0,
                          bool isNontemporal = false) {
-    mlir::IntegerAttr alignmentAttr = getAlignmentAttr(alignment);
+    cir::AlignmentAttr alignmentAttr = getAlignmentAttr(alignment);
     return cir::LoadOp::create(*this, loc, ptr, /*isDeref=*/false, isVolatile,
                                isNontemporal, alignmentAttr,
                                cir::SyncScopeKindAttr{}, cir::MemOrderAttr{},
@@ -479,7 +479,7 @@ class CIRBaseBuilderTy : public mlir::OpBuilder {
   }
 
   mlir::Value createAlloca(mlir::Location loc, cir::PointerType addrType,
-                           llvm::StringRef name, mlir::IntegerAttr alignment,
+                           llvm::StringRef name, cir::AlignmentAttr alignment,
                            mlir::Value dynAllocSize) {
     return cir::AllocaOp::create(*this, loc, addrType, name, alignment,
                                  dynAllocSize);
@@ -489,18 +489,18 @@ class CIRBaseBuilderTy : public mlir::OpBuilder {
                            mlir::Type type, llvm::StringRef name,
                            clang::CharUnits alignment,
                            mlir::Value dynAllocSize) {
-    mlir::IntegerAttr alignmentAttr = getAlignmentAttr(alignment);
+    cir::AlignmentAttr alignmentAttr = getAlignmentAttr(alignment);
     return createAlloca(loc, addrType, name, alignmentAttr, dynAllocSize);
   }
 
   mlir::Value createAlloca(mlir::Location loc, cir::PointerType addrType,
-                           llvm::StringRef name, mlir::IntegerAttr alignment) {
+                           llvm::StringRef name, cir::AlignmentAttr alignment) {
     return cir::AllocaOp::create(*this, loc, addrType, name, alignment);
   }
 
   mlir::Value createAlloca(mlir::Location loc, cir::PointerType addrType,
                            llvm::StringRef name, clang::CharUnits alignment) {
-    mlir::IntegerAttr alignmentAttr = getAlignmentAttr(alignment);
+    cir::AlignmentAttr alignmentAttr = getAlignmentAttr(alignment);
     return createAlloca(loc, addrType, name, alignmentAttr);
   }
 
@@ -558,7 +558,7 @@ class CIRBaseBuilderTy : public mlir::OpBuilder {
 
   cir::StoreOp createStore(mlir::Location loc, mlir::Value val, mlir::Value dst,
                            bool isVolatile = false, bool isNontemporal = false,
-                           mlir::IntegerAttr align = {},
+                           cir::AlignmentAttr align = {},
                            cir::SyncScopeKindAttr scope = {},
                            cir::MemOrderAttr order = {},
                            cir::TBAATagAttr tbaa = {}) {
@@ -601,7 +601,7 @@ class CIRBaseBuilderTy : public mlir::OpBuilder {
 
   mlir::Value createDummyValue(mlir::Location loc, mlir::Type type,
                                clang::CharUnits alignment) {
-    mlir::IntegerAttr alignmentAttr = getAlignmentAttr(alignment);
+    cir::AlignmentAttr alignmentAttr = getAlignmentAttr(alignment);
     auto addr = createAlloca(loc, getPointerTo(type), {}, alignmentAttr);
     return cir::LoadOp::create(*this, loc, addr, /*isDeref=*/false,
                                /*isVolatile=*/false, /*nontemporal=*/false,
@@ -1128,16 +1128,16 @@ class CIRBaseBuilderTy : public mlir::OpBuilder {
 
   // For 0 alignment, any overload of `getAlignmentAttr` returns an empty
   // attribute.
-  mlir::IntegerAttr getAlignmentAttr(clang::CharUnits alignment) {
+  cir::AlignmentAttr getAlignmentAttr(clang::CharUnits alignment) {
     return getAlignmentAttr(alignment.getQuantity());
   }
 
-  mlir::IntegerAttr getAlignmentAttr(llvm::Align alignment) {
+  cir::AlignmentAttr getAlignmentAttr(llvm::Align alignment) {
     return getAlignmentAttr(alignment.value());
   }
 
-  mlir::IntegerAttr getAlignmentAttr(int64_t alignment) {
-    return alignment ? getI64IntegerAttr(alignment) : mlir::IntegerAttr();
+  cir::AlignmentAttr getAlignmentAttr(int64_t alignment) {
+    return cir::AlignmentAttr::getOrEmpty(this->getContext(), alignment);
   }
 
   // Materialize an alignment value as a CIR integer constant of the given
diff --git a/clang/include/clang/CIR/Dialect/IR/CIRAttrs.td b/clang/include/clang/CIR/Dialect/IR/CIRAttrs.td
index 3ce42fb32f1a8f..7fd87fa869bccf 100644
--- a/clang/include/clang/CIR/Dialect/IR/CIRAttrs.td
+++ b/clang/include/clang/CIR/Dialect/IR/CIRAttrs.td
@@ -1535,7 +1535,7 @@ def CIR_TargetAddressSpaceAttr : CIR_Attr< "TargetAddressSpace",
     The TargetAddressSpaceAttr represents a target-specific numeric address space,
     corresponding to the LLVM IR `addrspace` qualifier and the clang
      `address_space` attribute.
-    
+
     A value of zero represents the default address space. The semantics of non-zero
     address spaces are target-specific.
 
@@ -2991,4 +2991,37 @@ def CIR_CXXModuleInitAttr : CIR_Attr<"CXXModuleInit", "cxx_module_init"> {
   let canHaveIllegalCXXABIType = 0;
 }
 
+//===----------------------------------------------------------------------===//
+// AlignmentAttr
+//===----------------------------------------------------------------------===//
+
+def CIR_AlignmentAttr : CIR_Attr<"Alignment", "alignment"> {
+  let summary = "Memory alignment in bytes";
+  let description = [{
+    Represents the alignment, in bytes, of memory accesses, allocations and
+    globals. The value must be a positive power of 2; the verifier rejects
+    anything else, including zero. "Alignment unspecified" should be represented
+    by the absence of the attribute.
+
+    ```
+    #cir<alignment 16>
+    ```
+  }];
+
+  let parameters = (ins "uint64_t":$align);
+  let assemblyFormat = "$align";
+  let canHaveIllegalCXXABIType = 0;
+
+  let genVerifyDecl = 1;
+
+  let extraClassDeclaration = [{
+    /// Returns an AlignmentAttr for `align`, or an empty (null) attribute when
+    /// `align` is 0.
+    static AlignmentAttr getOrEmpty(mlir::MLIRContext *ctx,
+                                    uint64_t align) {
+      return align ? AlignmentAttr::get(ctx, align) : AlignmentAttr();
+    }
+  }];
+}
+
 #endif // CLANG_CIR_DIALECT_IR_CIRATTRS_TD
diff --git a/clang/include/clang/CIR/Dialect/IR/CIROps.td b/clang/include/clang/CIR/Dialect/IR/CIROps.td
index 20d1f61eb347f2..e714823b38bbcc 100644
--- a/clang/include/clang/CIR/Dialect/IR/CIROps.td
+++ b/clang/include/clang/CIR/Dialect/IR/CIROps.td
@@ -253,6 +253,21 @@ defvar CIR_VolatileOrAtomicAccessDecl = [{
   }
 }];
 
+// Declares alignment helpers on ops with a CIR_AlignmentAttr.
+defvar CIR_AlignmentDecls = [{
+  /// Set the alignment attribute from a plain integer.
+  void setAlignment(uint64_t align) {
+    getProperties().alignment =
+        cir::AlignmentAttr::getOrEmpty(this->getContext(), align);
+  }
+
+  /// Returns the alignment integer value or 0 if the attribute is not set.
+  uint64_t getAlignmentValue() {
+    auto attr = getProperties().alignment;
+    return attr ? attr.getAlign() : 0;
+  }
+}];
+
 //===----------------------------------------------------------------------===//
 // CastOp
 //===----------------------------------------------------------------------===//
@@ -858,7 +873,7 @@ def CIR_AllocaOp : CIR_Op<"alloca", [
     UnitAttr:$constant,
     UnitAttr:$cleanup_dest_slot,
     UnitAttr:$return_slot,
-    ConfinedAttr<I64Attr, [IntMinValue<1>]>:$alignment
+    CIR_AlignmentAttr:$alignment
   );
 
   let results = (outs Res<CIR_PointerType, "",
@@ -868,11 +883,11 @@ def CIR_AllocaOp : CIR_Op<"alloca", [
   let builders = [
     OpBuilder<(ins "mlir::Type":$addr,
                    "llvm::StringRef":$name,
-                   "mlir::IntegerAttr":$alignment)>,
+                   "cir::AlignmentAttr":$alignment)>,
 
     OpBuilder<(ins "mlir::Type":$addr,
                    "llvm::StringRef":$name,
-                   "mlir::IntegerAttr":$alignment,
+                   "cir::AlignmentAttr":$alignment,
                    "mlir::Value":$dynAllocSize),
     [{
       if (dynAllocSize)
@@ -881,7 +896,7 @@ def CIR_AllocaOp : CIR_Op<"alloca", [
     }]>
   ];
 
-  let extraClassDeclaration = [{
+  let extraClassDeclaration = CIR_AlignmentDecls # [{
     mlir::Type getAllocaType() {
       return mlir::cast<cir::PointerType>(getAddr().getType()).getPointee();
     }
@@ -957,7 +972,7 @@ def CIR_LoadOp : CIR_Op<"load", [
                        UnitAttr:$isDeref,
                        UnitAttr:$is_volatile,
                        UnitAttr:$is_nontemporal,
-                       OptionalAttr<I64Attr>:$alignment,
+                       OptionalAttr<CIR_AlignmentAttr>:$alignment,
                        OptionalAttr<CIR_SyncScopeKindAttr>:$sync_scope,
                        OptionalAttr<CIR_MemOrderAttr>:$mem_order,
                        UnitAttr:$invariant,
@@ -980,18 +995,18 @@ def CIR_LoadOp : CIR_Op<"load", [
     OpBuilder<(ins "mlir::Value":$addr), [{
       build($_builder, $_state, addr, /*isDeref=*/false,
             /*is_volatile=*/false, /*is_nontemporal=*/false,
-            /*alignment=*/mlir::IntegerAttr{}, cir::SyncScopeKindAttr{},
+            /*alignment=*/cir::AlignmentAttr{}, cir::SyncScopeKindAttr{},
             cir::MemOrderAttr{}, /*invariant=*/false, /*tbaa=*/{});
     }]>,
     OpBuilder<(ins "mlir::Type":$result, "mlir::Value":$addr), [{
       build($_builder, $_state, result, addr, /*isDeref=*/false,
             /*is_volatile=*/false, /*is_nontemporal=*/false,
-            /*alignment=*/mlir::IntegerAttr{}, cir::SyncScopeKindAttr{},
+            /*alignment=*/cir::AlignmentAttr{}, cir::SyncScopeKindAttr{},
             cir::MemOrderAttr{}, /*invariant=*/false, /*tbaa=*/{});
     }]>
   ];
 
-  let extraClassDeclaration = CIR_VolatileOrAtomicAccessDecl;
+  let extraClassDeclaration = !strconcat(CIR_VolatileOrAtomicAccessDecl, CIR_AlignmentDecls);
   let customLLVMLoweringConstructorDecl =
     LoweringBuilders<(ins "LLVMTBAALowering &":$tbaaLowering)>;
 
@@ -1029,7 +1044,7 @@ def CIR_VecMaskedLoadOp : CIR_Op<"vec.masked_load", [
     Arg<CIR_PointerType, "base address (points to element type)", [MemRead]>:$addr,
     CIR_VectorType:$mask,
     CIR_VectorType:$pass_thru,
-    OptionalAttr<IntValidAlignment<I64Attr>>:$alignment
+    OptionalAttr<CIR_AlignmentAttr>:$alignment
   );
 
   let results = (outs CIR_AnyType:$result);
@@ -1084,7 +1099,7 @@ def CIR_StoreOp : CIR_Op<"store", [
                            [MemWrite]>:$addr,
                        UnitAttr:$is_volatile,
                        UnitAttr:$is_nontemporal,
-                       OptionalAttr<I64Attr>:$alignment,
+                       OptionalAttr<CIR_AlignmentAttr>:$alignment,
                        OptionalAttr<CIR_SyncScopeKindAttr>:$sync_scope,
                        OptionalAttr<CIR_MemOrderAttr>:$mem_order,
                        OptionalAttr<CIR_TBAATagAttr>:$tbaa);
@@ -1104,13 +1119,13 @@ def CIR_StoreOp : CIR_Op<"store", [
     OpBuilder<(ins "mlir::Value":$value, "mlir::Value":$addr), [{
       build($_builder, $_state, value, addr, /*is_volatile=*/mlir::UnitAttr(),
             /*is_nontemporal=*/mlir::UnitAttr(),
-            /*alignment=*/mlir::IntegerAttr(),
+            /*alignment=*/cir::AlignmentAttr(),
             /*sync_scope=*/cir::SyncScopeKindAttr(),
             /*mem_order=*/cir::MemOrderAttr(), /*tbaa=*/cir::TBAATagAttr());
     }]>
   ];
 
-  let extraClassDeclaration = CIR_VolatileOrAtomicAccessDecl;
+  let extraClassDeclaration = !strconcat(CIR_VolatileOrAtomicAccessDecl, CIR_AlignmentDecls);
   let customLLVMLoweringConstructorDecl =
     LoweringBuilders<(ins "LLVMTBAALowering &":$tbaaLowering)>;
 
@@ -3749,7 +3764,7 @@ def CIR_GlobalOp : CIR_RegionBranchOpBase<"global", [
                        UnitProp:$dso_local,
                        UnitAttr:$unnamed_addr,
                        OptionalAttr<CIR_DynamicInitGuardAttr>:$dynamic_init_guard,
-                       OptionalAttr<I64Attr>:$alignment,
+                       OptionalAttr<CIR_AlignmentAttr>:$alignment,
                        OptionalAttr<ASTVarDeclInterface>:$ast,
                        OptionalAttr<CIR_DynamicInitInfoAttr>:$dynamic_init_info,
                        OptionalAttr<StrAttr>:$section,
@@ -3790,7 +3805,7 @@ def CIR_GlobalOp : CIR_RegionBranchOpBase<"global", [
     attr-dict
   }];
 
-  let extraClassDeclaration = [{
+  let extraClassDeclaration = CIR_AlignmentDecls # [{
     bool isDeclaration() {
       // Aliases are always definitions.
       if (getAliasee())
@@ -4305,7 +4320,7 @@ def CIR_SetBitfieldOp : CIR_Op<"set_bitfield"> {
     Arg<CIR_PointerType, "the address to store the value", [MemWrite]>:$addr,
     CIR_AnyType:$src,
     CIR_BitfieldInfoAttr:$bitfield_info,
-    DefaultValuedOptionalAttr<I64Attr, "0">:$alignment,
+    OptionalAttr<CIR_AlignmentAttr>:$alignment,
     UnitAttr:$is_volatile
   );
 
@@ -4334,9 +4349,13 @@ def CIR_SetBitfieldOp : CIR_Op<"set_bitfield"> {
         BitfieldInfoAttr::get($_builder.getContext(),
                               name, storage_type,
                               size, offset, is_signed);
-      build($_builder, $_state, type, addr, src, info, alignment, is_volatile);
+      cir::AlignmentAttr alignAttr =
+          cir::AlignmentAttr::getOrEmpty($_builder.getContext(), alignment);
+      build($_builder, $_state, type, addr, src, info, alignAttr, is_volatile);
     }]>
   ];
+
+  let extraClassDeclaration = CIR_AlignmentDecls;
 }
 
 //===----------------------------------------------------------------------===//
@@ -4396,7 +4415,7 @@ def CIR_GetBitfieldOp : CIR_Op<"get_bitfield", [
   let arguments = (ins
     Arg<CIR_PointerType, "the address to load from">:$addr,
     CIR_BitfieldInfoAttr:$bitfield_info,
-    DefaultValuedOptionalAttr<I64Attr, "0">:$alignment,
+    OptionalAttr<CIR_AlignmentAttr>:$alignment,
     UnitAttr:$is_volatile
     );
 
@@ -4424,9 +4443,13 @@ def CIR_GetBitfieldOp : CIR_Op<"get_bitfield", [
         BitfieldInfoAttr::get($_builder.getContext(),
                               name, storage_type,
                               size, offset, is_signed);
-      build($_builder, $_state, type, addr, info, alignment, is_volatile);
+      cir::AlignmentAttr alignAttr =
+          cir::AlignmentAttr::getOrEmpty($_builder.getContext(), alignment);
+      build($_builder, $_state, type, addr, info, alignAttr, is_volatile);
     }]>
   ];
+
+  let extraClassDeclaration = CIR_AlignmentDecls;
 }
 
 //===----------------------------------------------------------------------===//
@@ -4822,8 +4845,8 @@ def CIR_FuncOp : CIR_Op<"func", [
     >:$calling_conv,
     OptionalAttr<StrAttr>:$sym_visibility,
     OptionalAttr<StrAttr>:$comdat,
-    OptionalAttr<I64Attr>:$alignment,
-    OptionalAttr<I64Attr>:$preferred_alignment,
+    OptionalAttr<CIR_AlignmentAttr>:$alignment,
+    OptionalAttr<CIR_AlignmentAttr>:$preferred_alignment,
     OptionalAttr<DictArrayAttr>:$arg_attrs,
     OptionalAttr<DictArrayAttr>:$res_attrs,
     OptionalAttr<FlatSymbolRefAttr>:$aliasee,
@@ -4847,7 +4870,7 @@ def CIR_FuncOp : CIR_Op<"func", [
     CArg<"cir::CallingConv", "cir::CallingConv::C">:$callingConv)
   >];
 
-  let extraClassDeclaration = [{
+  let extraClassDeclaration = CIR_AlignmentDecls # [{
     /// Returns the region on the current operation that is callable. This may
     /// return null in the case of an external callable object, e.g. an external
     /// function.
@@ -4900,7 +4923,7 @@ def CIR_FuncOp : CIR_Op<"func", [
     /// trivial default constructor, copy/move constructor, copy/move assignment,
     /// or destructor.
     bool isCxxTrivialMemberFunction();
-}];
+  }];
 
   let hasCustomAssemblyFormat = 1;
   let hasVerifier = 1;
@@ -5958,8 +5981,8 @@ def CIR_CopyOp : CIR_Op<"copy",[
   let arguments = (ins
       Arg<CIR_PointerType, "", [MemWrite]>:$dst,
       Arg<CIR_PointerType, "", [MemRead]>:$src,
-      OptionalAttr<I64Attr>:$dst_alignment,
-      OptionalAttr<I64Attr>:$src_alignment,
+      OptionalAttr<CIR_AlignmentAttr>:$dst_alignment,
+      OptionalAttr<CIR_AlignmentAttr>:$src_alignment,
       UnitAttr:$is_volatile,
       UnitAttr:$skip_tail_padding,
       OptionalAttr<CIR_TBAAStructFieldArrayAttr>:$tbaa_struct
@@ -5977,8 +6000,8 @@ def CIR_CopyOp : CIR_Op<"copy",[
 
   let builders = [
     OpBuilder<(ins "mlir::Value":$dst, "mlir::Value":$src,
-                   "mlir::IntegerAttr":$dst_alignment,
-                   "mlir::IntegerAttr":$src_alignment,
+                   "cir::AlignmentAttr":$dst_alignment,
+                   "cir::AlignmentAttr":$src_alignment,
                    CArg<"bool", "false">:$is_volatile,
                    CArg<"bool", "false">:$skip_tail_padding), [{
       build($_builder, $_state, dst, src, dst_alignment, src_alignment,
@@ -6044,8 +6067,8 @@ def CIR_MemCpyOp : CIR_MemOp<"libc.memcpy"> {
 
   let arguments = !con(commonArgs, (ins
     CIR_AnyFundamentalUIntType:$len,
-    OptionalAttr<I64Attr>:$dst_alignment,
-    OptionalAttr<I64Attr>:$src_alignment
+    OptionalAttr<CIR_AlignmentAttr>:$dst_alignment,
+    OptionalAttr<CIR_AlignmentAttr>:$src_alignment
   ));
 
   let assemblyFormat = [{
@@ -6079,8 +6102,8 @@ def CIR_MemMoveOp : CIR_MemOp<"libc.memmove"> {
 
   let arguments = !con(commonArgs, (ins
     CIR_AnyFundamentalUIntType:$len,
-    OptionalAttr<I64Attr>:$dst_alignment,
-    OptionalAttr<I64Attr>:$src_alignment
+    OptionalAttr<CIR_AlignmentAttr>:$dst_alignment,
+    OptionalAttr<CIR_AlignmentAttr>:$src_alignment
   ));
 
   let assemblyFormat = [{
@@ -6118,7 +6141,7 @@ def CIR_MemSetOp : CIR_Op<"libc.memset"> {
 
   let arguments = (ins
     Arg<CIR_VoidPtrType, "", [MemWrite]>:$dst,
-    OptionalAttr<I64Attr>:$alignment,
+    OptionalAttr<CIR_AlignmentAttr>:$alignment,
     CIR_UInt8:$val,
     CIR_AnyFundamentalUIntType:$len
   );
@@ -10775,7 +10798,7 @@ def CIR_AtomicFetchOp : CIR_Op<"atomic.fetch", [
     CIR_AtomicFetchKindAttr:$binop,
     Arg<CIR_MemOrderAttr, "memory order">:$mem_order,
     Arg<CIR_SyncScopeKindAttr, "synchronization scope">:$sync_scope,
-    OptionalAttr<I64Attr>:$alignment,
+    OptionalAttr<CIR_AlignmentAttr>:$alignment,
     UnitAttr:$is_volatile,
     UnitAttr:$fetch_first
   );
@@ -10803,6 +10826,8 @@ def CIR_AtomicFetchOp : CIR_Op<"atomic.fetch", [
                                   mlir::Value rmwVal, bool isInt,
                                   bool isSigned) const;
   }];
+
+  let extraClassDeclaration = CIR_AlignmentDecls;
 }
 
 def CIR_AtomicXchgOp : CIR_Op<"atomic.xchg", [
@@ -10833,7 +10858,7 @@ def CIR_AtomicXchgOp : CIR_Op<"atomic.xchg", [
     CIR_AnyType:$val,
     Arg<CIR_MemOrderAttr, "memory order">:$mem_order,
     CIR_SyncScopeKindAttr:$sync_scope,
-    OptionalAttr<I64Attr>:$alignment,
+    OptionalAttr<CIR_AlignmentAttr>:$alignment,
     UnitAttr:$is_volatile
   );
 
@@ -10900,7 +10925,7 @@ def CIR_AtomicCmpXchgOp : CIR_Op<"atomic.cmpxchg", [
                        Arg<CIR_MemOrderAttr, "success memory order">:$succ_order,
                        Arg<CIR_MemOrderAttr, "failure memory order">:$fail_order,
                        CIR_SyncScopeKindAttr:$sync_scope,
-                       OptionalAttr<I64Attr>:$alignment,
+                       OptionalAttr<CIR_AlignmentAttr>:$alignment,
                        UnitAttr:$weak,
                        UnitAttr:$is_volatile);
 
@@ -10913,6 +10938,8 @@ def CIR_AtomicCmpXchgOp : CIR_Op<"atomic.cmpxchg", [
     (`volatile` $is_volatile^)?
     `:` functional-type(operands, results) attr-dict
   }];
+
+  let extraClassDeclaration = CIR_AlignmentDecls;
 }
 
 def CIR_AtomicTestAndSetOp : CIR_Op<"atomic.test_and_set"> {
@@ -10935,7 +10962,7 @@ def CIR_AtomicTestAndSetOp : CIR_Op<"atomic.test_and_set"> {
   let arguments = (ins
     Arg<CIR_PtrToType<CIR_SInt8>, "", [MemRead, MemWrite]>:$ptr,
     Arg<CIR_MemOrderAttr, "memory order">:$mem_order,
-    OptionalAttr<I64Attr>:$alignment,
+    OptionalAttr<CIR_AlignmentAttr>:$alignment,
     UnitAttr:$is_volatile
   );
 
@@ -10947,6 +10974,8 @@ def CIR_AtomicTestAndSetOp : CIR_Op<"atomic.test_and_set"> {
     (`volatile` $is_volatile^)?
     `:` qualified(type($ptr)) `->` qualified(type($result)) attr-dict
   }];
+
+  let extraClassDeclaration = CIR_AlignmentDecls;
 }
 
 def CIR_AtomicClearOp : CIR_Op<"atomic.clear"> {
@@ -10967,7 +10996,7 @@ def CIR_AtomicClearOp : CIR_Op<"atomic.clear"> {
   let arguments = (ins
     Arg<CIR_PtrToType<CIR_SInt8>, "", [MemRead, MemWrite]>:$ptr,
     Arg<CIR_MemOrderAttr, "memory order">:$mem_order,
-    OptionalAttr<I64Attr>:$alignment,
+    OptionalAttr<CIR_AlignmentAttr>:$alignment,
     UnitAttr:$is_volatile
   );
 
@@ -10977,6 +11006,8 @@ def CIR_AtomicClearOp : CIR_Op<"atomic.clear"> {
     (`volatile` $is_volatile^)?
     `:` qualified(type($ptr)) attr-dict
   }];
+
+  let extraClassDeclaration = CIR_AlignmentDecls;
 }
 
 def CIR_AtomicFenceOp : CIR_Op<"atomic.fence"> {
@@ -11231,7 +11262,7 @@ def CIR_ClearPaddingOp : CIR_Op<"clear_padding", []> {
 
   let arguments = (ins
       Arg<CIR_PointerType, "", [MemWrite]> : $arg,
-      ConfinedAttr<I64Attr, [IntMinValue<1>]>:$alignment,
+      CIR_AlignmentAttr:$alignment,
       CIR_TypedArrayAttrBase<CIR_OffsetPairAttr,
                              "array of padding locations">:$padding
       );
@@ -11240,6 +11271,8 @@ def CIR_ClearPaddingOp : CIR_Op<"clear_padding", []> {
     `(` `align` `(` $alignment `)` $arg `,`
         $padding `)` `:` type($arg) `->` `(` `)` attr-dict
   }];
+
+  let extraClassDeclaration = CIR_AlignmentDecls;
 }
 
 include "clang/CIR/Dialect/IR/CIRStdOps.td"
diff --git a/clang/lib/CIR/CodeGen/CIRGenAtomic.cpp b/clang/lib/CIR/CodeGen/CIRGenAtomic.cpp
index ee623523eb94b4..552f4806a2682d 100644
--- a/clang/lib/CIR/CodeGen/CIRGenAtomic.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenAtomic.cpp
@@ -542,7 +542,8 @@ static void emitAtomicCmpXchg(CIRGenFunction &cgf, AtomicExpr *e, bool isWeak,
       cir::MemOrderAttr::get(&cgf.getMLIRContext(), successOrder),
       cir::MemOrderAttr::get(&cgf.getMLIRContext(), failureOrder),
       cir::SyncScopeKindAttr::get(&cgf.getMLIRContext(), scope),
-      builder.getI64IntegerAttr(ptr.getAlignment().getAsAlign().value()));
+      cir::AlignmentAttr::getOrEmpty(&cgf.getMLIRContext(),
+                                   ptr.getAlignment().getAsAlign().value()));
 
   cmpxchg.setIsVolatile(e->isVolatile());
   cmpxchg.setWeak(isWeak);
@@ -789,8 +790,8 @@ static void emitAtomicOp(CIRGenFunction &cgf, AtomicExpr *expr, Address dest,
     assert(!cir::MissingFeatures::atomicSyncScopeID());
 
     builder.createStore(loc, loadVal1, ptr, expr->isVolatile(),
-                        /*isNontemporal=*/false,
-                        /*align=*/mlir::IntegerAttr{}, scopeAttr, orderAttr);
+                        /*isNontemporal=*/false, cir::AlignmentAttr{},
+                        scopeAttr, orderAttr);
     return;
   }
 
@@ -929,7 +930,8 @@ static void emitAtomicOp(CIRGenFunction &cgf, AtomicExpr *expr, Address dest,
   case AtomicExpr::AO__atomic_test_and_set: {
     auto op = cir::AtomicTestAndSetOp::create(
         builder, loc, ptr.getPointer(), order,
-        builder.getI64IntegerAttr(ptr.getAlignment().getQuantity()),
+        cir::AlignmentAttr::getOrEmpty(builder.getContext(),
+                                     ptr.getAlignment().getQuantity()),
         expr->isVolatile());
     builder.createStore(loc, op, dest);
     return;
@@ -938,7 +940,8 @@ static void emitAtomicOp(CIRGenFunction &cgf, AtomicExpr *expr, Address dest,
   case AtomicExpr::AO__atomic_clear: {
     cir::AtomicClearOp::create(
         builder, loc, ptr.getPointer(), order,
-        builder.getI64IntegerAttr(ptr.getAlignment().getQuantity()),
+        cir::AlignmentAttr::getOrEmpty(builder.getContext(),
+                                     ptr.getAlignment().getQuantity()),
         expr->isVolatile());
     return;
   }
diff --git a/clang/lib/CIR/CodeGen/CIRGenBuilder.h b/clang/lib/CIR/CodeGen/CIRGenBuilder.h
index 0a6f790610ba94..b1c514c256f04a 100644
--- a/clang/lib/CIR/CodeGen/CIRGenBuilder.h
+++ b/clang/lib/CIR/CodeGen/CIRGenBuilder.h
@@ -190,25 +190,26 @@ class CIRGenBuilderTy : public cir::CIRBaseBuilderTy {
                          bool skipTailPadding = false) {
     cir::CopyOp op = createCopy(dst.getPointer(), src.getPointer(), isVolatile,
                                 skipTailPadding);
-    op.setDstAlignment(dst.getAlignment().getQuantity());
-    op.setSrcAlignment(src.getAlignment().getQuantity());
+    op.setDstAlignmentAttr(cir::AlignmentAttr::getOrEmpty(
+        op->getContext(), dst.getAlignment().getQuantity()));
+    op.setSrcAlignmentAttr(cir::AlignmentAttr::getOrEmpty(
+        op->getContext(), src.getAlignment().getQuantity()));
     return op;
   }
 
   cir::MemCpyOp createMemCpy(mlir::Location loc, Address dst, Address src,
                              mlir::Value len) {
-    return cir::MemCpyOp::create(
-        *this, loc, dst.getPointer(), src.getPointer(), len,
-        getI64IntegerAttr(dst.getAlignment().getQuantity()),
-        getI64IntegerAttr(src.getAlignment().getQuantity()));
+    return cir::MemCpyOp::create(*this, loc, dst.getPointer(), src.getPointer(),
+                                 len, getAlignmentAttr(dst.getAlignment()),
+                                 getAlignmentAttr(src.getAlignment()));
   }
 
   cir::MemMoveOp createMemMove(mlir::Location loc, Address dst, Address src,
                                mlir::Value len) {
-    return cir::MemMoveOp::create(
-        *this, loc, dst.getPointer(), src.getPointer(), len,
-        getI64IntegerAttr(dst.getAlignment().getQuantity()),
-        getI64IntegerAttr(src.getAlignment().getQuantity()));
+    return cir::MemMoveOp::create(*this, loc, dst.getPointer(),
+                                  src.getPointer(), len,
+                                  getAlignmentAttr(dst.getAlignment()),
+                                  getAlignmentAttr(src.getAlignment()));
   }
 
   cir::MemSetOp createMemSet(mlir::Location loc, mlir::Value dst,
@@ -219,7 +220,7 @@ class CIRGenBuilderTy : public cir::CIRBaseBuilderTy {
 
   cir::MemSetOp createMemSet(mlir::Location loc, Address dst, mlir::Value val,
                              mlir::Value len) {
-    mlir::IntegerAttr align = getAlignmentAttr(dst.getAlignment());
+    cir::AlignmentAttr align = getAlignmentAttr(dst.getAlignment());
     assert(val.getType() == getUInt8Ty());
     return cir::MemSetOp::create(*this, loc, dst.getPointer(), align, val, len);
   }
@@ -550,7 +551,7 @@ class CIRGenBuilderTy : public cir::CIRBaseBuilderTy {
 
   cir::LoadOp createLoad(mlir::Location loc, Address addr,
                          bool isVolatile = false, bool isNontemporal = false) {
-    mlir::IntegerAttr align = getAlignmentAttr(addr.getAlignment());
+    cir::AlignmentAttr align = getAlignmentAttr(addr.getAlignment());
     return cir::LoadOp::create(*this, loc, addr.getPointer(), /*isDeref=*/false,
                                isVolatile, isNontemporal,
                                /*alignment=*/align,
@@ -564,7 +565,7 @@ class CIRGenBuilderTy : public cir::CIRBaseBuilderTy {
     if (ty != mlir::cast<cir::PointerType>(ptr.getType()).getPointee())
       ptr = createPtrBitcast(ptr, ty);
     uint64_t alignment = align ? align->value() : 0;
-    mlir::IntegerAttr alignAttr = getAlignmentAttr(alignment);
+    cir::AlignmentAttr alignAttr = getAlignmentAttr(alignment);
     return cir::LoadOp::create(*this, loc, ptr, /*isDeref=*/false,
                                /*isVolatile=*/false, /*isNontemporal=*/false,
                                alignAttr,
@@ -581,7 +582,7 @@ class CIRGenBuilderTy : public cir::CIRBaseBuilderTy {
 
   cir::StoreOp createStore(mlir::Location loc, mlir::Value val, Address dst,
                            bool isVolatile = false, bool isNontemporal = false,
-                           mlir::IntegerAttr align = {},
+                           cir::AlignmentAttr align = {},
                            cir::SyncScopeKindAttr scope = {},
                            cir::MemOrderAttr order = {}) {
     if (!align)
@@ -794,8 +795,8 @@ class CIRGenBuilderTy : public cir::CIRBaseBuilderTy {
     if (!passThru)
       passThru = this->getConstant(loc, cir::PoisonAttr::get(ty));
 
-    auto alignAttr =
-        this->getI64IntegerAttr(static_cast<int64_t>(alignment.value()));
+    auto alignAttr = cir::AlignmentAttr::getOrEmpty(
+        this->getContext(), static_cast<int64_t>(alignment.value()));
 
     return cir::VecMaskedLoadOp::create(*this, loc, ty, ptr, mask, passThru,
                                         alignAttr);
diff --git a/clang/lib/CIR/CodeGen/CIRGenBuiltin.cpp b/clang/lib/CIR/CodeGen/CIRGenBuiltin.cpp
index 2af49c2afdcdc2..d53c1b6e6878dd 100644
--- a/clang/lib/CIR/CodeGen/CIRGenBuiltin.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenBuiltin.cpp
@@ -470,8 +470,8 @@ static void emitAtomicLockRelease(CIRGenFunction &cgf, const CallExpr *e) {
   auto scopeAttr = cir::SyncScopeKindAttr::get(&cgf.getMLIRContext(),
                                                cir::SyncScopeKind::System);
   builder.createStore(loc, zero, destAddr, /*isVolatile=*/false,
-                      /*isNontemporal=*/false,
-                      /*align=*/mlir::IntegerAttr{}, scopeAttr, orderAttr);
+                      /*isNontemporal=*/false, cir::AlignmentAttr{}, scopeAttr,
+                      orderAttr);
 }
 
 static void emitAtomicFenceOp(CIRGenFunction &cgf, const CallExpr *expr,
@@ -2669,7 +2669,8 @@ RValue CIRGenFunction::emitBuiltinExpr(const GlobalDecl &gd, unsigned builtinID,
 
     cir::ClearPaddingOp::create(
         builder, loc, addr.getPointer(),
-        builder.getI64IntegerAttr(addr.getAlignment().getQuantity()),
+        cir::AlignmentAttr::getOrEmpty(builder.getContext(),
+                                     addr.getAlignment().getQuantity()),
         mlir::ArrayAttr::get(&getMLIRContext(), paddingLocs));
     return RValue::get(nullptr);
   }
diff --git a/clang/lib/CIR/CodeGen/CIRGenBuiltinNVPTX.cpp b/clang/lib/CIR/CodeGen/CIRGenBuiltinNVPTX.cpp
index 7771f9528a61c3..98170f90110ed4 100644
--- a/clang/lib/CIR/CodeGen/CIRGenBuiltinNVPTX.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenBuiltinNVPTX.cpp
@@ -135,7 +135,8 @@ static mlir::Value makeScopedAtomicRMW(CIRGenFunction &cgf,
   auto rmwi = cir::AtomicFetchOp::create(
       builder, cgf.getLoc(expr->getSourceRange()), destValue, val, kind,
       cir::MemOrder::Relaxed, scope,
-      builder.getI64IntegerAttr(destAddr.getAlignment().getQuantity()),
+      cir::AlignmentAttr::getOrEmpty(builder.getContext(),
+                                   destAddr.getAlignment().getQuantity()),
       /*is_volatile=*/false, /*fetch_first=*/true);
   return rmwi->getResult(0);
 }
@@ -150,7 +151,8 @@ static mlir::Value makeScopedAtomicXchg(CIRGenFunction &cgf,
   auto xchg = cir::AtomicXchgOp::create(
       builder, cgf.getLoc(expr->getSourceRange()), destValue, val,
       cir::MemOrder::Relaxed, scope,
-      builder.getI64IntegerAttr(destAddr.getAlignment().getQuantity()),
+      cir::AlignmentAttr::getOrEmpty(builder.getContext(),
+                                   destAddr.getAlignment().getQuantity()),
       /*is_volatile=*/false);
   return xchg.getResult();
 }
diff --git a/clang/lib/CIR/CodeGen/CIRGenCUDANV.cpp b/clang/lib/CIR/CodeGen/CIRGenCUDANV.cpp
index 979f273358a757..9e85a82d9ed8de 100644
--- a/clang/lib/CIR/CodeGen/CIRGenCUDANV.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenCUDANV.cpp
@@ -365,8 +365,8 @@ void CIRGenNVCUDARuntime::emitDeviceStub(CIRGenFunction &cgf, cir::FuncOp fn,
     auto gv = cir::GlobalViewAttr::get(fnPtrTy, sym);
 
     globalOp->setAttr("initial_value", gv);
-    globalOp->setAttr("alignment", builder.getI64IntegerAttr(
-                                       cgm.getPointerAlign().getQuantity()));
+    globalOp.setAlignmentAttr(cir::AlignmentAttr::getOrEmpty(
+        builder.getContext(), cgm.getPointerAlign().getQuantity()));
 
     // The stub's linkage is only final once it is defined, so the handle
     // takes it over here.
@@ -431,8 +431,8 @@ mlir::Operation *CIRGenNVCUDARuntime::getKernelHandle(cir::FuncOp fn,
   cir::GlobalOp globalOp =
       cgm.createGlobalOp(fn.getLoc(), globalName, fnPtrTy, /*isConstant=*/true);
 
-  globalOp->setAttr("alignment", builder.getI64IntegerAttr(
-                                     cgm.getPointerAlign().getQuantity()));
+  globalOp.setAlignmentAttr(cir::AlignmentAttr::getOrEmpty(
+      builder.getContext(), cgm.getPointerAlign().getQuantity()));
 
   // Inherit visibility and comdat from the kernel's declaration.
   auto *fd = cast<FunctionDecl>(gd.getDecl());
@@ -685,7 +685,8 @@ void CIRGenNVCUDARuntime::transformManagedVars() {
       builder.setInsertionPointAfter(getGlobalOp);
       mlir::Value ld = builder.createAlignedLoad(
           getGlobalOp.getLoc(), varPtrTy, addr,
-          CharUnits::fromQuantity(var.getAlignment().value_or(1)));
+          CharUnits::fromQuantity(
+              var.getAlignmentAttr() ? var.getAlignmentAttr().getAlign() : 1));
       addr.replaceAllUsesExcept(ld, ld.getDefiningOp());
     }
 
diff --git a/clang/lib/CIR/CodeGen/CIRGenDecl.cpp b/clang/lib/CIR/CodeGen/CIRGenDecl.cpp
index a5f1f01a2391c8..50d3fde6d1112b 100644
--- a/clang/lib/CIR/CodeGen/CIRGenDecl.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenDecl.cpp
@@ -816,7 +816,7 @@ Address CIRGenModule::createUnnamedGlobalFrom(const VarDecl &d,
     gv.setUnnamedAddr(true);
 
     cacheEntry = gv;
-  } else if (cacheEntry.getAlignment() <
+  } else if (cacheEntry.getAlignmentValue() <
              static_cast<uint64_t>(align.getQuantity())) {
     cacheEntry.setAlignment(align.getAsAlign().value());
   }
diff --git a/clang/lib/CIR/CodeGen/CIRGenExpr.cpp b/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
index d17c324ed1dd74..761628534af715 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
@@ -1921,8 +1921,9 @@ LValue CIRGenFunction::emitMatrixElementExpr(const MatrixElementExpr *e) {
 LValue CIRGenFunction::emitStringLiteralLValue(const StringLiteral *e,
                                                llvm::StringRef name) {
   cir::GlobalOp globalOp = cgm.getGlobalForStringLiteral(e, name);
-  assert(globalOp.getAlignment() && "expected alignment for string literal");
-  unsigned align = *(globalOp.getAlignment());
+  assert(globalOp.getAlignmentAttr() &&
+         "expected alignment for string literal");
+  unsigned align = globalOp.getAlignmentAttr().getAlign();
   mlir::Value addr =
       builder.createGetGlobal(getLoc(e->getSourceRange()), globalOp);
   mlir::ptr::MemorySpaceAttrInterface destAS =
@@ -2258,10 +2259,9 @@ static Address createReferenceTemporary(CIRGenFunction &cgf,
     auto addr =
         mlir::cast<cir::GlobalOp>(cgf.cgm.getAddrOfGlobalTemporary(m, inner));
     auto getGlobal = cgf.cgm.getBuilder().createGetGlobal(addr);
-    assert(addr.getAlignment().has_value() &&
-           "This should always have an alignment");
-    return Address(getGlobal,
-                   clang::CharUnits::fromQuantity(addr.getAlignment().value()));
+    assert(addr.getAlignmentAttr() && "This should always have an alignment");
+    return Address(getGlobal, clang::CharUnits::fromQuantity(
+                                  addr.getAlignmentAttr().getAlign()));
   }
 
   case SD_Dynamic:
@@ -3111,14 +3111,18 @@ mlir::Value CIRGenFunction::emitAlloca(StringRef name, mlir::Type ty,
   // the lowering pass instead.
   cir::PointerType localVarPtrTy =
       builder.getPointerTo(ty, getCIRAllocaAddressSpace());
-  mlir::IntegerAttr alignIntAttr = cgm.getSize(alignment);
+  cir::AlignmentAttr alignAttr =
+      builder.getAlignmentAttr(alignment.getQuantity());
+  // cir.alloca's alignment attribute is required; zero would map to an empty
+  // attribute, which op verification rejects.
+  assert(alignAttr && "cir.alloca requires a concrete alignment");
 
   mlir::Value addr;
   {
     mlir::OpBuilder::InsertionGuard guard(builder);
     builder.restoreInsertionPoint(ip);
     addr = builder.createAlloca(loc, /*addr type*/ localVarPtrTy, name,
-                                alignIntAttr, arraySize);
+                                alignAttr, arraySize);
     assert(!cir::MissingFeatures::astVarDeclInterface());
   }
   return addr;
@@ -3249,7 +3253,7 @@ Address CIRGenFunction::createTempAllocaWithoutCast(
   cir::AllocaOp alloca = ip.isSet()
                              ? createTempAlloca(ty, loc, name, ip, arraySize)
                              : createTempAlloca(ty, loc, name, arraySize);
-  alloca.setAlignmentAttr(cgm.getSize(align));
+  alloca.setAlignment(align.getQuantity());
   return Address(alloca, ty, align);
 }
 
diff --git a/clang/lib/CIR/CodeGen/CIRGenExprCXX.cpp b/clang/lib/CIR/CodeGen/CIRGenExprCXX.cpp
index c8a2ff710cf0cf..29c8aea65eed70 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExprCXX.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExprCXX.cpp
@@ -987,9 +987,10 @@ static void enterNewDeleteCleanup(CIRGenFunction &cgf, const CXXNewExpr *e,
         v = castOp.getSrc();
       }
       cir::AllocaOp alloca = v.getDefiningOp<cir::AllocaOp>();
+      cir::AlignmentAttr alignment = alloca.getAlignment();
       return RValue::get(cgf.getBuilder().createAlignedLoad(
           alloca.getLoc(), alloca.getAllocaType(), alloca,
-          llvm::MaybeAlign(alloca.getAlignment())));
+          alignment ? llvm::MaybeAlign(alignment.getAlign()) : std::nullopt));
     }
   };
   typedef CallDeleteDuringNew<ConditionalCleanupTraits> ConditionalCleanup;
diff --git a/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp b/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
index a4b5b761c9be51..551eabea15500c 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
@@ -667,7 +667,8 @@ class ScalarExprEmitter : public StmtVisitor<ScalarExprEmitter, mlir::Value> {
         auto xchg = cir::AtomicXchgOp::create(
             builder, loc, intAddr.getPointer(), one,
             cir::MemOrder::SequentiallyConsistent, cir::SyncScopeKind::System,
-            builder.getI64IntegerAttr(intAddr.getAlignment().getQuantity()),
+            cir::AlignmentAttr::getOrEmpty(builder.getContext(),
+                                         intAddr.getAlignment().getQuantity()),
             lv.isVolatileQualified());
         return builder.createCast(cir::CastKind::int_to_bool, xchg.getResult(),
                                   builder.getBoolTy());
@@ -688,7 +689,8 @@ class ScalarExprEmitter : public StmtVisitor<ScalarExprEmitter, mlir::Value> {
         auto rmw = cir::AtomicFetchOp::create(
             builder, loc, lv.getPointer(), one, kind,
             cir::MemOrder::SequentiallyConsistent, cir::SyncScopeKind::System,
-            builder.getI64IntegerAttr(lv.getAlignment().getQuantity()),
+            cir::AlignmentAttr::getOrEmpty(builder.getContext(),
+                                         lv.getAlignment().getQuantity()),
             lv.isVolatileQualified(), /*fetch_first=*/true);
         mlir::Value oldVal = rmw->getResult(0);
         // Prefix returns new value; postfix returns old value.
@@ -710,7 +712,8 @@ class ScalarExprEmitter : public StmtVisitor<ScalarExprEmitter, mlir::Value> {
           auto rmw = cir::AtomicFetchOp::create(
               builder, loc, lv.getPointer(), amt, kind,
               cir::MemOrder::SequentiallyConsistent, cir::SyncScopeKind::System,
-              builder.getI64IntegerAttr(lv.getAlignment().getQuantity()),
+              cir::AlignmentAttr::getOrEmpty(builder.getContext(),
+                                           lv.getAlignment().getQuantity()),
               lv.isVolatileQualified(), /*fetch_first=*/true);
           mlir::Value oldVal = rmw->getResult(0);
           if (isPre)
diff --git a/clang/lib/CIR/CodeGen/CIRGenFunction.h b/clang/lib/CIR/CodeGen/CIRGenFunction.h
index 72e265a35f477e..3cc7acfb728752 100644
--- a/clang/lib/CIR/CodeGen/CIRGenFunction.h
+++ b/clang/lib/CIR/CodeGen/CIRGenFunction.h
@@ -2864,8 +2864,8 @@ class CIRGenFunction : public CIRGenTypeCache {
       cir::StoreOp store = builder.createStore(
           value.getLoc(), value, addr, /*isVolatile=*/false,
           /*isNontemporal=*/false,
-          mlir::IntegerAttr::get(
-              mlir::IntegerType::get(value.getContext(), 64),
+          cir::AlignmentAttr::getOrEmpty(
+              value.getContext(),
               (uint64_t)addr.getAlignment().getAsAlign().value()));
       outermostConditional->advanceInsertPoint(store);
     }
diff --git a/clang/lib/CIR/CodeGen/CIRGenItaniumCXXABI.cpp b/clang/lib/CIR/CodeGen/CIRGenItaniumCXXABI.cpp
index 3b28f633e72de1..65b3473c690ff1 100644
--- a/clang/lib/CIR/CodeGen/CIRGenItaniumCXXABI.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenItaniumCXXABI.cpp
@@ -1351,7 +1351,7 @@ CIRGenItaniumRTTIBuilder::buildTypeInfo(mlir::Location loc, QualType ty,
 
   CharUnits align = cgm.getASTContext().toCharUnitsFromBits(
       cgm.getTarget().getPointerAlign(LangAS::Default));
-  gv.setAlignmentAttr(cgm.getSize(align));
+  gv.setAlignment(align.getQuantity());
 
   // The Itanium ABI specifies that type_info objects must be globally
   // unique, with one exception: if the type is an incomplete class
diff --git a/clang/lib/CIR/CodeGen/CIRGenModule.cpp b/clang/lib/CIR/CodeGen/CIRGenModule.cpp
index 89310e2befbfb2..27b31683a292e0 100644
--- a/clang/lib/CIR/CodeGen/CIRGenModule.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenModule.cpp
@@ -1472,7 +1472,7 @@ cir::GlobalOp CIRGenModule::getOrCreateCIRGlobal(
     if (langOpts.OpenMP && !langOpts.OpenMPSimd)
       getOpenMPRuntime().registerTargetGlobalVariable(d);
 
-    gv.setAlignmentAttr(getSize(astContext.getDeclAlign(d)));
+    gv.setAlignment(astContext.getDeclAlign(d).getQuantity());
 
     setLinkageForGV(gv, d);
 
@@ -1867,7 +1867,7 @@ void CIRGenModule::emitGlobalVarDefinition(const clang::VarDecl *vd,
 
   // The global may have been created without a declaration, e.g. as the target
   // of a weakref, so make sure the alignment comes from the definition.
-  gv.setAlignmentAttr(getSize(astContext.getDeclAlign(vd)));
+  gv.setAlignment(astContext.getDeclAlign(vd).getQuantity());
 
   // Set CIR linkage and DLL storage class.
   gv.setLinkage(linkage);
@@ -2197,7 +2197,7 @@ cir::GlobalOp CIRGenModule::createOrReplaceCXXRuntimeVariable(
     gv.setSelfComdat();
   }
 
-  gv.setAlignmentAttr(getSize(alignment));
+  gv.setAlignment(alignment.getQuantity());
   setDSOLocal(static_cast<mlir::Operation *>(gv));
   return gv;
 }
@@ -2433,7 +2433,7 @@ generateStringLiteral(mlir::Location loc, mlir::TypedAttr c,
                          !cgm.getLangOpts().WritableStrings, addrSpace);
 
   // Set up extra information and add to the module
-  gv.setAlignmentAttr(cgm.getSize(alignment));
+  gv.setAlignment(cgm.getSize(alignment).getInt());
   gv.setLinkageAttr(
       cir::GlobalLinkageKindAttr::get(cgm.getBuilder().getContext(), lt));
   assert(!cir::MissingFeatures::opGlobalThreadLocal());
@@ -2483,9 +2483,9 @@ cir::GlobalOp CIRGenModule::getGlobalForStringLiteral(const StringLiteral *s,
   if (!getLangOpts().WritableStrings && constantStringMap.count(c)) {
     gv = constantStringMap[c];
     // The bigger alignment always wins.
-    if (!gv.getAlignment() ||
-        uint64_t(alignment.getQuantity()) > *gv.getAlignment())
-      gv.setAlignmentAttr(getSize(alignment));
+    if (!gv.getAlignmentAttr() ||
+        uint64_t(alignment.getQuantity()) > gv.getAlignmentAttr().getAlign())
+      gv.setAlignment(alignment.getQuantity());
   } else {
     // Mangle the string literal if that's how the ABI merges duplicate strings.
     // Don't do it if they are writable, since we don't want writes in one TU to
@@ -3751,9 +3751,11 @@ void CIRGenModule::setCIRFunctionAttributesForDefinition(
 
   if (explicitAlignment) {
     f.setAlignment(*explicitAlignment);
-    f.setPreferredAlignment(*explicitAlignment);
+    f.setPreferredAlignmentAttr(
+        cir::AlignmentAttr::getOrEmpty(f.getContext(), *explicitAlignment));
   } else if (langOpts.PreferredFunctionAlignment) {
-    f.setPreferredAlignment(langOpts.PreferredFunctionAlignment);
+    f.setPreferredAlignmentAttr(cir::AlignmentAttr::getOrEmpty(
+        f.getContext(), langOpts.PreferredFunctionAlignment));
   }
 
   // Some C++ ABIs require 2-byte alignment for member functions, in order to
@@ -3761,7 +3763,7 @@ void CIRGenModule::setCIRFunctionAttributesForDefinition(
   // functions. If the current target's C++ ABI requires this and this is a
   // member function, set its alignment accordingly.
   if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
-    if (isa<CXXMethodDecl>(decl) && f.getAlignment().value_or(1) < 2)
+    if (isa<CXXMethodDecl>(decl) && f.getAlignmentValue() < 2)
       f.setAlignment(2);
   }
 
diff --git a/clang/lib/CIR/CodeGen/CIRGenOpenACCRecipe.cpp b/clang/lib/CIR/CodeGen/CIRGenOpenACCRecipe.cpp
index 663ddf305ec91a..e405c44a291a6b 100644
--- a/clang/lib/CIR/CodeGen/CIRGenOpenACCRecipe.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenOpenACCRecipe.cpp
@@ -44,9 +44,11 @@ void OpenACCRecipeBuilderBase::makeAllocaCopy(mlir::Location loc,
 
   mlir::Type itrTy = cgf.cgm.convertType(cgf.getContext().UnsignedLongLongTy);
   auto itrPtrTy = cir::PointerType::get(itrTy);
-  mlir::IntegerAttr itrAlign =
-      cgf.cgm.getSize(cgf.getContext().getTypeAlignInChars(
-          cgf.getContext().UnsignedLongLongTy));
+  auto itrAlign = cir::AlignmentAttr::getOrEmpty(
+      &cgf.getMLIRContext(),
+      cgf.getContext()
+          .getTypeAlignInChars(cgf.getContext().UnsignedLongLongTy)
+          .getQuantity());
 
   auto loopBuilder = [&]() {
     auto itr = cir::AllocaOp::create(builder, loc, itrPtrTy, "itr", itrAlign);
@@ -223,9 +225,11 @@ std::pair<mlir::Value, mlir::Value> OpenACCRecipeBuilderBase::createBoundsLoop(
 
   mlir::Type itrTy = cgf.cgm.convertType(cgf.getContext().UnsignedLongLongTy);
   auto itrPtrTy = cir::PointerType::get(itrTy);
-  mlir::IntegerAttr itrAlign =
-      cgf.cgm.getSize(cgf.getContext().getTypeAlignInChars(
-          cgf.getContext().UnsignedLongLongTy));
+  auto itrAlign = cir::AlignmentAttr::getOrEmpty(
+      &cgf.getMLIRContext(),
+      cgf.getContext()
+          .getTypeAlignInChars(cgf.getContext().UnsignedLongLongTy)
+          .getQuantity());
   auto idxType = mlir::IndexType::get(&cgf.getMLIRContext());
 
   auto doSubscriptOp = [&](mlir::Value subVal,
@@ -614,7 +618,9 @@ void OpenACCRecipeBuilderBase::createReductionRecipeCombiner(
     mlir::Value zero =
         builder.getConstInt(loc, mlir::cast<cir::IntType>(cgf.ptrDiffTy), 0);
     mlir::Value itr = cir::AllocaOp::create(
-        builder, loc, itrPtrTy, "itr", cgf.cgm.getSize(cgf.getPointerAlign()));
+        builder, loc, itrPtrTy, "itr",
+        cir::AlignmentAttr::getOrEmpty(&cgf.getMLIRContext(),
+                                     cgf.getPointerAlign().getQuantity()));
     builder.CIRBaseBuilderTy::createStore(loc, zero, itr);
 
     builder.setInsertionPointAfter(builder.createFor(
diff --git a/clang/lib/CIR/CodeGen/CIRGenStmtOpenACC.cpp b/clang/lib/CIR/CodeGen/CIRGenStmtOpenACC.cpp
index 2d561e02b867ed..2d3cf65bf83816 100644
--- a/clang/lib/CIR/CodeGen/CIRGenStmtOpenACC.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenStmtOpenACC.cpp
@@ -354,8 +354,10 @@ emitAtomicUpdate(CIRGenFunction &cgf, CIRGenBuilderTy &builder,
     // alloca/load/store set.
     auto alloca = cir::AllocaOp::create(
         builder, start, x.getType(), "x_var",
-        cgf.cgm.getSize(
-            cgf.getContext().getTypeAlignInChars(inf.X->getType())));
+        cir::AlignmentAttr::getOrEmpty(builder.getContext(),
+                                     cgf.getContext()
+                                         .getTypeAlignInChars(inf.X->getType())
+                                         .getQuantity()));
 
     alloca.setInitAttr(builder.getUnitAttr());
     builder.CIRBaseBuilderTy::createStore(start, recipeBlock->getArgument(0),
diff --git a/clang/lib/CIR/Dialect/IR/CIRAttrs.cpp b/clang/lib/CIR/Dialect/IR/CIRAttrs.cpp
index 002b5c9c5a07a2..a5e6a5711923cf 100644
--- a/clang/lib/CIR/Dialect/IR/CIRAttrs.cpp
+++ b/clang/lib/CIR/Dialect/IR/CIRAttrs.cpp
@@ -1266,6 +1266,18 @@ RecordLayoutAttr cir::getRecordLayout(mlir::ModuleOp mod,
   return attr;
 }
 
+//===----------------------------------------------------------------------===//
+// AlignmentAttr
+//===----------------------------------------------------------------------===//
+
+LogicalResult
+AlignmentAttr::verify(function_ref<InFlightDiagnostic()> emitError,
+                      uint64_t align) {
+  if (align == 0 || !llvm::isPowerOf2_64(align))
+    return emitError() << "alignment has to be a positive power of 2";
+  return success();
+}
+
 //===----------------------------------------------------------------------===//
 // TBAA attributes
 //===----------------------------------------------------------------------===//
diff --git a/clang/lib/CIR/Dialect/IR/CIRDialect.cpp b/clang/lib/CIR/Dialect/IR/CIRDialect.cpp
index 15a2503cf9b424..2d416b654d707d 100644
--- a/clang/lib/CIR/Dialect/IR/CIRDialect.cpp
+++ b/clang/lib/CIR/Dialect/IR/CIRDialect.cpp
@@ -589,7 +589,7 @@ void cir::printOmittedTerminatorRegion(mlir::OpAsmPrinter &printer,
 
 void cir::AllocaOp::build(mlir::OpBuilder &odsBuilder,
                           mlir::OperationState &odsState, mlir::Type addr,
-                          llvm::StringRef name, mlir::IntegerAttr alignment) {
+                          llvm::StringRef name, cir::AlignmentAttr alignment) {
   odsState.addAttribute(getNameAttrName(odsState.name),
                         odsBuilder.getStringAttr(name));
   if (alignment) {
@@ -3192,15 +3192,17 @@ ParseResult cir::FuncOp::parse(OpAsmParser &parser, OperationState &state) {
     int64_t value;
     if (parseAlignmentBody(value).failed())
       return failure();
-    state.addAttribute(alignmentNameAttr, builder.getI64IntegerAttr(value));
+    state.addAttribute(alignmentNameAttr, cir::AlignmentAttr::getOrEmpty(
+                                              builder.getContext(), value));
   }
 
   if (parser.parseOptionalKeyword(preferredAlignmentNameAttr).succeeded()) {
     int64_t value;
     if (parseAlignmentBody(value).failed())
       return failure();
-    state.addAttribute(preferredAlignmentNameAttr,
-                       builder.getI64IntegerAttr(value));
+    state.addAttribute(
+        preferredAlignmentNameAttr,
+        cir::AlignmentAttr::getOrEmpty(builder.getContext(), value));
   }
 
   // Default to external linkage if no keyword is provided.
@@ -3521,11 +3523,12 @@ void cir::FuncOp::print(OpAsmPrinter &p) {
     ::printComdatName(p, getComdatAttr());
   }
 
-  if (getAlignment())
-    p << " alignment(" << *getAlignment() << ')';
+  if (getAlignmentAttr())
+    p << " alignment(" << getAlignmentAttr().getAlign() << ')';
 
-  if (getPreferredAlignment())
-    p << " preferred_alignment(" << *getPreferredAlignment() << ')';
+  if (getPreferredAlignmentAttr())
+    p << " preferred_alignment(" << getPreferredAlignmentAttr().getAlign()
+      << ')';
 
   if (getLinkage() != GlobalLinkageKind::ExternalLinkage)
     p << ' ' << stringifyGlobalLinkageKind(getLinkage());
diff --git a/clang/lib/CIR/Dialect/Transforms/EHABILowering.cpp b/clang/lib/CIR/Dialect/Transforms/EHABILowering.cpp
index edd8e1928489e4..3fcc51dd85d086 100644
--- a/clang/lib/CIR/Dialect/Transforms/EHABILowering.cpp
+++ b/clang/lib/CIR/Dialect/Transforms/EHABILowering.cpp
@@ -1088,9 +1088,9 @@ void ItaniumEHLowering::lowerInitCatchParam(cir::InitCatchParamOp op) {
       cir::CIRDataLayout dataLayout(mod);
       uint64_t alignment =
           dataLayout.getAlignment(caughtType, /*useABIAlign=*/true).value();
-      byRefTmp =
-          cir::AllocaOp::create(builder, loc, elementType, "exn.byref.tmp",
-                                builder.getI64IntegerAttr(alignment));
+      byRefTmp = cir::AllocaOp::create(
+          builder, loc, elementType, "exn.byref.tmp",
+          cir::AlignmentAttr::getOrEmpty(builder.getContext(), alignment));
     }
     mlir::Value casted = cir::CastOp::create(builder, loc, caughtType,
                                              cir::CastKind::bitcast, exnPtr);
diff --git a/clang/lib/CIR/Dialect/Transforms/FlattenCFG.cpp b/clang/lib/CIR/Dialect/Transforms/FlattenCFG.cpp
index a28f78179f3214..3764e3dbe3c488 100644
--- a/clang/lib/CIR/Dialect/Transforms/FlattenCFG.cpp
+++ b/clang/lib/CIR/Dialect/Transforms/FlattenCFG.cpp
@@ -867,7 +867,7 @@ static cir::AllocaOp getOrCreateCleanupDestSlot(cir::FuncOp funcOp,
   uint64_t alignment = dataLayout.getAlignment(s32Type, true).value();
   auto allocaOp = cir::AllocaOp::create(
       rewriter, loc, ptrToS32Type, "__cleanup_dest_slot",
-      /*alignment=*/rewriter.getI64IntegerAttr(alignment));
+      cir::AlignmentAttr::getOrEmpty(rewriter.getContext(), alignment));
   allocaOp.setCleanupDestSlot(true);
   return allocaOp;
 }
@@ -1278,9 +1278,9 @@ class CIRCleanupScopeOpFlattening
           cir::PointerType ptrType = cir::PointerType::get(
               operand.getType(),
               dataLayout.getAllocaAddrSpace(rewriter.getContext()));
-          alloca =
-              cir::AllocaOp::create(rewriter, loc, ptrType, "__ret_operand_tmp",
-                                    rewriter.getI64IntegerAttr(alignment));
+          alloca = cir::AllocaOp::create(
+              rewriter, loc, ptrType, "__ret_operand_tmp",
+              cir::AlignmentAttr::getOrEmpty(rewriter.getContext(), alignment));
         }
 
         // Store the operand value at the original return location.
diff --git a/clang/lib/CIR/Dialect/Transforms/LoweringPrepare.cpp b/clang/lib/CIR/Dialect/Transforms/LoweringPrepare.cpp
index 7500e6f51ab7b1..da5b0c698975a8 100644
--- a/clang/lib/CIR/Dialect/Transforms/LoweringPrepare.cpp
+++ b/clang/lib/CIR/Dialect/Transforms/LoweringPrepare.cpp
@@ -1726,7 +1726,7 @@ void LoweringPreparePass::emitGuardedInit(CIRBaseBuilderTy &builder,
     auto bytePtrTy = cir::PointerType::get(builder.getSIntNTy(8));
     mlir::Value bytePtr = builder.createBitcast(guardPtr, bytePtrTy);
     mlir::Value guardLoad = builder.createAlignedLoad(
-        globalOp.getLoc(), bytePtr, *guard.getAlignment());
+        globalOp.getLoc(), bytePtr, guard.getAlignmentValue());
 
     // Itanium ABI:
     //   An implementation supporting thread-safety on multiprocessor
@@ -2206,7 +2206,7 @@ cir::IfOp LoweringPreparePass::buildInitGuardCheck(CIRBaseBuilderTy &builder,
         getGuard, cir::PointerType::get(builder.getSIntNTy(8)));
 
   mlir::Value guardLoad =
-      builder.createAlignedLoad(loc, getGuardValue, *guard.getAlignment());
+      builder.createAlignedLoad(loc, getGuardValue, guard.getAlignmentValue());
   auto zero = builder.getConstantInt(loc, builder.getSIntNTy(8), 0);
   cir::CmpOp compare =
       builder.createCompare(loc, cir::CmpOpKind::eq, guardLoad, zero);
@@ -2650,7 +2650,7 @@ cir::GlobalOp LoweringPreparePass::getOrCreateConstAggregateGlobal(
   // First, check globals we've already discovered for this base name.
   for (cir::GlobalOp gv : versions) {
     if (gv.getSymType() == ty && gv.getInitialValue() == constant &&
-        gv.getAlignment() == alignment)
+        gv.getAlignmentValue() == alignment)
       return gv;
   }
 
@@ -2674,7 +2674,7 @@ cir::GlobalOp LoweringPreparePass::getOrCreateConstAggregateGlobal(
     versions.push_back(existingGv);
     if (existingGv.getSymType() == ty &&
         existingGv.getInitialValue() == constant &&
-        existingGv.getAlignment() == alignment)
+        existingGv.getAlignmentValue() == alignment)
       return existingGv;
     ++version;
   }
@@ -2756,7 +2756,7 @@ void LoweringPreparePass::lowerStoreOfConstAggregate(cir::StoreOp op) {
   // Check for existing globals and create a new global with a unique name
   // if no match is found.
   cir::GlobalOp gv = getOrCreateConstAggregateGlobal(
-      builder, op.getLoc(), baseName, ty, constant, alloca.getAlignment());
+      builder, op.getLoc(), baseName, ty, constant, alloca.getAlignmentValue());
 
   // Now replace the store with get_global + copy.
   builder.setInsertionPoint(op);
@@ -2770,11 +2770,13 @@ void LoweringPreparePass::lowerStoreOfConstAggregate(cir::StoreOp op) {
 
   cir::CIRDataLayout dataLayout(mlirModule);
   uint64_t naturalAlign = dataLayout.getTypeLanguageAlignment(ty);
-  if (alloca.getAlignment() != naturalAlign)
-    copyOp.setDstAlignment(alloca.getAlignment());
-  uint64_t srcAlign = gv.getAlignment().value_or(naturalAlign);
+  if (alloca.getAlignmentValue() != naturalAlign)
+    copyOp.setDstAlignmentAttr(alloca.getAlignment());
+  uint64_t srcAlign =
+      gv.getAlignmentAttr() ? gv.getAlignmentAttr().getAlign() : naturalAlign;
   if (srcAlign != naturalAlign)
-    copyOp.setSrcAlignment(srcAlign);
+    copyOp.setSrcAlignmentAttr(
+        cir::AlignmentAttr::getOrEmpty(op->getContext(), srcAlign));
 
   // Erase the original store.
   op.erase();
@@ -3470,7 +3472,10 @@ void LoweringPreparePass::buildCUDARegisterVars(cir::CIRBaseBuilderTy &builder,
       auto varSize = ConstantOp::create(
           builder, loc, IntAttr::get(sizeTy, size.getFixedValue()));
       auto align = ConstantOp::create(
-          builder, loc, IntAttr::get(intTy, global.getAlignment().value_or(1)));
+          builder, loc,
+          IntAttr::get(intTy, global.getAlignmentAttr()
+                                  ? global.getAlignmentAttr().getAlign()
+                                  : 1));
       builder.createCallOp(
           loc, cudaRegisterManagedVar,
           {fatbinHandle, managedPtr, hostVar, deviceName, varSize, align});
diff --git a/clang/lib/CIR/Dialect/Transforms/TargetLowering/CIRABIRewriteContext.cpp b/clang/lib/CIR/Dialect/Transforms/TargetLowering/CIRABIRewriteContext.cpp
index 9b5a562d83bbdd..d6239ef3775b2f 100644
--- a/clang/lib/CIR/Dialect/Transforms/TargetLowering/CIRABIRewriteContext.cpp
+++ b/clang/lib/CIR/Dialect/Transforms/TargetLowering/CIRABIRewriteContext.cpp
@@ -542,9 +542,9 @@ static cir::AllocaOp createCoercionSlot(
 
   mlir::OpBuilder::InsertionGuard guard(builder);
   builder.setInsertionPointToStart(slotBlock);
-  auto alloca = cir::AllocaOp::create(builder, loc, getAllocaPtrTy(slotTy, dl),
-                                      builder.getStringAttr("coerce"),
-                                      builder.getI64IntegerAttr(allocaAlign));
+  auto alloca = cir::AllocaOp::create(
+      builder, loc, getAllocaPtrTy(slotTy, dl), builder.getStringAttr("coerce"),
+      cir::AlignmentAttr::getOrEmpty(builder.getContext(), allocaAlign));
   createdOps.insert(alloca);
   return alloca;
 }
@@ -739,7 +739,7 @@ static mlir::Value emitInPlaceCoercedLoad(mlir::OpBuilder &builder,
   mlir::Value view = emitViewAtOffset(builder, loc, coercedTy, load.getAddr(),
                                       ignored, offset);
   auto coerced = cir::LoadOp::create(builder, loc, view);
-  coerced.setAlignment(llvm::MinAlign(src.getAlignment(), offset));
+  coerced.setAlignment(llvm::MinAlign(src.getAlignmentValue(), offset));
   return coerced;
 }
 
@@ -755,26 +755,30 @@ emitCopiedCoercionSlot(mlir::OpBuilder &builder, mlir::Location loc,
                        unsigned offset) {
   auto recTy = cast<cir::RecordType>(load.getType());
   uint64_t srcAlign;
-  if (cir::AllocaOp src = cir::getUnderlyingAlloca(load.getAddr()))
-    srcAlign = src.getAlignment();
-  else
-    srcAlign = load.getAlignment().value_or(
-        cir::CIRDataLayout(load->getParentOfType<mlir::ModuleOp>())
-            .getTypeLanguageAlignment(recTy));
+  if (cir::AllocaOp src = cir::getUnderlyingAlloca(load.getAddr())) {
+    srcAlign = src.getAlignmentValue();
+  } else {
+    auto alignment = load.getAlignmentAttr();
+    srcAlign = alignment
+                   ? alignment.getAlign()
+                   : cir::CIRDataLayout(load->getParentOfType<mlir::ModuleOp>())
+                         .getTypeLanguageAlignment(recTy);
+  }
   SmallPtrSet<mlir::Operation *, 4> ignored;
   cir::AllocaOp slot = createCoercionSlot(builder, loc, recTy, coercedTy,
                                           slotBlock, dl, ignored, offset);
-  slot.setAlignment(std::max(slot.getAlignment(), srcAlign));
+  slot.setAlignment(std::max(slot.getAlignmentValue(), srcAlign));
   assert((offset == 0 || slot.getAllocaType() == recTy) &&
          "a direct offset must leave the record as the slot's type");
   mlir::OpBuilder::InsertionGuard guard(builder);
   builder.setInsertionPoint(load);
   mlir::Value recView =
       emitViewAtOffset(builder, loc, recTy, slot, ignored, /*offset=*/0);
-  auto copy =
-      cir::CopyOp::create(builder, loc, recView, load.getAddr(),
-                          builder.getI64IntegerAttr(slot.getAlignment()),
-                          builder.getI64IntegerAttr(srcAlign));
+  auto copy = cir::CopyOp::create(
+      builder, loc, recView, load.getAddr(),
+      cir::AlignmentAttr::getOrEmpty(builder.getContext(),
+                                   slot.getAlignmentValue()),
+      cir::AlignmentAttr::getOrEmpty(builder.getContext(), srcAlign));
   copy.setIsVolatile(load.getIsVolatile());
   return slot;
 }
@@ -796,7 +800,7 @@ static mlir::Value emitCopiedCoercedLoad(mlir::OpBuilder &builder,
   mlir::Value coercedView =
       emitViewAtOffset(builder, loc, coercedTy, slot, ignored, offset);
   auto coerced = cir::LoadOp::create(builder, loc, coercedView);
-  coerced.setAlignment(llvm::MinAlign(slot.getAlignment(), offset));
+  coerced.setAlignment(llvm::MinAlign(slot.getAlignmentValue(), offset));
   return coerced;
 }
 
@@ -890,17 +894,19 @@ rewireRecordUses(mlir::OpBuilder &builder, mlir::Location loc, mlir::Value val,
     otherUses.push_back(&use);
   }
 
-  mlir::IntegerAttr srcAlign = builder.getI64IntegerAttr(addrAlign);
+  auto srcAlign = cir::AlignmentAttr::getOrEmpty(builder.getContext(), addrAlign);
   cir::CIRDataLayout cirDataLayout(
       val.getParentRegion()->getParentOfType<mlir::ModuleOp>());
   for (cir::StoreOp store : stores) {
     mlir::OpBuilder::InsertionGuard guard(builder);
     builder.setInsertionPoint(store);
-    uint64_t dstAlign = store.getAlignment().value_or(
-        cirDataLayout.getTypeLanguageAlignment(recTy));
-    auto copy =
-        cir::CopyOp::create(builder, store.getLoc(), store.getAddr(), addr,
-                            builder.getI64IntegerAttr(dstAlign), srcAlign);
+    auto dstAlignAttr = store.getAlignmentAttr();
+    uint64_t dstAlign = dstAlignAttr
+                            ? dstAlignAttr.getAlign()
+                            : cirDataLayout.getTypeLanguageAlignment(recTy);
+    auto copy = cir::CopyOp::create(
+        builder, store.getLoc(), store.getAddr(), addr,
+        cir::AlignmentAttr::getOrEmpty(builder.getContext(), dstAlign), srcAlign);
     copy.setIsVolatile(store.getIsVolatile());
     copy.setSkipTailPadding(shouldSkipTailPadding(store.getAddr(), recTy));
     store->erase();
@@ -932,7 +938,7 @@ replaceUsesFromSlot(mlir::OpBuilder &builder, mlir::Location loc,
   }
   cir::AllocaOp slot = cir::getUnderlyingAlloca(view);
   assert(slot && "the view must start at the coercion slot");
-  return rewireRecordUses(builder, loc, val, view, slot.getAlignment(), dl,
+  return rewireRecordUses(builder, loc, val, view, slot.getAlignmentValue(), dl,
                           exceptions);
 }
 
@@ -1047,7 +1053,7 @@ static mlir::Value forwardableIndirectAddr(cir::LoadOp load,
   if (addr.getType() != paramTy)
     return {};
   cir::AllocaOp slot = cir::getUnderlyingAlloca(addr);
-  return slot && slot.getAlignment() >= minAlign ? addr : mlir::Value();
+  return slot && slot.getAlignmentValue() >= minAlign ? addr : mlir::Value();
 }
 
 /// Whether a non-byval indirect argument of type \p ty is passed from the
@@ -1095,13 +1101,13 @@ static bool storageUnwrittenBetween(cir::LoadOp load, mlir::Operation *call,
 /// one \p load states, or the underlying slot's when it states none.  A load
 /// with neither names storage this pass cannot reason about, so the copy is
 /// left to assume nothing.
-static mlir::IntegerAttr loadSourceAlignment(cir::LoadOp load,
-                                             mlir::OpBuilder &builder) {
-  if (mlir::IntegerAttr stated = load.getAlignmentAttr())
+static cir::AlignmentAttr loadSourceAlignment(cir::LoadOp load,
+                                              mlir::OpBuilder &builder) {
+  if (cir::AlignmentAttr stated = load.getAlignmentAttr())
     return stated;
   if (cir::AllocaOp slot = cir::getUnderlyingAlloca(load.getAddr()))
-    return builder.getI64IntegerAttr(slot.getAlignment());
-  return builder.getI64IntegerAttr(1);
+    return slot.getAlignment();
+  return cir::AlignmentAttr::getOrEmpty(builder.getContext(), 1);
 }
 
 /// Decompose a struct value into one scalar call argument per field of \p
@@ -1340,7 +1346,8 @@ insertArgCoercion(mlir::FunctionOpInterface funcOp,
         slot = cir::AllocaOp::create(
             builder, loc, getAllocaPtrTy(flatTy, dl),
             builder.getStringAttr("coerce"),
-            builder.getI64IntegerAttr(
+            cir::AlignmentAttr::getOrEmpty(
+                builder.getContext(),
                 cir::CIRDataLayout(funcOp->getParentOfType<mlir::ModuleOp>())
                     .getTypeLanguageAlignment(flatTy)));
         flattenOps.insert(slot);
@@ -1361,8 +1368,8 @@ insertArgCoercion(mlir::FunctionOpInterface funcOp,
         auto storeOp = cir::StoreOp::create(
             builder, loc, entry.getArgument(blockArgIdx + f), fieldPtr);
         // A packed slot can be less aligned than the field's own type.
-        uint64_t fieldAlign =
-            llvm::MinAlign(slot.getAlignment(), flatTy.getElementOffset(dl, f));
+        uint64_t fieldAlign = llvm::MinAlign(slot.getAlignmentValue(),
+                                             flatTy.getElementOffset(dl, f));
         if (fieldAlign < dl.getTypeABIAlignment(fieldTy))
           storeOp.setAlignment(fieldAlign);
         flattenOps.insert(storeOp);
@@ -1445,7 +1452,7 @@ insertArgCoercion(mlir::FunctionOpInterface funcOp,
         // Erasing the spill before the block argument is retyped keeps the
         // store from being left with a value operand of the wrong type.
         mlir::Value destAddr;
-        mlir::IntegerAttr destAlign;
+        cir::AlignmentAttr destAlign;
         mlir::Operation *spillPos = nullptr;
         bool spillIsVolatile = false;
         if (paramStore) {
@@ -1472,7 +1479,8 @@ insertArgCoercion(mlir::FunctionOpInterface funcOp,
           builder.setInsertionPoint(spillPos);
           auto copy = cir::CopyOp::create(
               builder, funcOp.getLoc(), destAddr, blockArg, destAlign,
-              builder.getI64IntegerAttr(ac.indirectAlign.value()));
+              cir::AlignmentAttr::getOrEmpty(builder.getContext(),
+                                           ac.indirectAlign.value()));
           copy.setIsVolatile(spillIsVolatile);
           copy.setSkipTailPadding(
               shouldSkipTailPadding(destAddr, ptrTy.getPointee()));
@@ -1752,7 +1760,7 @@ rewriteIndirectReturnCall(cir::CallOp call, const FunctionClassification &fc,
     auto slot = cir::AllocaOp::create(
         builder, call.getLoc(), allocaPtrTy,
         /*name=*/builder.getStringAttr(""),
-        /*alignment=*/builder.getI64IntegerAttr(sretAlign));
+        cir::AlignmentAttr::getOrEmpty(builder.getContext(), sretAlign));
     slot.setReturnSlot(true);
     sretSlot = slot;
     // The sret pointer can be outside the alloca address space.
@@ -1890,7 +1898,8 @@ static mlir::LogicalResult prepareOneNonByvalParameter(
     auto synthesized = cir::AllocaOp::create(
         builder, funcOp.getLoc(), paramPtrTy,
         builder.getStringAttr("nonbyval.param"),
-        builder.getI64IntegerAttr(ac.indirectAlign.value()));
+        cir::AlignmentAttr::getOrEmpty(builder.getContext(),
+                                     ac.indirectAlign.value()));
     spill =
         cir::StoreOp::create(builder, funcOp.getLoc(), blockArg, synthesized);
   }
@@ -2282,7 +2291,7 @@ CIRABIRewriteContext::rewriteCallSite(mlir::Operation *callOp,
               canReadInPlace(recLoad, flatTy, cirDataLayout, /*offset=*/0)) {
             cir::AllocaOp baseAlloca = cir::getUnderlyingAlloca(base);
             assert(baseAlloca && "canReadInPlace requires an alloca");
-            baseAlign = baseAlloca.getAlignment();
+            baseAlign = baseAlloca.getAlignmentValue();
           } else {
             base = emitCopiedCoercionSlot(builder, call.getLoc(), recLoad,
                                           flatTy, slotBlock, dl, /*offset=*/0);
@@ -2407,7 +2416,8 @@ CIRABIRewriteContext::rewriteCallSite(mlir::Operation *callOp,
         return mlir::failure();
       if (!srcLoad)
         srcLoad = maybeGetCopyableRecordLoad(arg);
-      mlir::IntegerAttr slotAlign = builder.getI64IntegerAttr(minAlign);
+      auto slotAlign =
+          cir::AlignmentAttr::getOrEmpty(builder.getContext(), minAlign);
       mlir::OpBuilder::InsertionGuard guard(builder);
       if (srcLoad)
         builder.setInsertionPoint(srcLoad);
@@ -2778,8 +2788,9 @@ mlir::Value copyRegisterToTemp(CIRBaseBuilderTy &b, mlir::Location loc,
   if (mlir::isa<cir::RecordType>(f.resultTy))
     cir::CopyOp::create(
         b, loc, temp, regView,
-        b.getI64IntegerAttr(argumentAreaAlign(f.resultTy, f.module)),
-        b.getI64IntegerAttr(8));
+        cir::AlignmentAttr::getOrEmpty(b.getContext(),
+                                     argumentAreaAlign(f.resultTy, f.module)),
+        cir::AlignmentAttr::getOrEmpty(b.getContext(), 8));
   else
     b.createStore(loc, b.createAlignedLoad(loc, regView, 8), temp);
   return b.createPtrBitcast(temp, byteTy);
diff --git a/clang/lib/CIR/Dialect/Transforms/TargetLowering/LowerItaniumCXXABI.cpp b/clang/lib/CIR/Dialect/Transforms/TargetLowering/LowerItaniumCXXABI.cpp
index 4abb78d37f1ecb..cca6be8c900741 100644
--- a/clang/lib/CIR/Dialect/Transforms/TargetLowering/LowerItaniumCXXABI.cpp
+++ b/clang/lib/CIR/Dialect/Transforms/TargetLowering/LowerItaniumCXXABI.cpp
@@ -775,7 +775,8 @@ static mlir::Value buildDynamicCastToVoidAfterNullCheck(
                           /*isDeref=*/false,
                           /*is_volatile=*/false,
                           /*isNontemporal=*/false,
-                          /*alignment=*/builder.getI64IntegerAttr(vptrAlign),
+                          /*alignment=*/cir::AlignmentAttr::getOrEmpty(
+                              builder.getContext(), vptrAlign),
                           /*sync_scope=*/cir::SyncScopeKindAttr(),
                           /*mem_order=*/cir::MemOrderAttr(),
                           /*invariant=*/false, op.getTbaaAttr());
@@ -881,7 +882,8 @@ mlir::Value LowerItaniumCXXABI::readArrayCookieImpl(
   return cir::LoadOp::create(
       builder, loc, countPtr, /*isDeref=*/false, /*isVolatile=*/false,
       /*isNontemporal=*/false,
-      builder.getI64IntegerAttr(countAlignment.getQuantity()),
+      cir::AlignmentAttr::getOrEmpty(builder.getContext(),
+                                   countAlignment.getQuantity()),
       cir::SyncScopeKindAttr(), cir::MemOrderAttr(),
       /*invariant=*/false, /*tbaa=*/{});
 }
diff --git a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
index c037feac5b549f..f4e8b1f1e713ce 100644
--- a/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
+++ b/clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
@@ -381,12 +381,16 @@ lowerMemTransferOp(CIROp op, typename CIROp::Adaptor adaptor,
                    mlir::ConversionPatternRewriter &rewriter) {
   mlir::ArrayAttr argAttrs;
   if (op.getDstAlignment() || op.getSrcAlignment()) {
-    mlir::NamedAttribute dstAlignAttr = rewriter.getNamedAttr(
-        mlir::LLVM::LLVMDialect::getAlignAttrName(),
-        rewriter.getI64IntegerAttr(op.getDstAlignment().value_or(1)));
-    mlir::NamedAttribute srcAlignAttr = rewriter.getNamedAttr(
-        mlir::LLVM::LLVMDialect::getAlignAttrName(),
-        rewriter.getI64IntegerAttr(op.getSrcAlignment().value_or(1)));
+    uint64_t dstAlign =
+        op.getDstAlignment() ? op.getDstAlignment()->getAlign() : 1;
+    uint64_t srcAlign =
+        op.getSrcAlignment() ? op.getSrcAlignment()->getAlign() : 1;
+    mlir::NamedAttribute dstAlignAttr =
+        rewriter.getNamedAttr(mlir::LLVM::LLVMDialect::getAlignAttrName(),
+                              rewriter.getI64IntegerAttr(dstAlign));
+    mlir::NamedAttribute srcAlignAttr =
+        rewriter.getNamedAttr(mlir::LLVM::LLVMDialect::getAlignAttrName(),
+                              rewriter.getI64IntegerAttr(srcAlign));
     argAttrs = rewriter.getArrayAttr({
         /*dst_attrs=*/rewriter.getDictionaryAttr({dstAlignAttr}),
         /*src_attrs=*/rewriter.getDictionaryAttr({srcAlignAttr}),
@@ -420,7 +424,7 @@ mlir::LogicalResult CIRToLLVMMemSetOpLowering::matchAndRewrite(
     mlir::ConversionPatternRewriter &rewriter) const {
 
   // Capture the alignment before the replace erases `op`.
-  mlir::Attribute alignAttr = op.getAlignmentAttr();
+  cir::AlignmentAttr alignAttr = op.getAlignmentAttr();
   auto memset = rewriter.replaceOpWithNewOp<mlir::LLVM::MemsetOp>(
       op, adaptor.getDst(), adaptor.getVal(), adaptor.getLen(),
       /*isVolatile=*/false);
@@ -430,8 +434,8 @@ mlir::LogicalResult CIRToLLVMMemSetOpLowering::matchAndRewrite(
     llvm::SmallVector<mlir::Attribute> attrs{memset.getNumOperands(),
                                              rewriter.getDictionaryAttr({})};
     llvm::SmallVector<mlir::NamedAttribute> destAttrs;
-    destAttrs.push_back(
-        {mlir::LLVM::LLVMDialect::getAlignAttrName(), alignAttr});
+    destAttrs.push_back({mlir::LLVM::LLVMDialect::getAlignAttrName(),
+                         rewriter.getI64IntegerAttr(alignAttr.getAlign())});
     attrs[memset.odsIndex_dst] = rewriter.getDictionaryAttr(destAttrs);
 
     auto arrayAttr = rewriter.getArrayAttr(attrs);
@@ -1560,7 +1564,7 @@ mlir::LogicalResult CIRToLLVMAtomicCmpXchgOpLowering::matchAndRewrite(
       getLLVMSyncScope(op.getSyncScope(),
                        op->getParentOfType<mlir::ModuleOp>()));
 
-  cmpxchg.setAlignment(adaptor.getAlignment());
+  cmpxchg.setAlignment(op.getAlignmentValue());
   cmpxchg.setWeak(adaptor.getWeak());
   cmpxchg.setVolatile_(adaptor.getIsVolatile());
   forwardAMDGPUNoPrivateAddrSpace(op, cmpxchg, adaptor.getPtr());
@@ -1584,10 +1588,11 @@ mlir::LogicalResult CIRToLLVMAtomicXchgOpLowering::matchAndRewrite(
       op.getSyncScope(), op->getParentOfType<mlir::ModuleOp>());
   // Create the new op first: the forward helpers read `op`, which the
   // replace below erases immediately.
+  std::optional<cir::AlignmentAttr> alignment = adaptor.getAlignment();
   auto xchg = mlir::LLVM::AtomicRMWOp::create(
       rewriter, op.getLoc(), mlir::LLVM::AtomicBinOp::xchg, adaptor.getPtr(),
       adaptor.getVal(), llvmOrder, llvmSyncScope,
-      adaptor.getAlignment().value_or(0), op.getIsVolatile());
+      alignment ? alignment->getAlign() : 0, op.getIsVolatile());
   forwardAMDGPUAtomicOptionMarkers(op, xchg);
   forwardAMDGPUNoPrivateAddrSpace(op, xchg, adaptor.getPtr());
   rewriter.replaceOp(op, xchg);
@@ -1603,10 +1608,11 @@ mlir::LogicalResult CIRToLLVMAtomicTestAndSetOpLowering::matchAndRewrite(
 
   auto one = mlir::LLVM::ConstantOp::create(rewriter, op.getLoc(),
                                             rewriter.getI8Type(), 1);
+  std::optional<cir::AlignmentAttr> alignment = adaptor.getAlignment();
   auto rmw = mlir::LLVM::AtomicRMWOp::create(
       rewriter, op.getLoc(), mlir::LLVM::AtomicBinOp::xchg, adaptor.getPtr(),
       one, llvmOrder, /*syncscope=*/llvm::StringRef(),
-      adaptor.getAlignment().value_or(0), op.getIsVolatile());
+      alignment ? alignment->getAlign() : 0, op.getIsVolatile());
 
   auto zero = mlir::LLVM::ConstantOp::create(rewriter, op.getLoc(),
                                              rewriter.getI8Type(), 0);
@@ -1625,9 +1631,10 @@ mlir::LogicalResult CIRToLLVMAtomicClearOpLowering::matchAndRewrite(
   mlir::LLVM::AtomicOrdering llvmOrder = getLLVMMemOrder(op.getMemOrder());
   auto zero = mlir::LLVM::ConstantOp::create(rewriter, op.getLoc(),
                                              rewriter.getI8Type(), 0);
+  std::optional<cir::AlignmentAttr> alignment = adaptor.getAlignment();
   auto store = mlir::LLVM::StoreOp::create(
       rewriter, op.getLoc(), zero, adaptor.getPtr(),
-      adaptor.getAlignment().value_or(0), op.getIsVolatile(),
+      alignment ? alignment->getAlign() : 0, op.getIsVolatile(),
       /*isNonTemporal=*/false, /*isInvariantGroup=*/false, llvmOrder);
 
   rewriter.replaceOp(op, store);
@@ -1790,9 +1797,10 @@ mlir::LogicalResult CIRToLLVMAtomicFetchOpLowering::matchAndRewrite(
       op.getSyncScope(), op->getParentOfType<mlir::ModuleOp>());
   mlir::LLVM::AtomicBinOp llvmBinOp =
       getLLVMAtomicBinOp(op.getBinop(), isInt, isSignedInt);
+  std::optional<cir::AlignmentAttr> alignment = adaptor.getAlignment();
   auto rmwVal = mlir::LLVM::AtomicRMWOp::create(
       rewriter, op.getLoc(), llvmBinOp, adaptor.getPtr(), adaptor.getVal(),
-      llvmOrder, llvmSyncScope, adaptor.getAlignment().value_or(0),
+      llvmOrder, llvmSyncScope, alignment ? alignment->getAlign() : 0,
       op.getIsVolatile());
 
   forwardAMDGPUAtomicOptionMarkers(op, rmwVal);
@@ -2433,8 +2441,8 @@ mlir::LogicalResult CIRToLLVMAllocaOpLowering::matchAndRewrite(
 
   assert(!cir::MissingFeatures::addressSpace());
 
-  rewriter.replaceOpWithNewOp<mlir::LLVM::AllocaOp>(op, resultTy, elementTy,
-                                                    size, op.getAlignment());
+  rewriter.replaceOpWithNewOp<mlir::LLVM::AllocaOp>(
+      op, resultTy, elementTy, size, op.getAlignmentValue());
 
   return mlir::success();
 }
@@ -2843,12 +2851,20 @@ mlir::LogicalResult CIRToLLVMCopyOpLowering::matchAndRewrite(
   uint64_t srcTypeAlign = cirDataLayout.getTypeLanguageAlignment(
       op.getSrc().getType().getPointee());
 
+  auto getAlignValue = [](std::optional<cir::AlignmentAttr> alignAttr,
+                          uint64_t typeAlign) -> uint64_t {
+    if (alignAttr)
+      return alignAttr->getAlign();
+    return typeAlign;
+  };
   mlir::NamedAttribute dstAlignAttr = rewriter.getNamedAttr(
       mlir::LLVM::LLVMDialect::getAlignAttrName(),
-      rewriter.getI64IntegerAttr(op.getDstAlignment().value_or(dstTypeAlign)));
+      rewriter.getI64IntegerAttr(
+          getAlignValue(op.getDstAlignment(), dstTypeAlign)));
   mlir::NamedAttribute srcAlignAttr = rewriter.getNamedAttr(
       mlir::LLVM::LLVMDialect::getAlignAttrName(),
-      rewriter.getI64IntegerAttr(op.getSrcAlignment().value_or(srcTypeAlign)));
+      rewriter.getI64IntegerAttr(
+          getAlignValue(op.getSrcAlignment(), srcTypeAlign)));
   mlir::ArrayAttr argAttrs = rewriter.getArrayAttr({
       /*dst_attrs=*/rewriter.getDictionaryAttr({dstAlignAttr}),
       /*src_attrs=*/rewriter.getDictionaryAttr({srcAlignAttr}),
@@ -2871,9 +2887,10 @@ mlir::LogicalResult CIRToLLVMLoadOpLowering::matchAndRewrite(
   if (!llvmTy)
     return emitTypeConversionError(op, op.getType());
   mlir::LLVM::AtomicOrdering ordering = getLLVMMemOrder(op.getMemOrder());
-  std::optional<size_t> opAlign = op.getAlignment();
-  unsigned alignment = (unsigned)opAlign.value_or(
-      getMemoryFallbackAlignment(op, op.getType(), llvmTy, dataLayout));
+  std::optional<cir::AlignmentAttr> opAlign = op.getAlignment();
+  unsigned alignment = opAlign ? opAlign->getAlign()
+                               : getMemoryFallbackAlignment(op, op.getType(),
+                                                            llvmTy, dataLayout);
 
   assert(!cir::MissingFeatures::lowerModeOptLevel());
 
@@ -2908,9 +2925,9 @@ cir::direct::CIRToLLVMVecMaskedLoadOpLowering::matchAndRewrite(
            << "NYI: lowering masked load of a type with no memory "
               "representation";
 
-  std::optional<size_t> opAlign = op.getAlignment();
+  std::optional<cir::AlignmentAttr> opAlign = op.getAlignment();
   unsigned alignment =
-      (unsigned)opAlign.value_or(dataLayout.getTypeABIAlignment(llvmResTy));
+      opAlign ? opAlign->getAlign() : dataLayout.getTypeABIAlignment(llvmResTy);
 
   auto newLoad = mlir::LLVM::MaskedLoadOp::create(
       rewriter, op.getLoc(), llvmResTy, adaptor.getAddr(), adaptor.getMask(),
@@ -2930,9 +2947,10 @@ mlir::LogicalResult CIRToLLVMStoreOpLowering::matchAndRewrite(
   if (!llvmTy)
     return op.emitError()
            << "NYI: lowering store of a type with no memory representation";
-  std::optional<size_t> opAlign = op.getAlignment();
-  unsigned alignment = (unsigned)opAlign.value_or(
-      getMemoryFallbackAlignment(op, valueType, llvmTy, dataLayout));
+  std::optional<cir::AlignmentAttr> opAlign = op.getAlignment();
+  unsigned alignment =
+      opAlign ? opAlign->getAlign()
+              : getMemoryFallbackAlignment(op, valueType, llvmTy, dataLayout);
 
   assert(!cir::MissingFeatures::lowerModeOptLevel());
 
@@ -3433,7 +3451,9 @@ mlir::LogicalResult CIRToLLVMFuncOpLowering::matchAndRewrite(
   fn.setVisibility_(
       lowerCIRVisibilityToLLVMVisibility(op.getGlobalVisibility()));
 
-  fn.setAlignment(op.getAlignment());
+  std::optional<cir::AlignmentAttr> alignment = op.getAlignment();
+  fn.setAlignment(alignment ? std::optional<uint64_t>(alignment->getAlign())
+                            : std::nullopt);
   assert(!MissingFeatures::opFuncPreferredAlignment());
 
   symbolTables.getSymbolTable(modOp).remove(op);
@@ -3559,7 +3579,7 @@ CIRToLLVMGlobalOpLowering::setupRegionInitializedLLVMGlobalOp(
   bool isDsoLocal = op.getDsoLocal();
   mlir::LLVM::ThreadLocalMode threadLocalMode =
       convertTlsModelAttrToLLVM(op.getTlsModelAttr());
-  uint64_t alignment = op.getAlignment().value_or(0);
+  const uint64_t alignment = op.getAlignmentValue();
   mlir::LLVM::Linkage linkage = convertLinkage(op.getLinkage());
   std::string symbol = op.getSymName().str();
 
@@ -3929,7 +3949,7 @@ mlir::LogicalResult CIRToLLVMGlobalOpLowering::matchAndRewrite(
   const bool isDsoLocal = op.getDsoLocal();
   mlir::LLVM::ThreadLocalMode threadLocalMode =
       convertTlsModelAttrToLLVM(op.getTlsModelAttr());
-  const uint64_t alignment = op.getAlignment().value_or(0);
+  const uint64_t alignment = op.getAlignmentValue();
   const mlir::LLVM::Linkage linkage = convertLinkage(op.getLinkage());
   const StringRef symbol = op.getSymName();
   SmallVector<mlir::NamedAttribute> attributes =
@@ -7432,8 +7452,8 @@ mlir::LogicalResult CIRToLLVMSetBitfieldOpLowering::matchAndRewrite(
     assert(storageSize > size && "Invalid bitfield size.");
 
     mlir::Value val = mlir::LLVM::LoadOp::create(
-        rewriter, op.getLoc(), intType, adaptor.getAddr(), op.getAlignment(),
-        op.getIsVolatile());
+        rewriter, op.getLoc(), intType, adaptor.getAddr(),
+        op.getAlignmentValue(), op.getIsVolatile());
 
     srcVal =
         createAnd(rewriter, srcVal, llvm::APInt::getLowBitsSet(srcWidth, size));
@@ -7449,7 +7469,7 @@ mlir::LogicalResult CIRToLLVMSetBitfieldOpLowering::matchAndRewrite(
   }
 
   mlir::LLVM::StoreOp::create(rewriter, op.getLoc(), srcVal, adaptor.getAddr(),
-                              op.getAlignment(), op.getIsVolatile());
+                              op.getAlignmentValue(), op.getIsVolatile());
 
   mlir::Type resultTy = getTypeConverter()->convertType(op.getType());
 
@@ -7527,7 +7547,7 @@ mlir::LogicalResult CIRToLLVMGetBitfieldOpLowering::matchAndRewrite(
       computeBitfieldIntType(storageType, context, storageSize);
 
   mlir::Value val = mlir::LLVM::LoadOp::create(
-      rewriter, op.getLoc(), intType, adaptor.getAddr(), op.getAlignment(),
+      rewriter, op.getLoc(), intType, adaptor.getAddr(), op.getAlignmentValue(),
       op.getIsVolatile());
   val = mlir::LLVM::BitcastOp::create(rewriter, op.getLoc(), intType, val);
 
@@ -7942,7 +7962,7 @@ mlir::LogicalResult CIRToLLVMClearPaddingOpLowering::matchAndRewrite(
 
   mlir::Value inputPtr = adaptor.getArg();
   for (mlir::Attribute attr : op.getPadding())
-    clearPadding(rewriter, op.getLoc(), inputPtr, op.getAlignment(),
+    clearPadding(rewriter, op.getLoc(), inputPtr, op.getAlignmentValue(),
                  cast<cir::OffsetPairAttr>(attr));
 
   rewriter.eraseOp(op);
diff --git a/clang/test/CIR/IR/func.cir b/clang/test/CIR/IR/func.cir
index 680de0f58c9bd5..0d720e227e4441 100644
--- a/clang/test/CIR/IR/func.cir
+++ b/clang/test/CIR/IR/func.cir
@@ -214,24 +214,24 @@ cir.func @has_attrs() attributes {foo, baz = 5, floof = "flop"} {
 // CHECK:   cir.return
 // CHECK: }
 
-cir.func alignment(3) @has_alignment() {
+cir.func alignment(2) @has_alignment() {
   cir.return
 }
-// CHECK: cir.func alignment(3) @has_alignment() {
+// CHECK: cir.func alignment(2) @has_alignment() {
 // CHECK:   cir.return
 // CHECK: }
 
-cir.func comdat alignment(3) @has_alignment2() {
+cir.func comdat alignment(2) @has_alignment2() {
   cir.return
 }
-// CHECK: cir.func comdat alignment(3) @has_alignment2() {
+// CHECK: cir.func comdat alignment(2) @has_alignment2() {
 // CHECK:   cir.return
 // CHECK: }
 
-cir.func comdat alignment(3) preferred_alignment(4) @has_alignment3() {
+cir.func comdat alignment(2) preferred_alignment(4) @has_alignment3() {
   cir.return
 }
-// CHECK: cir.func comdat alignment(3) preferred_alignment(4) @has_alignment3() {
+// CHECK: cir.func comdat alignment(2) preferred_alignment(4) @has_alignment3() {
 // CHECK:   cir.return
 // CHECK: }
 
diff --git a/clang/test/CIR/IR/invalid-alignment.cir b/clang/test/CIR/IR/invalid-alignment.cir
new file mode 100644
index 00000000000000..a48ec5f6700da5
--- /dev/null
+++ b/clang/test/CIR/IR/invalid-alignment.cir
@@ -0,0 +1,23 @@
+// RUN: cir-opt %s --split-input-file -verify-diagnostics
+
+// Test that the alignment attribute verifier rejects values that are not
+// positive powers of 2. Zero is rejected too: "alignment unspecified" is
+// represented by the absence of the attribute, never by a zero alignment.
+
+module {
+  cir.func @bad_zero() {
+    // expected-error @below {{alignment has to be a positive power of 2}}
+    %0 = cir.alloca "x" align(0) : !cir.ptr<!s32i>
+    cir.return
+  }
+}
+
+// -----
+
+module {
+  cir.func @bad_non_pow2() {
+    // expected-error @below {{alignment has to be a positive power of 2}}
+    %0 = cir.alloca "x" align(3) : !cir.ptr<!s32i>
+    cir.return
+  }
+}
diff --git a/clang/unittests/CIR/PointerLikeTest.cpp b/clang/unittests/CIR/PointerLikeTest.cpp
index 01707738a4c00a..0152d8e07f738f 100644
--- a/clang/unittests/CIR/PointerLikeTest.cpp
+++ b/clang/unittests/CIR/PointerLikeTest.cpp
@@ -46,11 +46,11 @@ class CIROpenACCPointerLikeTest : public ::testing::Test {
   Location loc;
   llvm::StringMap<unsigned> recordNames;
 
-  mlir::IntegerAttr getAlignOne(mlir::MLIRContext *ctx) {
+  cir::AlignmentAttr getAlignOne(mlir::MLIRContext *ctx) {
     // Note that mlir::IntegerType is used instead of cir::IntType here because
     // we don't need sign information for this to be useful, so keep it simple.
     clang::CharUnits align = clang::CharUnits::One();
-    return b.getI64IntegerAttr(align.getQuantity());
+    return cir::AlignmentAttr::getOrEmpty(b.getContext(), align.getQuantity());
   }
 
   mlir::StringAttr getUniqueRecordName(const std::string &baseName) {



More information about the cfe-commits mailing list