[PATCH] D12781: PGO IR-level instrumentation infrastructure

Sean Silva via llvm-commits llvm-commits at lists.llvm.org
Tue Dec 1 16:12:31 PST 2015


On Tue, Dec 1, 2015 at 2:44 PM, Xinliang David Li <davidxl at google.com>
wrote:

> > +; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds
>> ([9 x i8], [9 x i8]* @__llvm_profile_name_test_br_1, i32 0, i32 0), i64
>> 25571299074, i32 2, i32 0)
>> > +
>> > +  // Set the hot/cold inline hints based on the count values.
>> > +  void applyFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount)
>> {
>> > +    if (ProgramMaxCount == 0)
>> > +      return;
>> > +    // Threshold of the hot functions.
>> > +    const BranchProbability HotFunctionThreshold(1, 100);
>> > +    // Threshold of the cold functions.
>> > +    const BranchProbability ColdFunctionThreshold(2, 10000);
>> > +    if (EntryCount >= HotFunctionThreshold.scale(ProgramMaxCount))
>> > +      F.addFnAttr(llvm::Attribute::InlineHint);
>> > +    else if (MaxCount <= ColdFunctionThreshold.scale(ProgramMaxCount))
>> > +      F.addFnAttr(llvm::Attribute::Cold);
>>
>> This is more or less a workaround for limitations of the inliner and
>> should eventually be removed in favour of making the inliner smarter,
>> correct?
>>
>>
> yes. Easwaran is working on making the logic migrated to the inliner. Once
> the inliner change is ready, this code together with similar/duplicated
> code in FE and SampleFDO will be removed.
>

This needs a FIXME comment saying that.

-- Sean Silva


>
>
> David
>
>
>
>
>
>
>
>
>> > +  }
>> > +
>> > +public:
>> > +  PGOUseFunc(Function &Func, Module *Modu,
>> > +             BranchProbabilityInfo *BPI_ = nullptr,
>> > +             BlockFrequencyInfo *BFI_ = nullptr)
>> > +      : F(Func), M(Modu), FuncInfo(Func, false, BPI_, BFI_) {}
>> > +
>> > +  // Read counts for the instrumented BB from profile.
>> > +  bool readCounters(IndexedInstrProfReader *PGOReader);
>> > +
>> > +  // Populate the counts for all BBs.
>> > +  void populateCounters();
>> > +
>> > +  // Set the branch weights based on the count values.
>> > +  void setBranchWeights();
>> > +};
>> > +
>> > +// Visit all the edges and assign the count value for the instrumented
>> > +// edges and the BB.
>> > +void PGOUseFunc::setInstrumentedCounts(
>> > +    const std::vector<uint64_t> &CountFromProfile) {
>> > +
>> > +  // Use a worklist as we will update the vector during the iteration.
>> > +  std::vector<PGOUseEdge *> WorkList;
>> > +  for (auto &Ei : FuncInfo.MST.AllEdges)
>> > +    WorkList.push_back(Ei.get());
>> > +
>> > +  uint32_t j = 0;
>> > +  for (auto &Ei : WorkList) {
>>
>> Same as before: j->J, Ei->E.
>>
>> > +    BasicBlock *InstrBB = FuncInfo.getInstrBB(Ei);
>> > +    if (!InstrBB)
>> > +      continue;
>> > +    uint64_t CountValue = CountFromProfile[j++];
>> > +    if (!Ei->Removed) {
>> > +      getBBInfo(InstrBB).setBBInfoCount(CountValue);
>> > +      Ei->setEdgeCount(CountValue);
>> > +      continue;
>> > +    }
>> > +
>> > +    // Need to add two new edges.
>> > +    BasicBlock *SrcBB = const_cast<BasicBlock *>(Ei->SrcBB);
>> > +    BasicBlock *DestBB = const_cast<BasicBlock *>(Ei->DestBB);
>> > +    // Add new edge of SrcBB->InstrBB.
>> > +    PGOUseEdge &NewEdge = FuncInfo.MST.addEdge(SrcBB, InstrBB, 0);
>> > +    NewEdge.setEdgeCount(CountValue);
>> > +    // Add new edge of InstrBB->DestBB.
>> > +    PGOUseEdge &NewEdge1 = FuncInfo.MST.addEdge(InstrBB, DestBB, 0);
>>
>> Why not just reuse the NewEdge variable here?
>>
>> > +    NewEdge1.setEdgeCount(CountValue);
>> > +    NewEdge1.InMST = true;
>> > +    getBBInfo(InstrBB).setBBInfoCount(CountValue);
>> > +  }
>> > +}
>> > +
>> > +// Set the count value for the unknown edge. There should be one and
>> only one
>> > +// unknown edge in Edges vector.
>> > +void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) {
>> > +  for (auto &Ei : Edges) {
>> > +    if (Ei->CountValid)
>> > +      continue;
>> > +    Ei->setEdgeCount(Value);
>> > +
>> > +    getBBInfo(Ei->SrcBB).UnknownCountOutEdge--;
>> > +    getBBInfo(Ei->DestBB).UnknownCountInEdge--;
>> > +    return;
>> > +  }
>> > +  llvm_unreachable("Cannot find the unknown count edge");
>> > +}
>> > +
>> > +// Read the profile from ProfileFileName and assign the value to the
>> > +// instrumented BB and the edges. This function also updates
>> ProgramMaxCount.
>> > +// Return true if the profile are successfully read, and false on
>> errors.
>> > +bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader) {
>> > +  auto &Ctx = M->getContext();
>> > +  ErrorOr<InstrProfRecord> Result =
>> > +      PGOReader->getInstrProfRecord(FuncInfo.FuncName,
>> FuncInfo.FunctionHash);
>> > +  if (std::error_code EC = Result.getError()) {
>> > +    if (EC == instrprof_error::unknown_function)
>> > +      NumOfPGOMissing++;
>> > +    else if (EC == instrprof_error::hash_mismatch ||
>> > +             EC == llvm::instrprof_error::malformed)
>> > +      NumOfPGOMismatch++;
>> > +
>> > +    std::string Msg = EC.message() + std::string(" ") +
>> F.getName().str();
>> > +    Ctx.diagnose(
>> > +        DiagnosticInfoPGOProfile(M->getName().data(), Msg,
>> DS_Warning));
>> > +    return false;
>> > +  }
>> > +  std::vector<uint64_t> &CountFromProfile = Result.get().Counts;
>> > +
>> > +  NumOfPGOFunc++;
>> > +  DEBUG(dbgs() << CountFromProfile.size() << " counts\n");
>> > +  uint64_t ValueSum = 0;
>> > +  for (unsigned i = 0, e = CountFromProfile.size(); i < e; i++) {
>> > +    DEBUG(dbgs() << "  " << i << ": " << CountFromProfile[i] << "\n");
>> > +    ValueSum += CountFromProfile[i];
>> > +  }
>> > +
>> > +  DEBUG(dbgs() << "SUM =  " << ValueSum << "\n");
>> > +
>> > +  getBBInfo(nullptr).UnknownCountOutEdge = 2;
>> > +  getBBInfo(nullptr).UnknownCountInEdge = 2;
>> > +
>> > +  setInstrumentedCounts(CountFromProfile);
>> > +  ProgramMaxCount = PGOReader->getMaximumFunctionCount();
>> > +  return true;
>> > +}
>> > +
>> > +// Populate the counters from instrumented BBs to all BBs.
>> > +// In the end of this operation, all BBs should have a valid count
>> value.
>> > +void PGOUseFunc::populateCounters() {
>> > +  // First set up Count variable for all BBs.
>> > +  for (auto &Ei : FuncInfo.MST.AllEdges) {
>> > +    if (Ei->Removed)
>> > +      continue;
>> > +
>> > +    const BasicBlock *SrcBB = Ei->SrcBB;
>> > +    const BasicBlock *DestBB = Ei->DestBB;
>> > +    UseBBInfo &SrcInfo = getBBInfo(SrcBB);
>> > +    UseBBInfo &DestInfo = getBBInfo(DestBB);
>> > +    SrcInfo.OutEdges.push_back(Ei.get());
>> > +    DestInfo.InEdges.push_back(Ei.get());
>> > +    SrcInfo.UnknownCountOutEdge++;
>> > +    DestInfo.UnknownCountInEdge++;
>> > +
>> > +    if (!Ei->CountValid)
>> > +      continue;
>> > +    DestInfo.UnknownCountInEdge--;
>> > +    SrcInfo.UnknownCountOutEdge--;
>> > +  }
>> > +
>> > +  bool Changes = true;
>> > +  unsigned NumPasses = 0;
>> > +  while (Changes) {
>> > +    NumPasses++;
>> > +    Changes = false;
>> > +
>> > +    // For efficient traversal, it's better to start from the end as
>> most
>> > +    // of the instrumented edges are at the end.
>> > +    for (auto &BB : reverse(F)) {
>> > +      UseBBInfo &Count = getBBInfo(&BB);
>> > +      if (!Count.CountValid) {
>> > +        if (Count.UnknownCountOutEdge == 0) {
>> > +          Count.CountValue = sumEdgeCount(Count.OutEdges);
>> > +          Count.CountValid = true;
>> > +          Changes = true;
>> > +        } else if (Count.UnknownCountInEdge == 0) {
>> > +          Count.CountValue = sumEdgeCount(Count.InEdges);
>> > +          Count.CountValid = true;
>> > +          Changes = true;
>> > +        }
>> > +      }
>> > +      if (Count.CountValid) {
>> > +        if (Count.UnknownCountOutEdge == 1) {
>> > +          uint64_t Total = Count.CountValue -
>> sumEdgeCount(Count.OutEdges);
>> > +          setEdgeCount(Count.OutEdges, Total);
>> > +          Changes = true;
>> > +        }
>> > +        if (Count.UnknownCountInEdge == 1) {
>> > +          uint64_t Total = Count.CountValue -
>> sumEdgeCount(Count.InEdges);
>> > +          setEdgeCount(Count.InEdges, Total);
>> > +          Changes = true;
>> > +        }
>> > +      }
>> > +    }
>> > +  }
>> > +
>> > +  DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n");
>> > +  // Assert every BB has a valid counter.
>> > +  uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue;
>> > +  uint64_t FuncMaxCount = FuncEntryCount;
>> > +  for (auto &BB : F) {
>> > +    assert(getBBInfo(&BB).CountValid && "BB count is not valid");
>> > +    uint64_t Count = getBBInfo(&BB).CountValue;
>> > +    if (Count > FuncMaxCount)
>> > +      FuncMaxCount = Count;
>> > +  }
>> > +  applyFunctionAttributes(FuncEntryCount, FuncMaxCount);
>> > +
>> > +  DEBUG(FuncInfo.dumpInfo("after reading profile."));
>> > +}
>> > +
>> > +// Assign the scaled count values to the BB with multiple out edges.
>> > +void PGOUseFunc::setBranchWeights() {
>> > +  // Generate MD_prof metadata for every branch instruction.
>> > +  DEBUG(dbgs() << "\nSetting branch weights.\n");
>> > +  MDBuilder MDB(M->getContext());
>> > +  for (auto &BB : F) {
>> > +    TerminatorInst *TI = BB.getTerminator();
>> > +    if (TI->getNumSuccessors() < 2)
>> > +      continue;
>> > +    if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
>> > +      continue;
>> > +    if (getBBInfo(&BB).CountValue == 0)
>> > +      continue;
>> > +
>> > +    // We have a non-zero Branch BB.
>> > +    const UseBBInfo &BBCountInfo = getBBInfo(&BB);
>> > +    unsigned Size = BBCountInfo.OutEdges.size();
>> > +    SmallVector<unsigned, 2> EdgeCounts(Size, 0);
>> > +    uint64_t MaxCount = 0;
>> > +    for (unsigned s = 0; s < Size; s++) {
>> > +      const PGOUseEdge *E = BBCountInfo.OutEdges[s];
>> > +      const BasicBlock *SrcBB = E->SrcBB;
>> > +      const BasicBlock *DestBB = E->DestBB;
>> > +      if (DestBB == 0)
>> > +        continue;
>> > +      unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
>> > +      uint64_t EdgeCount = E->CountValue;
>> > +      if (EdgeCount > MaxCount)
>> > +        MaxCount = EdgeCount;
>> > +      EdgeCounts[SuccNum] = EdgeCount;
>> > +    }
>> > +    assert(MaxCount > 0 && "Bad max count");
>> > +    uint64_t Scale = calculateCountScale(MaxCount);
>> > +    SmallVector<unsigned, 4> Weights;
>> > +    for (const auto &ECI : EdgeCounts)
>> > +      Weights.push_back(scaleBranchCount(ECI, Scale));
>> > +
>> > +    TI->setMetadata(llvm::LLVMContext::MD_prof,
>> > +                    MDB.createBranchWeights(Weights));
>> > +    DEBUG(dbgs() << "Weight is: "; for (const auto &W
>> > +                                        : Weights) dbgs()
>> > +                                   << W << " ";
>> > +          dbgs() << "\n";);
>>
>> This is formatted really strangely. It's possible that clang-format
>> doesn't know how to deal with this code-in-DEBUG() stuff and you just
>> need to format this manually (or file a bug on clang-format ;)
>>
>> > +  }
>> > +}
>> > +} // end anonymous namespace
>> > +
>> > +bool PGOInstrumentationGen::runOnModule(Module &M) {
>> > +  for (auto &F : M) {
>> > +    if (F.isDeclaration())
>> > +      continue;
>> > +    BranchProbabilityInfo *BPI =
>> > +        &(getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI());
>> > +    BlockFrequencyInfo *BFI =
>> > +        &(getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI());
>> > +    instrumentOneFunc(F, &M, BPI, BFI);
>> > +  }
>> > +  return true;
>> > +}
>> > +
>> > +static void setPGOCountOnFunc(PGOUseFunc &Func,
>> > +                              IndexedInstrProfReader *PGOReader) {
>> > +  if (Func.readCounters(PGOReader)) {
>> > +    Func.populateCounters();
>> > +    Func.setBranchWeights();
>> > +  }
>> > +}
>> > +
>> > +bool PGOInstrumentationUse::runOnModule(Module &M) {
>> > +  DEBUG(dbgs() << "Read in profile counters: ");
>> > +  auto &Ctx = M.getContext();
>> > +  // Read the counter array from file.
>> > +  auto ReaderOrErr = IndexedInstrProfReader::create(ProfileFileName);
>> > +  if (std::error_code EC = ReaderOrErr.getError()) {
>> > +    Ctx.diagnose(
>> > +        DiagnosticInfoPGOProfile(ProfileFileName.data(),
>> EC.message()));
>> > +    return false;
>> > +  }
>> > +
>> > +  PGOReader = std::move(ReaderOrErr.get());
>> > +  if (!PGOReader) {
>> > +    Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(),
>> > +                                          "Cannot get PGOReader"));
>> > +    return false;
>> > +  }
>> > +
>> > +  for (auto &F : M) {
>> > +    if (F.isDeclaration())
>> > +      continue;
>> > +    BranchProbabilityInfo *BPI =
>> > +        &(getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI());
>> > +    BlockFrequencyInfo *BFI =
>> > +        &(getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI());
>> > +    PGOUseFunc Func(F, &M, BPI, BFI);
>> > +    setPGOCountOnFunc(Func, PGOReader.get());
>> > +  }
>> > +  return true;
>> > +}
>> > Index: lib/Transforms/Instrumentation/LLVMBuild.txt
>> > ===================================================================
>> > --- lib/Transforms/Instrumentation/LLVMBuild.txt
>> > +++ lib/Transforms/Instrumentation/LLVMBuild.txt
>> > @@ -19,4 +19,4 @@
>> >  type = Library
>> >  name = Instrumentation
>> >  parent = Transforms
>> > -required_libraries = Analysis Core MC Support TransformUtils
>> > +required_libraries = Analysis Core MC Support TransformUtils
>> ProfileData
>> > Index: lib/Transforms/Instrumentation/Instrumentation.cpp
>> > ===================================================================
>> > --- lib/Transforms/Instrumentation/Instrumentation.cpp
>> > +++ lib/Transforms/Instrumentation/Instrumentation.cpp
>> > @@ -60,6 +60,8 @@
>> >    initializeAddressSanitizerModulePass(Registry);
>> >    initializeBoundsCheckingPass(Registry);
>> >    initializeGCOVProfilerPass(Registry);
>> > +  initializePGOInstrumentationGenPass(Registry);
>> > +  initializePGOInstrumentationUsePass(Registry);
>> >    initializeInstrProfilingPass(Registry);
>> >    initializeMemorySanitizerPass(Registry);
>> >    initializeThreadSanitizerPass(Registry);
>> > Index: lib/Transforms/Instrumentation/CMakeLists.txt
>> > ===================================================================
>> > --- lib/Transforms/Instrumentation/CMakeLists.txt
>> > +++ lib/Transforms/Instrumentation/CMakeLists.txt
>> > @@ -6,6 +6,7 @@
>> >    MemorySanitizer.cpp
>> >    Instrumentation.cpp
>> >    InstrProfiling.cpp
>> > +  PGOInstrumentation.cpp
>> >    SafeStack.cpp
>> >    SanitizerCoverage.cpp
>> >    ThreadSanitizer.cpp
>> > Index: lib/Transforms/Instrumentation/CFGMST.h
>> > ===================================================================
>> > --- /dev/null
>> > +++ lib/Transforms/Instrumentation/CFGMST.h
>> > @@ -0,0 +1,211 @@
>> > +//===-- CFGMST.h - Minimum Spanning Tree for CFG -------*- C++ -*-===//
>> > +//
>> > +//                      The LLVM Compiler Infrastructure
>> > +//
>> > +// This file is distributed under the University of Illinois Open
>> Source
>> > +// License. See LICENSE.TXT for details.
>> > +//
>> >
>> +//===----------------------------------------------------------------------===//
>> > +//
>> > +// This file implements Union-find algorithm to compute Minimum
>> Spanning Tree
>> > +// for a given CFG.
>> > +//
>> >
>> +//===----------------------------------------------------------------------===//
>> > +
>> > +#include "llvm/ADT/DenseMap.h"
>> > +#include "llvm/ADT/STLExtras.h"
>> > +#include "llvm/Analysis/BlockFrequencyInfo.h"
>> > +#include "llvm/Analysis/BranchProbabilityInfo.h"
>> > +#include "llvm/Analysis/CFG.h"
>> > +#include "llvm/Support/BranchProbability.h"
>> > +#include "llvm/Support/Debug.h"
>> > +#include "llvm/Support/raw_ostream.h"
>> > +#include "llvm/Transforms/Utils/BasicBlockUtils.h"
>> > +#include <string>
>> > +#include <utility>
>> > +#include <vector>
>> > +
>> > +namespace llvm {
>> > +
>> > +#define DEBUG_TYPE "cfgmst"
>> > +
>> > +template <class Edge, class BBInfo> class CFGMST {
>> > +public:
>> > +  Function &F;
>> > +
>> > +  // Store all the edges in CFG. It may contain some stale edges
>> > +  // when Removed is set.
>>
>> Might as well use doc comments here.
>>
>> > +  std::vector<std::unique_ptr<Edge>> AllEdges;
>> > +
>> > +  // This map records the auxiliary information for each BB.
>> > +  DenseMap<const BasicBlock *, std::unique_ptr<BBInfo>> BBInfos;
>> > +
>> > +  // Find the root group of the G and compress the path from G to the
>> root.
>> > +  BBInfo *findAndCompressGroup(BBInfo *G) {
>> > +    if (G->Group != G)
>> > +      G->Group = findAndCompressGroup(static_cast<BBInfo *>(G->Group));
>> > +    return static_cast<BBInfo *>(G->Group);
>> > +  }
>> > +
>> > +  // Union BB1 and BB2 into the same group and return true.
>> > +  // Returns false if BB1 and BB2 are already in the same group.
>> > +  bool unionGroups(const BasicBlock *BB1, const BasicBlock *BB2) {
>> > +    BBInfo *BB1G = findAndCompressGroup(&getBBInfo(BB1));
>> > +    BBInfo *BB2G = findAndCompressGroup(&getBBInfo(BB2));
>> > +
>> > +    if (BB1G == BB2G)
>> > +      return false;
>> > +
>> > +    // Make the smaller rank tree a direct child or the root of high
>> rank tree.
>> > +    if (BB1G->Rank < BB2G->Rank)
>> > +      BB1G->Group = BB2G;
>> > +    else {
>> > +      BB2G->Group = BB1G;
>> > +      // If the ranks are the same, increment root of one tree by one.
>> > +      if (BB1G->Rank == BB2G->Rank)
>> > +        BB1G->Rank++;
>> > +    }
>> > +    return true;
>> > +  }
>> > +
>> > +  // Give BB, return the auxiliary information.
>> > +  BBInfo &getBBInfo(const BasicBlock *BB) const {
>> > +    auto It = BBInfos.find(BB);
>> > +    assert(It->second.get() != nullptr);
>> > +    return *It->second.get();
>> > +  }
>> > +
>> > +  // Traverse the CFG using a stack. Find all the edges and assign the
>> weight.
>> > +  // Edges with large weight will be put into MST first so they are
>> less likely
>> > +  // to be instrumented.
>> > +  void buildEdges() {
>> > +    DEBUG(dbgs() << "Build Edge on " << F.getName() << "\n");
>> > +
>> > +    const BasicBlock *BB = &(F.getEntryBlock());
>> > +    // Add a fake edge to the entry.
>> > +    addEdge(nullptr, BB, BFI->getEntryFreq());
>> > +
>> > +    // Special handling for single BB functions.
>> > +    if (succ_empty(BB)) {
>> > +      addEdge(BB, nullptr, BFI->getEntryFreq());
>> > +      return;
>> > +    }
>> > +
>> > +    static const uint32_t CriticalEdgeMultiplier = 1000;
>> > +
>> > +    for (Function::iterator BB = F.begin(), E = F.end(); BB != E;
>> ++BB) {
>> > +      TerminatorInst *TI = BB->getTerminator();
>> > +      uint64_t BBWeight = BFI->getBlockFreq(&*BB).getFrequency();
>> > +      uint64_t Weight;
>> > +      if (int successors = TI->getNumSuccessors()) {
>> > +        for (int i = 0; i != successors; ++i) {
>> > +          BasicBlock *TargetBB = TI->getSuccessor(i);
>> > +          bool Critical = isCriticalEdge(TI, i);
>> > +          uint64_t scaleFactor = BBWeight;
>> > +          if (Critical) {
>> > +            if (scaleFactor < UINT64_MAX / CriticalEdgeMultiplier)
>> > +              scaleFactor *= CriticalEdgeMultiplier;
>> > +            else
>> > +              scaleFactor = UINT64_MAX;
>> > +          }
>> > +          Weight = BPI->getEdgeProbability(&*BB,
>> TargetBB).scale(scaleFactor);
>> > +          addEdge(&*BB, TargetBB, Weight).IsCritical = Critical;
>> > +          DEBUG(dbgs() << "  Edge: from " << BB->getName() << " to "
>> > +                       << TargetBB->getName() << "  w=" << Weight <<
>> "\n");
>> > +        }
>> > +      } else {
>> > +        addEdge(&*BB, nullptr, BBWeight);
>> > +        DEBUG(dbgs() << "  Edge: from " << BB->getName() << " to exit"
>> > +                     << " w = " << BBWeight << "\n");
>> > +      }
>> > +    }
>> > +  }
>> > +
>> > +  // Sort CFG edges based on its weight.
>> > +  void sortEdgesByWeight() {
>> > +    std::stable_sort(
>> > +        AllEdges.begin(), AllEdges.end(),
>> > +        [](const std::unique_ptr<Edge> &Edge1, const
>> std::unique_ptr<Edge> &Edge2) {
>> > +          return Edge1->Weight > Edge2->Weight;
>> > +        });
>> > +  }
>> > +
>> > +  // Traverse all the edges and compute the Minimum Weight Spanning
>> Tree
>> > +  // using union-find algorithm.
>> > +  void computeMinimumSpanningTree() {
>> > +    // First, put all the critical edge with landing-pad as the Dest
>> to MST.
>> > +    // This works around the insufficient support of critical edges
>> split
>> > +    // when destination BB is a landing pad.
>> > +    for (auto &Ei : AllEdges) {
>> > +      if (Ei->Removed)
>> > +        continue;
>> > +      if (Ei->IsCritical) {
>> > +        if (Ei->DestBB && Ei->DestBB->isLandingPad()) {
>> > +          if (unionGroups(Ei->SrcBB, Ei->DestBB))
>> > +            Ei->InMST = true;
>> > +        }
>> > +      }
>> > +    }
>> > +
>> > +    for (auto &Ei : AllEdges) {
>> > +      if (Ei->Removed)
>> > +        continue;
>> > +      if (unionGroups(Ei->SrcBB, Ei->DestBB))
>> > +        Ei->InMST = true;
>> > +    }
>> > +  }
>> > +
>> > +  // Dump the Debug information about the instrumentation.
>> > +  void dumpEdges(raw_ostream &OS, const StringRef Message =
>> StringRef()) const {
>> > +    if (!Message.empty())
>> > +      OS << Message << "\n";
>> > +    OS << "  Number of Basic Blocks: " << BBInfos.size() << "\n";
>> > +    for (auto &BI : BBInfos) {
>> > +      const BasicBlock *BB = BI.first;
>> > +      OS << "  BB: " << (BB == nullptr ? "FakeNode" : BB->getName())
>> << "  "
>> > +         << BI.second->infoString() << "\n";
>> > +    }
>> > +
>> > +    OS << "  Number of Edges: " << AllEdges.size()
>> > +       << " (*: Instrument, C: CriticalEdge, -: Removed)\n";
>> > +    uint32_t Count = 0;
>> > +    for (auto &EI : AllEdges) {
>> > +      OS << "  Edge " << Count++ << ": " << getBBInfo(EI->SrcBB).Index
>> << "-->"
>> > +         << getBBInfo(EI->DestBB).Index << EI->infoString() << "\n";
>> > +    };
>> > +  }
>> > +
>> > +  // Add an edge to AllEdges with weight W.
>> > +  Edge &addEdge(const BasicBlock *Src, const BasicBlock *Dest,
>> uint64_t W) {
>> > +    uint32_t Index = BBInfos.size();
>> > +    auto Iter = BBInfos.end();
>> > +    bool Inserted;
>> > +    std::tie(Iter, Inserted) = BBInfos.insert(std::make_pair(Src,
>> nullptr));
>> > +    if (Inserted) {
>> > +      // Newly inserted, update the real info.
>> > +      Iter->second = std::move(llvm::make_unique<BBInfo>(Index));
>> > +      Index++;
>> > +    }
>> > +    std::tie(Iter, Inserted) = BBInfos.insert(std::make_pair(Dest,
>> nullptr));
>> > +    if (Inserted)
>> > +      // Newly inserted, update the real info.
>> > +      Iter->second = std::move(llvm::make_unique<BBInfo>(Index));
>> > +    AllEdges.emplace_back(new Edge(Src, Dest, W));
>> > +    return *AllEdges.back();
>> > +  }
>> > +
>> > +  BranchProbabilityInfo *BPI;
>> > +  BlockFrequencyInfo *BFI;
>> > +
>> > +public:
>> > +  CFGMST(Function &Func, BranchProbabilityInfo *BPI_ = nullptr,
>> > +         BlockFrequencyInfo *BFI_ = nullptr)
>> > +      : F(Func), BPI(BPI_), BFI(BFI_) {
>> > +    buildEdges();
>> > +    sortEdgesByWeight();
>> > +    computeMinimumSpanningTree();
>> > +  }
>> > +};
>> > +
>> > +#undef DEBUG_TYPE // "cfgmst"
>> > +} // end namespace llvm
>> > Index: lib/IR/DiagnosticInfo.cpp
>> > ===================================================================
>> > --- lib/IR/DiagnosticInfo.cpp
>> > +++ lib/IR/DiagnosticInfo.cpp
>> > @@ -132,6 +132,12 @@
>> >    DP << getMsg();
>> >  }
>> >
>> > +void DiagnosticInfoPGOProfile::print(DiagnosticPrinter &DP) const {
>> > +  if (getFileName())
>> > +    DP << getFileName() << ": ";
>> > +  DP << getMsg();
>> > +}
>> > +
>> >  bool DiagnosticInfoOptimizationBase::isLocationAvailable() const {
>> >    return getDebugLoc();
>> >  }
>> > Index: include/llvm/Transforms/Instrumentation.h
>> > ===================================================================
>> > --- include/llvm/Transforms/Instrumentation.h
>> > +++ include/llvm/Transforms/Instrumentation.h
>> > @@ -79,6 +79,11 @@
>> >  ModulePass *createGCOVProfilerPass(const GCOVOptions &Options =
>> >                                     GCOVOptions::getDefault());
>> >
>> > +// PGO Instrumention
>> > +ModulePass *createPGOInstrumentationGenPass();
>> > +ModulePass *
>> > +createPGOInstrumentationUsePass(StringRef Filename = StringRef(""));
>> > +
>> >  /// Options for the frontend instrumentation based profiling pass.
>> >  struct InstrProfOptions {
>> >    InstrProfOptions() : NoRedZone(false) {}
>> > @@ -149,6 +154,24 @@
>> >  /// protect against stack-based overflow vulnerabilities.
>> >  FunctionPass *createSafeStackPass(const TargetMachine *TM = nullptr);
>> >
>> > +/// \brief Calculate what to divide by to scale counts.
>> > +///
>> > +/// Given the maximum count, calculate a divisor that will scale all
>> the
>> > +/// weights to strictly less than UINT32_MAX.
>> > +static inline uint64_t calculateCountScale(uint64_t MaxCount) {
>> > +  return MaxCount < UINT32_MAX ? 1 : MaxCount / UINT32_MAX + 1;
>> > +}
>> > +
>> > +/// \brief Scale an individual branch count.
>> > +///
>> > +/// Scale a 64-bit weight down to 32-bits using \c Scale.
>> > +///
>> > +static inline uint32_t scaleBranchCount(uint64_t Count, uint64_t
>> Scale) {
>> > +  uint64_t Scaled = Count / Scale;
>> > +  assert(Scaled <= UINT32_MAX && "overflow 32-bits");
>> > +  return Scaled;
>> > +}
>> > +
>> >  } // End llvm namespace
>> >
>> >  #endif
>> > Index: include/llvm/LinkAllPasses.h
>> > ===================================================================
>> > --- include/llvm/LinkAllPasses.h
>> > +++ include/llvm/LinkAllPasses.h
>> > @@ -85,6 +85,8 @@
>> >        (void) llvm::createDomOnlyViewerPass();
>> >        (void) llvm::createDomViewerPass();
>> >        (void) llvm::createGCOVProfilerPass();
>> > +      (void) llvm::createPGOInstrumentationGenPass();
>> > +      (void) llvm::createPGOInstrumentationUsePass();
>> >        (void) llvm::createInstrProfilingPass();
>> >        (void) llvm::createFunctionInliningPass();
>> >        (void) llvm::createAlwaysInlinerPass();
>> > Index: include/llvm/InitializePasses.h
>> > ===================================================================
>> > --- include/llvm/InitializePasses.h
>> > +++ include/llvm/InitializePasses.h
>> > @@ -117,6 +117,8 @@
>> >  void initializeExpandPostRAPass(PassRegistry&);
>> >  void initializeAAResultsWrapperPassPass(PassRegistry &);
>> >  void initializeGCOVProfilerPass(PassRegistry&);
>> > +void initializePGOInstrumentationGenPass(PassRegistry&);
>> > +void initializePGOInstrumentationUsePass(PassRegistry&);
>> >  void initializeInstrProfilingPass(PassRegistry&);
>> >  void initializeAddressSanitizerPass(PassRegistry&);
>> >  void initializeAddressSanitizerModulePass(PassRegistry&);
>> > Index: include/llvm/IR/DiagnosticInfo.h
>> > ===================================================================
>> > --- include/llvm/IR/DiagnosticInfo.h
>> > +++ include/llvm/IR/DiagnosticInfo.h
>> > @@ -60,6 +60,7 @@
>> >    DK_OptimizationRemarkAnalysisAliasing,
>> >    DK_OptimizationFailure,
>> >    DK_MIRParser,
>> > +  DK_PGOProfile,
>> >    DK_FirstPluginKind
>> >  };
>> >
>> > @@ -250,6 +251,31 @@
>> >    const Twine &Msg;
>> >  };
>> >
>> > +/// Diagnostic information for the PGO profiler.
>> > +class DiagnosticInfoPGOProfile : public DiagnosticInfo {
>> > +public:
>> > +  DiagnosticInfoPGOProfile(const char *FileName, const Twine &Msg,
>> > +                           DiagnosticSeverity Severity = DS_Error)
>> > +      : DiagnosticInfo(DK_PGOProfile, Severity), FileName(FileName),
>> Msg(Msg) {}
>> > +
>> > +  /// \see DiagnosticInfo::print.
>> > +  void print(DiagnosticPrinter &DP) const override;
>> > +
>> > +  static bool classof(const DiagnosticInfo *DI) {
>> > +    return DI->getKind() == DK_PGOProfile;
>> > +  }
>> > +
>> > +  const char *getFileName() const { return FileName; }
>> > +  const Twine &getMsg() const { return Msg; }
>> > +
>> > +private:
>> > +  /// Name of the input file associated with this diagnostic.
>> > +  const char *FileName;
>> > +
>> > +  /// Message to report.
>> > +  const Twine &Msg;
>> > +};
>> > +
>> >  /// Common features for diagnostics dealing with optimization remarks.
>> >  class DiagnosticInfoOptimizationBase : public DiagnosticInfo {
>> >  public:
>>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20151201/0902c19d/attachment.html>


More information about the llvm-commits mailing list