<commit_before>//===--- CGCXX.cpp - Emit LLVM Code for declarations ----------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This contains code dealing with C++ code generation.
//
//===----------------------------------------------------------------------===//

// We might split this into multiple files if it gets too unwieldy

#include "CodeGenModule.h"
#include "CGCXXABI.h"
#include "CodeGenFunction.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/Mangle.h"
#include "clang/AST/RecordLayout.h"
#include "clang/AST/StmtCXX.h"
#include "clang/Frontend/CodeGenOptions.h"
#include "llvm/ADT/StringExtras.h"
using namespace clang;
using namespace CodeGen;

/// Try to emit a base destructor as an alias to its primary
/// base-class destructor.
bool CodeGenModule::TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D) {
  if (!getCodeGenOpts().CXXCtorDtorAliases)
    return true;

  // Producing an alias to a base class ctor/dtor can degrade debug quality
  // as the debugger cannot tell them apart.
  if (getCodeGenOpts().OptimizationLevel == 0)
    return true;

  // If sanitizing memory to check for use-after-dtor, do not emit as
  //  an alias, unless this class owns no members.
  if (getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
      !D->getParent()->field_empty())
    return true;

  // If the destructor doesn't have a trivial body, we have to emit it
  // separately.
  if (!D->hasTrivialBody())
    return true;

  const CXXRecordDecl *Class = D->getParent();

  // We are going to instrument this destructor, so give up even if it is
  // currently empty.
  if (Class->mayInsertExtraPadding())
    return true;

  // If we need to manipulate a VTT parameter, give up.
  if (Class->getNumVBases()) {
    // Extra Credit:  passing extra parameters is perfectly safe
    // in many calling conventions, so only bail out if the ctor's
    // calling convention is nonstandard.
    return true;
  }

  // If any field has a non-trivial destructor, we have to emit the
  // destructor separately.
  for (const auto *I : Class->fields())
    if (I->getType().isDestructedType())
      return true;

  // Try to find a unique base class with a non-trivial destructor.
  const CXXRecordDecl *UniqueBase = nullptr;
  for (const auto &I : Class->bases()) {

    // We're in the base destructor, so skip virtual bases.
    if (I.isVirtual()) continue;

    // Skip base classes with trivial destructors.
    const auto *Base =
        cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
    if (Base->hasTrivialDestructor()) continue;

    // If we've already found a base class with a non-trivial
    // destructor, give up.
    if (UniqueBase) return true;
    UniqueBase = Base;
  }

  // If we didn't find any bases with a non-trivial destructor, then
  // the base destructor is actually effectively trivial, which can
  // happen if it was needlessly user-defined or if there are virtual
  // bases with non-trivial destructors.
  if (!UniqueBase)
    return true;

  // If the base is at a non-zero offset, give up.
  const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(Class);
  if (!ClassLayout.getBaseClassOffset(UniqueBase).isZero())
    return true;

  // Give up if the calling conventions don't match. We could update the call,
  // but it is probably not worth it.
  const CXXDestructorDecl *BaseD = UniqueBase->getDestructor();
  if (BaseD->getType()->getAs<FunctionType>()->getCallConv() !=
      D->getType()->getAs<FunctionType>()->getCallConv())
    return true;

  return TryEmitDefinitionAsAlias(GlobalDecl(D, Dtor_Base),
                                  GlobalDecl(BaseD, Dtor_Base),
                                  false);
}

/// Try to emit a definition as a global alias for another definition.
/// If \p InEveryTU is true, we know that an equivalent alias can be produced
/// in every translation unit.
bool CodeGenModule::TryEmitDefinitionAsAlias(GlobalDecl AliasDecl,
                                             GlobalDecl TargetDecl,
                                             bool InEveryTU) {
  if (!getCodeGenOpts().CXXCtorDtorAliases)
    return true;

  // The alias will use the linkage of the referent.  If we can't
  // support aliases with that linkage, fail.
  llvm::GlobalValue::LinkageTypes Linkage = getFunctionLinkage(AliasDecl);

  // We can't use an alias if the linkage is not valid for one.
  if (!llvm::GlobalAlias::isValidLinkage(Linkage))
    return true;

  llvm::GlobalValue::LinkageTypes TargetLinkage =
      getFunctionLinkage(TargetDecl);

  // Check if we have it already.
  StringRef MangledName = getMangledName(AliasDecl);
  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  if (Entry && !Entry->isDeclaration())
    return false;
  if (Replacements.count(MangledName))
    return false;

  // Derive the type for the alias.
  llvm::Type *AliasValueType = getTypes().GetFunctionType(AliasDecl);
  llvm::PointerType *AliasType = AliasValueType->getPointerTo();

  // Find the referent.  Some aliases might require a bitcast, in
  // which case the caller is responsible for ensuring the soundness
  // of these semantics.
  auto *Ref = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));
  llvm::Constant *Aliasee = Ref;
  if (Ref->getType() != AliasType)
    Aliasee = llvm::ConstantExpr::getBitCast(Ref, AliasType);

  // Instead of creating as alias to a linkonce_odr, replace all of the uses
  // of the aliasee.
  if (llvm::GlobalValue::isDiscardableIfUnused(Linkage) &&
     (TargetLinkage != llvm::GlobalValue::AvailableExternallyLinkage ||
      !TargetDecl.getDecl()->hasAttr<AlwaysInlineAttr>())) {
    // FIXME: An extern template instantiation will create functions with
    // linkage "AvailableExternally". In libc++, some classes also define
    // members with attribute "AlwaysInline" and expect no reference to
    // be generated. It is desirable to reenable this optimisation after
    // corresponding LLVM changes.
    Replacements[MangledName] = Aliasee;
    return false;
  }

  // If we have a weak, non-discardable alias (weak, weak_odr), like an extern
  // template instantiation or a dllexported class, avoid forming it on COFF.
  // A COFF weak external alias cannot satisfy a normal undefined symbol
  // reference from another TU. The other TU must also mark the referenced
  // symbol as weak, which we cannot rely on.
  if (llvm::GlobalValue::isWeakForLinker(Linkage) &&
      getTriple().isOSBinFormatCOFF()) {
    return true;
  }

  if (!InEveryTU) {
    // If we don't have a definition for the destructor yet, don't
    // emit.  We can't emit aliases to declarations; that's just not
    // how aliases work.
    if (Ref->isDeclaration())
      return true;
  }

  // Don't create an alias to a linker weak symbol. This avoids producing
  // different COMDATs in different TUs. Another option would be to
  // output the alias both for weak_odr and linkonce_odr, but that
  // requires explicit comdat support in the IL.
  if (llvm::GlobalValue::isWeakForLinker(TargetLinkage))
    return true;

  // Create the alias with no name.
  auto *Alias = llvm::GlobalAlias::create(AliasValueType, 0, Linkage, "",
                                          Aliasee, &getModule());

  // Switch any previous uses to the alias.
  if (Entry) {
    assert(Entry->getType() == AliasType &&
           "declaration exists with different type");
    Alias->takeName(Entry);
    Entry->replaceAllUsesWith(Alias);
    Entry->eraseFromParent();
  } else {
    Alias->setName(MangledName);
  }

  // Finally, set up the alias with its proper name and attributes.
  setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);

  return false;
}

llvm::Function *CodeGenModule::codegenCXXStructor(const CXXMethodDecl *MD,
                                                  StructorType Type) {
  const CGFunctionInfo &FnInfo =
      getTypes().arrangeCXXStructorDeclaration(MD, Type);
  auto *Fn = cast<llvm::Function>(
      getAddrOfCXXStructor(MD, Type, &FnInfo, /*FnType=*/nullptr,
                           /*DontDefer=*/true, /*IsForDefinition=*/true));

  GlobalDecl GD;
  if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
    GD = GlobalDecl(DD, toCXXDtorType(Type));
  } else {
    const auto *CD = cast<CXXConstructorDecl>(MD);
    GD = GlobalDecl(CD, toCXXCtorType(Type));
  }

  setFunctionLinkage(GD, Fn);
  setFunctionDLLStorageClass(GD, Fn);

  CodeGenFunction(*this).GenerateCode(GD, Fn, FnInfo);
  setFunctionDefinitionAttributes(MD, Fn);
  SetLLVMFunctionAttributesForDefinition(MD, Fn);
  return Fn;
}

llvm::Constant *CodeGenModule::getAddrOfCXXStructor(
    const CXXMethodDecl *MD, StructorType Type, const CGFunctionInfo *FnInfo,
    llvm::FunctionType *FnType, bool DontDefer, bool IsForDefinition) {
  GlobalDecl GD;
  if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
    GD = GlobalDecl(CD, toCXXCtorType(Type));
  } else {
    GD = GlobalDecl(cast<CXXDestructorDecl>(MD), toCXXDtorType(Type));
  }

  if (!FnType) {
    if (!FnInfo)
      FnInfo = &getTypes().arrangeCXXStructorDeclaration(MD, Type);
    FnType = getTypes().GetFunctionType(*FnInfo);
  }

  return GetOrCreateLLVMFunction(
      getMangledName(GD), FnType, GD, /*ForVTable=*/false, DontDefer,
      /*isThunk=*/false, /*ExtraAttrs=*/llvm::AttributeSet(), IsForDefinition);
}

static llvm::Value *BuildAppleKextVirtualCall(CodeGenFunction &CGF,
                                              GlobalDecl GD,
                                              llvm::Type *Ty,
                                              const CXXRecordDecl *RD) {
  assert(!CGF.CGM.getTarget().getCXXABI().isMicrosoft() &&
         "No kext in Microsoft ABI");
  GD = GD.getCanonicalDecl();
  CodeGenModule &CGM = CGF.CGM;
  llvm::Value *VTable = CGM.getCXXABI().getAddrOfVTable(RD, CharUnits());
  Ty = Ty->getPointerTo()->getPointerTo();
  VTable = CGF.Builder.CreateBitCast(VTable, Ty);
  assert(VTable && "BuildVirtualCall = kext vtbl pointer is null");
  uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
  uint64_t AddressPoint =
    CGM.getItaniumVTableContext().getVTableLayout(RD)
       .getAddressPoint(BaseSubobject(RD, CharUnits::Zero()));
  VTableIndex += AddressPoint;
  llvm::Value *VFuncPtr =
    CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfnkxt");
  return CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.PointerAlignInBytes);
}

/// BuildAppleKextVirtualCall - This routine is to support gcc's kext ABI making
/// indirect call to virtual functions. It makes the call through indexing
/// into the vtable.
llvm::Value *
CodeGenFunction::BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
                                  NestedNameSpecifier *Qual,
                                  llvm::Type *Ty) {
  assert((Qual->getKind() == NestedNameSpecifier::TypeSpec) &&
         "BuildAppleKextVirtualCall - bad Qual kind");

  const Type *QTy = Qual->getAsType();
  QualType T = QualType(QTy, 0);
  const RecordType *RT = T->getAs<RecordType>();
  assert(RT && "BuildAppleKextVirtualCall - Qual type must be record");
  const auto *RD = cast<CXXRecordDecl>(RT->getDecl());

  if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD))
    return BuildAppleKextVirtualDestructorCall(DD, Dtor_Complete, RD);

  return ::BuildAppleKextVirtualCall(*this, MD, Ty, RD);
}

/// BuildVirtualCall - This routine makes indirect vtable call for
/// call to virtual destructors. It returns 0 if it could not do it.
llvm::Value *
CodeGenFunction::BuildAppleKextVirtualDestructorCall(
                                            const CXXDestructorDecl *DD,
                                            CXXDtorType Type,
                                            const CXXRecordDecl *RD) {
  const auto *MD = cast<CXXMethodDecl>(DD);
  // FIXME. Dtor_Base dtor is always direct!!
  // It need be somehow inline expanded into the caller.
  // -O does that. But need to support -O0 as well.
  if (MD->isVirtual() && Type != Dtor_Base) {
    // Compute the function type we're calling.
    const CGFunctionInfo &FInfo = CGM.getTypes().arrangeCXXStructorDeclaration(
        DD, StructorType::Complete);
    llvm::Type *Ty = CGM.getTypes().GetFunctionType(FInfo);
    return ::BuildAppleKextVirtualCall(*this, GlobalDecl(DD, Type), Ty, RD);
  }
  return nullptr;
}
<commit_msg>Use CodeGenModule::addReplacement() instead of directly accessing Replacements[]. This helps when trying to debug who inserted into Replacements.<commit_after>//===--- CGCXX.cpp - Emit LLVM Code for declarations ----------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This contains code dealing with C++ code generation.
//
//===----------------------------------------------------------------------===//

