DebugInfoMetadata.cpp revision 360784
1//===- DebugInfoMetadata.cpp - Implement debug info metadata --------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the debug info Metadata classes.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/IR/DebugInfoMetadata.h"
14#include "LLVMContextImpl.h"
15#include "MetadataImpl.h"
16#include "llvm/ADT/SmallSet.h"
17#include "llvm/ADT/StringSwitch.h"
18#include "llvm/IR/DIBuilder.h"
19#include "llvm/IR/Function.h"
20#include "llvm/IR/Instructions.h"
21
22#include <numeric>
23
24using namespace llvm;
25
26const DIExpression::FragmentInfo DebugVariable::DefaultFragment = {
27    std::numeric_limits<uint64_t>::max(), std::numeric_limits<uint64_t>::min()};
28
29DILocation::DILocation(LLVMContext &C, StorageType Storage, unsigned Line,
30                       unsigned Column, ArrayRef<Metadata *> MDs,
31                       bool ImplicitCode)
32    : MDNode(C, DILocationKind, Storage, MDs) {
33  assert((MDs.size() == 1 || MDs.size() == 2) &&
34         "Expected a scope and optional inlined-at");
35
36  // Set line and column.
37  assert(Column < (1u << 16) && "Expected 16-bit column");
38
39  SubclassData32 = Line;
40  SubclassData16 = Column;
41
42  setImplicitCode(ImplicitCode);
43}
44
45static void adjustColumn(unsigned &Column) {
46  // Set to unknown on overflow.  We only have 16 bits to play with here.
47  if (Column >= (1u << 16))
48    Column = 0;
49}
50
51DILocation *DILocation::getImpl(LLVMContext &Context, unsigned Line,
52                                unsigned Column, Metadata *Scope,
53                                Metadata *InlinedAt, bool ImplicitCode,
54                                StorageType Storage, bool ShouldCreate) {
55  // Fixup column.
56  adjustColumn(Column);
57
58  if (Storage == Uniqued) {
59    if (auto *N = getUniqued(Context.pImpl->DILocations,
60                             DILocationInfo::KeyTy(Line, Column, Scope,
61                                                   InlinedAt, ImplicitCode)))
62      return N;
63    if (!ShouldCreate)
64      return nullptr;
65  } else {
66    assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
67  }
68
69  SmallVector<Metadata *, 2> Ops;
70  Ops.push_back(Scope);
71  if (InlinedAt)
72    Ops.push_back(InlinedAt);
73  return storeImpl(new (Ops.size()) DILocation(Context, Storage, Line, Column,
74                                               Ops, ImplicitCode),
75                   Storage, Context.pImpl->DILocations);
76}
77
78const DILocation *DILocation::getMergedLocation(const DILocation *LocA,
79                                                const DILocation *LocB) {
80  if (!LocA || !LocB)
81    return nullptr;
82
83  if (LocA == LocB)
84    return LocA;
85
86  SmallPtrSet<DILocation *, 5> InlinedLocationsA;
87  for (DILocation *L = LocA->getInlinedAt(); L; L = L->getInlinedAt())
88    InlinedLocationsA.insert(L);
89  SmallSet<std::pair<DIScope *, DILocation *>, 5> Locations;
90  DIScope *S = LocA->getScope();
91  DILocation *L = LocA->getInlinedAt();
92  while (S) {
93    Locations.insert(std::make_pair(S, L));
94    S = S->getScope();
95    if (!S && L) {
96      S = L->getScope();
97      L = L->getInlinedAt();
98    }
99  }
100  const DILocation *Result = LocB;
101  S = LocB->getScope();
102  L = LocB->getInlinedAt();
103  while (S) {
104    if (Locations.count(std::make_pair(S, L)))
105      break;
106    S = S->getScope();
107    if (!S && L) {
108      S = L->getScope();
109      L = L->getInlinedAt();
110    }
111  }
112
113  // If the two locations are irreconsilable, just pick one. This is misleading,
114  // but on the other hand, it's a "line 0" location.
115  if (!S || !isa<DILocalScope>(S))
116    S = LocA->getScope();
117  return DILocation::get(Result->getContext(), 0, 0, S, L);
118}
119
120Optional<unsigned> DILocation::encodeDiscriminator(unsigned BD, unsigned DF, unsigned CI) {
121  SmallVector<unsigned, 3> Components = {BD, DF, CI};
122  uint64_t RemainingWork = 0U;
123  // We use RemainingWork to figure out if we have no remaining components to
124  // encode. For example: if BD != 0 but DF == 0 && CI == 0, we don't need to
125  // encode anything for the latter 2.
126  // Since any of the input components is at most 32 bits, their sum will be
127  // less than 34 bits, and thus RemainingWork won't overflow.
128  RemainingWork = std::accumulate(Components.begin(), Components.end(), RemainingWork);
129
130  int I = 0;
131  unsigned Ret = 0;
132  unsigned NextBitInsertionIndex = 0;
133  while (RemainingWork > 0) {
134    unsigned C = Components[I++];
135    RemainingWork -= C;
136    unsigned EC = encodeComponent(C);
137    Ret |= (EC << NextBitInsertionIndex);
138    NextBitInsertionIndex += encodingBits(C);
139  }
140
141  // Encoding may be unsuccessful because of overflow. We determine success by
142  // checking equivalence of components before & after encoding. Alternatively,
143  // we could determine Success during encoding, but the current alternative is
144  // simpler.
145  unsigned TBD, TDF, TCI = 0;
146  decodeDiscriminator(Ret, TBD, TDF, TCI);
147  if (TBD == BD && TDF == DF && TCI == CI)
148    return Ret;
149  return None;
150}
151
152void DILocation::decodeDiscriminator(unsigned D, unsigned &BD, unsigned &DF,
153                                     unsigned &CI) {
154  BD = getUnsignedFromPrefixEncoding(D);
155  DF = getUnsignedFromPrefixEncoding(getNextComponentInDiscriminator(D));
156  CI = getUnsignedFromPrefixEncoding(
157      getNextComponentInDiscriminator(getNextComponentInDiscriminator(D)));
158}
159
160
161DINode::DIFlags DINode::getFlag(StringRef Flag) {
162  return StringSwitch<DIFlags>(Flag)
163#define HANDLE_DI_FLAG(ID, NAME) .Case("DIFlag" #NAME, Flag##NAME)
164#include "llvm/IR/DebugInfoFlags.def"
165      .Default(DINode::FlagZero);
166}
167
168StringRef DINode::getFlagString(DIFlags Flag) {
169  switch (Flag) {
170#define HANDLE_DI_FLAG(ID, NAME)                                               \
171  case Flag##NAME:                                                             \
172    return "DIFlag" #NAME;
173#include "llvm/IR/DebugInfoFlags.def"
174  }
175  return "";
176}
177
178DINode::DIFlags DINode::splitFlags(DIFlags Flags,
179                                   SmallVectorImpl<DIFlags> &SplitFlags) {
180  // Flags that are packed together need to be specially handled, so
181  // that, for example, we emit "DIFlagPublic" and not
182  // "DIFlagPrivate | DIFlagProtected".
183  if (DIFlags A = Flags & FlagAccessibility) {
184    if (A == FlagPrivate)
185      SplitFlags.push_back(FlagPrivate);
186    else if (A == FlagProtected)
187      SplitFlags.push_back(FlagProtected);
188    else
189      SplitFlags.push_back(FlagPublic);
190    Flags &= ~A;
191  }
192  if (DIFlags R = Flags & FlagPtrToMemberRep) {
193    if (R == FlagSingleInheritance)
194      SplitFlags.push_back(FlagSingleInheritance);
195    else if (R == FlagMultipleInheritance)
196      SplitFlags.push_back(FlagMultipleInheritance);
197    else
198      SplitFlags.push_back(FlagVirtualInheritance);
199    Flags &= ~R;
200  }
201  if ((Flags & FlagIndirectVirtualBase) == FlagIndirectVirtualBase) {
202    Flags &= ~FlagIndirectVirtualBase;
203    SplitFlags.push_back(FlagIndirectVirtualBase);
204  }
205
206#define HANDLE_DI_FLAG(ID, NAME)                                               \
207  if (DIFlags Bit = Flags & Flag##NAME) {                                      \
208    SplitFlags.push_back(Bit);                                                 \
209    Flags &= ~Bit;                                                             \
210  }
211#include "llvm/IR/DebugInfoFlags.def"
212  return Flags;
213}
214
215DIScope *DIScope::getScope() const {
216  if (auto *T = dyn_cast<DIType>(this))
217    return T->getScope();
218
219  if (auto *SP = dyn_cast<DISubprogram>(this))
220    return SP->getScope();
221
222  if (auto *LB = dyn_cast<DILexicalBlockBase>(this))
223    return LB->getScope();
224
225  if (auto *NS = dyn_cast<DINamespace>(this))
226    return NS->getScope();
227
228  if (auto *CB = dyn_cast<DICommonBlock>(this))
229    return CB->getScope();
230
231  if (auto *M = dyn_cast<DIModule>(this))
232    return M->getScope();
233
234  assert((isa<DIFile>(this) || isa<DICompileUnit>(this)) &&
235         "Unhandled type of scope.");
236  return nullptr;
237}
238
239StringRef DIScope::getName() const {
240  if (auto *T = dyn_cast<DIType>(this))
241    return T->getName();
242  if (auto *SP = dyn_cast<DISubprogram>(this))
243    return SP->getName();
244  if (auto *NS = dyn_cast<DINamespace>(this))
245    return NS->getName();
246  if (auto *CB = dyn_cast<DICommonBlock>(this))
247    return CB->getName();
248  if (auto *M = dyn_cast<DIModule>(this))
249    return M->getName();
250  assert((isa<DILexicalBlockBase>(this) || isa<DIFile>(this) ||
251          isa<DICompileUnit>(this)) &&
252         "Unhandled type of scope.");
253  return "";
254}
255
256#ifndef NDEBUG
257static bool isCanonical(const MDString *S) {
258  return !S || !S->getString().empty();
259}
260#endif
261
262GenericDINode *GenericDINode::getImpl(LLVMContext &Context, unsigned Tag,
263                                      MDString *Header,
264                                      ArrayRef<Metadata *> DwarfOps,
265                                      StorageType Storage, bool ShouldCreate) {
266  unsigned Hash = 0;
267  if (Storage == Uniqued) {
268    GenericDINodeInfo::KeyTy Key(Tag, Header, DwarfOps);
269    if (auto *N = getUniqued(Context.pImpl->GenericDINodes, Key))
270      return N;
271    if (!ShouldCreate)
272      return nullptr;
273    Hash = Key.getHash();
274  } else {
275    assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
276  }
277
278  // Use a nullptr for empty headers.
279  assert(isCanonical(Header) && "Expected canonical MDString");
280  Metadata *PreOps[] = {Header};
281  return storeImpl(new (DwarfOps.size() + 1) GenericDINode(
282                       Context, Storage, Hash, Tag, PreOps, DwarfOps),
283                   Storage, Context.pImpl->GenericDINodes);
284}
285
286void GenericDINode::recalculateHash() {
287  setHash(GenericDINodeInfo::KeyTy::calculateHash(this));
288}
289
290#define UNWRAP_ARGS_IMPL(...) __VA_ARGS__
291#define UNWRAP_ARGS(ARGS) UNWRAP_ARGS_IMPL ARGS
292#define DEFINE_GETIMPL_LOOKUP(CLASS, ARGS)                                     \
293  do {                                                                         \
294    if (Storage == Uniqued) {                                                  \
295      if (auto *N = getUniqued(Context.pImpl->CLASS##s,                        \
296                               CLASS##Info::KeyTy(UNWRAP_ARGS(ARGS))))         \
297        return N;                                                              \
298      if (!ShouldCreate)                                                       \
299        return nullptr;                                                        \
300    } else {                                                                   \
301      assert(ShouldCreate &&                                                   \
302             "Expected non-uniqued nodes to always be created");               \
303    }                                                                          \
304  } while (false)
305#define DEFINE_GETIMPL_STORE(CLASS, ARGS, OPS)                                 \
306  return storeImpl(new (array_lengthof(OPS))                                   \
307                       CLASS(Context, Storage, UNWRAP_ARGS(ARGS), OPS),        \
308                   Storage, Context.pImpl->CLASS##s)
309#define DEFINE_GETIMPL_STORE_NO_OPS(CLASS, ARGS)                               \
310  return storeImpl(new (0u) CLASS(Context, Storage, UNWRAP_ARGS(ARGS)),        \
311                   Storage, Context.pImpl->CLASS##s)
312#define DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(CLASS, OPS)                   \
313  return storeImpl(new (array_lengthof(OPS)) CLASS(Context, Storage, OPS),     \
314                   Storage, Context.pImpl->CLASS##s)
315#define DEFINE_GETIMPL_STORE_N(CLASS, ARGS, OPS, NUM_OPS)                      \
316  return storeImpl(new (NUM_OPS)                                               \
317                       CLASS(Context, Storage, UNWRAP_ARGS(ARGS), OPS),        \
318                   Storage, Context.pImpl->CLASS##s)
319
320DISubrange *DISubrange::getImpl(LLVMContext &Context, int64_t Count, int64_t Lo,
321                                StorageType Storage, bool ShouldCreate) {
322  auto *CountNode = ConstantAsMetadata::get(
323      ConstantInt::getSigned(Type::getInt64Ty(Context), Count));
324  return getImpl(Context, CountNode, Lo, Storage, ShouldCreate);
325}
326
327DISubrange *DISubrange::getImpl(LLVMContext &Context, Metadata *CountNode,
328                                int64_t Lo, StorageType Storage,
329                                bool ShouldCreate) {
330  DEFINE_GETIMPL_LOOKUP(DISubrange, (CountNode, Lo));
331  Metadata *Ops[] = { CountNode };
332  DEFINE_GETIMPL_STORE(DISubrange, (CountNode, Lo), Ops);
333}
334
335DIEnumerator *DIEnumerator::getImpl(LLVMContext &Context, int64_t Value,
336                                    bool IsUnsigned, MDString *Name,
337                                    StorageType Storage, bool ShouldCreate) {
338  assert(isCanonical(Name) && "Expected canonical MDString");
339  DEFINE_GETIMPL_LOOKUP(DIEnumerator, (Value, IsUnsigned, Name));
340  Metadata *Ops[] = {Name};
341  DEFINE_GETIMPL_STORE(DIEnumerator, (Value, IsUnsigned), Ops);
342}
343
344DIBasicType *DIBasicType::getImpl(LLVMContext &Context, unsigned Tag,
345                                  MDString *Name, uint64_t SizeInBits,
346                                  uint32_t AlignInBits, unsigned Encoding,
347                                  DIFlags Flags, StorageType Storage,
348                                  bool ShouldCreate) {
349  assert(isCanonical(Name) && "Expected canonical MDString");
350  DEFINE_GETIMPL_LOOKUP(DIBasicType,
351                        (Tag, Name, SizeInBits, AlignInBits, Encoding, Flags));
352  Metadata *Ops[] = {nullptr, nullptr, Name};
353  DEFINE_GETIMPL_STORE(DIBasicType, (Tag, SizeInBits, AlignInBits, Encoding,
354                      Flags), Ops);
355}
356
357Optional<DIBasicType::Signedness> DIBasicType::getSignedness() const {
358  switch (getEncoding()) {
359  case dwarf::DW_ATE_signed:
360  case dwarf::DW_ATE_signed_char:
361    return Signedness::Signed;
362  case dwarf::DW_ATE_unsigned:
363  case dwarf::DW_ATE_unsigned_char:
364    return Signedness::Unsigned;
365  default:
366    return None;
367  }
368}
369
370DIDerivedType *DIDerivedType::getImpl(
371    LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
372    unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits,
373    uint32_t AlignInBits, uint64_t OffsetInBits,
374    Optional<unsigned> DWARFAddressSpace, DIFlags Flags, Metadata *ExtraData,
375    StorageType Storage, bool ShouldCreate) {
376  assert(isCanonical(Name) && "Expected canonical MDString");
377  DEFINE_GETIMPL_LOOKUP(DIDerivedType,
378                        (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
379                         AlignInBits, OffsetInBits, DWARFAddressSpace, Flags,
380                         ExtraData));
381  Metadata *Ops[] = {File, Scope, Name, BaseType, ExtraData};
382  DEFINE_GETIMPL_STORE(
383      DIDerivedType, (Tag, Line, SizeInBits, AlignInBits, OffsetInBits,
384                      DWARFAddressSpace, Flags), Ops);
385}
386
387DICompositeType *DICompositeType::getImpl(
388    LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
389    unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits,
390    uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags,
391    Metadata *Elements, unsigned RuntimeLang, Metadata *VTableHolder,
392    Metadata *TemplateParams, MDString *Identifier, Metadata *Discriminator,
393    StorageType Storage, bool ShouldCreate) {
394  assert(isCanonical(Name) && "Expected canonical MDString");
395
396  // Keep this in sync with buildODRType.
397  DEFINE_GETIMPL_LOOKUP(
398      DICompositeType, (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
399                        AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
400                        VTableHolder, TemplateParams, Identifier, Discriminator));
401  Metadata *Ops[] = {File,     Scope,        Name,           BaseType,
402                     Elements, VTableHolder, TemplateParams, Identifier,
403                     Discriminator};
404  DEFINE_GETIMPL_STORE(DICompositeType, (Tag, Line, RuntimeLang, SizeInBits,
405                                         AlignInBits, OffsetInBits, Flags),
406                       Ops);
407}
408
409DICompositeType *DICompositeType::buildODRType(
410    LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name,
411    Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType,
412    uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
413    DIFlags Flags, Metadata *Elements, unsigned RuntimeLang,
414    Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator) {
415  assert(!Identifier.getString().empty() && "Expected valid identifier");
416  if (!Context.isODRUniquingDebugTypes())
417    return nullptr;
418  auto *&CT = (*Context.pImpl->DITypeMap)[&Identifier];
419  if (!CT)
420    return CT = DICompositeType::getDistinct(
421               Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
422               AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
423               VTableHolder, TemplateParams, &Identifier, Discriminator);
424
425  // Only mutate CT if it's a forward declaration and the new operands aren't.
426  assert(CT->getRawIdentifier() == &Identifier && "Wrong ODR identifier?");
427  if (!CT->isForwardDecl() || (Flags & DINode::FlagFwdDecl))
428    return CT;
429
430  // Mutate CT in place.  Keep this in sync with getImpl.
431  CT->mutate(Tag, Line, RuntimeLang, SizeInBits, AlignInBits, OffsetInBits,
432             Flags);
433  Metadata *Ops[] = {File,     Scope,        Name,           BaseType,
434                     Elements, VTableHolder, TemplateParams, &Identifier,
435                     Discriminator};
436  assert((std::end(Ops) - std::begin(Ops)) == (int)CT->getNumOperands() &&
437         "Mismatched number of operands");
438  for (unsigned I = 0, E = CT->getNumOperands(); I != E; ++I)
439    if (Ops[I] != CT->getOperand(I))
440      CT->setOperand(I, Ops[I]);
441  return CT;
442}
443
444DICompositeType *DICompositeType::getODRType(
445    LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name,
446    Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType,
447    uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
448    DIFlags Flags, Metadata *Elements, unsigned RuntimeLang,
449    Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator) {
450  assert(!Identifier.getString().empty() && "Expected valid identifier");
451  if (!Context.isODRUniquingDebugTypes())
452    return nullptr;
453  auto *&CT = (*Context.pImpl->DITypeMap)[&Identifier];
454  if (!CT)
455    CT = DICompositeType::getDistinct(
456        Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
457        AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, VTableHolder,
458        TemplateParams, &Identifier, Discriminator);
459  return CT;
460}
461
462DICompositeType *DICompositeType::getODRTypeIfExists(LLVMContext &Context,
463                                                     MDString &Identifier) {
464  assert(!Identifier.getString().empty() && "Expected valid identifier");
465  if (!Context.isODRUniquingDebugTypes())
466    return nullptr;
467  return Context.pImpl->DITypeMap->lookup(&Identifier);
468}
469
470DISubroutineType *DISubroutineType::getImpl(LLVMContext &Context, DIFlags Flags,
471                                            uint8_t CC, Metadata *TypeArray,
472                                            StorageType Storage,
473                                            bool ShouldCreate) {
474  DEFINE_GETIMPL_LOOKUP(DISubroutineType, (Flags, CC, TypeArray));
475  Metadata *Ops[] = {nullptr, nullptr, nullptr, TypeArray};
476  DEFINE_GETIMPL_STORE(DISubroutineType, (Flags, CC), Ops);
477}
478
479// FIXME: Implement this string-enum correspondence with a .def file and macros,
480// so that the association is explicit rather than implied.
481static const char *ChecksumKindName[DIFile::CSK_Last] = {
482  "CSK_MD5",
483  "CSK_SHA1"
484};
485
486StringRef DIFile::getChecksumKindAsString(ChecksumKind CSKind) {
487  assert(CSKind <= DIFile::CSK_Last && "Invalid checksum kind");
488  // The first space was originally the CSK_None variant, which is now
489  // obsolete, but the space is still reserved in ChecksumKind, so we account
490  // for it here.
491  return ChecksumKindName[CSKind - 1];
492}
493
494Optional<DIFile::ChecksumKind> DIFile::getChecksumKind(StringRef CSKindStr) {
495  return StringSwitch<Optional<DIFile::ChecksumKind>>(CSKindStr)
496      .Case("CSK_MD5", DIFile::CSK_MD5)
497      .Case("CSK_SHA1", DIFile::CSK_SHA1)
498      .Default(None);
499}
500
501DIFile *DIFile::getImpl(LLVMContext &Context, MDString *Filename,
502                        MDString *Directory,
503                        Optional<DIFile::ChecksumInfo<MDString *>> CS,
504                        Optional<MDString *> Source, StorageType Storage,
505                        bool ShouldCreate) {
506  assert(isCanonical(Filename) && "Expected canonical MDString");
507  assert(isCanonical(Directory) && "Expected canonical MDString");
508  assert((!CS || isCanonical(CS->Value)) && "Expected canonical MDString");
509  assert((!Source || isCanonical(*Source)) && "Expected canonical MDString");
510  DEFINE_GETIMPL_LOOKUP(DIFile, (Filename, Directory, CS, Source));
511  Metadata *Ops[] = {Filename, Directory, CS ? CS->Value : nullptr,
512                     Source.getValueOr(nullptr)};
513  DEFINE_GETIMPL_STORE(DIFile, (CS, Source), Ops);
514}
515
516DICompileUnit *DICompileUnit::getImpl(
517    LLVMContext &Context, unsigned SourceLanguage, Metadata *File,
518    MDString *Producer, bool IsOptimized, MDString *Flags,
519    unsigned RuntimeVersion, MDString *SplitDebugFilename,
520    unsigned EmissionKind, Metadata *EnumTypes, Metadata *RetainedTypes,
521    Metadata *GlobalVariables, Metadata *ImportedEntities, Metadata *Macros,
522    uint64_t DWOId, bool SplitDebugInlining, bool DebugInfoForProfiling,
523    unsigned NameTableKind, bool RangesBaseAddress, StorageType Storage,
524    bool ShouldCreate) {
525  assert(Storage != Uniqued && "Cannot unique DICompileUnit");
526  assert(isCanonical(Producer) && "Expected canonical MDString");
527  assert(isCanonical(Flags) && "Expected canonical MDString");
528  assert(isCanonical(SplitDebugFilename) && "Expected canonical MDString");
529
530  Metadata *Ops[] = {
531      File,      Producer,      Flags,           SplitDebugFilename,
532      EnumTypes, RetainedTypes, GlobalVariables, ImportedEntities,
533      Macros};
534  return storeImpl(new (array_lengthof(Ops)) DICompileUnit(
535                       Context, Storage, SourceLanguage, IsOptimized,
536                       RuntimeVersion, EmissionKind, DWOId, SplitDebugInlining,
537                       DebugInfoForProfiling, NameTableKind, RangesBaseAddress,
538                       Ops),
539                   Storage);
540}
541
542Optional<DICompileUnit::DebugEmissionKind>
543DICompileUnit::getEmissionKind(StringRef Str) {
544  return StringSwitch<Optional<DebugEmissionKind>>(Str)
545      .Case("NoDebug", NoDebug)
546      .Case("FullDebug", FullDebug)
547      .Case("LineTablesOnly", LineTablesOnly)
548      .Case("DebugDirectivesOnly", DebugDirectivesOnly)
549      .Default(None);
550}
551
552Optional<DICompileUnit::DebugNameTableKind>
553DICompileUnit::getNameTableKind(StringRef Str) {
554  return StringSwitch<Optional<DebugNameTableKind>>(Str)
555      .Case("Default", DebugNameTableKind::Default)
556      .Case("GNU", DebugNameTableKind::GNU)
557      .Case("None", DebugNameTableKind::None)
558      .Default(None);
559}
560
561const char *DICompileUnit::emissionKindString(DebugEmissionKind EK) {
562  switch (EK) {
563  case NoDebug:        return "NoDebug";
564  case FullDebug:      return "FullDebug";
565  case LineTablesOnly: return "LineTablesOnly";
566  case DebugDirectivesOnly: return "DebugDirectivesOnly";
567  }
568  return nullptr;
569}
570
571const char *DICompileUnit::nameTableKindString(DebugNameTableKind NTK) {
572  switch (NTK) {
573  case DebugNameTableKind::Default:
574    return nullptr;
575  case DebugNameTableKind::GNU:
576    return "GNU";
577  case DebugNameTableKind::None:
578    return "None";
579  }
580  return nullptr;
581}
582
583DISubprogram *DILocalScope::getSubprogram() const {
584  if (auto *Block = dyn_cast<DILexicalBlockBase>(this))
585    return Block->getScope()->getSubprogram();
586  return const_cast<DISubprogram *>(cast<DISubprogram>(this));
587}
588
589DILocalScope *DILocalScope::getNonLexicalBlockFileScope() const {
590  if (auto *File = dyn_cast<DILexicalBlockFile>(this))
591    return File->getScope()->getNonLexicalBlockFileScope();
592  return const_cast<DILocalScope *>(this);
593}
594
595DISubprogram::DISPFlags DISubprogram::getFlag(StringRef Flag) {
596  return StringSwitch<DISPFlags>(Flag)
597#define HANDLE_DISP_FLAG(ID, NAME) .Case("DISPFlag" #NAME, SPFlag##NAME)
598#include "llvm/IR/DebugInfoFlags.def"
599      .Default(SPFlagZero);
600}
601
602StringRef DISubprogram::getFlagString(DISPFlags Flag) {
603  switch (Flag) {
604  // Appease a warning.
605  case SPFlagVirtuality:
606    return "";
607#define HANDLE_DISP_FLAG(ID, NAME)                                             \
608  case SPFlag##NAME:                                                           \
609    return "DISPFlag" #NAME;
610#include "llvm/IR/DebugInfoFlags.def"
611  }
612  return "";
613}
614
615DISubprogram::DISPFlags
616DISubprogram::splitFlags(DISPFlags Flags,
617                         SmallVectorImpl<DISPFlags> &SplitFlags) {
618  // Multi-bit fields can require special handling. In our case, however, the
619  // only multi-bit field is virtuality, and all its values happen to be
620  // single-bit values, so the right behavior just falls out.
621#define HANDLE_DISP_FLAG(ID, NAME)                                             \
622  if (DISPFlags Bit = Flags & SPFlag##NAME) {                                  \
623    SplitFlags.push_back(Bit);                                                 \
624    Flags &= ~Bit;                                                             \
625  }
626#include "llvm/IR/DebugInfoFlags.def"
627  return Flags;
628}
629
630DISubprogram *DISubprogram::getImpl(
631    LLVMContext &Context, Metadata *Scope, MDString *Name,
632    MDString *LinkageName, Metadata *File, unsigned Line, Metadata *Type,
633    unsigned ScopeLine, Metadata *ContainingType, unsigned VirtualIndex,
634    int ThisAdjustment, DIFlags Flags, DISPFlags SPFlags, Metadata *Unit,
635    Metadata *TemplateParams, Metadata *Declaration, Metadata *RetainedNodes,
636    Metadata *ThrownTypes, StorageType Storage, bool ShouldCreate) {
637  assert(isCanonical(Name) && "Expected canonical MDString");
638  assert(isCanonical(LinkageName) && "Expected canonical MDString");
639  DEFINE_GETIMPL_LOOKUP(DISubprogram,
640                        (Scope, Name, LinkageName, File, Line, Type, ScopeLine,
641                         ContainingType, VirtualIndex, ThisAdjustment, Flags,
642                         SPFlags, Unit, TemplateParams, Declaration,
643                         RetainedNodes, ThrownTypes));
644  SmallVector<Metadata *, 11> Ops = {
645      File,        Scope,         Name,           LinkageName,    Type,       Unit,
646      Declaration, RetainedNodes, ContainingType, TemplateParams, ThrownTypes};
647  if (!ThrownTypes) {
648    Ops.pop_back();
649    if (!TemplateParams) {
650      Ops.pop_back();
651      if (!ContainingType)
652        Ops.pop_back();
653    }
654  }
655  DEFINE_GETIMPL_STORE_N(
656      DISubprogram,
657      (Line, ScopeLine, VirtualIndex, ThisAdjustment, Flags, SPFlags), Ops,
658      Ops.size());
659}
660
661bool DISubprogram::describes(const Function *F) const {
662  assert(F && "Invalid function");
663  if (F->getSubprogram() == this)
664    return true;
665  StringRef Name = getLinkageName();
666  if (Name.empty())
667    Name = getName();
668  return F->getName() == Name;
669}
670
671DILexicalBlock *DILexicalBlock::getImpl(LLVMContext &Context, Metadata *Scope,
672                                        Metadata *File, unsigned Line,
673                                        unsigned Column, StorageType Storage,
674                                        bool ShouldCreate) {
675  // Fixup column.
676  adjustColumn(Column);
677
678  assert(Scope && "Expected scope");
679  DEFINE_GETIMPL_LOOKUP(DILexicalBlock, (Scope, File, Line, Column));
680  Metadata *Ops[] = {File, Scope};
681  DEFINE_GETIMPL_STORE(DILexicalBlock, (Line, Column), Ops);
682}
683
684DILexicalBlockFile *DILexicalBlockFile::getImpl(LLVMContext &Context,
685                                                Metadata *Scope, Metadata *File,
686                                                unsigned Discriminator,
687                                                StorageType Storage,
688                                                bool ShouldCreate) {
689  assert(Scope && "Expected scope");
690  DEFINE_GETIMPL_LOOKUP(DILexicalBlockFile, (Scope, File, Discriminator));
691  Metadata *Ops[] = {File, Scope};
692  DEFINE_GETIMPL_STORE(DILexicalBlockFile, (Discriminator), Ops);
693}
694
695DINamespace *DINamespace::getImpl(LLVMContext &Context, Metadata *Scope,
696                                  MDString *Name, bool ExportSymbols,
697                                  StorageType Storage, bool ShouldCreate) {
698  assert(isCanonical(Name) && "Expected canonical MDString");
699  DEFINE_GETIMPL_LOOKUP(DINamespace, (Scope, Name, ExportSymbols));
700  // The nullptr is for DIScope's File operand. This should be refactored.
701  Metadata *Ops[] = {nullptr, Scope, Name};
702  DEFINE_GETIMPL_STORE(DINamespace, (ExportSymbols), Ops);
703}
704
705DICommonBlock *DICommonBlock::getImpl(LLVMContext &Context, Metadata *Scope,
706                                      Metadata *Decl, MDString *Name,
707                                      Metadata *File, unsigned LineNo,
708                                      StorageType Storage, bool ShouldCreate) {
709  assert(isCanonical(Name) && "Expected canonical MDString");
710  DEFINE_GETIMPL_LOOKUP(DICommonBlock, (Scope, Decl, Name, File, LineNo));
711  // The nullptr is for DIScope's File operand. This should be refactored.
712  Metadata *Ops[] = {Scope, Decl, Name, File};
713  DEFINE_GETIMPL_STORE(DICommonBlock, (LineNo), Ops);
714}
715
716DIModule *DIModule::getImpl(LLVMContext &Context, Metadata *Scope,
717                            MDString *Name, MDString *ConfigurationMacros,
718                            MDString *IncludePath, MDString *SysRoot,
719                            StorageType Storage, bool ShouldCreate) {
720  assert(isCanonical(Name) && "Expected canonical MDString");
721  DEFINE_GETIMPL_LOOKUP(
722      DIModule, (Scope, Name, ConfigurationMacros, IncludePath, SysRoot));
723  Metadata *Ops[] = {Scope, Name, ConfigurationMacros, IncludePath, SysRoot};
724  DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DIModule, Ops);
725}
726
727DITemplateTypeParameter *DITemplateTypeParameter::getImpl(LLVMContext &Context,
728                                                          MDString *Name,
729                                                          Metadata *Type,
730                                                          StorageType Storage,
731                                                          bool ShouldCreate) {
732  assert(isCanonical(Name) && "Expected canonical MDString");
733  DEFINE_GETIMPL_LOOKUP(DITemplateTypeParameter, (Name, Type));
734  Metadata *Ops[] = {Name, Type};
735  DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DITemplateTypeParameter, Ops);
736}
737
738DITemplateValueParameter *DITemplateValueParameter::getImpl(
739    LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *Type,
740    Metadata *Value, StorageType Storage, bool ShouldCreate) {
741  assert(isCanonical(Name) && "Expected canonical MDString");
742  DEFINE_GETIMPL_LOOKUP(DITemplateValueParameter, (Tag, Name, Type, Value));
743  Metadata *Ops[] = {Name, Type, Value};
744  DEFINE_GETIMPL_STORE(DITemplateValueParameter, (Tag), Ops);
745}
746
747DIGlobalVariable *
748DIGlobalVariable::getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
749                          MDString *LinkageName, Metadata *File, unsigned Line,
750                          Metadata *Type, bool IsLocalToUnit, bool IsDefinition,
751                          Metadata *StaticDataMemberDeclaration,
752                          Metadata *TemplateParams, uint32_t AlignInBits,
753                          StorageType Storage, bool ShouldCreate) {
754  assert(isCanonical(Name) && "Expected canonical MDString");
755  assert(isCanonical(LinkageName) && "Expected canonical MDString");
756  DEFINE_GETIMPL_LOOKUP(DIGlobalVariable, (Scope, Name, LinkageName, File, Line,
757                                           Type, IsLocalToUnit, IsDefinition,
758                                           StaticDataMemberDeclaration,
759                                           TemplateParams, AlignInBits));
760  Metadata *Ops[] = {Scope,
761                     Name,
762                     File,
763                     Type,
764                     Name,
765                     LinkageName,
766                     StaticDataMemberDeclaration,
767                     TemplateParams};
768  DEFINE_GETIMPL_STORE(DIGlobalVariable,
769                       (Line, IsLocalToUnit, IsDefinition, AlignInBits), Ops);
770}
771
772DILocalVariable *DILocalVariable::getImpl(LLVMContext &Context, Metadata *Scope,
773                                          MDString *Name, Metadata *File,
774                                          unsigned Line, Metadata *Type,
775                                          unsigned Arg, DIFlags Flags,
776                                          uint32_t AlignInBits,
777                                          StorageType Storage,
778                                          bool ShouldCreate) {
779  // 64K ought to be enough for any frontend.
780  assert(Arg <= UINT16_MAX && "Expected argument number to fit in 16-bits");
781
782  assert(Scope && "Expected scope");
783  assert(isCanonical(Name) && "Expected canonical MDString");
784  DEFINE_GETIMPL_LOOKUP(DILocalVariable,
785                        (Scope, Name, File, Line, Type, Arg, Flags,
786                         AlignInBits));
787  Metadata *Ops[] = {Scope, Name, File, Type};
788  DEFINE_GETIMPL_STORE(DILocalVariable, (Line, Arg, Flags, AlignInBits), Ops);
789}
790
791Optional<uint64_t> DIVariable::getSizeInBits() const {
792  // This is used by the Verifier so be mindful of broken types.
793  const Metadata *RawType = getRawType();
794  while (RawType) {
795    // Try to get the size directly.
796    if (auto *T = dyn_cast<DIType>(RawType))
797      if (uint64_t Size = T->getSizeInBits())
798        return Size;
799
800    if (auto *DT = dyn_cast<DIDerivedType>(RawType)) {
801      // Look at the base type.
802      RawType = DT->getRawBaseType();
803      continue;
804    }
805
806    // Missing type or size.
807    break;
808  }
809
810  // Fail gracefully.
811  return None;
812}
813
814DILabel *DILabel::getImpl(LLVMContext &Context, Metadata *Scope,
815                          MDString *Name, Metadata *File, unsigned Line,
816                          StorageType Storage,
817                          bool ShouldCreate) {
818  assert(Scope && "Expected scope");
819  assert(isCanonical(Name) && "Expected canonical MDString");
820  DEFINE_GETIMPL_LOOKUP(DILabel,
821                        (Scope, Name, File, Line));
822  Metadata *Ops[] = {Scope, Name, File};
823  DEFINE_GETIMPL_STORE(DILabel, (Line), Ops);
824}
825
826DIExpression *DIExpression::getImpl(LLVMContext &Context,
827                                    ArrayRef<uint64_t> Elements,
828                                    StorageType Storage, bool ShouldCreate) {
829  DEFINE_GETIMPL_LOOKUP(DIExpression, (Elements));
830  DEFINE_GETIMPL_STORE_NO_OPS(DIExpression, (Elements));
831}
832
833unsigned DIExpression::ExprOperand::getSize() const {
834  uint64_t Op = getOp();
835
836  if (Op >= dwarf::DW_OP_breg0 && Op <= dwarf::DW_OP_breg31)
837    return 2;
838
839  switch (Op) {
840  case dwarf::DW_OP_LLVM_convert:
841  case dwarf::DW_OP_LLVM_fragment:
842  case dwarf::DW_OP_bregx:
843    return 3;
844  case dwarf::DW_OP_constu:
845  case dwarf::DW_OP_consts:
846  case dwarf::DW_OP_deref_size:
847  case dwarf::DW_OP_plus_uconst:
848  case dwarf::DW_OP_LLVM_tag_offset:
849  case dwarf::DW_OP_LLVM_entry_value:
850  case dwarf::DW_OP_regx:
851    return 2;
852  default:
853    return 1;
854  }
855}
856
857bool DIExpression::isValid() const {
858  for (auto I = expr_op_begin(), E = expr_op_end(); I != E; ++I) {
859    // Check that there's space for the operand.
860    if (I->get() + I->getSize() > E->get())
861      return false;
862
863    uint64_t Op = I->getOp();
864    if ((Op >= dwarf::DW_OP_reg0 && Op <= dwarf::DW_OP_reg31) ||
865        (Op >= dwarf::DW_OP_breg0 && Op <= dwarf::DW_OP_breg31))
866      return true;
867
868    // Check that the operand is valid.
869    switch (Op) {
870    default:
871      return false;
872    case dwarf::DW_OP_LLVM_fragment:
873      // A fragment operator must appear at the end.
874      return I->get() + I->getSize() == E->get();
875    case dwarf::DW_OP_stack_value: {
876      // Must be the last one or followed by a DW_OP_LLVM_fragment.
877      if (I->get() + I->getSize() == E->get())
878        break;
879      auto J = I;
880      if ((++J)->getOp() != dwarf::DW_OP_LLVM_fragment)
881        return false;
882      break;
883    }
884    case dwarf::DW_OP_swap: {
885      // Must be more than one implicit element on the stack.
886
887      // FIXME: A better way to implement this would be to add a local variable
888      // that keeps track of the stack depth and introduce something like a
889      // DW_LLVM_OP_implicit_location as a placeholder for the location this
890      // DIExpression is attached to, or else pass the number of implicit stack
891      // elements into isValid.
892      if (getNumElements() == 1)
893        return false;
894      break;
895    }
896    case dwarf::DW_OP_LLVM_entry_value: {
897      // An entry value operator must appear at the beginning and the number of
898      // operations it cover can currently only be 1, because we support only
899      // entry values of a simple register location. One reason for this is that
900      // we currently can't calculate the size of the resulting DWARF block for
901      // other expressions.
902      return I->get() == expr_op_begin()->get() && I->getArg(0) == 1 &&
903             getNumElements() == 2;
904    }
905    case dwarf::DW_OP_LLVM_convert:
906    case dwarf::DW_OP_LLVM_tag_offset:
907    case dwarf::DW_OP_constu:
908    case dwarf::DW_OP_plus_uconst:
909    case dwarf::DW_OP_plus:
910    case dwarf::DW_OP_minus:
911    case dwarf::DW_OP_mul:
912    case dwarf::DW_OP_div:
913    case dwarf::DW_OP_mod:
914    case dwarf::DW_OP_or:
915    case dwarf::DW_OP_and:
916    case dwarf::DW_OP_xor:
917    case dwarf::DW_OP_shl:
918    case dwarf::DW_OP_shr:
919    case dwarf::DW_OP_shra:
920    case dwarf::DW_OP_deref:
921    case dwarf::DW_OP_deref_size:
922    case dwarf::DW_OP_xderef:
923    case dwarf::DW_OP_lit0:
924    case dwarf::DW_OP_not:
925    case dwarf::DW_OP_dup:
926    case dwarf::DW_OP_regx:
927    case dwarf::DW_OP_bregx:
928      break;
929    }
930  }
931  return true;
932}
933
934bool DIExpression::isImplicit() const {
935  if (!isValid())
936    return false;
937
938  if (getNumElements() == 0)
939    return false;
940
941  for (const auto &It : expr_ops()) {
942    switch (It.getOp()) {
943    default:
944      break;
945    case dwarf::DW_OP_stack_value:
946    case dwarf::DW_OP_LLVM_tag_offset:
947      return true;
948    }
949  }
950
951  return false;
952}
953
954bool DIExpression::isComplex() const {
955  if (!isValid())
956    return false;
957
958  if (getNumElements() == 0)
959    return false;
960
961  // If there are any elements other than fragment or tag_offset, then some
962  // kind of complex computation occurs.
963  for (const auto &It : expr_ops()) {
964    switch (It.getOp()) {
965      case dwarf::DW_OP_LLVM_tag_offset:
966      case dwarf::DW_OP_LLVM_fragment:
967        continue;
968      default: return true;
969    }
970  }
971
972  return false;
973}
974
975Optional<DIExpression::FragmentInfo>
976DIExpression::getFragmentInfo(expr_op_iterator Start, expr_op_iterator End) {
977  for (auto I = Start; I != End; ++I)
978    if (I->getOp() == dwarf::DW_OP_LLVM_fragment) {
979      DIExpression::FragmentInfo Info = {I->getArg(1), I->getArg(0)};
980      return Info;
981    }
982  return None;
983}
984
985void DIExpression::appendOffset(SmallVectorImpl<uint64_t> &Ops,
986                                int64_t Offset) {
987  if (Offset > 0) {
988    Ops.push_back(dwarf::DW_OP_plus_uconst);
989    Ops.push_back(Offset);
990  } else if (Offset < 0) {
991    Ops.push_back(dwarf::DW_OP_constu);
992    Ops.push_back(-Offset);
993    Ops.push_back(dwarf::DW_OP_minus);
994  }
995}
996
997bool DIExpression::extractIfOffset(int64_t &Offset) const {
998  if (getNumElements() == 0) {
999    Offset = 0;
1000    return true;
1001  }
1002
1003  if (getNumElements() == 2 && Elements[0] == dwarf::DW_OP_plus_uconst) {
1004    Offset = Elements[1];
1005    return true;
1006  }
1007
1008  if (getNumElements() == 3 && Elements[0] == dwarf::DW_OP_constu) {
1009    if (Elements[2] == dwarf::DW_OP_plus) {
1010      Offset = Elements[1];
1011      return true;
1012    }
1013    if (Elements[2] == dwarf::DW_OP_minus) {
1014      Offset = -Elements[1];
1015      return true;
1016    }
1017  }
1018
1019  return false;
1020}
1021
1022const DIExpression *DIExpression::extractAddressClass(const DIExpression *Expr,
1023                                                      unsigned &AddrClass) {
1024  // FIXME: This seems fragile. Nothing that verifies that these elements
1025  // actually map to ops and not operands.
1026  const unsigned PatternSize = 4;
1027  if (Expr->Elements.size() >= PatternSize &&
1028      Expr->Elements[PatternSize - 4] == dwarf::DW_OP_constu &&
1029      Expr->Elements[PatternSize - 2] == dwarf::DW_OP_swap &&
1030      Expr->Elements[PatternSize - 1] == dwarf::DW_OP_xderef) {
1031    AddrClass = Expr->Elements[PatternSize - 3];
1032
1033    if (Expr->Elements.size() == PatternSize)
1034      return nullptr;
1035    return DIExpression::get(Expr->getContext(),
1036                             makeArrayRef(&*Expr->Elements.begin(),
1037                                          Expr->Elements.size() - PatternSize));
1038  }
1039  return Expr;
1040}
1041
1042DIExpression *DIExpression::prepend(const DIExpression *Expr, uint8_t Flags,
1043                                    int64_t Offset) {
1044  SmallVector<uint64_t, 8> Ops;
1045  if (Flags & DIExpression::DerefBefore)
1046    Ops.push_back(dwarf::DW_OP_deref);
1047
1048  appendOffset(Ops, Offset);
1049  if (Flags & DIExpression::DerefAfter)
1050    Ops.push_back(dwarf::DW_OP_deref);
1051
1052  bool StackValue = Flags & DIExpression::StackValue;
1053  bool EntryValue = Flags & DIExpression::EntryValue;
1054
1055  return prependOpcodes(Expr, Ops, StackValue, EntryValue);
1056}
1057
1058DIExpression *DIExpression::prependOpcodes(const DIExpression *Expr,
1059                                           SmallVectorImpl<uint64_t> &Ops,
1060                                           bool StackValue,
1061                                           bool EntryValue) {
1062  assert(Expr && "Can't prepend ops to this expression");
1063
1064  if (EntryValue) {
1065    Ops.push_back(dwarf::DW_OP_LLVM_entry_value);
1066    // Add size info needed for entry value expression.
1067    // Add plus one for target register operand.
1068    Ops.push_back(Expr->getNumElements() + 1);
1069  }
1070
1071  // If there are no ops to prepend, do not even add the DW_OP_stack_value.
1072  if (Ops.empty())
1073    StackValue = false;
1074  for (auto Op : Expr->expr_ops()) {
1075    // A DW_OP_stack_value comes at the end, but before a DW_OP_LLVM_fragment.
1076    if (StackValue) {
1077      if (Op.getOp() == dwarf::DW_OP_stack_value)
1078        StackValue = false;
1079      else if (Op.getOp() == dwarf::DW_OP_LLVM_fragment) {
1080        Ops.push_back(dwarf::DW_OP_stack_value);
1081        StackValue = false;
1082      }
1083    }
1084    Op.appendToVector(Ops);
1085  }
1086  if (StackValue)
1087    Ops.push_back(dwarf::DW_OP_stack_value);
1088  return DIExpression::get(Expr->getContext(), Ops);
1089}
1090
1091DIExpression *DIExpression::append(const DIExpression *Expr,
1092                                   ArrayRef<uint64_t> Ops) {
1093  assert(Expr && !Ops.empty() && "Can't append ops to this expression");
1094
1095  // Copy Expr's current op list.
1096  SmallVector<uint64_t, 16> NewOps;
1097  for (auto Op : Expr->expr_ops()) {
1098    // Append new opcodes before DW_OP_{stack_value, LLVM_fragment}.
1099    if (Op.getOp() == dwarf::DW_OP_stack_value ||
1100        Op.getOp() == dwarf::DW_OP_LLVM_fragment) {
1101      NewOps.append(Ops.begin(), Ops.end());
1102
1103      // Ensure that the new opcodes are only appended once.
1104      Ops = None;
1105    }
1106    Op.appendToVector(NewOps);
1107  }
1108
1109  NewOps.append(Ops.begin(), Ops.end());
1110  return DIExpression::get(Expr->getContext(), NewOps);
1111}
1112
1113DIExpression *DIExpression::appendToStack(const DIExpression *Expr,
1114                                          ArrayRef<uint64_t> Ops) {
1115  assert(Expr && !Ops.empty() && "Can't append ops to this expression");
1116  assert(none_of(Ops,
1117                 [](uint64_t Op) {
1118                   return Op == dwarf::DW_OP_stack_value ||
1119                          Op == dwarf::DW_OP_LLVM_fragment;
1120                 }) &&
1121         "Can't append this op");
1122
1123  // Append a DW_OP_deref after Expr's current op list if it's non-empty and
1124  // has no DW_OP_stack_value.
1125  //
1126  // Match .* DW_OP_stack_value (DW_OP_LLVM_fragment A B)?.
1127  Optional<FragmentInfo> FI = Expr->getFragmentInfo();
1128  unsigned DropUntilStackValue = FI.hasValue() ? 3 : 0;
1129  ArrayRef<uint64_t> ExprOpsBeforeFragment =
1130      Expr->getElements().drop_back(DropUntilStackValue);
1131  bool NeedsDeref = (Expr->getNumElements() > DropUntilStackValue) &&
1132                    (ExprOpsBeforeFragment.back() != dwarf::DW_OP_stack_value);
1133  bool NeedsStackValue = NeedsDeref || ExprOpsBeforeFragment.empty();
1134
1135  // Append a DW_OP_deref after Expr's current op list if needed, then append
1136  // the new ops, and finally ensure that a single DW_OP_stack_value is present.
1137  SmallVector<uint64_t, 16> NewOps;
1138  if (NeedsDeref)
1139    NewOps.push_back(dwarf::DW_OP_deref);
1140  NewOps.append(Ops.begin(), Ops.end());
1141  if (NeedsStackValue)
1142    NewOps.push_back(dwarf::DW_OP_stack_value);
1143  return DIExpression::append(Expr, NewOps);
1144}
1145
1146Optional<DIExpression *> DIExpression::createFragmentExpression(
1147    const DIExpression *Expr, unsigned OffsetInBits, unsigned SizeInBits) {
1148  SmallVector<uint64_t, 8> Ops;
1149  // Copy over the expression, but leave off any trailing DW_OP_LLVM_fragment.
1150  if (Expr) {
1151    for (auto Op : Expr->expr_ops()) {
1152      switch (Op.getOp()) {
1153      default: break;
1154      case dwarf::DW_OP_shr:
1155      case dwarf::DW_OP_shra:
1156      case dwarf::DW_OP_shl:
1157      case dwarf::DW_OP_plus:
1158      case dwarf::DW_OP_plus_uconst:
1159      case dwarf::DW_OP_minus:
1160        // We can't safely split arithmetic or shift operations into multiple
1161        // fragments because we can't express carry-over between fragments.
1162        //
1163        // FIXME: We *could* preserve the lowest fragment of a constant offset
1164        // operation if the offset fits into SizeInBits.
1165        return None;
1166      case dwarf::DW_OP_LLVM_fragment: {
1167        // Make the new offset point into the existing fragment.
1168        uint64_t FragmentOffsetInBits = Op.getArg(0);
1169        uint64_t FragmentSizeInBits = Op.getArg(1);
1170        (void)FragmentSizeInBits;
1171        assert((OffsetInBits + SizeInBits <= FragmentSizeInBits) &&
1172               "new fragment outside of original fragment");
1173        OffsetInBits += FragmentOffsetInBits;
1174        continue;
1175      }
1176      }
1177      Op.appendToVector(Ops);
1178    }
1179  }
1180  assert(Expr && "Unknown DIExpression");
1181  Ops.push_back(dwarf::DW_OP_LLVM_fragment);
1182  Ops.push_back(OffsetInBits);
1183  Ops.push_back(SizeInBits);
1184  return DIExpression::get(Expr->getContext(), Ops);
1185}
1186
1187bool DIExpression::isConstant() const {
1188  // Recognize DW_OP_constu C DW_OP_stack_value (DW_OP_LLVM_fragment Len Ofs)?.
1189  if (getNumElements() != 3 && getNumElements() != 6)
1190    return false;
1191  if (getElement(0) != dwarf::DW_OP_constu ||
1192      getElement(2) != dwarf::DW_OP_stack_value)
1193    return false;
1194  if (getNumElements() == 6 && getElement(3) != dwarf::DW_OP_LLVM_fragment)
1195    return false;
1196  return true;
1197}
1198
1199DIExpression::ExtOps DIExpression::getExtOps(unsigned FromSize, unsigned ToSize,
1200                                             bool Signed) {
1201  dwarf::TypeKind TK = Signed ? dwarf::DW_ATE_signed : dwarf::DW_ATE_unsigned;
1202  DIExpression::ExtOps Ops{{dwarf::DW_OP_LLVM_convert, FromSize, TK,
1203                            dwarf::DW_OP_LLVM_convert, ToSize, TK}};
1204  return Ops;
1205}
1206
1207DIExpression *DIExpression::appendExt(const DIExpression *Expr,
1208                                      unsigned FromSize, unsigned ToSize,
1209                                      bool Signed) {
1210  return appendToStack(Expr, getExtOps(FromSize, ToSize, Signed));
1211}
1212
1213DIGlobalVariableExpression *
1214DIGlobalVariableExpression::getImpl(LLVMContext &Context, Metadata *Variable,
1215                                    Metadata *Expression, StorageType Storage,
1216                                    bool ShouldCreate) {
1217  DEFINE_GETIMPL_LOOKUP(DIGlobalVariableExpression, (Variable, Expression));
1218  Metadata *Ops[] = {Variable, Expression};
1219  DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DIGlobalVariableExpression, Ops);
1220}
1221
1222DIObjCProperty *DIObjCProperty::getImpl(
1223    LLVMContext &Context, MDString *Name, Metadata *File, unsigned Line,
1224    MDString *GetterName, MDString *SetterName, unsigned Attributes,
1225    Metadata *Type, StorageType Storage, bool ShouldCreate) {
1226  assert(isCanonical(Name) && "Expected canonical MDString");
1227  assert(isCanonical(GetterName) && "Expected canonical MDString");
1228  assert(isCanonical(SetterName) && "Expected canonical MDString");
1229  DEFINE_GETIMPL_LOOKUP(DIObjCProperty, (Name, File, Line, GetterName,
1230                                         SetterName, Attributes, Type));
1231  Metadata *Ops[] = {Name, File, GetterName, SetterName, Type};
1232  DEFINE_GETIMPL_STORE(DIObjCProperty, (Line, Attributes), Ops);
1233}
1234
1235DIImportedEntity *DIImportedEntity::getImpl(LLVMContext &Context, unsigned Tag,
1236                                            Metadata *Scope, Metadata *Entity,
1237                                            Metadata *File, unsigned Line,
1238                                            MDString *Name, StorageType Storage,
1239                                            bool ShouldCreate) {
1240  assert(isCanonical(Name) && "Expected canonical MDString");
1241  DEFINE_GETIMPL_LOOKUP(DIImportedEntity,
1242                        (Tag, Scope, Entity, File, Line, Name));
1243  Metadata *Ops[] = {Scope, Entity, Name, File};
1244  DEFINE_GETIMPL_STORE(DIImportedEntity, (Tag, Line), Ops);
1245}
1246
1247DIMacro *DIMacro::getImpl(LLVMContext &Context, unsigned MIType,
1248                          unsigned Line, MDString *Name, MDString *Value,
1249                          StorageType Storage, bool ShouldCreate) {
1250  assert(isCanonical(Name) && "Expected canonical MDString");
1251  DEFINE_GETIMPL_LOOKUP(DIMacro, (MIType, Line, Name, Value));
1252  Metadata *Ops[] = { Name, Value };
1253  DEFINE_GETIMPL_STORE(DIMacro, (MIType, Line), Ops);
1254}
1255
1256DIMacroFile *DIMacroFile::getImpl(LLVMContext &Context, unsigned MIType,
1257                                  unsigned Line, Metadata *File,
1258                                  Metadata *Elements, StorageType Storage,
1259                                  bool ShouldCreate) {
1260  DEFINE_GETIMPL_LOOKUP(DIMacroFile,
1261                        (MIType, Line, File, Elements));
1262  Metadata *Ops[] = { File, Elements };
1263  DEFINE_GETIMPL_STORE(DIMacroFile, (MIType, Line), Ops);
1264}
1265