1 //===-- LLVMContext.cpp - Implement LLVMContext ---------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements LLVMContext, as a wrapper around the opaque
11 //  class LLVMContextImpl.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/IR/LLVMContext.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 "LLVMContextImpl.h"
21 #include "llvm/IR/DiagnosticInfo.h"
22 #include "llvm/IR/DiagnosticPrinter.h"
23 #include "llvm/IR/Metadata.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/Support/Casting.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include <cassert>
29 #include <cstdlib>
30 #include <string>
31 #include <utility>
32 
33 using namespace llvm;
34 
35 LLVMContext::LLVMContext() : pImpl(new LLVMContextImpl(*this)) {
36   // Create the fixed metadata kinds. This is done in the same order as the
37   // MD_* enum values so that they correspond.
38 
39   // Create the 'dbg' metadata kind.
40   unsigned DbgID = getMDKindID("dbg");
41   assert(DbgID == MD_dbg && "dbg kind id drifted"); (void)DbgID;
42 
43   // Create the 'tbaa' metadata kind.
44   unsigned TBAAID = getMDKindID("tbaa");
45   assert(TBAAID == MD_tbaa && "tbaa kind id drifted"); (void)TBAAID;
46 
47   // Create the 'prof' metadata kind.
48   unsigned ProfID = getMDKindID("prof");
49   assert(ProfID == MD_prof && "prof kind id drifted"); (void)ProfID;
50 
51   // Create the 'fpmath' metadata kind.
52   unsigned FPAccuracyID = getMDKindID("fpmath");
53   assert(FPAccuracyID == MD_fpmath && "fpmath kind id drifted");
54   (void)FPAccuracyID;
55 
56   // Create the 'range' metadata kind.
57   unsigned RangeID = getMDKindID("range");
58   assert(RangeID == MD_range && "range kind id drifted");
59   (void)RangeID;
60 
61   // Create the 'tbaa.struct' metadata kind.
62   unsigned TBAAStructID = getMDKindID("tbaa.struct");
63   assert(TBAAStructID == MD_tbaa_struct && "tbaa.struct kind id drifted");
64   (void)TBAAStructID;
65 
66   // Create the 'invariant.load' metadata kind.
67   unsigned InvariantLdId = getMDKindID("invariant.load");
68   assert(InvariantLdId == MD_invariant_load && "invariant.load kind id drifted");
69   (void)InvariantLdId;
70 
71   // Create the 'alias.scope' metadata kind.
72   unsigned AliasScopeID = getMDKindID("alias.scope");
73   assert(AliasScopeID == MD_alias_scope && "alias.scope kind id drifted");
74   (void)AliasScopeID;
75 
76   // Create the 'noalias' metadata kind.
77   unsigned NoAliasID = getMDKindID("noalias");
78   assert(NoAliasID == MD_noalias && "noalias kind id drifted");
79   (void)NoAliasID;
80 
81   // Create the 'nontemporal' metadata kind.
82   unsigned NonTemporalID = getMDKindID("nontemporal");
83   assert(NonTemporalID == MD_nontemporal && "nontemporal kind id drifted");
84   (void)NonTemporalID;
85 
86   // Create the 'llvm.mem.parallel_loop_access' metadata kind.
87   unsigned MemParallelLoopAccessID = getMDKindID("llvm.mem.parallel_loop_access");
88   assert(MemParallelLoopAccessID == MD_mem_parallel_loop_access &&
89          "mem_parallel_loop_access kind id drifted");
90   (void)MemParallelLoopAccessID;
91 
92   // Create the 'nonnull' metadata kind.
93   unsigned NonNullID = getMDKindID("nonnull");
94   assert(NonNullID == MD_nonnull && "nonnull kind id drifted");
95   (void)NonNullID;
96 
97   // Create the 'dereferenceable' metadata kind.
98   unsigned DereferenceableID = getMDKindID("dereferenceable");
99   assert(DereferenceableID == MD_dereferenceable &&
100          "dereferenceable kind id drifted");
101   (void)DereferenceableID;
102 
103   // Create the 'dereferenceable_or_null' metadata kind.
104   unsigned DereferenceableOrNullID = getMDKindID("dereferenceable_or_null");
105   assert(DereferenceableOrNullID == MD_dereferenceable_or_null &&
106          "dereferenceable_or_null kind id drifted");
107   (void)DereferenceableOrNullID;
108 
109   // Create the 'make.implicit' metadata kind.
110   unsigned MakeImplicitID = getMDKindID("make.implicit");
111   assert(MakeImplicitID == MD_make_implicit &&
112          "make.implicit kind id drifted");
113   (void)MakeImplicitID;
114 
115   // Create the 'unpredictable' metadata kind.
116   unsigned UnpredictableID = getMDKindID("unpredictable");
117   assert(UnpredictableID == MD_unpredictable &&
118          "unpredictable kind id drifted");
119   (void)UnpredictableID;
120 
121   // Create the 'invariant.group' metadata kind.
122   unsigned InvariantGroupId = getMDKindID("invariant.group");
123   assert(InvariantGroupId == MD_invariant_group &&
124          "invariant.group kind id drifted");
125   (void)InvariantGroupId;
126 
127   // Create the 'align' metadata kind.
128   unsigned AlignID = getMDKindID("align");
129   assert(AlignID == MD_align && "align kind id drifted");
130   (void)AlignID;
131 
132   // Create the 'llvm.loop' metadata kind.
133   unsigned LoopID = getMDKindID("llvm.loop");
134   assert(LoopID == MD_loop && "llvm.loop kind id drifted");
135   (void)LoopID;
136 
137   unsigned TypeID = getMDKindID("type");
138   assert(TypeID == MD_type && "type kind id drifted");
139   (void)TypeID;
140 
141   unsigned SectionPrefixID = getMDKindID("section_prefix");
142   assert(SectionPrefixID == MD_section_prefix &&
143          "section_prefix kind id drifted");
144   (void)SectionPrefixID;
145 
146   auto *DeoptEntry = pImpl->getOrInsertBundleTag("deopt");
147   assert(DeoptEntry->second == LLVMContext::OB_deopt &&
148          "deopt operand bundle id drifted!");
149   (void)DeoptEntry;
150 
151   auto *FuncletEntry = pImpl->getOrInsertBundleTag("funclet");
152   assert(FuncletEntry->second == LLVMContext::OB_funclet &&
153          "funclet operand bundle id drifted!");
154   (void)FuncletEntry;
155 
156   auto *GCTransitionEntry = pImpl->getOrInsertBundleTag("gc-transition");
157   assert(GCTransitionEntry->second == LLVMContext::OB_gc_transition &&
158          "gc-transition operand bundle id drifted!");
159   (void)GCTransitionEntry;
160 }
161 
162 LLVMContext::~LLVMContext() { delete pImpl; }
163 
164 void LLVMContext::addModule(Module *M) {
165   pImpl->OwnedModules.insert(M);
166 }
167 
168 void LLVMContext::removeModule(Module *M) {
169   pImpl->OwnedModules.erase(M);
170 }
171 
172 //===----------------------------------------------------------------------===//
173 // Recoverable Backend Errors
174 //===----------------------------------------------------------------------===//
175 
176 void LLVMContext::
177 setInlineAsmDiagnosticHandler(InlineAsmDiagHandlerTy DiagHandler,
178                               void *DiagContext) {
179   pImpl->InlineAsmDiagHandler = DiagHandler;
180   pImpl->InlineAsmDiagContext = DiagContext;
181 }
182 
183 /// getInlineAsmDiagnosticHandler - Return the diagnostic handler set by
184 /// setInlineAsmDiagnosticHandler.
185 LLVMContext::InlineAsmDiagHandlerTy
186 LLVMContext::getInlineAsmDiagnosticHandler() const {
187   return pImpl->InlineAsmDiagHandler;
188 }
189 
190 /// getInlineAsmDiagnosticContext - Return the diagnostic context set by
191 /// setInlineAsmDiagnosticHandler.
192 void *LLVMContext::getInlineAsmDiagnosticContext() const {
193   return pImpl->InlineAsmDiagContext;
194 }
195 
196 void LLVMContext::setDiagnosticHandler(DiagnosticHandlerTy DiagnosticHandler,
197                                        void *DiagnosticContext,
198                                        bool RespectFilters) {
199   pImpl->DiagnosticHandler = DiagnosticHandler;
200   pImpl->DiagnosticContext = DiagnosticContext;
201   pImpl->RespectDiagnosticFilters = RespectFilters;
202 }
203 
204 void LLVMContext::setDiagnosticHotnessRequested(bool Requested) {
205   pImpl->DiagnosticHotnessRequested = Requested;
206 }
207 bool LLVMContext::getDiagnosticHotnessRequested() const {
208   return pImpl->DiagnosticHotnessRequested;
209 }
210 
211 yaml::Output *LLVMContext::getDiagnosticsOutputFile() {
212   return pImpl->DiagnosticsOutputFile.get();
213 }
214 
215 void LLVMContext::setDiagnosticsOutputFile(yaml::Output *F) {
216   pImpl->DiagnosticsOutputFile.reset(F);
217 }
218 
219 LLVMContext::DiagnosticHandlerTy LLVMContext::getDiagnosticHandler() const {
220   return pImpl->DiagnosticHandler;
221 }
222 
223 void *LLVMContext::getDiagnosticContext() const {
224   return pImpl->DiagnosticContext;
225 }
226 
227 void LLVMContext::setYieldCallback(YieldCallbackTy Callback, void *OpaqueHandle)
228 {
229   pImpl->YieldCallback = Callback;
230   pImpl->YieldOpaqueHandle = OpaqueHandle;
231 }
232 
233 void LLVMContext::yield() {
234   if (pImpl->YieldCallback)
235     pImpl->YieldCallback(this, pImpl->YieldOpaqueHandle);
236 }
237 
238 void LLVMContext::emitError(const Twine &ErrorStr) {
239   diagnose(DiagnosticInfoInlineAsm(ErrorStr));
240 }
241 
242 void LLVMContext::emitError(const Instruction *I, const Twine &ErrorStr) {
243   assert (I && "Invalid instruction");
244   diagnose(DiagnosticInfoInlineAsm(*I, ErrorStr));
245 }
246 
247 static bool isDiagnosticEnabled(const DiagnosticInfo &DI) {
248   // Optimization remarks are selective. They need to check whether the regexp
249   // pattern, passed via one of the -pass-remarks* flags, matches the name of
250   // the pass that is emitting the diagnostic. If there is no match, ignore the
251   // diagnostic and return.
252   if (auto *Remark = dyn_cast<DiagnosticInfoOptimizationBase>(&DI))
253     return Remark->isEnabled();
254 
255   return true;
256 }
257 
258 const char *
259 LLVMContext::getDiagnosticMessagePrefix(DiagnosticSeverity Severity) {
260   switch (Severity) {
261   case DS_Error:
262     return "error";
263   case DS_Warning:
264     return "warning";
265   case DS_Remark:
266     return "remark";
267   case DS_Note:
268     return "note";
269   }
270   llvm_unreachable("Unknown DiagnosticSeverity");
271 }
272 
273 void LLVMContext::diagnose(const DiagnosticInfo &DI) {
274   // If there is a report handler, use it.
275   if (pImpl->DiagnosticHandler) {
276     if (!pImpl->RespectDiagnosticFilters || isDiagnosticEnabled(DI))
277       pImpl->DiagnosticHandler(DI, pImpl->DiagnosticContext);
278     return;
279   }
280 
281   if (!isDiagnosticEnabled(DI))
282     return;
283 
284   // Otherwise, print the message with a prefix based on the severity.
285   DiagnosticPrinterRawOStream DP(errs());
286   errs() << getDiagnosticMessagePrefix(DI.getSeverity()) << ": ";
287   DI.print(DP);
288   errs() << "\n";
289   if (DI.getSeverity() == DS_Error)
290     exit(1);
291 }
292 
293 void LLVMContext::emitError(unsigned LocCookie, const Twine &ErrorStr) {
294   diagnose(DiagnosticInfoInlineAsm(LocCookie, ErrorStr));
295 }
296 
297 //===----------------------------------------------------------------------===//
298 // Metadata Kind Uniquing
299 //===----------------------------------------------------------------------===//
300 
301 /// Return a unique non-zero ID for the specified metadata kind.
302 unsigned LLVMContext::getMDKindID(StringRef Name) const {
303   // If this is new, assign it its ID.
304   return pImpl->CustomMDKindNames.insert(
305                                      std::make_pair(
306                                          Name, pImpl->CustomMDKindNames.size()))
307       .first->second;
308 }
309 
310 /// getHandlerNames - Populate client-supplied smallvector using custom
311 /// metadata name and ID.
312 void LLVMContext::getMDKindNames(SmallVectorImpl<StringRef> &Names) const {
313   Names.resize(pImpl->CustomMDKindNames.size());
314   for (StringMap<unsigned>::const_iterator I = pImpl->CustomMDKindNames.begin(),
315        E = pImpl->CustomMDKindNames.end(); I != E; ++I)
316     Names[I->second] = I->first();
317 }
318 
319 void LLVMContext::getOperandBundleTags(SmallVectorImpl<StringRef> &Tags) const {
320   pImpl->getOperandBundleTags(Tags);
321 }
322 
323 uint32_t LLVMContext::getOperandBundleTagID(StringRef Tag) const {
324   return pImpl->getOperandBundleTagID(Tag);
325 }
326 
327 void LLVMContext::setGC(const Function &Fn, std::string GCName) {
328   auto It = pImpl->GCNames.find(&Fn);
329 
330   if (It == pImpl->GCNames.end()) {
331     pImpl->GCNames.insert(std::make_pair(&Fn, std::move(GCName)));
332     return;
333   }
334   It->second = std::move(GCName);
335 }
336 
337 const std::string &LLVMContext::getGC(const Function &Fn) {
338   return pImpl->GCNames[&Fn];
339 }
340 
341 void LLVMContext::deleteGC(const Function &Fn) {
342   pImpl->GCNames.erase(&Fn);
343 }
344 
345 bool LLVMContext::shouldDiscardValueNames() const {
346   return pImpl->DiscardValueNames;
347 }
348 
349 bool LLVMContext::isODRUniquingDebugTypes() const { return !!pImpl->DITypeMap; }
350 
351 void LLVMContext::enableDebugTypeODRUniquing() {
352   if (pImpl->DITypeMap)
353     return;
354 
355   pImpl->DITypeMap.emplace();
356 }
357 
358 void LLVMContext::disableDebugTypeODRUniquing() { pImpl->DITypeMap.reset(); }
359 
360 void LLVMContext::setDiscardValueNames(bool Discard) {
361   pImpl->DiscardValueNames = Discard;
362 }
363 
364 OptBisect &LLVMContext::getOptBisect() {
365   return pImpl->getOptBisect();
366 }
367