// We might split this into multiple files if it gets too unwieldy

#include "CodeGenModule.h"
#include "CGCXXABI.h"
#include "CodeGenFunction.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/Mangle.h"
#include "clang/AST/RecordLayout.h"
#include "clang/AST/StmtCXX.h"
#include "clang/Frontend/CodeGenOptions.h"
#include "llvm/ADT/StringExtras.h"
using namespace clang;
using namespace CodeGen;

/// Try to emit a base destructor as an alias to its primary
/// base-class destructor.
bool CodeGenModule::TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D) {
  if (!getCodeGenOpts().CXXCtorDtorAliases)
    return true;

  // Producing an alias to a base class ctor/dtor can degrade debug quality
  // as the debugger cannot tell them apart.
  if (getCodeGenOpts().OptimizationLevel == 0)
    return true;

  // If sanitizing memory to check for use-after-dtor, do not emit as
  //  an alias, unless this class owns no members.
  if (getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
      !D->getParent()->field_empty())
    return true;

  // If the destructor doesn't have a trivial body, we have to emit it
  // separately.
  if (!D->hasTrivialBody())
    return true;

  const CXXRecordDecl *Class = D->getParent();

  // We are going to instrument this destructor, so give up even if it is
  // currently empty.
  if (Class->mayInsertExtraPadding())
    return true;

  // If we need to manipulate a VTT parameter, give up.
  if (Class->getNumVBases()) {
    // Extra Credit:  passing extra parameters is perfectly safe
    // in many calling conventions, so only bail out if the ctor's
    // calling convention is nonstandard.
    return true;
  }

  // If any field has a non-trivial destructor, we have to emit the
  // destructor separately.
  for (const auto *I : Class->fields())
    if (I->getType().isDestructedType())
      return true;

  // Try to find a unique base class with a non-trivial destructor.
  const CXXRecordDecl *UniqueBase = nullptr;
  for (const auto &I : Class->bases()) {

    // We're in the base destructor, so skip virtual bases.
    if (I.isVirtual()) continue;

    // Skip base classes with trivial destructors.
    const auto *Base =
        cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
    if (Base->hasTrivialDestructor()) continue;

    // If we've already found a base class with a non-trivial
    // destructor, give up.
    if (UniqueBase) return true;
    UniqueBase = Base;
  }

  // If we didn't find any bases with a non-trivial destructor, then
  // the base destructor is actually effectively trivial, which can
  // happen if it was needlessly user-defined or if there are virtual
  // bases with non-trivial destructors.
  if (!UniqueBase)
    return true;

  // If the base is at a non-zero offset, give up.
  const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(Class);
  if (!ClassLayout.getBaseClassOffset(UniqueBase).isZero())
    return true;

  // Give up if the calling conventions don't match. We could update the call,
  // but it is probably not worth it.
  const CXXDestructorDecl *BaseD = UniqueBase->getDestructor();
  if (BaseD->getType()->getAs<FunctionType>()->getCallConv() !=
      D->getType()->getAs<FunctionType>()->getCallConv())
    return true;

  return TryEmitDefinitionAsAlias(GlobalDecl(D, Dtor_Base),
                                  GlobalDecl(BaseD, Dtor_Base),
                                  false);
}

/// Try to emit a definition as a global alias for another definition.
/// If \p InEveryTU is true, we know that an equivalent alias can be produced
/// in every translation unit.
bool CodeGenModule::TryEmitDefinitionAsAlias(GlobalDecl AliasDecl,
                                             GlobalDecl TargetDecl,
                                             bool InEveryTU) {
  if (!getCodeGenOpts().CXXCtorDtorAliases)
    return true;

  // The alias will use the linkage of the referent.  If we can't
  // support aliases with that linkage, fail.
  llvm::GlobalValue::LinkageTypes Linkage = getFunctionLinkage(AliasDecl);

  // We can't use an alias if the linkage is not valid for one.
  if (!llvm::GlobalAlias::isValidLinkage(Linkage))
    return true;

  llvm::GlobalValue::LinkageTypes TargetLinkage =
      getFunctionLinkage(TargetDecl);

  // Check if we have it already.
  StringRef MangledName = getMangledName(AliasDecl);
  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  if (Entry && !Entry->isDeclaration())
    return false;
  if (Replacements.count(MangledName))
    return false;

  // Derive the type for the alias.
  llvm::Type *AliasValueType = getTypes().GetFunctionType(AliasDecl);
  llvm::PointerType *AliasType = AliasValueType->getPointerTo();

  // Find the referent.  Some aliases might require a bitcast, in
  // which case the caller is responsible for ensuring the soundness
  // of these semantics.
  auto *Ref = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));
  llvm::Constant *Aliasee = Ref;
  if (Ref->getType() != AliasType)
    Aliasee = llvm::ConstantExpr::getBitCast(Ref, AliasType);

  // Instead of creating as alias to a linkonce_odr, replace all of the uses
  // of the aliasee.
  if (llvm::GlobalValue::isDiscardableIfUnused(Linkage) &&
     (TargetLinkage != llvm::GlobalValue::AvailableExternallyLinkage ||
      !TargetDecl.getDecl()->hasAttr<AlwaysInlineAttr>())) {
    // FIXME: An extern template instantiation will create functions with
    // linkage "AvailableExternally". In libc++, some classes also define
    // members with attribute "AlwaysInline" and expect no reference to
    // be generated. It is desirable to reenable this optimisation after
    // corresponding LLVM changes.
    addReplacement(MangledName, Aliasee);
    return false;
  }

  // If we have a weak, non-discardable alias (weak, weak_odr), like an extern
  // template instantiation or a dllexported class, avoid forming it on COFF.
  // A COFF weak external alias cannot satisfy a normal undefined symbol
  // reference from another TU. The other TU must also mark the referenced
  // symbol as weak, which we cannot rely on.
  if (llvm::GlobalValue::isWeakForLinker(Linkage) &&
      getTriple().isOSBinFormatCOFF()) {
    return true;
  }

  if (!InEveryTU) {
    // If we don't have a definition for the destructor yet, don't
    // emit.  We can't emit aliases to declarations; that's just not
    // how aliases work.
    if (Ref->isDeclaration())
      return true;
  }

  // Don't create an alias to a linker weak symbol. This avoids producing
  // different COMDATs in different TUs. Another option would be to
  // output the alias both for weak_odr and linkonce_odr, but that
  // requires explicit comdat support in the IL.
  if (llvm::GlobalValue::isWeakForLinker(TargetLinkage))
    return true;

  // Create the alias with no name.
  auto *Alias = llvm::GlobalAlias::create(AliasValueType, 0, Linkage, "",
                                          Aliasee, &getModule());

  // Switch any previous uses to the alias.
  if (Entry) {
    assert(Entry->getType() == AliasType &&
           "declaration exists with different type");
    Alias->takeName(Entry);
    Entry->replaceAllUsesWith(Alias);
    Entry->eraseFromParent();
  } else {
    Alias->setName(MangledName);
  }

  // Finally, set up the alias with its proper name and attributes.
  setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);

  return false;
}

llvm::Function *CodeGenModule::codegenCXXStructor(const CXXMethodDecl *MD,
                                                  StructorType Type) {
  const CGFunctionInfo &FnInfo =
      getTypes().arrangeCXXStructorDeclaration(MD, Type);
  auto *Fn = cast<llvm::Function>(
      getAddrOfCXXStructor(MD, Type, &FnInfo, /*FnType=*/nullptr,
                           /*DontDefer=*/true, /*IsForDefinition=*/true));

  GlobalDecl GD;
  if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
    GD = GlobalDecl(DD, toCXXDtorType(Type));
  } else {
    const auto *CD = cast<CXXConstructorDecl>(MD);
    GD = GlobalDecl(CD, toCXXCtorType(Type));
  }

  setFunctionLinkage(GD, Fn);
  setFunctionDLLStorageClass(GD, Fn);

  CodeGenFunction(*this).GenerateCode(GD, Fn, FnInfo);
  setFunctionDefinitionAttributes(MD, Fn);
  SetLLVMFunctionAttributesForDefinition(MD, Fn);
  return Fn;
}

llvm::Constant *CodeGenModule::getAddrOfCXXStructor(
    const CXXMethodDecl *MD, StructorType Type, const CGFunctionInfo *FnInfo,
    llvm::FunctionType *FnType, bool DontDefer, bool IsForDefinition) {
  GlobalDecl GD;
  if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
    GD = GlobalDecl(CD, toCXXCtorType(Type));
  } else {
    GD = GlobalDecl(cast<CXXDestructorDecl>(MD), toCXXDtorType(Type));
  }

  if (!FnType) {
    if (!FnInfo)
      FnInfo = &getTypes().arrangeCXXStructorDeclaration(MD, Type);
    FnType = getTypes().GetFunctionType(*FnInfo);
  }

  return GetOrCreateLLVMFunction(
      getMangledName(GD), FnType, GD, /*ForVTable=*/false, DontDefer,
      /*isThunk=*/false, /*ExtraAttrs=*/llvm::AttributeSet(), IsForDefinition);
}

static llvm::Value *BuildAppleKextVirtualCall(CodeGenFunction &CGF,
                                              GlobalDecl GD,
                                              llvm::Type *Ty,
                                              const CXXRecordDecl *RD) {
  assert(!CGF.CGM.getTarget().getCXXABI().isMicrosoft() &&
         "No kext in Microsoft ABI");
  GD = GD.getCanonicalDecl();
  CodeGenModule &CGM = CGF.CGM;
  llvm::Value *VTable = CGM.getCXXABI().getAddrOfVTable(RD, CharUnits());
  Ty = Ty->getPointerTo()->getPointerTo();
  VTable = CGF.Builder.CreateBitCast(VTable, Ty);
  assert(VTable && "BuildVirtualCall = kext vtbl pointer is null");
  uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
  uint64_t AddressPoint =
    CGM.getItaniumVTableContext().getVTableLayout(RD)
       .getAddressPoint(BaseSubobject(RD, CharUnits::Zero()));
  VTableIndex += AddressPoint;
  llvm::Value *VFuncPtr =
    CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfnkxt");
  return CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.PointerAlignInBytes);
}

/// BuildAppleKextVirtualCall - This routine is to support gcc's kext ABI making
/// indirect call to virtual functions. It makes the call through indexing
/// into the vtable.
llvm::Value *
CodeGenFunction::BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
                                  NestedNameSpecifier *Qual,
                                  llvm::Type *Ty) {
  assert((Qual->getKind() == NestedNameSpecifier::TypeSpec) &&
         "BuildAppleKextVirtualCall - bad Qual kind");

  const Type *QTy = Qual->getAsType();
  QualType T = QualType(QTy, 0);
  const RecordType *RT = T->getAs<RecordType>();
  assert(RT && "BuildAppleKextVirtualCall - Qual type must be record");
  const auto *RD = cast<CXXRecordDecl>(RT->getDecl());

  if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD))
    return BuildAppleKextVirtualDestructorCall(DD, Dtor_Complete, RD);

  return ::BuildAppleKextVirtualCall(*this, MD, Ty, RD);
}

/// BuildVirtualCall - This routine makes indirect vtable call for
/// call to virtual destructors. It returns 0 if it could not do it.
llvm::Value *
CodeGenFunction::BuildAppleKextVirtualDestructorCall(
                                            const CXXDestructorDecl *DD,
                                            CXXDtorType Type,
                                            const CXXRecordDecl *RD) {
  const auto *MD = cast<CXXMethodDecl>(DD);
  // FIXME. Dtor_Base dtor is always direct!!
  // It need be somehow inline expanded into the caller.
  // -O does that. But need to support -O0 as well.
  if (MD->isVirtual() && Type != Dtor_Base) {
    // Compute the function type we're calling.
    const CGFunctionInfo &FInfo = CGM.getTypes().arrangeCXXStructorDeclaration(
        DD, StructorType::Complete);
    llvm::Type *Ty = CGM.getTypes().GetFunctionType(FInfo);
    return ::BuildAppleKextVirtualCall(*this, GlobalDecl(DD, Type), Ty, RD);
  }
  return nullptr;
}
<|endoftext|>


