1//===-- LLVMContext.cpp - Implement LLVMContext ---------------------------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements LLVMContext, as a wrapper around the opaque
10// class LLVMContextImpl.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/IR/LLVMContext.h"
15#include "LLVMContextImpl.h"
16#include "llvm/ADT/SmallVector.h"
17#include "llvm/ADT/StringMap.h"
18#include "llvm/ADT/StringRef.h"
19#include "llvm/ADT/Twine.h"
20#include "llvm/IR/DiagnosticInfo.h"
21#include "llvm/IR/DiagnosticPrinter.h"
22#include "llvm/IR/LLVMRemarkStreamer.h"
23#include "llvm/Remarks/RemarkStreamer.h"
24#include "llvm/Support/Casting.h"
25#include "llvm/Support/ErrorHandling.h"
26#include "llvm/Support/raw_ostream.h"
27#include <cassert>
28#include <cstdlib>
29#include <string>
30#include <utility>
31
32using namespace llvm;
33
34static StringRef knownBundleName(unsigned BundleTagID) {
35 switch (BundleTagID) {
36#define ATTR(Name, Str) \
37 case LLVMContext::OB_##Name: \
38 return #Str;
39#include "llvm/IR/BundleAttributes.def"
40 case LLVMContext::OB_deopt:
41 return "deopt";
42 case LLVMContext::OB_funclet:
43 return "funclet";
44 case LLVMContext::OB_gc_transition:
45 return "gc-transition";
46 case LLVMContext::OB_cfguardtarget:
47 return "cfguardtarget";
48 case LLVMContext::OB_preallocated:
49 return "preallocated";
50 case LLVMContext::OB_gc_live:
51 return "gc-live";
52 case LLVMContext::OB_clang_arc_attachedcall:
53 return "clang.arc.attachedcall";
54 case LLVMContext::OB_ptrauth:
55 return "ptrauth";
56 case LLVMContext::OB_kcfi:
57 return "kcfi";
58 case LLVMContext::OB_convergencectrl:
59 return "convergencectrl";
60 case LLVMContext::OB_deactivation_symbol:
61 return "deactivation-symbol";
62 default:
63 llvm_unreachable("unknown bundle id");
64 }
65
66 llvm_unreachable("covered switch");
67}
68
69LLVMContext::LLVMContext() : pImpl(new LLVMContextImpl(*this)) {
70 // Create the fixed metadata kinds. This is done in the same order as the
71 // MD_* enum values so that they correspond.
72 std::pair<unsigned, StringRef> MDKinds[] = {
73#define LLVM_FIXED_MD_KIND(EnumID, Name, Value) {EnumID, Name},
74#include "llvm/IR/FixedMetadataKinds.def"
75#undef LLVM_FIXED_MD_KIND
76 };
77
78 for (auto &MDKind : MDKinds) {
79 unsigned ID = getMDKindID(Name: MDKind.second);
80 assert(ID == MDKind.first && "metadata kind id drifted");
81 (void)ID;
82 }
83
84 for (unsigned BundleTagID = 0; BundleTagID <= LLVMContext::OB_LastBundleID;
85 ++BundleTagID) {
86 [[maybe_unused]] const auto *Entry =
87 pImpl->getOrInsertBundleTag(Tag: knownBundleName(BundleTagID));
88 assert(Entry->second == BundleTagID && "operand bundle id drifted!");
89 }
90
91 SyncScope::ID SingleThreadSSID =
92 pImpl->getOrInsertSyncScopeID(SSN: "singlethread");
93 assert(SingleThreadSSID == SyncScope::SingleThread &&
94 "singlethread synchronization scope ID drifted!");
95 (void)SingleThreadSSID;
96
97 SyncScope::ID SystemSSID =
98 pImpl->getOrInsertSyncScopeID(SSN: "");
99 assert(SystemSSID == SyncScope::System &&
100 "system synchronization scope ID drifted!");
101 (void)SystemSSID;
102}
103
104LLVMContext::~LLVMContext() { delete pImpl; }
105
106void LLVMContext::addModule(Module *M) {
107 pImpl->OwnedModules.insert(Ptr: M);
108}
109
110void LLVMContext::removeModule(Module *M) {
111 pImpl->OwnedModules.erase(Ptr: M);
112 pImpl->MachineFunctionNums.erase(Val: M);
113}
114
115unsigned LLVMContext::generateMachineFunctionNum(Function &F) {
116 Module *M = F.getParent();
117 assert(pImpl->OwnedModules.contains(M) && "Unexpected module!");
118 return pImpl->MachineFunctionNums[M]++;
119}
120
121//===----------------------------------------------------------------------===//
122// Recoverable Backend Errors
123//===----------------------------------------------------------------------===//
124
125void LLVMContext::setDiagnosticHandlerCallBack(
126 DiagnosticHandler::DiagnosticHandlerTy DiagnosticHandler,
127 void *DiagnosticContext, bool RespectFilters) {
128 pImpl->DiagHandler->DiagHandlerCallback = DiagnosticHandler;
129 pImpl->DiagHandler->DiagnosticContext = DiagnosticContext;
130 pImpl->RespectDiagnosticFilters = RespectFilters;
131}
132
133void LLVMContext::setDiagnosticHandler(std::unique_ptr<DiagnosticHandler> &&DH,
134 bool RespectFilters) {
135 pImpl->DiagHandler = std::move(DH);
136 pImpl->RespectDiagnosticFilters = RespectFilters;
137}
138
139void LLVMContext::setDiagnosticsHotnessRequested(bool Requested) {
140 pImpl->DiagnosticsHotnessRequested = Requested;
141}
142bool LLVMContext::getDiagnosticsHotnessRequested() const {
143 return pImpl->DiagnosticsHotnessRequested;
144}
145
146void LLVMContext::setDiagnosticsHotnessThreshold(std::optional<uint64_t> Threshold) {
147 pImpl->DiagnosticsHotnessThreshold = Threshold;
148}
149void LLVMContext::setMisExpectWarningRequested(bool Requested) {
150 pImpl->MisExpectWarningRequested = Requested;
151}
152bool LLVMContext::getMisExpectWarningRequested() const {
153 return pImpl->MisExpectWarningRequested;
154}
155uint64_t LLVMContext::getDiagnosticsHotnessThreshold() const {
156 return pImpl->DiagnosticsHotnessThreshold.value_or(UINT64_MAX);
157}
158void LLVMContext::setDiagnosticsMisExpectTolerance(
159 std::optional<uint32_t> Tolerance) {
160 pImpl->DiagnosticsMisExpectTolerance = Tolerance;
161}
162uint32_t LLVMContext::getDiagnosticsMisExpectTolerance() const {
163 return pImpl->DiagnosticsMisExpectTolerance.value_or(u: 0);
164}
165
166bool LLVMContext::isDiagnosticsHotnessThresholdSetFromPSI() const {
167 return !pImpl->DiagnosticsHotnessThreshold.has_value();
168}
169
170remarks::RemarkStreamer *LLVMContext::getMainRemarkStreamer() {
171 return pImpl->MainRemarkStreamer.get();
172}
173const remarks::RemarkStreamer *LLVMContext::getMainRemarkStreamer() const {
174 return const_cast<LLVMContext *>(this)->getMainRemarkStreamer();
175}
176void LLVMContext::setMainRemarkStreamer(
177 std::unique_ptr<remarks::RemarkStreamer> RemarkStreamer) {
178 pImpl->MainRemarkStreamer = std::move(RemarkStreamer);
179}
180
181LLVMRemarkStreamer *LLVMContext::getLLVMRemarkStreamer() {
182 return pImpl->LLVMRS.get();
183}
184const LLVMRemarkStreamer *LLVMContext::getLLVMRemarkStreamer() const {
185 return const_cast<LLVMContext *>(this)->getLLVMRemarkStreamer();
186}
187void LLVMContext::setLLVMRemarkStreamer(
188 std::unique_ptr<LLVMRemarkStreamer> RemarkStreamer) {
189 pImpl->LLVMRS = std::move(RemarkStreamer);
190}
191
192DiagnosticHandler::DiagnosticHandlerTy
193LLVMContext::getDiagnosticHandlerCallBack() const {
194 return pImpl->DiagHandler->DiagHandlerCallback;
195}
196
197void *LLVMContext::getDiagnosticContext() const {
198 return pImpl->DiagHandler->DiagnosticContext;
199}
200
201void LLVMContext::setYieldCallback(YieldCallbackTy Callback, void *OpaqueHandle)
202{
203 pImpl->YieldCallback = Callback;
204 pImpl->YieldOpaqueHandle = OpaqueHandle;
205}
206
207void LLVMContext::yield() {
208 if (pImpl->YieldCallback)
209 pImpl->YieldCallback(this, pImpl->YieldOpaqueHandle);
210}
211
212void LLVMContext::emitError(const Twine &ErrorStr) {
213 diagnose(DI: DiagnosticInfoGeneric(ErrorStr));
214}
215
216void LLVMContext::emitError(const Instruction *I, const Twine &ErrorStr) {
217 assert(I && "Invalid instruction");
218 diagnose(DI: DiagnosticInfoGeneric(I, ErrorStr));
219}
220
221static bool isDiagnosticEnabled(const DiagnosticInfo &DI) {
222 // Optimization remarks are selective. They need to check whether the regexp
223 // pattern, passed via one of the -pass-remarks* flags, matches the name of
224 // the pass that is emitting the diagnostic. If there is no match, ignore the
225 // diagnostic and return.
226 //
227 // Also noisy remarks are only enabled if we have hotness information to sort
228 // them.
229 if (auto *Remark = dyn_cast<DiagnosticInfoOptimizationBase>(Val: &DI))
230 return Remark->isEnabled() &&
231 (!Remark->isVerbose() || Remark->getHotness());
232
233 return true;
234}
235
236const char *
237LLVMContext::getDiagnosticMessagePrefix(DiagnosticSeverity Severity) {
238 switch (Severity) {
239 case DS_Error:
240 return "error";
241 case DS_Warning:
242 return "warning";
243 case DS_Remark:
244 return "remark";
245 case DS_Note:
246 return "note";
247 }
248 llvm_unreachable("Unknown DiagnosticSeverity");
249}
250
251void LLVMContext::diagnose(const DiagnosticInfo &DI) {
252 if (auto *OptDiagBase = dyn_cast<DiagnosticInfoOptimizationBase>(Val: &DI))
253 if (LLVMRemarkStreamer *RS = getLLVMRemarkStreamer())
254 RS->emit(Diag: *OptDiagBase);
255
256 // If there is a report handler, use it.
257 if (pImpl->DiagHandler) {
258 if (DI.getSeverity() == DS_Error)
259 pImpl->DiagHandler->HasErrors = true;
260 if ((!pImpl->RespectDiagnosticFilters || isDiagnosticEnabled(DI)) &&
261 pImpl->DiagHandler->handleDiagnostics(DI))
262 return;
263 }
264
265 if (!isDiagnosticEnabled(DI))
266 return;
267
268 // Otherwise, print the message with a prefix based on the severity.
269 DiagnosticPrinterRawOStream DP(errs());
270 errs() << getDiagnosticMessagePrefix(Severity: DI.getSeverity()) << ": ";
271 DI.print(DP);
272 errs() << "\n";
273}
274
275//===----------------------------------------------------------------------===//
276// Metadata Kind Uniquing
277//===----------------------------------------------------------------------===//
278
279/// Return a unique non-zero ID for the specified metadata kind.
280unsigned LLVMContext::getMDKindID(StringRef Name) const {
281 // If this is new, assign it its ID.
282 return pImpl->CustomMDKindNames.insert(
283 KV: std::make_pair(
284 x&: Name, y: pImpl->CustomMDKindNames.size()))
285 .first->second;
286}
287
288/// getHandlerNames - Populate client-supplied smallvector using custom
289/// metadata name and ID.
290void LLVMContext::getMDKindNames(SmallVectorImpl<StringRef> &Names) const {
291 Names.resize(N: pImpl->CustomMDKindNames.size());
292 for (StringMap<unsigned>::const_iterator I = pImpl->CustomMDKindNames.begin(),
293 E = pImpl->CustomMDKindNames.end(); I != E; ++I)
294 Names[I->second] = I->first();
295}
296
297void LLVMContext::getOperandBundleTags(SmallVectorImpl<StringRef> &Tags) const {
298 pImpl->getOperandBundleTags(Tags);
299}
300
301StringMapEntry<uint32_t> *
302LLVMContext::getOrInsertBundleTag(StringRef TagName) const {
303 return pImpl->getOrInsertBundleTag(Tag: TagName);
304}
305
306uint32_t LLVMContext::getOperandBundleTagID(StringRef Tag) const {
307 return pImpl->getOperandBundleTagID(Tag);
308}
309
310SyncScope::ID LLVMContext::getOrInsertSyncScopeID(StringRef SSN) {
311 return pImpl->getOrInsertSyncScopeID(SSN);
312}
313
314void LLVMContext::getSyncScopeNames(SmallVectorImpl<StringRef> &SSNs) const {
315 pImpl->getSyncScopeNames(SSNs);
316}
317
318std::optional<StringRef> LLVMContext::getSyncScopeName(SyncScope::ID Id) const {
319 return pImpl->getSyncScopeName(Id);
320}
321
322void LLVMContext::setGC(const Function &Fn, std::string GCName) {
323 pImpl->GCNames[&Fn] = std::move(GCName);
324}
325
326const std::string &LLVMContext::getGC(const Function &Fn) {
327 return pImpl->GCNames[&Fn];
328}
329
330void LLVMContext::deleteGC(const Function &Fn) {
331 pImpl->GCNames.erase(Val: &Fn);
332}
333
334bool LLVMContext::shouldDiscardValueNames() const {
335 return pImpl->DiscardValueNames;
336}
337
338bool LLVMContext::isODRUniquingDebugTypes() const { return !!pImpl->DITypeMap; }
339
340void LLVMContext::enableDebugTypeODRUniquing() {
341 if (pImpl->DITypeMap)
342 return;
343
344 pImpl->DITypeMap.emplace();
345}
346
347void LLVMContext::disableDebugTypeODRUniquing() { pImpl->DITypeMap.reset(); }
348
349void LLVMContext::setDiscardValueNames(bool Discard) {
350 pImpl->DiscardValueNames = Discard;
351}
352
353OptPassGate &LLVMContext::getOptPassGate() const {
354 return pImpl->getOptPassGate();
355}
356
357void LLVMContext::setOptPassGate(OptPassGate& OPG) {
358 pImpl->setOptPassGate(OPG);
359}
360
361const DiagnosticHandler *LLVMContext::getDiagHandlerPtr() const {
362 return pImpl->DiagHandler.get();
363}
364
365std::unique_ptr<DiagnosticHandler> LLVMContext::getDiagnosticHandler() {
366 return std::move(pImpl->DiagHandler);
367}
368
369StringRef LLVMContext::getDefaultTargetCPU() {
370 return pImpl->DefaultTargetCPU;
371}
372
373void LLVMContext::setDefaultTargetCPU(StringRef CPU) {
374 pImpl->DefaultTargetCPU = CPU;
375}
376
377StringRef LLVMContext::getDefaultTargetFeatures() {
378 return pImpl->DefaultTargetFeatures;
379}
380
381void LLVMContext::setDefaultTargetFeatures(StringRef Features) {
382 pImpl->DefaultTargetFeatures = Features;
383}
384
385void LLVMContext::updateDILocationAtomGroupWaterline(uint64_t V) {
386 pImpl->NextAtomGroup = std::max(a: pImpl->NextAtomGroup, b: V);
387}
388
389uint64_t LLVMContext::incNextDILocationAtomGroup() {
390 return pImpl->NextAtomGroup++;
391}
392