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 142 uint64_t LLVMContext::getDiagnosticsHotnessThreshold() const { 143 return pImpl->DiagnosticsHotnessThreshold.getValueOr(UINT64_MAX); 144 } 145 146 bool LLVMContext::isDiagnosticsHotnessThresholdSetFromPSI() const { 147 return !pImpl->DiagnosticsHotnessThreshold.hasValue(); 148 } 149 150 remarks::RemarkStreamer *LLVMContext::getMainRemarkStreamer() { 151 return pImpl->MainRemarkStreamer.get(); 152 } 153 const remarks::RemarkStreamer *LLVMContext::getMainRemarkStreamer() const { 154 return const_cast<LLVMContext *>(this)->getMainRemarkStreamer(); 155 } 156 void LLVMContext::setMainRemarkStreamer( 157 std::unique_ptr<remarks::RemarkStreamer> RemarkStreamer) { 158 pImpl->MainRemarkStreamer = std::move(RemarkStreamer); 159 } 160 161 LLVMRemarkStreamer *LLVMContext::getLLVMRemarkStreamer() { 162 return pImpl->LLVMRS.get(); 163 } 164 const LLVMRemarkStreamer *LLVMContext::getLLVMRemarkStreamer() const { 165 return const_cast<LLVMContext *>(this)->getLLVMRemarkStreamer(); 166 } 167 void LLVMContext::setLLVMRemarkStreamer( 168 std::unique_ptr<LLVMRemarkStreamer> RemarkStreamer) { 169 pImpl->LLVMRS = std::move(RemarkStreamer); 170 } 171 172 DiagnosticHandler::DiagnosticHandlerTy 173 LLVMContext::getDiagnosticHandlerCallBack() const { 174 return pImpl->DiagHandler->DiagHandlerCallback; 175 } 176 177 void *LLVMContext::getDiagnosticContext() const { 178 return pImpl->DiagHandler->DiagnosticContext; 179 } 180 181 void LLVMContext::setYieldCallback(YieldCallbackTy Callback, void *OpaqueHandle) 182 { 183 pImpl->YieldCallback = Callback; 184 pImpl->YieldOpaqueHandle = OpaqueHandle; 185 } 186 187 void LLVMContext::yield() { 188 if (pImpl->YieldCallback) 189 pImpl->YieldCallback(this, pImpl->YieldOpaqueHandle); 190 } 191 192 void LLVMContext::emitError(const Twine &ErrorStr) { 193 diagnose(DiagnosticInfoInlineAsm(ErrorStr)); 194 } 195 196 void LLVMContext::emitError(const Instruction *I, const Twine &ErrorStr) { 197 assert (I && "Invalid instruction"); 198 diagnose(DiagnosticInfoInlineAsm(*I, ErrorStr)); 199 } 200 201 static bool isDiagnosticEnabled(const DiagnosticInfo &DI) { 202 // Optimization remarks are selective. They need to check whether the regexp 203 // pattern, passed via one of the -pass-remarks* flags, matches the name of 204 // the pass that is emitting the diagnostic. If there is no match, ignore the 205 // diagnostic and return. 206 // 207 // Also noisy remarks are only enabled if we have hotness information to sort 208 // them. 209 if (auto *Remark = dyn_cast<DiagnosticInfoOptimizationBase>(&DI)) 210 return Remark->isEnabled() && 211 (!Remark->isVerbose() || Remark->getHotness()); 212 213 return true; 214 } 215 216 const char * 217 LLVMContext::getDiagnosticMessagePrefix(DiagnosticSeverity Severity) { 218 switch (Severity) { 219 case DS_Error: 220 return "error"; 221 case DS_Warning: 222 return "warning"; 223 case DS_Remark: 224 return "remark"; 225 case DS_Note: 226 return "note"; 227 } 228 llvm_unreachable("Unknown DiagnosticSeverity"); 229 } 230 231 void LLVMContext::diagnose(const DiagnosticInfo &DI) { 232 if (auto *OptDiagBase = dyn_cast<DiagnosticInfoOptimizationBase>(&DI)) 233 if (LLVMRemarkStreamer *RS = getLLVMRemarkStreamer()) 234 RS->emit(*OptDiagBase); 235 236 // If there is a report handler, use it. 237 if (pImpl->DiagHandler && 238 (!pImpl->RespectDiagnosticFilters || isDiagnosticEnabled(DI)) && 239 pImpl->DiagHandler->handleDiagnostics(DI)) 240 return; 241 242 if (!isDiagnosticEnabled(DI)) 243 return; 244 245 // Otherwise, print the message with a prefix based on the severity. 246 DiagnosticPrinterRawOStream DP(errs()); 247 errs() << getDiagnosticMessagePrefix(DI.getSeverity()) << ": "; 248 DI.print(DP); 249 errs() << "\n"; 250 if (DI.getSeverity() == DS_Error) 251 exit(1); 252 } 253 254 void LLVMContext::emitError(uint64_t LocCookie, const Twine &ErrorStr) { 255 diagnose(DiagnosticInfoInlineAsm(LocCookie, ErrorStr)); 256 } 257 258 //===----------------------------------------------------------------------===// 259 // Metadata Kind Uniquing 260 //===----------------------------------------------------------------------===// 261 262 /// Return a unique non-zero ID for the specified metadata kind. 263 unsigned LLVMContext::getMDKindID(StringRef Name) const { 264 // If this is new, assign it its ID. 265 return pImpl->CustomMDKindNames.insert( 266 std::make_pair( 267 Name, pImpl->CustomMDKindNames.size())) 268 .first->second; 269 } 270 271 /// getHandlerNames - Populate client-supplied smallvector using custom 272 /// metadata name and ID. 273 void LLVMContext::getMDKindNames(SmallVectorImpl<StringRef> &Names) const { 274 Names.resize(pImpl->CustomMDKindNames.size()); 275 for (StringMap<unsigned>::const_iterator I = pImpl->CustomMDKindNames.begin(), 276 E = pImpl->CustomMDKindNames.end(); I != E; ++I) 277 Names[I->second] = I->first(); 278 } 279 280 void LLVMContext::getOperandBundleTags(SmallVectorImpl<StringRef> &Tags) const { 281 pImpl->getOperandBundleTags(Tags); 282 } 283 284 StringMapEntry<uint32_t> * 285 LLVMContext::getOrInsertBundleTag(StringRef TagName) const { 286 return pImpl->getOrInsertBundleTag(TagName); 287 } 288 289 uint32_t LLVMContext::getOperandBundleTagID(StringRef Tag) const { 290 return pImpl->getOperandBundleTagID(Tag); 291 } 292 293 SyncScope::ID LLVMContext::getOrInsertSyncScopeID(StringRef SSN) { 294 return pImpl->getOrInsertSyncScopeID(SSN); 295 } 296 297 void LLVMContext::getSyncScopeNames(SmallVectorImpl<StringRef> &SSNs) const { 298 pImpl->getSyncScopeNames(SSNs); 299 } 300 301 void LLVMContext::setGC(const Function &Fn, std::string GCName) { 302 auto It = pImpl->GCNames.find(&Fn); 303 304 if (It == pImpl->GCNames.end()) { 305 pImpl->GCNames.insert(std::make_pair(&Fn, std::move(GCName))); 306 return; 307 } 308 It->second = std::move(GCName); 309 } 310 311 const std::string &LLVMContext::getGC(const Function &Fn) { 312 return pImpl->GCNames[&Fn]; 313 } 314 315 void LLVMContext::deleteGC(const Function &Fn) { 316 pImpl->GCNames.erase(&Fn); 317 } 318 319 bool LLVMContext::shouldDiscardValueNames() const { 320 return pImpl->DiscardValueNames; 321 } 322 323 bool LLVMContext::isODRUniquingDebugTypes() const { return !!pImpl->DITypeMap; } 324 325 void LLVMContext::enableDebugTypeODRUniquing() { 326 if (pImpl->DITypeMap) 327 return; 328 329 pImpl->DITypeMap.emplace(); 330 } 331 332 void LLVMContext::disableDebugTypeODRUniquing() { pImpl->DITypeMap.reset(); } 333 334 void LLVMContext::setDiscardValueNames(bool Discard) { 335 pImpl->DiscardValueNames = Discard; 336 } 337 338 OptPassGate &LLVMContext::getOptPassGate() const { 339 return pImpl->getOptPassGate(); 340 } 341 342 void LLVMContext::setOptPassGate(OptPassGate& OPG) { 343 pImpl->setOptPassGate(OPG); 344 } 345 346 const DiagnosticHandler *LLVMContext::getDiagHandlerPtr() const { 347 return pImpl->DiagHandler.get(); 348 } 349 350 std::unique_ptr<DiagnosticHandler> LLVMContext::getDiagnosticHandler() { 351 return std::move(pImpl->DiagHandler); 352 } 353 354 bool LLVMContext::hasSetOpaquePointersValue() const { 355 return pImpl->hasOpaquePointersValue(); 356 } 357 358 void LLVMContext::setOpaquePointers(bool Enable) const { 359 pImpl->setOpaquePointers(Enable); 360 } 361 362 bool LLVMContext::supportsTypedPointers() const { 363 return !pImpl->getOpaquePointers(); 364 } 365