<commit_before>// -*- compile-command: "c++ -std=c++11 parse.cpp -o parse" -*-

#include <iostream>
#include "parse.hpp"

#include <sstream>

#include <set>
#include <memory>

namespace impl {
  template<std::size_t start, class ... T>
  struct select;

  template<std::size_t start, class H, class ... T>
  struct select<start, H, T...> : select<start + 1, T...> {

    using select<start + 1, T...>::index;
    static constexpr std::size_t index(const H& ) { return start; }

    using select<start + 1, T...>::cast;
    static const H& cast(const H& value) { return value; }
    static H&& cast(H&& value) { return std::move(value); }

  };

  template<std::size_t start> struct select<start> {
    static void index();
    static void cast();
  };
}

template<class ... T>
class variant {
  std::size_t index;
  using storage_type = typename std::aligned_union<0, T...>::type;
  storage_type storage;

  using select_type = impl::select<0, T...>;

  template<class U, class Variant, class Visitor, class ... Args>
  static void apply_thunk(Variant& self, Visitor&& visitor, Args&& ... args) {
    std::forward<Visitor>(visitor)(self.template get<U>(), std::forward<Args>(args)...);
  }

  template<class U>
  void construct(U&& value) {
    new (&storage) typename std::decay<U>::type(std::forward<U>(value));
  }

  struct copy {
    template<class U>
    void operator()(U& self, const variant& other) const {
      new (&self) U(other.template get<U>());
    }
  };

  struct move {
    template<class U>
    void operator()(U& self, variant&& other) const {
      new (&self) U(std::move(other.template get<U>()));
    }
  };

  struct destruct {
    template<class U>
    void operator()(U& self) const {
      self.~U();
    }
  };

public:

  template<class U>
  U& get() {
    U& res = reinterpret_cast<U&>(storage);
    if( select_type::index(res) != index ) throw std::runtime_error("bad cast");
    return res;
  }

  template<class U>
  const U& get() const {
    const U& res = reinterpret_cast<const U&>(storage);
    if( select_type::index(res) != index ) throw std::runtime_error("bad cast");
    return res;
  }

  template<class U>
  variant(U&& value)
    : index( select_type::index(value) ) {
    construct( select_type::cast(value) );
  }

  variant(const variant& other)
    : index(other.index) {
    apply( copy(), other );
  }

  variant(variant&& other)
    : index(other.index) {
    apply( move(), std::move(other) );
  }

  ~variant() {
    apply( destruct() );
  }

  template<class Visitor, class ... Args>
  void apply(Visitor&& visitor, Args&& ... args) {
    using thunk_type = void (*)(variant& self, Visitor&& visitor, Args&& ... args);

    static constexpr thunk_type thunk[] = {
      apply_thunk<T, variant, Visitor, Args...>...
    };

    thunk[index](*this, std::forward<Visitor>(visitor), std::forward<Args>(args)...);
  }

  template<class Visitor, class ... Args>
  void apply(Visitor&& visitor, Args&& ... args) const {
    using thunk_type = void (*)(const variant& self, Visitor&& visitor, Args&& ... args);

    static constexpr thunk_type thunk[] = {
      apply_thunk<T, const variant, Visitor, Args...>...
    };

    thunk[index](*this, std::forward<Visitor>(visitor), std::forward<Args>(args)...);
  }

};

class symbol {
  using table_type = std::set<std::string>;
  static table_type table;

  using iterator_type = table_type::iterator;
  iterator_type iterator;
public:

  symbol(const std::string& value) : iterator(table.insert(value).first) { }

};

int test() {

  struct cell;
  using list = std::shared_ptr<cell>;

  using string = std::string;
  using value = variant<long, double, symbol, string, list >;

  struct cell {
    value head;
    list tail = 0;
  };

  value x = 1.0f;

}

int main(int, char** ) {

  using namespace parse;

  auto alpha = chr<std::isalpha>();
  auto alnum = chr<std::isalnum>();
  auto space = chr<std::isspace>();

  auto endl = chr('\n');
  auto comment = (chr(';'), *!endl, endl);

  auto real = lit<double>();
  auto integer = lit<int>();

  auto dquote = chr('"');

  // TODO escaped strings
  auto string = tos( no_skip( (dquote,
                               *!dquote,
                               dquote)) );

  auto symbol = tos( no_skip( (alpha, *alnum) ) );

  auto atom = symbol | string | real | integer;

  struct expr_tag;
  any<expr_tag> expr;

  auto list = no_skip( (chr('('),
                        *space,
                        ~( expr, *(+space, expr) ),
                        *space,
                        chr(')' )) );

  expr = atom | list;

  auto parser = expr;

  while(std::cin) {
	std::string line;

    std::cout << "> ";
	std::getline(std::cin, line);

	std::stringstream ss(line);
	if(ss >> parser) {
	  std::cout << "parse succeded" << std::endl;
	} else if(!std::cin.eof()) {
	  std::cerr << "parse error" << std::endl;
	}
  }

}

<commit_msg>monadic parsers<commit_after>// -*- compile-command: "c++ -std=c++11 parse.cpp -o parse" -*-

#include <iostream>
#include "parse.hpp"

#include <sstream>

#include <set>
#include <memory>
#include <vector>

namespace impl {
  template<std::size_t start, class ... T>
  struct select;

  template<std::size_t start, class H, class ... T>
  struct select<start, H, T...> : select<start + 1, T...> {

    using select<start + 1, T...>::index;
    static constexpr std::size_t index(const H& ) { return start; }

    using select<start + 1, T...>::cast;
    static const H& cast(const H& value) { return value; }
    static H&& cast(H&& value) { return std::move(value); }

  };

  template<std::size_t start> struct select<start> {
    static void index();
    static void cast();
  };
}

template<class ... T>
class variant {

  using storage_type = typename std::aligned_union<0, T...>::type;
  storage_type storage;

  using index_type = std::size_t;
  index_type index;

  using select_type = impl::select<0, T...>;

  template<class U, class Variant, class Visitor, class ... Args>
  static void apply_thunk(Variant& self, Visitor&& visitor, Args&& ... args) {
    std::forward<Visitor>(visitor)(self.template get<U>(), std::forward<Args>(args)...);
  }

  template<class U>
  void construct(U&& value) {
    new (&storage) typename std::decay<U>::type(std::forward<U>(value));
  }

  struct copy_construct {
    template<class U>
    void operator()(U& self, const variant& other) const {
      new (&self) U(other.template get<U>());
    }
  };

  struct copy {
    template<class U>
    void operator()(U& self, const variant& other) const {
      self = other.template get<U>();
    }
  };

  struct move {
    template<class U>
    void operator()(U& self, variant&& other) const {
      self = std::move(other.template get<U>());
    }
  };

  struct move_construct {
    template<class U>
    void operator()(U& self, variant&& other) const {
      new (&self) U(std::move(other.template get<U>()));
    }
  };

  struct destruct {
    template<class U>
    void operator()(U& self) const {
      self.~U();
    }
  };

public:
  std::size_t type() const { return index; }

  template<class U>
  U& get() {
    U& res = reinterpret_cast<U&>(storage);
    if( select_type::index(res) != index ) throw std::runtime_error("bad cast");
    return res;
  }

  template<class U>
  const U& get() const {
    const U& res = reinterpret_cast<const U&>(storage);
    if( select_type::index(res) != index ) throw std::runtime_error("bad cast");
    return res;
  }

  variant(const variant& other)
    : index(other.index) {
    apply( copy_construct(), other );
  }

  variant(variant&& other)
    : index(other.index) {
    apply( move_construct(), std::move(other) );
  }

  ~variant() {
    apply( destruct() );
  }

  variant& operator=(const variant& other) {
    if(type() == other.type()) {
      apply( copy(), other );
    } else {
      apply( destruct() );
      apply( copy_construct(), other );
    }

    return *this;
  }

  variant& operator=(variant&& other) {
    if(type() == other.type()) {
      apply( move(), std::move(other) );
    } else {
      apply( destruct() );
      apply( move_construct(), std::move(other) );
    }

    return *this;
  }

  // TODO move constructors from values ?
  template<class U>
  variant(const U& value)
    : index( select_type::index(value) ) {
    construct( select_type::cast(value) );
  }

  template<class Visitor, class ... Args>
  void apply(Visitor&& visitor, Args&& ... args) {
    using thunk_type = void (*)(variant& self, Visitor&& visitor, Args&& ... args);

    static constexpr thunk_type thunk[] = {
      apply_thunk<T, variant, Visitor, Args...>...
    };

    thunk[index](*this, std::forward<Visitor>(visitor), std::forward<Args>(args)...);
  }

  template<class Visitor, class ... Args>
  void apply(Visitor&& visitor, Args&& ... args) const {
    using thunk_type = void (*)(const variant& self, Visitor&& visitor, Args&& ... args);

    static constexpr thunk_type thunk[] = {
      apply_thunk<T, const variant, Visitor, Args...>...
    };

    thunk[index](*this, std::forward<Visitor>(visitor), std::forward<Args>(args)...);
  }

};

struct none { };

template<class T>
struct maybe : public variant<none, T> {
  using variant<none, T>::variant;

  explicit operator bool() const {
    return this->type();
  }

};

namespace monad {

  // monadic return
  template<class T>
  struct result_type {
    using value_type = T;

    const value_type value;

    maybe<value_type> operator()(std::istream& in) const {
      return value;
    }

  };

  template<class T>
  static result_type<T> result(T value) { return {value}; }

  // lazy result
  template<class F>
  struct lazy_type {
    using value_type = typename std::result_of< F(void) >::type;

    const F f;

    maybe<value_type> operator()(std::istream& in) const {
      return f();
    }

  };

  template<class F>
  static lazy_type<F> lazy(F f) { return {f}; }

  // monadic zero
  template<class T>
  struct fail_type {
    using value_type = T;

    maybe<value_type> operator()(std::istream& in) const {
      return none();
    }

  };

  // sequencing with binding
  template<class Parser, class F>
  struct bind_type {
    const Parser parser;
    const F f;

    using source_type = typename Parser::value_type;

    using result_type = typename std::result_of< F(source_type) >::type;
    using value_type = typename result_type::value_type;

    maybe<value_type> operator()(std::istream& in) const {
      parse::point pos(in);

      maybe<source_type> value = parser(in);

      if(!value) return none();

      const maybe<value_type> res = f( std::move(value.template get<source_type>() ) )(in);
      if(res) return res;

      // backtrack
      pos.reset(in);
      // in.setstate(std::ios::failbit);
      return none();
    }

  };

  template<class Parser, class F>
  static bind_type<Parser, F> bind(Parser parser, F f) {
    return {parser, f};
  }

  template<class Parser, class F>
  static bind_type<Parser, F> operator>>(Parser parser, F f) {
    return {parser, f};
  }

  // sequencing without binding (last parser result is returned)
  template<class Parser>
  struct then_type {
    const Parser parser;

    template<class U>
    Parser operator()(const U& ) const {
      return parser;
    }

  };

  template<class Parser>
  static then_type<Parser> then(Parser parser) {
    return {parser};
  }

  template<class LHS, class RHS>
  static bind_type<LHS, then_type<RHS> > operator,(LHS lhs, RHS rhs) {
    return lhs >> then(rhs);
  }

  // alternatives
  template<class LHS, class RHS>
  struct alt_type {
    const LHS lhs;
    const RHS rhs;

    static_assert( std::is_same< typename LHS::value_type, typename RHS::value_type>::value );

    using value_type = typename LHS::value_type;

    maybe<value_type> operator()(std::istream& in) const {
      const maybe<value_type> left = lhs(in);
      if(left) return left;
      return rhs(in);
    }

  };

  template<class LHS, class RHS>
  static alt_type<LHS, RHS> alt(LHS lhs, RHS rhs) {
    return {lhs, rhs};
  }

  template<class LHS, class RHS>
  static alt_type<LHS, RHS> operator|(LHS lhs, RHS rhs) {
    return {lhs, rhs};
  }

  template<class Parser>
  struct kleene_type {
    const Parser parser;

    using source_type = typename Parser::value_type;
    using value_type = std::vector< source_type >;

