1 /*
2 	This file is part of solidity.
3 
4 	solidity is free software: you can redistribute it and/or modify
5 	it under the terms of the GNU General Public License as published by
6 	the Free Software Foundation, either version 3 of the License, or
7 	(at your option) any later version.
8 
9 	solidity is distributed in the hope that it will be useful,
10 	but WITHOUT ANY WARRANTY; without even the implied warranty of
11 	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 	GNU General Public License for more details.
13 
14 	You should have received a copy of the GNU General Public License
15 	along with solidity.  If not, see <http://www.gnu.org/licenses/>.
16 */
17 // SPDX-License-Identifier: GPL-3.0
18 /**
19  * Analyzer part of inline assembly.
20  */
21 
22 #include <libyul/AsmAnalysis.h>
23 
24 #include <libyul/AST.h>
25 #include <libyul/AsmAnalysisInfo.h>
26 #include <libyul/Utilities.h>
27 #include <libyul/Exceptions.h>
28 #include <libyul/Object.h>
29 #include <libyul/Scope.h>
30 #include <libyul/ScopeFiller.h>
31 
32 #include <liblangutil/ErrorReporter.h>
33 
34 #include <libsolutil/CommonData.h>
35 #include <libsolutil/StringUtils.h>
36 #include <libsolutil/Visitor.h>
37 
38 #include <boost/algorithm/string.hpp>
39 
40 #include <fmt/format.h>
41 
42 #include <memory>
43 #include <functional>
44 
45 using namespace std;
46 using namespace solidity;
47 using namespace solidity::yul;
48 using namespace solidity::util;
49 using namespace solidity::langutil;
50 
51 namespace
52 {
to_string(LiteralKind _kind)53 inline string to_string(LiteralKind _kind)
54 {
55 	switch (_kind)
56 	{
57 	case LiteralKind::Number: return "number";
58 	case LiteralKind::Boolean: return "boolean";
59 	case LiteralKind::String: return "string";
60 	default: yulAssert(false, "");
61 	}
62 }
63 }
64 
analyze(Block const & _block)65 bool AsmAnalyzer::analyze(Block const& _block)
66 {
67 	auto watcher = m_errorReporter.errorWatcher();
68 	try
69 	{
70 		if (!(ScopeFiller(m_info, m_errorReporter))(_block))
71 			return false;
72 
73 		(*this)(_block);
74 	}
75 	catch (FatalError const&)
76 	{
77 		// This FatalError con occur if the errorReporter has too many errors.
78 		yulAssert(!watcher.ok(), "Fatal error detected, but no error is reported.");
79 	}
80 	return watcher.ok();
81 }
82 
analyzeStrictAssertCorrect(Dialect const & _dialect,Object const & _object)83 AsmAnalysisInfo AsmAnalyzer::analyzeStrictAssertCorrect(Dialect const& _dialect, Object const& _object)
84 {
85 	ErrorList errorList;
86 	langutil::ErrorReporter errors(errorList);
87 	AsmAnalysisInfo analysisInfo;
88 	bool success = yul::AsmAnalyzer(
89 		analysisInfo,
90 		errors,
91 		_dialect,
92 		{},
93 		_object.qualifiedDataNames()
94 	).analyze(*_object.code);
95 	yulAssert(success && !errors.hasErrors(), "Invalid assembly/yul code.");
96 	return analysisInfo;
97 }
98 
operator ()(Literal const & _literal)99 vector<YulString> AsmAnalyzer::operator()(Literal const& _literal)
100 {
101 	expectValidType(_literal.type, nativeLocationOf(_literal));
102 	if (_literal.kind == LiteralKind::String && _literal.value.str().size() > 32)
103 		m_errorReporter.typeError(
104 			3069_error,
105 			nativeLocationOf(_literal),
106 			"String literal too long (" + to_string(_literal.value.str().size()) + " > 32)"
107 		);
108 	else if (_literal.kind == LiteralKind::Number && bigint(_literal.value.str()) > u256(-1))
109 		m_errorReporter.typeError(6708_error, nativeLocationOf(_literal), "Number literal too large (> 256 bits)");
110 	else if (_literal.kind == LiteralKind::Boolean)
111 		yulAssert(_literal.value == "true"_yulstring || _literal.value == "false"_yulstring, "");
112 
113 	if (!m_dialect.validTypeForLiteral(_literal.kind, _literal.value, _literal.type))
114 		m_errorReporter.typeError(
115 			5170_error,
116 			nativeLocationOf(_literal),
117 			"Invalid type \"" + _literal.type.str() + "\" for literal \"" + _literal.value.str() + "\"."
118 		);
119 
120 
121 	return {_literal.type};
122 }
123 
operator ()(Identifier const & _identifier)124 vector<YulString> AsmAnalyzer::operator()(Identifier const& _identifier)
125 {
126 	yulAssert(!_identifier.name.empty(), "");
127 	auto watcher = m_errorReporter.errorWatcher();
128 	YulString type = m_dialect.defaultType;
129 
130 	if (m_currentScope->lookup(_identifier.name, GenericVisitor{
131 		[&](Scope::Variable const& _var)
132 		{
133 			if (!m_activeVariables.count(&_var))
134 				m_errorReporter.declarationError(
135 					4990_error,
136 					nativeLocationOf(_identifier),
137 					"Variable " + _identifier.name.str() + " used before it was declared."
138 				);
139 			type = _var.type;
140 		},
141 		[&](Scope::Function const&)
142 		{
143 			m_errorReporter.typeError(
144 				6041_error,
145 				nativeLocationOf(_identifier),
146 				"Function " + _identifier.name.str() + " used without being called."
147 			);
148 		}
149 	}))
150 	{
151 		if (m_resolver)
152 			// We found a local reference, make sure there is no external reference.
153 			m_resolver(
154 				_identifier,
155 				yul::IdentifierContext::NonExternal,
156 				m_currentScope->insideFunction()
157 			);
158 	}
159 	else
160 	{
161 		bool found = m_resolver && m_resolver(
162 			_identifier,
163 			yul::IdentifierContext::RValue,
164 			m_currentScope->insideFunction()
165 		);
166 		if (!found && watcher.ok())
167 			// Only add an error message if the callback did not do it.
168 			m_errorReporter.declarationError(
169 				8198_error,
170 				nativeLocationOf(_identifier),
171 				"Identifier \"" + _identifier.name.str() + "\" not found."
172 			);
173 
174 	}
175 
176 	return {type};
177 }
178 
operator ()(ExpressionStatement const & _statement)179 void AsmAnalyzer::operator()(ExpressionStatement const& _statement)
180 {
181 	auto watcher = m_errorReporter.errorWatcher();
182 	vector<YulString> types = std::visit(*this, _statement.expression);
183 	if (watcher.ok() && !types.empty())
184 		m_errorReporter.typeError(
185 			3083_error,
186 			nativeLocationOf(_statement),
187 			"Top-level expressions are not supposed to return values (this expression returns " +
188 			to_string(types.size()) +
189 			" value" +
190 			(types.size() == 1 ? "" : "s") +
191 			"). Use ``pop()`` or assign them."
192 		);
193 }
194 
operator ()(Assignment const & _assignment)195 void AsmAnalyzer::operator()(Assignment const& _assignment)
196 {
197 	yulAssert(_assignment.value, "");
198 	size_t const numVariables = _assignment.variableNames.size();
199 	yulAssert(numVariables >= 1, "");
200 
201 	set<YulString> variables;
202 	for (auto const& _variableName: _assignment.variableNames)
203 		if (!variables.insert(_variableName.name).second)
204 			m_errorReporter.declarationError(
205 				9005_error,
206 				nativeLocationOf(_assignment),
207 				"Variable " +
208 				_variableName.name.str() +
209 				" occurs multiple times on the left-hand side of the assignment."
210 			);
211 
212 	vector<YulString> types = std::visit(*this, *_assignment.value);
213 
214 	if (types.size() != numVariables)
215 		m_errorReporter.declarationError(
216 			8678_error,
217 			nativeLocationOf(_assignment),
218 			"Variable count for assignment to \"" +
219 			joinHumanReadable(applyMap(_assignment.variableNames, [](auto const& _identifier){ return _identifier.name.str(); })) +
220 			"\" does not match number of values (" +
221 			to_string(numVariables) +
222 			" vs. " +
223 			to_string(types.size()) +
224 			")"
225 		);
226 
227 	for (size_t i = 0; i < numVariables; ++i)
228 		if (i < types.size())
229 			checkAssignment(_assignment.variableNames[i], types[i]);
230 }
231 
operator ()(VariableDeclaration const & _varDecl)232 void AsmAnalyzer::operator()(VariableDeclaration const& _varDecl)
233 {
234 	size_t const numVariables = _varDecl.variables.size();
235 	if (m_resolver)
236 		for (auto const& variable: _varDecl.variables)
237 			// Call the resolver for variable declarations to allow it to raise errors on shadowing.
238 			m_resolver(
239 				yul::Identifier{variable.debugData, variable.name},
240 				yul::IdentifierContext::VariableDeclaration,
241 				m_currentScope->insideFunction()
242 			);
243 	for (auto const& variable: _varDecl.variables)
244 	{
245 		expectValidIdentifier(variable.name, nativeLocationOf(variable));
246 		expectValidType(variable.type, nativeLocationOf(variable));
247 	}
248 
249 	if (_varDecl.value)
250 	{
251 		vector<YulString> types = std::visit(*this, *_varDecl.value);
252 		if (types.size() != numVariables)
253 			m_errorReporter.declarationError(
254 				3812_error,
255 				nativeLocationOf(_varDecl),
256 				"Variable count mismatch for declaration of \"" +
257 				joinHumanReadable(applyMap(_varDecl.variables, [](auto const& _identifier){ return _identifier.name.str(); })) +
258 				+ "\": " +
259 				to_string(numVariables) +
260 				" variables and " +
261 				to_string(types.size()) +
262 				" values."
263 			);
264 
265 		for (size_t i = 0; i < _varDecl.variables.size(); ++i)
266 		{
267 			YulString givenType = m_dialect.defaultType;
268 			if (i < types.size())
269 				givenType = types[i];
270 			TypedName const& variable = _varDecl.variables[i];
271 			if (variable.type != givenType)
272 				m_errorReporter.typeError(
273 					3947_error,
274 					nativeLocationOf(variable),
275 					"Assigning value of type \"" + givenType.str() + "\" to variable of type \"" + variable.type.str() + "\"."
276 				);
277 		}
278 	}
279 
280 	for (TypedName const& variable: _varDecl.variables)
281 		m_activeVariables.insert(&std::get<Scope::Variable>(
282 			m_currentScope->identifiers.at(variable.name))
283 		);
284 }
285 
operator ()(FunctionDefinition const & _funDef)286 void AsmAnalyzer::operator()(FunctionDefinition const& _funDef)
287 {
288 	yulAssert(!_funDef.name.empty(), "");
289 	expectValidIdentifier(_funDef.name, nativeLocationOf(_funDef));
290 	Block const* virtualBlock = m_info.virtualBlocks.at(&_funDef).get();
291 	yulAssert(virtualBlock, "");
292 	Scope& varScope = scope(virtualBlock);
293 	for (auto const& var: _funDef.parameters + _funDef.returnVariables)
294 	{
295 		expectValidIdentifier(var.name, nativeLocationOf(var));
296 		expectValidType(var.type, nativeLocationOf(var));
297 		m_activeVariables.insert(&std::get<Scope::Variable>(varScope.identifiers.at(var.name)));
298 	}
299 
300 	(*this)(_funDef.body);
301 }
302 
operator ()(FunctionCall const & _funCall)303 vector<YulString> AsmAnalyzer::operator()(FunctionCall const& _funCall)
304 {
305 	yulAssert(!_funCall.functionName.name.empty(), "");
306 	auto watcher = m_errorReporter.errorWatcher();
307 	vector<YulString> const* parameterTypes = nullptr;
308 	vector<YulString> const* returnTypes = nullptr;
309 	vector<optional<LiteralKind>> const* literalArguments = nullptr;
310 
311 	if (BuiltinFunction const* f = m_dialect.builtin(_funCall.functionName.name))
312 	{
313 		parameterTypes = &f->parameters;
314 		returnTypes = &f->returns;
315 		if (!f->literalArguments.empty())
316 			literalArguments = &f->literalArguments;
317 
318 		validateInstructions(_funCall);
319 	}
320 	else if (m_currentScope->lookup(_funCall.functionName.name, GenericVisitor{
321 		[&](Scope::Variable const&)
322 		{
323 			m_errorReporter.typeError(
324 				4202_error,
325 				nativeLocationOf(_funCall.functionName),
326 				"Attempt to call variable instead of function."
327 			);
328 		},
329 		[&](Scope::Function const& _fun)
330 		{
331 			parameterTypes = &_fun.arguments;
332 			returnTypes = &_fun.returns;
333 		}
334 	}))
335 	{
336 		if (m_resolver)
337 			// We found a local reference, make sure there is no external reference.
338 			m_resolver(
339 				_funCall.functionName,
340 				yul::IdentifierContext::NonExternal,
341 				m_currentScope->insideFunction()
342 			);
343 	}
344 	else
345 	{
346 		if (!validateInstructions(_funCall))
347 			m_errorReporter.declarationError(
348 				4619_error,
349 				nativeLocationOf(_funCall.functionName),
350 				"Function \"" + _funCall.functionName.name.str() + "\" not found."
351 			);
352 		yulAssert(!watcher.ok(), "Expected a reported error.");
353 	}
354 
355 	if (parameterTypes && _funCall.arguments.size() != parameterTypes->size())
356 		m_errorReporter.typeError(
357 			7000_error,
358 			nativeLocationOf(_funCall.functionName),
359 			"Function \"" + _funCall.functionName.name.str() + "\" expects " +
360 			to_string(parameterTypes->size()) +
361 			" arguments but got " +
362 			to_string(_funCall.arguments.size()) + "."
363 		);
364 
365 	vector<YulString> argTypes;
366 	for (size_t i = _funCall.arguments.size(); i > 0; i--)
367 	{
368 		Expression const& arg = _funCall.arguments[i - 1];
369 		if (
370 			auto literalArgumentKind = (literalArguments && i <= literalArguments->size()) ?
371 				literalArguments->at(i - 1) :
372 				std::nullopt
373 		)
374 		{
375 			if (!holds_alternative<Literal>(arg))
376 				m_errorReporter.typeError(
377 					9114_error,
378 					nativeLocationOf(_funCall.functionName),
379 					"Function expects direct literals as arguments."
380 				);
381 			else if (*literalArgumentKind != get<Literal>(arg).kind)
382 				m_errorReporter.typeError(
383 					5859_error,
384 					nativeLocationOf(arg),
385 					"Function expects " + to_string(*literalArgumentKind) + " literal."
386 				);
387 			else if (*literalArgumentKind == LiteralKind::String)
388 			{
389 				string functionName = _funCall.functionName.name.str();
390 				if (functionName == "datasize" || functionName == "dataoffset")
391 				{
392 					if (!m_dataNames.count(get<Literal>(arg).value))
393 						m_errorReporter.typeError(
394 							3517_error,
395 							nativeLocationOf(arg),
396 							"Unknown data object \"" + std::get<Literal>(arg).value.str() + "\"."
397 						);
398 				}
399 				else if (functionName.substr(0, "verbatim_"s.size()) == "verbatim_")
400 				{
401 					if (get<Literal>(arg).value.empty())
402 						m_errorReporter.typeError(
403 							1844_error,
404 							nativeLocationOf(arg),
405 							"The \"verbatim_*\" builtins cannot be used with empty bytecode."
406 						);
407 				}
408 
409 				argTypes.emplace_back(expectUnlimitedStringLiteral(get<Literal>(arg)));
410 				continue;
411 			}
412 		}
413 		argTypes.emplace_back(expectExpression(arg));
414 	}
415 	std::reverse(argTypes.begin(), argTypes.end());
416 
417 	if (parameterTypes && parameterTypes->size() == argTypes.size())
418 		for (size_t i = 0; i < parameterTypes->size(); ++i)
419 			expectType((*parameterTypes)[i], argTypes[i], nativeLocationOf(_funCall.arguments[i]));
420 
421 	if (watcher.ok())
422 	{
423 		yulAssert(parameterTypes && parameterTypes->size() == argTypes.size(), "");
424 		yulAssert(returnTypes, "");
425 		return *returnTypes;
426 	}
427 	else if (returnTypes)
428 		return vector<YulString>(returnTypes->size(), m_dialect.defaultType);
429 	else
430 		return {};
431 }
432 
operator ()(If const & _if)433 void AsmAnalyzer::operator()(If const& _if)
434 {
435 	expectBoolExpression(*_if.condition);
436 
437 	(*this)(_if.body);
438 }
439 
operator ()(Switch const & _switch)440 void AsmAnalyzer::operator()(Switch const& _switch)
441 {
442 	yulAssert(_switch.expression, "");
443 
444 	if (_switch.cases.size() == 1 && !_switch.cases[0].value)
445 		m_errorReporter.warning(
446 			9592_error,
447 			nativeLocationOf(_switch),
448 			"\"switch\" statement with only a default case."
449 		);
450 
451 	YulString valueType = expectExpression(*_switch.expression);
452 
453 	set<u256> cases;
454 	for (auto const& _case: _switch.cases)
455 	{
456 		if (_case.value)
457 		{
458 			auto watcher = m_errorReporter.errorWatcher();
459 
460 			expectType(valueType, _case.value->type, nativeLocationOf(*_case.value));
461 
462 			// We cannot use "expectExpression" here because *_case.value is not an
463 			// Expression and would be converted to an Expression otherwise.
464 			(*this)(*_case.value);
465 
466 			/// Note: the parser ensures there is only one default case
467 			if (watcher.ok() && !cases.insert(valueOfLiteral(*_case.value)).second)
468 				m_errorReporter.declarationError(
469 					6792_error,
470 					nativeLocationOf(_case),
471 					"Duplicate case \"" +
472 					valueOfLiteral(*_case.value).str() +
473 					"\" defined."
474 				);
475 		}
476 
477 		(*this)(_case.body);
478 	}
479 }
480 
operator ()(ForLoop const & _for)481 void AsmAnalyzer::operator()(ForLoop const& _for)
482 {
483 	yulAssert(_for.condition, "");
484 
485 	Scope* outerScope = m_currentScope;
486 
487 	(*this)(_for.pre);
488 
489 	// The block was closed already, but we re-open it again and stuff the
490 	// condition, the body and the post part inside.
491 	m_currentScope = &scope(&_for.pre);
492 
493 	expectBoolExpression(*_for.condition);
494 	// backup outer for-loop & create new state
495 	auto outerForLoop = m_currentForLoop;
496 	m_currentForLoop = &_for;
497 
498 	(*this)(_for.body);
499 	(*this)(_for.post);
500 
501 	m_currentScope = outerScope;
502 	m_currentForLoop = outerForLoop;
503 }
504 
operator ()(Block const & _block)505 void AsmAnalyzer::operator()(Block const& _block)
506 {
507 	auto previousScope = m_currentScope;
508 	m_currentScope = &scope(&_block);
509 
510 	for (auto const& s: _block.statements)
511 		std::visit(*this, s);
512 
513 	m_currentScope = previousScope;
514 }
515 
expectExpression(Expression const & _expr)516 YulString AsmAnalyzer::expectExpression(Expression const& _expr)
517 {
518 	vector<YulString> types = std::visit(*this, _expr);
519 	if (types.size() != 1)
520 		m_errorReporter.typeError(
521 			3950_error,
522 			nativeLocationOf(_expr),
523 			"Expected expression to evaluate to one value, but got " +
524 			to_string(types.size()) +
525 			" values instead."
526 		);
527 	return types.empty() ? m_dialect.defaultType : types.front();
528 }
529 
expectUnlimitedStringLiteral(Literal const & _literal)530 YulString AsmAnalyzer::expectUnlimitedStringLiteral(Literal const& _literal)
531 {
532 	yulAssert(_literal.kind == LiteralKind::String, "");
533 	yulAssert(m_dialect.validTypeForLiteral(LiteralKind::String, _literal.value, _literal.type), "");
534 
535 	return {_literal.type};
536 }
537 
expectBoolExpression(Expression const & _expr)538 void AsmAnalyzer::expectBoolExpression(Expression const& _expr)
539 {
540 	YulString type = expectExpression(_expr);
541 	if (type != m_dialect.boolType)
542 		m_errorReporter.typeError(
543 			1733_error,
544 			nativeLocationOf(_expr),
545 			"Expected a value of boolean type \"" +
546 			m_dialect.boolType.str() +
547 			"\" but got \"" +
548 			type.str() +
549 			"\""
550 		);
551 }
552 
checkAssignment(Identifier const & _variable,YulString _valueType)553 void AsmAnalyzer::checkAssignment(Identifier const& _variable, YulString _valueType)
554 {
555 	yulAssert(!_variable.name.empty(), "");
556 	auto watcher = m_errorReporter.errorWatcher();
557 	YulString const* variableType = nullptr;
558 	bool found = false;
559 	if (Scope::Identifier const* var = m_currentScope->lookup(_variable.name))
560 	{
561 		if (m_resolver)
562 			// We found a local reference, make sure there is no external reference.
563 			m_resolver(
564 				_variable,
565 				yul::IdentifierContext::NonExternal,
566 				m_currentScope->insideFunction()
567 			);
568 
569 		if (!holds_alternative<Scope::Variable>(*var))
570 			m_errorReporter.typeError(2657_error, nativeLocationOf(_variable), "Assignment requires variable.");
571 		else if (!m_activeVariables.count(&std::get<Scope::Variable>(*var)))
572 			m_errorReporter.declarationError(
573 				1133_error,
574 				nativeLocationOf(_variable),
575 				"Variable " + _variable.name.str() + " used before it was declared."
576 			);
577 		else
578 			variableType = &std::get<Scope::Variable>(*var).type;
579 		found = true;
580 	}
581 	else if (m_resolver)
582 	{
583 		bool insideFunction = m_currentScope->insideFunction();
584 		if (m_resolver(_variable, yul::IdentifierContext::LValue, insideFunction))
585 		{
586 			found = true;
587 			variableType = &m_dialect.defaultType;
588 		}
589 	}
590 
591 	if (!found && watcher.ok())
592 		// Only add message if the callback did not.
593 		m_errorReporter.declarationError(4634_error, nativeLocationOf(_variable), "Variable not found or variable not lvalue.");
594 	if (variableType && *variableType != _valueType)
595 		m_errorReporter.typeError(
596 			9547_error,
597 			nativeLocationOf(_variable),
598 			"Assigning a value of type \"" +
599 			_valueType.str() +
600 			"\" to a variable of type \"" +
601 			variableType->str() +
602 			"\"."
603 		);
604 
605 	yulAssert(!watcher.ok() || variableType, "");
606 }
607 
scope(Block const * _block)608 Scope& AsmAnalyzer::scope(Block const* _block)
609 {
610 	yulAssert(m_info.scopes.count(_block) == 1, "Scope requested but not present.");
611 	auto scopePtr = m_info.scopes.at(_block);
612 	yulAssert(scopePtr, "Scope requested but not present.");
613 	return *scopePtr;
614 }
615 
expectValidIdentifier(YulString _identifier,SourceLocation const & _location)616 void AsmAnalyzer::expectValidIdentifier(YulString _identifier, SourceLocation const& _location)
617 {
618 	// NOTE: the leading dot case is handled by the parser not allowing it.
619 
620 	if (boost::ends_with(_identifier.str(), "."))
621 		m_errorReporter.syntaxError(
622 			3384_error,
623 			_location,
624 			"\"" + _identifier.str() + "\" is not a valid identifier (ends with a dot)."
625 		);
626 
627 	if (_identifier.str().find("..") != std::string::npos)
628 		m_errorReporter.syntaxError(
629 			7771_error,
630 			_location,
631 			"\"" + _identifier.str() + "\" is not a valid identifier (contains consecutive dots)."
632 		);
633 
634 	if (m_dialect.reservedIdentifier(_identifier))
635 		m_errorReporter.declarationError(
636 			5017_error,
637 			_location,
638 			"The identifier \"" + _identifier.str() + "\" is reserved and can not be used."
639 		);
640 }
641 
expectValidType(YulString _type,SourceLocation const & _location)642 void AsmAnalyzer::expectValidType(YulString _type, SourceLocation const& _location)
643 {
644 	if (!m_dialect.types.count(_type))
645 		m_errorReporter.typeError(
646 			5473_error,
647 			_location,
648 			fmt::format("\"{}\" is not a valid type (user defined types are not yet supported).", _type)
649 		);
650 }
651 
expectType(YulString _expectedType,YulString _givenType,SourceLocation const & _location)652 void AsmAnalyzer::expectType(YulString _expectedType, YulString _givenType, SourceLocation const& _location)
653 {
654 	if (_expectedType != _givenType)
655 		m_errorReporter.typeError(
656 			3781_error,
657 			_location,
658 			fmt::format("Expected a value of type \"{}\" but got \"{}\".", _expectedType, _givenType)
659 		);
660 }
661 
validateInstructions(std::string const & _instructionIdentifier,langutil::SourceLocation const & _location)662 bool AsmAnalyzer::validateInstructions(std::string const& _instructionIdentifier, langutil::SourceLocation const& _location)
663 {
664 	auto const builtin = EVMDialect::strictAssemblyForEVM(EVMVersion{}).builtin(YulString(_instructionIdentifier));
665 	if (builtin && builtin->instruction.has_value())
666 		return validateInstructions(builtin->instruction.value(), _location);
667 	else
668 		return false;
669 }
670 
validateInstructions(evmasm::Instruction _instr,SourceLocation const & _location)671 bool AsmAnalyzer::validateInstructions(evmasm::Instruction _instr, SourceLocation const& _location)
672 {
673 	// We assume that returndatacopy, returndatasize and staticcall are either all available
674 	// or all not available.
675 	yulAssert(m_evmVersion.supportsReturndata() == m_evmVersion.hasStaticCall(), "");
676 	// Similarly we assume bitwise shifting and create2 go together.
677 	yulAssert(m_evmVersion.hasBitwiseShifting() == m_evmVersion.hasCreate2(), "");
678 
679 	// These instructions are disabled in the dialect.
680 	yulAssert(
681 		_instr != evmasm::Instruction::JUMP &&
682 		_instr != evmasm::Instruction::JUMPI &&
683 		_instr != evmasm::Instruction::JUMPDEST,
684 	"");
685 
686 	auto errorForVM = [&](ErrorId _errorId, string const& vmKindMessage) {
687 		m_errorReporter.typeError(
688 			_errorId,
689 			_location,
690 			fmt::format(
691 				"The \"{instruction}\" instruction is {kind} VMs (you are currently compiling for \"{version}\").",
692 				fmt::arg("instruction", boost::to_lower_copy(instructionInfo(_instr).name)),
693 				fmt::arg("kind", vmKindMessage),
694 				fmt::arg("version", m_evmVersion.name())
695 			)
696 		);
697 	};
698 
699 	if (_instr == evmasm::Instruction::RETURNDATACOPY && !m_evmVersion.supportsReturndata())
700 		errorForVM(7756_error, "only available for Byzantium-compatible");
701 	else if (_instr == evmasm::Instruction::RETURNDATASIZE && !m_evmVersion.supportsReturndata())
702 		errorForVM(4778_error, "only available for Byzantium-compatible");
703 	else if (_instr == evmasm::Instruction::STATICCALL && !m_evmVersion.hasStaticCall())
704 		errorForVM(1503_error, "only available for Byzantium-compatible");
705 	else if (_instr == evmasm::Instruction::SHL && !m_evmVersion.hasBitwiseShifting())
706 		errorForVM(6612_error, "only available for Constantinople-compatible");
707 	else if (_instr == evmasm::Instruction::SHR && !m_evmVersion.hasBitwiseShifting())
708 		errorForVM(7458_error, "only available for Constantinople-compatible");
709 	else if (_instr == evmasm::Instruction::SAR && !m_evmVersion.hasBitwiseShifting())
710 		errorForVM(2054_error, "only available for Constantinople-compatible");
711 	else if (_instr == evmasm::Instruction::CREATE2 && !m_evmVersion.hasCreate2())
712 		errorForVM(6166_error, "only available for Constantinople-compatible");
713 	else if (_instr == evmasm::Instruction::EXTCODEHASH && !m_evmVersion.hasExtCodeHash())
714 		errorForVM(7110_error, "only available for Constantinople-compatible");
715 	else if (_instr == evmasm::Instruction::CHAINID && !m_evmVersion.hasChainID())
716 		errorForVM(1561_error, "only available for Istanbul-compatible");
717 	else if (_instr == evmasm::Instruction::SELFBALANCE && !m_evmVersion.hasSelfBalance())
718 		errorForVM(7721_error, "only available for Istanbul-compatible");
719 	else if (_instr == evmasm::Instruction::BASEFEE && !m_evmVersion.hasBaseFee())
720 		errorForVM(5430_error, "only available for London-compatible");
721 	else if (_instr == evmasm::Instruction::PC)
722 		m_errorReporter.error(
723 			2450_error,
724 			Error::Type::SyntaxError,
725 			_location,
726 			"PC instruction is a low-level EVM feature. "
727 			"Because of that PC is disallowed in strict assembly."
728 		);
729 	else
730 		return false;
731 
732 	return true;
733 }
734 
validateInstructions(FunctionCall const & _functionCall)735 bool AsmAnalyzer::validateInstructions(FunctionCall const& _functionCall)
736 {
737 	return validateInstructions(_functionCall.functionName.name.str(), nativeLocationOf(_functionCall.functionName));
738 }
739