Bug Summary

File:llvm/lib/Bitcode/Reader/MetadataLoader.cpp
Warning:line 1093, column 11
1st function call argument is an uninitialized value

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name MetadataLoader.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/build-llvm -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I lib/Bitcode/Reader -I /build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/llvm/lib/Bitcode/Reader -I include -I /build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-01-19-134126-35450-1 -x c++ /build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/llvm/lib/Bitcode/Reader/MetadataLoader.cpp

/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/llvm/lib/Bitcode/Reader/MetadataLoader.cpp

1//===- MetadataLoader.cpp - Internal BitcodeReader implementation ---------===//
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#include "MetadataLoader.h"
10#include "ValueList.h"
11
12#include "llvm/ADT/APFloat.h"
13#include "llvm/ADT/APInt.h"
14#include "llvm/ADT/ArrayRef.h"
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/DenseSet.h"
17#include "llvm/ADT/None.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/SmallString.h"
20#include "llvm/ADT/Statistic.h"
21#include "llvm/ADT/StringRef.h"
22#include "llvm/ADT/Twine.h"
23#include "llvm/Bitcode/BitcodeReader.h"
24#include "llvm/Bitcode/LLVMBitCodes.h"
25#include "llvm/Bitstream/BitstreamReader.h"
26#include "llvm/IR/Argument.h"
27#include "llvm/IR/Attributes.h"
28#include "llvm/IR/AutoUpgrade.h"
29#include "llvm/IR/BasicBlock.h"
30#include "llvm/IR/CallingConv.h"
31#include "llvm/IR/Comdat.h"
32#include "llvm/IR/Constant.h"
33#include "llvm/IR/Constants.h"
34#include "llvm/IR/DebugInfo.h"
35#include "llvm/IR/DebugInfoMetadata.h"
36#include "llvm/IR/DebugLoc.h"
37#include "llvm/IR/DerivedTypes.h"
38#include "llvm/IR/DiagnosticPrinter.h"
39#include "llvm/IR/Function.h"
40#include "llvm/IR/GVMaterializer.h"
41#include "llvm/IR/GlobalAlias.h"
42#include "llvm/IR/GlobalIFunc.h"
43#include "llvm/IR/GlobalObject.h"
44#include "llvm/IR/GlobalValue.h"
45#include "llvm/IR/GlobalVariable.h"
46#include "llvm/IR/InlineAsm.h"
47#include "llvm/IR/InstrTypes.h"
48#include "llvm/IR/Instruction.h"
49#include "llvm/IR/Instructions.h"
50#include "llvm/IR/IntrinsicInst.h"
51#include "llvm/IR/Intrinsics.h"
52#include "llvm/IR/LLVMContext.h"
53#include "llvm/IR/Module.h"
54#include "llvm/IR/ModuleSummaryIndex.h"
55#include "llvm/IR/OperandTraits.h"
56#include "llvm/IR/TrackingMDRef.h"
57#include "llvm/IR/Type.h"
58#include "llvm/IR/ValueHandle.h"
59#include "llvm/Support/AtomicOrdering.h"
60#include "llvm/Support/Casting.h"
61#include "llvm/Support/CommandLine.h"
62#include "llvm/Support/Compiler.h"
63#include "llvm/Support/Debug.h"
64#include "llvm/Support/ErrorHandling.h"
65#include "llvm/Support/ManagedStatic.h"
66#include "llvm/Support/MemoryBuffer.h"
67#include "llvm/Support/raw_ostream.h"
68#include <algorithm>
69#include <cassert>
70#include <cstddef>
71#include <cstdint>
72#include <deque>
73#include <limits>
74#include <map>
75#include <string>
76#include <system_error>
77#include <tuple>
78#include <utility>
79#include <vector>
80
81using namespace llvm;
82
83#define DEBUG_TYPE"bitcode-reader" "bitcode-reader"
84
85STATISTIC(NumMDStringLoaded, "Number of MDStrings loaded")static llvm::Statistic NumMDStringLoaded = {"bitcode-reader",
"NumMDStringLoaded", "Number of MDStrings loaded"}
;
86STATISTIC(NumMDNodeTemporary, "Number of MDNode::Temporary created")static llvm::Statistic NumMDNodeTemporary = {"bitcode-reader"
, "NumMDNodeTemporary", "Number of MDNode::Temporary created"
}
;
87STATISTIC(NumMDRecordLoaded, "Number of Metadata records loaded")static llvm::Statistic NumMDRecordLoaded = {"bitcode-reader",
"NumMDRecordLoaded", "Number of Metadata records loaded"}
;
88
89/// Flag whether we need to import full type definitions for ThinLTO.
90/// Currently needed for Darwin and LLDB.
91static cl::opt<bool> ImportFullTypeDefinitions(
92 "import-full-type-definitions", cl::init(false), cl::Hidden,
93 cl::desc("Import full type definitions for ThinLTO."));
94
95static cl::opt<bool> DisableLazyLoading(
96 "disable-ondemand-mds-loading", cl::init(false), cl::Hidden,
97 cl::desc("Force disable the lazy-loading on-demand of metadata when "
98 "loading bitcode for importing."));
99
100namespace {
101
102static int64_t unrotateSign(uint64_t U) { return (U & 1) ? ~(U >> 1) : U >> 1; }
103
104class BitcodeReaderMetadataList {
105 /// Array of metadata references.
106 ///
107 /// Don't use std::vector here. Some versions of libc++ copy (instead of
108 /// move) on resize, and TrackingMDRef is very expensive to copy.
109 SmallVector<TrackingMDRef, 1> MetadataPtrs;
110
111 /// The set of indices in MetadataPtrs above of forward references that were
112 /// generated.
113 SmallDenseSet<unsigned, 1> ForwardReference;
114
115 /// The set of indices in MetadataPtrs above of Metadata that need to be
116 /// resolved.
117 SmallDenseSet<unsigned, 1> UnresolvedNodes;
118
119 /// Structures for resolving old type refs.
120 struct {
121 SmallDenseMap<MDString *, TempMDTuple, 1> Unknown;
122 SmallDenseMap<MDString *, DICompositeType *, 1> Final;
123 SmallDenseMap<MDString *, DICompositeType *, 1> FwdDecls;
124 SmallVector<std::pair<TrackingMDRef, TempMDTuple>, 1> Arrays;
125 } OldTypeRefs;
126
127 LLVMContext &Context;
128
129 /// Maximum number of valid references. Forward references exceeding the
130 /// maximum must be invalid.
131 unsigned RefsUpperBound;
132
133public:
134 BitcodeReaderMetadataList(LLVMContext &C, size_t RefsUpperBound)
135 : Context(C),
136 RefsUpperBound(std::min((size_t)std::numeric_limits<unsigned>::max(),
137 RefsUpperBound)) {}
138
139 // vector compatibility methods
140 unsigned size() const { return MetadataPtrs.size(); }
141 void resize(unsigned N) { MetadataPtrs.resize(N); }
142 void push_back(Metadata *MD) { MetadataPtrs.emplace_back(MD); }
143 void clear() { MetadataPtrs.clear(); }
144 Metadata *back() const { return MetadataPtrs.back(); }
145 void pop_back() { MetadataPtrs.pop_back(); }
146 bool empty() const { return MetadataPtrs.empty(); }
147
148 Metadata *operator[](unsigned i) const {
149 assert(i < MetadataPtrs.size())(static_cast <bool> (i < MetadataPtrs.size()) ? void
(0) : __assert_fail ("i < MetadataPtrs.size()", "llvm/lib/Bitcode/Reader/MetadataLoader.cpp"
, 149, __extension__ __PRETTY_FUNCTION__))
;
150 return MetadataPtrs[i];
151 }
152
153 Metadata *lookup(unsigned I) const {
154 if (I < MetadataPtrs.size())
31
Taking false branch
155 return MetadataPtrs[I];
156 return nullptr;
32
Returning null pointer, which participates in a condition later
157 }
158
159 void shrinkTo(unsigned N) {
160 assert(N <= size() && "Invalid shrinkTo request!")(static_cast <bool> (N <= size() && "Invalid shrinkTo request!"
) ? void (0) : __assert_fail ("N <= size() && \"Invalid shrinkTo request!\""
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 160, __extension__
__PRETTY_FUNCTION__))
;
161 assert(ForwardReference.empty() && "Unexpected forward refs")(static_cast <bool> (ForwardReference.empty() &&
"Unexpected forward refs") ? void (0) : __assert_fail ("ForwardReference.empty() && \"Unexpected forward refs\""
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 161, __extension__
__PRETTY_FUNCTION__))
;
162 assert(UnresolvedNodes.empty() && "Unexpected unresolved node")(static_cast <bool> (UnresolvedNodes.empty() &&
"Unexpected unresolved node") ? void (0) : __assert_fail ("UnresolvedNodes.empty() && \"Unexpected unresolved node\""
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 162, __extension__
__PRETTY_FUNCTION__))
;
163 MetadataPtrs.resize(N);
164 }
165
166 /// Return the given metadata, creating a replaceable forward reference if
167 /// necessary.
168 Metadata *getMetadataFwdRef(unsigned Idx);
169
170 /// Return the given metadata only if it is fully resolved.
171 ///
172 /// Gives the same result as \a lookup(), unless \a MDNode::isResolved()
173 /// would give \c false.
174 Metadata *getMetadataIfResolved(unsigned Idx);
175
176 MDNode *getMDNodeFwdRefOrNull(unsigned Idx);
177 void assignValue(Metadata *MD, unsigned Idx);
178 void tryToResolveCycles();
179 bool hasFwdRefs() const { return !ForwardReference.empty(); }
180 int getNextFwdRef() {
181 assert(hasFwdRefs())(static_cast <bool> (hasFwdRefs()) ? void (0) : __assert_fail
("hasFwdRefs()", "llvm/lib/Bitcode/Reader/MetadataLoader.cpp"
, 181, __extension__ __PRETTY_FUNCTION__))
;
182 return *ForwardReference.begin();
183 }
184
185 /// Upgrade a type that had an MDString reference.
186 void addTypeRef(MDString &UUID, DICompositeType &CT);
187
188 /// Upgrade a type that had an MDString reference.
189 Metadata *upgradeTypeRef(Metadata *MaybeUUID);
190
191 /// Upgrade a type ref array that may have MDString references.
192 Metadata *upgradeTypeRefArray(Metadata *MaybeTuple);
193
194private:
195 Metadata *resolveTypeRefArray(Metadata *MaybeTuple);
196};
197
198void BitcodeReaderMetadataList::assignValue(Metadata *MD, unsigned Idx) {
199 if (auto *MDN = dyn_cast<MDNode>(MD))
200 if (!MDN->isResolved())
201 UnresolvedNodes.insert(Idx);
202
203 if (Idx == size()) {
204 push_back(MD);
205 return;
206 }
207
208 if (Idx >= size())
209 resize(Idx + 1);
210
211 TrackingMDRef &OldMD = MetadataPtrs[Idx];
212 if (!OldMD) {
213 OldMD.reset(MD);
214 return;
215 }
216
217 // If there was a forward reference to this value, replace it.
218 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
219 PrevMD->replaceAllUsesWith(MD);
220 ForwardReference.erase(Idx);
221}
222
223Metadata *BitcodeReaderMetadataList::getMetadataFwdRef(unsigned Idx) {
224 // Bail out for a clearly invalid value.
225 if (Idx >= RefsUpperBound)
226 return nullptr;
227
228 if (Idx >= size())
229 resize(Idx + 1);
230
231 if (Metadata *MD = MetadataPtrs[Idx])
232 return MD;
233
234 // Track forward refs to be resolved later.
235 ForwardReference.insert(Idx);
236
237 // Create and return a placeholder, which will later be RAUW'd.
238 ++NumMDNodeTemporary;
239 Metadata *MD = MDNode::getTemporary(Context, None).release();
240 MetadataPtrs[Idx].reset(MD);
241 return MD;
242}
243
244Metadata *BitcodeReaderMetadataList::getMetadataIfResolved(unsigned Idx) {
245 Metadata *MD = lookup(Idx);
246 if (auto *N = dyn_cast_or_null<MDNode>(MD))
247 if (!N->isResolved())
248 return nullptr;
249 return MD;
250}
251
252MDNode *BitcodeReaderMetadataList::getMDNodeFwdRefOrNull(unsigned Idx) {
253 return dyn_cast_or_null<MDNode>(getMetadataFwdRef(Idx));
254}
255
256void BitcodeReaderMetadataList::tryToResolveCycles() {
257 if (!ForwardReference.empty())
258 // Still forward references... can't resolve cycles.
259 return;
260
261 // Give up on finding a full definition for any forward decls that remain.
262 for (const auto &Ref : OldTypeRefs.FwdDecls)
263 OldTypeRefs.Final.insert(Ref);
264 OldTypeRefs.FwdDecls.clear();
265
266 // Upgrade from old type ref arrays. In strange cases, this could add to
267 // OldTypeRefs.Unknown.
268 for (const auto &Array : OldTypeRefs.Arrays)
269 Array.second->replaceAllUsesWith(resolveTypeRefArray(Array.first.get()));
270 OldTypeRefs.Arrays.clear();
271
272 // Replace old string-based type refs with the resolved node, if possible.
273 // If we haven't seen the node, leave it to the verifier to complain about
274 // the invalid string reference.
275 for (const auto &Ref : OldTypeRefs.Unknown) {
276 if (DICompositeType *CT = OldTypeRefs.Final.lookup(Ref.first))
277 Ref.second->replaceAllUsesWith(CT);
278 else
279 Ref.second->replaceAllUsesWith(Ref.first);
280 }
281 OldTypeRefs.Unknown.clear();
282
283 if (UnresolvedNodes.empty())
284 // Nothing to do.
285 return;
286
287 // Resolve any cycles.
288 for (unsigned I : UnresolvedNodes) {
289 auto &MD = MetadataPtrs[I];
290 auto *N = dyn_cast_or_null<MDNode>(MD);
291 if (!N)
292 continue;
293
294 assert(!N->isTemporary() && "Unexpected forward reference")(static_cast <bool> (!N->isTemporary() && "Unexpected forward reference"
) ? void (0) : __assert_fail ("!N->isTemporary() && \"Unexpected forward reference\""
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 294, __extension__
__PRETTY_FUNCTION__))
;
295 N->resolveCycles();
296 }
297
298 // Make sure we return early again until there's another unresolved ref.
299 UnresolvedNodes.clear();
300}
301
302void BitcodeReaderMetadataList::addTypeRef(MDString &UUID,
303 DICompositeType &CT) {
304 assert(CT.getRawIdentifier() == &UUID && "Mismatched UUID")(static_cast <bool> (CT.getRawIdentifier() == &UUID
&& "Mismatched UUID") ? void (0) : __assert_fail ("CT.getRawIdentifier() == &UUID && \"Mismatched UUID\""
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 304, __extension__
__PRETTY_FUNCTION__))
;
305 if (CT.isForwardDecl())
306 OldTypeRefs.FwdDecls.insert(std::make_pair(&UUID, &CT));
307 else
308 OldTypeRefs.Final.insert(std::make_pair(&UUID, &CT));
309}
310
311Metadata *BitcodeReaderMetadataList::upgradeTypeRef(Metadata *MaybeUUID) {
312 auto *UUID = dyn_cast_or_null<MDString>(MaybeUUID);
313 if (LLVM_LIKELY(!UUID)__builtin_expect((bool)(!UUID), true))
314 return MaybeUUID;
315
316 if (auto *CT = OldTypeRefs.Final.lookup(UUID))
317 return CT;
318
319 auto &Ref = OldTypeRefs.Unknown[UUID];
320 if (!Ref)
321 Ref = MDNode::getTemporary(Context, None);
322 return Ref.get();
323}
324
325Metadata *BitcodeReaderMetadataList::upgradeTypeRefArray(Metadata *MaybeTuple) {
326 auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
327 if (!Tuple || Tuple->isDistinct())
328 return MaybeTuple;
329
330 // Look through the array immediately if possible.
331 if (!Tuple->isTemporary())
332 return resolveTypeRefArray(Tuple);
333
334 // Create and return a placeholder to use for now. Eventually
335 // resolveTypeRefArrays() will be resolve this forward reference.
336 OldTypeRefs.Arrays.emplace_back(
337 std::piecewise_construct, std::forward_as_tuple(Tuple),
338 std::forward_as_tuple(MDTuple::getTemporary(Context, None)));
339 return OldTypeRefs.Arrays.back().second.get();
340}
341
342Metadata *BitcodeReaderMetadataList::resolveTypeRefArray(Metadata *MaybeTuple) {
343 auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
344 if (!Tuple || Tuple->isDistinct())
345 return MaybeTuple;
346
347 // Look through the DITypeRefArray, upgrading each DIType *.
348 SmallVector<Metadata *, 32> Ops;
349 Ops.reserve(Tuple->getNumOperands());
350 for (Metadata *MD : Tuple->operands())
351 Ops.push_back(upgradeTypeRef(MD));
352
353 return MDTuple::get(Context, Ops);
354}
355
356namespace {
357
358class PlaceholderQueue {
359 // Placeholders would thrash around when moved, so store in a std::deque
360 // instead of some sort of vector.
361 std::deque<DistinctMDOperandPlaceholder> PHs;
362
363public:
364 ~PlaceholderQueue() {
365 assert(empty() &&(static_cast <bool> (empty() && "PlaceholderQueue hasn't been flushed before being destroyed"
) ? void (0) : __assert_fail ("empty() && \"PlaceholderQueue hasn't been flushed before being destroyed\""
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 366, __extension__
__PRETTY_FUNCTION__))
366 "PlaceholderQueue hasn't been flushed before being destroyed")(static_cast <bool> (empty() && "PlaceholderQueue hasn't been flushed before being destroyed"
) ? void (0) : __assert_fail ("empty() && \"PlaceholderQueue hasn't been flushed before being destroyed\""
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 366, __extension__
__PRETTY_FUNCTION__))
;
367 }
368 bool empty() const { return PHs.empty(); }
369 DistinctMDOperandPlaceholder &getPlaceholderOp(unsigned ID);
370 void flush(BitcodeReaderMetadataList &MetadataList);
371
372 /// Return the list of temporaries nodes in the queue, these need to be
373 /// loaded before we can flush the queue.
374 void getTemporaries(BitcodeReaderMetadataList &MetadataList,
375 DenseSet<unsigned> &Temporaries) {
376 for (auto &PH : PHs) {
377 auto ID = PH.getID();
378 auto *MD = MetadataList.lookup(ID);
379 if (!MD) {
380 Temporaries.insert(ID);
381 continue;
382 }
383 auto *N = dyn_cast_or_null<MDNode>(MD);
384 if (N && N->isTemporary())
385 Temporaries.insert(ID);
386 }
387 }
388};
389
390} // end anonymous namespace
391
392DistinctMDOperandPlaceholder &PlaceholderQueue::getPlaceholderOp(unsigned ID) {
393 PHs.emplace_back(ID);
394 return PHs.back();
395}
396
397void PlaceholderQueue::flush(BitcodeReaderMetadataList &MetadataList) {
398 while (!PHs.empty()) {
399 auto *MD = MetadataList.lookup(PHs.front().getID());
400 assert(MD && "Flushing placeholder on unassigned MD")(static_cast <bool> (MD && "Flushing placeholder on unassigned MD"
) ? void (0) : __assert_fail ("MD && \"Flushing placeholder on unassigned MD\""
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 400, __extension__
__PRETTY_FUNCTION__))
;
401#ifndef NDEBUG
402 if (auto *MDN = dyn_cast<MDNode>(MD))
403 assert(MDN->isResolved() &&(static_cast <bool> (MDN->isResolved() && "Flushing Placeholder while cycles aren't resolved"
) ? void (0) : __assert_fail ("MDN->isResolved() && \"Flushing Placeholder while cycles aren't resolved\""
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 404, __extension__
__PRETTY_FUNCTION__))
404 "Flushing Placeholder while cycles aren't resolved")(static_cast <bool> (MDN->isResolved() && "Flushing Placeholder while cycles aren't resolved"
) ? void (0) : __assert_fail ("MDN->isResolved() && \"Flushing Placeholder while cycles aren't resolved\""
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 404, __extension__
__PRETTY_FUNCTION__))
;
405#endif
406 PHs.front().replaceUseWith(MD);
407 PHs.pop_front();
408 }
409}
410
411} // anonymous namespace
412
413static Error error(const Twine &Message) {
414 return make_error<StringError>(
415 Message, make_error_code(BitcodeError::CorruptedBitcode));
416}
417
418class MetadataLoader::MetadataLoaderImpl {
419 BitcodeReaderMetadataList MetadataList;
420 BitcodeReaderValueList &ValueList;
421 BitstreamCursor &Stream;
422 LLVMContext &Context;
423 Module &TheModule;
424 std::function<Type *(unsigned)> getTypeByID;
425
426 /// Cursor associated with the lazy-loading of Metadata. This is the easy way
427 /// to keep around the right "context" (Abbrev list) to be able to jump in
428 /// the middle of the metadata block and load any record.
429 BitstreamCursor IndexCursor;
430
431 /// Index that keeps track of MDString values.
432 std::vector<StringRef> MDStringRef;
433
434 /// On-demand loading of a single MDString. Requires the index above to be
435 /// populated.
436 MDString *lazyLoadOneMDString(unsigned Idx);
437
438 /// Index that keeps track of where to find a metadata record in the stream.
439 std::vector<uint64_t> GlobalMetadataBitPosIndex;
440
441 /// Cursor position of the start of the global decl attachments, to enable
442 /// loading using the index built for lazy loading, instead of forward
443 /// references.
444 uint64_t GlobalDeclAttachmentPos = 0;
445
446#ifndef NDEBUG
447 /// Baisic correctness check that we end up parsing all of the global decl
448 /// attachments.
449 unsigned NumGlobalDeclAttachSkipped = 0;
450 unsigned NumGlobalDeclAttachParsed = 0;
451#endif
452
453 /// Load the global decl attachments, using the index built for lazy loading.
454 Expected<bool> loadGlobalDeclAttachments();
455
456 /// Populate the index above to enable lazily loading of metadata, and load
457 /// the named metadata as well as the transitively referenced global
458 /// Metadata.
459 Expected<bool> lazyLoadModuleMetadataBlock();
460
461 /// On-demand loading of a single metadata. Requires the index above to be
462 /// populated.
463 void lazyLoadOneMetadata(unsigned Idx, PlaceholderQueue &Placeholders);
464
465 // Keep mapping of seens pair of old-style CU <-> SP, and update pointers to
466 // point from SP to CU after a block is completly parsed.
467 std::vector<std::pair<DICompileUnit *, Metadata *>> CUSubprograms;
468
469 /// Functions that need to be matched with subprograms when upgrading old
470 /// metadata.
471 SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs;
472
473 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
474 DenseMap<unsigned, unsigned> MDKindMap;
475
476 bool StripTBAA = false;
477 bool HasSeenOldLoopTags = false;
478 bool NeedUpgradeToDIGlobalVariableExpression = false;
479 bool NeedDeclareExpressionUpgrade = false;
480
481 /// True if metadata is being parsed for a module being ThinLTO imported.
482 bool IsImporting = false;
483
484 Error parseOneMetadata(SmallVectorImpl<uint64_t> &Record, unsigned Code,
485 PlaceholderQueue &Placeholders, StringRef Blob,
486 unsigned &NextMetadataNo);
487 Error parseMetadataStrings(ArrayRef<uint64_t> Record, StringRef Blob,
488 function_ref<void(StringRef)> CallBack);
489 Error parseGlobalObjectAttachment(GlobalObject &GO,
490 ArrayRef<uint64_t> Record);
491 Error parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
492
493 void resolveForwardRefsAndPlaceholders(PlaceholderQueue &Placeholders);
494
495 /// Upgrade old-style CU <-> SP pointers to point from SP to CU.
496 void upgradeCUSubprograms() {
497 for (auto CU_SP : CUSubprograms)
498 if (auto *SPs = dyn_cast_or_null<MDTuple>(CU_SP.second))
499 for (auto &Op : SPs->operands())
500 if (auto *SP = dyn_cast_or_null<DISubprogram>(Op))
501 SP->replaceUnit(CU_SP.first);
502 CUSubprograms.clear();
503 }
504
505 /// Upgrade old-style bare DIGlobalVariables to DIGlobalVariableExpressions.
506 void upgradeCUVariables() {
507 if (!NeedUpgradeToDIGlobalVariableExpression)
508 return;
509
510 // Upgrade list of variables attached to the CUs.
511 if (NamedMDNode *CUNodes = TheModule.getNamedMetadata("llvm.dbg.cu"))
512 for (unsigned I = 0, E = CUNodes->getNumOperands(); I != E; ++I) {
513 auto *CU = cast<DICompileUnit>(CUNodes->getOperand(I));
514 if (auto *GVs = dyn_cast_or_null<MDTuple>(CU->getRawGlobalVariables()))
515 for (unsigned I = 0; I < GVs->getNumOperands(); I++)
516 if (auto *GV =
517 dyn_cast_or_null<DIGlobalVariable>(GVs->getOperand(I))) {
518 auto *DGVE = DIGlobalVariableExpression::getDistinct(
519 Context, GV, DIExpression::get(Context, {}));
520 GVs->replaceOperandWith(I, DGVE);
521 }
522 }
523
524 // Upgrade variables attached to globals.
525 for (auto &GV : TheModule.globals()) {
526 SmallVector<MDNode *, 1> MDs;
527 GV.getMetadata(LLVMContext::MD_dbg, MDs);
528 GV.eraseMetadata(LLVMContext::MD_dbg);
529 for (auto *MD : MDs)
530 if (auto *DGV = dyn_cast<DIGlobalVariable>(MD)) {
531 auto *DGVE = DIGlobalVariableExpression::getDistinct(
532 Context, DGV, DIExpression::get(Context, {}));
533 GV.addMetadata(LLVMContext::MD_dbg, *DGVE);
534 } else
535 GV.addMetadata(LLVMContext::MD_dbg, *MD);
536 }
537 }
538
539 /// Remove a leading DW_OP_deref from DIExpressions in a dbg.declare that
540 /// describes a function argument.
541 void upgradeDeclareExpressions(Function &F) {
542 if (!NeedDeclareExpressionUpgrade)
543 return;
544
545 for (auto &BB : F)
546 for (auto &I : BB)
547 if (auto *DDI = dyn_cast<DbgDeclareInst>(&I))
548 if (auto *DIExpr = DDI->getExpression())
549 if (DIExpr->startsWithDeref() &&
550 isa_and_nonnull<Argument>(DDI->getAddress())) {
551 SmallVector<uint64_t, 8> Ops;
552 Ops.append(std::next(DIExpr->elements_begin()),
553 DIExpr->elements_end());
554 DDI->setExpression(DIExpression::get(Context, Ops));
555 }
556 }
557
558 /// Upgrade the expression from previous versions.
559 Error upgradeDIExpression(uint64_t FromVersion,
560 MutableArrayRef<uint64_t> &Expr,
561 SmallVectorImpl<uint64_t> &Buffer) {
562 auto N = Expr.size();
563 switch (FromVersion) {
564 default:
565 return error("Invalid record");
566 case 0:
567 if (N >= 3 && Expr[N - 3] == dwarf::DW_OP_bit_piece)
568 Expr[N - 3] = dwarf::DW_OP_LLVM_fragment;
569 LLVM_FALLTHROUGH[[gnu::fallthrough]];
570 case 1:
571 // Move DW_OP_deref to the end.
572 if (N && Expr[0] == dwarf::DW_OP_deref) {
573 auto End = Expr.end();
574 if (Expr.size() >= 3 &&
575 *std::prev(End, 3) == dwarf::DW_OP_LLVM_fragment)
576 End = std::prev(End, 3);
577 std::move(std::next(Expr.begin()), End, Expr.begin());
578 *std::prev(End) = dwarf::DW_OP_deref;
579 }
580 NeedDeclareExpressionUpgrade = true;
581 LLVM_FALLTHROUGH[[gnu::fallthrough]];
582 case 2: {
583 // Change DW_OP_plus to DW_OP_plus_uconst.
584 // Change DW_OP_minus to DW_OP_uconst, DW_OP_minus
585 auto SubExpr = ArrayRef<uint64_t>(Expr);
586 while (!SubExpr.empty()) {
587 // Skip past other operators with their operands
588 // for this version of the IR, obtained from
589 // from historic DIExpression::ExprOperand::getSize().
590 size_t HistoricSize;
591 switch (SubExpr.front()) {
592 default:
593 HistoricSize = 1;
594 break;
595 case dwarf::DW_OP_constu:
596 case dwarf::DW_OP_minus:
597 case dwarf::DW_OP_plus:
598 HistoricSize = 2;
599 break;
600 case dwarf::DW_OP_LLVM_fragment:
601 HistoricSize = 3;
602 break;
603 }
604
605 // If the expression is malformed, make sure we don't
606 // copy more elements than we should.
607 HistoricSize = std::min(SubExpr.size(), HistoricSize);
608 ArrayRef<uint64_t> Args = SubExpr.slice(1, HistoricSize - 1);
609
610 switch (SubExpr.front()) {
611 case dwarf::DW_OP_plus:
612 Buffer.push_back(dwarf::DW_OP_plus_uconst);
613 Buffer.append(Args.begin(), Args.end());
614 break;
615 case dwarf::DW_OP_minus:
616 Buffer.push_back(dwarf::DW_OP_constu);
617 Buffer.append(Args.begin(), Args.end());
618 Buffer.push_back(dwarf::DW_OP_minus);
619 break;
620 default:
621 Buffer.push_back(*SubExpr.begin());
622 Buffer.append(Args.begin(), Args.end());
623 break;
624 }
625
626 // Continue with remaining elements.
627 SubExpr = SubExpr.slice(HistoricSize);
628 }
629 Expr = MutableArrayRef<uint64_t>(Buffer);
630 LLVM_FALLTHROUGH[[gnu::fallthrough]];
631 }
632 case 3:
633 // Up-to-date!
634 break;
635 }
636
637 return Error::success();
638 }
639
640 void upgradeDebugInfo() {
641 upgradeCUSubprograms();
642 upgradeCUVariables();
643 }
644
645public:
646 MetadataLoaderImpl(BitstreamCursor &Stream, Module &TheModule,
647 BitcodeReaderValueList &ValueList,
648 std::function<Type *(unsigned)> getTypeByID,
649 bool IsImporting)
650 : MetadataList(TheModule.getContext(), Stream.SizeInBytes()),
651 ValueList(ValueList), Stream(Stream), Context(TheModule.getContext()),
652 TheModule(TheModule), getTypeByID(std::move(getTypeByID)),
653 IsImporting(IsImporting) {}
654
655 Error parseMetadata(bool ModuleLevel);
656
657 bool hasFwdRefs() const { return MetadataList.hasFwdRefs(); }
658
659 Metadata *getMetadataFwdRefOrLoad(unsigned ID) {
660 if (ID < MDStringRef.size())
20
Assuming the condition is false
21
Taking false branch
661 return lazyLoadOneMDString(ID);
662 if (auto *MD
21.1
'MD' is null
21.1
'MD' is null
= MetadataList.lookup(ID))
22
Taking false branch
663 return MD;
664 // If lazy-loading is enabled, we try recursively to load the operand
665 // instead of creating a temporary.
666 if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
23
Assuming the condition is true
24
Taking true branch
667 PlaceholderQueue Placeholders;
668 lazyLoadOneMetadata(ID, Placeholders);
25
Calling 'MetadataLoaderImpl::lazyLoadOneMetadata'
669 resolveForwardRefsAndPlaceholders(Placeholders);
670 return MetadataList.lookup(ID);
671 }
672 return MetadataList.getMetadataFwdRef(ID);
673 }
674
675 DISubprogram *lookupSubprogramForFunction(Function *F) {
676 return FunctionsWithSPs.lookup(F);
677 }
678
679 bool hasSeenOldLoopTags() const { return HasSeenOldLoopTags; }
680
681 Error parseMetadataAttachment(
682 Function &F, const SmallVectorImpl<Instruction *> &InstructionList);
683
684 Error parseMetadataKinds();
685
686 void setStripTBAA(bool Value) { StripTBAA = Value; }
687 bool isStrippingTBAA() const { return StripTBAA; }
688
689 unsigned size() const { return MetadataList.size(); }
690 void shrinkTo(unsigned N) { MetadataList.shrinkTo(N); }
691 void upgradeDebugIntrinsics(Function &F) { upgradeDeclareExpressions(F); }
692};
693
694Expected<bool>
695MetadataLoader::MetadataLoaderImpl::lazyLoadModuleMetadataBlock() {
696 IndexCursor = Stream;
697 SmallVector<uint64_t, 64> Record;
698 GlobalDeclAttachmentPos = 0;
699 // Get the abbrevs, and preload record positions to make them lazy-loadable.
700 while (true) {
701 uint64_t SavedPos = IndexCursor.GetCurrentBitNo();
702 BitstreamEntry Entry;
703 if (Error E =
704 IndexCursor
705 .advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd)
706 .moveInto(Entry))
707 return std::move(E);
708
709 switch (Entry.Kind) {
710 case BitstreamEntry::SubBlock: // Handled for us already.
711 case BitstreamEntry::Error:
712 return error("Malformed block");
713 case BitstreamEntry::EndBlock: {
714 return true;
715 }
716 case BitstreamEntry::Record: {
717 // The interesting case.
718 ++NumMDRecordLoaded;
719 uint64_t CurrentPos = IndexCursor.GetCurrentBitNo();
720 unsigned Code;
721 if (Error E = IndexCursor.skipRecord(Entry.ID).moveInto(Code))
722 return std::move(E);
723 switch (Code) {
724 case bitc::METADATA_STRINGS: {
725 // Rewind and parse the strings.
726 if (Error Err = IndexCursor.JumpToBit(CurrentPos))
727 return std::move(Err);
728 StringRef Blob;
729 Record.clear();
730 if (Expected<unsigned> MaybeRecord =
731 IndexCursor.readRecord(Entry.ID, Record, &Blob))
732 ;
733 else
734 return MaybeRecord.takeError();
735 unsigned NumStrings = Record[0];
736 MDStringRef.reserve(NumStrings);
737 auto IndexNextMDString = [&](StringRef Str) {
738 MDStringRef.push_back(Str);
739 };
740 if (auto Err = parseMetadataStrings(Record, Blob, IndexNextMDString))
741 return std::move(Err);
742 break;
743 }
744 case bitc::METADATA_INDEX_OFFSET: {
745 // This is the offset to the index, when we see this we skip all the
746 // records and load only an index to these.
747 if (Error Err = IndexCursor.JumpToBit(CurrentPos))
748 return std::move(Err);
749 Record.clear();
750 if (Expected<unsigned> MaybeRecord =
751 IndexCursor.readRecord(Entry.ID, Record))
752 ;
753 else
754 return MaybeRecord.takeError();
755 if (Record.size() != 2)
756 return error("Invalid record");
757 auto Offset = Record[0] + (Record[1] << 32);
758 auto BeginPos = IndexCursor.GetCurrentBitNo();
759 if (Error Err = IndexCursor.JumpToBit(BeginPos + Offset))
760 return std::move(Err);
761 Expected<BitstreamEntry> MaybeEntry =
762 IndexCursor.advanceSkippingSubblocks(
763 BitstreamCursor::AF_DontPopBlockAtEnd);
764 if (!MaybeEntry)
765 return MaybeEntry.takeError();
766 Entry = MaybeEntry.get();
767 assert(Entry.Kind == BitstreamEntry::Record &&(static_cast <bool> (Entry.Kind == BitstreamEntry::Record
&& "Corrupted bitcode: Expected `Record` when trying to find the "
"Metadata index") ? void (0) : __assert_fail ("Entry.Kind == BitstreamEntry::Record && \"Corrupted bitcode: Expected `Record` when trying to find the \" \"Metadata index\""
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 769, __extension__
__PRETTY_FUNCTION__))
768 "Corrupted bitcode: Expected `Record` when trying to find the "(static_cast <bool> (Entry.Kind == BitstreamEntry::Record
&& "Corrupted bitcode: Expected `Record` when trying to find the "
"Metadata index") ? void (0) : __assert_fail ("Entry.Kind == BitstreamEntry::Record && \"Corrupted bitcode: Expected `Record` when trying to find the \" \"Metadata index\""
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 769, __extension__
__PRETTY_FUNCTION__))
769 "Metadata index")(static_cast <bool> (Entry.Kind == BitstreamEntry::Record
&& "Corrupted bitcode: Expected `Record` when trying to find the "
"Metadata index") ? void (0) : __assert_fail ("Entry.Kind == BitstreamEntry::Record && \"Corrupted bitcode: Expected `Record` when trying to find the \" \"Metadata index\""
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 769, __extension__
__PRETTY_FUNCTION__))
;
770 Record.clear();
771 if (Expected<unsigned> MaybeCode =
772 IndexCursor.readRecord(Entry.ID, Record))
773 assert(MaybeCode.get() == bitc::METADATA_INDEX &&(static_cast <bool> (MaybeCode.get() == bitc::METADATA_INDEX
&& "Corrupted bitcode: Expected `METADATA_INDEX` when trying to "
"find the Metadata index") ? void (0) : __assert_fail ("MaybeCode.get() == bitc::METADATA_INDEX && \"Corrupted bitcode: Expected `METADATA_INDEX` when trying to \" \"find the Metadata index\""
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 775, __extension__
__PRETTY_FUNCTION__))
774 "Corrupted bitcode: Expected `METADATA_INDEX` when trying to "(static_cast <bool> (MaybeCode.get() == bitc::METADATA_INDEX
&& "Corrupted bitcode: Expected `METADATA_INDEX` when trying to "
"find the Metadata index") ? void (0) : __assert_fail ("MaybeCode.get() == bitc::METADATA_INDEX && \"Corrupted bitcode: Expected `METADATA_INDEX` when trying to \" \"find the Metadata index\""
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 775, __extension__
__PRETTY_FUNCTION__))
775 "find the Metadata index")(static_cast <bool> (MaybeCode.get() == bitc::METADATA_INDEX
&& "Corrupted bitcode: Expected `METADATA_INDEX` when trying to "
"find the Metadata index") ? void (0) : __assert_fail ("MaybeCode.get() == bitc::METADATA_INDEX && \"Corrupted bitcode: Expected `METADATA_INDEX` when trying to \" \"find the Metadata index\""
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 775, __extension__
__PRETTY_FUNCTION__))
;
776 else
777 return MaybeCode.takeError();
778 // Delta unpack
779 auto CurrentValue = BeginPos;
780 GlobalMetadataBitPosIndex.reserve(Record.size());
781 for (auto &Elt : Record) {
782 CurrentValue += Elt;
783 GlobalMetadataBitPosIndex.push_back(CurrentValue);
784 }
785 break;
786 }
787 case bitc::METADATA_INDEX:
788 // We don't expect to get there, the Index is loaded when we encounter
789 // the offset.
790 return error("Corrupted Metadata block");
791 case bitc::METADATA_NAME: {
792 // Named metadata need to be materialized now and aren't deferred.
793 if (Error Err = IndexCursor.JumpToBit(CurrentPos))
794 return std::move(Err);
795 Record.clear();
796
797 unsigned Code;
798 if (Expected<unsigned> MaybeCode =
799 IndexCursor.readRecord(Entry.ID, Record)) {
800 Code = MaybeCode.get();
801 assert(Code == bitc::METADATA_NAME)(static_cast <bool> (Code == bitc::METADATA_NAME) ? void
(0) : __assert_fail ("Code == bitc::METADATA_NAME", "llvm/lib/Bitcode/Reader/MetadataLoader.cpp"
, 801, __extension__ __PRETTY_FUNCTION__))
;
802 } else
803 return MaybeCode.takeError();
804
805 // Read name of the named metadata.
806 SmallString<8> Name(Record.begin(), Record.end());
807 if (Expected<unsigned> MaybeCode = IndexCursor.ReadCode())
808 Code = MaybeCode.get();
809 else
810 return MaybeCode.takeError();
811
812 // Named Metadata comes in two parts, we expect the name to be followed
813 // by the node
814 Record.clear();
815 if (Expected<unsigned> MaybeNextBitCode =
816 IndexCursor.readRecord(Code, Record))
817 assert(MaybeNextBitCode.get() == bitc::METADATA_NAMED_NODE)(static_cast <bool> (MaybeNextBitCode.get() == bitc::METADATA_NAMED_NODE
) ? void (0) : __assert_fail ("MaybeNextBitCode.get() == bitc::METADATA_NAMED_NODE"
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 817, __extension__
__PRETTY_FUNCTION__))
;
818 else
819 return MaybeNextBitCode.takeError();
820
821 // Read named metadata elements.
822 unsigned Size = Record.size();
823 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
824 for (unsigned i = 0; i != Size; ++i) {
825 // FIXME: We could use a placeholder here, however NamedMDNode are
826 // taking MDNode as operand and not using the Metadata infrastructure.
827 // It is acknowledged by 'TODO: Inherit from Metadata' in the
828 // NamedMDNode class definition.
829 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
830 assert(MD && "Invalid metadata: expect fwd ref to MDNode")(static_cast <bool> (MD && "Invalid metadata: expect fwd ref to MDNode"
) ? void (0) : __assert_fail ("MD && \"Invalid metadata: expect fwd ref to MDNode\""
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 830, __extension__
__PRETTY_FUNCTION__))
;
831 NMD->addOperand(MD);
832 }
833 break;
834 }
835 case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
836 if (!GlobalDeclAttachmentPos)
837 GlobalDeclAttachmentPos = SavedPos;
838#ifndef NDEBUG
839 NumGlobalDeclAttachSkipped++;
840#endif
841 break;
842 }
843 case bitc::METADATA_KIND:
844 case bitc::METADATA_STRING_OLD:
845 case bitc::METADATA_OLD_FN_NODE:
846 case bitc::METADATA_OLD_NODE:
847 case bitc::METADATA_VALUE:
848 case bitc::METADATA_DISTINCT_NODE:
849 case bitc::METADATA_NODE:
850 case bitc::METADATA_LOCATION:
851 case bitc::METADATA_GENERIC_DEBUG:
852 case bitc::METADATA_SUBRANGE:
853 case bitc::METADATA_ENUMERATOR:
854 case bitc::METADATA_BASIC_TYPE:
855 case bitc::METADATA_STRING_TYPE:
856 case bitc::METADATA_DERIVED_TYPE:
857 case bitc::METADATA_COMPOSITE_TYPE:
858 case bitc::METADATA_SUBROUTINE_TYPE:
859 case bitc::METADATA_MODULE:
860 case bitc::METADATA_FILE:
861 case bitc::METADATA_COMPILE_UNIT:
862 case bitc::METADATA_SUBPROGRAM:
863 case bitc::METADATA_LEXICAL_BLOCK:
864 case bitc::METADATA_LEXICAL_BLOCK_FILE:
865 case bitc::METADATA_NAMESPACE:
866 case bitc::METADATA_COMMON_BLOCK:
867 case bitc::METADATA_MACRO:
868 case bitc::METADATA_MACRO_FILE:
869 case bitc::METADATA_TEMPLATE_TYPE:
870 case bitc::METADATA_TEMPLATE_VALUE:
871 case bitc::METADATA_GLOBAL_VAR:
872 case bitc::METADATA_LOCAL_VAR:
873 case bitc::METADATA_LABEL:
874 case bitc::METADATA_EXPRESSION:
875 case bitc::METADATA_OBJC_PROPERTY:
876 case bitc::METADATA_IMPORTED_ENTITY:
877 case bitc::METADATA_GLOBAL_VAR_EXPR:
878 case bitc::METADATA_GENERIC_SUBRANGE:
879 // We don't expect to see any of these, if we see one, give up on
880 // lazy-loading and fallback.
881 MDStringRef.clear();
882 GlobalMetadataBitPosIndex.clear();
883 return false;
884 }
885 break;
886 }
887 }
888 }
889}
890
891// Load the global decl attachments after building the lazy loading index.
892// We don't load them "lazily" - all global decl attachments must be
893// parsed since they aren't materialized on demand. However, by delaying
894// their parsing until after the index is created, we can use the index
895// instead of creating temporaries.
896Expected<bool> MetadataLoader::MetadataLoaderImpl::loadGlobalDeclAttachments() {
897 // Nothing to do if we didn't find any of these metadata records.
898 if (!GlobalDeclAttachmentPos)
899 return true;
900 // Use a temporary cursor so that we don't mess up the main Stream cursor or
901 // the lazy loading IndexCursor (which holds the necessary abbrev ids).
902 BitstreamCursor TempCursor = Stream;
903 SmallVector<uint64_t, 64> Record;
904 // Jump to the position before the first global decl attachment, so we can
905 // scan for the first BitstreamEntry record.
906 if (Error Err = TempCursor.JumpToBit(GlobalDeclAttachmentPos))
907 return std::move(Err);
908 while (true) {
909 BitstreamEntry Entry;
910 if (Error E =
911 TempCursor
912 .advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd)
913 .moveInto(Entry))
914 return std::move(E);
915
916 switch (Entry.Kind) {
917 case BitstreamEntry::SubBlock: // Handled for us already.
918 case BitstreamEntry::Error:
919 return error("Malformed block");
920 case BitstreamEntry::EndBlock:
921 // Check that we parsed them all.
922 assert(NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed)(static_cast <bool> (NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed
) ? void (0) : __assert_fail ("NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed"
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 922, __extension__
__PRETTY_FUNCTION__))
;
923 return true;
924 case BitstreamEntry::Record:
925 break;
926 }
927 uint64_t CurrentPos = TempCursor.GetCurrentBitNo();
928 Expected<unsigned> MaybeCode = TempCursor.skipRecord(Entry.ID);
929 if (!MaybeCode)
930 return MaybeCode.takeError();
931 if (MaybeCode.get() != bitc::METADATA_GLOBAL_DECL_ATTACHMENT) {
932 // Anything other than a global decl attachment signals the end of
933 // these records. Check that we parsed them all.
934 assert(NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed)(static_cast <bool> (NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed
) ? void (0) : __assert_fail ("NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed"
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 934, __extension__
__PRETTY_FUNCTION__))
;
935 return true;
936 }
937#ifndef NDEBUG
938 NumGlobalDeclAttachParsed++;
939#endif
940 // FIXME: we need to do this early because we don't materialize global
941 // value explicitly.
942 if (Error Err = TempCursor.JumpToBit(CurrentPos))
943 return std::move(Err);
944 Record.clear();
945 if (Expected<unsigned> MaybeRecord =
946 TempCursor.readRecord(Entry.ID, Record))
947 ;
948 else
949 return MaybeRecord.takeError();
950 if (Record.size() % 2 == 0)
951 return error("Invalid record");
952 unsigned ValueID = Record[0];
953 if (ValueID >= ValueList.size())
954 return error("Invalid record");
955 if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID])) {
956 // Need to save and restore the current position since
957 // parseGlobalObjectAttachment will resolve all forward references which
958 // would require parsing from locations stored in the index.
959 CurrentPos = TempCursor.GetCurrentBitNo();
960 if (Error Err = parseGlobalObjectAttachment(
961 *GO, ArrayRef<uint64_t>(Record).slice(1)))
962 return std::move(Err);
963 if (Error Err = TempCursor.JumpToBit(CurrentPos))
964 return std::move(Err);
965 }
966 }
967}
968
969/// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
970/// module level metadata.
971Error MetadataLoader::MetadataLoaderImpl::parseMetadata(bool ModuleLevel) {
972 if (!ModuleLevel && MetadataList.hasFwdRefs())
973 return error("Invalid metadata: fwd refs into function blocks");
974
975 // Record the entry position so that we can jump back here and efficiently
976 // skip the whole block in case we lazy-load.
977 auto EntryPos = Stream.GetCurrentBitNo();
978
979 if (Error Err = Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
980 return Err;
981
982 SmallVector<uint64_t, 64> Record;
983 PlaceholderQueue Placeholders;
984
985 // We lazy-load module-level metadata: we build an index for each record, and
986 // then load individual record as needed, starting with the named metadata.
987 if (ModuleLevel && IsImporting && MetadataList.empty() &&
988 !DisableLazyLoading) {
989 auto SuccessOrErr = lazyLoadModuleMetadataBlock();
990 if (!SuccessOrErr)
991 return SuccessOrErr.takeError();
992 if (SuccessOrErr.get()) {
993 // An index was successfully created and we will be able to load metadata
994 // on-demand.
995 MetadataList.resize(MDStringRef.size() +
996 GlobalMetadataBitPosIndex.size());
997
998 // Now that we have built the index, load the global decl attachments
999 // that were deferred during that process. This avoids creating
1000 // temporaries.
1001 SuccessOrErr = loadGlobalDeclAttachments();
1002 if (!SuccessOrErr)
1003 return SuccessOrErr.takeError();
1004 assert(SuccessOrErr.get())(static_cast <bool> (SuccessOrErr.get()) ? void (0) : __assert_fail
("SuccessOrErr.get()", "llvm/lib/Bitcode/Reader/MetadataLoader.cpp"
, 1004, __extension__ __PRETTY_FUNCTION__))
;
1005
1006 // Reading the named metadata created forward references and/or
1007 // placeholders, that we flush here.
1008 resolveForwardRefsAndPlaceholders(Placeholders);
1009 upgradeDebugInfo();
1010 // Return at the beginning of the block, since it is easy to skip it
1011 // entirely from there.
1012 Stream.ReadBlockEnd(); // Pop the abbrev block context.
1013 if (Error Err = IndexCursor.JumpToBit(EntryPos))
1014 return Err;
1015 if (Error Err = Stream.SkipBlock()) {
1016 // FIXME this drops the error on the floor, which
1017 // ThinLTO/X86/debuginfo-cu-import.ll relies on.
1018 consumeError(std::move(Err));
1019 return Error::success();
1020 }
1021 return Error::success();
1022 }
1023 // Couldn't load an index, fallback to loading all the block "old-style".
1024 }
1025
1026 unsigned NextMetadataNo = MetadataList.size();
1027
1028 // Read all the records.
1029 while (true) {
1030 BitstreamEntry Entry;
1031 if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
1032 return E;
1033
1034 switch (Entry.Kind) {
1035 case BitstreamEntry::SubBlock: // Handled for us already.
1036 case BitstreamEntry::Error:
1037 return error("Malformed block");
1038 case BitstreamEntry::EndBlock:
1039 resolveForwardRefsAndPlaceholders(Placeholders);
1040 upgradeDebugInfo();
1041 return Error::success();
1042 case BitstreamEntry::Record:
1043 // The interesting case.
1044 break;
1045 }
1046
1047 // Read a record.
1048 Record.clear();
1049 StringRef Blob;
1050 ++NumMDRecordLoaded;
1051 if (Expected<unsigned> MaybeCode =
1052 Stream.readRecord(Entry.ID, Record, &Blob)) {
1053 if (Error Err = parseOneMetadata(Record, MaybeCode.get(), Placeholders,
1054 Blob, NextMetadataNo))
1055 return Err;
1056 } else
1057 return MaybeCode.takeError();
1058 }
1059}
1060
1061MDString *MetadataLoader::MetadataLoaderImpl::lazyLoadOneMDString(unsigned ID) {
1062 ++NumMDStringLoaded;
1063 if (Metadata *MD = MetadataList.lookup(ID))
1064 return cast<MDString>(MD);
1065 auto MDS = MDString::get(Context, MDStringRef[ID]);
1066 MetadataList.assignValue(MDS, ID);
1067 return MDS;
1068}
1069
1070void MetadataLoader::MetadataLoaderImpl::lazyLoadOneMetadata(
1071 unsigned ID, PlaceholderQueue &Placeholders) {
1072 assert(ID < (MDStringRef.size()) + GlobalMetadataBitPosIndex.size())(static_cast <bool> (ID < (MDStringRef.size()) + GlobalMetadataBitPosIndex
.size()) ? void (0) : __assert_fail ("ID < (MDStringRef.size()) + GlobalMetadataBitPosIndex.size()"
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 1072, __extension__
__PRETTY_FUNCTION__))
;
26
Assuming the condition is true
27
'?' condition is true
1073 assert(ID >= MDStringRef.size() && "Unexpected lazy-loading of MDString")(static_cast <bool> (ID >= MDStringRef.size() &&
"Unexpected lazy-loading of MDString") ? void (0) : __assert_fail
("ID >= MDStringRef.size() && \"Unexpected lazy-loading of MDString\""
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 1073, __extension__
__PRETTY_FUNCTION__))
;
28
Assuming the condition is true
29
'?' condition is true
1074 // Lookup first if the metadata hasn't already been loaded.
1075 if (auto *MD
33.1
'MD' is null
33.1
'MD' is null
= MetadataList.lookup(ID)) {
30
Calling 'BitcodeReaderMetadataList::lookup'
33
Returning from 'BitcodeReaderMetadataList::lookup'
34
Taking false branch
1076 auto *N = cast<MDNode>(MD);
1077 if (!N->isTemporary())
1078 return;
1079 }
1080 SmallVector<uint64_t, 64> Record;
1081 StringRef Blob;
1082 if (Error Err = IndexCursor.JumpToBit(
35
Assuming the condition is false
36
Taking false branch
1083 GlobalMetadataBitPosIndex[ID - MDStringRef.size()]))
1084 report_fatal_error("lazyLoadOneMetadata failed jumping: " +
1085 Twine(toString(std::move(Err))));
1086 BitstreamEntry Entry;
1087 if (Error E = IndexCursor.advanceSkippingSubblocks().moveInto(Entry))
37
Calling 'Expected::moveInto'
40
Returning from 'Expected::moveInto'
41
Assuming the condition is false
42
Taking false branch
1088 // FIXME this drops the error on the floor.
1089 report_fatal_error("lazyLoadOneMetadata failed advanceSkippingSubblocks: " +
1090 Twine(toString(std::move(E))));
1091 ++NumMDRecordLoaded;
1092 if (Expected<unsigned> MaybeCode =
1093 IndexCursor.readRecord(Entry.ID, Record, &Blob)) {
43
1st function call argument is an uninitialized value
1094 if (Error Err =
1095 parseOneMetadata(Record, MaybeCode.get(), Placeholders, Blob, ID))
1096 report_fatal_error("Can't lazyload MD, parseOneMetadata: " +
1097 Twine(toString(std::move(Err))));
1098 } else
1099 report_fatal_error("Can't lazyload MD: " +
1100 Twine(toString(MaybeCode.takeError())));
1101}
1102
1103/// Ensure that all forward-references and placeholders are resolved.
1104/// Iteratively lazy-loading metadata on-demand if needed.
1105void MetadataLoader::MetadataLoaderImpl::resolveForwardRefsAndPlaceholders(
1106 PlaceholderQueue &Placeholders) {
1107 DenseSet<unsigned> Temporaries;
1108 while (true) {
1109 // Populate Temporaries with the placeholders that haven't been loaded yet.
1110 Placeholders.getTemporaries(MetadataList, Temporaries);
1111
1112 // If we don't have any temporary, or FwdReference, we're done!
1113 if (Temporaries.empty() && !MetadataList.hasFwdRefs())
1114 break;
1115
1116 // First, load all the temporaries. This can add new placeholders or
1117 // forward references.
1118 for (auto ID : Temporaries)
1119 lazyLoadOneMetadata(ID, Placeholders);
1120 Temporaries.clear();
1121
1122 // Second, load the forward-references. This can also add new placeholders
1123 // or forward references.
1124 while (MetadataList.hasFwdRefs())
1125 lazyLoadOneMetadata(MetadataList.getNextFwdRef(), Placeholders);
1126 }
1127 // At this point we don't have any forward reference remaining, or temporary
1128 // that haven't been loaded. We can safely drop RAUW support and mark cycles
1129 // as resolved.
1130 MetadataList.tryToResolveCycles();
1131
1132 // Finally, everything is in place, we can replace the placeholders operands
1133 // with the final node they refer to.
1134 Placeholders.flush(MetadataList);
1135}
1136
1137Error MetadataLoader::MetadataLoaderImpl::parseOneMetadata(
1138 SmallVectorImpl<uint64_t> &Record, unsigned Code,
1139 PlaceholderQueue &Placeholders, StringRef Blob, unsigned &NextMetadataNo) {
1140
1141 bool IsDistinct = false;
1142 auto getMD = [&](unsigned ID) -> Metadata * {
1143 if (ID < MDStringRef.size())
1144 return lazyLoadOneMDString(ID);
1145 if (!IsDistinct) {
1146 if (auto *MD = MetadataList.lookup(ID))
1147 return MD;
1148 // If lazy-loading is enabled, we try recursively to load the operand
1149 // instead of creating a temporary.
1150 if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
1151 // Create a temporary for the node that is referencing the operand we
1152 // will lazy-load. It is needed before recursing in case there are
1153 // uniquing cycles.
1154 MetadataList.getMetadataFwdRef(NextMetadataNo);
1155 lazyLoadOneMetadata(ID, Placeholders);
1156 return MetadataList.lookup(ID);
1157 }
1158 // Return a temporary.
1159 return MetadataList.getMetadataFwdRef(ID);
1160 }
1161 if (auto *MD = MetadataList.getMetadataIfResolved(ID))
1162 return MD;
1163 return &Placeholders.getPlaceholderOp(ID);
1164 };
1165 auto getMDOrNull = [&](unsigned ID) -> Metadata * {
1166 if (ID)
1167 return getMD(ID - 1);
1168 return nullptr;
1169 };
1170 auto getMDOrNullWithoutPlaceholders = [&](unsigned ID) -> Metadata * {
1171 if (ID)
1172 return MetadataList.getMetadataFwdRef(ID - 1);
1173 return nullptr;
1174 };
1175 auto getMDString = [&](unsigned ID) -> MDString * {
1176 // This requires that the ID is not really a forward reference. In
1177 // particular, the MDString must already have been resolved.
1178 auto MDS = getMDOrNull(ID);
1179 return cast_or_null<MDString>(MDS);
1180 };
1181
1182 // Support for old type refs.
1183 auto getDITypeRefOrNull = [&](unsigned ID) {
1184 return MetadataList.upgradeTypeRef(getMDOrNull(ID));
1185 };
1186
1187#define GET_OR_DISTINCT(CLASS, ARGS) \
1188 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1189
1190 switch (Code) {
1191 default: // Default behavior: ignore.
1192 break;
1193 case bitc::METADATA_NAME: {
1194 // Read name of the named metadata.
1195 SmallString<8> Name(Record.begin(), Record.end());
1196 Record.clear();
1197 if (Error E = Stream.ReadCode().moveInto(Code))
1198 return E;
1199
1200 ++NumMDRecordLoaded;
1201 if (Expected<unsigned> MaybeNextBitCode = Stream.readRecord(Code, Record)) {
1202 if (MaybeNextBitCode.get() != bitc::METADATA_NAMED_NODE)
1203 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
1204 } else
1205 return MaybeNextBitCode.takeError();
1206
1207 // Read named metadata elements.
1208 unsigned Size = Record.size();
1209 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
1210 for (unsigned i = 0; i != Size; ++i) {
1211 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
1212 if (!MD)
1213 return error("Invalid named metadata: expect fwd ref to MDNode");
1214 NMD->addOperand(MD);
1215 }
1216 break;
1217 }
1218 case bitc::METADATA_OLD_FN_NODE: {
1219 // Deprecated, but still needed to read old bitcode files.
1220 // This is a LocalAsMetadata record, the only type of function-local
1221 // metadata.
1222 if (Record.size() % 2 == 1)
1223 return error("Invalid record");
1224
1225 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1226 // to be legal, but there's no upgrade path.
1227 auto dropRecord = [&] {
1228 MetadataList.assignValue(MDNode::get(Context, None), NextMetadataNo);
1229 NextMetadataNo++;
1230 };
1231 if (Record.size() != 2) {
1232 dropRecord();
1233 break;
1234 }
1235
1236 Type *Ty = getTypeByID(Record[0]);
1237 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1238 dropRecord();
1239 break;
1240 }
1241
1242 MetadataList.assignValue(
1243 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1244 NextMetadataNo);
1245 NextMetadataNo++;
1246 break;
1247 }
1248 case bitc::METADATA_OLD_NODE: {
1249 // Deprecated, but still needed to read old bitcode files.
1250 if (Record.size() % 2 == 1)
1251 return error("Invalid record");
1252
1253 unsigned Size = Record.size();
1254 SmallVector<Metadata *, 8> Elts;
1255 for (unsigned i = 0; i != Size; i += 2) {
1256 Type *Ty = getTypeByID(Record[i]);
1257 if (!Ty)
1258 return error("Invalid record");
1259 if (Ty->isMetadataTy())
1260 Elts.push_back(getMD(Record[i + 1]));
1261 else if (!Ty->isVoidTy()) {
1262 auto *MD =
1263 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1264 assert(isa<ConstantAsMetadata>(MD) &&(static_cast <bool> (isa<ConstantAsMetadata>(MD) &&
"Expected non-function-local metadata") ? void (0) : __assert_fail
("isa<ConstantAsMetadata>(MD) && \"Expected non-function-local metadata\""
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 1265, __extension__
__PRETTY_FUNCTION__))
1265 "Expected non-function-local metadata")(static_cast <bool> (isa<ConstantAsMetadata>(MD) &&
"Expected non-function-local metadata") ? void (0) : __assert_fail
("isa<ConstantAsMetadata>(MD) && \"Expected non-function-local metadata\""
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 1265, __extension__
__PRETTY_FUNCTION__))
;
1266 Elts.push_back(MD);
1267 } else
1268 Elts.push_back(nullptr);
1269 }
1270 MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo);
1271 NextMetadataNo++;
1272 break;
1273 }
1274 case bitc::METADATA_VALUE: {
1275 if (Record.size() != 2)
1276 return error("Invalid record");
1277
1278 Type *Ty = getTypeByID(Record[0]);
1279 if (Ty->isMetadataTy() || Ty->isVoidTy())
1280 return error("Invalid record");
1281
1282 MetadataList.assignValue(
1283 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1284 NextMetadataNo);
1285 NextMetadataNo++;
1286 break;
1287 }
1288 case bitc::METADATA_DISTINCT_NODE:
1289 IsDistinct = true;
1290 LLVM_FALLTHROUGH[[gnu::fallthrough]];
1291 case bitc::METADATA_NODE: {
1292 SmallVector<Metadata *, 8> Elts;
1293 Elts.reserve(Record.size());
1294 for (unsigned ID : Record)
1295 Elts.push_back(getMDOrNull(ID));
1296 MetadataList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1297 : MDNode::get(Context, Elts),
1298 NextMetadataNo);
1299 NextMetadataNo++;
1300 break;
1301 }
1302 case bitc::METADATA_LOCATION: {
1303 if (Record.size() != 5 && Record.size() != 6)
1304 return error("Invalid record");
1305
1306 IsDistinct = Record[0];
1307 unsigned Line = Record[1];
1308 unsigned Column = Record[2];
1309 Metadata *Scope = getMD(Record[3]);
1310 Metadata *InlinedAt = getMDOrNull(Record[4]);
1311 bool ImplicitCode = Record.size() == 6 && Record[5];
1312 MetadataList.assignValue(
1313 GET_OR_DISTINCT(DILocation, (Context, Line, Column, Scope, InlinedAt,
1314 ImplicitCode)),
1315 NextMetadataNo);
1316 NextMetadataNo++;
1317 break;
1318 }
1319 case bitc::METADATA_GENERIC_DEBUG: {
1320 if (Record.size() < 4)
1321 return error("Invalid record");
1322
1323 IsDistinct = Record[0];
1324 unsigned Tag = Record[1];
1325 unsigned Version = Record[2];
1326
1327 if (Tag >= 1u << 16 || Version != 0)
1328 return error("Invalid record");
1329
1330 auto *Header = getMDString(Record[3]);
1331 SmallVector<Metadata *, 8> DwarfOps;
1332 for (unsigned I = 4, E = Record.size(); I != E; ++I)
1333 DwarfOps.push_back(getMDOrNull(Record[I]));
1334 MetadataList.assignValue(
1335 GET_OR_DISTINCT(GenericDINode, (Context, Tag, Header, DwarfOps)),
1336 NextMetadataNo);
1337 NextMetadataNo++;
1338 break;
1339 }
1340 case bitc::METADATA_SUBRANGE: {
1341 Metadata *Val = nullptr;
1342 // Operand 'count' is interpreted as:
1343 // - Signed integer (version 0)
1344 // - Metadata node (version 1)
1345 // Operand 'lowerBound' is interpreted as:
1346 // - Signed integer (version 0 and 1)
1347 // - Metadata node (version 2)
1348 // Operands 'upperBound' and 'stride' are interpreted as:
1349 // - Metadata node (version 2)
1350 switch (Record[0] >> 1) {
1351 case 0:
1352 Val = GET_OR_DISTINCT(DISubrange,
1353 (Context, Record[1], unrotateSign(Record[2])));
1354 break;
1355 case 1:
1356 Val = GET_OR_DISTINCT(DISubrange, (Context, getMDOrNull(Record[1]),
1357 unrotateSign(Record[2])));
1358 break;
1359 case 2:
1360 Val = GET_OR_DISTINCT(
1361 DISubrange, (Context, getMDOrNull(Record[1]), getMDOrNull(Record[2]),
1362 getMDOrNull(Record[3]), getMDOrNull(Record[4])));
1363 break;
1364 default:
1365 return error("Invalid record: Unsupported version of DISubrange");
1366 }
1367
1368 MetadataList.assignValue(Val, NextMetadataNo);
1369 IsDistinct = Record[0] & 1;
1370 NextMetadataNo++;
1371 break;
1372 }
1373 case bitc::METADATA_GENERIC_SUBRANGE: {
1374 Metadata *Val = nullptr;
1375 Val = GET_OR_DISTINCT(DIGenericSubrange,
1376 (Context, getMDOrNull(Record[1]),
1377 getMDOrNull(Record[2]), getMDOrNull(Record[3]),
1378 getMDOrNull(Record[4])));
1379
1380 MetadataList.assignValue(Val, NextMetadataNo);
1381 IsDistinct = Record[0] & 1;
1382 NextMetadataNo++;
1383 break;
1384 }
1385 case bitc::METADATA_ENUMERATOR: {
1386 if (Record.size() < 3)
1387 return error("Invalid record");
1388
1389 IsDistinct = Record[0] & 1;
1390 bool IsUnsigned = Record[0] & 2;
1391 bool IsBigInt = Record[0] & 4;
1392 APInt Value;
1393
1394 if (IsBigInt) {
1395 const uint64_t BitWidth = Record[1];
1396 const size_t NumWords = Record.size() - 3;
1397 Value = readWideAPInt(makeArrayRef(&Record[3], NumWords), BitWidth);
1398 } else
1399 Value = APInt(64, unrotateSign(Record[1]), !IsUnsigned);
1400
1401 MetadataList.assignValue(
1402 GET_OR_DISTINCT(DIEnumerator,
1403 (Context, Value, IsUnsigned, getMDString(Record[2]))),
1404 NextMetadataNo);
1405 NextMetadataNo++;
1406 break;
1407 }
1408 case bitc::METADATA_BASIC_TYPE: {
1409 if (Record.size() < 6 || Record.size() > 7)
1410 return error("Invalid record");
1411
1412 IsDistinct = Record[0];
1413 DINode::DIFlags Flags = (Record.size() > 6)
1414 ? static_cast<DINode::DIFlags>(Record[6])
1415 : DINode::FlagZero;
1416
1417 MetadataList.assignValue(
1418 GET_OR_DISTINCT(DIBasicType,
1419 (Context, Record[1], getMDString(Record[2]), Record[3],
1420 Record[4], Record[5], Flags)),
1421 NextMetadataNo);
1422 NextMetadataNo++;
1423 break;
1424 }
1425 case bitc::METADATA_STRING_TYPE: {
1426 if (Record.size() != 8)
1427 return error("Invalid record");
1428
1429 IsDistinct = Record[0];
1430 MetadataList.assignValue(
1431 GET_OR_DISTINCT(DIStringType,
1432 (Context, Record[1], getMDString(Record[2]),
1433 getMDOrNull(Record[3]), getMDOrNull(Record[4]),
1434 Record[5], Record[6], Record[7])),
1435 NextMetadataNo);
1436 NextMetadataNo++;
1437 break;
1438 }
1439 case bitc::METADATA_DERIVED_TYPE: {
1440 if (Record.size() < 12 || Record.size() > 14)
1441 return error("Invalid record");
1442
1443 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1444 // that there is no DWARF address space associated with DIDerivedType.
1445 Optional<unsigned> DWARFAddressSpace;
1446 if (Record.size() > 12 && Record[12])
1447 DWARFAddressSpace = Record[12] - 1;
1448
1449 Metadata *Annotations = nullptr;
1450 if (Record.size() > 13 && Record[13])
1451 Annotations = getMDOrNull(Record[13]);
1452
1453 IsDistinct = Record[0];
1454 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
1455 MetadataList.assignValue(
1456 GET_OR_DISTINCT(DIDerivedType,
1457 (Context, Record[1], getMDString(Record[2]),
1458 getMDOrNull(Record[3]), Record[4],
1459 getDITypeRefOrNull(Record[5]),
1460 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1461 Record[9], DWARFAddressSpace, Flags,
1462 getDITypeRefOrNull(Record[11]), Annotations)),
1463 NextMetadataNo);
1464 NextMetadataNo++;
1465 break;
1466 }
1467 case bitc::METADATA_COMPOSITE_TYPE: {
1468 if (Record.size() < 16 || Record.size() > 22)
1469 return error("Invalid record");
1470
1471 // If we have a UUID and this is not a forward declaration, lookup the
1472 // mapping.
1473 IsDistinct = Record[0] & 0x1;
1474 bool IsNotUsedInTypeRef = Record[0] >= 2;
1475 unsigned Tag = Record[1];
1476 MDString *Name = getMDString(Record[2]);
1477 Metadata *File = getMDOrNull(Record[3]);
1478 unsigned Line = Record[4];
1479 Metadata *Scope = getDITypeRefOrNull(Record[5]);
1480 Metadata *BaseType = nullptr;
1481 uint64_t SizeInBits = Record[7];
1482 if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
1483 return error("Alignment value is too large");
1484 uint32_t AlignInBits = Record[8];
1485 uint64_t OffsetInBits = 0;
1486 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
1487 Metadata *Elements = nullptr;
1488 unsigned RuntimeLang = Record[12];
1489 Metadata *VTableHolder = nullptr;
1490 Metadata *TemplateParams = nullptr;
1491 Metadata *Discriminator = nullptr;
1492 Metadata *DataLocation = nullptr;
1493 Metadata *Associated = nullptr;
1494 Metadata *Allocated = nullptr;
1495 Metadata *Rank = nullptr;
1496 Metadata *Annotations = nullptr;
1497 auto *Identifier = getMDString(Record[15]);
1498 // If this module is being parsed so that it can be ThinLTO imported
1499 // into another module, composite types only need to be imported
1500 // as type declarations (unless full type definitions requested).
1501 // Create type declarations up front to save memory. Also, buildODRType
1502 // handles the case where this is type ODRed with a definition needed
1503 // by the importing module, in which case the existing definition is
1504 // used.
1505 if (IsImporting && !ImportFullTypeDefinitions && Identifier &&
1506 (Tag == dwarf::DW_TAG_enumeration_type ||
1507 Tag == dwarf::DW_TAG_class_type ||
1508 Tag == dwarf::DW_TAG_structure_type ||
1509 Tag == dwarf::DW_TAG_union_type)) {
1510 Flags = Flags | DINode::FlagFwdDecl;
1511 } else {
1512 BaseType = getDITypeRefOrNull(Record[6]);
1513 OffsetInBits = Record[9];
1514 Elements = getMDOrNull(Record[11]);
1515 VTableHolder = getDITypeRefOrNull(Record[13]);
1516 TemplateParams = getMDOrNull(Record[14]);
1517 if (Record.size() > 16)
1518 Discriminator = getMDOrNull(Record[16]);
1519 if (Record.size() > 17)
1520 DataLocation = getMDOrNull(Record[17]);
1521 if (Record.size() > 19) {
1522 Associated = getMDOrNull(Record[18]);
1523 Allocated = getMDOrNull(Record[19]);
1524 }
1525 if (Record.size() > 20) {
1526 Rank = getMDOrNull(Record[20]);
1527 }
1528 if (Record.size() > 21) {
1529 Annotations = getMDOrNull(Record[21]);
1530 }
1531 }
1532 DICompositeType *CT = nullptr;
1533 if (Identifier)
1534 CT = DICompositeType::buildODRType(
1535 Context, *Identifier, Tag, Name, File, Line, Scope, BaseType,
1536 SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
1537 VTableHolder, TemplateParams, Discriminator, DataLocation, Associated,
1538 Allocated, Rank, Annotations);
1539
1540 // Create a node if we didn't get a lazy ODR type.
1541 if (!CT)
1542 CT = GET_OR_DISTINCT(DICompositeType,
1543 (Context, Tag, Name, File, Line, Scope, BaseType,
1544 SizeInBits, AlignInBits, OffsetInBits, Flags,
1545 Elements, RuntimeLang, VTableHolder, TemplateParams,
1546 Identifier, Discriminator, DataLocation, Associated,
1547 Allocated, Rank, Annotations));
1548 if (!IsNotUsedInTypeRef && Identifier)
1549 MetadataList.addTypeRef(*Identifier, *cast<DICompositeType>(CT));
1550
1551 MetadataList.assignValue(CT, NextMetadataNo);
1552 NextMetadataNo++;
1553 break;
1554 }
1555 case bitc::METADATA_SUBROUTINE_TYPE: {
1556 if (Record.size() < 3 || Record.size() > 4)
1557 return error("Invalid record");
1558 bool IsOldTypeRefArray = Record[0] < 2;
1559 unsigned CC = (Record.size() > 3) ? Record[3] : 0;
1560
1561 IsDistinct = Record[0] & 0x1;
1562 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[1]);
1563 Metadata *Types = getMDOrNull(Record[2]);
1564 if (LLVM_UNLIKELY(IsOldTypeRefArray)__builtin_expect((bool)(IsOldTypeRefArray), false))
1565 Types = MetadataList.upgradeTypeRefArray(Types);
1566
1567 MetadataList.assignValue(
1568 GET_OR_DISTINCT(DISubroutineType, (Context, Flags, CC, Types)),
1569 NextMetadataNo);
1570 NextMetadataNo++;
1571 break;
1572 }
1573
1574 case bitc::METADATA_MODULE: {
1575 if (Record.size() < 5 || Record.size() > 9)
1576 return error("Invalid record");
1577
1578 unsigned Offset = Record.size() >= 8 ? 2 : 1;
1579 IsDistinct = Record[0];
1580 MetadataList.assignValue(
1581 GET_OR_DISTINCT(
1582 DIModule,
1583 (Context, Record.size() >= 8 ? getMDOrNull(Record[1]) : nullptr,
1584 getMDOrNull(Record[0 + Offset]), getMDString(Record[1 + Offset]),
1585 getMDString(Record[2 + Offset]), getMDString(Record[3 + Offset]),
1586 getMDString(Record[4 + Offset]),
1587 Record.size() <= 7 ? 0 : Record[7],
1588 Record.size() <= 8 ? false : Record[8])),
1589 NextMetadataNo);
1590 NextMetadataNo++;
1591 break;
1592 }
1593
1594 case bitc::METADATA_FILE: {
1595 if (Record.size() != 3 && Record.size() != 5 && Record.size() != 6)
1596 return error("Invalid record");
1597
1598 IsDistinct = Record[0];
1599 Optional<DIFile::ChecksumInfo<MDString *>> Checksum;
1600 // The BitcodeWriter writes null bytes into Record[3:4] when the Checksum
1601 // is not present. This matches up with the old internal representation,
1602 // and the old encoding for CSK_None in the ChecksumKind. The new
1603 // representation reserves the value 0 in the ChecksumKind to continue to
1604 // encode None in a backwards-compatible way.
1605 if (Record.size() > 4 && Record[3] && Record[4])
1606 Checksum.emplace(static_cast<DIFile::ChecksumKind>(Record[3]),
1607 getMDString(Record[4]));
1608 MetadataList.assignValue(
1609 GET_OR_DISTINCT(
1610 DIFile,
1611 (Context, getMDString(Record[1]), getMDString(Record[2]), Checksum,
1612 Record.size() > 5 ? Optional<MDString *>(getMDString(Record[5]))
1613 : None)),
1614 NextMetadataNo);
1615 NextMetadataNo++;
1616 break;
1617 }
1618 case bitc::METADATA_COMPILE_UNIT: {
1619 if (Record.size() < 14 || Record.size() > 22)
1620 return error("Invalid record");
1621
1622 // Ignore Record[0], which indicates whether this compile unit is
1623 // distinct. It's always distinct.
1624 IsDistinct = true;
1625 auto *CU = DICompileUnit::getDistinct(
1626 Context, Record[1], getMDOrNull(Record[2]), getMDString(Record[3]),
1627 Record[4], getMDString(Record[5]), Record[6], getMDString(Record[7]),
1628 Record[8], getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1629 getMDOrNull(Record[12]), getMDOrNull(Record[13]),
1630 Record.size() <= 15 ? nullptr : getMDOrNull(Record[15]),
1631 Record.size() <= 14 ? 0 : Record[14],
1632 Record.size() <= 16 ? true : Record[16],
1633 Record.size() <= 17 ? false : Record[17],
1634 Record.size() <= 18 ? 0 : Record[18],
1635 Record.size() <= 19 ? false : Record[19],
1636 Record.size() <= 20 ? nullptr : getMDString(Record[20]),
1637 Record.size() <= 21 ? nullptr : getMDString(Record[21]));
1638
1639 MetadataList.assignValue(CU, NextMetadataNo);
1640 NextMetadataNo++;
1641
1642 // Move the Upgrade the list of subprograms.
1643 if (Metadata *SPs = getMDOrNullWithoutPlaceholders(Record[11]))
1644 CUSubprograms.push_back({CU, SPs});
1645 break;
1646 }
1647 case bitc::METADATA_SUBPROGRAM: {
1648 if (Record.size() < 18 || Record.size() > 21)
1649 return error("Invalid record");
1650
1651 bool HasSPFlags = Record[0] & 4;
1652
1653 DINode::DIFlags Flags;
1654 DISubprogram::DISPFlags SPFlags;
1655 if (!HasSPFlags)
1656 Flags = static_cast<DINode::DIFlags>(Record[11 + 2]);
1657 else {
1658 Flags = static_cast<DINode::DIFlags>(Record[11]);
1659 SPFlags = static_cast<DISubprogram::DISPFlags>(Record[9]);
1660 }
1661
1662 // Support for old metadata when
1663 // subprogram specific flags are placed in DIFlags.
1664 const unsigned DIFlagMainSubprogram = 1 << 21;
1665 bool HasOldMainSubprogramFlag = Flags & DIFlagMainSubprogram;
1666 if (HasOldMainSubprogramFlag)
1667 // Remove old DIFlagMainSubprogram from DIFlags.
1668 // Note: This assumes that any future use of bit 21 defaults to it
1669 // being 0.
1670 Flags &= ~static_cast<DINode::DIFlags>(DIFlagMainSubprogram);
1671
1672 if (HasOldMainSubprogramFlag && HasSPFlags)
1673 SPFlags |= DISubprogram::SPFlagMainSubprogram;
1674 else if (!HasSPFlags)
1675 SPFlags = DISubprogram::toSPFlags(
1676 /*IsLocalToUnit=*/Record[7], /*IsDefinition=*/Record[8],
1677 /*IsOptimized=*/Record[14], /*Virtuality=*/Record[11],
1678 /*IsMainSubprogram=*/HasOldMainSubprogramFlag);
1679
1680 // All definitions should be distinct.
1681 IsDistinct = (Record[0] & 1) || (SPFlags & DISubprogram::SPFlagDefinition);
1682 // Version 1 has a Function as Record[15].
1683 // Version 2 has removed Record[15].
1684 // Version 3 has the Unit as Record[15].
1685 // Version 4 added thisAdjustment.
1686 // Version 5 repacked flags into DISPFlags, changing many element numbers.
1687 bool HasUnit = Record[0] & 2;
1688 if (!HasSPFlags && HasUnit && Record.size() < 19)
1689 return error("Invalid record");
1690 if (HasSPFlags && !HasUnit)
1691 return error("Invalid record");
1692 // Accommodate older formats.
1693 bool HasFn = false;
1694 bool HasThisAdj = true;
1695 bool HasThrownTypes = true;
1696 bool HasAnnotations = false;
1697 unsigned OffsetA = 0;
1698 unsigned OffsetB = 0;
1699 if (!HasSPFlags) {
1700 OffsetA = 2;
1701 OffsetB = 2;
1702 if (Record.size() >= 19) {
1703 HasFn = !HasUnit;
1704 OffsetB++;
1705 }
1706 HasThisAdj = Record.size() >= 20;
1707 HasThrownTypes = Record.size() >= 21;
1708 } else {
1709 HasAnnotations = Record.size() >= 19;
1710 }
1711 Metadata *CUorFn = getMDOrNull(Record[12 + OffsetB]);
1712 DISubprogram *SP = GET_OR_DISTINCT(
1713 DISubprogram,
1714 (Context,
1715 getDITypeRefOrNull(Record[1]), // scope
1716 getMDString(Record[2]), // name
1717 getMDString(Record[3]), // linkageName
1718 getMDOrNull(Record[4]), // file
1719 Record[5], // line
1720 getMDOrNull(Record[6]), // type
1721 Record[7 + OffsetA], // scopeLine
1722 getDITypeRefOrNull(Record[8 + OffsetA]), // containingType
1723 Record[10 + OffsetA], // virtualIndex
1724 HasThisAdj ? Record[16 + OffsetB] : 0, // thisAdjustment
1725 Flags, // flags
1726 SPFlags, // SPFlags
1727 HasUnit ? CUorFn : nullptr, // unit
1728 getMDOrNull(Record[13 + OffsetB]), // templateParams
1729 getMDOrNull(Record[14 + OffsetB]), // declaration
1730 getMDOrNull(Record[15 + OffsetB]), // retainedNodes
1731 HasThrownTypes ? getMDOrNull(Record[17 + OffsetB])
1732 : nullptr, // thrownTypes
1733 HasAnnotations ? getMDOrNull(Record[18 + OffsetB])
1734 : nullptr // annotations
1735 ));
1736 MetadataList.assignValue(SP, NextMetadataNo);
1737 NextMetadataNo++;
1738
1739 // Upgrade sp->function mapping to function->sp mapping.
1740 if (HasFn) {
1741 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(CUorFn))
1742 if (auto *F = dyn_cast<Function>(CMD->getValue())) {
1743 if (F->isMaterializable())
1744 // Defer until materialized; unmaterialized functions may not have
1745 // metadata.
1746 FunctionsWithSPs[F] = SP;
1747 else if (!F->empty())
1748 F->setSubprogram(SP);
1749 }
1750 }
1751 break;
1752 }
1753 case bitc::METADATA_LEXICAL_BLOCK: {
1754 if (Record.size() != 5)
1755 return error("Invalid record");
1756
1757 IsDistinct = Record[0];
1758 MetadataList.assignValue(
1759 GET_OR_DISTINCT(DILexicalBlock,
1760 (Context, getMDOrNull(Record[1]),
1761 getMDOrNull(Record[2]), Record[3], Record[4])),
1762 NextMetadataNo);
1763 NextMetadataNo++;
1764 break;
1765 }
1766 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
1767 if (Record.size() != 4)
1768 return error("Invalid record");
1769
1770 IsDistinct = Record[0];
1771 MetadataList.assignValue(
1772 GET_OR_DISTINCT(DILexicalBlockFile,
1773 (Context, getMDOrNull(Record[1]),
1774 getMDOrNull(Record[2]), Record[3])),
1775 NextMetadataNo);
1776 NextMetadataNo++;
1777 break;
1778 }
1779 case bitc::METADATA_COMMON_BLOCK: {
1780 IsDistinct = Record[0] & 1;
1781 MetadataList.assignValue(
1782 GET_OR_DISTINCT(DICommonBlock,
1783 (Context, getMDOrNull(Record[1]),
1784 getMDOrNull(Record[2]), getMDString(Record[3]),
1785 getMDOrNull(Record[4]), Record[5])),
1786 NextMetadataNo);
1787 NextMetadataNo++;
1788 break;
1789 }
1790 case bitc::METADATA_NAMESPACE: {
1791 // Newer versions of DINamespace dropped file and line.
1792 MDString *Name;
1793 if (Record.size() == 3)
1794 Name = getMDString(Record[2]);
1795 else if (Record.size() == 5)
1796 Name = getMDString(Record[3]);
1797 else
1798 return error("Invalid record");
1799
1800 IsDistinct = Record[0] & 1;
1801 bool ExportSymbols = Record[0] & 2;
1802 MetadataList.assignValue(
1803 GET_OR_DISTINCT(DINamespace,
1804 (Context, getMDOrNull(Record[1]), Name, ExportSymbols)),
1805 NextMetadataNo);
1806 NextMetadataNo++;
1807 break;
1808 }
1809 case bitc::METADATA_MACRO: {
1810 if (Record.size() != 5)
1811 return error("Invalid record");
1812
1813 IsDistinct = Record[0];
1814 MetadataList.assignValue(
1815 GET_OR_DISTINCT(DIMacro,
1816 (Context, Record[1], Record[2], getMDString(Record[3]),
1817 getMDString(Record[4]))),
1818 NextMetadataNo);
1819 NextMetadataNo++;
1820 break;
1821 }
1822 case bitc::METADATA_MACRO_FILE: {
1823 if (Record.size() != 5)
1824 return error("Invalid record");
1825
1826 IsDistinct = Record[0];
1827 MetadataList.assignValue(
1828 GET_OR_DISTINCT(DIMacroFile,
1829 (Context, Record[1], Record[2], getMDOrNull(Record[3]),
1830 getMDOrNull(Record[4]))),
1831 NextMetadataNo);
1832 NextMetadataNo++;
1833 break;
1834 }
1835 case bitc::METADATA_TEMPLATE_TYPE: {
1836 if (Record.size() < 3 || Record.size() > 4)
1837 return error("Invalid record");
1838
1839 IsDistinct = Record[0];
1840 MetadataList.assignValue(
1841 GET_OR_DISTINCT(DITemplateTypeParameter,
1842 (Context, getMDString(Record[1]),
1843 getDITypeRefOrNull(Record[2]),
1844 (Record.size() == 4) ? getMDOrNull(Record[3])
1845 : getMDOrNull(false))),
1846 NextMetadataNo);
1847 NextMetadataNo++;
1848 break;
1849 }
1850 case bitc::METADATA_TEMPLATE_VALUE: {
1851 if (Record.size() < 5 || Record.size() > 6)
1852 return error("Invalid record");
1853
1854 IsDistinct = Record[0];
1855
1856 MetadataList.assignValue(
1857 GET_OR_DISTINCT(
1858 DITemplateValueParameter,
1859 (Context, Record[1], getMDString(Record[2]),
1860 getDITypeRefOrNull(Record[3]),
1861 (Record.size() == 6) ? getMDOrNull(Record[4]) : getMDOrNull(false),
1862 (Record.size() == 6) ? getMDOrNull(Record[5])
1863 : getMDOrNull(Record[4]))),
1864 NextMetadataNo);
1865 NextMetadataNo++;
1866 break;
1867 }
1868 case bitc::METADATA_GLOBAL_VAR: {
1869 if (Record.size() < 11 || Record.size() > 13)
1870 return error("Invalid record");
1871
1872 IsDistinct = Record[0] & 1;
1873 unsigned Version = Record[0] >> 1;
1874
1875 if (Version == 2) {
1876 Metadata *Annotations = nullptr;
1877 if (Record.size() > 12)
1878 Annotations = getMDOrNull(Record[12]);
1879
1880 MetadataList.assignValue(
1881 GET_OR_DISTINCT(DIGlobalVariable,
1882 (Context, getMDOrNull(Record[1]),
1883 getMDString(Record[2]), getMDString(Record[3]),
1884 getMDOrNull(Record[4]), Record[5],
1885 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1886 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1887 Record[11], Annotations)),
1888 NextMetadataNo);
1889
1890 NextMetadataNo++;
1891 } else if (Version == 1) {
1892 // No upgrade necessary. A null field will be introduced to indicate
1893 // that no parameter information is available.
1894 MetadataList.assignValue(
1895 GET_OR_DISTINCT(
1896 DIGlobalVariable,
1897 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1898 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1899 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1900 getMDOrNull(Record[10]), nullptr, Record[11], nullptr)),
1901 NextMetadataNo);
1902
1903 NextMetadataNo++;
1904 } else if (Version == 0) {
1905 // Upgrade old metadata, which stored a global variable reference or a
1906 // ConstantInt here.
1907 NeedUpgradeToDIGlobalVariableExpression = true;
1908 Metadata *Expr = getMDOrNull(Record[9]);
1909 uint32_t AlignInBits = 0;
1910 if (Record.size() > 11) {
1911 if (Record[11] > (uint64_t)std::numeric_limits<uint32_t>::max())
1912 return error("Alignment value is too large");
1913 AlignInBits = Record[11];
1914 }
1915 GlobalVariable *Attach = nullptr;
1916 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(Expr)) {
1917 if (auto *GV = dyn_cast<GlobalVariable>(CMD->getValue())) {
1918 Attach = GV;
1919 Expr = nullptr;
1920 } else if (auto *CI = dyn_cast<ConstantInt>(CMD->getValue())) {
1921 Expr = DIExpression::get(Context,
1922 {dwarf::DW_OP_constu, CI->getZExtValue(),
1923 dwarf::DW_OP_stack_value});
1924 } else {
1925 Expr = nullptr;
1926 }
1927 }
1928 DIGlobalVariable *DGV = GET_OR_DISTINCT(
1929 DIGlobalVariable,
1930 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1931 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1932 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1933 getMDOrNull(Record[10]), nullptr, AlignInBits, nullptr));
1934
1935 DIGlobalVariableExpression *DGVE = nullptr;
1936 if (Attach || Expr)
1937 DGVE = DIGlobalVariableExpression::getDistinct(
1938 Context, DGV, Expr ? Expr : DIExpression::get(Context, {}));
1939 if (Attach)
1940 Attach->addDebugInfo(DGVE);
1941
1942 auto *MDNode = Expr ? cast<Metadata>(DGVE) : cast<Metadata>(DGV);
1943 MetadataList.assignValue(MDNode, NextMetadataNo);
1944 NextMetadataNo++;
1945 } else
1946 return error("Invalid record");
1947
1948 break;
1949 }
1950 case bitc::METADATA_LOCAL_VAR: {
1951 // 10th field is for the obseleted 'inlinedAt:' field.
1952 if (Record.size() < 8 || Record.size() > 10)
1953 return error("Invalid record");
1954
1955 IsDistinct = Record[0] & 1;
1956 bool HasAlignment = Record[0] & 2;
1957 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
1958 // DW_TAG_arg_variable, if we have alignment flag encoded it means, that
1959 // this is newer version of record which doesn't have artificial tag.
1960 bool HasTag = !HasAlignment && Record.size() > 8;
1961 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[7 + HasTag]);
1962 uint32_t AlignInBits = 0;
1963 Metadata *Annotations = nullptr;
1964 if (HasAlignment) {
1965 if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
1966 return error("Alignment value is too large");
1967 AlignInBits = Record[8];
1968 if (Record.size() > 9)
1969 Annotations = getMDOrNull(Record[9]);
1970 }
1971
1972 MetadataList.assignValue(
1973 GET_OR_DISTINCT(DILocalVariable,
1974 (Context, getMDOrNull(Record[1 + HasTag]),
1975 getMDString(Record[2 + HasTag]),
1976 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
1977 getDITypeRefOrNull(Record[5 + HasTag]),
1978 Record[6 + HasTag], Flags, AlignInBits, Annotations)),
1979 NextMetadataNo);
1980 NextMetadataNo++;
1981 break;
1982 }
1983 case bitc::METADATA_LABEL: {
1984 if (Record.size() != 5)
1985 return error("Invalid record");
1986
1987 IsDistinct = Record[0] & 1;
1988 MetadataList.assignValue(
1989 GET_OR_DISTINCT(DILabel, (Context, getMDOrNull(Record[1]),
1990 getMDString(Record[2]),
1991 getMDOrNull(Record[3]), Record[4])),
1992 NextMetadataNo);
1993 NextMetadataNo++;
1994 break;
1995 }
1996 case bitc::METADATA_EXPRESSION: {
1997 if (Record.size() < 1)
1998 return error("Invalid record");
1999
2000 IsDistinct = Record[0] & 1;
2001 uint64_t Version = Record[0] >> 1;
2002 auto Elts = MutableArrayRef<uint64_t>(Record).slice(1);
2003
2004 SmallVector<uint64_t, 6> Buffer;
2005 if (Error Err = upgradeDIExpression(Version, Elts, Buffer))
2006 return Err;
2007
2008 MetadataList.assignValue(GET_OR_DISTINCT(DIExpression, (Context, Elts)),
2009 NextMetadataNo);
2010 NextMetadataNo++;
2011 break;
2012 }
2013 case bitc::METADATA_GLOBAL_VAR_EXPR: {
2014 if (Record.size() != 3)
2015 return error("Invalid record");
2016
2017 IsDistinct = Record[0];
2018 Metadata *Expr = getMDOrNull(Record[2]);
2019 if (!Expr)
2020 Expr = DIExpression::get(Context, {});
2021 MetadataList.assignValue(
2022 GET_OR_DISTINCT(DIGlobalVariableExpression,
2023 (Context, getMDOrNull(Record[1]), Expr)),
2024 NextMetadataNo);
2025 NextMetadataNo++;
2026 break;
2027 }
2028 case bitc::METADATA_OBJC_PROPERTY: {
2029 if (Record.size() != 8)
2030 return error("Invalid record");
2031
2032 IsDistinct = Record[0];
2033 MetadataList.assignValue(
2034 GET_OR_DISTINCT(DIObjCProperty,
2035 (Context, getMDString(Record[1]),
2036 getMDOrNull(Record[2]), Record[3],
2037 getMDString(Record[4]), getMDString(Record[5]),
2038 Record[6], getDITypeRefOrNull(Record[7]))),
2039 NextMetadataNo);
2040 NextMetadataNo++;
2041 break;
2042 }
2043 case bitc::METADATA_IMPORTED_ENTITY: {
2044 if (Record.size() < 6 && Record.size() > 8)
2045 return error("Invalid record");
2046
2047 IsDistinct = Record[0];
2048 bool HasFile = (Record.size() >= 7);
2049 bool HasElements = (Record.size() >= 8);
2050 MetadataList.assignValue(
2051 GET_OR_DISTINCT(DIImportedEntity,
2052 (Context, Record[1], getMDOrNull(Record[2]),
2053 getDITypeRefOrNull(Record[3]),
2054 HasFile ? getMDOrNull(Record[6]) : nullptr,
2055 HasFile ? Record[4] : 0, getMDString(Record[5]),
2056 HasElements ? getMDOrNull(Record[7]) : nullptr)),
2057 NextMetadataNo);
2058 NextMetadataNo++;
2059 break;
2060 }
2061 case bitc::METADATA_STRING_OLD: {
2062 std::string String(Record.begin(), Record.end());
2063
2064 // Test for upgrading !llvm.loop.
2065 HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String);
2066 ++NumMDStringLoaded;
2067 Metadata *MD = MDString::get(Context, String);
2068 MetadataList.assignValue(MD, NextMetadataNo);
2069 NextMetadataNo++;
2070 break;
2071 }
2072 case bitc::METADATA_STRINGS: {
2073 auto CreateNextMDString = [&](StringRef Str) {
2074 ++NumMDStringLoaded;
2075 MetadataList.assignValue(MDString::get(Context, Str), NextMetadataNo);
2076 NextMetadataNo++;
2077 };
2078 if (Error Err = parseMetadataStrings(Record, Blob, CreateNextMDString))
2079 return Err;
2080 break;
2081 }
2082 case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
2083 if (Record.size() % 2 == 0)
2084 return error("Invalid record");
2085 unsigned ValueID = Record[0];
2086 if (ValueID >= ValueList.size())
2087 return error("Invalid record");
2088 if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID]))
2089 if (Error Err = parseGlobalObjectAttachment(
2090 *GO, ArrayRef<uint64_t>(Record).slice(1)))
2091 return Err;
2092 break;
2093 }
2094 case bitc::METADATA_KIND: {
2095 // Support older bitcode files that had METADATA_KIND records in a
2096 // block with METADATA_BLOCK_ID.
2097 if (Error Err = parseMetadataKindRecord(Record))
2098 return Err;
2099 break;
2100 }
2101 case bitc::METADATA_ARG_LIST: {
2102 SmallVector<ValueAsMetadata *, 4> Elts;
2103 Elts.reserve(Record.size());
2104 for (uint64_t Elt : Record) {
2105 Metadata *MD = getMD(Elt);
2106 if (isa<MDNode>(MD) && cast<MDNode>(MD)->isTemporary())
2107 return error(
2108 "Invalid record: DIArgList should not contain forward refs");
2109 if (!isa<ValueAsMetadata>(MD))
2110 return error("Invalid record");
2111 Elts.push_back(cast<ValueAsMetadata>(MD));
2112 }
2113
2114 MetadataList.assignValue(DIArgList::get(Context, Elts), NextMetadataNo);
2115 NextMetadataNo++;
2116 break;
2117 }
2118 }
2119 return Error::success();
2120#undef GET_OR_DISTINCT
2121}
2122
2123Error MetadataLoader::MetadataLoaderImpl::parseMetadataStrings(
2124 ArrayRef<uint64_t> Record, StringRef Blob,
2125 function_ref<void(StringRef)> CallBack) {
2126 // All the MDStrings in the block are emitted together in a single
2127 // record. The strings are concatenated and stored in a blob along with
2128 // their sizes.
2129 if (Record.size() != 2)
2130 return error("Invalid record: metadata strings layout");
2131
2132 unsigned NumStrings = Record[0];
2133 unsigned StringsOffset = Record[1];
2134 if (!NumStrings)
2135 return error("Invalid record: metadata strings with no strings");
2136 if (StringsOffset > Blob.size())
2137 return error("Invalid record: metadata strings corrupt offset");
2138
2139 StringRef Lengths = Blob.slice(0, StringsOffset);
2140 SimpleBitstreamCursor R(Lengths);
2141
2142 StringRef Strings = Blob.drop_front(StringsOffset);
2143 do {
2144 if (R.AtEndOfStream())
2145 return error("Invalid record: metadata strings bad length");
2146
2147 uint32_t Size;
2148 if (Error E = R.ReadVBR(6).moveInto(Size))
2149 return E;
2150 if (Strings.size() < Size)
2151 return error("Invalid record: metadata strings truncated chars");
2152
2153 CallBack(Strings.slice(0, Size));
2154 Strings = Strings.drop_front(Size);
2155 } while (--NumStrings);
2156
2157 return Error::success();
2158}
2159
2160Error MetadataLoader::MetadataLoaderImpl::parseGlobalObjectAttachment(
2161 GlobalObject &GO, ArrayRef<uint64_t> Record) {
2162 assert(Record.size() % 2 == 0)(static_cast <bool> (Record.size() % 2 == 0) ? void (0)
: __assert_fail ("Record.size() % 2 == 0", "llvm/lib/Bitcode/Reader/MetadataLoader.cpp"
, 2162, __extension__ __PRETTY_FUNCTION__))
;
14
Assuming the condition is true
15
'?' condition is true
2163 for (unsigned I = 0, E = Record.size(); I != E; I += 2) {
16
Assuming 'I' is not equal to 'E'
17
Loop condition is true. Entering loop body
2164 auto K = MDKindMap.find(Record[I]);
2165 if (K == MDKindMap.end())
18
Taking false branch
2166 return error("Invalid ID");
2167 MDNode *MD =
2168 dyn_cast_or_null<MDNode>(getMetadataFwdRefOrLoad(Record[I + 1]));
19
Calling 'MetadataLoaderImpl::getMetadataFwdRefOrLoad'
2169 if (!MD)
2170 return error("Invalid metadata attachment: expect fwd ref to MDNode");
2171 GO.addMetadata(K->second, *MD);
2172 }
2173 return Error::success();
2174}
2175
2176/// Parse metadata attachments.
2177Error MetadataLoader::MetadataLoaderImpl::parseMetadataAttachment(
2178 Function &F, const SmallVectorImpl<Instruction *> &InstructionList) {
2179 if (Error Err = Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2
Assuming the condition is false
3
Taking false branch
2180 return Err;
2181
2182 SmallVector<uint64_t, 64> Record;
2183 PlaceholderQueue Placeholders;
2184
2185 while (true) {
4
Loop condition is true. Entering loop body
2186 BitstreamEntry Entry;
2187 if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
5
Taking false branch
2188 return E;
2189
2190 switch (Entry.Kind) {
6
Control jumps to 'case Record:' at line 2197
2191 case BitstreamEntry::SubBlock: // Handled for us already.
2192 case BitstreamEntry::Error:
2193 return error("Malformed block");
2194 case BitstreamEntry::EndBlock:
2195 resolveForwardRefsAndPlaceholders(Placeholders);
2196 return Error::success();
2197 case BitstreamEntry::Record:
2198 // The interesting case.
2199 break;
7
Execution continues on line 2203
2200 }
2201
2202 // Read a metadata attachment record.
2203 Record.clear();
2204 ++NumMDRecordLoaded;
2205 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2206 if (!MaybeRecord)
8
Taking false branch
2207 return MaybeRecord.takeError();
2208 switch (MaybeRecord.get()) {
9
Control jumps to 'case METADATA_ATTACHMENT:' at line 2211
2209 default: // Default behavior: ignore.
2210 break;
2211 case bitc::METADATA_ATTACHMENT: {
2212 unsigned RecordLength = Record.size();
2213 if (Record.empty())
10
Taking false branch
2214 return error("Invalid record");
2215 if (RecordLength % 2 == 0) {
11
Assuming the condition is true
12
Taking true branch
2216 // A function attachment.
2217 if (Error Err = parseGlobalObjectAttachment(F, Record))
13
Calling 'MetadataLoaderImpl::parseGlobalObjectAttachment'
2218 return Err;
2219 continue;
2220 }
2221
2222 // An instruction attachment.
2223 Instruction *Inst = InstructionList[Record[0]];
2224 for (unsigned i = 1; i != RecordLength; i = i + 2) {
2225 unsigned Kind = Record[i];
2226 DenseMap<unsigned, unsigned>::iterator I = MDKindMap.find(Kind);
2227 if (I == MDKindMap.end())
2228 return error("Invalid ID");
2229 if (I->second == LLVMContext::MD_tbaa && StripTBAA)
2230 continue;
2231
2232 auto Idx = Record[i + 1];
2233 if (Idx < (MDStringRef.size() + GlobalMetadataBitPosIndex.size()) &&
2234 !MetadataList.lookup(Idx)) {
2235 // Load the attachment if it is in the lazy-loadable range and hasn't
2236 // been loaded yet.
2237 lazyLoadOneMetadata(Idx, Placeholders);
2238 resolveForwardRefsAndPlaceholders(Placeholders);
2239 }
2240
2241 Metadata *Node = MetadataList.getMetadataFwdRef(Idx);
2242 if (isa<LocalAsMetadata>(Node))
2243 // Drop the attachment. This used to be legal, but there's no
2244 // upgrade path.
2245 break;
2246 MDNode *MD = dyn_cast_or_null<MDNode>(Node);
2247 if (!MD)
2248 return error("Invalid metadata attachment");
2249
2250 if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop)
2251 MD = upgradeInstructionLoopAttachment(*MD);
2252
2253 if (I->second == LLVMContext::MD_tbaa) {
2254 assert(!MD->isTemporary() && "should load MDs before attachments")(static_cast <bool> (!MD->isTemporary() && "should load MDs before attachments"
) ? void (0) : __assert_fail ("!MD->isTemporary() && \"should load MDs before attachments\""
, "llvm/lib/Bitcode/Reader/MetadataLoader.cpp", 2254, __extension__
__PRETTY_FUNCTION__))
;
2255 MD = UpgradeTBAANode(*MD);
2256 }
2257 Inst->setMetadata(I->second, MD);
2258 }
2259 break;
2260 }
2261 }
2262 }
2263}
2264
2265/// Parse a single METADATA_KIND record, inserting result in MDKindMap.
2266Error MetadataLoader::MetadataLoaderImpl::parseMetadataKindRecord(
2267 SmallVectorImpl<uint64_t> &Record) {
2268 if (Record.size() < 2)
2269 return error("Invalid record");
2270
2271 unsigned Kind = Record[0];
2272 SmallString<8> Name(Record.begin() + 1, Record.end());
2273
2274 unsigned NewKind = TheModule.getMDKindID(Name.str());
2275 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2276 return error("Conflicting METADATA_KIND records");
2277 return Error::success();
2278}
2279
2280/// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
2281Error MetadataLoader::MetadataLoaderImpl::parseMetadataKinds() {
2282 if (Error Err = Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
2283 return Err;
2284
2285 SmallVector<uint64_t, 64> Record;
2286
2287 // Read all the records.
2288 while (true) {
2289 BitstreamEntry Entry;
2290 if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
2291 return E;
2292
2293 switch (Entry.Kind) {
2294 case BitstreamEntry::SubBlock: // Handled for us already.
2295 case BitstreamEntry::Error:
2296 return error("Malformed block");
2297 case BitstreamEntry::EndBlock:
2298 return Error::success();
2299 case BitstreamEntry::Record:
2300 // The interesting case.
2301 break;
2302 }
2303
2304 // Read a record.
2305 Record.clear();
2306 ++NumMDRecordLoaded;
2307 Expected<unsigned> MaybeCode = Stream.readRecord(Entry.ID, Record);
2308 if (!MaybeCode)
2309 return MaybeCode.takeError();
2310 switch (MaybeCode.get()) {
2311 default: // Default behavior: ignore.
2312 break;
2313 case bitc::METADATA_KIND: {
2314 if (Error Err = parseMetadataKindRecord(Record))
2315 return Err;
2316 break;
2317 }
2318 }
2319 }
2320}
2321
2322MetadataLoader &MetadataLoader::operator=(MetadataLoader &&RHS) {
2323 Pimpl = std::move(RHS.Pimpl);
2324 return *this;
2325}
2326MetadataLoader::MetadataLoader(MetadataLoader &&RHS)
2327 : Pimpl(std::move(RHS.Pimpl)) {}
2328
2329MetadataLoader::~MetadataLoader() = default;
2330MetadataLoader::MetadataLoader(BitstreamCursor &Stream, Module &TheModule,
2331 BitcodeReaderValueList &ValueList,
2332 bool IsImporting,
2333 std::function<Type *(unsigned)> getTypeByID)
2334 : Pimpl(std::make_unique<MetadataLoaderImpl>(
2335 Stream, TheModule, ValueList, std::move(getTypeByID), IsImporting)) {}
2336
2337Error MetadataLoader::parseMetadata(bool ModuleLevel) {
2338 return Pimpl->parseMetadata(ModuleLevel);
2339}
2340
2341bool MetadataLoader::hasFwdRefs() const { return Pimpl->hasFwdRefs(); }
2342
2343/// Return the given metadata, creating a replaceable forward reference if
2344/// necessary.
2345Metadata *MetadataLoader::getMetadataFwdRefOrLoad(unsigned Idx) {
2346 return Pimpl->getMetadataFwdRefOrLoad(Idx);
2347}
2348
2349DISubprogram *MetadataLoader::lookupSubprogramForFunction(Function *F) {
2350 return Pimpl->lookupSubprogramForFunction(F);
2351}
2352
2353Error MetadataLoader::parseMetadataAttachment(
2354 Function &F, const SmallVectorImpl<Instruction *> &InstructionList) {
2355 return Pimpl->parseMetadataAttachment(F, InstructionList);
1
Calling 'MetadataLoaderImpl::parseMetadataAttachment'
2356}
2357
2358Error MetadataLoader::parseMetadataKinds() {
2359 return Pimpl->parseMetadataKinds();
2360}
2361
2362void MetadataLoader::setStripTBAA(bool StripTBAA) {
2363 return Pimpl->setStripTBAA(StripTBAA);
2364}
2365
2366bool MetadataLoader::isStrippingTBAA() { return Pimpl->isStrippingTBAA(); }
2367
2368unsigned MetadataLoader::size() const { return Pimpl->size(); }
2369void MetadataLoader::shrinkTo(unsigned N) { return Pimpl->shrinkTo(N); }
2370
2371void MetadataLoader::upgradeDebugIntrinsics(Function &F) {
2372 return Pimpl->upgradeDebugIntrinsics(F);
2373}

/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/llvm/include/llvm/Support/Error.h

1//===- llvm/Support/Error.h - Recoverable error handling --------*- C++ -*-===//
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 defines an API used to report recoverable errors.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_SUPPORT_ERROR_H
14#define LLVM_SUPPORT_ERROR_H
15
16#include "llvm-c/Error.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/StringExtras.h"
20#include "llvm/ADT/Twine.h"
21#include "llvm/Config/abi-breaking.h"
22#include "llvm/Support/AlignOf.h"
23#include "llvm/Support/Compiler.h"
24#include "llvm/Support/Debug.h"
25#include "llvm/Support/ErrorHandling.h"
26#include "llvm/Support/ErrorOr.h"
27#include "llvm/Support/Format.h"
28#include "llvm/Support/raw_ostream.h"
29#include <algorithm>
30#include <cassert>
31#include <cstdint>
32#include <cstdlib>
33#include <functional>
34#include <memory>
35#include <new>
36#include <string>
37#include <system_error>
38#include <type_traits>
39#include <utility>
40#include <vector>
41
42namespace llvm {
43
44class ErrorSuccess;
45
46/// Base class for error info classes. Do not extend this directly: Extend
47/// the ErrorInfo template subclass instead.
48class ErrorInfoBase {
49public:
50 virtual ~ErrorInfoBase() = default;
51
52 /// Print an error message to an output stream.
53 virtual void log(raw_ostream &OS) const = 0;
54
55 /// Return the error message as a string.
56 virtual std::string message() const {
57 std::string Msg;
58 raw_string_ostream OS(Msg);
59 log(OS);
60 return OS.str();
61 }
62
63 /// Convert this error to a std::error_code.
64 ///
65 /// This is a temporary crutch to enable interaction with code still
66 /// using std::error_code. It will be removed in the future.
67 virtual std::error_code convertToErrorCode() const = 0;
68
69 // Returns the class ID for this type.
70 static const void *classID() { return &ID; }
71
72 // Returns the class ID for the dynamic type of this ErrorInfoBase instance.
73 virtual const void *dynamicClassID() const = 0;
74
75 // Check whether this instance is a subclass of the class identified by
76 // ClassID.
77 virtual bool isA(const void *const ClassID) const {
78 return ClassID == classID();
79 }
80
81 // Check whether this instance is a subclass of ErrorInfoT.
82 template <typename ErrorInfoT> bool isA() const {
83 return isA(ErrorInfoT::classID());
84 }
85
86private:
87 virtual void anchor();
88
89 static char ID;
90};
91
92/// Lightweight error class with error context and mandatory checking.
93///
94/// Instances of this class wrap a ErrorInfoBase pointer. Failure states
95/// are represented by setting the pointer to a ErrorInfoBase subclass
96/// instance containing information describing the failure. Success is
97/// represented by a null pointer value.
98///
99/// Instances of Error also contains a 'Checked' flag, which must be set
100/// before the destructor is called, otherwise the destructor will trigger a
101/// runtime error. This enforces at runtime the requirement that all Error
102/// instances be checked or returned to the caller.
103///
104/// There are two ways to set the checked flag, depending on what state the
105/// Error instance is in. For Error instances indicating success, it
106/// is sufficient to invoke the boolean conversion operator. E.g.:
107///
108/// @code{.cpp}
109/// Error foo(<...>);
110///
111/// if (auto E = foo(<...>))
112/// return E; // <- Return E if it is in the error state.
113/// // We have verified that E was in the success state. It can now be safely
114/// // destroyed.
115/// @endcode
116///
117/// A success value *can not* be dropped. For example, just calling 'foo(<...>)'
118/// without testing the return value will raise a runtime error, even if foo
119/// returns success.
120///
121/// For Error instances representing failure, you must use either the
122/// handleErrors or handleAllErrors function with a typed handler. E.g.:
123///
124/// @code{.cpp}
125/// class MyErrorInfo : public ErrorInfo<MyErrorInfo> {
126/// // Custom error info.
127/// };
128///
129/// Error foo(<...>) { return make_error<MyErrorInfo>(...); }
130///
131/// auto E = foo(<...>); // <- foo returns failure with MyErrorInfo.
132/// auto NewE =
133/// handleErrors(E,
134/// [](const MyErrorInfo &M) {
135/// // Deal with the error.
136/// },
137/// [](std::unique_ptr<OtherError> M) -> Error {
138/// if (canHandle(*M)) {
139/// // handle error.
140/// return Error::success();
141/// }
142/// // Couldn't handle this error instance. Pass it up the stack.
143/// return Error(std::move(M));
144/// );
145/// // Note - we must check or return NewE in case any of the handlers
146/// // returned a new error.
147/// @endcode
148///
149/// The handleAllErrors function is identical to handleErrors, except
150/// that it has a void return type, and requires all errors to be handled and
151/// no new errors be returned. It prevents errors (assuming they can all be
152/// handled) from having to be bubbled all the way to the top-level.
153///
154/// *All* Error instances must be checked before destruction, even if
155/// they're moved-assigned or constructed from Success values that have already
156/// been checked. This enforces checking through all levels of the call stack.
157class LLVM_NODISCARD[[clang::warn_unused_result]] Error {
158 // ErrorList needs to be able to yank ErrorInfoBase pointers out of Errors
159 // to add to the error list. It can't rely on handleErrors for this, since
160 // handleErrors does not support ErrorList handlers.
161 friend class ErrorList;
162
163 // handleErrors needs to be able to set the Checked flag.
164 template <typename... HandlerTs>
165 friend Error handleErrors(Error E, HandlerTs &&... Handlers);
166
167 // Expected<T> needs to be able to steal the payload when constructed from an
168 // error.
169 template <typename T> friend class Expected;
170
171 // wrap needs to be able to steal the payload.
172 friend LLVMErrorRef wrap(Error);
173
174protected:
175 /// Create a success value. Prefer using 'Error::success()' for readability
176 Error() {
177 setPtr(nullptr);
178 setChecked(false);
179 }
180
181public:
182 /// Create a success value.
183 static ErrorSuccess success();
184
185 // Errors are not copy-constructable.
186 Error(const Error &Other) = delete;
187
188 /// Move-construct an error value. The newly constructed error is considered
189 /// unchecked, even if the source error had been checked. The original error
190 /// becomes a checked Success value, regardless of its original state.
191 Error(Error &&Other) {
192 setChecked(true);
193 *this = std::move(Other);
194 }
195
196 /// Create an error value. Prefer using the 'make_error' function, but
197 /// this constructor can be useful when "re-throwing" errors from handlers.
198 Error(std::unique_ptr<ErrorInfoBase> Payload) {
199 setPtr(Payload.release());
200 setChecked(false);
201 }
202
203 // Errors are not copy-assignable.
204 Error &operator=(const Error &Other) = delete;
205
206 /// Move-assign an error value. The current error must represent success, you
207 /// you cannot overwrite an unhandled error. The current error is then
208 /// considered unchecked. The source error becomes a checked success value,
209 /// regardless of its original state.
210 Error &operator=(Error &&Other) {
211 // Don't allow overwriting of unchecked values.
212 assertIsChecked();
213 setPtr(Other.getPtr());
214
215 // This Error is unchecked, even if the source error was checked.
216 setChecked(false);
217
218 // Null out Other's payload and set its checked bit.
219 Other.setPtr(nullptr);
220 Other.setChecked(true);
221
222 return *this;
223 }
224
225 /// Destroy a Error. Fails with a call to abort() if the error is
226 /// unchecked.
227 ~Error() {
228 assertIsChecked();
229 delete getPtr();
230 }
231
232 /// Bool conversion. Returns true if this Error is in a failure state,
233 /// and false if it is in an accept state. If the error is in a Success state
234 /// it will be considered checked.
235 explicit operator bool() {
236 setChecked(getPtr() == nullptr);
237 return getPtr() != nullptr;
238 }
239
240 /// Check whether one error is a subclass of another.
241 template <typename ErrT> bool isA() const {
242 return getPtr() && getPtr()->isA(ErrT::classID());
243 }
244
245 /// Returns the dynamic class id of this error, or null if this is a success
246 /// value.
247 const void* dynamicClassID() const {
248 if (!getPtr())
249 return nullptr;
250 return getPtr()->dynamicClassID();
251 }
252
253private:
254#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
255 // assertIsChecked() happens very frequently, but under normal circumstances
256 // is supposed to be a no-op. So we want it to be inlined, but having a bunch
257 // of debug prints can cause the function to be too large for inlining. So
258 // it's important that we define this function out of line so that it can't be
259 // inlined.
260 [[noreturn]] void fatalUncheckedError() const;
261#endif
262
263 void assertIsChecked() {
264#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
265 if (LLVM_UNLIKELY(!getChecked() || getPtr())__builtin_expect((bool)(!getChecked() || getPtr()), false))
266 fatalUncheckedError();
267#endif
268 }
269
270 ErrorInfoBase *getPtr() const {
271#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
272 return reinterpret_cast<ErrorInfoBase*>(
273 reinterpret_cast<uintptr_t>(Payload) &
274 ~static_cast<uintptr_t>(0x1));
275#else
276 return Payload;
277#endif
278 }
279
280 void setPtr(ErrorInfoBase *EI) {
281#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
282 Payload = reinterpret_cast<ErrorInfoBase*>(
283 (reinterpret_cast<uintptr_t>(EI) &
284 ~static_cast<uintptr_t>(0x1)) |
285 (reinterpret_cast<uintptr_t>(Payload) & 0x1));
286#else
287 Payload = EI;
288#endif
289 }
290
291 bool getChecked() const {
292#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
293 return (reinterpret_cast<uintptr_t>(Payload) & 0x1) == 0;
294#else
295 return true;
296#endif
297 }
298
299 void setChecked(bool V) {
300#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
301 Payload = reinterpret_cast<ErrorInfoBase*>(
302 (reinterpret_cast<uintptr_t>(Payload) &
303 ~static_cast<uintptr_t>(0x1)) |
304 (V ? 0 : 1));
305#endif
306 }
307
308 std::unique_ptr<ErrorInfoBase> takePayload() {
309 std::unique_ptr<ErrorInfoBase> Tmp(getPtr());
310 setPtr(nullptr);
311 setChecked(true);
312 return Tmp;
313 }
314
315 friend raw_ostream &operator<<(raw_ostream &OS, const Error &E) {
316 if (auto *P = E.getPtr())
317 P->log(OS);
318 else
319 OS << "success";
320 return OS;
321 }
322
323 ErrorInfoBase *Payload = nullptr;
324};
325
326/// Subclass of Error for the sole purpose of identifying the success path in
327/// the type system. This allows to catch invalid conversion to Expected<T> at
328/// compile time.
329class ErrorSuccess final : public Error {};
330
331inline ErrorSuccess Error::success() { return ErrorSuccess(); }
332
333/// Make a Error instance representing failure using the given error info
334/// type.
335template <typename ErrT, typename... ArgTs> Error make_error(ArgTs &&... Args) {
336 return Error(std::make_unique<ErrT>(std::forward<ArgTs>(Args)...));
337}
338
339/// Base class for user error types. Users should declare their error types
340/// like:
341///
342/// class MyError : public ErrorInfo<MyError> {
343/// ....
344/// };
345///
346/// This class provides an implementation of the ErrorInfoBase::kind
347/// method, which is used by the Error RTTI system.
348template <typename ThisErrT, typename ParentErrT = ErrorInfoBase>
349class ErrorInfo : public ParentErrT {
350public:
351 using ParentErrT::ParentErrT; // inherit constructors
352
353 static const void *classID() { return &ThisErrT::ID; }
354
355 const void *dynamicClassID() const override { return &ThisErrT::ID; }
356
357 bool isA(const void *const ClassID) const override {
358 return ClassID == classID() || ParentErrT::isA(ClassID);
359 }
360};
361
362/// Special ErrorInfo subclass representing a list of ErrorInfos.
363/// Instances of this class are constructed by joinError.
364class ErrorList final : public ErrorInfo<ErrorList> {
365 // handleErrors needs to be able to iterate the payload list of an
366 // ErrorList.
367 template <typename... HandlerTs>
368 friend Error handleErrors(Error E, HandlerTs &&... Handlers);
369
370 // joinErrors is implemented in terms of join.
371 friend Error joinErrors(Error, Error);
372
373public:
374 void log(raw_ostream &OS) const override {
375 OS << "Multiple errors:\n";
376 for (const auto &ErrPayload : Payloads) {
377 ErrPayload->log(OS);
378 OS << "\n";
379 }
380 }
381
382 std::error_code convertToErrorCode() const override;
383
384 // Used by ErrorInfo::classID.
385 static char ID;
386
387private:
388 ErrorList(std::unique_ptr<ErrorInfoBase> Payload1,
389 std::unique_ptr<ErrorInfoBase> Payload2) {
390 assert(!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() &&(static_cast <bool> (!Payload1->isA<ErrorList>
() && !Payload2->isA<ErrorList>() &&
"ErrorList constructor payloads should be singleton errors")
? void (0) : __assert_fail ("!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() && \"ErrorList constructor payloads should be singleton errors\""
, "llvm/include/llvm/Support/Error.h", 391, __extension__ __PRETTY_FUNCTION__
))
391 "ErrorList constructor payloads should be singleton errors")(static_cast <bool> (!Payload1->isA<ErrorList>
() && !Payload2->isA<ErrorList>() &&
"ErrorList constructor payloads should be singleton errors")
? void (0) : __assert_fail ("!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() && \"ErrorList constructor payloads should be singleton errors\""
, "llvm/include/llvm/Support/Error.h", 391, __extension__ __PRETTY_FUNCTION__
))
;
392 Payloads.push_back(std::move(Payload1));
393 Payloads.push_back(std::move(Payload2));
394 }
395
396 static Error join(Error E1, Error E2) {
397 if (!E1)
398 return E2;
399 if (!E2)
400 return E1;
401 if (E1.isA<ErrorList>()) {
402 auto &E1List = static_cast<ErrorList &>(*E1.getPtr());
403 if (E2.isA<ErrorList>()) {
404 auto E2Payload = E2.takePayload();
405 auto &E2List = static_cast<ErrorList &>(*E2Payload);
406 for (auto &Payload : E2List.Payloads)
407 E1List.Payloads.push_back(std::move(Payload));
408 } else
409 E1List.Payloads.push_back(E2.takePayload());
410
411 return E1;
412 }
413 if (E2.isA<ErrorList>()) {
414 auto &E2List = static_cast<ErrorList &>(*E2.getPtr());
415 E2List.Payloads.insert(E2List.Payloads.begin(), E1.takePayload());
416 return E2;
417 }
418 return Error(std::unique_ptr<ErrorList>(
419 new ErrorList(E1.takePayload(), E2.takePayload())));
420 }
421
422 std::vector<std::unique_ptr<ErrorInfoBase>> Payloads;
423};
424
425/// Concatenate errors. The resulting Error is unchecked, and contains the
426/// ErrorInfo(s), if any, contained in E1, followed by the
427/// ErrorInfo(s), if any, contained in E2.
428inline Error joinErrors(Error E1, Error E2) {
429 return ErrorList::join(std::move(E1), std::move(E2));
430}
431
432/// Tagged union holding either a T or a Error.
433///
434/// This class parallels ErrorOr, but replaces error_code with Error. Since
435/// Error cannot be copied, this class replaces getError() with
436/// takeError(). It also adds an bool errorIsA<ErrT>() method for testing the
437/// error class type.
438///
439/// Example usage of 'Expected<T>' as a function return type:
440///
441/// @code{.cpp}
442/// Expected<int> myDivide(int A, int B) {
443/// if (B == 0) {
444/// // return an Error
445/// return createStringError(inconvertibleErrorCode(),
446/// "B must not be zero!");
447/// }
448/// // return an integer
449/// return A / B;
450/// }
451/// @endcode
452///
453/// Checking the results of to a function returning 'Expected<T>':
454/// @code{.cpp}
455/// if (auto E = Result.takeError()) {
456/// // We must consume the error. Typically one of:
457/// // - return the error to our caller
458/// // - toString(), when logging
459/// // - consumeError(), to silently swallow the error
460/// // - handleErrors(), to distinguish error types
461/// errs() << "Problem with division " << toString(std::move(E)) << "\n";
462/// return;
463/// }
464/// // use the result
465/// outs() << "The answer is " << *Result << "\n";
466/// @endcode
467///
468/// For unit-testing a function returning an 'Expceted<T>', see the
469/// 'EXPECT_THAT_EXPECTED' macros in llvm/Testing/Support/Error.h
470
471template <class T> class LLVM_NODISCARD[[clang::warn_unused_result]] Expected {
472 template <class T1> friend class ExpectedAsOutParameter;
473 template <class OtherT> friend class Expected;
474
475 static constexpr bool isRef = std::is_reference<T>::value;
476
477 using wrap = std::reference_wrapper<std::remove_reference_t<T>>;
478
479 using error_type = std::unique_ptr<ErrorInfoBase>;
480
481public:
482 using storage_type = std::conditional_t<isRef, wrap, T>;
483 using value_type = T;
484
485private:
486 using reference = std::remove_reference_t<T> &;
487 using const_reference = const std::remove_reference_t<T> &;
488 using pointer = std::remove_reference_t<T> *;
489 using const_pointer = const std::remove_reference_t<T> *;
490
491public:
492 /// Create an Expected<T> error value from the given Error.
493 Expected(Error Err)
494 : HasError(true)
495#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
496 // Expected is unchecked upon construction in Debug builds.
497 , Unchecked(true)
498#endif
499 {
500 assert(Err && "Cannot create Expected<T> from Error success value.")(static_cast <bool> (Err && "Cannot create Expected<T> from Error success value."
) ? void (0) : __assert_fail ("Err && \"Cannot create Expected<T> from Error success value.\""
, "llvm/include/llvm/Support/Error.h", 500, __extension__ __PRETTY_FUNCTION__
))
;
501 new (getErrorStorage()) error_type(Err.takePayload());
502 }
503
504 /// Forbid to convert from Error::success() implicitly, this avoids having
505 /// Expected<T> foo() { return Error::success(); } which compiles otherwise
506 /// but triggers the assertion above.
507 Expected(ErrorSuccess) = delete;
508
509 /// Create an Expected<T> success value from the given OtherT value, which
510 /// must be convertible to T.
511 template <typename OtherT>
512 Expected(OtherT &&Val,
513 std::enable_if_t<std::is_convertible<OtherT, T>::value> * = nullptr)
514 : HasError(false)
515#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
516 // Expected is unchecked upon construction in Debug builds.
517 ,
518 Unchecked(true)
519#endif
520 {
521 new (getStorage()) storage_type(std::forward<OtherT>(Val));
522 }
523
524 /// Move construct an Expected<T> value.
525 Expected(Expected &&Other) { moveConstruct(std::move(Other)); }
526
527 /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
528 /// must be convertible to T.
529 template <class OtherT>
530 Expected(
531 Expected<OtherT> &&Other,
532 std::enable_if_t<std::is_convertible<OtherT, T>::value> * = nullptr) {
533 moveConstruct(std::move(Other));
534 }
535
536 /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
537 /// isn't convertible to T.
538 template <class OtherT>
539 explicit Expected(
540 Expected<OtherT> &&Other,
541 std::enable_if_t<!std::is_convertible<OtherT, T>::value> * = nullptr) {
542 moveConstruct(std::move(Other));
543 }
544
545 /// Move-assign from another Expected<T>.
546 Expected &operator=(Expected &&Other) {
547 moveAssign(std::move(Other));
548 return *this;
549 }
550
551 /// Destroy an Expected<T>.
552 ~Expected() {
553 assertIsChecked();
554 if (!HasError)
555 getStorage()->~storage_type();
556 else
557 getErrorStorage()->~error_type();
558 }
559
560 /// Return false if there is an error.
561 explicit operator bool() {
562#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
563 Unchecked = HasError;
564#endif
565 return !HasError;
566 }
567
568 /// Returns a reference to the stored T value.
569 reference get() {
570 assertIsChecked();
571 return *getStorage();
572 }
573
574 /// Returns a const reference to the stored T value.
575 const_reference get() const {
576 assertIsChecked();
577 return const_cast<Expected<T> *>(this)->get();
578 }
579
580 /// Returns \a takeError() after moving the held T (if any) into \p V.
581 template <class OtherT>
582 Error moveInto(OtherT &Value,
583 std::enable_if_t<std::is_assignable<OtherT &, T &&>::value> * =
584 nullptr) && {
585 if (*this)
38
Taking false branch
586 Value = std::move(get());
587 return takeError();
39
Returning without writing to 'Value.ID'
588 }
589
590 /// Check that this Expected<T> is an error of type ErrT.
591 template <typename ErrT> bool errorIsA() const {
592 return HasError && (*getErrorStorage())->template isA<ErrT>();
593 }
594
595 /// Take ownership of the stored error.
596 /// After calling this the Expected<T> is in an indeterminate state that can
597 /// only be safely destructed. No further calls (beside the destructor) should
598 /// be made on the Expected<T> value.
599 Error takeError() {
600#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
601 Unchecked = false;
602#endif
603 return HasError ? Error(std::move(*getErrorStorage())) : Error::success();
604 }
605
606 /// Returns a pointer to the stored T value.
607 pointer operator->() {
608 assertIsChecked();
609 return toPointer(getStorage());
610 }
611
612 /// Returns a const pointer to the stored T value.
613 const_pointer operator->() const {
614 assertIsChecked();
615 return toPointer(getStorage());
616 }
617
618 /// Returns a reference to the stored T value.
619 reference operator*() {
620 assertIsChecked();
621 return *getStorage();
622 }
623
624 /// Returns a const reference to the stored T value.
625 const_reference operator*() const {
626 assertIsChecked();
627 return *getStorage();
628 }
629
630private:
631 template <class T1>
632 static bool compareThisIfSameType(const T1 &a, const T1 &b) {
633 return &a == &b;
634 }
635
636 template <class T1, class T2>
637 static bool compareThisIfSameType(const T1 &, const T2 &) {
638 return false;
639 }
640
641 template <class OtherT> void moveConstruct(Expected<OtherT> &&Other) {
642 HasError = Other.HasError;
643#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
644 Unchecked = true;
645 Other.Unchecked = false;
646#endif
647
648 if (!HasError)
649 new (getStorage()) storage_type(std::move(*Other.getStorage()));
650 else
651 new (getErrorStorage()) error_type(std::move(*Other.getErrorStorage()));
652 }
653
654 template <class OtherT> void moveAssign(Expected<OtherT> &&Other) {
655 assertIsChecked();
656
657 if (compareThisIfSameType(*this, Other))
658 return;
659
660 this->~Expected();
661 new (this) Expected(std::move(Other));
662 }
663
664 pointer toPointer(pointer Val) { return Val; }
665
666 const_pointer toPointer(const_pointer Val) const { return Val; }
667
668 pointer toPointer(wrap *Val) { return &Val->get(); }
669
670 const_pointer toPointer(const wrap *Val) const { return &Val->get(); }
671
672 storage_type *getStorage() {
673 assert(!HasError && "Cannot get value when an error exists!")(static_cast <bool> (!HasError && "Cannot get value when an error exists!"
) ? void (0) : __assert_fail ("!HasError && \"Cannot get value when an error exists!\""
, "llvm/include/llvm/Support/Error.h", 673, __extension__ __PRETTY_FUNCTION__
))
;
674 return reinterpret_cast<storage_type *>(&TStorage);
675 }
676
677 const storage_type *getStorage() const {
678 assert(!HasError && "Cannot get value when an error exists!")(static_cast <bool> (!HasError && "Cannot get value when an error exists!"
) ? void (0) : __assert_fail ("!HasError && \"Cannot get value when an error exists!\""
, "llvm/include/llvm/Support/Error.h", 678, __extension__ __PRETTY_FUNCTION__
))
;
679 return reinterpret_cast<const storage_type *>(&TStorage);
680 }
681
682 error_type *getErrorStorage() {
683 assert(HasError && "Cannot get error when a value exists!")(static_cast <bool> (HasError && "Cannot get error when a value exists!"
) ? void (0) : __assert_fail ("HasError && \"Cannot get error when a value exists!\""
, "llvm/include/llvm/Support/Error.h", 683, __extension__ __PRETTY_FUNCTION__
))
;
684 return reinterpret_cast<error_type *>(&ErrorStorage);
685 }
686
687 const error_type *getErrorStorage() const {
688 assert(HasError && "Cannot get error when a value exists!")(static_cast <bool> (HasError && "Cannot get error when a value exists!"
) ? void (0) : __assert_fail ("HasError && \"Cannot get error when a value exists!\""
, "llvm/include/llvm/Support/Error.h", 688, __extension__ __PRETTY_FUNCTION__
))
;
689 return reinterpret_cast<const error_type *>(&ErrorStorage);
690 }
691
692 // Used by ExpectedAsOutParameter to reset the checked flag.
693 void setUnchecked() {
694#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
695 Unchecked = true;
696#endif
697 }
698
699#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
700 [[noreturn]] LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) void fatalUncheckedExpected() const {
701 dbgs() << "Expected<T> must be checked before access or destruction.\n";
702 if (HasError) {
703 dbgs() << "Unchecked Expected<T> contained error:\n";
704 (*getErrorStorage())->log(dbgs());
705 } else
706 dbgs() << "Expected<T> value was in success state. (Note: Expected<T> "
707 "values in success mode must still be checked prior to being "
708 "destroyed).\n";
709 abort();
710 }
711#endif
712
713 void assertIsChecked() const {
714#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
715 if (LLVM_UNLIKELY(Unchecked)__builtin_expect((bool)(Unchecked), false))
716 fatalUncheckedExpected();
717#endif
718 }
719
720 union {
721 AlignedCharArrayUnion<storage_type> TStorage;
722 AlignedCharArrayUnion<error_type> ErrorStorage;
723 };
724 bool HasError : 1;
725#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
726 bool Unchecked : 1;
727#endif
728};
729
730/// Report a serious error, calling any installed error handler. See
731/// ErrorHandling.h.
732[[noreturn]] void report_fatal_error(Error Err, bool gen_crash_diag = true);
733
734/// Report a fatal error if Err is a failure value.
735///
736/// This function can be used to wrap calls to fallible functions ONLY when it
737/// is known that the Error will always be a success value. E.g.
738///
739/// @code{.cpp}
740/// // foo only attempts the fallible operation if DoFallibleOperation is
741/// // true. If DoFallibleOperation is false then foo always returns
742/// // Error::success().
743/// Error foo(bool DoFallibleOperation);
744///
745/// cantFail(foo(false));
746/// @endcode
747inline void cantFail(Error Err, const char *Msg = nullptr) {
748 if (Err) {
749 if (!Msg)
750 Msg = "Failure value returned from cantFail wrapped call";
751#ifndef NDEBUG
752 std::string Str;
753 raw_string_ostream OS(Str);
754 OS << Msg << "\n" << Err;
755 Msg = OS.str().c_str();
756#endif
757 llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "llvm/include/llvm/Support/Error.h"
, 757)
;
758 }
759}
760
761/// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
762/// returns the contained value.
763///
764/// This function can be used to wrap calls to fallible functions ONLY when it
765/// is known that the Error will always be a success value. E.g.
766///
767/// @code{.cpp}
768/// // foo only attempts the fallible operation if DoFallibleOperation is
769/// // true. If DoFallibleOperation is false then foo always returns an int.
770/// Expected<int> foo(bool DoFallibleOperation);
771///
772/// int X = cantFail(foo(false));
773/// @endcode
774template <typename T>
775T cantFail(Expected<T> ValOrErr, const char *Msg = nullptr) {
776 if (ValOrErr)
777 return std::move(*ValOrErr);
778 else {
779 if (!Msg)
780 Msg = "Failure value returned from cantFail wrapped call";
781#ifndef NDEBUG
782 std::string Str;
783 raw_string_ostream OS(Str);
784 auto E = ValOrErr.takeError();
785 OS << Msg << "\n" << E;
786 Msg = OS.str().c_str();
787#endif
788 llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "llvm/include/llvm/Support/Error.h"
, 788)
;
789 }
790}
791
792/// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
793/// returns the contained reference.
794///
795/// This function can be used to wrap calls to fallible functions ONLY when it
796/// is known that the Error will always be a success value. E.g.
797///
798/// @code{.cpp}
799/// // foo only attempts the fallible operation if DoFallibleOperation is
800/// // true. If DoFallibleOperation is false then foo always returns a Bar&.
801/// Expected<Bar&> foo(bool DoFallibleOperation);
802///
803/// Bar &X = cantFail(foo(false));
804/// @endcode
805template <typename T>
806T& cantFail(Expected<T&> ValOrErr, const char *Msg = nullptr) {
807 if (ValOrErr)
808 return *ValOrErr;
809 else {
810 if (!Msg)
811 Msg = "Failure value returned from cantFail wrapped call";
812#ifndef NDEBUG
813 std::string Str;
814 raw_string_ostream OS(Str);
815 auto E = ValOrErr.takeError();
816 OS << Msg << "\n" << E;
817 Msg = OS.str().c_str();
818#endif
819 llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "llvm/include/llvm/Support/Error.h"
, 819)
;
820 }
821}
822
823/// Helper for testing applicability of, and applying, handlers for
824/// ErrorInfo types.
825template <typename HandlerT>
826class ErrorHandlerTraits
827 : public ErrorHandlerTraits<decltype(
828 &std::remove_reference<HandlerT>::type::operator())> {};
829
830// Specialization functions of the form 'Error (const ErrT&)'.
831template <typename ErrT> class ErrorHandlerTraits<Error (&)(ErrT &)> {
832public:
833 static bool appliesTo(const ErrorInfoBase &E) {
834 return E.template isA<ErrT>();
835 }
836
837 template <typename HandlerT>
838 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
839 assert(appliesTo(*E) && "Applying incorrect handler")(static_cast <bool> (appliesTo(*E) && "Applying incorrect handler"
) ? void (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\""
, "llvm/include/llvm/Support/Error.h", 839, __extension__ __PRETTY_FUNCTION__
))
;
840 return H(static_cast<ErrT &>(*E));
841 }
842};
843
844// Specialization functions of the form 'void (const ErrT&)'.
845template <typename ErrT> class ErrorHandlerTraits<void (&)(ErrT &)> {
846public:
847 static bool appliesTo(const ErrorInfoBase &E) {
848 return E.template isA<ErrT>();
849 }
850
851 template <typename HandlerT>
852 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
853 assert(appliesTo(*E) && "Applying incorrect handler")(static_cast <bool> (appliesTo(*E) && "Applying incorrect handler"
) ? void (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\""
, "llvm/include/llvm/Support/Error.h", 853, __extension__ __PRETTY_FUNCTION__
))
;
854 H(static_cast<ErrT &>(*E));
855 return Error::success();
856 }
857};
858
859/// Specialization for functions of the form 'Error (std::unique_ptr<ErrT>)'.
860template <typename ErrT>
861class ErrorHandlerTraits<Error (&)(std::unique_ptr<ErrT>)> {
862public:
863 static bool appliesTo(const ErrorInfoBase &E) {
864 return E.template isA<ErrT>();
865 }
866
867 template <typename HandlerT>
868 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
869 assert(appliesTo(*E) && "Applying incorrect handler")(static_cast <bool> (appliesTo(*E) && "Applying incorrect handler"
) ? void (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\""
, "llvm/include/llvm/Support/Error.h", 869, __extension__ __PRETTY_FUNCTION__
))
;
870 std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
871 return H(std::move(SubE));
872 }
873};
874
875/// Specialization for functions of the form 'void (std::unique_ptr<ErrT>)'.
876template <typename ErrT>
877class ErrorHandlerTraits<void (&)(std::unique_ptr<ErrT>)> {
878public:
879 static bool appliesTo(const ErrorInfoBase &E) {
880 return E.template isA<ErrT>();
881 }
882
883 template <typename HandlerT>
884 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
885 assert(appliesTo(*E) && "Applying incorrect handler")(static_cast <bool> (appliesTo(*E) && "Applying incorrect handler"
) ? void (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\""
, "llvm/include/llvm/Support/Error.h", 885, __extension__ __PRETTY_FUNCTION__
))
;
886 std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
887 H(std::move(SubE));
888 return Error::success();
889 }
890};
891
892// Specialization for member functions of the form 'RetT (const ErrT&)'.
893template <typename C, typename RetT, typename ErrT>
894class ErrorHandlerTraits<RetT (C::*)(ErrT &)>
895 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
896
897// Specialization for member functions of the form 'RetT (const ErrT&) const'.
898template <typename C, typename RetT, typename ErrT>
899class ErrorHandlerTraits<RetT (C::*)(ErrT &) const>
900 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
901
902// Specialization for member functions of the form 'RetT (const ErrT&)'.
903template <typename C, typename RetT, typename ErrT>
904class ErrorHandlerTraits<RetT (C::*)(const ErrT &)>
905 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
906
907// Specialization for member functions of the form 'RetT (const ErrT&) const'.
908template <typename C, typename RetT, typename ErrT>
909class ErrorHandlerTraits<RetT (C::*)(const ErrT &) const>
910 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
911
912/// Specialization for member functions of the form
913/// 'RetT (std::unique_ptr<ErrT>)'.
914template <typename C, typename RetT, typename ErrT>
915class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>)>
916 : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
917
918/// Specialization for member functions of the form
919/// 'RetT (std::unique_ptr<ErrT>) const'.
920template <typename C, typename RetT, typename ErrT>
921class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>) const>
922 : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
923
924inline Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload) {
925 return Error(std::move(Payload));
926}
927
928template <typename HandlerT, typename... HandlerTs>
929Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload,
930 HandlerT &&Handler, HandlerTs &&... Handlers) {
931 if (ErrorHandlerTraits<HandlerT>::appliesTo(*Payload))
932 return ErrorHandlerTraits<HandlerT>::apply(std::forward<HandlerT>(Handler),
933 std::move(Payload));
934 return handleErrorImpl(std::move(Payload),
935 std::forward<HandlerTs>(Handlers)...);
936}
937
938/// Pass the ErrorInfo(s) contained in E to their respective handlers. Any
939/// unhandled errors (or Errors returned by handlers) are re-concatenated and
940/// returned.
941/// Because this function returns an error, its result must also be checked
942/// or returned. If you intend to handle all errors use handleAllErrors
943/// (which returns void, and will abort() on unhandled errors) instead.
944template <typename... HandlerTs>
945Error handleErrors(Error E, HandlerTs &&... Hs) {
946 if (!E)
947 return Error::success();
948
949 std::unique_ptr<ErrorInfoBase> Payload = E.takePayload();
950
951 if (Payload->isA<ErrorList>()) {
952 ErrorList &List = static_cast<ErrorList &>(*Payload);
953 Error R;
954 for (auto &P : List.Payloads)
955 R = ErrorList::join(
956 std::move(R),
957 handleErrorImpl(std::move(P), std::forward<HandlerTs>(Hs)...));
958 return R;
959 }
960
961 return handleErrorImpl(std::move(Payload), std::forward<HandlerTs>(Hs)...);
962}
963
964/// Behaves the same as handleErrors, except that by contract all errors
965/// *must* be handled by the given handlers (i.e. there must be no remaining
966/// errors after running the handlers, or llvm_unreachable is called).
967template <typename... HandlerTs>
968void handleAllErrors(Error E, HandlerTs &&... Handlers) {
969 cantFail(handleErrors(std::move(E), std::forward<HandlerTs>(Handlers)...));
970}
971
972/// Check that E is a non-error, then drop it.
973/// If E is an error, llvm_unreachable will be called.
974inline void handleAllErrors(Error E) {
975 cantFail(std::move(E));
976}
977
978/// Handle any errors (if present) in an Expected<T>, then try a recovery path.
979///
980/// If the incoming value is a success value it is returned unmodified. If it
981/// is a failure value then it the contained error is passed to handleErrors.
982/// If handleErrors is able to handle the error then the RecoveryPath functor
983/// is called to supply the final result. If handleErrors is not able to
984/// handle all errors then the unhandled errors are returned.
985///
986/// This utility enables the follow pattern:
987///
988/// @code{.cpp}
989/// enum FooStrategy { Aggressive, Conservative };
990/// Expected<Foo> foo(FooStrategy S);
991///
992/// auto ResultOrErr =
993/// handleExpected(
994/// foo(Aggressive),
995/// []() { return foo(Conservative); },
996/// [](AggressiveStrategyError&) {
997/// // Implicitly conusme this - we'll recover by using a conservative
998/// // strategy.
999/// });
1000///
1001/// @endcode
1002template <typename T, typename RecoveryFtor, typename... HandlerTs>
1003Expected<T> handleExpected(Expected<T> ValOrErr, RecoveryFtor &&RecoveryPath,
1004 HandlerTs &&... Handlers) {
1005 if (ValOrErr)
1006 return ValOrErr;
1007
1008 if (auto Err = handleErrors(ValOrErr.takeError(),
1009 std::forward<HandlerTs>(Handlers)...))
1010 return std::move(Err);
1011
1012 return RecoveryPath();
1013}
1014
1015/// Log all errors (if any) in E to OS. If there are any errors, ErrorBanner
1016/// will be printed before the first one is logged. A newline will be printed
1017/// after each error.
1018///
1019/// This function is compatible with the helpers from Support/WithColor.h. You
1020/// can pass any of them as the OS. Please consider using them instead of
1021/// including 'error: ' in the ErrorBanner.
1022///
1023/// This is useful in the base level of your program to allow clean termination
1024/// (allowing clean deallocation of resources, etc.), while reporting error
1025/// information to the user.
1026void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner = {});
1027
1028/// Write all error messages (if any) in E to a string. The newline character
1029/// is used to separate error messages.
1030inline std::string toString(Error E) {
1031 SmallVector<std::string, 2> Errors;
1032 handleAllErrors(std::move(E), [&Errors](const ErrorInfoBase &EI) {
1033 Errors.push_back(EI.message());
1034 });
1035 return join(Errors.begin(), Errors.end(), "\n");
1036}
1037
1038/// Consume a Error without doing anything. This method should be used
1039/// only where an error can be considered a reasonable and expected return
1040/// value.
1041///
1042/// Uses of this method are potentially indicative of design problems: If it's
1043/// legitimate to do nothing while processing an "error", the error-producer
1044/// might be more clearly refactored to return an Optional<T>.
1045inline void consumeError(Error Err) {
1046 handleAllErrors(std::move(Err), [](const ErrorInfoBase &) {});
1047}
1048
1049/// Convert an Expected to an Optional without doing anything. This method
1050/// should be used only where an error can be considered a reasonable and
1051/// expected return value.
1052///
1053/// Uses of this method are potentially indicative of problems: perhaps the
1054/// error should be propagated further, or the error-producer should just
1055/// return an Optional in the first place.
1056template <typename T> Optional<T> expectedToOptional(Expected<T> &&E) {
1057 if (E)
1058 return std::move(*E);
1059 consumeError(E.takeError());
1060 return None;
1061}
1062
1063/// Helper for converting an Error to a bool.
1064///
1065/// This method returns true if Err is in an error state, or false if it is
1066/// in a success state. Puts Err in a checked state in both cases (unlike
1067/// Error::operator bool(), which only does this for success states).
1068inline bool errorToBool(Error Err) {
1069 bool IsError = static_cast<bool>(Err);
1070 if (IsError)
1071 consumeError(std::move(Err));
1072 return IsError;
1073}
1074
1075/// Helper for Errors used as out-parameters.
1076///
1077/// This helper is for use with the Error-as-out-parameter idiom, where an error
1078/// is passed to a function or method by reference, rather than being returned.
1079/// In such cases it is helpful to set the checked bit on entry to the function
1080/// so that the error can be written to (unchecked Errors abort on assignment)
1081/// and clear the checked bit on exit so that clients cannot accidentally forget
1082/// to check the result. This helper performs these actions automatically using
1083/// RAII:
1084///
1085/// @code{.cpp}
1086/// Result foo(Error &Err) {
1087/// ErrorAsOutParameter ErrAsOutParam(&Err); // 'Checked' flag set
1088/// // <body of foo>
1089/// // <- 'Checked' flag auto-cleared when ErrAsOutParam is destructed.
1090/// }
1091/// @endcode
1092///
1093/// ErrorAsOutParameter takes an Error* rather than Error& so that it can be
1094/// used with optional Errors (Error pointers that are allowed to be null). If
1095/// ErrorAsOutParameter took an Error reference, an instance would have to be
1096/// created inside every condition that verified that Error was non-null. By
1097/// taking an Error pointer we can just create one instance at the top of the
1098/// function.
1099class ErrorAsOutParameter {
1100public:
1101 ErrorAsOutParameter(Error *Err) : Err(Err) {
1102 // Raise the checked bit if Err is success.
1103 if (Err)
1104 (void)!!*Err;
1105 }
1106
1107 ~ErrorAsOutParameter() {
1108 // Clear the checked bit.
1109 if (Err && !*Err)
1110 *Err = Error::success();
1111 }
1112
1113private:
1114 Error *Err;
1115};
1116
1117/// Helper for Expected<T>s used as out-parameters.
1118///
1119/// See ErrorAsOutParameter.
1120template <typename T>
1121class ExpectedAsOutParameter {
1122public:
1123 ExpectedAsOutParameter(Expected<T> *ValOrErr)
1124 : ValOrErr(ValOrErr) {
1125 if (ValOrErr)
1126 (void)!!*ValOrErr;
1127 }
1128
1129 ~ExpectedAsOutParameter() {
1130 if (ValOrErr)
1131 ValOrErr->setUnchecked();
1132 }
1133
1134private:
1135 Expected<T> *ValOrErr;
1136};
1137
1138/// This class wraps a std::error_code in a Error.
1139///
1140/// This is useful if you're writing an interface that returns a Error
1141/// (or Expected) and you want to call code that still returns
1142/// std::error_codes.
1143class ECError : public ErrorInfo<ECError> {
1144 friend Error errorCodeToError(std::error_code);
1145
1146 virtual void anchor() override;
1147
1148public:
1149 void setErrorCode(std::error_code EC) { this->EC = EC; }
1150 std::error_code convertToErrorCode() const override { return EC; }
1151 void log(raw_ostream &OS) const override { OS << EC.message(); }
1152
1153 // Used by ErrorInfo::classID.
1154 static char ID;
1155
1156protected:
1157 ECError() = default;
1158 ECError(std::error_code EC) : EC(EC) {}
1159
1160 std::error_code EC;
1161};
1162
1163/// The value returned by this function can be returned from convertToErrorCode
1164/// for Error values where no sensible translation to std::error_code exists.
1165/// It should only be used in this situation, and should never be used where a
1166/// sensible conversion to std::error_code is available, as attempts to convert
1167/// to/from this error will result in a fatal error. (i.e. it is a programmatic
1168/// error to try to convert such a value).
1169std::error_code inconvertibleErrorCode();
1170
1171/// Helper for converting an std::error_code to a Error.
1172Error errorCodeToError(std::error_code EC);
1173
1174/// Helper for converting an ECError to a std::error_code.
1175///
1176/// This method requires that Err be Error() or an ECError, otherwise it
1177/// will trigger a call to abort().
1178std::error_code errorToErrorCode(Error Err);
1179
1180/// Convert an ErrorOr<T> to an Expected<T>.
1181template <typename T> Expected<T> errorOrToExpected(ErrorOr<T> &&EO) {
1182 if (auto EC = EO.getError())
1183 return errorCodeToError(EC);
1184 return std::move(*EO);
1185}
1186
1187/// Convert an Expected<T> to an ErrorOr<T>.
1188template <typename T> ErrorOr<T> expectedToErrorOr(Expected<T> &&E) {
1189 if (auto Err = E.takeError())
1190 return errorToErrorCode(std::move(Err));
1191 return std::move(*E);
1192}
1193
1194/// This class wraps a string in an Error.
1195///
1196/// StringError is useful in cases where the client is not expected to be able
1197/// to consume the specific error message programmatically (for example, if the
1198/// error message is to be presented to the user).
1199///
1200/// StringError can also be used when additional information is to be printed
1201/// along with a error_code message. Depending on the constructor called, this
1202/// class can either display:
1203/// 1. the error_code message (ECError behavior)
1204/// 2. a string
1205/// 3. the error_code message and a string
1206///
1207/// These behaviors are useful when subtyping is required; for example, when a
1208/// specific library needs an explicit error type. In the example below,
1209/// PDBError is derived from StringError:
1210///
1211/// @code{.cpp}
1212/// Expected<int> foo() {
1213/// return llvm::make_error<PDBError>(pdb_error_code::dia_failed_loading,
1214/// "Additional information");
1215/// }
1216/// @endcode
1217///
1218class StringError : public ErrorInfo<StringError> {
1219public:
1220 static char ID;
1221
1222 // Prints EC + S and converts to EC
1223 StringError(std::error_code EC, const Twine &S = Twine());
1224
1225 // Prints S and converts to EC
1226 StringError(const Twine &S, std::error_code EC);
1227
1228 void log(raw_ostream &OS) const override;
1229 std::error_code convertToErrorCode() const override;
1230
1231 const std::string &getMessage() const { return Msg; }
1232
1233private:
1234 std::string Msg;
1235 std::error_code EC;
1236 const bool PrintMsgOnly = false;
1237};
1238
1239/// Create formatted StringError object.
1240template <typename... Ts>
1241inline Error createStringError(std::error_code EC, char const *Fmt,
1242 const Ts &... Vals) {
1243 std::string Buffer;
1244 raw_string_ostream Stream(Buffer);
1245 Stream << format(Fmt, Vals...);
1246 return make_error<StringError>(Stream.str(), EC);
1247}
1248
1249Error createStringError(std::error_code EC, char const *Msg);
1250
1251inline Error createStringError(std::error_code EC, const Twine &S) {
1252 return createStringError(EC, S.str().c_str());
1253}
1254
1255template <typename... Ts>
1256inline Error createStringError(std::errc EC, char const *Fmt,
1257 const Ts &... Vals) {
1258 return createStringError(std::make_error_code(EC), Fmt, Vals...);
1259}
1260
1261/// This class wraps a filename and another Error.
1262///
1263/// In some cases, an error needs to live along a 'source' name, in order to
1264/// show more detailed information to the user.
1265class FileError final : public ErrorInfo<FileError> {
1266
1267 friend Error createFileError(const Twine &, Error);
1268 friend Error createFileError(const Twine &, size_t, Error);
1269
1270public:
1271 void log(raw_ostream &OS) const override {
1272 assert(Err && "Trying to log after takeError().")(static_cast <bool> (Err && "Trying to log after takeError()."
) ? void (0) : __assert_fail ("Err && \"Trying to log after takeError().\""
, "llvm/include/llvm/Support/Error.h", 1272, __extension__ __PRETTY_FUNCTION__
))
;
1273 OS << "'" << FileName << "': ";
1274 if (Line.hasValue())
1275 OS << "line " << Line.getValue() << ": ";
1276 Err->log(OS);
1277 }
1278
1279 std::string messageWithoutFileInfo() const {
1280 std::string Msg;
1281 raw_string_ostream OS(Msg);
1282 Err->log(OS);
1283 return OS.str();
1284 }
1285
1286 StringRef getFileName() { return FileName; }
1287
1288 Error takeError() { return Error(std::move(Err)); }
1289
1290 std::error_code convertToErrorCode() const override;
1291
1292 // Used by ErrorInfo::classID.
1293 static char ID;
1294
1295private:
1296 FileError(const Twine &F, Optional<size_t> LineNum,
1297 std::unique_ptr<ErrorInfoBase> E) {
1298 assert(E && "Cannot create FileError from Error success value.")(static_cast <bool> (E && "Cannot create FileError from Error success value."
) ? void (0) : __assert_fail ("E && \"Cannot create FileError from Error success value.\""
, "llvm/include/llvm/Support/Error.h", 1298, __extension__ __PRETTY_FUNCTION__
))
;
1299 FileName = F.str();
1300 Err = std::move(E);
1301 Line = std::move(LineNum);
1302 }
1303
1304 static Error build(const Twine &F, Optional<size_t> Line, Error E) {
1305 std::unique_ptr<ErrorInfoBase> Payload;
1306 handleAllErrors(std::move(E),
1307 [&](std::unique_ptr<ErrorInfoBase> EIB) -> Error {
1308 Payload = std::move(EIB);
1309 return Error::success();
1310 });
1311 return Error(
1312 std::unique_ptr<FileError>(new FileError(F, Line, std::move(Payload))));
1313 }
1314
1315 std::string FileName;
1316 Optional<size_t> Line;
1317 std::unique_ptr<ErrorInfoBase> Err;
1318};
1319
1320/// Concatenate a source file path and/or name with an Error. The resulting
1321/// Error is unchecked.
1322inline Error createFileError(const Twine &F, Error E) {
1323 return FileError::build(F, Optional<size_t>(), std::move(E));
1324}
1325
1326/// Concatenate a source file path and/or name with line number and an Error.
1327/// The resulting Error is unchecked.
1328inline Error createFileError(const Twine &F, size_t Line, Error E) {
1329 return FileError::build(F, Optional<size_t>(Line), std::move(E));
1330}
1331
1332/// Concatenate a source file path and/or name with a std::error_code
1333/// to form an Error object.
1334inline Error createFileError(const Twine &F, std::error_code EC) {
1335 return createFileError(F, errorCodeToError(EC));
1336}
1337
1338/// Concatenate a source file path and/or name with line number and
1339/// std::error_code to form an Error object.
1340inline Error createFileError(const Twine &F, size_t Line, std::error_code EC) {
1341 return createFileError(F, Line, errorCodeToError(EC));
1342}
1343
1344Error createFileError(const Twine &F, ErrorSuccess) = delete;
1345
1346/// Helper for check-and-exit error handling.
1347///
1348/// For tool use only. NOT FOR USE IN LIBRARY CODE.
1349///
1350class ExitOnError {
1351public:
1352 /// Create an error on exit helper.
1353 ExitOnError(std::string Banner = "", int DefaultErrorExitCode = 1)
1354 : Banner(std::move(Banner)),
1355 GetExitCode([=](const Error &) { return DefaultErrorExitCode; }) {}
1356
1357 /// Set the banner string for any errors caught by operator().
1358 void setBanner(std::string Banner) { this->Banner = std::move(Banner); }
1359
1360 /// Set the exit-code mapper function.
1361 void setExitCodeMapper(std::function<int(const Error &)> GetExitCode) {
1362 this->GetExitCode = std::move(GetExitCode);
1363 }
1364
1365 /// Check Err. If it's in a failure state log the error(s) and exit.
1366 void operator()(Error Err) const { checkError(std::move(Err)); }
1367
1368 /// Check E. If it's in a success state then return the contained value. If
1369 /// it's in a failure state log the error(s) and exit.
1370 template <typename T> T operator()(Expected<T> &&E) const {
1371 checkError(E.takeError());
1372 return std::move(*E);
1373 }
1374
1375 /// Check E. If it's in a success state then return the contained reference. If
1376 /// it's in a failure state log the error(s) and exit.
1377 template <typename T> T& operator()(Expected<T&> &&E) const {
1378 checkError(E.takeError());
1379 return *E;
1380 }
1381
1382private:
1383 void checkError(Error Err) const {
1384 if (Err) {
1385 int ExitCode = GetExitCode(Err);
1386 logAllUnhandledErrors(std::move(Err), errs(), Banner);
1387 exit(ExitCode);
1388 }
1389 }
1390
1391 std::string Banner;
1392 std::function<int(const Error &)> GetExitCode;
1393};
1394
1395/// Conversion from Error to LLVMErrorRef for C error bindings.
1396inline LLVMErrorRef wrap(Error Err) {
1397 return reinterpret_cast<LLVMErrorRef>(Err.takePayload().release());
1398}
1399
1400/// Conversion from LLVMErrorRef to Error for C error bindings.
1401inline Error unwrap(LLVMErrorRef ErrRef) {
1402 return Error(std::unique_ptr<ErrorInfoBase>(
1403 reinterpret_cast<ErrorInfoBase *>(ErrRef)));
1404}
1405
1406} // end namespace llvm
1407
1408#endif // LLVM_SUPPORT_ERROR_H