    maybe<value_type> operator()(std::istream& in) const {
      value_type res;

      while( maybe<source_type> x = parser(in) ) {
        res.push_back(x.template get<source_type>() );
      }

      return res;
    }

  };

  template<class Parser>
  static kleene_type<Parser> kleene(Parser parser) {
    return {parser};
  }

  template<class Parser>
  static kleene_type<Parser> operator*(Parser parser) {
    return {parser};
  }

  template<class Pred>
  struct character {
	const Pred pred;

	struct negate {
	  const Pred pred;

	  bool operator()(char c) const {
		return !pred(c);
	  }

	};

	character<negate> operator!() const {
	  return {pred};
	}

    using value_type = char;

    maybe<value_type> operator()(std::istream& in) const {
      char c;
      if(in >> c) {
        if( pred(c) ) return c;
        in.putback(c);
        // in.setstate(std::ios::failbit);
      }

      return none();
    }

  };

  struct equals {
	const char expected;

	bool operator()(char c) const {
      // std::clog << "got: '" << c << "', expecting: '" << expected << "'" << std::endl;
	  return c == expected;
	}
  };

  static character<equals> chr(char c) { return {{c}}; }

  template<int (*pred)(int) > struct adaptor {
    bool operator()(char c) const { return pred(c); }
  };

  template<int (*pred)(int)> static character<adaptor<pred>> chr() { return {}; }

  // literal
  template<class T>
  struct lit {

    using value_type = T;

    maybe<value_type> operator()(std::istream& in) const {
      parse::point pos(in);

      value_type value;
      if( in >> value ) {
        return value;
      }

      pos.reset(in);
      // in.setstate(std::ios::failbit);
      return none();
    }

  };

  template<class Parser>
  struct no_skip_type {
    const Parser parser;

    using value_type = typename Parser::value_type;

    maybe<value_type> operator()(std::istream& in) const {
      if(in.flags() & std::ios::skipws) {
        in >> std::noskipws;

        const maybe<value_type> res = parser(in);

        in >> std::skipws;
        return res;
      } else {
        return parser(in);
      }
    }

  };

  template<class Parser>
  static no_skip_type< Parser > no_skip(Parser parser) {
	return {parser};
  }

  template<class T>
  struct any : std::function< maybe<T>(std::istream& in) > {
    using std::function< maybe<T>(std::istream&) >::function;

    using value_type = T;

  };

  template<class Parser>
  struct ref_type {
    const Parser& parser;

    using value_type = typename Parser::value_type;

    maybe<value_type> operator()(std::istream& in) const {
      return parser(in);
    }

  };

  template<class Parser>
  static ref_type<Parser> ref(const Parser& parser) { return { parser }; }

  template<class Parser>
  static ref_type<Parser> operator&(const Parser& parser) { return { parser }; }

  template<class T>
  struct cast {

    template<class U>
    result_type<T> operator()(U u) const {
      return result<T>(u);
    }

  };

  template<class Parser>
  struct plus_type {
    const Parser parser;

    using source_type = typename Parser::value_type;
    using value_type = typename kleene_type<Parser>::value_type;

    maybe<value_type> operator()(std::istream& in) const {

      const auto impl = parser >> [&](source_type&& first) {
        return *parser >> [first](value_type&& value) {
          value.emplace(value.begin(), std::move(first));
          return result(value);
        };
      };

      return impl(in);
    }

  };

  template<class Parser>
  static plus_type<Parser> plus(Parser parser) { return {parser}; }

  template<class Parser>
  static plus_type<Parser> operator+(Parser parser) { return {parser}; }

  template<class Parser, class Separator>
  struct list_type {
    const Parser parser;
    const Separator separator;

    using source_type = typename Parser::value_type;
    using value_type = typename kleene_type<Parser>::value_type;

    maybe<value_type> operator()(std::istream& in) const {

      const auto impl = parser >> [&](source_type first) {
        return *(separator, parser) >> [first](value_type&& value) {
          value.emplace(value.begin(), std::move(first));
          return result(value);
        };
        } | result( value_type() );

      return impl(in);
    }
  };

  template<class Parser, class Separator>
  static list_type<Parser, Separator> list(Parser parser, Separator separator) {
    return {parser, separator};
  }

  template<class Parser, class Separator>
  static list_type<Parser, Separator> operator%(Parser parser, Separator separator) {
    return {parser, separator};
  }

}

class symbol {
  using table_type = std::set<std::string>;
  static table_type table;

  using iterator_type = table_type::iterator;
  iterator_type iterator;
public:

  symbol(const std::string& value)
    : iterator(table.insert(value).first) { }

};

int test() {

  struct cell;
  using list = std::shared_ptr<cell>;

  using string = std::string;
  using value = variant<long, double, symbol, string, list >;

  struct cell {
    value head;
    list tail = 0;
  };

  value x = 1.0f;

}

template<class F>
static void repl(const F& f) {

  while(std::cin) {
	std::string line;

    std::cout << "> ";
	std::getline(std::cin, line);

	std::stringstream ss(line);

	if( f(ss) ) {
	  std::cout << "parse succeded" << std::endl;
	} else if(!std::cin.eof()) {
	  std::cerr << "parse error" << std::endl;
	}

  }

};

using string = std::string;
struct value;

struct value : variant<long, double, symbol, std::vector<value> > {
  using value::variant::variant;
};

int main(int, char** ) {

  {
    using namespace monad;

    auto alpha = chr<std::isalpha>();
    auto alnum = chr<std::isalnum>();
    auto space = chr<std::isspace>();

    auto endl = chr('\n');
    auto comment = (chr(';'), *!endl, endl);

    auto real = lit<double>();
    auto integer = lit<long>();
    auto dquote = chr('"');

    // auto symbol = no_skip( alpha >> *alnum) ) );

    auto string = no_skip( (dquote,
                            (*!dquote) >> [dquote](std::vector<char>&& value) {
                              return dquote, result(std::move(value));
                            }));

    auto atom = real >> cast<value>() | integer >> cast<value>();

    any<value> expr;

    auto list = no_skip( (chr('('), *space, (&expr % +space) >> [space](std::vector<value>&& x) {
          return *space, chr(')'), result(x);
        }) );

    expr = atom | list >> cast<value>();

    auto parser = list;

    repl([&](std::istream& in) {
        return bool(parser(in));
      });

    return 0;
  }

  using namespace parse;

  auto alpha = chr<std::isalpha>();
  auto alnum = chr<std::isalnum>();
  auto space = chr<std::isspace>();

  auto endl = chr('\n');
  auto comment = (chr(';'), *!endl, endl);

  auto real = lit<double>();
  auto integer = lit<int>();

  auto dquote = chr('"');

  // TODO escaped strings
  auto string = tos( no_skip( (dquote,
                               *!dquote,
                               dquote)) );

  auto symbol = tos( no_skip( (alpha, *alnum) ) );

  auto atom = symbol | string | real | integer;

  struct expr_tag;
  any<expr_tag> expr;

  auto list = no_skip( (chr('('),
                        *space,
                        ~( expr, *(+space, expr) ),
                        *space,
                        chr(')' )) );

  expr = atom | list;

  auto parser = expr;

  repl([&](std::istream& in) {
      return bool(in >> parser);
    });

}

<|endoftext|>


<commit_before>//===- Core/Resolver.cpp - Resolves Atom References -----------------------===//
//
//                             The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lld/Core/Atom.h"
#include "lld/Core/ArchiveLibraryFile.h"
#include "lld/Core/File.h"
#include "lld/Core/SharedLibraryFile.h"
#include "lld/Core/Instrumentation.h"
#include "lld/Core/LLVM.h"
#include "lld/Core/Resolver.h"
#include "lld/Core/SymbolTable.h"
#include "lld/Core/LinkingContext.h"
#include "lld/Core/UndefinedAtom.h"

#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/raw_ostream.h"

#include <algorithm>
#include <cassert>
#include <vector>

namespace lld {

namespace {

/// This is used as a filter function to std::remove_if to dead strip atoms.
class NotLive {
public:
  explicit NotLive(const llvm::DenseSet<const Atom *> &la) : _liveAtoms(la) {}

  bool operator()(const Atom *atom) const {
    // don't remove if live
    if (_liveAtoms.count(atom))
      return false;
    // don't remove if marked never-dead-strip
    if (const DefinedAtom *defAtom = dyn_cast<DefinedAtom>(atom))
      if (defAtom->deadStrip() == DefinedAtom::deadStripNever)
        return false;
    // do remove this atom
    return true;
  }

private:
  const llvm::DenseSet<const Atom *> &_liveAtoms;
};

/// This is used as a filter function to std::remove_if to coalesced atoms.
class AtomCoalescedAway {
public:
  explicit AtomCoalescedAway(SymbolTable &sym) : _symbolTable(sym) {}

