Skip to content

Cpp 08 errors

Mugundan edited this page Nov 27, 2026 · 1 revision

Errors, Output and Assertions

Relevant source files

The following files were used as context for generating this wiki page:

LLVM is compiled without C++ exceptions, so functions that can fail return their error as a value: llvm::Error when there is nothing else to return, llvm::Expected<T> when there is. For programmer mistakes ("this can never happen") LLVM uses assert and llvm_unreachable instead. For printing it uses raw_ostream rather than iostream. This page shows all three.

Purpose and Scope

This page covers recoverable errors (Error, Expected<T>, createStringError, toString, handleAllErrors, cantFail), programmer errors (assert, llvm_unreachable, report_fatal_error) and output (outs(), errs(), dbgs(), raw_string_ostream).

The Parcel Delivery Analogy

Delivery LLVM
You get either the parcel or a "sorry, we missed you" card Expected<T>: either a T or an Error
You must read the card; you can't just throw it away An Error must be checked or LLVM aborts in debug builds
The van falling off a bridge A bug: assert / llvm_unreachable crash immediately

Two Kinds of Failure

flowchart TD
    F["Something went wrong"] --> Q{"Could correct input cause it?<br/>(bad file, invalid IR, user typo)"}
    Q -->|"yes: recoverable"| E["Return Error / Expected&lt;T&gt;<br/>caller decides what to do"]
    Q -->|"no: a bug in our code"| A["assert(cond && \"msg\")<br/>or llvm_unreachable(\"msg\")"]
Loading

Error and Expected

// example: errors
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;

Expected<int> parseCount(StringRef S) {
  int V;
  if (S.getAsInteger(10, V))                       // returns true on failure
    return createStringError("not a number: '" + S + "'");
  if (V < 0)
    return createStringError("negative count: " + Twine(V));
  return V;                                        // success: implicit Expected<int>
}

Error checkAll(ArrayRef<StringRef> Inputs) {
  for (StringRef In : Inputs) {
    Expected<int> N = parseCount(In);
    if (!N)
      return N.takeError();                        // pass the error up
  }
  return Error::success();
}

int main() {
  for (StringRef In : {"12", "abc", "-4"}) {
    Expected<int> N = parseCount(In);
    if (N)
      outs() << "ok " << *N << "\n";
    else
      outs() << "error: " << toString(N.takeError()) << "\n";
  }
  if (Error E = checkAll({"1", "2", "x"}))
    outs() << "checkAll failed: " << toString(std::move(E)) << "\n";
  int Sure = cantFail(parseCount("7"));            // "this cannot fail"
  outs() << "sure " << Sure << "\n";
}
ok 12
error: not a number: 'abc'
error: negative count: -4
checkAll failed: not a number: 'x'
sure 7
Tool Meaning
Expected<T> Holds a T or an error; if (N) tests success, *N reads the value
N.takeError() Take the error out (to return it or handle it)
Error::success() "No error"
if (Error E = f()) An Error is true when it holds a failure
createStringError(Twine) Make a simple error with a message
toString(Error) Consume the error and get its message
handleAllErrors(E, handlers...) Dispatch on error type
logAllUnhandledErrors(E, errs(), "prefix: ") Print and consume
cantFail(X) Assert X succeeded and unwrap it
flowchart LR
    C["Expected&lt;int&gt; N = parseCount(s)"] --> T{"if (N)"}
    T -->|"true"| V["use *N"]
    T -->|"false"| E["N.takeError()"]
    E --> H1["return it upward"]
    E --> H2["toString / log it"]
Loading

The checked rule. Every Error must be looked at before it is destroyed, and every Expected checked before use. In builds with LLVM's ABI-breaking checks (debug builds by default) forgetting this aborts with "Program aborted due to an unhandled Error". This catches ignored failures early.

Sources: llvm/include/llvm/Support/Error.h:159, llvm/include/llvm/Support/Error.h:485, llvm/include/llvm/Support/Error.h:769, llvm/include/llvm/Support/Error.h:1013, llvm/include/llvm/Support/Error.h:1088, llvm/include/llvm/Support/Error.h:1339

Programmer Errors: assert and llvm_unreachable

// illustrative
assert(Idx < Ops.size() && "operand index out of range");   // message as a string literal

switch (Kind) {
case SK_Circle: return area(cast<Circle>(S));
case SK_Square: return area(cast<Square>(S));
}
llvm_unreachable("unknown shape kind");                       // after a fully covered switch
Tool When it fires In release builds
assert(cond && "msg") cond is false Removed (NDEBUG)
llvm_unreachable("msg") Control reaches it Becomes an optimisation hint; reaching it is UB
report_fatal_error("msg") Always Always prints and exits; for unrecoverable user-facing problems in tools

Many LLVM developers build with -DLLVM_ENABLE_ASSERTIONS=ON while developing so these checks run; release compilers usually ship without them.

Sources: llvm/include/llvm/Support/ErrorHandling.h:164-171

Output: raw_ostream

// example: output
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Format.h"
#include <string>
using namespace llvm;

int main() {
  outs() << "count " << 42 << ", hex " << format_hex(255, 6) << "\n";
  std::string Buf;
  raw_string_ostream OS(Buf);            // write into a std::string
  OS << "inst" << 3;
  outs() << "built '" << OS.str() << "'\n";
  outs().indent(4) << "indented\n";
}
count 42, hex 0x00ff
built 'inst3'
    indented
Stream Goes to Use
outs() stdout Normal tool output
errs() stderr, unbuffered Warnings, errors
dbgs() stderr, only with -debug Debug traces inside LLVM_DEBUG(...)
raw_string_ostream A std::string Building text
raw_fd_ostream A file Writing output files

Every IR object can print itself: errs() << *I << "\n"; prints an instruction, F.print(errs()) a function, and I->dump() (in assertion builds) prints to stderr from a debugger.

// illustrative: debug output that only appears with -debug-only=my-pass
#define DEBUG_TYPE "my-pass"
LLVM_DEBUG(dbgs() << "visiting " << *I << "\n");

Sources: llvm/include/llvm/Support/raw_ostream.h:53, llvm/include/llvm/Support/raw_ostream.h:613-620, llvm/include/llvm/Support/raw_ostream.h:664

Common Traps

  • Ignoring an Error or Expected return: aborts in debug builds.
  • Reading *N without checking if (N) first.
  • Side effects inside assert(...): they disappear in release builds.
  • Using std::cout in LLVM library code; use raw_ostream.

Key Points

  • Recoverable failures return Error / Expected<T>, which must always be checked.
  • Bugs are caught with assert(cond && "msg") and llvm_unreachable.
  • Print with outs(), errs(), dbgs(); every IR object can be streamed with <<.

Start here

Computer Organization & Architecture

Hexagon ISA

Operating Systems

C++ for LLVM Development

LLVM IR

SelectionDAG

Backend Assignments

Target Bring-up

Calling Conventions

Frame Lowering

MC Layer

Register Allocation

Scheduling

Clone this wiki locally