[llvm] Enhance chapter 03 for Kaleidoscope (PR #149718)

via llvm-commits llvm-commits at lists.llvm.org
Sun Jul 20 09:13:45 PDT 2025


https://github.com/Aneureka created https://github.com/llvm/llvm-project/pull/149718

None

>From fe2e8fc241c79c8d4a69bcac3700ac35dce4e5d7 Mon Sep 17 00:00:00 2001
From: Aneureka <aneureka2 at gmail.com>
Date: Mon, 21 Jul 2025 00:09:31 +0800
Subject: [PATCH] Enhance chapter 03 for Kaleidoscope

---
 llvm/examples/Kaleidoscope/Chapter3/toy.cpp | 26 +++++++++++++++++++--
 1 file changed, 24 insertions(+), 2 deletions(-)

diff --git a/llvm/examples/Kaleidoscope/Chapter3/toy.cpp b/llvm/examples/Kaleidoscope/Chapter3/toy.cpp
index 03563006685ad..f243117e85214 100644
--- a/llvm/examples/Kaleidoscope/Chapter3/toy.cpp
+++ b/llvm/examples/Kaleidoscope/Chapter3/toy.cpp
@@ -165,6 +165,8 @@ class PrototypeAST {
 
   Function *codegen();
   const std::string &getName() const { return Name; }
+
+  const std::vector<std::string> &getArgs() const { return Args; }
 };
 
 /// FunctionAST - This class represents a function definition itself.
@@ -383,7 +385,7 @@ static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
   if (auto E = ParseExpression()) {
     // Make an anonymous proto.
     auto Proto = std::make_unique<PrototypeAST>("__anon_expr",
-                                                 std::vector<std::string>());
+                                                std::vector<std::string>());
     return std::make_unique<FunctionAST>(std::move(Proto), std::move(E));
   }
   return nullptr;
@@ -484,8 +486,28 @@ Function *FunctionAST::codegen() {
   // First, check for an existing function from a previous 'extern' declaration.
   Function *TheFunction = TheModule->getFunction(Proto->getName());
 
-  if (!TheFunction)
+  if (TheFunction && !TheFunction->empty()) {
+    fprintf(stderr, "Error: Function '%s' redefined.\n",
+            TheFunction->getName().str().c_str());
+    return nullptr;
+  }
+
+  if (!TheFunction) {
     TheFunction = Proto->codegen();
+  } else {
+    if (TheFunction->arg_size() != Proto->getArgs().size()) {
+      fprintf(stderr,
+              "Error: Function '%s' redefined with different number of "
+              "arguments.\n",
+              TheFunction->getName().str().c_str());
+      return nullptr;
+    }
+
+    size_t ArgIdx = 0ul;
+    for (auto &FArg : TheFunction->args()) {
+      FArg.setName(Proto->getArgs()[ArgIdx++]);
+    }
+  }
 
   if (!TheFunction)
     return nullptr;



More information about the llvm-commits mailing list