  bool operator()(const Atom *atom) const {
    const Atom *rep = _symbolTable.replacement(atom);
    return rep != atom;
  }

private:
  SymbolTable &_symbolTable;
};

} // namespace

// called before the first atom in any file is added with doAtom()
void Resolver::doFile(const File &file) {}

void Resolver::handleFile(const File &file) {
  uint32_t resolverState = Resolver::StateNoChange;
  const SharedLibraryFile *sharedLibraryFile =
      llvm::dyn_cast<SharedLibraryFile>(&file);

  doFile(file);
  for (const DefinedAtom *atom : file.defined()) {
    doDefinedAtom(*atom);
    resolverState |= StateNewDefinedAtoms;
  }
  if (!sharedLibraryFile ||
      _context.addUndefinedAtomsFromSharedLibrary(sharedLibraryFile)) {
    for (const UndefinedAtom *undefAtom : file.undefined()) {
      doUndefinedAtom(*undefAtom);
      resolverState |= StateNewUndefinedAtoms;
      // If the undefined symbol has an alternative name, try to resolve the
      // symbol with the name to give it a second chance. This feature is used
      // for COFF "weak external" symbol.
      if (!_symbolTable.isDefined(undefAtom->name())) {
        if (const UndefinedAtom *fallbackAtom = undefAtom->fallback()) {
          doUndefinedAtom(*fallbackAtom);
          _symbolTable.addReplacement(undefAtom, fallbackAtom);
        }
      }
    }
  }
  for (const SharedLibraryAtom *shlibAtom : file.sharedLibrary()) {
    doSharedLibraryAtom(*shlibAtom);
    resolverState |= StateNewSharedLibraryAtoms;
  }
  for (const AbsoluteAtom *absAtom : file.absolute()) {
    doAbsoluteAtom(*absAtom);
    resolverState |= StateNewAbsoluteAtoms;
  }
  _context.setResolverState(resolverState);
}

void Resolver::forEachUndefines(UndefCallback callback,
                                bool searchForOverrides) {
  // Handle normal archives
  int64_t undefineGenCount = 0;
  do {
    undefineGenCount = _symbolTable.size();
    std::vector<const UndefinedAtom *> undefines;
    _symbolTable.undefines(undefines);
    for (const UndefinedAtom *undefAtom : undefines) {
      StringRef undefName = undefAtom->name();
      // load for previous undefine may also have loaded this undefine
      if (!_symbolTable.isDefined(undefName))
        callback(undefName, false);
    }
    // search libraries for overrides of common symbols
    if (searchForOverrides) {
      std::vector<StringRef> tentDefNames;
      _symbolTable.tentativeDefinitions(tentDefNames);
      for (StringRef tentDefName : tentDefNames) {
        // Load for previous tentative may also have loaded
        // something that overrode this tentative, so always check.
        const Atom *curAtom = _symbolTable.findByName(tentDefName);
        assert(curAtom != nullptr);
        if (const DefinedAtom *curDefAtom = dyn_cast<DefinedAtom>(curAtom)) {
          if (curDefAtom->merge() == DefinedAtom::mergeAsTentative)
            callback(tentDefName, true);
        }
      }
    }
  } while (undefineGenCount != _symbolTable.size());
}

void Resolver::handleArchiveFile(const File &file) {
  const ArchiveLibraryFile *archiveFile = dyn_cast<ArchiveLibraryFile>(&file);
  auto callback = [&](StringRef undefName, bool dataSymbolOnly) {
    if (const File *member = archiveFile->find(undefName, dataSymbolOnly)) {
      member->setOrdinal(_context.getNextOrdinalAndIncrement());
      handleFile(*member);
    }
  };
  bool searchForOverrides =
      _context.searchArchivesToOverrideTentativeDefinitions();
  forEachUndefines(callback, searchForOverrides);
}

void Resolver::handleSharedLibrary(const File &file) {
  // Add all the atoms from the shared library
  const SharedLibraryFile *sharedLibrary = dyn_cast<SharedLibraryFile>(&file);
  handleFile(*sharedLibrary);

  auto callback = [&](StringRef undefName, bool dataSymbolOnly) {
    if (const SharedLibraryAtom *shAtom =
            sharedLibrary->exports(undefName, dataSymbolOnly))
      doSharedLibraryAtom(*shAtom);
  };
  bool searchForOverrides =
      _context.searchSharedLibrariesToOverrideTentativeDefinitions();
  forEachUndefines(callback, searchForOverrides);
}

void Resolver::doUndefinedAtom(const UndefinedAtom &atom) {
  DEBUG_WITH_TYPE("resolver", llvm::dbgs()
                    << "       UndefinedAtom: "
                    << llvm::format("0x%09lX", &atom)
                    << ", name="
                    << atom.name()
                    << "\n");

  // add to list of known atoms
  _atoms.push_back(&atom);

  // tell symbol table
  _symbolTable.add(atom);
}

// called on each atom when a file is added
void Resolver::doDefinedAtom(const DefinedAtom &atom) {
  DEBUG_WITH_TYPE("resolver", llvm::dbgs()
                    << "         DefinedAtom: "
                    << llvm::format("0x%09lX", &atom)
                    << ", file=#"
                    << atom.file().ordinal()
                    << ", atom=#"
                    << atom.ordinal()
                    << ", name="
                    << atom.name()
                    << "\n");

  // Verify on zero-size atoms are pinned to start or end of section.
  switch (atom.sectionPosition()) {
  case DefinedAtom::sectionPositionStart:
  case DefinedAtom::sectionPositionEnd:
    assert(atom.size() == 0);
    break;
  case DefinedAtom::sectionPositionEarly:
  case DefinedAtom::sectionPositionAny:
    break;
  }

  // add to list of known atoms
  _atoms.push_back(&atom);

  // tell symbol table
  _symbolTable.add(atom);

  if (_context.deadStrip()) {
    // add to set of dead-strip-roots, all symbols that
    // the compiler marks as don't strip
    if (atom.deadStrip() == DefinedAtom::deadStripNever)
      _deadStripRoots.insert(&atom);
  }
}

void Resolver::doSharedLibraryAtom(const SharedLibraryAtom &atom) {
  DEBUG_WITH_TYPE("resolver", llvm::dbgs()
                    << "   SharedLibraryAtom: "
                    << llvm::format("0x%09lX", &atom)
                    << ", name="
                    << atom.name()
                    << "\n");

  // add to list of known atoms
  _atoms.push_back(&atom);

  // tell symbol table
  _symbolTable.add(atom);
}

void Resolver::doAbsoluteAtom(const AbsoluteAtom &atom) {
  DEBUG_WITH_TYPE("resolver", llvm::dbgs()
                    << "       AbsoluteAtom: "
                    << llvm::format("0x%09lX", &atom)
                    << ", name="
                    << atom.name()
                    << "\n");

  // add to list of known atoms
  _atoms.push_back(&atom);

  // tell symbol table
  if (atom.scope() != Atom::scopeTranslationUnit)
    _symbolTable.add(atom);
}

// utility to add a vector of atoms
void Resolver::addAtoms(const std::vector<const DefinedAtom *> &newAtoms) {
  for (const DefinedAtom *newAtom : newAtoms)
    this->doDefinedAtom(*newAtom);
}

// Keep adding atoms until _context.nextFile() returns an error. This function
// is where undefined atoms are resolved.
bool Resolver::resolveUndefines() {
  ScopedTask task(getDefaultDomain(), "resolveUndefines");

  for (;;) {
    ErrorOr<File &> file = _context.nextFile();
    _context.setResolverState(Resolver::StateNoChange);
    error_code ec = file.getError();
    if (ec == InputGraphError::no_more_files)
      return true;
    if (!file) {
      llvm::errs() << "Error occurred in nextFile: "
                   << ec.message() << "\n";
      return false;
    }

    switch (file->kind()) {
    case File::kindObject:
      assert(!file->hasOrdinal());
      file->setOrdinal(_context.getNextOrdinalAndIncrement());
      handleFile(*file);
      break;
    case File::kindArchiveLibrary:
      if (!file->hasOrdinal())
        file->setOrdinal(_context.getNextOrdinalAndIncrement());
      handleArchiveFile(*file);
      break;
    case File::kindSharedLibrary:
      if (!file->hasOrdinal())
        file->setOrdinal(_context.getNextOrdinalAndIncrement());
      handleSharedLibrary(*file);
      break;
    }
  }
}

// switch all references to undefined or coalesced away atoms
// to the new defined atom
void Resolver::updateReferences() {
  ScopedTask task(getDefaultDomain(), "updateReferences");
  for (const Atom *atom : _atoms) {
    if (const DefinedAtom *defAtom = dyn_cast<DefinedAtom>(atom)) {
      for (const Reference *ref : *defAtom) {
        const Atom *newTarget = _symbolTable.replacement(ref->target());
        const_cast<Reference *>(ref)->setTarget(newTarget);
      }
    }
  }
}

// For dead code stripping, recursively mark atoms "live"
void Resolver::markLive(const Atom &atom) {
  // Mark the atom is live. If it's already marked live, then stop recursion.
  auto exists = _liveAtoms.insert(&atom);
  if (!exists.second)
    return;

  // Mark all atoms it references as live
  if (const DefinedAtom *defAtom = dyn_cast<DefinedAtom>(&atom))
    for (const Reference *ref : *defAtom)
      if (const Atom *target = ref->target())
        this->markLive(*target);
}

// remove all atoms not actually used
void Resolver::deadStripOptimize() {
  ScopedTask task(getDefaultDomain(), "deadStripOptimize");
  // only do this optimization with -dead_strip
  if (!_context.deadStrip())
    return;
  assert(_liveAtoms.empty());

  // By default, shared libraries are built with all globals as dead strip roots
  if (_context.globalsAreDeadStripRoots()) {
    for (const Atom *atom : _atoms) {
      const DefinedAtom *defAtom = dyn_cast<DefinedAtom>(atom);
      if (defAtom == nullptr)
        continue;
      if (defAtom->scope() == DefinedAtom::scopeGlobal)
        _deadStripRoots.insert(defAtom);
    }
  }

  // Or, use list of names that are dead strip roots.
  for (const StringRef &name : _context.deadStripRoots()) {
    const Atom *symAtom = _symbolTable.findByName(name);
    assert(symAtom);
    _deadStripRoots.insert(symAtom);
  }

  // mark all roots as live, and recursively all atoms they reference
  for (const Atom *dsrAtom : _deadStripRoots)
    this->markLive(*dsrAtom);

  // now remove all non-live atoms from _atoms
  _atoms.erase(
      std::remove_if(_atoms.begin(), _atoms.end(), NotLive(_liveAtoms)),
      _atoms.end());
}

// error out if some undefines remain
bool Resolver::checkUndefines(bool isFinal) {
  // when using LTO, undefines are checked after bitcode is optimized
  if (_haveLLVMObjs && !isFinal)
    return false;

  // build vector of remaining undefined symbols
  std::vector<const UndefinedAtom *> undefinedAtoms;
  _symbolTable.undefines(undefinedAtoms);
  if (_context.deadStrip()) {
    // When dead code stripping, we don't care if dead atoms are undefined.
    undefinedAtoms.erase(std::remove_if(undefinedAtoms.begin(),
                                        undefinedAtoms.end(),
                                        NotLive(_liveAtoms)),
                         undefinedAtoms.end());
  }

  // error message about missing symbols
  if (!undefinedAtoms.empty()) {
    // FIXME: need diagnostics interface for writing error messages
    bool foundUndefines = false;
    for (const UndefinedAtom *undefAtom : undefinedAtoms) {
      const File &f = undefAtom->file();

      // Skip over a weak symbol.
      if (undefAtom->canBeNull() != UndefinedAtom::canBeNullNever)
        continue;

      // If this is a library and undefined symbols are allowed on the
      // target platform, skip over it.
      if (isa<SharedLibraryFile>(f) && _context.allowShlibUndefines())
        continue;

      // If the undefine is coalesced away, skip over it.
      if (_symbolTable.replacement(undefAtom) != undefAtom)
        continue;

      // Seems like this symbol is undefined. Warn that.
      foundUndefines = true;
      if (_context.printRemainingUndefines()) {
        llvm::errs() << "Undefined Symbol: " << undefAtom->file().path()
                     << " : " << undefAtom->name() << "\n";
      }
    }
    if (foundUndefines) {
      if (_context.printRemainingUndefines())
        llvm::errs() << "symbol(s) not found\n";
      return true;
    }
  }
  return false;
}

// remove from _atoms all coaleseced away atoms
void Resolver::removeCoalescedAwayAtoms() {
  ScopedTask task(getDefaultDomain(), "removeCoalescedAwayAtoms");
  _atoms.erase(std::remove_if(_atoms.begin(), _atoms.end(),
                              AtomCoalescedAway(_symbolTable)),
               _atoms.end());
}

void Resolver::linkTimeOptimize() {
  // FIX ME
}

bool Resolver::resolve() {
  if (!this->resolveUndefines())
    return false;
  this->updateReferences();
  this->deadStripOptimize();
  if (this->checkUndefines(false))
    if (!_context.allowRemainingUndefines())
      return false;
  this->removeCoalescedAwayAtoms();
  this->linkTimeOptimize();
  this->_result->addAtoms(_atoms);
  return true;
}

void Resolver::MergedFile::addAtom(const Atom &atom) {
  if (const DefinedAtom *defAtom = dyn_cast<DefinedAtom>(&atom)) {
    _definedAtoms._atoms.push_back(defAtom);
  } else if (const UndefinedAtom *undefAtom = dyn_cast<UndefinedAtom>(&atom)) {
    _undefinedAtoms._atoms.push_back(undefAtom);
  } else if (const SharedLibraryAtom *slAtom =
                 dyn_cast<SharedLibraryAtom>(&atom)) {
    _sharedLibraryAtoms._atoms.push_back(slAtom);
  } else if (const AbsoluteAtom *abAtom = dyn_cast<AbsoluteAtom>(&atom)) {
    _absoluteAtoms._atoms.push_back(abAtom);
  } else {
    llvm_unreachable("atom has unknown definition kind");
  }
}

MutableFile::DefinedAtomRange Resolver::MergedFile::definedAtoms() {
  return range<std::vector<const DefinedAtom *>::iterator>(
      _definedAtoms._atoms.begin(), _definedAtoms._atoms.end());
}

void Resolver::MergedFile::addAtoms(std::vector<const Atom *> &all) {
  ScopedTask task(getDefaultDomain(), "addAtoms");
  DEBUG_WITH_TYPE("resolver", llvm::dbgs() << "Resolver final atom list:\n");
  for (const Atom *atom : all) {
    DEBUG_WITH_TYPE("resolver", llvm::dbgs()
                    << llvm::format("    0x%09lX", atom)
                    << ", name="
                    << atom->name()
                    << "\n");
    this->addAtom(*atom);
  }
}

} // namespace lld
<commit_msg>Use auto for readability. No functionality change.<commit_after>//===- Core/Resolver.cpp - Resolves Atom References -----------------------===//
//
//                             The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lld/Core/Atom.h"
#include "lld/Core/ArchiveLibraryFile.h"
#include "lld/Core/File.h"
#include "lld/Core/SharedLibraryFile.h"
#include "lld/Core/Instrumentation.h"
#include "lld/Core/LLVM.h"
#include "lld/Core/Resolver.h"
#include "lld/Core/SymbolTable.h"
#include "lld/Core/LinkingContext.h"
#include "lld/Core/UndefinedAtom.h"

#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/raw_ostream.h"

#include <algorithm>
#include <cassert>
#include <vector>

namespace lld {

namespace {

/// This is used as a filter function to std::remove_if to dead strip atoms.
class NotLive {
public:
  explicit NotLive(const llvm::DenseSet<const Atom *> &la) : _liveAtoms(la) {}

