You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

564 lines
25 KiB

  1. // Copyright (c) 2017 Siegfried Pammer
  2. //
  3. // Permission is hereby granted, free of charge, to any person obtaining a copy of this
  4. // software and associated documentation files (the "Software"), to deal in the Software
  5. // without restriction, including without limitation the rights to use, copy, modify, merge,
  6. // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
  7. // to whom the Software is furnished to do so, subject to the following conditions:
  8. //
  9. // The above copyright notice and this permission notice shall be included in all copies or
  10. // substantial portions of the Software.
  11. //
  12. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  13. // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
  14. // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
  15. // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  16. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  17. // DEALINGS IN THE SOFTWARE.
  18. using System;
  19. using System.Collections.Generic;
  20. using System.Linq;
  21. using ICSharpCode.Decompiler.IL.ControlFlow;
  22. using ICSharpCode.Decompiler.TypeSystem;
  23. using ICSharpCode.Decompiler.Util;
  24. namespace ICSharpCode.Decompiler.IL.Transforms
  25. {
  26. /// <summary>
  27. /// Detects switch-on-string patterns employed by the C# compiler and transforms them to an ILAst-switch-instruction.
  28. /// </summary>
  29. class SwitchOnStringTransform : IILTransform
  30. {
  31. public void Run(ILFunction function, ILTransformContext context)
  32. {
  33. if (!context.Settings.SwitchStatementOnString)
  34. return;
  35. HashSet<BlockContainer> changedContainers = new HashSet<BlockContainer>();
  36. foreach (var block in function.Descendants.OfType<Block>()) {
  37. bool changed = false;
  38. for (int i = block.Instructions.Count - 1; i >= 0; i--) {
  39. SwitchInstruction newSwitch;
  40. if (SimplifyCascadingIfStatements(block.Instructions, i, out newSwitch, out var extraLoad, out var keepAssignmentBefore)) {
  41. if (extraLoad) {
  42. block.Instructions[i - 2].ReplaceWith(newSwitch);
  43. block.Instructions.RemoveRange(i - 1, 3);
  44. i -= 2;
  45. } else {
  46. if (keepAssignmentBefore) {
  47. block.Instructions[i].ReplaceWith(newSwitch);
  48. block.Instructions.RemoveAt(i + 1);
  49. } else {
  50. block.Instructions[i - 1].ReplaceWith(newSwitch);
  51. block.Instructions.RemoveRange(i, 2);
  52. i--;
  53. }
  54. }
  55. changed = true;
  56. continue;
  57. }
  58. if (MatchLegacySwitchOnStringWithHashtable(block.Instructions, i, out newSwitch)) {
  59. block.Instructions[i + 1].ReplaceWith(newSwitch);
  60. block.Instructions.RemoveAt(i);
  61. changed = true;
  62. continue;
  63. }
  64. if (MatchLegacySwitchOnStringWithDict(block.Instructions, i, out newSwitch, out keepAssignmentBefore)) {
  65. block.Instructions[i + 1].ReplaceWith(newSwitch);
  66. if (keepAssignmentBefore) {
  67. block.Instructions.RemoveAt(i);
  68. i--;
  69. } else {
  70. block.Instructions.RemoveRange(i - 1, 2);
  71. i -= 2;
  72. }
  73. changed = true;
  74. continue;
  75. }
  76. if (MatchRoslynSwitchOnString(block.Instructions, i, out newSwitch, out keepAssignmentBefore)) {
  77. block.Instructions[i].ReplaceWith(newSwitch);
  78. if (keepAssignmentBefore) {
  79. block.Instructions.RemoveAt(i - 1);
  80. i--;
  81. } else {
  82. block.Instructions.RemoveRange(i - 2, 2);
  83. i -= 2;
  84. }
  85. changed = true;
  86. continue;
  87. }
  88. }
  89. if (!changed) continue;
  90. SwitchDetection.SimplifySwitchInstruction(block);
  91. if (block.Parent is BlockContainer container)
  92. changedContainers.Add(container);
  93. }
  94. foreach (var container in changedContainers)
  95. container.SortBlocks(deleteUnreachableBlocks: true);
  96. }
  97. bool SimplifyCascadingIfStatements(InstructionCollection<ILInstruction> instructions, int i, out SwitchInstruction inst, out bool extraLoad, out bool keepAssignmentBefore)
  98. {
  99. inst = null;
  100. extraLoad = false;
  101. keepAssignmentBefore = false;
  102. if (i < 1) return false;
  103. // match first block: checking switch-value for null or first value (Roslyn)
  104. // if (call op_Equality(ldloc switchValueVar, ldstr value)) br firstBlock
  105. // -or-
  106. // if (comp(ldloc switchValueVar == ldnull)) br defaultBlock
  107. if (!(instructions[i].MatchIfInstruction(out var condition, out var firstBlockJump)))
  108. return false;
  109. if (!firstBlockJump.MatchBranch(out var firstBlock))
  110. return false;
  111. List<(string, Block)> values = new List<(string, Block)>();
  112. ILInstruction switchValue = null;
  113. // Roslyn: match call to operator ==(string, string)
  114. if (MatchStringEqualityComparison(condition, out var switchValueVar, out string value)) {
  115. values.Add((value, firstBlock));
  116. if(!instructions[i - 1].MatchStLoc(switchValueVar, out switchValue)) {
  117. switchValue = new LdLoc(switchValueVar);
  118. }
  119. } else {
  120. // match null check with different variable:
  121. // this is used by the old C# compiler.
  122. if (MatchCompEqualsNull(condition, out var otherSwitchValueVar)) {
  123. values.Add((null, firstBlock));
  124. } else {
  125. return false;
  126. }
  127. // in case of optimized legacy code there are two stlocs:
  128. // stloc otherSwitchValueVar(ldloc switchValue)
  129. // stloc switchValueVar(ldloc otherSwitchValueVar)
  130. // if (comp(ldloc otherSwitchValueVar == ldnull)) br nullCase
  131. if (i > 1 && otherSwitchValueVar != null && instructions[i - 2].MatchStLoc(otherSwitchValueVar, out switchValue)
  132. && instructions[i - 1].MatchStLoc(out switchValueVar, out var switchValueCopyInst)
  133. && switchValueCopyInst.MatchLdLoc(otherSwitchValueVar) && otherSwitchValueVar.IsSingleDefinition && otherSwitchValueVar.LoadCount == 2) {
  134. extraLoad = true;
  135. } else if (instructions[i - 1].MatchStLoc(out switchValueVar, out switchValue)) {
  136. // unoptimized legacy switch
  137. }
  138. }
  139. // if instruction must be followed by a branch to the next case
  140. if (!(instructions.ElementAtOrDefault(i + 1) is Branch nextCaseJump))
  141. return false;
  142. // extract all cases and add them to the values list.
  143. Block currentCaseBlock = nextCaseJump.TargetBlock;
  144. Block nextCaseBlock;
  145. while ((nextCaseBlock = MatchCaseBlock(currentCaseBlock, switchValueVar, out value, out Block block)) != null) {
  146. values.Add((value, block));
  147. currentCaseBlock = nextCaseBlock;
  148. }
  149. // We didn't find enough cases, exit
  150. if (values.Count < 3)
  151. return false;
  152. // if the switchValueVar is used in other places as well, do not eliminate the store.
  153. if (switchValueVar.LoadCount > values.Count) {
  154. keepAssignmentBefore = true;
  155. switchValue = new LdLoc(switchValueVar);
  156. }
  157. var sections = new List<SwitchSection>(values.SelectWithIndex((index, b) => new SwitchSection { Labels = new LongSet(index), Body = new Branch(b.Item2) }));
  158. sections.Add(new SwitchSection { Labels = new LongSet(new LongInterval(0, sections.Count)).Invert(), Body = new Branch(currentCaseBlock) });
  159. var stringToInt = new StringToInt(switchValue, values.SelectArray(item => item.Item1));
  160. inst = new SwitchInstruction(stringToInt);
  161. inst.Sections.AddRange(sections);
  162. return true;
  163. }
  164. /// <summary>
  165. /// Each case consists of two blocks:
  166. /// 1. block:
  167. /// if (call op_Equality(ldloc switchVariable, ldstr value)) br caseBlock
  168. /// br nextBlock
  169. /// -or-
  170. /// if (comp(ldloc switchValueVar == ldnull)) br nextBlock
  171. /// br caseBlock
  172. /// 2. block is caseBlock
  173. /// This method matches the above pattern or its inverted form:
  174. /// the call to ==(string, string) is wrapped in logic.not and the branch targets are reversed.
  175. /// Returns the next block that follows in the block-chain.
  176. /// The <paramref name="switchVariable"/> is updated if the value gets copied to a different variable.
  177. /// See comments below for more info.
  178. /// </summary>
  179. Block MatchCaseBlock(Block currentBlock, ILVariable switchVariable, out string value, out Block caseBlock)
  180. {
  181. value = null;
  182. caseBlock = null;
  183. if (currentBlock.IncomingEdgeCount != 1 || currentBlock.Instructions.Count != 2)
  184. return null;
  185. if (!currentBlock.Instructions[0].MatchIfInstruction(out var condition, out var caseBlockBranch))
  186. return null;
  187. if (!caseBlockBranch.MatchBranch(out caseBlock))
  188. return null;
  189. Block nextBlock;
  190. if (condition.MatchLogicNot(out var inner)) {
  191. condition = inner;
  192. nextBlock = caseBlock;
  193. if (!currentBlock.Instructions[1].MatchBranch(out caseBlock))
  194. return null;
  195. } else {
  196. if (!currentBlock.Instructions[1].MatchBranch(out nextBlock))
  197. return null;
  198. }
  199. if (!MatchStringEqualityComparison(condition, out var v, out value)) {
  200. if (MatchCompEqualsNull(condition, out v)) {
  201. value = null;
  202. } else {
  203. return null;
  204. }
  205. }
  206. if (v != switchVariable)
  207. return null;
  208. return nextBlock;
  209. }
  210. /// <summary>
  211. /// Returns true if <paramref name="left"/> is only assigned once and the initialization is done by copying <paramref name="right"/>.
  212. /// </summary>
  213. bool IsInitializedBy(ILVariable left, ILVariable right)
  214. {
  215. if (!left.IsSingleDefinition)
  216. return false;
  217. var storeInst = left.StoreInstructions.OfType<StLoc>().SingleOrDefault();
  218. if (storeInst == null)
  219. return false;
  220. return storeInst.Value.MatchLdLoc(right);
  221. }
  222. /// <summary>
  223. /// Matches the C# 2.0 switch-on-string pattern, which uses Dictionary&lt;string, int&gt;.
  224. /// </summary>
  225. bool MatchLegacySwitchOnStringWithDict(InstructionCollection<ILInstruction> instructions, int i, out SwitchInstruction inst, out bool keepAssignmentBefore)
  226. {
  227. inst = null;
  228. keepAssignmentBefore = false;
  229. if (i < 1) return false;
  230. // match first block: checking switch-value for null
  231. if (!(instructions[i].MatchIfInstruction(out var condition, out var exitBlockJump) &&
  232. instructions[i - 1].MatchStLoc(out var switchValueVar, out var switchValue) && switchValueVar.Type.IsKnownType(KnownTypeCode.String)))
  233. return false;
  234. if (!switchValueVar.IsSingleDefinition)
  235. return false;
  236. if (!exitBlockJump.MatchBranch(out var nullValueCaseBlock))
  237. return false;
  238. if (!(condition.MatchCompEquals(out var left, out var right) && right.MatchLdNull() && (left.Match(switchValue).Success || left.MatchLdLoc(switchValueVar))))
  239. return false;
  240. var nextBlockJump = instructions.ElementAtOrDefault(i + 1) as Branch;
  241. if (nextBlockJump == null || nextBlockJump.TargetBlock.IncomingEdgeCount != 1)
  242. return false;
  243. // match second block: checking compiler-generated Dictionary<string, int> for null
  244. var nextBlock = nextBlockJump.TargetBlock;
  245. if (nextBlock.Instructions.Count != 2 || !nextBlock.Instructions[0].MatchIfInstruction(out condition, out var tryGetValueBlockJump))
  246. return false;
  247. if (!tryGetValueBlockJump.MatchBranch(out var tryGetValueBlock))
  248. return false;
  249. if (!nextBlock.Instructions[1].MatchBranch(out var dictInitBlock) || dictInitBlock.IncomingEdgeCount != 1)
  250. return false;
  251. if (!(condition.MatchCompNotEquals(out left, out right) && right.MatchLdNull() &&
  252. MatchDictionaryFieldLoad(left, IsStringToIntDictionary, out var dictField, out var dictionaryType)))
  253. return false;
  254. // match third block: initialization of compiler-generated Dictionary<string, int>
  255. if (dictInitBlock.IncomingEdgeCount != 1 || dictInitBlock.Instructions.Count < 3)
  256. return false;
  257. if (!ExtractStringValuesFromInitBlock(dictInitBlock, out var stringValues, tryGetValueBlock, dictionaryType, dictField))
  258. return false;
  259. // match fourth block: TryGetValue on compiler-generated Dictionary<string, int>
  260. if (tryGetValueBlock.IncomingEdgeCount != 2 || tryGetValueBlock.Instructions.Count != 2)
  261. return false;
  262. if (!tryGetValueBlock.Instructions[0].MatchIfInstruction(out condition, out var defaultBlockJump))
  263. return false;
  264. if (!defaultBlockJump.MatchBranch(out var defaultBlock))
  265. return false;
  266. if (!(condition.MatchLogicNot(out var arg) && arg is Call c && c.Method.Name == "TryGetValue" &&
  267. MatchDictionaryFieldLoad(c.Arguments[0], IsStringToIntDictionary, out var dictField2, out _) && dictField2.Equals(dictField)))
  268. return false;
  269. if (!c.Arguments[1].MatchLdLoc(switchValueVar) || !c.Arguments[2].MatchLdLoca(out var switchIndexVar))
  270. return false;
  271. if (!tryGetValueBlock.Instructions[1].MatchBranch(out var switchBlock))
  272. return false;
  273. // match fifth block: switch-instruction block
  274. if (switchBlock.IncomingEdgeCount != 1 || switchBlock.Instructions.Count != 1)
  275. return false;
  276. if (!(switchBlock.Instructions[0] is SwitchInstruction switchInst && switchInst.Value.MatchLdLoc(switchIndexVar)))
  277. return false;
  278. var sections = new List<SwitchSection>(switchInst.Sections);
  279. // switch contains case null:
  280. if (nullValueCaseBlock != defaultBlock) {
  281. var label = new Util.LongSet(switchInst.Sections.Count);
  282. var possibleConflicts = switchInst.Sections.Where(sec => sec.Labels.Overlaps(label)).ToArray();
  283. if (possibleConflicts.Length > 1)
  284. return false;
  285. else if (possibleConflicts.Length == 1)
  286. possibleConflicts[0].Labels = possibleConflicts[0].Labels.ExceptWith(label);
  287. stringValues.Add(null);
  288. sections.Add(new SwitchSection() { Labels = label, Body = new Branch(nullValueCaseBlock) });
  289. }
  290. if (switchValueVar.LoadCount > 2) {
  291. switchValue = new LdLoc(switchValueVar);
  292. keepAssignmentBefore = true;
  293. }
  294. var stringToInt = new StringToInt(switchValue, stringValues.ToArray());
  295. inst = new SwitchInstruction(stringToInt);
  296. inst.Sections.AddRange(sections);
  297. return true;
  298. }
  299. bool MatchDictionaryFieldLoad(ILInstruction inst, Func<IType, bool> typeMatcher, out IField dictField, out IType dictionaryType)
  300. {
  301. dictField = null;
  302. dictionaryType = null;
  303. return inst.MatchLdObj(out var dictionaryFieldLoad, out dictionaryType) &&
  304. typeMatcher(dictionaryType) &&
  305. dictionaryFieldLoad.MatchLdsFlda(out dictField) &&
  306. (dictField.IsCompilerGeneratedOrIsInCompilerGeneratedClass() || dictField.Name.StartsWith("$$method", StringComparison.Ordinal));
  307. }
  308. bool ExtractStringValuesFromInitBlock(Block block, out List<string> values, Block targetBlock, IType dictionaryType, IField dictionaryField)
  309. {
  310. values = null;
  311. if (!(block.Instructions[0].MatchStLoc(out var dictVar, out var newObjDict) &&
  312. newObjDict is NewObj newObj && newObj.Arguments.Count >= 1 && newObj.Arguments[0].MatchLdcI4(out var valuesLength)))
  313. return false;
  314. values = new List<string>(valuesLength);
  315. int i = 0;
  316. while (i + 1 < block.Instructions.Count - 2 && MatchAddCall(block.Instructions[i + 1], dictVar, i, out var value)) {
  317. values.Add(value);
  318. i++;
  319. }
  320. if (!(block.Instructions[i + 1].MatchStObj(out var loadField, out var dictVarLoad, out var dictType) &&
  321. dictType.Equals(dictionaryType) && loadField.MatchLdsFlda(out var dictField) && dictField.Equals(dictionaryField)) &&
  322. dictVarLoad.MatchLdLoc(dictVar))
  323. return false;
  324. return block.Instructions[i + 2].MatchBranch(targetBlock);
  325. }
  326. bool MatchAddCall(ILInstruction inst, ILVariable dictVar, int i, out string value)
  327. {
  328. value = null;
  329. return inst is Call c && c.Method.Name == "Add" && c.Arguments.Count == 3 &&
  330. c.Arguments[0].MatchLdLoc(dictVar) && c.Arguments[1].MatchLdStr(out value) &&
  331. (c.Arguments[2].MatchLdcI4(i) || (c.Arguments[2].MatchBox(out var arg, out _) && arg.MatchLdcI4(i)));
  332. }
  333. bool IsStringToIntDictionary(IType dictionaryType)
  334. {
  335. if (dictionaryType.FullName != "System.Collections.Generic.Dictionary")
  336. return false;
  337. if (dictionaryType.TypeArguments.Count != 2)
  338. return false;
  339. return dictionaryType.TypeArguments[0].IsKnownType(KnownTypeCode.String) &&
  340. dictionaryType.TypeArguments[1].IsKnownType(KnownTypeCode.Int32);
  341. }
  342. bool IsNonGenericHashtable(IType dictionaryType)
  343. {
  344. if (dictionaryType.FullName != "System.Collections.Hashtable")
  345. return false;
  346. if (dictionaryType.TypeArguments.Count != 0)
  347. return false;
  348. return true;
  349. }
  350. bool MatchLegacySwitchOnStringWithHashtable(InstructionCollection<ILInstruction> instructions, int i, out SwitchInstruction inst)
  351. {
  352. inst = null;
  353. // match first block: checking compiler-generated Hashtable for null
  354. // if (comp(volatile.ldobj System.Collections.Hashtable(ldsflda $$method0x600003f-1) != ldnull)) br switchHeadBlock
  355. // br tableInitBlock
  356. if (!(instructions[i].MatchIfInstruction(out var condition, out var branchToSwitchHead) && i + 1 < instructions.Count))
  357. return false;
  358. if (!instructions[i + 1].MatchBranch(out var tableInitBlock) || tableInitBlock.IncomingEdgeCount != 1)
  359. return false;
  360. if (!(condition.MatchCompNotEquals(out var left, out var right) && right.MatchLdNull() &&
  361. MatchDictionaryFieldLoad(left, IsNonGenericHashtable, out var dictField, out var dictionaryType)))
  362. return false;
  363. if (!branchToSwitchHead.MatchBranch(out var switchHead))
  364. return false;
  365. // match second block: initialization of compiler-generated Hashtable
  366. // stloc table(newobj Hashtable..ctor(ldc.i4 capacity, ldc.f loadFactor))
  367. // call Add(ldloc table, ldstr value, box System.Int32(ldc.i4 index))
  368. // ... more calls to Add ...
  369. // volatile.stobj System.Collections.Hashtable(ldsflda $$method0x600003f - 1, ldloc table)
  370. // br switchHeadBlock
  371. if (tableInitBlock.IncomingEdgeCount != 1 || tableInitBlock.Instructions.Count < 3)
  372. return false;
  373. if (!ExtractStringValuesFromInitBlock(tableInitBlock, out var stringValues, switchHead, dictionaryType, dictField))
  374. return false;
  375. // match third block: checking switch-value for null
  376. // stloc tmp(ldloc switch-value)
  377. // stloc switchVariable(ldloc tmp)
  378. // if (comp(ldloc tmp == ldnull)) br nullCaseBlock
  379. // br getItemBlock
  380. if (switchHead.Instructions.Count != 4 || switchHead.IncomingEdgeCount != 2)
  381. return false;
  382. if (!switchHead.Instructions[0].MatchStLoc(out var tmp, out var switchValue))
  383. return false;
  384. if (!switchHead.Instructions[1].MatchStLoc(out var switchVariable, out var tmpLoad) || !tmpLoad.MatchLdLoc(tmp))
  385. return false;
  386. if (!switchHead.Instructions[2].MatchIfInstruction(out condition, out var nullCaseBlockBranch))
  387. return false;
  388. if (!switchHead.Instructions[3].MatchBranch(out var getItemBlock) || !nullCaseBlockBranch.MatchBranch(out var nullCaseBlock))
  389. return false;
  390. if (!(condition.MatchCompEquals(out left, out right) && right.MatchLdNull() && left.MatchLdLoc(tmp)))
  391. return false;
  392. // match fourth block: get_Item on compiler-generated Hashtable
  393. // stloc tmp2(call get_Item(volatile.ldobj System.Collections.Hashtable(ldsflda $$method0x600003f - 1), ldloc switchVariable))
  394. // stloc switchVariable(ldloc tmp2)
  395. // if (comp(ldloc tmp2 == ldnull)) br defaultCaseBlock
  396. // br switchBlock
  397. if (getItemBlock.IncomingEdgeCount != 1 || getItemBlock.Instructions.Count != 4)
  398. return false;
  399. if (!(getItemBlock.Instructions[0].MatchStLoc(out var tmp2, out var getItem) && getItem is Call getItemCall && getItemCall.Method.Name == "get_Item"))
  400. return false;
  401. if (!getItemBlock.Instructions[1].MatchStLoc(out var switchVariable2, out var tmp2Load) || !tmp2Load.MatchLdLoc(tmp2))
  402. return false;
  403. if (!ILVariableEqualityComparer.Instance.Equals(switchVariable, switchVariable2))
  404. return false;
  405. if (!getItemBlock.Instructions[2].MatchIfInstruction(out condition, out var defaultBlockBranch))
  406. return false;
  407. if (!getItemBlock.Instructions[3].MatchBranch(out var switchBlock) || !defaultBlockBranch.MatchBranch(out var defaultBlock))
  408. return false;
  409. if (!(condition.MatchCompEquals(out left, out right) && right.MatchLdNull() && left.MatchLdLoc(tmp2)))
  410. return false;
  411. if (!(getItemCall.Arguments.Count == 2 && MatchDictionaryFieldLoad(getItemCall.Arguments[0], IsStringToIntDictionary, out var dictField2, out _) && dictField2.Equals(dictField)) &&
  412. getItemCall.Arguments[1].MatchLdLoc(switchVariable2))
  413. return false;
  414. // match fifth block: switch-instruction block
  415. // switch (ldobj System.Int32(unbox System.Int32(ldloc switchVariable))) {
  416. // case [0..1): br caseBlock1
  417. // ... more cases ...
  418. // case [long.MinValue..0),[13..long.MaxValue]: br defaultBlock
  419. // }
  420. if (switchBlock.IncomingEdgeCount != 1 || switchBlock.Instructions.Count != 1)
  421. return false;
  422. if (!(switchBlock.Instructions[0] is SwitchInstruction switchInst && switchInst.Value.MatchLdObj(out var target, out var ldobjType) &&
  423. target.MatchUnbox(out var arg, out var unboxType) && arg.MatchLdLoc(switchVariable2) && ldobjType.IsKnownType(KnownTypeCode.Int32) && unboxType.Equals(ldobjType)))
  424. return false;
  425. var sections = new List<SwitchSection>(switchInst.Sections);
  426. // switch contains case null:
  427. if (nullCaseBlock != defaultBlock) {
  428. var label = new Util.LongSet(switchInst.Sections.Count);
  429. var possibleConflicts = switchInst.Sections.Where(sec => sec.Labels.Overlaps(label)).ToArray();
  430. if (possibleConflicts.Length > 1)
  431. return false;
  432. else if (possibleConflicts.Length == 1)
  433. possibleConflicts[0].Labels = possibleConflicts[0].Labels.ExceptWith(label);
  434. stringValues.Add(null);
  435. sections.Add(new SwitchSection() { Labels = label, Body = new Branch(nullCaseBlock) });
  436. }
  437. var stringToInt = new StringToInt(switchValue, stringValues.ToArray());
  438. inst = new SwitchInstruction(stringToInt);
  439. inst.Sections.AddRange(sections);
  440. return true;
  441. }
  442. bool MatchRoslynSwitchOnString(InstructionCollection<ILInstruction> instructions, int i, out SwitchInstruction inst, out bool keepAssignmentBefore)
  443. {
  444. inst = null;
  445. keepAssignmentBefore = false;
  446. if (i < 1) return false;
  447. if (!(instructions[i] is SwitchInstruction switchInst && switchInst.Value.MatchLdLoc(out var targetVar) &&
  448. MatchComputeStringHashCall(instructions[i - 1], targetVar, out var switchValue)))
  449. return false;
  450. var stringValues = new List<(int, string, Block)>();
  451. int index = 0;
  452. ILInstruction defaultBranch = null;
  453. foreach (var section in switchInst.Sections) {
  454. if (!section.Body.MatchBranch(out Block target)) {
  455. if (section.Body is Leave leave) {
  456. defaultBranch = leave;
  457. continue;
  458. }
  459. return false;
  460. }
  461. if (target.IncomingEdgeCount > 1) {
  462. defaultBranch = new Branch(target);
  463. continue;
  464. }
  465. if (target.Instructions.Count != 2)
  466. return false;
  467. if (!target.Instructions[0].MatchIfInstruction(out var condition, out var bodyBranch))
  468. return false;
  469. if (!bodyBranch.MatchBranch(out Block body))
  470. return false;
  471. if (!MatchStringEqualityOrNullComparison(condition, switchValue.Variable, out string stringValue)) {
  472. if (condition.MatchLogicNot(out condition) && MatchStringEqualityOrNullComparison(condition, switchValue.Variable, out stringValue)) {
  473. if (!target.Instructions[1].MatchBranch(out Block exit))
  474. return false;
  475. body = exit;
  476. } else
  477. return false;
  478. }
  479. stringValues.Add((index++, stringValue, body));
  480. }
  481. ILInstruction switchValueInst = switchValue;
  482. if (i > 1 && instructions[i - 2].MatchStLoc(switchValue.Variable, out var switchValueTmp) &&
  483. switchValue.Variable.IsSingleDefinition && switchValue.Variable.LoadCount == switchInst.Sections.Count) {
  484. switchValueInst = switchValueTmp;
  485. } else {
  486. keepAssignmentBefore = true;
  487. }
  488. var defaultLabel = new LongSet(new LongInterval(0, index)).Invert();
  489. var value = new StringToInt(switchValueInst, stringValues.Select(item => item.Item2).ToArray());
  490. inst = new SwitchInstruction(value);
  491. inst.Sections.AddRange(stringValues.Select(section => new SwitchSection { Labels = new Util.LongSet(section.Item1), Body = new Branch(section.Item3) }));
  492. inst.Sections.Add(new SwitchSection { Labels = defaultLabel, Body = defaultBranch });
  493. return true;
  494. }
  495. bool MatchComputeStringHashCall(ILInstruction inst, ILVariable targetVar, out LdLoc switchValue)
  496. {
  497. switchValue = null;
  498. if (!inst.MatchStLoc(targetVar, out var value))
  499. return false;
  500. if (!(value is Call c && c.Arguments.Count == 1 && c.Method.Name == "ComputeStringHash" && c.Method.IsCompilerGeneratedOrIsInCompilerGeneratedClass()))
  501. return false;
  502. if (!(c.Arguments[0] is LdLoc))
  503. return false;
  504. switchValue = (LdLoc)c.Arguments[0];
  505. return true;
  506. }
  507. bool MatchStringEqualityOrNullComparison(ILInstruction condition, ILVariable variable, out string stringValue)
  508. {
  509. if (!MatchStringEqualityComparison(condition, out var v, out stringValue)) {
  510. if (!MatchCompEqualsNull(condition, out v))
  511. return false;
  512. stringValue = null;
  513. }
  514. return v == variable;
  515. }
  516. bool MatchStringEqualityComparison(ILInstruction condition, out ILVariable variable, out string stringValue)
  517. {
  518. stringValue = null;
  519. variable = null;
  520. ILInstruction left, right;
  521. if (condition is Call c && c.Method.IsOperator && c.Method.Name == "op_Equality" && c.Arguments.Count == 2) {
  522. left = c.Arguments[0];
  523. right = c.Arguments[1];
  524. if (!right.MatchLdStr(out stringValue))
  525. return false;
  526. } else {
  527. return false;
  528. }
  529. return left.MatchLdLoc(out variable);
  530. }
  531. bool MatchCompEqualsNull(ILInstruction condition, out ILVariable variable)
  532. {
  533. variable = null;
  534. if (!condition.MatchCompEquals(out var left, out var right))
  535. return false;
  536. return right.MatchLdNull() && left.MatchLdLoc(out variable);
  537. }
  538. }
  539. }