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 "LLVMContextImpl.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/DebugLoc.h"
19 #include "llvm/IR/DiagnosticInfo.h"
20 #include "llvm/IR/DiagnosticPrinter.h"
21 #include "llvm/IR/Instruction.h"
22 #include "llvm/IR/Metadata.h"
23 #include "llvm/Support/ManagedStatic.h"
24 #include "llvm/Support/SourceMgr.h"
25 #include <cctype>
26 using namespace llvm;
27 
28 static ManagedStatic<LLVMContext> GlobalContext;
29 
getGlobalContext()30 LLVMContext& llvm::getGlobalContext() {
31   return *GlobalContext;
32 }
33 
LLVMContext()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 
38   // Create the 'dbg' metadata kind.
39   unsigned DbgID = getMDKindID("dbg");
40   assert(DbgID == MD_dbg && "dbg kind id drifted"); (void)DbgID;
41 
42   // Create the 'tbaa' metadata kind.
43   unsigned TBAAID = getMDKindID("tbaa");
44   assert(TBAAID == MD_tbaa && "tbaa kind id drifted"); (void)TBAAID;
45 
46   // Create the 'prof' metadata kind.
47   unsigned ProfID = getMDKindID("prof");
48   assert(ProfID == MD_prof && "prof kind id drifted"); (void)ProfID;
49 
50   // Create the 'fpmath' metadata kind.
51   unsigned FPAccuracyID = getMDKindID("fpmath");
52   assert(FPAccuracyID == MD_fpmath && "fpmath kind id drifted");
53   (void)FPAccuracyID;
54 
55   // Create the 'range' metadata kind.
56   unsigned RangeID = getMDKindID("range");
57   assert(RangeID == MD_range && "range kind id drifted");
58   (void)RangeID;
59 
60   // Create the 'tbaa.struct' metadata kind.
61   unsigned TBAAStructID = getMDKindID("tbaa.struct");
62   assert(TBAAStructID == MD_tbaa_struct && "tbaa.struct kind id drifted");
63   (void)TBAAStructID;
64 
65   // Create the 'invariant.load' metadata kind.
66   unsigned InvariantLdId = getMDKindID("invariant.load");
67   assert(InvariantLdId == MD_invariant_load && "invariant.load kind id drifted");
68   (void)InvariantLdId;
69 
70   // Create the 'alias.scope' metadata kind.
71   unsigned AliasScopeID = getMDKindID("alias.scope");
72   assert(AliasScopeID == MD_alias_scope && "alias.scope kind id drifted");
73   (void)AliasScopeID;
74 
75   // Create the 'noalias' metadata kind.
76   unsigned NoAliasID = getMDKindID("noalias");
77   assert(NoAliasID == MD_noalias && "noalias kind id drifted");
78   (void)NoAliasID;
79 
80   // Create the 'nontemporal' metadata kind.
81   unsigned NonTemporalID = getMDKindID("nontemporal");
82   assert(NonTemporalID == MD_nontemporal && "nontemporal kind id drifted");
83   (void)NonTemporalID;
84 
85   // Create the 'llvm.mem.parallel_loop_access' metadata kind.
86   unsigned MemParallelLoopAccessID = getMDKindID("llvm.mem.parallel_loop_access");
87   assert(MemParallelLoopAccessID == MD_mem_parallel_loop_access &&
88          "mem_parallel_loop_access kind id drifted");
89   (void)MemParallelLoopAccessID;
90 
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 }
~LLVMContext()97 LLVMContext::~LLVMContext() { delete pImpl; }
98 
addModule(Module * M)99 void LLVMContext::addModule(Module *M) {
100   pImpl->OwnedModules.insert(M);
101 }
102 
removeModule(Module * M)103 void LLVMContext::removeModule(Module *M) {
104   pImpl->OwnedModules.erase(M);
105 }
106 
107 //===----------------------------------------------------------------------===//
108 // Recoverable Backend Errors
109 //===----------------------------------------------------------------------===//
110 
111 void LLVMContext::
setInlineAsmDiagnosticHandler(InlineAsmDiagHandlerTy DiagHandler,void * DiagContext)112 setInlineAsmDiagnosticHandler(InlineAsmDiagHandlerTy DiagHandler,
113                               void *DiagContext) {
114   pImpl->InlineAsmDiagHandler = DiagHandler;
115   pImpl->InlineAsmDiagContext = DiagContext;
116 }
117 
118 /// getInlineAsmDiagnosticHandler - Return the diagnostic handler set by
119 /// setInlineAsmDiagnosticHandler.
120 LLVMContext::InlineAsmDiagHandlerTy
getInlineAsmDiagnosticHandler() const121 LLVMContext::getInlineAsmDiagnosticHandler() const {
122   return pImpl->InlineAsmDiagHandler;
123 }
124 
125 /// getInlineAsmDiagnosticContext - Return the diagnostic context set by
126 /// setInlineAsmDiagnosticHandler.
getInlineAsmDiagnosticContext() const127 void *LLVMContext::getInlineAsmDiagnosticContext() const {
128   return pImpl->InlineAsmDiagContext;
129 }
130 
setDiagnosticHandler(DiagnosticHandlerTy DiagnosticHandler,void * DiagnosticContext,bool RespectFilters)131 void LLVMContext::setDiagnosticHandler(DiagnosticHandlerTy DiagnosticHandler,
132                                        void *DiagnosticContext,
133                                        bool RespectFilters) {
134   pImpl->DiagnosticHandler = DiagnosticHandler;
135   pImpl->DiagnosticContext = DiagnosticContext;
136   pImpl->RespectDiagnosticFilters = RespectFilters;
137 }
138 
getDiagnosticHandler() const139 LLVMContext::DiagnosticHandlerTy LLVMContext::getDiagnosticHandler() const {
140   return pImpl->DiagnosticHandler;
141 }
142 
getDiagnosticContext() const143 void *LLVMContext::getDiagnosticContext() const {
144   return pImpl->DiagnosticContext;
145 }
146 
setYieldCallback(YieldCallbackTy Callback,void * OpaqueHandle)147 void LLVMContext::setYieldCallback(YieldCallbackTy Callback, void *OpaqueHandle)
148 {
149   pImpl->YieldCallback = Callback;
150   pImpl->YieldOpaqueHandle = OpaqueHandle;
151 }
152 
yield()153 void LLVMContext::yield() {
154   if (pImpl->YieldCallback)
155     pImpl->YieldCallback(this, pImpl->YieldOpaqueHandle);
156 }
157 
emitError(const Twine & ErrorStr)158 void LLVMContext::emitError(const Twine &ErrorStr) {
159   diagnose(DiagnosticInfoInlineAsm(ErrorStr));
160 }
161 
emitError(const Instruction * I,const Twine & ErrorStr)162 void LLVMContext::emitError(const Instruction *I, const Twine &ErrorStr) {
163   assert (I && "Invalid instruction");
164   diagnose(DiagnosticInfoInlineAsm(*I, ErrorStr));
165 }
166 
isDiagnosticEnabled(const DiagnosticInfo & DI)167 static bool isDiagnosticEnabled(const DiagnosticInfo &DI) {
168   // Optimization remarks are selective. They need to check whether the regexp
169   // pattern, passed via one of the -pass-remarks* flags, matches the name of
170   // the pass that is emitting the diagnostic. If there is no match, ignore the
171   // diagnostic and return.
172   switch (DI.getKind()) {
173   case llvm::DK_OptimizationRemark:
174     if (!cast<DiagnosticInfoOptimizationRemark>(DI).isEnabled())
175       return false;
176     break;
177   case llvm::DK_OptimizationRemarkMissed:
178     if (!cast<DiagnosticInfoOptimizationRemarkMissed>(DI).isEnabled())
179       return false;
180     break;
181   case llvm::DK_OptimizationRemarkAnalysis:
182     if (!cast<DiagnosticInfoOptimizationRemarkAnalysis>(DI).isEnabled())
183       return false;
184     break;
185   default:
186     break;
187   }
188   return true;
189 }
190 
diagnose(const DiagnosticInfo & DI)191 void LLVMContext::diagnose(const DiagnosticInfo &DI) {
192   // If there is a report handler, use it.
193   if (pImpl->DiagnosticHandler) {
194     if (!pImpl->RespectDiagnosticFilters || isDiagnosticEnabled(DI))
195       pImpl->DiagnosticHandler(DI, pImpl->DiagnosticContext);
196     return;
197   }
198 
199   if (!isDiagnosticEnabled(DI))
200     return;
201 
202   // Otherwise, print the message with a prefix based on the severity.
203   std::string MsgStorage;
204   raw_string_ostream Stream(MsgStorage);
205   DiagnosticPrinterRawOStream DP(Stream);
206   DI.print(DP);
207   Stream.flush();
208   switch (DI.getSeverity()) {
209   case DS_Error:
210     errs() << "error: " << MsgStorage << "\n";
211     exit(1);
212   case DS_Warning:
213     errs() << "warning: " << MsgStorage << "\n";
214     break;
215   case DS_Remark:
216     errs() << "remark: " << MsgStorage << "\n";
217     break;
218   case DS_Note:
219     errs() << "note: " << MsgStorage << "\n";
220     break;
221   }
222 }
223 
emitError(unsigned LocCookie,const Twine & ErrorStr)224 void LLVMContext::emitError(unsigned LocCookie, const Twine &ErrorStr) {
225   diagnose(DiagnosticInfoInlineAsm(LocCookie, ErrorStr));
226 }
227 
228 //===----------------------------------------------------------------------===//
229 // Metadata Kind Uniquing
230 //===----------------------------------------------------------------------===//
231 
232 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
getMDKindID(StringRef Name) const233 unsigned LLVMContext::getMDKindID(StringRef Name) const {
234   assert(!std::isdigit(Name.front()) &&
235          "Named metadata may not start with a digit");
236 
237   // If this is new, assign it its ID.
238   return pImpl->CustomMDKindNames.insert(std::make_pair(
239                                              Name,
240                                              pImpl->CustomMDKindNames.size()))
241       .first->second;
242 }
243 
244 /// getHandlerNames - Populate client supplied smallvector using custome
245 /// metadata name and ID.
getMDKindNames(SmallVectorImpl<StringRef> & Names) const246 void LLVMContext::getMDKindNames(SmallVectorImpl<StringRef> &Names) const {
247   Names.resize(pImpl->CustomMDKindNames.size());
248   for (StringMap<unsigned>::const_iterator I = pImpl->CustomMDKindNames.begin(),
249        E = pImpl->CustomMDKindNames.end(); I != E; ++I)
250     Names[I->second] = I->first();
251 }
252