  bool operator()(const Atom *atom) const {
    // don't remove if live
    if (_liveAtoms.count(atom))
      return false;
    // don't remove if marked never-dead-strip
    if (const DefinedAtom *defAtom = dyn_cast<DefinedAtom>(atom))
      if (defAtom->deadStrip() == DefinedAtom::deadStripNever)
        return false;
    // do remove this atom
    return true;
  }

private:
  const llvm::DenseSet<const Atom *> &_liveAtoms;
};

/// This is used as a filter function to std::remove_if to coalesced atoms.
class AtomCoalescedAway {
public:
  explicit AtomCoalescedAway(SymbolTable &sym) : _symbolTable(sym) {}

  bool operator()(const Atom *atom) const {
    const Atom *rep = _symbolTable.replacement(atom);
    return rep != atom;
  }

private:
  SymbolTable &_symbolTable;
};

} // namespace

// called before the first atom in any file is added with doAtom()
void Resolver::doFile(const File &file) {}

void Resolver::handleFile(const File &file) {
  uint32_t resolverState = Resolver::StateNoChange;
  const SharedLibraryFile *sharedLibraryFile =
      llvm::dyn_cast<SharedLibraryFile>(&file);

  doFile(file);
  for (const DefinedAtom *atom : file.defined()) {
    doDefinedAtom(*atom);
    resolverState |= StateNewDefinedAtoms;
  }
  if (!sharedLibraryFile ||
      _context.addUndefinedAtomsFromSharedLibrary(sharedLibraryFile)) {
    for (const UndefinedAtom *undefAtom : file.undefined()) {
      doUndefinedAtom(*undefAtom);
      resolverState |= StateNewUndefinedAtoms;
      // If the undefined symbol has an alternative name, try to resolve the
      // symbol with the name to give it a second chance. This feature is used
      // for COFF "weak external" symbol.
      if (!_symbolTable.isDefined(undefAtom->name())) {
        if (const UndefinedAtom *fallbackAtom = undefAtom->fallback()) {
          doUndefinedAtom(*fallbackAtom);
          _symbolTable.addReplacement(undefAtom, fallbackAtom);
        }
      }
    }
  }
  for (const SharedLibraryAtom *shlibAtom : file.sharedLibrary()) {
    doSharedLibraryAtom(*shlibAtom);
    resolverState |= StateNewSharedLibraryAtoms;
  }
  for (const AbsoluteAtom *absAtom : file.absolute()) {
    doAbsoluteAtom(*absAtom);
    resolverState |= StateNewAbsoluteAtoms;
  }
  _context.setResolverState(resolverState);
}

void Resolver::forEachUndefines(UndefCallback callback,
                                bool searchForOverrides) {
  // Handle normal archives
  int64_t undefineGenCount = 0;
  do {
    undefineGenCount = _symbolTable.size();
    std::vector<const UndefinedAtom *> undefines;
    _symbolTable.undefines(undefines);
    for (const UndefinedAtom *undefAtom : undefines) {
      StringRef undefName = undefAtom->name();
      // load for previous undefine may also have loaded this undefine
      if (!_symbolTable.isDefined(undefName))
        callback(undefName, false);
    }
    // search libraries for overrides of common symbols
    if (searchForOverrides) {
      std::vector<StringRef> tentDefNames;
      _symbolTable.tentativeDefinitions(tentDefNames);
      for (StringRef tentDefName : tentDefNames) {
        // Load for previous tentative may also have loaded
        // something that overrode this tentative, so always check.
        const Atom *curAtom = _symbolTable.findByName(tentDefName);
        assert(curAtom != nullptr);
        if (const DefinedAtom *curDefAtom = dyn_cast<DefinedAtom>(curAtom)) {
          if (curDefAtom->merge() == DefinedAtom::mergeAsTentative)
            callback(tentDefName, true);
        }
      }
    }
  } while (undefineGenCount != _symbolTable.size());
}

void Resolver::handleArchiveFile(const File &file) {
  const ArchiveLibraryFile *archiveFile = dyn_cast<ArchiveLibraryFile>(&file);
  auto callback = [&](StringRef undefName, bool dataSymbolOnly) {
    if (const File *member = archiveFile->find(undefName, dataSymbolOnly)) {
      member->setOrdinal(_context.getNextOrdinalAndIncrement());
      handleFile(*member);
    }
  };
  bool searchForOverrides =
      _context.searchArchivesToOverrideTentativeDefinitions();
  forEachUndefines(callback, searchForOverrides);
}

void Resolver::handleSharedLibrary(const File &file) {
  // Add all the atoms from the shared library
  const SharedLibraryFile *sharedLibrary = dyn_cast<SharedLibraryFile>(&file);
  handleFile(*sharedLibrary);

  auto callback = [&](StringRef undefName, bool dataSymbolOnly) {
    if (const SharedLibraryAtom *shAtom =
            sharedLibrary->exports(undefName, dataSymbolOnly))
      doSharedLibraryAtom(*shAtom);
  };
  bool searchForOverrides =
      _context.searchSharedLibrariesToOverrideTentativeDefinitions();
  forEachUndefines(callback, searchForOverrides);
}

void Resolver::doUndefinedAtom(const UndefinedAtom &atom) {
  DEBUG_WITH_TYPE("resolver", llvm::dbgs()
                    << "       UndefinedAtom: "
                    << llvm::format("0x%09lX", &atom)
                    << ", name="
                    << atom.name()
                    << "\n");

  // add to list of known atoms
  _atoms.push_back(&atom);

  // tell symbol table
  _symbolTable.add(atom);
}

// called on each atom when a file is added
void Resolver::doDefinedAtom(const DefinedAtom &atom) {
  DEBUG_WITH_TYPE("resolver", llvm::dbgs()
                    << "         DefinedAtom: "
                    << llvm::format("0x%09lX", &atom)
                    << ", file=#"
                    << atom.file().ordinal()
                    << ", atom=#"
                    << atom.ordinal()
                    << ", name="
                    << atom.name()
                    << "\n");

  // Verify on zero-size atoms are pinned to start or end of section.
  switch (atom.sectionPosition()) {
  case DefinedAtom::sectionPositionStart:
  case DefinedAtom::sectionPositionEnd:
    assert(atom.size() == 0);
    break;
  case DefinedAtom::sectionPositionEarly:
  case DefinedAtom::sectionPositionAny:
    break;
  }

  // add to list of known atoms
  _atoms.push_back(&atom);

  // tell symbol table
  _symbolTable.add(atom);

  if (_context.deadStrip()) {
    // add to set of dead-strip-roots, all symbols that
    // the compiler marks as don't strip
    if (atom.deadStrip() == DefinedAtom::deadStripNever)
      _deadStripRoots.insert(&atom);
  }
}

void Resolver::doSharedLibraryAtom(const SharedLibraryAtom &atom) {
  DEBUG_WITH_TYPE("resolver", llvm::dbgs()
                    << "   SharedLibraryAtom: "
                    << llvm::format("0x%09lX", &atom)
                    << ", name="
                    << atom.name()
                    << "\n");

  // add to list of known atoms
  _atoms.push_back(&atom);

  // tell symbol table
  _symbolTable.add(atom);
}

void Resolver::doAbsoluteAtom(const AbsoluteAtom &atom) {
  DEBUG_WITH_TYPE("resolver", llvm::dbgs()
                    << "       AbsoluteAtom: "
                    << llvm::format("0x%09lX", &atom)
                    << ", name="
                    << atom.name()
                    << "\n");

  // add to list of known atoms
  _atoms.push_back(&atom);

  // tell symbol table
  if (atom.scope() != Atom::scopeTranslationUnit)
    _symbolTable.add(atom);
}

// utility to add a vector of atoms
void Resolver::addAtoms(const std::vector<const DefinedAtom *> &newAtoms) {
  for (const DefinedAtom *newAtom : newAtoms)
    this->doDefinedAtom(*newAtom);
}

// Keep adding atoms until _context.nextFile() returns an error. This function
// is where undefined atoms are resolved.
bool Resolver::resolveUndefines() {
  ScopedTask task(getDefaultDomain(), "resolveUndefines");

  for (;;) {
    ErrorOr<File &> file = _context.nextFile();
    _context.setResolverState(Resolver::StateNoChange);
    error_code ec = file.getError();
    if (ec == InputGraphError::no_more_files)
      return true;
    if (!file) {
      llvm::errs() << "Error occurred in nextFile: "
                   << ec.message() << "\n";
      return false;
    }

    switch (file->kind()) {
    case File::kindObject:
      assert(!file->hasOrdinal());
      file->setOrdinal(_context.getNextOrdinalAndIncrement());
      handleFile(*file);
      break;
    case File::kindArchiveLibrary:
      if (!file->hasOrdinal())
        file->setOrdinal(_context.getNextOrdinalAndIncrement());
      handleArchiveFile(*file);
      break;
    case File::kindSharedLibrary:
      if (!file->hasOrdinal())
        file->setOrdinal(_context.getNextOrdinalAndIncrement());
      handleSharedLibrary(*file);
      break;
    }
  }
}

// switch all references to undefined or coalesced away atoms
// to the new defined atom
void Resolver::updateReferences() {
  ScopedTask task(getDefaultDomain(), "updateReferences");
  for (const Atom *atom : _atoms) {
    if (const DefinedAtom *defAtom = dyn_cast<DefinedAtom>(atom)) {
      for (const Reference *ref : *defAtom) {
        const Atom *newTarget = _symbolTable.replacement(ref->target());
        const_cast<Reference *>(ref)->setTarget(newTarget);
      }
    }
  }
}

// For dead code stripping, recursively mark atoms "live"
void Resolver::markLive(const Atom &atom) {
  // Mark the atom is live. If it's already marked live, then stop recursion.
  auto exists = _liveAtoms.insert(&atom);
  if (!exists.second)
    return;

  // Mark all atoms it references as live
  if (const DefinedAtom *defAtom = dyn_cast<DefinedAtom>(&atom))
    for (const Reference *ref : *defAtom)
      if (const Atom *target = ref->target())
        this->markLive(*target);
}

// remove all atoms not actually used
void Resolver::deadStripOptimize() {
  ScopedTask task(getDefaultDomain(), "deadStripOptimize");
  // only do this optimization with -dead_strip
  if (!_context.deadStrip())
    return;
  assert(_liveAtoms.empty());

  // By default, shared libraries are built with all globals as dead strip roots
  if (_context.globalsAreDeadStripRoots()) {
    for (const Atom *atom : _atoms) {
      const DefinedAtom *defAtom = dyn_cast<DefinedAtom>(atom);
      if (defAtom == nullptr)
        continue;
      if (defAtom->scope() == DefinedAtom::scopeGlobal)
        _deadStripRoots.insert(defAtom);
    }
  }

  // Or, use list of names that are dead strip roots.
  for (const StringRef &name : _context.deadStripRoots()) {
    const Atom *symAtom = _symbolTable.findByName(name);
    assert(symAtom);
    _deadStripRoots.insert(symAtom);
  }

  // mark all roots as live, and recursively all atoms they reference
  for (const Atom *dsrAtom : _deadStripRoots)
    this->markLive(*dsrAtom);

  // now remove all non-live atoms from _atoms
  _atoms.erase(
      std::remove_if(_atoms.begin(), _atoms.end(), NotLive(_liveAtoms)),
      _atoms.end());
}

// error out if some undefines remain
bool Resolver::checkUndefines(bool isFinal) {
  // when using LTO, undefines are checked after bitcode is optimized
  if (_haveLLVMObjs && !isFinal)
    return false;

  // build vector of remaining undefined symbols
  std::vector<const UndefinedAtom *> undefinedAtoms;
  _symbolTable.undefines(undefinedAtoms);
  if (_context.deadStrip()) {
    // When dead code stripping, we don't care if dead atoms are undefined.
    undefinedAtoms.erase(std::remove_if(undefinedAtoms.begin(),
                                        undefinedAtoms.end(),
                                        NotLive(_liveAtoms)),
                         undefinedAtoms.end());
  }

  // error message about missing symbols
  if (!undefinedAtoms.empty()) {
    // FIXME: need diagnostics interface for writing error messages
    bool foundUndefines = false;
    for (const UndefinedAtom *undefAtom : undefinedAtoms) {
      const File &f = undefAtom->file();

      // Skip over a weak symbol.
      if (undefAtom->canBeNull() != UndefinedAtom::canBeNullNever)
        continue;

      // If this is a library and undefined symbols are allowed on the
      // target platform, skip over it.
      if (isa<SharedLibraryFile>(f) && _context.allowShlibUndefines())
        continue;

      // If the undefine is coalesced away, skip over it.
      if (_symbolTable.replacement(undefAtom) != undefAtom)
        continue;

      // Seems like this symbol is undefined. Warn that.
      foundUndefines = true;
      if (_context.printRemainingUndefines()) {
        llvm::errs() << "Undefined Symbol: " << undefAtom->file().path()
                     << " : " << undefAtom->name() << "\n";
      }
    }
    if (foundUndefines) {
      if (_context.printRemainingUndefines())
        llvm::errs() << "symbol(s) not found\n";
      return true;
    }
  }
  return false;
}

// remove from _atoms all coaleseced away atoms
void Resolver::removeCoalescedAwayAtoms() {
  ScopedTask task(getDefaultDomain(), "removeCoalescedAwayAtoms");
  _atoms.erase(std::remove_if(_atoms.begin(), _atoms.end(),
                              AtomCoalescedAway(_symbolTable)),
               _atoms.end());
}

void Resolver::linkTimeOptimize() {
  // FIX ME
}

bool Resolver::resolve() {
  if (!this->resolveUndefines())
    return false;
  this->updateReferences();
  this->deadStripOptimize();
  if (this->checkUndefines(false))
    if (!_context.allowRemainingUndefines())
      return false;
  this->removeCoalescedAwayAtoms();
  this->linkTimeOptimize();
  this->_result->addAtoms(_atoms);
  return true;
}

void Resolver::MergedFile::addAtom(const Atom &atom) {
  if (auto *def = dyn_cast<DefinedAtom>(&atom)) {
    _definedAtoms._atoms.push_back(def);
  } else if (auto *undef = dyn_cast<UndefinedAtom>(&atom)) {
    _undefinedAtoms._atoms.push_back(undef);
  } else if (auto *shared = dyn_cast<SharedLibraryAtom>(&atom)) {
    _sharedLibraryAtoms._atoms.push_back(shared);
  } else if (auto *abs = dyn_cast<AbsoluteAtom>(&atom)) {
    _absoluteAtoms._atoms.push_back(abs);
  } else {
    llvm_unreachable("atom has unknown definition kind");
  }
}

MutableFile::DefinedAtomRange Resolver::MergedFile::definedAtoms() {
  return range<std::vector<const DefinedAtom *>::iterator>(
      _definedAtoms._atoms.begin(), _definedAtoms._atoms.end());
}

void Resolver::MergedFile::addAtoms(std::vector<const Atom *> &all) {
  ScopedTask task(getDefaultDomain(), "addAtoms");
  DEBUG_WITH_TYPE("resolver", llvm::dbgs() << "Resolver final atom list:\n");
  for (const Atom *atom : all) {
    DEBUG_WITH_TYPE("resolver", llvm::dbgs()
                    << llvm::format("    0x%09lX", atom)
                    << ", name="
                    << atom->name()
                    << "\n");
    this->addAtom(*atom);
  }
}

} // namespace lld
<|endoftext|>


