/// Returns a generated guard statement that checks whether the given lhs and
/// rhs expressions are equal. If not equal, the else block for the guard
/// returns false.
/// \p C The AST context.
/// \p lhsExpr The first expression to compare for equality.
/// \p rhsExpr The second expression to compare for equality.
static GuardStmt *returnIfNotEqualGuard(ASTContext &C,
                                        Expr *lhsExpr,
                                        Expr *rhsExpr) {
  SmallVector<StmtConditionElement, 1> conditions;
  SmallVector<ASTNode, 1> statements;

  // First, generate the statement for the body of the guard.
  // return false
  auto falseExpr = new (C) BooleanLiteralExpr(false, SourceLoc(),
                                              /*Implicit*/true);
  auto returnStmt = new (C) ReturnStmt(SourceLoc(), falseExpr);
  statements.emplace_back(ASTNode(returnStmt));

  // Next, generate the condition being checked.
  // lhs == rhs
  auto cmpFuncExpr = new (C) UnresolvedDeclRefExpr(
    DeclName(C.getIdentifier("==")), DeclRefKind::BinaryOperator,
    DeclNameLoc());
  auto cmpArgsTuple = TupleExpr::create(C, SourceLoc(),
                                        { lhsExpr, rhsExpr },
                                        { }, { }, SourceLoc(),
                                        /*HasTrailingClosure*/false,
                                        /*Implicit*/true);
  auto cmpExpr = new (C) BinaryExpr(cmpFuncExpr, cmpArgsTuple,
                                    /*Implicit*/true);
  conditions.emplace_back(cmpExpr);

  // Build and return the complete guard statement.
  // guard lhs == rhs else { return false }
  auto body = BraceStmt::create(C, SourceLoc(), statements, SourceLoc());
  return new (C) GuardStmt(SourceLoc(), C.AllocateCopy(conditions), body);
}
예제 #2
0
bool IRTranslator::translateCall(const CallInst &CI) {
  auto TII = MIRBuilder.getMF().getTarget().getIntrinsicInfo();
  const Function &F = *CI.getCalledFunction();
  Intrinsic::ID ID = F.getIntrinsicID();
  if (TII && ID == Intrinsic::not_intrinsic)
    ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(&F));

  assert(ID != Intrinsic::not_intrinsic && "FIXME: support real calls");

  // Need types (starting with return) & args.
  SmallVector<LLT, 4> Tys;
  Tys.emplace_back(*CI.getType());
  for (auto &Arg : CI.arg_operands())
    Tys.emplace_back(*Arg->getType());

  unsigned Res = CI.getType()->isVoidTy() ? 0 : getOrCreateVReg(CI);
  MachineInstrBuilder MIB =
      MIRBuilder.buildIntrinsic(Tys, ID, Res, !CI.doesNotAccessMemory());

  for (auto &Arg : CI.arg_operands()) {
    if (ConstantInt *CI = dyn_cast<ConstantInt>(Arg))
      MIB.addImm(CI->getSExtValue());
    else
      MIB.addUse(getOrCreateVReg(*Arg));
  }
  return true;
}
/// Emit column labels for the table in the index.
static void emitColumnLabelsForIndex(raw_ostream &OS) {
  SmallVector<std::string, 4> Columns;
  Columns.emplace_back(tag("td", "Filename", "column-entry-left"));
  for (const char *Label : {"Function Coverage", "Instantiation Coverage",
                            "Line Coverage", "Region Coverage"})
    Columns.emplace_back(tag("td", Label, "column-entry"));
  OS << tag("tr", join(Columns.begin(), Columns.end(), ""));
}
예제 #4
0
/// Render a file coverage summary (\p FCS) in a table row. If \p IsTotals is
/// false, link the summary to \p SF.
void CoveragePrinterHTML::emitFileSummary(raw_ostream &OS, StringRef SF,
                                          const FileCoverageSummary &FCS,
                                          bool IsTotals) const {
  SmallVector<std::string, 8> Columns;

  // Format a coverage triple and add the result to the list of columns.
  auto AddCoverageTripleToColumn = [&Columns](unsigned Hit, unsigned Total,
                                              float Pctg) {
    std::string S;
    {
      raw_string_ostream RSO{S};
      if (Total)
        RSO << format("%*.2f", 7, Pctg) << "% ";
      else
        RSO << "- ";
      RSO << '(' << Hit << '/' << Total << ')';
    }
    const char *CellClass = "column-entry-yellow";
    if (Hit == Total)
      CellClass = "column-entry-green";
    else if (Pctg < 80.0)
      CellClass = "column-entry-red";
    Columns.emplace_back(tag("td", tag("pre", S), CellClass));
  };

  // Simplify the display file path, and wrap it in a link if requested.
  std::string Filename;
  if (IsTotals) {
    Filename = SF;
  } else {
    Filename = buildLinkToFile(SF, FCS);
  }

  Columns.emplace_back(tag("td", tag("pre", Filename)));
  AddCoverageTripleToColumn(FCS.FunctionCoverage.getExecuted(),
                            FCS.FunctionCoverage.getNumFunctions(),
                            FCS.FunctionCoverage.getPercentCovered());
  if (Opts.ShowInstantiationSummary)
    AddCoverageTripleToColumn(FCS.InstantiationCoverage.getExecuted(),
                              FCS.InstantiationCoverage.getNumFunctions(),
                              FCS.InstantiationCoverage.getPercentCovered());
  AddCoverageTripleToColumn(FCS.LineCoverage.getCovered(),
                            FCS.LineCoverage.getNumLines(),
                            FCS.LineCoverage.getPercentCovered());
  if (Opts.ShowRegionSummary)
    AddCoverageTripleToColumn(FCS.RegionCoverage.getCovered(),
                              FCS.RegionCoverage.getNumRegions(),
                              FCS.RegionCoverage.getPercentCovered());

  if (IsTotals)
    OS << tag("tr", join(Columns.begin(), Columns.end(), ""), "light-row-bold");
  else
    OS << tag("tr", join(Columns.begin(), Columns.end(), ""), "light-row");
}
예제 #5
0
void InstructionTables::run() {
  ArrayRef<uint64_t> Masks = IB.getProcResourceMasks();
  SmallVector<std::pair<ResourceRef, double>, 4> UsedResources;

  // Create an instruction descriptor for every instruction in the sequence.
  while (S.hasNext()) {
    UsedResources.clear();
    SourceRef SR = S.peekNext();
    std::unique_ptr<Instruction> Inst = IB.createInstruction(*SR.second);
    const InstrDesc &Desc = Inst->getDesc();
    // Now identify the resources consumed by this instruction.
    for (const std::pair<uint64_t, ResourceUsage> Resource : Desc.Resources) {
      // Skip zero-cycle resources (i.e. unused resources).
      if (!Resource.second.size())
        continue;
      double Cycles = static_cast<double>(Resource.second.size());
      unsigned Index =
          std::distance(Masks.begin(), std::find(Masks.begin(), Masks.end(),
                                                 Resource.first));
      const MCProcResourceDesc &ProcResource = *SM.getProcResource(Index);
      unsigned NumUnits = ProcResource.NumUnits;
      if (!ProcResource.SubUnitsIdxBegin) {
        // The number of cycles consumed by each unit.
        Cycles /= NumUnits;
        for (unsigned I = 0, E = NumUnits; I < E; ++I) {
          ResourceRef ResourceUnit = std::make_pair(Index, 1U << I);
          UsedResources.emplace_back(std::make_pair(ResourceUnit, Cycles));
        }
        continue;
      }

      // This is a group. Obtain the set of resources contained in this
      // group. Some of these resources may implement multiple units.
      // Uniformly distribute Cycles across all of the units.
      for (unsigned I1 = 0; I1 < NumUnits; ++I1) {
        unsigned SubUnitIdx = ProcResource.SubUnitsIdxBegin[I1];
        const MCProcResourceDesc &SubUnit = *SM.getProcResource(SubUnitIdx);
        // Compute the number of cycles consumed by each resource unit.
        double RUCycles = Cycles / (NumUnits * SubUnit.NumUnits);
        for (unsigned I2 = 0, E2 = SubUnit.NumUnits; I2 < E2; ++I2) {
          ResourceRef ResourceUnit = std::make_pair(SubUnitIdx, 1U << I2);
          UsedResources.emplace_back(std::make_pair(ResourceUnit, RUCycles));
        }
      }
    }

    // Now send a fake instruction issued event to all the views.
    InstRef IR(SR.first, Inst.get());
    HWInstructionIssuedEvent Event(IR, UsedResources);
    for (std::unique_ptr<View> &Listener : Views)
      Listener->onInstructionEvent(Event);
    S.updateNext();
  }
}
/// Render a file coverage summary (\p FCS) in a table row. If \p IsTotals is
/// false, link the summary to \p SF.
void CoveragePrinterHTML::emitFileSummary(raw_ostream &OS, StringRef SF,
                                          const FileCoverageSummary &FCS,
                                          bool IsTotals) const {
  SmallVector<std::string, 8> Columns;

  // Format a coverage triple and add the result to the list of columns.
  auto AddCoverageTripleToColumn = [&Columns](unsigned Hit, unsigned Total,
                                              float Pctg) {
    std::string S;
    {
      raw_string_ostream RSO{S};
      if (Total)
        RSO << format("%*.2f", 7, Pctg) << "% ";
      else
        RSO << "- ";
      RSO << '(' << Hit << '/' << Total << ')';
    }
    const char *CellClass = "column-entry-yellow";
    if (Hit == Total)
      CellClass = "column-entry-green";
    else if (Pctg < 80.0)
      CellClass = "column-entry-red";
    Columns.emplace_back(tag("td", tag("pre", S), CellClass));
  };

  // Simplify the display file path, and wrap it in a link if requested.
  std::string Filename;
  if (IsTotals) {
    Filename = "TOTALS";
  } else {
    SmallString<128> LinkTextStr(sys::path::relative_path(FCS.Name));
    sys::path::remove_dots(LinkTextStr, /*remove_dot_dots=*/true);
    sys::path::native(LinkTextStr);
    std::string LinkText = escape(LinkTextStr, Opts);
    std::string LinkTarget =
        escape(getOutputPath(SF, "html", /*InToplevel=*/false), Opts);
    Filename = a(LinkTarget, LinkText);
  }

  Columns.emplace_back(tag("td", tag("pre", Filename)));
  AddCoverageTripleToColumn(FCS.FunctionCoverage.Executed,
                            FCS.FunctionCoverage.NumFunctions,
                            FCS.FunctionCoverage.getPercentCovered());
  AddCoverageTripleToColumn(FCS.InstantiationCoverage.Executed,
                            FCS.InstantiationCoverage.NumFunctions,
                            FCS.InstantiationCoverage.getPercentCovered());
  AddCoverageTripleToColumn(FCS.LineCoverage.Covered, FCS.LineCoverage.NumLines,
                            FCS.LineCoverage.getPercentCovered());
  AddCoverageTripleToColumn(FCS.RegionCoverage.Covered,
                            FCS.RegionCoverage.NumRegions,
                            FCS.RegionCoverage.getPercentCovered());

  OS << tag("tr", join(Columns.begin(), Columns.end(), ""), "light-row");
}
TEST(FileSpecificDiagnosticConsumer,
     ErrorsInUnaffiliatedFilesGoToEveryConsumer) {
  SourceManager sourceMgr;
  //                                             01234
  unsigned bufferA = sourceMgr.addMemBufferCopy("abcde", "A");
  unsigned bufferB = sourceMgr.addMemBufferCopy("vwxyz", "B");

  SourceLoc frontOfA = sourceMgr.getLocForOffset(bufferA, 0);
  SourceLoc middleOfA = sourceMgr.getLocForOffset(bufferA, 2);
  SourceLoc backOfA = sourceMgr.getLocForOffset(bufferA, 4);

  SourceLoc frontOfB = sourceMgr.getLocForOffset(bufferB, 0);
  SourceLoc middleOfB = sourceMgr.getLocForOffset(bufferB, 2);
  SourceLoc backOfB = sourceMgr.getLocForOffset(bufferB, 4);

  ExpectedDiagnostic expectedA[] = {
    {frontOfA, "front"},
    {frontOfB, "front"},
    {middleOfA, "middle"},
    {middleOfB, "middle"},
    {backOfA, "back"},
    {backOfB, "back"}
  };
  ExpectedDiagnostic expectedUnaffiliated[] = {
    {frontOfB, "front"},
    {middleOfB, "middle"},
    {backOfB, "back"}
  };

  auto consumerA = llvm::make_unique<ExpectationDiagnosticConsumer>(
      nullptr, expectedA);
  auto consumerUnaffiliated = llvm::make_unique<ExpectationDiagnosticConsumer>(
      consumerA.get(), expectedUnaffiliated);

  SmallVector<FileSpecificDiagnosticConsumer::Subconsumer, 2> consumers;
  consumers.emplace_back("A", std::move(consumerA));
  consumers.emplace_back("", std::move(consumerUnaffiliated));

  auto topConsumer =
      FileSpecificDiagnosticConsumer::consolidateSubconsumers(consumers);
  topConsumer->handleDiagnostic(sourceMgr, frontOfA, DiagnosticKind::Error,
                                "front", {}, DiagnosticInfo(), SourceLoc());
  topConsumer->handleDiagnostic(sourceMgr, frontOfB, DiagnosticKind::Error,
                                "front", {}, DiagnosticInfo(), SourceLoc());
  topConsumer->handleDiagnostic(sourceMgr, middleOfA, DiagnosticKind::Error,
                                "middle", {}, DiagnosticInfo(), SourceLoc());
  topConsumer->handleDiagnostic(sourceMgr, middleOfB, DiagnosticKind::Error,
                                "middle", {}, DiagnosticInfo(), SourceLoc());
  topConsumer->handleDiagnostic(sourceMgr, backOfA, DiagnosticKind::Error,
                                "back", {}, DiagnosticInfo(), SourceLoc());
  topConsumer->handleDiagnostic(sourceMgr, backOfB, DiagnosticKind::Error,
                                "back", {}, DiagnosticInfo(), SourceLoc());
  topConsumer->finishProcessing();
}
예제 #8
0
/// Emit column labels for the table in the index.
static void emitColumnLabelsForIndex(raw_ostream &OS,
                                     const CoverageViewOptions &Opts) {
  SmallVector<std::string, 4> Columns;
  Columns.emplace_back(tag("td", "Filename", "column-entry-left"));
  Columns.emplace_back(tag("td", "Function Coverage", "column-entry"));
  if (Opts.ShowInstantiationSummary)
    Columns.emplace_back(tag("td", "Instantiation Coverage", "column-entry"));
  Columns.emplace_back(tag("td", "Line Coverage", "column-entry"));
  if (Opts.ShowRegionSummary)
    Columns.emplace_back(tag("td", "Region Coverage", "column-entry"));
  OS << tag("tr", join(Columns.begin(), Columns.end(), ""));
}
TEST(FileSpecificDiagnosticConsumer,
     NotesWithInvalidLocsAreStillAttachedToErrors) {
  SourceManager sourceMgr;
  //                                             01234
  unsigned bufferA = sourceMgr.addMemBufferCopy("abcde", "A");
  unsigned bufferB = sourceMgr.addMemBufferCopy("vwxyz", "B");

  SourceLoc frontOfA = sourceMgr.getLocForBufferStart(bufferA);
  SourceLoc frontOfB = sourceMgr.getLocForBufferStart(bufferB);

  ExpectedDiagnostic expectedA[] = {
    {frontOfA, "error"},
    {SourceLoc(), "note"},
    {frontOfB, "error"},
    {SourceLoc(), "note"},
    {frontOfA, "error"},
    {SourceLoc(), "note"},
  };
  ExpectedDiagnostic expectedUnaffiliated[] = {
    {frontOfB, "error"},
    {SourceLoc(), "note"},
  };

  auto consumerA = llvm::make_unique<ExpectationDiagnosticConsumer>(
      nullptr, expectedA);
  auto consumerUnaffiliated = llvm::make_unique<ExpectationDiagnosticConsumer>(
      consumerA.get(), expectedUnaffiliated);

  SmallVector<FileSpecificDiagnosticConsumer::Subconsumer, 2> consumers;
  consumers.emplace_back("A", std::move(consumerA));
  consumers.emplace_back("", std::move(consumerUnaffiliated));

  auto topConsumer =
      FileSpecificDiagnosticConsumer::consolidateSubconsumers(consumers);
  topConsumer->handleDiagnostic(sourceMgr, frontOfA, DiagnosticKind::Error,
                                "error", {}, DiagnosticInfo(), SourceLoc());
  topConsumer->handleDiagnostic(sourceMgr, SourceLoc(), DiagnosticKind::Note,
                                "note", {}, DiagnosticInfo(), SourceLoc());
  topConsumer->handleDiagnostic(sourceMgr, frontOfB, DiagnosticKind::Error,
                                "error", {}, DiagnosticInfo(), SourceLoc());
  topConsumer->handleDiagnostic(sourceMgr, SourceLoc(), DiagnosticKind::Note,
                                "note", {}, DiagnosticInfo(), SourceLoc());
  topConsumer->handleDiagnostic(sourceMgr, frontOfA, DiagnosticKind::Error,
                                "error", {}, DiagnosticInfo(), SourceLoc());
  topConsumer->handleDiagnostic(sourceMgr, SourceLoc(), DiagnosticKind::Note,
                                "note", {}, DiagnosticInfo(), SourceLoc());
  topConsumer->finishProcessing();
}
예제 #10
0
/// Hack to deal with the fact that Sema/CodeSynthesis.cpp creates ParamDecls
/// containing contextual types.
Type ParameterList::getInterfaceType(DeclContext *DC) const {
  auto &C = DC->getASTContext();

  if (size() == 0)
    return TupleType::getEmpty(C);

  SmallVector<TupleTypeElt, 8> argumentInfo;

  for (auto P : *this) {
    assert(P->hasType());

    Type type;
    if (P->hasInterfaceType())
      type = P->getInterfaceType();
    else if (!P->getTypeLoc().hasLocation())
      type = ArchetypeBuilder::mapTypeOutOfContext(DC, P->getType());
    else
      type = P->getType();
    assert(!type->hasArchetype());

    argumentInfo.emplace_back(
        type, P->getArgumentName(),
        ParameterTypeFlags::fromParameterType(type, P->isVariadic()));
  }

  return TupleType::get(argumentInfo, C);
}
TEST(FileSpecificDiagnosticConsumer, NotesAreAttachedToErrorsEvenAcrossFiles) {
  SourceManager sourceMgr;
  //                                             01234
  unsigned bufferA = sourceMgr.addMemBufferCopy("abcde", "A");
  unsigned bufferB = sourceMgr.addMemBufferCopy("vwxyz", "B");

  SourceLoc frontOfA = sourceMgr.getLocForOffset(bufferA, 0);
  SourceLoc middleOfA = sourceMgr.getLocForOffset(bufferA, 2);
  SourceLoc backOfA = sourceMgr.getLocForOffset(bufferA, 4);

  SourceLoc frontOfB = sourceMgr.getLocForOffset(bufferB, 0);
  SourceLoc middleOfB = sourceMgr.getLocForOffset(bufferB, 2);
  SourceLoc backOfB = sourceMgr.getLocForOffset(bufferB, 4);

  ExpectedDiagnostic expectedA[] = {
    {frontOfA, "error"},
    {middleOfB, "note"},
    {backOfA, "note"},
    {frontOfA, "error"},
    {middleOfB, "note"},
    {backOfA, "note"},
  };
  ExpectedDiagnostic expectedB[] = {
    {frontOfB, "error"},
    {middleOfA, "note"},
    {backOfB, "note"},
  };

  auto consumerA = llvm::make_unique<ExpectationDiagnosticConsumer>(
      nullptr, expectedA);
  auto consumerB = llvm::make_unique<ExpectationDiagnosticConsumer>(
      consumerA.get(), expectedB);

  SmallVector<FileSpecificDiagnosticConsumer::Subconsumer, 2> consumers;
  consumers.emplace_back("A", std::move(consumerA));
  consumers.emplace_back("B", std::move(consumerB));

  auto topConsumer =
      FileSpecificDiagnosticConsumer::consolidateSubconsumers(consumers);
  topConsumer->handleDiagnostic(sourceMgr, frontOfA, DiagnosticKind::Error,
                                "error", {}, DiagnosticInfo(), SourceLoc());
  topConsumer->handleDiagnostic(sourceMgr, middleOfB, DiagnosticKind::Note,
                                "note", {}, DiagnosticInfo(), SourceLoc());
  topConsumer->handleDiagnostic(sourceMgr, backOfA, DiagnosticKind::Note,
                                "note", {}, DiagnosticInfo(), SourceLoc());
  topConsumer->handleDiagnostic(sourceMgr, frontOfB, DiagnosticKind::Error,
                                "error", {}, DiagnosticInfo(), SourceLoc());
  topConsumer->handleDiagnostic(sourceMgr, middleOfA, DiagnosticKind::Note,
                                "note", {}, DiagnosticInfo(), SourceLoc());
  topConsumer->handleDiagnostic(sourceMgr, backOfB, DiagnosticKind::Note,
                                "note", {}, DiagnosticInfo(), SourceLoc());
  topConsumer->handleDiagnostic(sourceMgr, frontOfA, DiagnosticKind::Error,
                                "error", {}, DiagnosticInfo(), SourceLoc());
  topConsumer->handleDiagnostic(sourceMgr, middleOfB, DiagnosticKind::Note,
                                "note", {}, DiagnosticInfo(), SourceLoc());
  topConsumer->handleDiagnostic(sourceMgr, backOfA, DiagnosticKind::Note,
                                "note", {}, DiagnosticInfo(), SourceLoc());
  topConsumer->finishProcessing();
}
예제 #12
0
TEST(FileSpecificDiagnosticConsumer, SubConsumersFinishInOrder) {
  SourceManager sourceMgr;
  (void)sourceMgr.addMemBufferCopy("abcde", "A");
  (void)sourceMgr.addMemBufferCopy("vwxyz", "B");

  auto consumerA = llvm::make_unique<ExpectationDiagnosticConsumer>(
      nullptr, None);
  auto consumerUnaffiliated = llvm::make_unique<ExpectationDiagnosticConsumer>(
      consumerA.get(), None);

  SmallVector<FileSpecificDiagnosticConsumer::ConsumerPair, 2> consumers;
  consumers.emplace_back("A", std::move(consumerA));
  consumers.emplace_back("", std::move(consumerUnaffiliated));

  FileSpecificDiagnosticConsumer topConsumer(consumers);
  topConsumer.finishProcessing();
}
예제 #13
0
static SmallVector<StringRef, 2> getNames(const DWARFDie &DIE,
                                          bool IncludeLinkageName = true) {
  SmallVector<StringRef, 2> Result;
  if (const char *Str = DIE.getName(DINameKind::ShortName))
    Result.emplace_back(Str);
  else if (DIE.getTag() == dwarf::DW_TAG_namespace)
    Result.emplace_back("(anonymous namespace)");

  if (IncludeLinkageName) {
    if (const char *Str = DIE.getName(DINameKind::LinkageName)) {
      if (Result.empty() || Result[0] != Str)
        Result.emplace_back(Str);
    }
  }

  return Result;
}
예제 #14
0
// For WinEH exception representation backend need to know what funclet coro.end
// belongs to. That information is passed in a funclet bundle.
static SmallVector<llvm::OperandBundleDef, 1>
getBundlesForCoroEnd(CodeGenFunction &CGF) {
  SmallVector<llvm::OperandBundleDef, 1> BundleList;

  if (llvm::Instruction *EHPad = CGF.CurrentFuncletPad)
    BundleList.emplace_back("funclet", EHPad);

  return BundleList;
}
예제 #15
0
TEST(FileSpecificDiagnosticConsumer, InvalidLocDiagsGoToEveryConsumer) {
  SourceManager sourceMgr;
  (void)sourceMgr.addMemBufferCopy("abcde", "A");
  (void)sourceMgr.addMemBufferCopy("vwxyz", "B");

  ExpectedDiagnostic expected[] = { {SourceLoc(), "dummy"} };
  auto consumerA = llvm::make_unique<ExpectationDiagnosticConsumer>(
      nullptr, expected);
  auto consumerUnaffiliated = llvm::make_unique<ExpectationDiagnosticConsumer>(
      consumerA.get(), expected);

  SmallVector<FileSpecificDiagnosticConsumer::ConsumerPair, 2> consumers;
  consumers.emplace_back("A", std::move(consumerA));
  consumers.emplace_back("", std::move(consumerUnaffiliated));

  FileSpecificDiagnosticConsumer topConsumer(consumers);
  topConsumer.handleDiagnostic(sourceMgr, SourceLoc(), DiagnosticKind::Error,
                               "dummy", {}, DiagnosticInfo());
  topConsumer.finishProcessing();
}
예제 #16
0
    bool HandleBinding(StoreManager &SMgr, Store S, const MemRegion *Region,
                       SVal Val) override {

      if (!isa<GlobalsSpaceRegion>(Region->getMemorySpace()))
        return true;
      const MemRegion *VR = Val.getAsRegion();
      if (VR && isa<StackSpaceRegion>(VR->getMemorySpace()) &&
          !isArcManagedBlock(VR, Ctx) && !isNotInCurrentFrame(VR, Ctx))
        V.emplace_back(Region, VR);
      return true;
    }
