1 //===-- diagnostic.cpp - tool for testing libLLVM and llvm-c API ----------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements the --test-diagnostic-handler command in llvm-c-test.
11 // This command uses the C API to read a module with a custom diagnostic
12 // handler set to test the diagnostic handler functionality.
14 //===----------------------------------------------------------------------===//
16 #include "llvm-c-test.h"
17 #include "llvm-c/BitReader.h"
18 #include "llvm-c/Core.h"
22 static void diagnosticHandler(LLVMDiagnosticInfoRef DI
, void *C
) {
23 fprintf(stderr
, "Executing diagnostic handler\n");
25 fprintf(stderr
, "Diagnostic severity is of type ");
26 switch (LLVMGetDiagInfoSeverity(DI
)) {
28 fprintf(stderr
, "error");
31 fprintf(stderr
, "warning");
34 fprintf(stderr
, "remark");
37 fprintf(stderr
, "note");
40 fprintf(stderr
, "\n");
45 static int handlerCalled
= 0;
47 int llvm_test_diagnostic_handler(void) {
48 LLVMContextRef C
= LLVMGetGlobalContext();
49 LLVMContextSetDiagnosticHandler(C
, diagnosticHandler
, &handlerCalled
);
51 if (LLVMContextGetDiagnosticHandler(C
) != diagnosticHandler
) {
52 fprintf(stderr
, "LLVMContext{Set,Get}DiagnosticHandler failed\n");
56 int *DC
= (int *)LLVMContextGetDiagnosticContext(C
);
57 if (DC
!= &handlerCalled
|| *DC
) {
58 fprintf(stderr
, "LLVMContextGetDiagnosticContext failed\n");
62 LLVMMemoryBufferRef MB
;
64 if (LLVMCreateMemoryBufferWithSTDIN(&MB
, &msg
)) {
65 fprintf(stderr
, "Error reading file: %s\n", msg
);
66 LLVMDisposeMessage(msg
);
72 int Ret
= LLVMGetBitcodeModule2(MB
, &M
);
74 // We do not return if the bitcode was invalid, as we want to test whether
75 // the diagnostic handler was executed.
76 fprintf(stderr
, "Error parsing bitcode: %s\n", msg
);
79 LLVMDisposeMemoryBuffer(MB
);
82 fprintf(stderr
, "Diagnostic handler was called while loading module\n");
84 fprintf(stderr
, "Diagnostic handler was not called while loading module\n");