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
191DiagnosticHandler::DiagnosticHandlerTy
192LLVMContext::getDiagnosticHandlerCallBack() const {
193 return pImpl->DiagHandler->DiagHandlerCallback;
194}
195
196void *LLVMContext::getDiagnosticContext() const {
197 return pImpl->DiagHandler->DiagnosticContext;
198}
199
200void LLVMContext::setYieldCallback(YieldCallbackTy Callback, void *OpaqueHandle)
201{
202 pImpl->YieldCallback = Callback;
203 pImpl->YieldOpaqueHandle = OpaqueHandle;
204}
205
206void LLVMContext::yield() {
207 if (pImpl->YieldCallback)
208 pImpl->YieldCallback(this, pImpl->YieldOpaqueHandle);
209}
210
211void LLVMContext::emitError(const Twine &ErrorStr) {
212 diagnose(DI: DiagnosticInfoGeneric(ErrorStr));
213}
214
215void LLVMContext::emitError(const Instruction *I, const Twine &ErrorStr) {
216 assert(I && "Invalid instruction");
217 diagnose(DI: DiagnosticInfoGeneric(I, ErrorStr));
218}
219
220static bool isDiagnosticEnabled(const DiagnosticInfo &DI) {
221 // Optimization remarks are selective. They need to check whether the regexp
222 // pattern, passed via one of the -pass-remarks* flags, matches the name of
223 // the pass that is emitting the diagnostic. If there is no match, ignore the
224 // diagnostic and return.
225 //
226 // Also noisy remarks are only enabled if we have hotness information to sort
227 // them.
228 if (auto *Remark = dyn_cast<DiagnosticInfoOptimizationBase>(Val: &DI))
229 return Remark->isEnabled() &&
230 (!Remark->isVerbose() || Remark->getHotness());
231
232 return true;
233}
234
235const char *
236LLVMContext::getDiagnosticMessagePrefix(DiagnosticSeverity Severity) {
237 switch (Severity) {
238 case DS_Error:
239 return "error";
240 case DS_Warning:
241 return "warning";
242 case DS_Remark:
243 return "remark";
244 case DS_Note:
245 return "note";
246 }
247 llvm_unreachable("Unknown DiagnosticSeverity");
248}
249
250void LLVMContext::diagnose(const DiagnosticInfo &DI) {
251 if (auto *OptDiagBase = dyn_cast<DiagnosticInfoOptimizationBase>(Val: &DI))
252 if (LLVMRemarkStreamer *RS = getLLVMRemarkStreamer())
253 RS->emit(Diag: *OptDiagBase);
254
255 // If there is a report handler, use it.
256 if (pImpl->DiagHandler) {
257 if (DI.getSeverity() == DS_Error)
258 pImpl->DiagHandler->HasErrors = true;
259 if ((!pImpl->RespectDiagnosticFilters || isDiagnosticEnabled(DI)) &&
260 pImpl->DiagHandler->handleDiagnostics(DI))
261 return;
262 }
263
264 if (!isDiagnosticEnabled(DI))
265 return;
266
267 // Otherwise, print the message with a prefix based on the severity.
268 DiagnosticPrinterRawOStream DP(errs());
269 errs() << getDiagnosticMessagePrefix(Severity: DI.getSeverity()) << ": ";
270 DI.print(DP);
271 errs() << "\n";
272}
273
274//===----------------------------------------------------------------------===//
275// Metadata Kind Uniquing
276//===----------------------------------------------------------------------===//
277
278/// Return a unique non-zero ID for the specified metadata kind.
279unsigned LLVMContext::getMDKindID(StringRef Name) const {
280 // If this is new, assign it its ID.
281 return pImpl->CustomMDKindNames.insert(
282 KV: std::make_pair(
283 x&: Name, y: pImpl->CustomMDKindNames.size()))
284 .first->second;
285}
286
287/// getHandlerNames - Populate client-supplied smallvector using custom
288/// metadata name and ID.
289void LLVMContext::getMDKindNames(SmallVectorImpl<StringRef> &Names) const {
290 Names.resize(N: pImpl->CustomMDKindNames.size());
291 for (StringMap<unsigned>::const_iterator I = pImpl->CustomMDKindNames.begin(),
292 E = pImpl->CustomMDKindNames.end(); I != E; ++I)
293 Names[I->second] = I->first();
294}
295
296void LLVMContext::getOperandBundleTags(SmallVectorImpl<StringRef> &Tags) const {
297 pImpl->getOperandBundleTags(Tags);
298}
299
300StringMapEntry<uint32_t> *
301LLVMContext::getOrInsertBundleTag(StringRef TagName) const {
302 return pImpl->getOrInsertBundleTag(Tag: TagName);
303}
304
305uint32_t LLVMContext::getOperandBundleTagID(StringRef Tag) const {
306 return pImpl->getOperandBundleTagID(Tag);
307}
308
309SyncScope::ID LLVMContext::getOrInsertSyncScopeID(StringRef SSN) {
310 return pImpl->getOrInsertSyncScopeID(SSN);
311}
312
313void LLVMContext::getSyncScopeNames(SmallVectorImpl<StringRef> &SSNs) const {
314 pImpl->getSyncScopeNames(SSNs);
315}
316
317std::optional<StringRef> LLVMContext::getSyncScopeName(SyncScope::ID Id) const {
318 return pImpl->getSyncScopeName(Id);
319}
320
321void LLVMContext::setGC(const Function &Fn, std::string GCName) {
322 pImpl->GCNames[&Fn] = std::move(GCName);
323}
324
325const std::string &LLVMContext::getGC(const Function &Fn) {
326 return pImpl->GCNames[&Fn];
327}
328
329void LLVMContext::deleteGC(const Function &Fn) {
330 pImpl->GCNames.erase(Val: &Fn);
331}
332
333bool LLVMContext::shouldDiscardValueNames() const {
334 return pImpl->DiscardValueNames;
335}
336
337bool LLVMContext::isODRUniquingDebugTypes() const { return !!pImpl->DITypeMap; }
338
339void LLVMContext::enableDebugTypeODRUniquing() {
340 if (pImpl->DITypeMap)
341 return;
342
343 pImpl->DITypeMap.emplace();
344}
345
346void LLVMContext::disableDebugTypeODRUniquing() { pImpl->DITypeMap.reset(); }
347
348void LLVMContext::setDiscardValueNames(bool Discard) {
349 pImpl->DiscardValueNames = Discard;
350}
351
352OptPassGate &LLVMContext::getOptPassGate() const {
353 return pImpl->getOptPassGate();
354}
355
356void LLVMContext::setOptPassGate(OptPassGate& OPG) {
357 pImpl->setOptPassGate(OPG);
358}
359
360const DiagnosticHandler *LLVMContext::getDiagHandlerPtr() const {
361 return pImpl->DiagHandler.get();
362}
363
364std::unique_ptr<DiagnosticHandler> LLVMContext::getDiagnosticHandler() {
365 return std::move(pImpl->DiagHandler);
366}
367
368StringRef LLVMContext::getDefaultTargetCPU() {
369 return pImpl->DefaultTargetCPU;
370}
371
372void LLVMContext::setDefaultTargetCPU(StringRef CPU) {
373 pImpl->DefaultTargetCPU = CPU;
374}
375
376StringRef LLVMContext::getDefaultTargetFeatures() {
377 return pImpl->DefaultTargetFeatures;
378}
379
380void LLVMContext::setDefaultTargetFeatures(StringRef Features) {
381 pImpl->DefaultTargetFeatures = Features;
382}
383
384void LLVMContext::updateDILocationAtomGroupWaterline(uint64_t V) {
385 pImpl->NextAtomGroup = std::max(a: pImpl->NextAtomGroup, b: V);
386}
387
388uint64_t LLVMContext::incNextDILocationAtomGroup() {
389 return pImpl->NextAtomGroup++;
390}
391