[llvm] Compute GUIDs once and store in metadata (PR #184065)

Mircea Trofin via llvm-commits llvm-commits at lists.llvm.org
Sat Mar 7 17:19:22 PST 2026


================
@@ -79,6 +79,48 @@ GlobalValue::getGUIDAssumingExternalLinkage(StringRef GlobalIdentifier) {
   return MD5Hash(GlobalIdentifier);
 }
 
+void GlobalValue::assignGUID() {
+  if (getMetadata(LLVMContext::MD_unique_id) != nullptr)
+    return;
+
+  const GUID G =
+      GlobalValue::getGUIDAssumingExternalLinkage(getGlobalIdentifier());
+  setMetadata(
+      LLVMContext::MD_unique_id,
+      MDNode::get(getContext(), {ConstantAsMetadata::get(ConstantInt::get(
+                                    Type::getInt64Ty(getContext()), G))}));
+}
+
+GlobalValue::GUID GlobalValue::getGUID() const {
+  auto MaybeGUID = getGUIDIfAssigned();
+  assert(MaybeGUID.has_value() &&
+         "GUID was not assigned before calling GetGUID()");
+  return *MaybeGUID;
+}
+
+std::optional<GlobalValue::GUID> GlobalValue::getGUIDIfAssigned() const {
+  // First check the metadata.
+  auto *MD = getMetadata(LLVMContext::MD_unique_id);
+  if (MD != nullptr)
+    return cast<ConstantInt>(cast<ConstantAsMetadata>(MD->getOperand(0))
+                                ->getValue()
+                                ->stripPointerCasts())
+        ->getZExtValue();
+
+  // Handle a few special cases where we just want to compute it based on the
+  // current properties.
+  if (isDeclaration() || isa<GlobalAlias>(this) || getName().starts_with("llvm.")) {
----------------
mtrofin wrote:

nit: do we have a "this is an intrinsic" API (so we dont just check if it has .llvm.). Could be a TODO.

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


More information about the llvm-commits mailing list