Index: lib/CodeGen/AsmPrinter/DwarfDebug.h =================================================================== --- lib/CodeGen/AsmPrinter/DwarfDebug.h +++ lib/CodeGen/AsmPrinter/DwarfDebug.h @@ -311,6 +311,7 @@ typedef SmallVector, 32> ImportedEntityMap; ImportedEntityMap ScopesWithImportedEntities; + bool IsScopesWithImportedEntitiesSorted; /// Map from MDNodes for user-defined types to the type units that /// describe them. @@ -668,12 +669,7 @@ const MachineFunction *getCurrentFunction() const { return CurFn; } iterator_range - findImportedEntitiesForScope(const MDNode *Scope) const { - return make_range(std::equal_range( - ScopesWithImportedEntities.begin(), ScopesWithImportedEntities.end(), - std::pair(Scope, nullptr), - less_first())); - } + findImportedEntitiesForScope(const MDNode *Scope); /// A helper function to check whether the DIE for a given Scope is /// going to be null. Index: lib/CodeGen/AsmPrinter/DwarfDebug.cpp =================================================================== --- lib/CodeGen/AsmPrinter/DwarfDebug.cpp +++ lib/CodeGen/AsmPrinter/DwarfDebug.cpp @@ -503,11 +503,8 @@ DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode); for (auto *IE : CUNode->getImportedEntities()) ScopesWithImportedEntities.push_back(std::make_pair(IE->getScope(), IE)); - // Stable sort to preserve the order of appearance of imported entities. - // This is to avoid out-of-order processing of interdependent declarations - // within the same scope, e.g. { namespace A = base; namespace B = A; } - std::stable_sort(ScopesWithImportedEntities.begin(), - ScopesWithImportedEntities.end(), less_first()); + IsScopesWithImportedEntitiesSorted = false; + for (auto *GV : CUNode->getGlobalVariables()) CU.getOrCreateGlobalVariableDIE(GV); for (auto *SP : CUNode->getSubprograms()) @@ -554,6 +551,23 @@ } } +iterator_range +DwarfDebug::findImportedEntitiesForScope(const MDNode *Scope) { + // Stable sort to preserve the order of appearance of imported entities. + // This is to avoid out-of-order processing of interdependent declarations + // within the same scope, e.g. { namespace A = base; namespace B = A; } + if (!IsScopesWithImportedEntitiesSorted) { + std::stable_sort(ScopesWithImportedEntities.begin(), + ScopesWithImportedEntities.end(), less_first()); + IsScopesWithImportedEntitiesSorted = true; + } + + return make_range(std::equal_range( + ScopesWithImportedEntities.begin(), ScopesWithImportedEntities.end(), + std::pair(Scope, nullptr), + less_first())); +} + void DwarfDebug::finishSubprogramDefinitions() { for (const auto &P : SPMap) forBothCUs(*P.second, [&](DwarfCompileUnit &CU) {