[TableGen] Make OpcodeMappings sort comparator deterministic NFCI
authorAndrew Ng <anng.sw@gmail.com>
Tue, 26 Feb 2019 18:50:49 +0000 (18:50 +0000)
committerAndrew Ng <anng.sw@gmail.com>
Tue, 26 Feb 2019 18:50:49 +0000 (18:50 +0000)
The previous sort comparator was not deterministic, i.e. in some
situations it would be possible for lhs < rhs && rhs < lhs. This was
discovered by an STL assertion in a Windows debug build of llvm-tblgen.

Differential Revision: https://reviews.llvm.org/D58687

llvm-svn: 354910

llvm/utils/TableGen/CodeGenSchedule.cpp

index 4abe122..943e7ef 100644 (file)
@@ -368,24 +368,22 @@ processSTIPredicate(STIPredicateFunction &Fn,
              [&](const OpcodeMapPair &Lhs, const OpcodeMapPair &Rhs) {
                unsigned LhsIdx = Opcode2Index[Lhs.first];
                unsigned RhsIdx = Opcode2Index[Rhs.first];
-               std::pair<APInt, APInt> &LhsMasks = OpcodeMasks[LhsIdx];
-               std::pair<APInt, APInt> &RhsMasks = OpcodeMasks[RhsIdx];
-
-               if (LhsMasks.first != RhsMasks.first) {
-                 if (LhsMasks.first.countPopulation() <
-                     RhsMasks.first.countPopulation())
-                   return true;
-                 return LhsMasks.first.countLeadingZeros() >
-                        RhsMasks.first.countLeadingZeros();
-               }
-
-               if (LhsMasks.second != RhsMasks.second) {
-                 if (LhsMasks.second.countPopulation() <
-                     RhsMasks.second.countPopulation())
-                   return true;
-                 return LhsMasks.second.countLeadingZeros() >
-                        RhsMasks.second.countLeadingZeros();
-               }
+               const std::pair<APInt, APInt> &LhsMasks = OpcodeMasks[LhsIdx];
+               const std::pair<APInt, APInt> &RhsMasks = OpcodeMasks[RhsIdx];
+
+               auto LessThan = [](const APInt &Lhs, const APInt &Rhs) {
+                 unsigned LhsCountPopulation = Lhs.countPopulation();
+                 unsigned RhsCountPopulation = Rhs.countPopulation();
+                 return ((LhsCountPopulation < RhsCountPopulation) ||
+                         ((LhsCountPopulation == RhsCountPopulation) &&
+                          (Lhs.countLeadingZeros() > Rhs.countLeadingZeros())));
+               };
+
+               if (LhsMasks.first != RhsMasks.first)
+                 return LessThan(LhsMasks.first, RhsMasks.first);
+
+               if (LhsMasks.second != RhsMasks.second)
+                 return LessThan(LhsMasks.second, RhsMasks.second);
 
                return LhsIdx < RhsIdx;
              });