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