<commit_before>#pragma once

#include "numerics/global_optimization.hpp"

#include <utility>

#include "geometry/barycentre_calculator.hpp"
#include "numerics/gradient_descent.hpp"

namespace principia {
namespace numerics {
namespace internal_global_optimization {

using geometry::Barycentre;
using geometry::Wedge;
using quantities::Cbrt;

// TODO(phl): Provide a way to parameterize the PCP trees?
constexpr int64_t pcp_tree_max_values_per_cell = 10;

template<typename Scalar, typename Argument>
Cube<typename Hilbert<Difference<Argument>>::NormType>
MultiLevelSingleLinkage<Scalar, Argument>::Box::Measure() const {
  return 8 * Wedge(vertices[0], Wedge(vertices[1], vertices[2])).Norm();
}

template<typename Scalar, typename Argument>
MultiLevelSingleLinkage<Scalar, Argument>::MultiLevelSingleLinkage(
    Box const& box,
    Field<Scalar, Argument> const& f,
    Field<Gradient<Scalar, Argument>, Argument> const& grad_f)
    : box_(box),
      box_measure_(box_.Measure()),
      f_(f),
      grad_f_(grad_f),
      random_(42),
      distribution_(-1.0, 1.0) {
  CHECK_LT(Cube<typename Hilbert<Difference<Argument>>::NormType>{},
           box_measure_);
}

template<typename Scalar, typename Argument>
std::vector<Argument>
MultiLevelSingleLinkage<Scalar, Argument>::FindGlobalMinima(
    std::int64_t const points_per_round,
    std::int64_t const number_of_rounds,
    NormType const local_search_tolerance) {
  const std::int64_t N = points_per_round;

  // This is the set X* from [RT87b].  It contains |unique_ptr|s because we need
  // pointer stability for the PCP tree but we cannot precompute the vector
  // size.
  std::vector<std::unique_ptr<Argument>> stationary_points;

  // The PCP tree used for detecting proximity of the stationary points.  It
  // gets updated as new stationary points are found.
  PrincipalComponentPartitioningTree<Argument> stationary_point_neighbourhoods(
      /*values=*/{},
      pcp_tree_max_values_per_cell);

  // The sample points.  Make sure that pointers don't get invalidated as new
  // points are added.
  std::vector<Argument> points;
  points.reserve(N * number_of_rounds);

  // The PCP tree used for detecting proximity of the sample points .  It gets
  // updated as new points are generated.
  PrincipalComponentPartitioningTree<Argument> point_neighbourhoods(
      /*values=*/{},
      pcp_tree_max_values_per_cell);

  // TODO(phl): This is quadratic.  Make the algorithm linear once we believe
  // that it is correct.
  for (std::int64_t k = 1; k <= number_of_rounds; ++k) {
    // Generate N new random points and add them to the PCP tree.
    std::vector<Argument> pointsₖ = RandomArguments(N);
    for (auto& pointₖ : pointsₖ) {
      points.push_back(std::move(pointₖ));
      point_neighbourhoods.Add(&points.back());
    }

    auto const rₖ = CriticalRadius(/*σ=*/4, /*kN=*/k * N);

    for (auto& xᵢ : points) {
      auto* const xⱼ = point_neighbourhoods.FindNearestNeighbour(
          xᵢ, [this, f_xᵢ = f_(xᵢ)](Argument const* const xⱼ) {
            return f_(*xⱼ) < f_xᵢ;
          });

      if (xⱼ == nullptr || (xᵢ - *xⱼ).Norm() > rₖ) {
        auto const stationary_point = BroydenFletcherGoldfarbShanno(
            xᵢ, f_, grad_f_, local_search_tolerance);

        // If the new stationary point is sufficiently far from the ones we
        // already know, record it.
        if (IsNewStationaryPoint(stationary_point,
                                 stationary_point_neighbourhoods,
                                 local_search_tolerance)) {
          stationary_points.push_back(
              std::make_unique<Argument>(stationary_point));
          stationary_point_neighbourhoods.Add(stationary_points.back().get());
        }
      }
    }
  }

  std::vector<Argument> result;
  result.reserve(stationary_points.size());
  for (const auto& stationary_point : stationary_points) {
    result.push_back(*stationary_point);
  }

  return result;
}

template<typename Scalar, typename Argument>
bool MultiLevelSingleLinkage<Scalar, Argument>::IsNewStationaryPoint(
    Argument const& stationary_point,
    PrincipalComponentPartitioningTree<Argument> const&
        stationary_point_neighbourhoods,
    NormType const local_search_tolerance) {
  auto* const stationary_point_nearest_neighbour =
      stationary_point_neighbourhoods.FindNearestNeighbour(stationary_point);

  // The factor 2 below is because we are looking at the distance between two
  // approximate stationary points, not between an approximate stationary point
  // and the real one.
  return stationary_point_nearest_neighbour == nullptr ||
         (stationary_point - *stationary_point_nearest_neighbour).Norm() >
             2 * local_search_tolerance;
}

template<typename Scalar, typename Argument>
std::vector<Argument>
MultiLevelSingleLinkage<Scalar, Argument>::RandomArguments(
    std::int64_t const values_per_round) {
  std::vector<Argument> result;
  for (std::int64_t i = 0; i < values_per_round; ++i) {
    Argument argument = box_.centre;
    for (const auto& vertex : box_.vertices) {
      argument += distribution_(random_) * vertex;
    }
    result.push_back(argument);
  }
  return result;
}

template<typename Scalar, typename Argument>
typename Hilbert<Difference<Argument>>::NormType
MultiLevelSingleLinkage<Scalar, Argument>::CriticalRadius(
    double const σ,
    std::int64_t const kN) {
  return Cbrt(3.0 * box_measure_ * std::log(kN) / (4.0 * π * kN));
}

}  // namespace internal_global_optimization
}  // namespace numerics
}  // namespace principia
<commit_msg>Lint.<commit_after>#pragma once

#include "numerics/global_optimization.hpp"

#include <vector>
#include <utility>

#include "geometry/barycentre_calculator.hpp"
#include "numerics/gradient_descent.hpp"

namespace principia {
namespace numerics {
namespace internal_global_optimization {

using geometry::Barycentre;
using geometry::Wedge;
using quantities::Cbrt;

// TODO(phl): Provide a way to parameterize the PCP trees?
constexpr int64_t pcp_tree_max_values_per_cell = 10;

template<typename Scalar, typename Argument>
Cube<typename Hilbert<Difference<Argument>>::NormType>
MultiLevelSingleLinkage<Scalar, Argument>::Box::Measure() const {
  return 8 * Wedge(vertices[0], Wedge(vertices[1], vertices[2])).Norm();
}

template<typename Scalar, typename Argument>
MultiLevelSingleLinkage<Scalar, Argument>::MultiLevelSingleLinkage(
    Box const& box,
    Field<Scalar, Argument> const& f,
    Field<Gradient<Scalar, Argument>, Argument> const& grad_f)
    : box_(box),
      box_measure_(box_.Measure()),
      f_(f),
      grad_f_(grad_f),
      random_(42),
      distribution_(-1.0, 1.0) {
  CHECK_LT(Cube<typename Hilbert<Difference<Argument>>::NormType>{},
           box_measure_);
}

template<typename Scalar, typename Argument>
std::vector<Argument>
MultiLevelSingleLinkage<Scalar, Argument>::FindGlobalMinima(
    std::int64_t const points_per_round,
    std::int64_t const number_of_rounds,
    NormType const local_search_tolerance) {
  const std::int64_t N = points_per_round;

  // This is the set X* from [RT87b].  It contains |unique_ptr|s because we need
  // pointer stability for the PCP tree but we cannot precompute the vector
  // size.
  std::vector<std::unique_ptr<Argument>> stationary_points;

  // The PCP tree used for detecting proximity of the stationary points.  It
  // gets updated as new stationary points are found.
  PrincipalComponentPartitioningTree<Argument> stationary_point_neighbourhoods(
      /*values=*/{},
      pcp_tree_max_values_per_cell);

  // The sample points.  Make sure that pointers don't get invalidated as new
  // points are added.
  std::vector<Argument> points;
  points.reserve(N * number_of_rounds);

  // The PCP tree used for detecting proximity of the sample points .  It gets
  // updated as new points are generated.
  PrincipalComponentPartitioningTree<Argument> point_neighbourhoods(
      /*values=*/{},
      pcp_tree_max_values_per_cell);

  // TODO(phl): This is quadratic.  Make the algorithm linear once we believe
  // that it is correct.
  for (std::int64_t k = 1; k <= number_of_rounds; ++k) {
    // Generate N new random points and add them to the PCP tree.
    std::vector<Argument> pointsₖ = RandomArguments(N);
    for (auto& pointₖ : pointsₖ) {
      points.push_back(std::move(pointₖ));
      point_neighbourhoods.Add(&points.back());
    }

    auto const rₖ = CriticalRadius(/*σ=*/4, /*kN=*/k * N);

    for (auto& xᵢ : points) {
      auto* const xⱼ = point_neighbourhoods.FindNearestNeighbour(
          xᵢ, [this, f_xᵢ = f_(xᵢ)](Argument const* const xⱼ) {
            return f_(*xⱼ) < f_xᵢ;
          });

      if (xⱼ == nullptr || (xᵢ - *xⱼ).Norm() > rₖ) {
        auto const stationary_point = BroydenFletcherGoldfarbShanno(
            xᵢ, f_, grad_f_, local_search_tolerance);

        // If the new stationary point is sufficiently far from the ones we
        // already know, record it.
        if (IsNewStationaryPoint(stationary_point,
                                 stationary_point_neighbourhoods,
                                 local_search_tolerance)) {
          stationary_points.push_back(
              std::make_unique<Argument>(stationary_point));
          stationary_point_neighbourhoods.Add(stationary_points.back().get());
        }
      }
    }
  }

  std::vector<Argument> result;
  result.reserve(stationary_points.size());
  for (const auto& stationary_point : stationary_points) {
    result.push_back(*stationary_point);
  }

  return result;
}

template<typename Scalar, typename Argument>
bool MultiLevelSingleLinkage<Scalar, Argument>::IsNewStationaryPoint(
    Argument const& stationary_point,
    PrincipalComponentPartitioningTree<Argument> const&
        stationary_point_neighbourhoods,
    NormType const local_search_tolerance) {
  auto* const stationary_point_nearest_neighbour =
      stationary_point_neighbourhoods.FindNearestNeighbour(stationary_point);

  // The factor 2 below is because we are looking at the distance between two
  // approximate stationary points, not between an approximate stationary point
  // and the real one.
  return stationary_point_nearest_neighbour == nullptr ||
         (stationary_point - *stationary_point_nearest_neighbour).Norm() >
             2 * local_search_tolerance;
}

template<typename Scalar, typename Argument>
std::vector<Argument>
MultiLevelSingleLinkage<Scalar, Argument>::RandomArguments(
    std::int64_t const values_per_round) {
  std::vector<Argument> result;
  for (std::int64_t i = 0; i < values_per_round; ++i) {
    Argument argument = box_.centre;
    for (const auto& vertex : box_.vertices) {
      argument += distribution_(random_) * vertex;
    }
    result.push_back(argument);
  }
  return result;
}

template<typename Scalar, typename Argument>
typename Hilbert<Difference<Argument>>::NormType
MultiLevelSingleLinkage<Scalar, Argument>::CriticalRadius(
    double const σ,
    std::int64_t const kN) {
  return Cbrt(3.0 * box_measure_ * std::log(kN) / (4.0 * π * kN));
}

}  // namespace internal_global_optimization
}  // namespace numerics
}  // namespace principia
<|endoftext|>


