Debian Codegraph @

gcc/d/dmd/iasmgcc.d

raw
1 /**
2 * Inline assembler for the GCC D compiler.
3 *
4 * Copyright (C) 2018-2025 by The D Language Foundation, All Rights Reserved
5 * Authors: Iain Buclaw
6 * License: $(LINK2 https://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
7 * Source: $(LINK2 https://github.com/dlang/dmd/blob/master/compiler/src/dmd/iasmgcc.d, _iasmgcc.d)
8 * Documentation: https://dlang.org/phobos/dmd_iasmgcc.html
9 * Coverage: https://codecov.io/gh/dlang/dmd/src/master/compiler/src/dmd/iasmgcc.d
10 */
11
12 module dmd.iasmgcc;
13
14 import core.stdc.string;
15
16 import dmd.arraytypes;
17 import dmd.astcodegen;
18 import dmd.dscope;
19 import dmd.dsymbol;
20 import dmd.errors;
21 import dmd.errorsink;
22 import dmd.expression;
23 import dmd.expressionsem;
24 import dmd.identifier;
25 import dmd.globals;
26 import dmd.location;
27 import dmd.parse;
28 import dmd.tokens;
29 import dmd.statement;
30 import dmd.statementsem;
31
32 /***********************************
33 * Parse and run semantic analysis on a GccAsmStatement.
34 * Params:
35 * s = gcc asm statement being parsed
36 * sc = the scope where the asm statement is located
37 * Returns:
38 * the completed gcc asm statement, or null if errors occurred
39 */
40 public Statement gccAsmSemantic(GccAsmStatement s, Scope* sc)
41 {
42 //printf("GccAsmStatement.semantic()\n");
43 const bool doUnittests = global.params.parsingUnittestsRequired();
44 scope p = new Parser!ASTCodegen(sc._module, ";", false, global.errorSink, &global.compileEnv, doUnittests);
45
46 // Make a safe copy of the token list before parsing.
47 Token* toklist = null;
48 Token **ptoklist = &toklist;
49
50 for (Token* token = s.tokens; token; token = token.next)
51 {
52 *ptoklist = p.allocateToken();
53 memcpy(*ptoklist, token, Token.sizeof);
54 ptoklist = &(*ptoklist).next;
55 *ptoklist = null;
56 }
57 p.token = *toklist;
58 p.baseLoc.startLine = s.loc.linnum;
59 p.linnum = s.loc.linnum;
60
61 // Parse the gcc asm statement.
62 const errors = global.errors;
63 s = p.parseGccAsm(s);
64 if (errors != global.errors)
65 return null;
66 s.stc = sc.stc;
67
68 // Fold the instruction template string.
69 s.insn = semanticString(sc, s.insn, "asm instruction template");
70
71 if (s.labels && s.outputargs)
72 error(s.loc, "extended asm statements with labels cannot have output constraints");
73
74 // Analyse all input and output operands.
75 if (s.args)
76 {
77 foreach (i; 0 .. s.args.length)
78 {
79 Expression e = (*s.args)[i];
80 e = e.expressionSemantic(sc);
81 // Check argument is a valid lvalue/rvalue.
82 if (i < s.outputargs)
83 e = e.modifiableLvalue(sc);
84 else if (e.checkValue())
85 e = ErrorExp.get();
86 (*s.args)[i] = e;
87
88 e = (*s.constraints)[i];
89 e = e.expressionSemantic(sc);
90 assert(e.op == EXP.string_ && (cast(StringExp) e).sz == 1);
91 (*s.constraints)[i] = e;
92 }
93 }
94
95 // Analyse all clobbers.
96 if (s.clobbers)
97 {
98 foreach (i; 0 .. s.clobbers.length)
99 {
100 Expression e = (*s.clobbers)[i];
101 e = e.expressionSemantic(sc);
102 assert(e.op == EXP.string_ && (cast(StringExp) e).sz == 1);
103 (*s.clobbers)[i] = e;
104 }
105 }
106
107 // Analyse all goto labels.
108 if (s.labels)
109 {
110 foreach (i; 0 .. s.labels.length)
111 {
112 Identifier ident = (*s.labels)[i];
113 GotoStatement gs = new GotoStatement(s.loc, ident);
114 if (!s.gotos)
115 s.gotos = new GotoStatements();
116 s.gotos.push(gs);
117 gs.statementSemantic(sc);
118 }
119 }
120
121 return s;
122 }
123
124 /***********************************
125 * Run semantic analysis on an CAsmDeclaration.
126 * Params:
127 * ad = asm declaration
128 * sc = the scope where the asm declaration is located
129 */
130 public void gccAsmSemantic(CAsmDeclaration ad, Scope* sc)
131 {
132 import dmd.typesem : pointerTo;
133 ad.code = semanticString(sc, ad.code, "asm definition");
134 ad.code.type = ad.code.type.nextOf().pointerTo();
135
136 // Asm definition always needs emitting into the root module.
137 import dmd.dmodule : Module;
138 if (sc._module && sc._module.isRoot())
139 return;
140 if (Module m = Module.rootModule)
141 m.members.push(ad);
142 }
143
144 private:
145
146 /***********************************
147 * Parse list of extended asm input or output operands.
148 * Grammar:
149 * | Operands:
150 * | SymbolicName(opt) StringLiteral ( AssignExpression )
151 * | SymbolicName(opt) StringLiteral ( AssignExpression ), Operands
152 * |
153 * | SymbolicName:
154 * | [ Identifier ]
155 * Params:
156 * p = parser state
157 * s = asm statement to parse
158 * Returns:
159 * number of operands added to the gcc asm statement
160 */
161 int parseExtAsmOperands(Parser)(Parser p, GccAsmStatement s)
162 {
163 int numargs = 0;
164
165 while (1)
166 {
167 Expression arg;
168 Identifier name;
169 Expression constraint;
170
171 switch (p.token.value)
172 {
173 case TOK.semicolon:
174 case TOK.colon:
175 case TOK.endOfFile:
176 return numargs;
177
178 case TOK.leftBracket:
179 if (p.peekNext() == TOK.identifier)
180 {
181 // Skip over opening `[`
182 p.nextToken();
183 // Store the symbolic name
184 name = p.token.ident;
185 p.nextToken();
186 }
187 else
188 {
189 p.eSink.error(s.loc, "expected identifier after `[`");
190 goto Lerror;
191 }
192 // Look for closing `]`
193 p.check(TOK.rightBracket);
194 // Look for the string literal and fall through
195 if (p.token.value == TOK.string_)
196 goto case;
197 else
198 goto default;
199
200 case TOK.string_:
201 constraint = p.parsePrimaryExp();
202 if (p.token.value != TOK.leftParenthesis)
203 {
204 arg = p.parseAssignExp();
205 error(arg.loc, "`%s` must be surrounded by parentheses", arg.toChars());
206 }
207 else
208 {
209 // Look for the opening `(`
210 p.check(TOK.leftParenthesis);
211 // Parse the assign expression
212 arg = p.parseAssignExp();
213 // Look for the closing `)`
214 p.check(TOK.rightParenthesis);
215 }
216
217 if (!s.args)
218 {
219 s.names = new Identifiers();
220 s.constraints = new Expressions();
221 s.args = new Expressions();
222 }
223 s.names.push(name);
224 s.args.push(arg);
225 s.constraints.push(constraint);
226 numargs++;
227
228 if (p.token.value == TOK.comma)
229 p.nextToken();
230 break;
231
232 default:
233 p.eSink.error(p.token.loc, "expected constant string constraint for operand, not `%s`",
234 p.token.toChars());
235 goto Lerror;
236 }
237 }
238 Lerror:
239 while (p.token.value != TOK.rightCurly &&
240 p.token.value != TOK.semicolon &&
241 p.token.value != TOK.endOfFile)
242 p.nextToken();
243
244 return numargs;
245 }
246
247 /***********************************
248 * Parse list of extended asm clobbers.
249 * Grammar:
250 * | Clobbers:
251 * | StringLiteral
252 * | StringLiteral , Clobbers
253 * Params:
254 * p = parser state
255 * Returns:
256 * array of parsed clobber expressions
257 */
258 Expressions* parseExtAsmClobbers(Parser)(Parser p)
259 {
260 Expressions* clobbers;
261
262 while (1)
263 {
264 Expression clobber;
265
266 switch (p.token.value)
267 {
268 case TOK.semicolon:
269 case TOK.colon:
270 case TOK.endOfFile:
271 return clobbers;
272
273 case TOK.string_:
274 clobber = p.parsePrimaryExp();
275 if (!clobbers)
276 clobbers = new Expressions();
277 clobbers.push(clobber);
278
279 if (p.token.value == TOK.comma)
280 p.nextToken();
281 break;
282
283 default:
284 p.eSink.error(p.token.loc, "expected constant string constraint for clobber name, not `%s`",
285 p.token.toChars());
286 goto Lerror;
287 }
288 }
289 Lerror:
290 while (p.token.value != TOK.rightCurly &&
291 p.token.value != TOK.semicolon &&
292 p.token.value != TOK.endOfFile)
293 p.nextToken();
294
295 return clobbers;
296 }
297
298 /***********************************
299 * Parse list of extended asm goto labels.
300 * Grammar:
301 * | GotoLabels:
302 * | Identifier
303 * | Identifier , GotoLabels
304 * Params:
305 * p = parser state
306 * Returns:
307 * array of parsed goto labels
308 */
309 Identifiers* parseExtAsmGotoLabels(Parser)(Parser p)
310 {
311 Identifiers* labels;
312
313 while (1)
314 {
315 switch (p.token.value)
316 {
317 case TOK.semicolon:
318 case TOK.endOfFile:
319 return labels;
320
321 case TOK.identifier:
322 if (!labels)
323 labels = new Identifiers();
324 labels.push(p.token.ident);
325
326 if (p.nextToken() == TOK.comma)
327 p.nextToken();
328 break;
329
330 default:
331 p.eSink.error(p.token.loc, "expected identifier for goto label name, not `%s`",
332 p.token.toChars());
333 goto Lerror;
334 }
335 }
336 Lerror:
337 while (p.token.value != TOK.rightCurly &&
338 p.token.value != TOK.semicolon &&
339 p.token.value != TOK.endOfFile)
340 p.nextToken();
341
342 return labels;
343 }
344
345 /***********************************
346 * Parse a gcc asm statement.
347 * There are three forms of inline asm statements, basic, extended, and goto.
348 * Grammar:
349 * | AsmInstruction:
350 * | BasicAsmInstruction
351 * | ExtAsmInstruction
352 * | GotoAsmInstruction
353 * |
354 * | BasicAsmInstruction:
355 * | AssignExpression
356 * |
357 * | ExtAsmInstruction:
358 * | AssignExpression : Operands(opt) : Operands(opt) : Clobbers(opt)
359 * |
360 * | GotoAsmInstruction:
361 * | AssignExpression : : Operands(opt) : Clobbers(opt) : GotoLabels(opt)
362 * Params:
363 * p = parser state
364 * s = asm statement to parse
365 * Returns:
366 * the parsed gcc asm statement
367 */
368 GccAsmStatement parseGccAsm(Parser)(Parser p, GccAsmStatement s)
369 {
370 s.insn = p.parseAssignExp();
371 if (p.token.value == TOK.semicolon || p.token.value == TOK.endOfFile)
372 goto Ldone;
373
374 // No semicolon followed after instruction template, treat as extended asm.
375 foreach (section; 0 .. 4)
376 {
377 p.check(TOK.colon);
378
379 final switch (section)
380 {
381 case 0:
382 s.outputargs = p.parseExtAsmOperands(s);
383 break;
384
385 case 1:
386 p.parseExtAsmOperands(s);
387 break;
388
389 case 2:
390 s.clobbers = p.parseExtAsmClobbers();
391 break;
392
393 case 3:
394 s.labels = p.parseExtAsmGotoLabels();
395 break;
396 }
397
398 if (p.token.value == TOK.semicolon || p.token.value == TOK.endOfFile)
399 goto Ldone;
400 }
401 Ldone:
402 p.check(TOK.semicolon);
403
404 return s;
405 }
406
407 unittest
408 {
409 import dmd.mtype : TypeBasic;
410
411 if (!global.errorSink)
412 global.errorSink = new ErrorSinkCompiler;
413
414 const errors = global.startGagging();
415 scope(exit) global.endGagging(errors);
416
417 // If this check fails, then Type._init() was called before reaching here,
418 // and the entire chunk of code that follows can be removed.
419 assert(ASTCodegen.Type.tint32 is null);
420 // Minimally initialize the cached types in ASTCodegen.Type, as they are
421 // dependencies for some fail asm tests to succeed.
422 ASTCodegen.Type.stringtable._init();
423 scope(exit)
424 {
425 ASTCodegen.Type.deinitialize();
426 ASTCodegen.Type.tint32 = null;
427 }
428 scope tint32 = new TypeBasic(ASTCodegen.Tint32);
429 ASTCodegen.Type.tint32 = tint32;
430
431 // Imitates asmSemantic if version = IN_GCC.
432 static int semanticAsm(Token* tokens)
433 {
434 const errors = global.errors;
435 scope gas = new GccAsmStatement(Loc.initial, tokens);
436 const bool doUnittests = false;
437 scope p = new Parser!ASTCodegen(null, ";", false, global.errorSink, &global.compileEnv, doUnittests);
438 p.token = *tokens;
439 p.parseGccAsm(gas);
440 return global.errors - errors;
441 }
442
443 // Imitates parseStatement for asm statements.
444 static void parseAsm(string input, bool expectError)
445 {
446 // Generate tokens from input test.
447 const bool doUnittests = false;
448 scope p = new Parser!ASTCodegen(null, input, false, global.errorSink, &global.compileEnv, doUnittests);
449 p.nextToken();
450
451 Token* toklist = null;
452 Token** ptoklist = &toklist;
453 p.check(TOK.asm_);
454 p.check(TOK.leftCurly);
455 while (1)
456 {
457 if (p.token.value == TOK.rightCurly || p.token.value == TOK.endOfFile)
458 break;
459 if (p.token.value == TOK.colonColon)
460 {
461 *ptoklist = p.allocateToken();
462 memcpy(*ptoklist, &p.token, Token.sizeof);
463 (*ptoklist).value = TOK.colon;
464 ptoklist = &(*ptoklist).next;
465
466 *ptoklist = p.allocateToken();
467 memcpy(*ptoklist, &p.token, Token.sizeof);
468 (*ptoklist).value = TOK.colon;
469 ptoklist = &(*ptoklist).next;
470 }
471 else
472 {
473 *ptoklist = p.allocateToken();
474 memcpy(*ptoklist, &p.token, Token.sizeof);
475 ptoklist = &(*ptoklist).next;
476 }
477 *ptoklist = null;
478 p.nextToken();
479 }
480 p.check(TOK.rightCurly);
481
482 auto res = semanticAsm(toklist);
483 // Checks for both unexpected passes and failures.
484 assert((res == 0) != expectError);
485 }
486
487 /// Assembly Tests, all should pass.
488 /// Note: Frontend is not initialized, use only strings and identifiers.
489 immutable string[] passAsmTests = [
490 // Basic asm statement
491 q{ asm { "nop";
492 } },
493
494 // Extended asm statement
495 q{ asm { "cpuid"
496 : "=a" (a), "=b" (b), "=c" (c), "=d" (d)
497 : "a" (input);
498 } },
499
500 // Assembly with symbolic names
501 q{ asm { "bts %[base], %[offset]"
502 : [base] "+rm" (*ptr),
503 : [offset] "Ir" (bitnum);
504 } },
505
506 // Assembly with clobbers
507 q{ asm { "cpuid"
508 : "=a" (a)
509 : "a" (input)
510 : "ebx", "ecx", "edx";
511 } },
512
513 // Goto asm statement
514 q{ asm { "jmp %l0"
515 :
516 :
517 :
518 : Ljmplabel;
519 } },
520
521 // Any CTFE-able string allowed as instruction template.
522 q{ asm { generateAsm();
523 } },
524
525 // Likewise mixins, permissible so long as the result is a string.
526 q{ asm { mixin(`"repne"`, `~ "scasb"`);
527 } },
528
529 // :: token tests
530 q{ asm { "" : : : "memory"; } },
531 q{ asm { "" :: : "memory"; } },
532 q{ asm { "" : :: "memory"; } },
533 q{ asm { "" ::: "memory"; } },
534 ];
535
536 immutable string[] failAsmTests = [
537 // Found 'h' when expecting ';'
538 q{ asm { ""h;
539 } },
540
541 // https://issues.dlang.org/show_bug.cgi?id=20592
542 q{ asm { "nop" : [name] string (expr); } },
543
544 // Expression expected, not ';'
545 q{ asm { ""[;
546 } },
547
548 // Expression expected, not ':'
549 q{ asm { ""
550 :
551 : "g" (a ? b : : c);
552 } },
553
554 // Found ',' when expecting ':'
555 q{ asm { "", "";
556 } },
557
558 // https://issues.dlang.org/show_bug.cgi?id=20593
559 q{ asm { "instruction" : : "operand" 123; } },
560 ];
561
562 foreach (test; passAsmTests)
563 parseAsm(test, false);
564
565 foreach (test; failAsmTests)
566 parseAsm(test, true);
567 }