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