<commit_before>/******************************************************************************\
 * This example program represents a minimal terminal chat program            *
 * based on group communication.                                              *
 *                                                                            *
 * Setup for a minimal chat between "alice" and "bob":                        *
 * - ./build/bin/group_server -p 4242                                         *
 * - ./build/bin/group_chat -g remote:chatroom@localhost:4242 -n alice        *
 * - ./build/bin/group_chat -g remote:chatroom@localhost:4242 -n bob          *
\******************************************************************************/

#include <set>
#include <map>
#include <vector>
#include <dlfcn.h>
#include <iostream>
#include <sstream>
#include <time.h>
#include <cstdlib>

#include "cppa/opt.hpp"
#include "cppa/cppa.hpp"

using namespace std;
using namespace cppa;
using namespace cppa::placeholders;

struct line { string str; };

istream& operator>>(istream& is, line& l) {
    getline(is, l.str);
    return is;
}

any_tuple s_last_line;

any_tuple split_line(const line& l) {
    vector<string> result;
    stringstream strs(l.str);
    string tmp;
    while (getline(strs, tmp, ' ')) {
        if (!tmp.empty()) result.push_back(std::move(tmp));
    }
    s_last_line = any_tuple::view(std::move(result));
    return s_last_line;
}

class client : public event_based_actor {

 public:

    client(string name) : m_name(move(name)) { }

 protected:

    void init() {
        become (
            on(atom("broadcast"), arg_match) >> [=](const string& message) {
                for(auto& dest : joined_groups()) {
                    send(dest, m_name + ": " + message);
                }
            },
            on(atom("join"), arg_match) >> [=](const group_ptr& what) {
                for (auto g : joined_groups()) {
                    cout << "*** leave " << to_string(g) << endl;
                    send(g, m_name + " has left the chatroom");
                    leave(g);
                }
                cout << "*** join " << to_string(what) << endl;
                join(what);
                send(what, m_name + " has entered the chatroom");
            },
            on<string>() >> [=](const string& txt) {
                // don't print own messages
                if (last_sender() != this) cout << txt << endl;
            },
            others() >> [=]() {
                cout << "unexpected: " << to_string(last_dequeued()) << endl;
            }
        );
    }

 private:

    string    m_name;

};

int main(int argc, char** argv) {

    string name;
    string group_id;
    options_description desc;
    bool args_valid = match_stream<string>(argv + 1, argv + argc) (
        on_opt1('n', "name", &desc, "set name") >> rd_arg(name),
        on_opt1('g', "group", &desc, "join group <arg1>") >> rd_arg(group_id),
        on_opt0('h', "help", &desc, "print help") >> print_desc_and_exit(&desc)
    );

    if (!args_valid) print_desc_and_exit(&desc)();

    while (name.empty()) {
        cout << "please enter your name: " << flush;
        if (!getline(cin, name)) {
            cerr << "*** no name given... terminating" << endl;
            return 1;
        }
    }

    cout << "*** starting client, type '/help' for a list of commands" << endl;
    auto client_actor = spawn<client>(name);

    // evaluate group parameters
    if (!group_id.empty()) {
        auto p = group_id.find(':');
        if (p == std::string::npos) {
            cerr << "*** error parsing argument " << group_id
                 << ", expected format: <module_name>:<group_id>";
        }
        else {
            try {
                auto g = group::get(group_id.substr(0, p),
                                    group_id.substr(p + 1));
                send(client_actor, atom("join"), g);
            }
            catch (exception& e) {
                ostringstream err;
                cerr << "*** exception: group::get(\"" << group_id.substr(0, p)
                     << "\", \"" << group_id.substr(p + 1) << "\") failed; "
                     << to_verbose_string(e) << endl;
            }
        }
    }

    istream_iterator<line> lines(cin);
    istream_iterator<line> eof;
    match_each (lines, eof, split_line) (
        on("/join", arg_match) >> [&](const string& mod, const string& id) {
            try {
                send(client_actor, atom("join"), group::get(mod, id));
            }
            catch (exception& e) {
                cerr << "*** exception: " << to_verbose_string(e) << endl;
            }
        },
        on("/quit") >> [&] {
            close(STDIN_FILENO); // close STDIN; causes this match loop to quit
        },
        on<string, anything>().when(_x1.starts_with("/")) >> [&] {
            cout <<  "*** available commands:\n"
                     "    /join <module> <group> join a new chat channel\n"
                     "    /quit                  quit the program\n"
                     "    /help                  print this text\n" << flush;
        },
        others() >> [&] {
            if (s_last_line.size() > 0) {
                string msg = s_last_line.get_as<string>(0);
                for (size_t i = 1; i < s_last_line.size(); ++i) {
                    msg += " ";
                    msg += s_last_line.get_as<string>(i);
                }
                send(client_actor, atom("broadcast"), msg);
            }
        }
    );
    // force actor to quit
    send(client_actor, atom("EXIT"), exit_reason::user_defined);
    await_all_others_done();
    shutdown();
    return 0;
}
<commit_msg>use string for s_last_line rather than any_tuple<commit_after>/******************************************************************************\
 * This example program represents a minimal terminal chat program            *
 * based on group communication.                                              *
 *                                                                            *
 * Setup for a minimal chat between "alice" and "bob":                        *
 * - ./build/bin/group_server -p 4242                                         *
 * - ./build/bin/group_chat -g remote:chatroom@localhost:4242 -n alice        *
 * - ./build/bin/group_chat -g remote:chatroom@localhost:4242 -n bob          *
\******************************************************************************/

#include <set>
#include <map>
#include <vector>
#include <cstdlib>
#include <sstream>
#include <iostream>

#include "cppa/opt.hpp"
#include "cppa/cppa.hpp"

using namespace std;
using namespace cppa;
using namespace cppa::placeholders;

struct line { string str; };

istream& operator>>(istream& is, line& l) {
    getline(is, l.str);
    return is;
}

string s_last_line;

any_tuple split_line(const line& l) {
    istringstream strs(l.str);
    s_last_line = move(l.str);
    string tmp;
    vector<string> result;
    while (getline(strs, tmp, ' ')) {
        if (!tmp.empty()) result.push_back(std::move(tmp));
    }
    return any_tuple::view(std::move(result));
}

class client : public event_based_actor {

 public:

    client(string name) : m_name(move(name)) { }

 protected:

    void init() {
        become (
            on(atom("broadcast"), arg_match) >> [=](const string& message) {
                for(auto& dest : joined_groups()) {
                    send(dest, m_name + ": " + message);
                }
            },
            on(atom("join"), arg_match) >> [=](const group_ptr& what) {
                for (auto g : joined_groups()) {
                    cout << "*** leave " << to_string(g) << endl;
                    send(g, m_name + " has left the chatroom");
                    leave(g);
                }
                cout << "*** join " << to_string(what) << endl;
                join(what);
                send(what, m_name + " has entered the chatroom");
            },
            on<string>() >> [=](const string& txt) {
                // don't print own messages
                if (last_sender() != this) cout << txt << endl;
            },
            others() >> [=]() {
                cout << "unexpected: " << to_string(last_dequeued()) << endl;
            }
        );
    }

 private:

    string    m_name;

};

int main(int argc, char** argv) {

    string name;
    string group_id;
    options_description desc;
    bool args_valid = match_stream<string>(argv + 1, argv + argc) (
        on_opt1('n', "name", &desc, "set name") >> rd_arg(name),
        on_opt1('g', "group", &desc, "join group <arg1>") >> rd_arg(group_id),
        on_opt0('h', "help", &desc, "print help") >> print_desc_and_exit(&desc)
    );

    if (!args_valid) print_desc_and_exit(&desc)();

    while (name.empty()) {
        cout << "please enter your name: " << flush;
        if (!getline(cin, name)) {
            cerr << "*** no name given... terminating" << endl;
            return 1;
        }
    }

    cout << "*** starting client, type '/help' for a list of commands" << endl;
    auto client_actor = spawn<client>(name);

    // evaluate group parameters
    if (!group_id.empty()) {
        auto p = group_id.find(':');
        if (p == std::string::npos) {
            cerr << "*** error parsing argument " << group_id
                 << ", expected format: <module_name>:<group_id>";
        }
        else {
            try {
                auto g = group::get(group_id.substr(0, p),
                                    group_id.substr(p + 1));
                send(client_actor, atom("join"), g);
            }
            catch (exception& e) {
                ostringstream err;
                cerr << "*** exception: group::get(\"" << group_id.substr(0, p)
                     << "\", \"" << group_id.substr(p + 1) << "\") failed; "
                     << to_verbose_string(e) << endl;
            }
        }
    }

    istream_iterator<line> lines(cin);
    istream_iterator<line> eof;
    match_each (lines, eof, split_line) (
        on("/join", arg_match) >> [&](const string& mod, const string& id) {
            try {
                send(client_actor, atom("join"), group::get(mod, id));
            }
            catch (exception& e) {
                cerr << "*** exception: " << to_verbose_string(e) << endl;
            }
        },
        on("/quit") >> [&] {
            close(STDIN_FILENO); // close STDIN; causes this match loop to quit
        },
        on<string, anything>().when(_x1.starts_with("/")) >> [&] {
            cout <<  "*** available commands:\n"
                     "    /join <module> <group> join a new chat channel\n"
                     "    /quit                  quit the program\n"
                     "    /help                  print this text\n" << flush;
        },
        others() >> [&] {
            if (!s_last_line.empty()) {
                send(client_actor, atom("broadcast"), s_last_line);
            }
        }
    );
    // force actor to quit
    send(client_actor, atom("EXIT"), exit_reason::user_defined);
    await_all_others_done();
    shutdown();
    return 0;
}
<|endoftext|>