TEST(FileSpecificDiagnosticConsumer, WarningsAndRemarksAreTreatedLikeErrors) {
  SourceManager sourceMgr;
  //                                             01234
  unsigned bufferA = sourceMgr.addMemBufferCopy("abcde", "A");
  unsigned bufferB = sourceMgr.addMemBufferCopy("vwxyz", "B");

  SourceLoc frontOfA = sourceMgr.getLocForBufferStart(bufferA);
  SourceLoc frontOfB = sourceMgr.getLocForBufferStart(bufferB);

  ExpectedDiagnostic expectedA[] = {
    {frontOfA, "warning"},
    {frontOfB, "warning"},
    {frontOfA, "remark"},
    {frontOfB, "remark"},
  };
  ExpectedDiagnostic expectedUnaffiliated[] = {
    {frontOfB, "warning"},
    {frontOfB, "remark"},
  };

  auto consumerA = llvm::make_unique<ExpectationDiagnosticConsumer>(
      nullptr, expectedA);
  auto consumerUnaffiliated = llvm::make_unique<ExpectationDiagnosticConsumer>(
      consumerA.get(), expectedUnaffiliated);

  SmallVector<FileSpecificDiagnosticConsumer::Subconsumer, 2> consumers;
  consumers.emplace_back("A", std::move(consumerA));
  consumers.emplace_back("", std::move(consumerUnaffiliated));

  auto topConsumer =
      FileSpecificDiagnosticConsumer::consolidateSubconsumers(consumers);
  topConsumer->handleDiagnostic(sourceMgr, frontOfA, DiagnosticKind::Warning,
                                "warning", {}, DiagnosticInfo(), SourceLoc());
  topConsumer->handleDiagnostic(sourceMgr, frontOfB, DiagnosticKind::Warning,
                                "warning", {}, DiagnosticInfo(), SourceLoc());
  topConsumer->handleDiagnostic(sourceMgr, frontOfA, DiagnosticKind::Remark,
                                "remark", {}, DiagnosticInfo(), SourceLoc());
  topConsumer->handleDiagnostic(sourceMgr, frontOfB, DiagnosticKind::Remark,
                                "remark", {}, DiagnosticInfo(), SourceLoc());
  topConsumer->finishProcessing();
}
예제 #18
0
bool IRTranslator::translateInvoke(const User &U) {
  const InvokeInst &I = cast<InvokeInst>(U);
  MachineFunction &MF = MIRBuilder.getMF();
  MachineModuleInfo &MMI = MF.getMMI();

  const BasicBlock *ReturnBB = I.getSuccessor(0);
  const BasicBlock *EHPadBB = I.getSuccessor(1);

  const Value *Callee(I.getCalledValue());
  const Function *Fn = dyn_cast<Function>(Callee);
  if (isa<InlineAsm>(Callee))
    return false;

  // FIXME: support invoking patchpoint and statepoint intrinsics.
  if (Fn && Fn->isIntrinsic())
    return false;

  // FIXME: support whatever these are.
  if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
    return false;

  // FIXME: support Windows exception handling.
  if (!isa<LandingPadInst>(EHPadBB->front()))
    return false;


  // Emit the actual call, bracketed by EH_LABELs so that the MMI knows about
  // the region covered by the try.
  MCSymbol *BeginSymbol = MMI.getContext().createTempSymbol();
  MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol);

  unsigned Res = I.getType()->isVoidTy() ? 0 : getOrCreateVReg(I);
  SmallVector<CallLowering::ArgInfo, 8> Args;
  for (auto &Arg: I.arg_operands())
    Args.emplace_back(getOrCreateVReg(*Arg), Arg->getType());

  if (!CLI->lowerCall(MIRBuilder, MachineOperand::CreateGA(Fn, 0),
                      CallLowering::ArgInfo(Res, I.getType()), Args))
    return false;

  MCSymbol *EndSymbol = MMI.getContext().createTempSymbol();
  MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol);

  // FIXME: track probabilities.
  MachineBasicBlock &EHPadMBB = getOrCreateBB(*EHPadBB),
                    &ReturnMBB = getOrCreateBB(*ReturnBB);
  MMI.addInvoke(&EHPadMBB, BeginSymbol, EndSymbol);
  MIRBuilder.getMBB().addSuccessor(&ReturnMBB);
  MIRBuilder.getMBB().addSuccessor(&EHPadMBB);

  return true;
}
예제 #19
0
TEST(FileSpecificDiagnosticConsumer, ErrorsWithLocationsGoToExpectedConsumers) {
  SourceManager sourceMgr;
  //                                             01234
  unsigned bufferA = sourceMgr.addMemBufferCopy("abcde", "A");
  unsigned bufferB = sourceMgr.addMemBufferCopy("vwxyz", "B");

  SourceLoc frontOfA = sourceMgr.getLocForOffset(bufferA, 0);
  SourceLoc middleOfA = sourceMgr.getLocForOffset(bufferA, 2);
  SourceLoc backOfA = sourceMgr.getLocForOffset(bufferA, 4);

  SourceLoc frontOfB = sourceMgr.getLocForOffset(bufferB, 0);
  SourceLoc middleOfB = sourceMgr.getLocForOffset(bufferB, 2);
  SourceLoc backOfB = sourceMgr.getLocForOffset(bufferB, 4);

  ExpectedDiagnostic expectedA[] = {
    {frontOfA, "front"},
    {middleOfA, "middle"},
    {backOfA, "back"},
  };
  ExpectedDiagnostic expectedB[] = {
    {frontOfB, "front"},
    {middleOfB, "middle"},
    {backOfB, "back"}
  };

  auto consumerA = llvm::make_unique<ExpectationDiagnosticConsumer>(
      nullptr, expectedA);
  auto consumerB = llvm::make_unique<ExpectationDiagnosticConsumer>(
      consumerA.get(), expectedB);

  SmallVector<FileSpecificDiagnosticConsumer::ConsumerPair, 2> consumers;
  consumers.emplace_back("A", std::move(consumerA));
  consumers.emplace_back("B", std::move(consumerB));

  FileSpecificDiagnosticConsumer topConsumer(consumers);
  topConsumer.handleDiagnostic(sourceMgr, frontOfA, DiagnosticKind::Error,
                               "front", {}, DiagnosticInfo());
  topConsumer.handleDiagnostic(sourceMgr, frontOfB, DiagnosticKind::Error,
                               "front", {}, DiagnosticInfo());
  topConsumer.handleDiagnostic(sourceMgr, middleOfA, DiagnosticKind::Error,
                               "middle", {}, DiagnosticInfo());
  topConsumer.handleDiagnostic(sourceMgr, middleOfB, DiagnosticKind::Error,
                               "middle", {}, DiagnosticInfo());
  topConsumer.handleDiagnostic(sourceMgr, backOfA, DiagnosticKind::Error,
                               "back", {}, DiagnosticInfo());
  topConsumer.handleDiagnostic(sourceMgr, backOfB, DiagnosticKind::Error,
                               "back", {}, DiagnosticInfo());
  topConsumer.finishProcessing();
}
예제 #20
0
/// Create a call instruction with the correct funclet token. Should be used
/// instead of calling CallInst::Create directly.
static CallInst *
createCallInst(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
               const Twine &NameStr, Instruction *InsertBefore,
               const DenseMap<BasicBlock *, ColorVector> &BlockColors) {
  SmallVector<OperandBundleDef, 1> OpBundles;
  if (!BlockColors.empty()) {
    const ColorVector &CV = BlockColors.find(InsertBefore->getParent())->second;
    assert(CV.size() == 1 && "non-unique color for block!");
    Instruction *EHPad = CV.front()->getFirstNonPHI();
    if (EHPad->isEHPad())
      OpBundles.emplace_back("funclet", EHPad);
  }

  return CallInst::Create(FTy, Func, Args, OpBundles, NameStr, InsertBefore);
}
예제 #21
0
/// Return a TupleType or ParenType for this parameter list.  This returns a
/// null type if one of the ParamDecls does not have a type set for it yet.
Type ParameterList::getType(const ASTContext &C) const {
  if (size() == 0)
    return TupleType::getEmpty(C);
  
  SmallVector<TupleTypeElt, 8> argumentInfo;
  
  for (auto P : *this) {
    if (!P->hasType()) return Type();

    argumentInfo.emplace_back(
        P->getType(), P->getArgumentName(),
        ParameterTypeFlags::fromParameterType(P->getType(), P->isVariadic()));
  }

  return TupleType::get(argumentInfo, C);
}
예제 #22
0
bool DispatchStage::checkPRF(const InstRef &IR) {
  SmallVector<unsigned, 4> RegDefs;
  for (const std::unique_ptr<WriteState> &RegDef :
       IR.getInstruction()->getDefs())
    RegDefs.emplace_back(RegDef->getRegisterID());

  const unsigned RegisterMask = PRF.isAvailable(RegDefs);
  // A mask with all zeroes means: register files are available.
  if (RegisterMask) {
    notifyEvent<HWStallEvent>(
        HWStallEvent(HWStallEvent::RegisterFileStall, IR));
    return false;
  }

  return true;
}
/// Derive the body for an '==' operator for a struct.
static void deriveBodyEquatable_struct_eq(AbstractFunctionDecl *eqDecl) {
  auto parentDC = eqDecl->getDeclContext();
  ASTContext &C = parentDC->getASTContext();

  auto args = eqDecl->getParameters();
  auto aParam = args->get(0);
  auto bParam = args->get(1);

  auto structDecl = cast<StructDecl>(aParam->getType()->getAnyNominal());

  SmallVector<ASTNode, 6> statements;

  auto storedProperties =
    structDecl->getStoredProperties(/*skipInaccessible=*/true);

  // For each stored property element, generate a guard statement that returns
  // false if a property is not pairwise-equal.
  for (auto propertyDecl : storedProperties) {
    auto aPropertyRef = new (C) DeclRefExpr(propertyDecl, DeclNameLoc(),
                                            /*implicit*/ true);
    auto aParamRef = new (C) DeclRefExpr(aParam, DeclNameLoc(),
                                         /*implicit*/ true);
    auto aPropertyExpr = new (C) DotSyntaxCallExpr(aPropertyRef, SourceLoc(),
                                                   aParamRef);

    auto bPropertyRef = new (C) DeclRefExpr(propertyDecl, DeclNameLoc(),
                                            /*implicit*/ true);
    auto bParamRef = new (C) DeclRefExpr(bParam, DeclNameLoc(),
                                         /*implicit*/ true);
    auto bPropertyExpr = new (C) DotSyntaxCallExpr(bPropertyRef, SourceLoc(),
                                                   bParamRef);

    auto guardStmt = returnIfNotEqualGuard(C, aPropertyExpr, bPropertyExpr);
    statements.emplace_back(guardStmt);
  }

  // If none of the guard statements caused an early exit, then all the pairs
  // were true.
  // return true
  auto trueExpr = new (C) BooleanLiteralExpr(true, SourceLoc(),
                                             /*Implicit*/true);
  auto returnStmt = new (C) ReturnStmt(SourceLoc(), trueExpr);
  statements.push_back(returnStmt);

  auto body = BraceStmt::create(C, SourceLoc(), statements, SourceLoc());
  eqDecl->setBody(body);
}
예제 #24
0
bool IRTranslator::translateMemcpy(const CallInst &CI) {
  LLT SizeTy{*CI.getArgOperand(2)->getType(), *DL};
  if (cast<PointerType>(CI.getArgOperand(0)->getType())->getAddressSpace() !=
          0 ||
      cast<PointerType>(CI.getArgOperand(1)->getType())->getAddressSpace() !=
          0 ||
      SizeTy.getSizeInBits() != DL->getPointerSizeInBits(0))
    return false;

  SmallVector<CallLowering::ArgInfo, 8> Args;
  for (int i = 0; i < 3; ++i) {
    const auto &Arg = CI.getArgOperand(i);
    Args.emplace_back(getOrCreateVReg(*Arg), Arg->getType());
  }

  MachineOperand Callee = MachineOperand::CreateES("memcpy");

  return CLI->lowerCall(MIRBuilder, Callee,
                        CallLowering::ArgInfo(0, CI.getType()), Args);
}
예제 #25
0
Type ASTBuilder::createTupleType(ArrayRef<Type> eltTypes,
                                 StringRef labels,
                                 bool isVariadic) {
  // Just bail out on variadic tuples for now.
  if (isVariadic) return Type();

  SmallVector<TupleTypeElt, 4> elements;
  elements.reserve(eltTypes.size());
  for (auto eltType : eltTypes) {
    Identifier label;
    if (!labels.empty()) {
      auto split = labels.split(' ');
      if (!split.first.empty())
        label = Ctx.getIdentifier(split.first);
      labels = split.second;
    }
    elements.emplace_back(eltType, label);
  }

  return TupleType::get(elements, Ctx);
}
/// Derive the body for the 'hash(into:)' method for a struct.
static void
deriveBodyHashable_struct_hashInto(AbstractFunctionDecl *hashIntoDecl) {
  // struct SomeStruct {
  //   var x: Int
  //   var y: String
  //   @derived func hash(into hasher: inout Hasher) {
  //     hasher.combine(x)
  //     hasher.combine(y)
  //   }
  // }
  auto parentDC = hashIntoDecl->getDeclContext();
  ASTContext &C = parentDC->getASTContext();

  auto structDecl = parentDC->getAsStructOrStructExtensionContext();
  SmallVector<ASTNode, 6> statements;
  auto selfDecl = hashIntoDecl->getImplicitSelfDecl();

  // Extract the decl for the hasher parameter.
  auto hasherParam = hashIntoDecl->getParameters()->get(0);

  auto storedProperties =
    structDecl->getStoredProperties(/*skipInaccessible=*/true);

  // Feed each stored property into the hasher.
  for (auto propertyDecl : storedProperties) {
    auto propertyRef = new (C) DeclRefExpr(propertyDecl, DeclNameLoc(),
                                           /*implicit*/ true);
    auto selfRef = new (C) DeclRefExpr(selfDecl, DeclNameLoc(),
                                       /*implicit*/ true);
    auto selfPropertyExpr = new (C) DotSyntaxCallExpr(propertyRef, SourceLoc(),
                                                      selfRef);
    // Generate: hasher.combine(self.<property>)
    auto combineExpr = createHasherCombineCall(C, hasherParam, selfPropertyExpr);
    statements.emplace_back(ASTNode(combineExpr));
  }

  auto body = BraceStmt::create(C, SourceLoc(), statements,
                                SourceLoc(), /*implicit*/ true);
  hashIntoDecl->setBody(body);
}
예제 #27
0
파일: Scope.cpp 프로젝트: PiersonBro/swift
void Scope::popPreservingValues(ArrayRef<ManagedValue> innerValues,
                                MutableArrayRef<ManagedValue> outerValues) {
  auto &SGF = cleanups.SGF;
  assert(innerValues.size() == outerValues.size());

  // Record the cleanup information for each preserved value and deactivate its
  // cleanup.
  SmallVector<CleanupCloner, 4> cleanups;
  cleanups.reserve(innerValues.size());
  for (auto &mv : innerValues) {
    cleanups.emplace_back(SGF, mv);
    mv.forward(SGF);
  }

  // Pop any unpreserved cleanups.
  pop();

  // Create a managed value for each preserved value, cloning its cleanup.
  // Since the CleanupCloner does not remember its SILValue, grab it from the
  // original, now-deactivated managed value.
  for (auto index : indices(innerValues)) {
    outerValues[index] = cleanups[index].clone(innerValues[index].getValue());
  }
}
void SourceCoverageViewHTML::renderLine(
    raw_ostream &OS, LineRef L, const coverage::CoverageSegment *WrappedSegment,
    CoverageSegmentArray Segments, unsigned ExpansionCol, unsigned) {
  StringRef Line = L.Line;
  unsigned LineNo = L.LineNo;

  // Steps for handling text-escaping, highlighting, and tooltip creation:
  //
  // 1. Split the line into N+1 snippets, where N = |Segments|. The first
  //    snippet starts from Col=1 and ends at the start of the first segment.
  //    The last snippet starts at the last mapped column in the line and ends
  //    at the end of the line. Both are required but may be empty.

  SmallVector<std::string, 8> Snippets;

  unsigned LCol = 1;
  auto Snip = [&](unsigned Start, unsigned Len) {
    Snippets.push_back(Line.substr(Start, Len));
    LCol += Len;
  };

  Snip(LCol - 1, Segments.empty() ? 0 : (Segments.front()->Col - 1));

  for (unsigned I = 1, E = Segments.size(); I < E; ++I)
    Snip(LCol - 1, Segments[I]->Col - LCol);

  // |Line| + 1 is needed to avoid underflow when, e.g |Line| = 0 and LCol = 1.
  Snip(LCol - 1, Line.size() + 1 - LCol);

  // 2. Escape all of the snippets.

  for (unsigned I = 0, E = Snippets.size(); I < E; ++I)
    Snippets[I] = escape(Snippets[I], getOptions());

  // 3. Use \p WrappedSegment to set the highlight for snippet 0. Use segment
  //    1 to set the highlight for snippet 2, segment 2 to set the highlight for
  //    snippet 3, and so on.

  Optional<std::string> Color;
  SmallVector<std::pair<unsigned, unsigned>, 2> HighlightedRanges;
  auto Highlight = [&](const std::string &Snippet, unsigned LC, unsigned RC) {
    if (getOptions().Debug)
      HighlightedRanges.emplace_back(LC, RC);
    return tag("span", Snippet, Color.getValue());
  };

  auto CheckIfUncovered = [](const coverage::CoverageSegment *S) {
    return S && S->HasCount && S->Count == 0;
  };

  if (CheckIfUncovered(WrappedSegment)) {
    Color = "red";
    if (!Snippets[0].empty())
      Snippets[0] = Highlight(Snippets[0], 1, 1 + Snippets[0].size());
  }

  for (unsigned I = 0, E = Segments.size(); I < E; ++I) {
    const auto *CurSeg = Segments[I];
    if (CurSeg->Col == ExpansionCol)
      Color = "cyan";
    else if (CheckIfUncovered(CurSeg))
      Color = "red";
    else
      Color = None;

    if (Color.hasValue())
      Snippets[I + 1] = Highlight(Snippets[I + 1], CurSeg->Col,
                                  CurSeg->Col + Snippets[I + 1].size());
  }

  if (Color.hasValue() && Segments.empty())
    Snippets.back() = Highlight(Snippets.back(), 1, 1 + Snippets.back().size());

  if (getOptions().Debug) {
    for (const auto &Range : HighlightedRanges) {
      errs() << "Highlighted line " << LineNo << ", " << Range.first << " -> ";
      if (Range.second == 0)
        errs() << "?";
      else
        errs() << Range.second;
      errs() << "\n";
    }
  }

  // 4. Snippets[1:N+1] correspond to \p Segments[0:N]: use these to generate
  //    sub-line region count tooltips if needed.

  bool HasMultipleRegions = [&] {
    unsigned RegionCount = 0;
    for (const auto *S : Segments)
      if (S->HasCount && S->IsRegionEntry)
        if (++RegionCount > 1)
          return true;
    return false;
  }();

  if (shouldRenderRegionMarkers(HasMultipleRegions)) {
    for (unsigned I = 0, E = Segments.size(); I < E; ++I) {
      const auto *CurSeg = Segments[I];
      if (!CurSeg->IsRegionEntry || !CurSeg->HasCount)
        continue;

      Snippets[I + 1] =
          tag("div", Snippets[I + 1] + tag("span", formatCount(CurSeg->Count),
                                           "tooltip-content"),
              "tooltip");
    }
  }

  OS << BeginCodeTD;
  OS << BeginPre;
  for (const auto &Snippet : Snippets)
    OS << Snippet;
  OS << EndPre;

  // If there are no sub-views left to attach to this cell, end the cell.
  // Otherwise, end it after the sub-views are rendered (renderLineSuffix()).
  if (!hasSubViews())
    OS << EndCodeTD;
}
/// Derive the body for the 'hash(into:)' method for an enum with associated
/// values.
static void
deriveBodyHashable_enum_hasAssociatedValues_hashInto(
  AbstractFunctionDecl *hashIntoDecl
) {
  // enum SomeEnumWithAssociatedValues {
  //   case A, B(Int), C(String, Int)
  //   @derived func hash(into hasher: inout Hasher) {
  //     switch self {
  //     case A:
  //       hasher.combine(0)
  //     case B(let a0):
  //       hasher.combine(1)
  //       hasher.combine(a0)
  //     case C(let a0, let a1):
  //       hasher.combine(2)
  //       hasher.combine(a0)
  //       hasher.combine(a1)
  //     }
  //   }
  // }
  auto parentDC = hashIntoDecl->getDeclContext();
  ASTContext &C = parentDC->getASTContext();

  auto enumDecl = parentDC->getAsEnumOrEnumExtensionContext();
  auto selfDecl = hashIntoDecl->getImplicitSelfDecl();

  Type enumType = selfDecl->getType();

  // Extract the decl for the hasher parameter.
  auto hasherParam = hashIntoDecl->getParameters()->get(0);

  unsigned index = 0;
  SmallVector<ASTNode, 4> cases;

  // For each enum element, generate a case statement that binds the associated
  // values so that they can be fed to the hasher.
  for (auto elt : enumDecl->getAllElements()) {
    // case .<elt>(let a0, let a1, ...):
    SmallVector<VarDecl*, 3> payloadVars;
    SmallVector<ASTNode, 3> statements;

    auto payloadPattern = enumElementPayloadSubpattern(elt, 'a', hashIntoDecl,
                                                       payloadVars);
    auto pat = new (C) EnumElementPattern(TypeLoc::withoutLoc(enumType),
                                          SourceLoc(), SourceLoc(),
                                          elt->getName(), elt, payloadPattern);
    pat->setImplicit();

    auto labelItem = CaseLabelItem(pat);

    // If the enum has no associated values, we use the ordinal as the single
    // hash component, because that is sufficient for a good distribution. If
    // any case does have associated values, then the ordinal is used as the
    // first term fed into the hasher.

    {
      // Generate: hasher.combine(<ordinal>)
      auto ordinalExpr = IntegerLiteralExpr::createFromUnsigned(C, index++);
      auto combineExpr = createHasherCombineCall(C, hasherParam, ordinalExpr);
      statements.emplace_back(ASTNode(combineExpr));
    }

    // Generate a sequence of statements that feed the payloads into hasher.
    for (auto payloadVar : payloadVars) {
      auto payloadVarRef = new (C) DeclRefExpr(payloadVar, DeclNameLoc(),
                                               /*implicit*/ true);
      // Generate: hasher.combine(<payloadVar>)
      auto combineExpr = createHasherCombineCall(C, hasherParam, payloadVarRef);
      statements.emplace_back(ASTNode(combineExpr));
    }

    auto hasBoundDecls = !payloadVars.empty();
    auto body = BraceStmt::create(C, SourceLoc(), statements, SourceLoc());
    cases.push_back(CaseStmt::create(C, SourceLoc(), labelItem, hasBoundDecls,
                                     SourceLoc(), SourceLoc(), body,
                                     /*implicit*/ true));
  }

  // generate: switch enumVar { }
  auto enumRef = new (C) DeclRefExpr(selfDecl, DeclNameLoc(),
                                     /*implicit*/true);
  auto switchStmt = SwitchStmt::create(LabeledStmtInfo(), SourceLoc(), enumRef,
                                       SourceLoc(), cases, SourceLoc(), C);

  auto body = BraceStmt::create(C, SourceLoc(), {ASTNode(switchStmt)},
                                SourceLoc());
  hashIntoDecl->setBody(body);
}
/// Derive the body for an '==' operator for an enum where at least one of the
/// cases has associated values.
static void
deriveBodyEquatable_enum_hasAssociatedValues_eq(AbstractFunctionDecl *eqDecl) {
  auto parentDC = eqDecl->getDeclContext();
  ASTContext &C = parentDC->getASTContext();

  auto args = eqDecl->getParameters();
  auto aParam = args->get(0);
  auto bParam = args->get(1);

  Type enumType = aParam->getType();
  auto enumDecl = cast<EnumDecl>(aParam->getType()->getAnyNominal());

  SmallVector<ASTNode, 6> statements;
  SmallVector<ASTNode, 4> cases;
  unsigned elementCount = 0;

  // For each enum element, generate a case statement matching a pair containing
  // the same case, binding variables for the left- and right-hand associated
  // values.
  for (auto elt : enumDecl->getAllElements()) {
    elementCount++;

    // .<elt>(let l0, let l1, ...)
    SmallVector<VarDecl*, 3> lhsPayloadVars;
    auto lhsSubpattern = enumElementPayloadSubpattern(elt, 'l', eqDecl,
                                                      lhsPayloadVars);
    auto lhsElemPat = new (C) EnumElementPattern(TypeLoc::withoutLoc(enumType),
                                                 SourceLoc(), SourceLoc(),
                                                 Identifier(), elt,
                                                 lhsSubpattern);
    lhsElemPat->setImplicit();

    // .<elt>(let r0, let r1, ...)
    SmallVector<VarDecl*, 3> rhsPayloadVars;
    auto rhsSubpattern = enumElementPayloadSubpattern(elt, 'r', eqDecl,
                                                      rhsPayloadVars);
    auto rhsElemPat = new (C) EnumElementPattern(TypeLoc::withoutLoc(enumType),
                                                 SourceLoc(), SourceLoc(),
                                                 Identifier(), elt,
                                                 rhsSubpattern);
    rhsElemPat->setImplicit();

    auto hasBoundDecls = !lhsPayloadVars.empty();

    // case (.<elt>(let l0, let l1, ...), .<elt>(let r0, let r1, ...))
    auto caseTuplePattern = TuplePattern::create(C, SourceLoc(), {
      TuplePatternElt(lhsElemPat), TuplePatternElt(rhsElemPat) },
                                                 SourceLoc());
    caseTuplePattern->setImplicit();

    auto labelItem = CaseLabelItem(caseTuplePattern);

    // Generate a guard statement for each associated value in the payload,
    // breaking out early if any pair is unequal. (This is done to avoid
    // constructing long lists of autoclosure-wrapped conditions connected by
    // &&, which the type checker has more difficulty processing.)
    SmallVector<ASTNode, 6> statementsInCase;
    for (size_t varIdx = 0; varIdx < lhsPayloadVars.size(); varIdx++) {
      auto lhsVar = lhsPayloadVars[varIdx];
      auto lhsExpr = new (C) DeclRefExpr(lhsVar, DeclNameLoc(),
                                         /*implicit*/true);
      auto rhsVar = rhsPayloadVars[varIdx];
      auto rhsExpr = new (C) DeclRefExpr(rhsVar, DeclNameLoc(),
                                         /*Implicit*/true);
      auto guardStmt = returnIfNotEqualGuard(C, lhsExpr, rhsExpr);
      statementsInCase.emplace_back(guardStmt);
    }

    // If none of the guard statements caused an early exit, then all the pairs
    // were true.
    // return true
    auto trueExpr = new (C) BooleanLiteralExpr(true, SourceLoc(),
                                               /*Implicit*/true);
    auto returnStmt = new (C) ReturnStmt(SourceLoc(), trueExpr);
    statementsInCase.push_back(returnStmt);

    auto body = BraceStmt::create(C, SourceLoc(), statementsInCase,
                                  SourceLoc());
    cases.push_back(CaseStmt::create(C, SourceLoc(), labelItem, hasBoundDecls,
                                     SourceLoc(), SourceLoc(), body));
  }

  // default: result = false
  //
  // We only generate this if the enum has more than one case. If it has exactly
  // one case, then that single case statement is already exhaustive.
  if (elementCount > 1) {
    auto defaultPattern = new (C) AnyPattern(SourceLoc());
    defaultPattern->setImplicit();
    auto defaultItem = CaseLabelItem::getDefault(defaultPattern);
    auto falseExpr = new (C) BooleanLiteralExpr(false, SourceLoc(),
                                                /*implicit*/ true);
    auto returnStmt = new (C) ReturnStmt(SourceLoc(), falseExpr);
    auto body = BraceStmt::create(C, SourceLoc(), ASTNode(returnStmt),
                                  SourceLoc());
    cases.push_back(CaseStmt::create(C, SourceLoc(), defaultItem,
                                     /*HasBoundDecls*/ false,
                                     SourceLoc(), SourceLoc(), body));
  }

  // switch (a, b) { <case statements> }
  auto aRef = new (C) DeclRefExpr(aParam, DeclNameLoc(), /*implicit*/true);
  auto bRef = new (C) DeclRefExpr(bParam, DeclNameLoc(), /*implicit*/true);
  auto abExpr = TupleExpr::create(C, SourceLoc(), { aRef, bRef }, {}, {},
                                  SourceLoc(), /*HasTrailingClosure*/ false,
                                  /*implicit*/ true);
  auto switchStmt = SwitchStmt::create(LabeledStmtInfo(), SourceLoc(), abExpr,
                                       SourceLoc(), cases, SourceLoc(), C);
  statements.push_back(switchStmt);

  auto body = BraceStmt::create(C, SourceLoc(), statements, SourceLoc());
  eqDecl->setBody(body);
}