/// matchEdges - Link every profile counter with an edge.
unsigned ProfileMetadataLoaderPass::matchEdges(Module &M, ProfileData &PB,
                                               ArrayRef<unsigned> Counters) {
  if (Counters.size() == 0) return 0;

  unsigned ReadCount = 0;

  for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
    if (F->isDeclaration()) continue;
    DEBUG(dbgs() << "Loading edges in '" << F->getName() << "'\n");
    readEdge(ReadCount++, PB, PB.getEdge(0, &F->getEntryBlock()), Counters);
    for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
      TerminatorInst *TI = BB->getTerminator();
      for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s) {
        readEdge(ReadCount++, PB, PB.getEdge(BB,TI->getSuccessor(s)),
                 Counters);
      }
    }
  }

  return ReadCount;
}
/// setBranchWeightMetadata - Translate the counter values associated with each
/// edge into branch weights for each conditional branch (a branch with 2 or
/// more desinations).
void ProfileMetadataLoaderPass::setBranchWeightMetadata(Module &M,
                                                        ProfileData &PB) {
  for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
    if (F->isDeclaration()) continue;
    DEBUG(dbgs() << "Setting branch metadata in '" << F->getName() << "'\n");

    for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
      TerminatorInst *TI = BB->getTerminator();
      unsigned NumSuccessors = TI->getNumSuccessors();

      // If there is only one successor then we can not set a branch
      // probability as the target is certain.
      if (NumSuccessors < 2) continue;

      // Load the weights of all edges leading from this terminator.
      DEBUG(dbgs() << "-- Terminator with " << NumSuccessors
                   << " successors:\n");
      SmallVector<uint32_t, 4> Weights(NumSuccessors);
      for (unsigned s = 0 ; s < NumSuccessors ; ++s) {
          ProfileData::Edge edge = PB.getEdge(BB, TI->getSuccessor(s));
          Weights[s] = (uint32_t)PB.getEdgeWeight(edge);
          DEBUG(dbgs() << "---- Edge '" << edge << "' has weight "
                       << Weights[s] << "\n");
      }

      // Set branch weight metadata.  This will set branch probabilities of
      // 100%/0% if that is true of the dynamic execution.
      // BranchProbabilityInfo can account for this when it loads this metadata
      // (it gives the unexectuted branch a weight of 1 for the purposes of
      // probability calculations).
      MDBuilder MDB(TI->getContext());
      MDNode *Node = MDB.createBranchWeights(Weights);
      TI->setMetadata(LLVMContext::MD_prof, Node);
      NumTermsAnnotated++;
    }
  }
}