Intel® Implicit SPMD Program Compiler (Intel® ISPC)  1.13.0
stmt.cpp
Go to the documentation of this file.
1 /*
2  Copyright (c) 2010-2019, Intel Corporation
3  All rights reserved.
4 
5  Redistribution and use in source and binary forms, with or without
6  modification, are permitted provided that the following conditions are
7  met:
8 
9  * Redistributions of source code must retain the above copyright
10  notice, this list of conditions and the following disclaimer.
11 
12  * Redistributions in binary form must reproduce the above copyright
13  notice, this list of conditions and the following disclaimer in the
14  documentation and/or other materials provided with the distribution.
15 
16  * Neither the name of Intel Corporation nor the names of its
17  contributors may be used to endorse or promote products derived from
18  this software without specific prior written permission.
19 
20 
21  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
22  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
23  TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
24  PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
25  OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
26  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
27  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
28  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
29  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
30  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 */
33 
34 /** @file stmt.cpp
35  @brief File with definitions classes related to statements in the language
36 */
37 
38 #include "stmt.h"
39 #include "ctx.h"
40 #include "expr.h"
41 #include "func.h"
42 #include "llvmutil.h"
43 #include "module.h"
44 #include "sym.h"
45 #include "type.h"
46 #include "util.h"
47 
48 #include <map>
49 #include <stdio.h>
50 
51 #include <llvm/IR/CallingConv.h>
52 #include <llvm/IR/DerivedTypes.h>
53 #include <llvm/IR/Function.h>
54 #include <llvm/IR/Instructions.h>
55 #include <llvm/IR/LLVMContext.h>
56 #include <llvm/IR/Metadata.h>
57 #include <llvm/IR/Module.h>
58 #include <llvm/IR/Type.h>
59 #include <llvm/Support/raw_ostream.h>
60 
61 ///////////////////////////////////////////////////////////////////////////
62 // Stmt
63 
64 Stmt *Stmt::Optimize() { return this; }
65 
66 ///////////////////////////////////////////////////////////////////////////
67 // ExprStmt
68 
70 
72  if (!ctx->GetCurrentBasicBlock())
73  return;
74 
75  ctx->SetDebugPos(pos);
76  if (expr)
77  expr->GetValue(ctx);
78 }
79 
80 Stmt *ExprStmt::TypeCheck() { return this; }
81 
82 void ExprStmt::Print(int indent) const {
83  if (!expr)
84  return;
85 
86  printf("%*c", indent, ' ');
87  printf("Expr stmt: ");
88  pos.Print();
89  expr->Print();
90  printf("\n");
91 }
92 
93 int ExprStmt::EstimateCost() const { return 0; }
94 
95 ///////////////////////////////////////////////////////////////////////////
96 // DeclStmt
97 
98 DeclStmt::DeclStmt(const std::vector<VariableDeclaration> &v, SourcePos p) : Stmt(p, DeclStmtID), vars(v) {}
99 
100 static bool lHasUnsizedArrays(const Type *type) {
101  const ArrayType *at = CastType<ArrayType>(type);
102  if (at == NULL)
103  return false;
104 
105  if (at->GetElementCount() == 0)
106  return true;
107  else
108  return lHasUnsizedArrays(at->GetElementType());
109 }
110 
112  if (!ctx->GetCurrentBasicBlock())
113  return;
114 
115  for (unsigned int i = 0; i < vars.size(); ++i) {
116  Symbol *sym = vars[i].sym;
117  AssertPos(pos, sym != NULL);
118  if (sym->type == NULL)
119  continue;
120  Expr *initExpr = vars[i].init;
121 
122  // Now that we're in the thick of emitting code, it's easy for us
123  // to find out the level of nesting of varying control flow we're
124  // in at this declaration. So we can finally set that
125  // Symbol::varyingCFDepth variable.
126  // @todo It's disgusting to be doing this here.
127  sym->varyingCFDepth = ctx->VaryingCFDepth();
128 
129  ctx->SetDebugPos(sym->pos);
130 
131  // If it's an array that was declared without a size but has an
132  // initializer list, then use the number of elements in the
133  // initializer list to finally set the array's size.
134  sym->type = ArrayType::SizeUnsizedArrays(sym->type, initExpr);
135  if (sym->type == NULL)
136  continue;
137 
138  if (lHasUnsizedArrays(sym->type)) {
139  Error(pos, "Illegal to declare an unsized array variable without "
140  "providing an initializer expression to set its size.");
141  continue;
142  }
143 
144  // References must have initializer expressions as well.
145  if (IsReferenceType(sym->type) == true) {
146  if (initExpr == NULL) {
147  Error(sym->pos,
148  "Must provide initializer for reference-type "
149  "variable \"%s\".",
150  sym->name.c_str());
151  continue;
152  }
153  if (IsReferenceType(initExpr->GetType()) == false) {
154  const Type *initLVType = initExpr->GetLValueType();
155  if (initLVType == NULL) {
156  Error(initExpr->pos,
157  "Initializer for reference-type variable "
158  "\"%s\" must have an lvalue type.",
159  sym->name.c_str());
160  continue;
161  }
162  if (initLVType->IsUniformType() == false) {
163  Error(initExpr->pos,
164  "Initializer for reference-type variable "
165  "\"%s\" must have a uniform lvalue type.",
166  sym->name.c_str());
167  continue;
168  }
169  }
170  }
171 
172  llvm::Type *llvmType = sym->type->LLVMType(g->ctx);
173  if (llvmType == NULL) {
174  AssertPos(pos, m->errorCount > 0);
175  return;
176  }
177 
178  if (sym->storageClass == SC_STATIC) {
179  // For static variables, we need a compile-time constant value
180  // for its initializer; if there's no initializer, we use a
181  // zero value.
182  llvm::Constant *cinit = NULL;
183  if (initExpr != NULL) {
184  if (PossiblyResolveFunctionOverloads(initExpr, sym->type) == false)
185  continue;
186  // FIXME: we only need this for function pointers; it was
187  // already done for atomic types and enums in
188  // DeclStmt::TypeCheck()...
189  if (llvm::dyn_cast<ExprList>(initExpr) == NULL) {
190  initExpr = TypeConvertExpr(initExpr, sym->type, "initializer");
191  // FIXME: and this is only needed to re-establish
192  // constant-ness so that GetConstant below works for
193  // constant artithmetic expressions...
194  initExpr = ::Optimize(initExpr);
195  }
196 
197  std::pair<llvm::Constant *, bool> cinitPair = initExpr->GetConstant(sym->type);
198  cinit = cinitPair.first;
199  if (cinit == NULL)
200  Error(initExpr->pos,
201  "Initializer for static variable "
202  "\"%s\" must be a constant.",
203  sym->name.c_str());
204  }
205  if (cinit == NULL)
206  cinit = llvm::Constant::getNullValue(llvmType);
207 
208  // Allocate space for the static variable in global scope, so
209  // that it persists across function calls
210  sym->storagePtr = new llvm::GlobalVariable(
211  *m->module, llvmType, sym->type->IsConstType(), llvm::GlobalValue::InternalLinkage, cinit,
212  llvm::Twine("static.") + llvm::Twine(sym->pos.first_line) + llvm::Twine(".") + sym->name.c_str());
213  // Tell the FunctionEmitContext about the variable
214  ctx->EmitVariableDebugInfo(sym);
215  } else {
216  // For non-static variables, allocate storage on the stack
217  sym->storagePtr = ctx->AllocaInst(sym->type, sym->name.c_str());
218 
219  // Tell the FunctionEmitContext about the variable; must do
220  // this before the initializer stuff.
221  ctx->EmitVariableDebugInfo(sym);
222  if (initExpr == 0 && sym->type->IsConstType())
223  Error(sym->pos,
224  "Missing initializer for const variable "
225  "\"%s\".",
226  sym->name.c_str());
227 
228  // And then get it initialized...
229  sym->parentFunction = ctx->GetFunction();
230  InitSymbol(sym->storagePtr, sym->type, initExpr, ctx, sym->pos);
231  }
232  }
233 }
234 
236  for (unsigned int i = 0; i < vars.size(); ++i) {
237  Expr *init = vars[i].init;
238  if (init != NULL && llvm::dyn_cast<ExprList>(init) == NULL) {
239  // If the variable is const-qualified, after we've optimized
240  // the initializer expression, see if we have a ConstExpr. If
241  // so, save it in Symbol::constValue where it can be used in
242  // optimizing later expressions that have this symbol in them.
243  // Note that there are cases where the expression may be
244  // constant but where we don't have a ConstExpr; an example is
245  // const arrays--the ConstExpr implementation just can't
246  // represent an array of values.
247  //
248  // All this is fine in terms of the code that's generated in
249  // the end (LLVM's constant folding stuff is good), but it
250  // means that the ispc compiler's ability to reason about what
251  // is definitely a compile-time constant for things like
252  // computing array sizes from non-trivial expressions is
253  // consequently limited.
254  Symbol *sym = vars[i].sym;
255  if (sym->type && sym->type->IsConstType() && Type::Equal(init->GetType(), sym->type))
256  sym->constValue = llvm::dyn_cast<ConstExpr>(init);
257  }
258  }
259  return this;
260 }
261 
262 // Do type conversion if needed and check for not initializing array with
263 // another array (array assignment is not allowed).
264 // Do that recursively to handle brace initialization, which may contain
265 // another brace initialization.
266 static bool checkInit(const Type *type, Expr **init) {
267  bool encounteredError = false;
268 
269  // get the right type for stuff like const float foo = 2; so that
270  // the int->float type conversion is in there and we don't return
271  // an int as the constValue later...
272  if (CastType<AtomicType>(type) != NULL || CastType<EnumType>(type) != NULL) {
273  // If it's an expr list with an atomic type, we'll later issue
274  // an error. Need to leave vars[i].init as is in that case so
275  // it is in fact caught later, though.
276  if (llvm::dyn_cast<ExprList>(*init) == NULL) {
277  *init = TypeConvertExpr(*init, type, "initializer");
278  if (*init == NULL)
279  encounteredError = true;
280  }
281  } else if (CastType<ArrayType>(type) != NULL && llvm::dyn_cast<ExprList>(*init) == NULL) {
282  encounteredError = true;
283  Error((*init)->pos, "Array initializer must be an initializer list");
284  } else if (CastType<StructType>(type) != NULL && llvm::dyn_cast<ExprList>(*init) != NULL) {
285  const StructType *st = CastType<StructType>(type);
286  ExprList *el = llvm::dyn_cast<ExprList>(*init);
287  int elt_count = st->GetElementCount() < el->exprs.size() ? st->GetElementCount() : el->exprs.size();
288  for (int i = 0; i < elt_count; i++) {
289  encounteredError |= checkInit(st->GetElementType(i), &(el->exprs[i]));
290  }
291  }
292 
293  return encounteredError;
294 }
295 
297  bool encounteredError = false;
298  for (unsigned int i = 0; i < vars.size(); ++i) {
299  if (vars[i].sym == NULL) {
300  encounteredError = true;
301  continue;
302  }
303 
304  if (vars[i].init == NULL)
305  continue;
306 
307  // Check an init.
308  encounteredError |= checkInit(vars[i].sym->type, &(vars[i].init));
309  }
310  return encounteredError ? NULL : this;
311 }
312 
313 void DeclStmt::Print(int indent) const {
314  printf("%*cDecl Stmt:", indent, ' ');
315  pos.Print();
316  for (unsigned int i = 0; i < vars.size(); ++i) {
317  printf("%*cVariable %s (%s)", indent + 4, ' ', vars[i].sym->name.c_str(),
318  vars[i].sym->type->GetString().c_str());
319  if (vars[i].init != NULL) {
320  printf(" = ");
321  vars[i].init->Print();
322  }
323  printf("\n");
324  }
325  printf("\n");
326 }
327 
328 int DeclStmt::EstimateCost() const { return 0; }
329 
330 ///////////////////////////////////////////////////////////////////////////
331 // IfStmt
332 
333 IfStmt::IfStmt(Expr *t, Stmt *ts, Stmt *fs, bool checkCoherence, SourcePos p)
334  : Stmt(p, IfStmtID), test(t), trueStmts(ts), falseStmts(fs),
335  doAllCheck(checkCoherence && !g->opt.disableCoherentControlFlow) {}
336 
337 static void lEmitIfStatements(FunctionEmitContext *ctx, Stmt *stmts, const char *trueOrFalse) {
338  if (!stmts)
339  return;
340 
341  if (llvm::dyn_cast<StmtList>(stmts) == NULL)
342  ctx->StartScope();
343  ctx->AddInstrumentationPoint(trueOrFalse);
344  stmts->EmitCode(ctx);
345  if (llvm::dyn_cast<const StmtList>(stmts) == NULL)
346  ctx->EndScope();
347 }
348 
349 /** Returns true if the "true" block for the if statement consists of a
350  single 'break' statement, and the "false" block is empty. */
351 /*
352 static bool
353 lCanApplyBreakOptimization(Stmt *trueStmts, Stmt *falseStmts) {
354  if (falseStmts != NULL) {
355  if (StmtList *sl = llvm::dyn_cast<StmtList>(falseStmts)) {
356  return (sl->stmts.size() == 0);
357  }
358  else
359  return false;
360  }
361 
362  if (llvm::dyn_cast<BreakStmt>(trueStmts))
363  return true;
364  else if (StmtList *sl = llvm::dyn_cast<StmtList>(trueStmts))
365  return (sl->stmts.size() == 1 &&
366  llvm::dyn_cast<BreakStmt>(sl->stmts[0]) != NULL);
367  else
368  return false;
369 }
370 */
371 
373  // First check all of the things that might happen due to errors
374  // earlier in compilation and bail out if needed so that we don't
375  // dereference NULL pointers in the below...
376  if (!ctx->GetCurrentBasicBlock())
377  return;
378  if (!test)
379  return;
380  const Type *testType = test->GetType();
381  if (!testType)
382  return;
383 
384  ctx->SetDebugPos(pos);
385  bool isUniform = testType->IsUniformType();
386 
387  llvm::Value *testValue = test->GetValue(ctx);
388  if (testValue == NULL)
389  return;
390 
391  if (isUniform) {
392  ctx->StartUniformIf();
393  if (doAllCheck)
394  Warning(test->pos, "Uniform condition supplied to \"cif\" statement.");
395 
396  // 'If' statements with uniform conditions are relatively
397  // straightforward. We evaluate the condition and then jump to
398  // either the 'then' or 'else' clause depending on its value.
399  llvm::BasicBlock *bthen = ctx->CreateBasicBlock("if_then");
400  llvm::BasicBlock *belse = ctx->CreateBasicBlock("if_else");
401  llvm::BasicBlock *bexit = ctx->CreateBasicBlock("if_exit");
402 
403  // Jump to the appropriate basic block based on the value of
404  // the 'if' test
405  ctx->BranchInst(bthen, belse, testValue);
406 
407  // Emit code for the 'true' case
408  ctx->SetCurrentBasicBlock(bthen);
409  lEmitIfStatements(ctx, trueStmts, "true");
410  if (ctx->GetCurrentBasicBlock())
411  ctx->BranchInst(bexit);
412 
413  // Emit code for the 'false' case
414  ctx->SetCurrentBasicBlock(belse);
415  lEmitIfStatements(ctx, falseStmts, "false");
416  if (ctx->GetCurrentBasicBlock())
417  ctx->BranchInst(bexit);
418 
419  // Set the active basic block to the newly-created exit block
420  // so that subsequent emitted code starts there.
421  ctx->SetCurrentBasicBlock(bexit);
422  ctx->EndIf();
423  }
424  /*
425  // Disabled for performance reasons. Change to an optional compile-time opt switch.
426  else if (lCanApplyBreakOptimization(trueStmts, falseStmts)) {
427  // If we have a simple break statement inside the 'if' and are
428  // under varying control flow, just update the execution mask
429  // directly and don't emit code for the statements. This leads to
430  // better code for this case--this is surprising and should be
431  // root-caused further, but for now this gives us performance
432  // benefit in this case.
433  ctx->SetInternalMaskAndNot(ctx->GetInternalMask(), testValue);
434  }
435  */
436  else
437  emitVaryingIf(ctx, testValue);
438 }
439 
441  if (test != NULL) {
442  const Type *testType = test->GetType();
443  if (testType != NULL) {
444  bool isUniform = (testType->IsUniformType() && !g->opt.disableUniformControlFlow);
446  "\"if\" statement test");
447  if (test == NULL)
448  return NULL;
449  }
450  }
451 
452  return this;
453 }
454 
455 int IfStmt::EstimateCost() const {
456  const Type *type;
457  if (test == NULL || (type = test->GetType()) == NULL)
458  return 0;
459 
460  return type->IsUniformType() ? COST_UNIFORM_IF : COST_VARYING_IF;
461 }
462 
463 void IfStmt::Print(int indent) const {
464  printf("%*cIf Stmt %s", indent, ' ', doAllCheck ? "DO ALL CHECK" : "");
465  pos.Print();
466  printf("\n%*cTest: ", indent + 4, ' ');
467  test->Print();
468  printf("\n");
469  if (trueStmts) {
470  printf("%*cTrue:\n", indent + 4, ' ');
471  trueStmts->Print(indent + 8);
472  }
473  if (falseStmts) {
474  printf("%*cFalse:\n", indent + 4, ' ');
475  falseStmts->Print(indent + 8);
476  }
477 }
478 
479 /** Emit code to run both the true and false statements for the if test,
480  with the mask set appropriately before running each one.
481 */
482 void IfStmt::emitMaskedTrueAndFalse(FunctionEmitContext *ctx, llvm::Value *oldMask, llvm::Value *test) const {
483  if (trueStmts) {
484  ctx->SetInternalMaskAnd(oldMask, test);
485  lEmitIfStatements(ctx, trueStmts, "if: expr mixed, true statements");
486  // under varying control flow,, returns can't stop instruction
487  // emission, so this better be non-NULL...
489  }
490  if (falseStmts) {
491  ctx->SetInternalMaskAndNot(oldMask, test);
492  lEmitIfStatements(ctx, falseStmts, "if: expr mixed, false statements");
494  }
495 }
496 
497 /** Emit code for an if test that checks the mask and the test values and
498  tries to be smart about jumping over code that doesn't need to be run.
499  */
500 void IfStmt::emitVaryingIf(FunctionEmitContext *ctx, llvm::Value *ltest) const {
501  llvm::Value *oldMask = ctx->GetInternalMask();
502  if (doAllCheck) {
503  // We can't tell if the mask going into the if is all on at the
504  // compile time. Emit code to check for this and then either run
505  // the code for the 'all on' or the 'mixed' case depending on the
506  // mask's value at runtime.
507  llvm::BasicBlock *bAllOn = ctx->CreateBasicBlock("cif_mask_all");
508  llvm::BasicBlock *bMixedOn = ctx->CreateBasicBlock("cif_mask_mixed");
509  llvm::BasicBlock *bDone = ctx->CreateBasicBlock("cif_done");
510 
511  // Jump to either bAllOn or bMixedOn, depending on the mask's value
512  llvm::Value *maskAllQ = ctx->All(ctx->GetFullMask());
513  ctx->BranchInst(bAllOn, bMixedOn, maskAllQ);
514 
515  // Emit code for the 'mask all on' case
516  ctx->SetCurrentBasicBlock(bAllOn);
517  emitMaskAllOn(ctx, ltest, bDone);
518 
519  // And emit code for the mixed mask case
520  ctx->SetCurrentBasicBlock(bMixedOn);
521  emitMaskMixed(ctx, oldMask, ltest, bDone);
522 
523  // When done, set the current basic block to the block that the two
524  // paths above jump to when they're done.
525  ctx->SetCurrentBasicBlock(bDone);
526  } else if (trueStmts != NULL || falseStmts != NULL) {
527  // If there is nothing that is potentially unsafe to run with all
528  // lanes off in the true and false statements and if the total
529  // complexity of those two is relatively simple, then we'll go
530  // ahead and emit straightline code that runs both sides, updating
531  // the mask accordingly. This is useful for efficiently compiling
532  // things like:
533  //
534  // if (foo) x = 0;
535  // else ++x;
536  //
537  // Where the overhead of checking if any of the program instances wants
538  // to run one side or the other is more than the actual computation.
539  // SafeToRunWithMaskAllOff() checks to make sure that we don't do this
540  // for potentially dangerous code like:
541  //
542  // if (index < count) array[index] = 0;
543  //
544  // where our use of blend for conditional assignments doesn't check
545  // for the 'all lanes' off case.
546  int trueFalseCost = (::EstimateCost(trueStmts) + ::EstimateCost(falseStmts));
547  bool costIsAcceptable = (trueFalseCost < PREDICATE_SAFE_IF_STATEMENT_COST);
548 
549  bool safeToRunWithAllLanesOff = (SafeToRunWithMaskAllOff(trueStmts) && SafeToRunWithMaskAllOff(falseStmts));
550 
551  Debug(pos, "If statement: true cost %d (safe %d), false cost %d (safe %d).", ::EstimateCost(trueStmts),
554 
555  if (safeToRunWithAllLanesOff && (costIsAcceptable || g->opt.disableCoherentControlFlow)) {
556  ctx->StartVaryingIf(oldMask);
557  emitMaskedTrueAndFalse(ctx, oldMask, ltest);
559  ctx->EndIf();
560  } else {
561  llvm::BasicBlock *bDone = ctx->CreateBasicBlock("if_done");
562  emitMaskMixed(ctx, oldMask, ltest, bDone);
563  ctx->SetCurrentBasicBlock(bDone);
564  }
565  }
566 }
567 
568 /** Emits code for 'if' tests under the case where we know that the program
569  mask is all on going into the 'if'.
570  */
571 void IfStmt::emitMaskAllOn(FunctionEmitContext *ctx, llvm::Value *ltest, llvm::BasicBlock *bDone) const {
572  // We start by explicitly storing "all on" into the mask mask. Note
573  // that this doesn't change its actual value, but doing so lets the
574  // compiler see what's going on so that subsequent optimizations for
575  // code emitted here can operate with the knowledge that the mask is
576  // definitely all on (until it modifies the mask itself).
580  llvm::Value *oldFunctionMask = ctx->GetFunctionMask();
583 
584  // First, check the value of the test. If it's all on, then we jump to
585  // a basic block that will only have code for the true case.
586  llvm::BasicBlock *bTestAll = ctx->CreateBasicBlock("cif_test_all");
587  llvm::BasicBlock *bTestNoneCheck = ctx->CreateBasicBlock("cif_test_none_check");
588  llvm::Value *testAllQ = ctx->All(ltest);
589  ctx->BranchInst(bTestAll, bTestNoneCheck, testAllQ);
590 
591  // Emit code for the 'test is all true' case
592  ctx->SetCurrentBasicBlock(bTestAll);
594  lEmitIfStatements(ctx, trueStmts, "if: all on mask, expr all true");
595  ctx->EndIf();
596  if (ctx->GetCurrentBasicBlock() != NULL)
597  // bblock may legitimately be NULL since if there's a return stmt
598  // or break or continue we can actually jump and end emission since
599  // we know all of the lanes are following this path...
600  ctx->BranchInst(bDone);
601 
602  // The test isn't all true. Now emit code to determine if it's all
603  // false, or has mixed values.
604  ctx->SetCurrentBasicBlock(bTestNoneCheck);
605  llvm::BasicBlock *bTestNone = ctx->CreateBasicBlock("cif_test_none");
606  llvm::BasicBlock *bTestMixed = ctx->CreateBasicBlock("cif_test_mixed");
607  llvm::Value *testMixedQ = ctx->Any(ltest);
608  ctx->BranchInst(bTestMixed, bTestNone, testMixedQ);
609 
610  // Emit code for the 'test is all false' case
611  ctx->SetCurrentBasicBlock(bTestNone);
613  lEmitIfStatements(ctx, falseStmts, "if: all on mask, expr all false");
614  ctx->EndIf();
615  if (ctx->GetCurrentBasicBlock())
616  // bblock may be NULL since if there's a return stmt or break or
617  // continue we can actually jump or whatever and end emission...
618  ctx->BranchInst(bDone);
619 
620  // Finally emit code for the 'mixed true/false' case. We unavoidably
621  // need to run both the true and the false statements.
622  ctx->SetCurrentBasicBlock(bTestMixed);
625  // In this case, return/break/continue isn't allowed to jump and end
626  // emission.
628  ctx->EndIf();
629  ctx->BranchInst(bDone);
630 
631  ctx->SetCurrentBasicBlock(bDone);
632  ctx->SetFunctionMask(oldFunctionMask);
633 }
634 
635 /** Emit code for an 'if' test where the lane mask is known to be mixed
636  on/off going into it.
637  */
638 void IfStmt::emitMaskMixed(FunctionEmitContext *ctx, llvm::Value *oldMask, llvm::Value *ltest,
639  llvm::BasicBlock *bDone) const {
640  ctx->StartVaryingIf(oldMask);
641  llvm::BasicBlock *bNext = ctx->CreateBasicBlock("safe_if_after_true");
642 
643  llvm::BasicBlock *bRunTrue = ctx->CreateBasicBlock("safe_if_run_true");
644  ctx->SetInternalMaskAnd(oldMask, ltest);
645 
646  // Do any of the program instances want to run the 'true'
647  // block? If not, jump ahead to bNext.
648 
649  llvm::Value *maskAnyTrueQ = ctx->Any(ctx->GetFullMask());
650 
651  ctx->BranchInst(bRunTrue, bNext, maskAnyTrueQ);
652 
653  // Emit statements for true
654  ctx->SetCurrentBasicBlock(bRunTrue);
655  if (trueStmts != NULL)
656  lEmitIfStatements(ctx, trueStmts, "if: expr mixed, true statements");
658  ctx->BranchInst(bNext);
659  ctx->SetCurrentBasicBlock(bNext);
660 
661  // False...
662  llvm::BasicBlock *bRunFalse = ctx->CreateBasicBlock("safe_if_run_false");
663  ctx->SetInternalMaskAndNot(oldMask, ltest);
664 
665  // Similarly, check to see if any of the instances want to
666  // run the 'false' block...
667 
668  llvm::Value *maskAnyFalseQ = ctx->Any(ctx->GetFullMask());
669  ctx->BranchInst(bRunFalse, bDone, maskAnyFalseQ);
670 
671  // Emit code for false
672  ctx->SetCurrentBasicBlock(bRunFalse);
673  if (falseStmts)
674  lEmitIfStatements(ctx, falseStmts, "if: expr mixed, false statements");
676 
677  ctx->BranchInst(bDone);
678  ctx->SetCurrentBasicBlock(bDone);
679  ctx->EndIf();
680 }
681 
682 ///////////////////////////////////////////////////////////////////////////
683 // DoStmt
684 
687  varyingControlFlowDepth = 0;
688  foundVaryingBreakOrContinue = false;
689  }
690 
693 };
694 
695 /** Returns true if the given node is an 'if' statement where the test
696  condition has varying type. */
697 static bool lIsVaryingFor(ASTNode *node) {
698  IfStmt *ifStmt;
699  if ((ifStmt = llvm::dyn_cast<IfStmt>(node)) != NULL && ifStmt->test != NULL) {
700  const Type *type = ifStmt->test->GetType();
701  return (type != NULL && type->IsVaryingType());
702  } else
703  return false;
704 }
705 
706 /** Preorder callback function for checking for varying breaks or
707  continues. */
708 static bool lVaryingBCPreFunc(ASTNode *node, void *d) {
710 
711  // We found a break or continue statement; if we're under varying
712  // control flow, then bingo.
713  if ((llvm::dyn_cast<BreakStmt>(node) != NULL || llvm::dyn_cast<ContinueStmt>(node) != NULL) &&
714  info->varyingControlFlowDepth > 0) {
715  info->foundVaryingBreakOrContinue = true;
716  return false;
717  }
718 
719  // Update the count of the nesting depth of varying control flow if
720  // this is an if statement with a varying condition.
721  if (lIsVaryingFor(node))
722  ++info->varyingControlFlowDepth;
723 
724  if (llvm::dyn_cast<ForStmt>(node) != NULL || llvm::dyn_cast<DoStmt>(node) != NULL ||
725  llvm::dyn_cast<ForeachStmt>(node) != NULL)
726  // Don't recurse into these guys, since we don't care about varying
727  // breaks or continues within them...
728  return false;
729  else
730  return true;
731 }
732 
733 /** Postorder callback function for checking for varying breaks or
734  continues; decrement the varying control flow depth after the node's
735  children have been processed, if this is a varying if statement. */
736 static ASTNode *lVaryingBCPostFunc(ASTNode *node, void *d) {
738  if (lIsVaryingFor(node))
739  --info->varyingControlFlowDepth;
740  return node;
741 }
742 
743 /** Given a statment, walk through it to see if there is a 'break' or
744  'continue' statement inside if its children, under varying control
745  flow. We need to detect this case for loops since what might otherwise
746  look like a 'uniform' loop needs to have code emitted to do all of the
747  lane management stuff if this is the case.
748  */
749 static bool lHasVaryingBreakOrContinue(Stmt *stmt) {
750  VaryingBCCheckInfo info;
752  return info.foundVaryingBreakOrContinue;
753 }
754 
755 DoStmt::DoStmt(Expr *t, Stmt *s, bool cc, SourcePos p)
756  : Stmt(p, DoStmtID), testExpr(t), bodyStmts(s), doCoherentCheck(cc && !g->opt.disableCoherentControlFlow) {}
757 
759  // Check for things that could be NULL due to earlier errors during
760  // compilation.
761  if (!ctx->GetCurrentBasicBlock())
762  return;
763  if (!testExpr || !testExpr->GetType())
764  return;
765 
766  bool uniformTest = testExpr->GetType()->IsUniformType();
767  if (uniformTest && doCoherentCheck)
768  Warning(testExpr->pos, "Uniform condition supplied to \"cdo\" "
769  "statement.");
770 
771  llvm::BasicBlock *bloop = ctx->CreateBasicBlock("do_loop");
772  llvm::BasicBlock *bexit = ctx->CreateBasicBlock("do_exit");
773  llvm::BasicBlock *btest = ctx->CreateBasicBlock("do_test");
774 
775  ctx->StartLoop(bexit, btest, uniformTest);
776 
777  // Start by jumping into the loop body
778  ctx->BranchInst(bloop);
779 
780  // And now emit code for the loop body
781  ctx->SetCurrentBasicBlock(bloop);
782  ctx->SetBlockEntryMask(ctx->GetFullMask());
783  ctx->SetDebugPos(pos);
784  // FIXME: in the StmtList::EmitCode() method takes starts/stops a new
785  // scope around the statements in the list. So if the body is just a
786  // single statement (and thus not a statement list), we need a new
787  // scope, but we don't want two scopes in the StmtList case.
788  if (!bodyStmts || !llvm::dyn_cast<StmtList>(bodyStmts))
789  ctx->StartScope();
790 
791  ctx->AddInstrumentationPoint("do loop body");
792  if (doCoherentCheck && !uniformTest) {
793  // Check to see if the mask is all on
794  llvm::BasicBlock *bAllOn = ctx->CreateBasicBlock("do_all_on");
795  llvm::BasicBlock *bMixed = ctx->CreateBasicBlock("do_mixed");
796  ctx->BranchIfMaskAll(bAllOn, bMixed);
797 
798  // If so, emit code for the 'mask all on' case. In particular,
799  // explicitly set the mask to 'all on' (see rationale in
800  // IfStmt::emitCoherentTests()), and then emit the code for the
801  // loop body.
802  ctx->SetCurrentBasicBlock(bAllOn);
805  llvm::Value *oldFunctionMask = ctx->GetFunctionMask();
808  if (bodyStmts)
809  bodyStmts->EmitCode(ctx);
811  ctx->SetFunctionMask(oldFunctionMask);
812  ctx->BranchInst(btest);
813 
814  // The mask is mixed. Just emit the code for the loop body.
815  ctx->SetCurrentBasicBlock(bMixed);
816  if (bodyStmts)
817  bodyStmts->EmitCode(ctx);
819  ctx->BranchInst(btest);
820  } else {
821  // Otherwise just emit the code for the loop body. The current
822  // mask is good.
823  if (bodyStmts)
824  bodyStmts->EmitCode(ctx);
825  if (ctx->GetCurrentBasicBlock())
826  ctx->BranchInst(btest);
827  }
828  // End the scope we started above, if needed.
829  if (!bodyStmts || !llvm::dyn_cast<StmtList>(bodyStmts))
830  ctx->EndScope();
831 
832  // Now emit code for the loop test.
833  ctx->SetCurrentBasicBlock(btest);
834  // First, emit code to restore the mask value for any lanes that
835  // executed a 'continue' during the current loop before we go and emit
836  // the code for the test. This is only necessary for varying loops;
837  // 'uniform' loops just jump when they hit a continue statement and
838  // don't mess with the mask.
839  if (!uniformTest) {
840  ctx->RestoreContinuedLanes();
841  ctx->ClearBreakLanes();
842  }
843  llvm::Value *testValue = testExpr->GetValue(ctx);
844  if (!testValue)
845  return;
846 
847  if (uniformTest)
848  // For the uniform case, just jump to the top of the loop or the
849  // exit basic block depending on the value of the test.
850  ctx->BranchInst(bloop, bexit, testValue);
851  else {
852  // For the varying case, update the mask based on the value of the
853  // test. If any program instances still want to be running, jump
854  // to the top of the loop. Otherwise, jump out.
855  llvm::Value *mask = ctx->GetInternalMask();
856  ctx->SetInternalMaskAnd(mask, testValue);
857  ctx->BranchIfMaskAny(bloop, bexit);
858  }
859 
860  // ...and we're done. Set things up for subsequent code to be emitted
861  // in the right basic block.
862  ctx->SetCurrentBasicBlock(bexit);
863  ctx->EndLoop();
864 }
865 
867  const Type *testType;
868  if (testExpr != NULL && (testType = testExpr->GetType()) != NULL) {
869  // Should the test condition for the loop be uniform or varying?
870  // It can be uniform only if three conditions are met:
871  //
872  // - First and foremost, the type of the test condition must be
873  // uniform.
874  //
875  // - Second, the user must not have set the dis-optimization option
876  // that disables uniform flow control.
877  //
878  // - Thirdly, and most subtlely, there must not be any break or
879  // continue statements inside the loop that are within the scope
880  // of a 'varying' if statement. If there are, then we type cast
881  // the test to be 'varying', so that the code generated for the
882  // loop includes masking stuff, so that we can track which lanes
883  // actually want to be running, accounting for breaks/continues.
884  //
885  bool uniformTest =
888  "\"do\" statement");
889  }
890 
891  return this;
892 }
893 
894 int DoStmt::EstimateCost() const {
895  bool uniformTest = testExpr ? testExpr->GetType()->IsUniformType()
897 
898  return uniformTest ? COST_UNIFORM_LOOP : COST_VARYING_LOOP;
899 }
900 
901 void DoStmt::Print(int indent) const {
902  printf("%*cDo Stmt", indent, ' ');
903  pos.Print();
904  printf(":\n");
905  printf("%*cTest: ", indent + 4, ' ');
906  if (testExpr)
907  testExpr->Print();
908  printf("\n");
909  if (bodyStmts) {
910  printf("%*cStmts:\n", indent + 4, ' ');
911  bodyStmts->Print(indent + 8);
912  }
913 }
914 
915 ///////////////////////////////////////////////////////////////////////////
916 // ForStmt
917 
918 ForStmt::ForStmt(Stmt *i, Expr *t, Stmt *s, Stmt *st, bool cc, SourcePos p)
919  : Stmt(p, ForStmtID), init(i), test(t), step(s), stmts(st),
920  doCoherentCheck(cc && !g->opt.disableCoherentControlFlow) {}
921 
923  if (!ctx->GetCurrentBasicBlock())
924  return;
925 
926  llvm::BasicBlock *btest = ctx->CreateBasicBlock("for_test");
927  llvm::BasicBlock *bstep = ctx->CreateBasicBlock("for_step");
928  llvm::BasicBlock *bloop = ctx->CreateBasicBlock("for_loop");
929  llvm::BasicBlock *bexit = ctx->CreateBasicBlock("for_exit");
930 
931  bool uniformTest = test ? test->GetType()->IsUniformType()
933 
934  ctx->StartLoop(bexit, bstep, uniformTest);
935  ctx->SetDebugPos(pos);
936 
937  // If we have an initiailizer statement, start by emitting the code for
938  // it and then jump into the loop test code. (Also start a new scope
939  // since the initiailizer may be a declaration statement).
940  if (init) {
941  AssertPos(pos, llvm::dyn_cast<StmtList>(init) == NULL);
942  ctx->StartScope();
943  init->EmitCode(ctx);
944  }
945  ctx->BranchInst(btest);
946 
947  // Emit code to get the value of the loop test. If no test expression
948  // was provided, just go with a true value.
949  ctx->SetCurrentBasicBlock(btest);
950  llvm::Value *ltest = NULL;
951  if (test) {
952  ltest = test->GetValue(ctx);
953  if (!ltest) {
954  // We need to end scope only if we had initializer statement.
955  if (init) {
956  ctx->EndScope();
957  }
958  ctx->EndLoop();
959  return;
960  }
961  } else
962  ltest = uniformTest ? LLVMTrue : LLVMBoolVector(true);
963 
964  // Now use the test's value. For a uniform loop, we can either jump to
965  // the loop body or the loop exit, based on whether it's true or false.
966  // For a non-uniform loop, we update the mask and jump into the loop if
967  // any of the mask values are true.
968  if (uniformTest) {
969  if (doCoherentCheck)
970  if (test)
971  Warning(test->pos, "Uniform condition supplied to cfor/cwhile "
972  "statement.");
973  AssertPos(pos, ltest->getType() == LLVMTypes::BoolType);
974  ctx->BranchInst(bloop, bexit, ltest);
975  } else {
976  llvm::Value *mask = ctx->GetInternalMask();
977  ctx->SetInternalMaskAnd(mask, ltest);
978  ctx->BranchIfMaskAny(bloop, bexit);
979  }
980 
981  // On to emitting the code for the loop body.
982  ctx->SetCurrentBasicBlock(bloop);
983  ctx->SetBlockEntryMask(ctx->GetFullMask());
984  ctx->AddInstrumentationPoint("for loop body");
985  if (!llvm::dyn_cast_or_null<StmtList>(stmts))
986  ctx->StartScope();
987 
988  if (doCoherentCheck && !uniformTest) {
989  // For 'varying' loops with the coherence check, we start by
990  // checking to see if the mask is all on, after it has been updated
991  // based on the value of the test.
992  llvm::BasicBlock *bAllOn = ctx->CreateBasicBlock("for_all_on");
993  llvm::BasicBlock *bMixed = ctx->CreateBasicBlock("for_mixed");
994  ctx->BranchIfMaskAll(bAllOn, bMixed);
995 
996  // Emit code for the mask being all on. Explicitly set the mask to
997  // be on so that the optimizer can see that it's on (i.e. now that
998  // the runtime test has passed, make this fact clear for code
999  // generation at compile time here.)
1000  ctx->SetCurrentBasicBlock(bAllOn);
1003  llvm::Value *oldFunctionMask = ctx->GetFunctionMask();
1006  if (stmts)
1007  stmts->EmitCode(ctx);
1009  ctx->SetFunctionMask(oldFunctionMask);
1010  ctx->BranchInst(bstep);
1011 
1012  // Emit code for the mask being mixed. We should never run the
1013  // loop with the mask all off, based on the BranchIfMaskAny call
1014  // above.
1015  ctx->SetCurrentBasicBlock(bMixed);
1016  if (stmts)
1017  stmts->EmitCode(ctx);
1018  ctx->BranchInst(bstep);
1019  } else {
1020  // For both uniform loops and varying loops without the coherence
1021  // check, we know that at least one program instance wants to be
1022  // running the loop, so just emit code for the loop body and jump
1023  // to the loop step code.
1024  if (stmts)
1025  stmts->EmitCode(ctx);
1026  if (ctx->GetCurrentBasicBlock())
1027  ctx->BranchInst(bstep);
1028  }
1029  if (!llvm::dyn_cast_or_null<StmtList>(stmts))
1030  ctx->EndScope();
1031 
1032  // Emit code for the loop step. First, restore the lane mask of any
1033  // program instances that executed a 'continue' during the previous
1034  // iteration. Then emit code for the loop step and then jump to the
1035  // test code.
1036  ctx->SetCurrentBasicBlock(bstep);
1037  ctx->RestoreContinuedLanes();
1038  ctx->ClearBreakLanes();
1039 
1040  if (step)
1041  step->EmitCode(ctx);
1042  ctx->BranchInst(btest);
1043 
1044  // Set the current emission basic block to the loop exit basic block
1045  ctx->SetCurrentBasicBlock(bexit);
1046  if (init)
1047  ctx->EndScope();
1048  ctx->EndLoop();
1049 }
1050 
1052  const Type *testType;
1053  if (test && (testType = test->GetType()) != NULL) {
1054  // See comments in DoStmt::TypeCheck() regarding
1055  // 'uniformTest' and the type conversion here.
1056  bool uniformTest =
1059  "\"for\"/\"while\" statement");
1060  if (test == NULL)
1061  return NULL;
1062  }
1063 
1064  return this;
1065 }
1066 
1068  bool uniformTest = test ? test->GetType()->IsUniformType()
1070 
1071  return uniformTest ? COST_UNIFORM_LOOP : COST_VARYING_LOOP;
1072 }
1073 
1074 void ForStmt::Print(int indent) const {
1075  printf("%*cFor Stmt", indent, ' ');
1076  pos.Print();
1077  printf("\n");
1078  if (init) {
1079  printf("%*cInit:\n", indent + 4, ' ');
1080  init->Print(indent + 8);
1081  }
1082  if (test) {
1083  printf("%*cTest: ", indent + 4, ' ');
1084  test->Print();
1085  printf("\n");
1086  }
1087  if (step) {
1088  printf("%*cStep:\n", indent + 4, ' ');
1089  step->Print(indent + 8);
1090  }
1091  if (stmts) {
1092  printf("%*cStmts:\n", indent + 4, ' ');
1093  stmts->Print(indent + 8);
1094  }
1095 }
1096 
1097 ///////////////////////////////////////////////////////////////////////////
1098 // BreakStmt
1099 
1101 
1103  if (!ctx->GetCurrentBasicBlock())
1104  return;
1105 
1106  ctx->SetDebugPos(pos);
1107  ctx->Break(true);
1108 }
1109 
1110 Stmt *BreakStmt::TypeCheck() { return this; }
1111 
1113 
1114 void BreakStmt::Print(int indent) const {
1115  printf("%*cBreak Stmt", indent, ' ');
1116  pos.Print();
1117  printf("\n");
1118 }
1119 
1120 ///////////////////////////////////////////////////////////////////////////
1121 // ContinueStmt
1122 
1124 
1126  if (!ctx->GetCurrentBasicBlock())
1127  return;
1128 
1129  ctx->SetDebugPos(pos);
1130  ctx->Continue(true);
1131 }
1132 
1133 Stmt *ContinueStmt::TypeCheck() { return this; }
1134 
1136 
1137 void ContinueStmt::Print(int indent) const {
1138  printf("%*cContinue Stmt", indent, ' ');
1139  pos.Print();
1140  printf("\n");
1141 }
1142 
1143 ///////////////////////////////////////////////////////////////////////////
1144 // ForeachStmt
1145 
1146 ForeachStmt::ForeachStmt(const std::vector<Symbol *> &lvs, const std::vector<Expr *> &se, const std::vector<Expr *> &ee,
1147  Stmt *s, bool t, SourcePos pos)
1148  : Stmt(pos, ForeachStmtID), dimVariables(lvs), startExprs(se), endExprs(ee), isTiled(t), stmts(s) {}
1149 
1150 /* Given a uniform counter value in the memory location pointed to by
1151  uniformCounterPtr, compute the corresponding set of varying counter
1152  values for use within the loop body.
1153  */
1154 static llvm::Value *lUpdateVaryingCounter(int dim, int nDims, FunctionEmitContext *ctx, llvm::Value *uniformCounterPtr,
1155  llvm::Value *varyingCounterPtr, const std::vector<int> &spans) {
1156  // Smear the uniform counter value out to be varying
1157  llvm::Value *counter = ctx->LoadInst(uniformCounterPtr);
1158  llvm::Value *smearCounter = ctx->BroadcastValue(counter, LLVMTypes::Int32VectorType, "smear_counter");
1159 
1160  // Figure out the offsets; this is a little bit tricky. As an example,
1161  // consider a 2D tiled foreach loop, where we're running 8-wide and
1162  // where the inner dimension has a stride of 4 and the outer dimension
1163  // has a stride of 2. For the inner dimension, we want the offsets
1164  // (0,1,2,3,0,1,2,3), and for the outer dimension we want
1165  // (0,0,0,0,1,1,1,1).
1166  int32_t delta[ISPC_MAX_NVEC];
1167  for (int i = 0; i < g->target->getVectorWidth(); ++i) {
1168  int d = i;
1169  // First, account for the effect of any dimensions at deeper
1170  // nesting levels than the current one.
1171  int prevDimSpanCount = 1;
1172  for (int j = dim; j < nDims - 1; ++j)
1173  prevDimSpanCount *= spans[j + 1];
1174  d /= prevDimSpanCount;
1175 
1176  // And now with what's left, figure out our own offset
1177  delta[i] = d % spans[dim];
1178  }
1179 
1180  // Add the deltas to compute the varying counter values; store the
1181  // result to memory and then return it directly as well.
1182  llvm::Value *varyingCounter =
1183  ctx->BinaryOperator(llvm::Instruction::Add, smearCounter, LLVMInt32Vector(delta), "iter_val");
1184  ctx->StoreInst(varyingCounter, varyingCounterPtr);
1185  return varyingCounter;
1186 }
1187 
1188 /** Returns the integer log2 of the given integer. */
1189 static int lLog2(int i) {
1190  int ret = 0;
1191  while (i != 0) {
1192  ++ret;
1193  i >>= 1;
1194  }
1195  return ret - 1;
1196 }
1197 
1198 /* Figure out how many elements to process in each dimension for each time
1199  through a foreach loop. The untiled case is easy; all of the outer
1200  dimensions up until the innermost one have a span of 1, and the
1201  innermost one takes the entire vector width. For the tiled case, we
1202  give wider spans to the innermost dimensions while also trying to
1203  generate relatively square domains.
1204 
1205  This code works recursively from outer dimensions to inner dimensions.
1206  */
1207 static void lGetSpans(int dimsLeft, int nDims, int itemsLeft, bool isTiled, int *a) {
1208  if (dimsLeft == 0) {
1209  // Nothing left to do but give all of the remaining work to the
1210  // innermost domain.
1211  *a = itemsLeft;
1212  return;
1213  }
1214 
1215  if (isTiled == false || (dimsLeft >= lLog2(itemsLeft)))
1216  // If we're not tiled, or if there are enough dimensions left that
1217  // giving this one any more than a span of one would mean that a
1218  // later dimension would have to have a span of one, give this one
1219  // a span of one to save the available items for later.
1220  *a = 1;
1221  else if (itemsLeft >= 16 && (dimsLeft == 1))
1222  // Special case to have 4x4 domains for the 2D case when running
1223  // 16-wide.
1224  *a = 4;
1225  else
1226  // Otherwise give this dimension a span of two.
1227  *a = 2;
1228 
1229  lGetSpans(dimsLeft - 1, nDims, itemsLeft / *a, isTiled, a + 1);
1230 }
1231 
1232 /* Emit code for a foreach statement. We effectively emit code to run the
1233  set of n-dimensional nested loops corresponding to the dimensionality of
1234  the foreach statement along with the extra logic to deal with mismatches
1235  between the vector width we're compiling to and the number of elements
1236  to process.
1237  */
1239  if (ctx->GetCurrentBasicBlock() == NULL || stmts == NULL)
1240  return;
1241 
1242  llvm::BasicBlock *bbFullBody = ctx->CreateBasicBlock("foreach_full_body");
1243  llvm::BasicBlock *bbMaskedBody = ctx->CreateBasicBlock("foreach_masked_body");
1244  llvm::BasicBlock *bbExit = ctx->CreateBasicBlock("foreach_exit");
1245 
1246  llvm::Value *oldMask = ctx->GetInternalMask();
1247  llvm::Value *oldFunctionMask = ctx->GetFunctionMask();
1248 
1249  ctx->SetDebugPos(pos);
1250  ctx->StartScope();
1251 
1254 
1255  // This should be caught during typechecking
1256  AssertPos(pos, startExprs.size() == dimVariables.size() && endExprs.size() == dimVariables.size());
1257  int nDims = (int)dimVariables.size();
1258 
1259  ///////////////////////////////////////////////////////////////////////
1260  // Setup: compute the number of items we have to work on in each
1261  // dimension and a number of derived values.
1262  std::vector<llvm::BasicBlock *> bbReset, bbStep, bbTest;
1263  std::vector<llvm::Value *> startVals, endVals, uniformCounterPtrs;
1264  std::vector<llvm::Value *> nExtras, alignedEnd, extrasMaskPtrs;
1265 
1266  std::vector<int> span(nDims, 0);
1267  lGetSpans(nDims - 1, nDims, g->target->getVectorWidth(), isTiled, &span[0]);
1268 
1269  for (int i = 0; i < nDims; ++i) {
1270  // Basic blocks that we'll fill in later with the looping logic for
1271  // this dimension.
1272  bbReset.push_back(ctx->CreateBasicBlock("foreach_reset"));
1273  if (i < nDims - 1)
1274  // stepping for the innermost dimension is handled specially
1275  bbStep.push_back(ctx->CreateBasicBlock("foreach_step"));
1276  bbTest.push_back(ctx->CreateBasicBlock("foreach_test"));
1277 
1278  // Start and end value for this loop dimension
1279  llvm::Value *sv = startExprs[i]->GetValue(ctx);
1280  llvm::Value *ev = endExprs[i]->GetValue(ctx);
1281  if (sv == NULL || ev == NULL)
1282  return;
1283  startVals.push_back(sv);
1284  endVals.push_back(ev);
1285 
1286  // nItems = endVal - startVal
1287  llvm::Value *nItems = ctx->BinaryOperator(llvm::Instruction::Sub, ev, sv, "nitems");
1288 
1289  // nExtras = nItems % (span for this dimension)
1290  // This gives us the number of extra elements we need to deal with
1291  // at the end of the loop for this dimension that don't fit cleanly
1292  // into a vector width.
1293  nExtras.push_back(ctx->BinaryOperator(llvm::Instruction::SRem, nItems, LLVMInt32(span[i]), "nextras"));
1294 
1295  // alignedEnd = endVal - nExtras
1296  alignedEnd.push_back(ctx->BinaryOperator(llvm::Instruction::Sub, ev, nExtras[i], "aligned_end"));
1297 
1298  ///////////////////////////////////////////////////////////////////////
1299  // Each dimension has a loop counter that is a uniform value that
1300  // goes from startVal to endVal, in steps of the span for this
1301  // dimension. Its value is only used internally here for looping
1302  // logic and isn't directly available in the user's program code.
1303  uniformCounterPtrs.push_back(ctx->AllocaInst(LLVMTypes::Int32Type, "counter"));
1304  ctx->StoreInst(startVals[i], uniformCounterPtrs[i]);
1305 
1306  // There is also a varying variable that holds the set of index
1307  // values for each dimension in the current loop iteration; this is
1308  // the value that is program-visible.
1309  dimVariables[i]->storagePtr = ctx->AllocaInst(LLVMTypes::Int32VectorType, dimVariables[i]->name.c_str());
1310  dimVariables[i]->parentFunction = ctx->GetFunction();
1312 
1313  // Each dimension also maintains a mask that represents which of
1314  // the varying elements in the current iteration should be
1315  // processed. (i.e. this is used to disable the lanes that have
1316  // out-of-bounds offsets.)
1317  extrasMaskPtrs.push_back(ctx->AllocaInst(LLVMTypes::MaskType, "extras mask"));
1318  ctx->StoreInst(LLVMMaskAllOn, extrasMaskPtrs[i]);
1319  }
1320 
1322 
1323  // On to the outermost loop's test
1324  ctx->BranchInst(bbTest[0]);
1325 
1326  ///////////////////////////////////////////////////////////////////////////
1327  // foreach_reset: this code runs when we need to reset the counter for
1328  // a given dimension in preparation for running through its loop again,
1329  // after the enclosing level advances its counter.
1330  for (int i = 0; i < nDims; ++i) {
1331  ctx->SetCurrentBasicBlock(bbReset[i]);
1332  if (i == 0)
1333  ctx->BranchInst(bbExit);
1334  else {
1335  ctx->StoreInst(LLVMMaskAllOn, extrasMaskPtrs[i]);
1336  ctx->StoreInst(startVals[i], uniformCounterPtrs[i]);
1337  ctx->BranchInst(bbStep[i - 1]);
1338  }
1339  }
1340 
1341  ///////////////////////////////////////////////////////////////////////////
1342  // foreach_step: increment the uniform counter by the vector width.
1343  // Note that we don't increment the varying counter here as well but
1344  // just generate its value when we need it in the loop body. Don't do
1345  // this for the innermost dimension, which has a more complex stepping
1346  // structure..
1347  for (int i = 0; i < nDims - 1; ++i) {
1348  ctx->SetCurrentBasicBlock(bbStep[i]);
1349  llvm::Value *counter = ctx->LoadInst(uniformCounterPtrs[i]);
1350  llvm::Value *newCounter =
1351  ctx->BinaryOperator(llvm::Instruction::Add, counter, LLVMInt32(span[i]), "new_counter");
1352  ctx->StoreInst(newCounter, uniformCounterPtrs[i]);
1353  ctx->BranchInst(bbTest[i]);
1354  }
1355 
1356  ///////////////////////////////////////////////////////////////////////////
1357  // foreach_test (for all dimensions other than the innermost...)
1358  std::vector<llvm::Value *> inExtras;
1359  for (int i = 0; i < nDims - 1; ++i) {
1360  ctx->SetCurrentBasicBlock(bbTest[i]);
1361 
1362  llvm::Value *haveExtras =
1363  ctx->CmpInst(llvm::Instruction::ICmp, llvm::CmpInst::ICMP_SGT, endVals[i], alignedEnd[i], "have_extras");
1364 
1365  llvm::Value *counter = ctx->LoadInst(uniformCounterPtrs[i], NULL, "counter");
1366  llvm::Value *atAlignedEnd =
1367  ctx->CmpInst(llvm::Instruction::ICmp, llvm::CmpInst::ICMP_EQ, counter, alignedEnd[i], "at_aligned_end");
1368  llvm::Value *inEx = ctx->BinaryOperator(llvm::Instruction::And, haveExtras, atAlignedEnd, "in_extras");
1369 
1370  if (i == 0)
1371  inExtras.push_back(inEx);
1372  else
1373  inExtras.push_back(ctx->BinaryOperator(llvm::Instruction::Or, inEx, inExtras[i - 1], "in_extras_all"));
1374 
1375  llvm::Value *varyingCounter =
1376  lUpdateVaryingCounter(i, nDims, ctx, uniformCounterPtrs[i], dimVariables[i]->storagePtr, span);
1377 
1378  llvm::Value *smearEnd = ctx->BroadcastValue(endVals[i], LLVMTypes::Int32VectorType, "smear_end");
1379 
1380  // Do a vector compare of its value to the end value to generate a
1381  // mask for this last bit of work.
1382  llvm::Value *emask = ctx->CmpInst(llvm::Instruction::ICmp, llvm::CmpInst::ICMP_SLT, varyingCounter, smearEnd);
1383  emask = ctx->I1VecToBoolVec(emask);
1384 
1385  if (i == 0)
1386  ctx->StoreInst(emask, extrasMaskPtrs[i]);
1387  else {
1388  llvm::Value *oldMask = ctx->LoadInst(extrasMaskPtrs[i - 1]);
1389  llvm::Value *newMask = ctx->BinaryOperator(llvm::Instruction::And, oldMask, emask, "extras_mask");
1390  ctx->StoreInst(newMask, extrasMaskPtrs[i]);
1391  }
1392 
1393  llvm::Value *notAtEnd = ctx->CmpInst(llvm::Instruction::ICmp, llvm::CmpInst::ICMP_SLT, counter, endVals[i]);
1394  ctx->BranchInst(bbTest[i + 1], bbReset[i], notAtEnd);
1395  }
1396 
1397  ///////////////////////////////////////////////////////////////////////////
1398  // foreach_test (for innermost dimension)
1399  //
1400  // All of the outer dimensions are handled generically--basically as a
1401  // for() loop from the start value to the end value, where at each loop
1402  // test, we compute the mask of active elements for the current
1403  // dimension and then update an overall mask that is the AND
1404  // combination of all of the outer ones.
1405  //
1406  // The innermost loop is handled specially, for performance purposes.
1407  // When starting the innermost dimension, we start by checking once
1408  // whether any of the outer dimensions has set the mask to be
1409  // partially-active or not. We follow different code paths for these
1410  // two cases, taking advantage of the knowledge that the mask is all
1411  // on, when this is the case.
1412  //
1413  // In each of these code paths, we start with a loop from the starting
1414  // value to the aligned end value for the innermost dimension; we can
1415  // guarantee that the innermost loop will have an "all on" mask (as far
1416  // as its dimension is concerned) for the duration of this loop. Doing
1417  // so allows us to emit code that assumes the mask is all on (for the
1418  // case where none of the outer dimensions has set the mask to be
1419  // partially on), or allows us to emit code that just uses the mask
1420  // from the outer dimensions directly (for the case where they have).
1421  //
1422  // After this loop, we just need to deal with one vector's worth of
1423  // "ragged extra bits", where the mask used includes the effect of the
1424  // mask for the innermost dimension.
1425  //
1426  // We start out this process by emitting the check that determines
1427  // whether any of the enclosing dimensions is partially active
1428  // (i.e. processing extra elements that don't exactly fit into a
1429  // vector).
1430  llvm::BasicBlock *bbOuterInExtras = ctx->CreateBasicBlock("outer_in_extras");
1431  llvm::BasicBlock *bbOuterNotInExtras = ctx->CreateBasicBlock("outer_not_in_extras");
1432 
1433  ctx->SetCurrentBasicBlock(bbTest[nDims - 1]);
1434  if (inExtras.size())
1435  ctx->BranchInst(bbOuterInExtras, bbOuterNotInExtras, inExtras.back());
1436  else
1437  // for a 1D iteration domain, we certainly don't have any enclosing
1438  // dimensions that are processing extra elements.
1439  ctx->BranchInst(bbOuterNotInExtras);
1440 
1441  ///////////////////////////////////////////////////////////////////////////
1442  // One or more outer dimensions in extras, so we need to mask for the loop
1443  // body regardless. We break this into two cases, roughly:
1444  // for (counter = start; counter < alignedEnd; counter += step) {
1445  // // mask is all on for inner, so set mask to outer mask
1446  // // run loop body with mask
1447  // }
1448  // // counter == alignedEnd
1449  // if (counter < end) {
1450  // // set mask to outermask & (counter+programCounter < end)
1451  // // run loop body with mask
1452  // }
1453  llvm::BasicBlock *bbAllInnerPartialOuter = ctx->CreateBasicBlock("all_inner_partial_outer");
1454  llvm::BasicBlock *bbPartial = ctx->CreateBasicBlock("both_partial");
1455  ctx->SetCurrentBasicBlock(bbOuterInExtras);
1456  {
1457  // Update the varying counter value here, since all subsequent
1458  // blocks along this path need it.
1459  lUpdateVaryingCounter(nDims - 1, nDims, ctx, uniformCounterPtrs[nDims - 1], dimVariables[nDims - 1]->storagePtr,
1460  span);
1461 
1462  // here we just check to see if counter < alignedEnd
1463  llvm::Value *counter = ctx->LoadInst(uniformCounterPtrs[nDims - 1], NULL, "counter");
1464  llvm::Value *beforeAlignedEnd = ctx->CmpInst(llvm::Instruction::ICmp, llvm::CmpInst::ICMP_SLT, counter,
1465  alignedEnd[nDims - 1], "before_aligned_end");
1466  ctx->BranchInst(bbAllInnerPartialOuter, bbPartial, beforeAlignedEnd);
1467  }
1468 
1469  // Below we have a basic block that runs the loop body code for the
1470  // case where the mask is partially but not fully on. This same block
1471  // runs in multiple cases: both for handling any ragged extra data for
1472  // the innermost dimension but also when outer dimensions have set the
1473  // mask to be partially on.
1474  //
1475  // The value stored in stepIndexAfterMaskedBodyPtr is used after each
1476  // execution of the body code to determine whether the innermost index
1477  // value should be incremented by the step (we're running the "for"
1478  // loop of full vectors at the innermost dimension, with outer
1479  // dimensions having set the mask to be partially on), or whether we're
1480  // running once for the ragged extra bits at the end of the innermost
1481  // dimension, in which case we're done with the innermost dimension and
1482  // should step the loop counter for the next enclosing dimension
1483  // instead.
1484  // Revisit : Should this be an i1.
1485  llvm::Value *stepIndexAfterMaskedBodyPtr = ctx->AllocaInst(LLVMTypes::BoolType, "step_index");
1486 
1487  ///////////////////////////////////////////////////////////////////////////
1488  // We're in the inner loop part where the only masking is due to outer
1489  // dimensions but the innermost dimension fits fully into a vector's
1490  // width. Set the mask and jump to the masked loop body.
1491  ctx->SetCurrentBasicBlock(bbAllInnerPartialOuter);
1492  {
1493  llvm::Value *mask;
1494  if (nDims == 1)
1495  // 1D loop; we shouldn't ever get here anyway
1496  mask = LLVMMaskAllOff;
1497  else
1498  mask = ctx->LoadInst(extrasMaskPtrs[nDims - 2]);
1499 
1500  ctx->SetInternalMask(mask);
1501 
1502  ctx->StoreInst(LLVMTrue, stepIndexAfterMaskedBodyPtr);
1503  ctx->BranchInst(bbMaskedBody);
1504  }
1505 
1506  ///////////////////////////////////////////////////////////////////////////
1507  // We need to include the effect of the innermost dimension in the mask
1508  // for the final bits here
1509  ctx->SetCurrentBasicBlock(bbPartial);
1510  {
1511  llvm::Value *varyingCounter = ctx->LoadInst(dimVariables[nDims - 1]->storagePtr, dimVariables[nDims - 1]->type);
1512  llvm::Value *smearEnd = ctx->BroadcastValue(endVals[nDims - 1], LLVMTypes::Int32VectorType, "smear_end");
1513 
1514  llvm::Value *emask = ctx->CmpInst(llvm::Instruction::ICmp, llvm::CmpInst::ICMP_SLT, varyingCounter, smearEnd);
1515  emask = ctx->I1VecToBoolVec(emask);
1516 
1517  if (nDims == 1) {
1518  ctx->SetInternalMask(emask);
1519  } else {
1520  llvm::Value *oldMask = ctx->LoadInst(extrasMaskPtrs[nDims - 2]);
1521  llvm::Value *newMask = ctx->BinaryOperator(llvm::Instruction::And, oldMask, emask, "extras_mask");
1522  ctx->SetInternalMask(newMask);
1523  }
1524 
1525  ctx->StoreInst(LLVMFalse, stepIndexAfterMaskedBodyPtr);
1526 
1527  // check to see if counter != end, otherwise, the next step is not necessary
1528  llvm::Value *counter = ctx->LoadInst(uniformCounterPtrs[nDims - 1], NULL, "counter");
1529  llvm::Value *atEnd =
1530  ctx->CmpInst(llvm::Instruction::ICmp, llvm::CmpInst::ICMP_NE, counter, endVals[nDims - 1], "at_end");
1531  ctx->BranchInst(bbMaskedBody, bbReset[nDims - 1], atEnd);
1532  }
1533 
1534  ///////////////////////////////////////////////////////////////////////////
1535  // None of the outer dimensions is processing extras; along the lines
1536  // of above, we can express this as:
1537  // for (counter = start; counter < alignedEnd; counter += step) {
1538  // // mask is all on
1539  // // run loop body with mask all on
1540  // }
1541  // // counter == alignedEnd
1542  // if (counter < end) {
1543  // // set mask to (counter+programCounter < end)
1544  // // run loop body with mask
1545  // }
1546  llvm::BasicBlock *bbPartialInnerAllOuter = ctx->CreateBasicBlock("partial_inner_all_outer");
1547  ctx->SetCurrentBasicBlock(bbOuterNotInExtras);
1548  {
1549  llvm::Value *counter = ctx->LoadInst(uniformCounterPtrs[nDims - 1], NULL, "counter");
1550  llvm::Value *beforeAlignedEnd = ctx->CmpInst(llvm::Instruction::ICmp, llvm::CmpInst::ICMP_SLT, counter,
1551  alignedEnd[nDims - 1], "before_aligned_end");
1552  ctx->BranchInst(bbFullBody, bbPartialInnerAllOuter, beforeAlignedEnd);
1553  }
1554 
1555  ///////////////////////////////////////////////////////////////////////////
1556  // full_body: do a full vector's worth of work. We know that all
1557  // lanes will be running here, so we explicitly set the mask to be 'all
1558  // on'. This ends up being relatively straightforward: just update the
1559  // value of the varying loop counter and have the statements in the
1560  // loop body emit their code.
1561  llvm::BasicBlock *bbFullBodyContinue = ctx->CreateBasicBlock("foreach_full_continue");
1562  ctx->SetCurrentBasicBlock(bbFullBody);
1563  {
1566  lUpdateVaryingCounter(nDims - 1, nDims, ctx, uniformCounterPtrs[nDims - 1], dimVariables[nDims - 1]->storagePtr,
1567  span);
1568  ctx->SetContinueTarget(bbFullBodyContinue);
1569  ctx->AddInstrumentationPoint("foreach loop body (all on)");
1570  stmts->EmitCode(ctx);
1571  AssertPos(pos, ctx->GetCurrentBasicBlock() != NULL);
1572  ctx->BranchInst(bbFullBodyContinue);
1573  }
1574  ctx->SetCurrentBasicBlock(bbFullBodyContinue);
1575  {
1576  ctx->RestoreContinuedLanes();
1577  llvm::Value *counter = ctx->LoadInst(uniformCounterPtrs[nDims - 1]);
1578  llvm::Value *newCounter =
1579  ctx->BinaryOperator(llvm::Instruction::Add, counter, LLVMInt32(span[nDims - 1]), "new_counter");
1580  ctx->StoreInst(newCounter, uniformCounterPtrs[nDims - 1]);
1581  ctx->BranchInst(bbOuterNotInExtras);
1582  }
1583 
1584  ///////////////////////////////////////////////////////////////////////////
1585  // We're done running blocks with the mask all on; see if the counter is
1586  // less than the end value, in which case we need to run the body one
1587  // more time to get the extra bits.
1588  llvm::BasicBlock *bbSetInnerMask = ctx->CreateBasicBlock("partial_inner_only");
1589  ctx->SetCurrentBasicBlock(bbPartialInnerAllOuter);
1590  {
1591  llvm::Value *counter = ctx->LoadInst(uniformCounterPtrs[nDims - 1], NULL, "counter");
1592  llvm::Value *beforeFullEnd = ctx->CmpInst(llvm::Instruction::ICmp, llvm::CmpInst::ICMP_SLT, counter,
1593  endVals[nDims - 1], "before_full_end");
1594  ctx->BranchInst(bbSetInnerMask, bbReset[nDims - 1], beforeFullEnd);
1595  }
1596 
1597  ///////////////////////////////////////////////////////////////////////////
1598  // The outer dimensions are all on, so the mask is just given by the
1599  // mask for the innermost dimension
1600  ctx->SetCurrentBasicBlock(bbSetInnerMask);
1601  {
1602  llvm::Value *varyingCounter = lUpdateVaryingCounter(nDims - 1, nDims, ctx, uniformCounterPtrs[nDims - 1],
1603  dimVariables[nDims - 1]->storagePtr, span);
1604  llvm::Value *smearEnd = ctx->BroadcastValue(endVals[nDims - 1], LLVMTypes::Int32VectorType, "smear_end");
1605  llvm::Value *emask = ctx->CmpInst(llvm::Instruction::ICmp, llvm::CmpInst::ICMP_SLT, varyingCounter, smearEnd);
1606  emask = ctx->I1VecToBoolVec(emask);
1607  ctx->SetInternalMask(emask);
1608  ctx->SetBlockEntryMask(emask);
1609 
1610  ctx->StoreInst(LLVMFalse, stepIndexAfterMaskedBodyPtr);
1611  ctx->BranchInst(bbMaskedBody);
1612  }
1613 
1614  ///////////////////////////////////////////////////////////////////////////
1615  // masked_body: set the mask and have the statements emit their
1616  // code again. Note that it's generally worthwhile having two copies
1617  // of the statements' code, since the code above is emitted with the
1618  // mask known to be all-on, which in turn leads to more efficient code
1619  // for that case.
1620  llvm::BasicBlock *bbStepInnerIndex = ctx->CreateBasicBlock("step_inner_index");
1621  llvm::BasicBlock *bbMaskedBodyContinue = ctx->CreateBasicBlock("foreach_masked_continue");
1622  ctx->SetCurrentBasicBlock(bbMaskedBody);
1623  {
1624  ctx->AddInstrumentationPoint("foreach loop body (masked)");
1625  ctx->SetContinueTarget(bbMaskedBodyContinue);
1627  ctx->SetBlockEntryMask(ctx->GetFullMask());
1628  stmts->EmitCode(ctx);
1630  ctx->BranchInst(bbMaskedBodyContinue);
1631  }
1632  ctx->SetCurrentBasicBlock(bbMaskedBodyContinue);
1633  {
1634  ctx->RestoreContinuedLanes();
1635  llvm::Value *stepIndex = ctx->LoadInst(stepIndexAfterMaskedBodyPtr);
1636  ctx->BranchInst(bbStepInnerIndex, bbReset[nDims - 1], stepIndex);
1637  }
1638 
1639  ///////////////////////////////////////////////////////////////////////////
1640  // step the innermost index, for the case where we're doing the
1641  // innermost for loop over full vectors.
1642  ctx->SetCurrentBasicBlock(bbStepInnerIndex);
1643  {
1644  llvm::Value *counter = ctx->LoadInst(uniformCounterPtrs[nDims - 1]);
1645  llvm::Value *newCounter =
1646  ctx->BinaryOperator(llvm::Instruction::Add, counter, LLVMInt32(span[nDims - 1]), "new_counter");
1647  ctx->StoreInst(newCounter, uniformCounterPtrs[nDims - 1]);
1648  ctx->BranchInst(bbOuterInExtras);
1649  }
1650 
1651  ///////////////////////////////////////////////////////////////////////////
1652  // foreach_exit: All done. Restore the old mask and clean up
1653  ctx->SetCurrentBasicBlock(bbExit);
1654 
1655  ctx->SetInternalMask(oldMask);
1656  ctx->SetFunctionMask(oldFunctionMask);
1657 
1658  ctx->EndForeach();
1659  ctx->EndScope();
1660 }
1661 
1663  bool anyErrors = false;
1664  for (unsigned int i = 0; i < startExprs.size(); ++i) {
1665  if (startExprs[i] != NULL)
1666  startExprs[i] = TypeConvertExpr(startExprs[i], AtomicType::UniformInt32, "foreach starting value");
1667  anyErrors |= (startExprs[i] == NULL);
1668  }
1669  for (unsigned int i = 0; i < endExprs.size(); ++i) {
1670  if (endExprs[i] != NULL)
1671  endExprs[i] = TypeConvertExpr(endExprs[i], AtomicType::UniformInt32, "foreach ending value");
1672  anyErrors |= (endExprs[i] == NULL);
1673  }
1674 
1675  if (startExprs.size() < dimVariables.size()) {
1676  Error(pos,
1677  "Not enough initial values provided for \"foreach\" loop; "
1678  "got %d, expected %d\n",
1679  (int)startExprs.size(), (int)dimVariables.size());
1680  anyErrors = true;
1681  } else if (startExprs.size() > dimVariables.size()) {
1682  Error(pos,
1683  "Too many initial values provided for \"foreach\" loop; "
1684  "got %d, expected %d\n",
1685  (int)startExprs.size(), (int)dimVariables.size());
1686  anyErrors = true;
1687  }
1688 
1689  if (endExprs.size() < dimVariables.size()) {
1690  Error(pos,
1691  "Not enough initial values provided for \"foreach\" loop; "
1692  "got %d, expected %d\n",
1693  (int)endExprs.size(), (int)dimVariables.size());
1694  anyErrors = true;
1695  } else if (endExprs.size() > dimVariables.size()) {
1696  Error(pos,
1697  "Too many initial values provided for \"foreach\" loop; "
1698  "got %d, expected %d\n",
1699  (int)endExprs.size(), (int)dimVariables.size());
1700  anyErrors = true;
1701  }
1702 
1703  return anyErrors ? NULL : this;
1704 }
1705 
1707 
1708 void ForeachStmt::Print(int indent) const {
1709  printf("%*cForeach Stmt", indent, ' ');
1710  pos.Print();
1711  printf("\n");
1712 
1713  for (unsigned int i = 0; i < dimVariables.size(); ++i)
1714  if (dimVariables[i] != NULL)
1715  printf("%*cVar %d: %s\n", indent + 4, ' ', i, dimVariables[i]->name.c_str());
1716  else
1717  printf("%*cVar %d: NULL\n", indent + 4, ' ', i);
1718 
1719  printf("Start values:\n");
1720  for (unsigned int i = 0; i < startExprs.size(); ++i) {
1721  if (startExprs[i] != NULL)
1722  startExprs[i]->Print();
1723  else
1724  printf("NULL");
1725  if (i != startExprs.size() - 1)
1726  printf(", ");
1727  else
1728  printf("\n");
1729  }
1730 
1731  printf("End values:\n");
1732  for (unsigned int i = 0; i < endExprs.size(); ++i) {
1733  if (endExprs[i] != NULL)
1734  endExprs[i]->Print();
1735  else
1736  printf("NULL");
1737  if (i != endExprs.size() - 1)
1738  printf(", ");
1739  else
1740  printf("\n");
1741  }
1742 
1743  if (stmts != NULL) {
1744  printf("%*cStmts:\n", indent + 4, ' ');
1745  stmts->Print(indent + 8);
1746  }
1747 }
1748 
1749 ///////////////////////////////////////////////////////////////////////////
1750 // ForeachActiveStmt
1751 
1753  sym = s;
1754  stmts = st;
1755 }
1756 
1758  if (!ctx->GetCurrentBasicBlock())
1759  return;
1760 
1761  // Allocate storage for the symbol that we'll use for the uniform
1762  // variable that holds the current program instance in each loop
1763  // iteration.
1764  if (sym->type == NULL) {
1765  Assert(m->errorCount > 0);
1766  return;
1767  }
1770 
1771  ctx->SetDebugPos(pos);
1772  ctx->EmitVariableDebugInfo(sym);
1773 
1774  // The various basic blocks that we'll need in the below
1775  llvm::BasicBlock *bbFindNext = ctx->CreateBasicBlock("foreach_active_find_next");
1776  llvm::BasicBlock *bbBody = ctx->CreateBasicBlock("foreach_active_body");
1777  llvm::BasicBlock *bbCheckForMore = ctx->CreateBasicBlock("foreach_active_check_for_more");
1778  llvm::BasicBlock *bbDone = ctx->CreateBasicBlock("foreach_active_done");
1779 
1780  // Save the old mask so that we can restore it at the end
1781  llvm::Value *oldInternalMask = ctx->GetInternalMask();
1782 
1783  // Now, *maskBitsPtr will maintain a bitmask for the lanes that remain
1784  // to be processed by a pass through the loop body. It starts out with
1785  // the current execution mask (which should never be all off going in
1786  // to this)...
1787  llvm::Value *oldFullMask = ctx->GetFullMask();
1788  llvm::Value *maskBitsPtr = ctx->AllocaInst(LLVMTypes::Int64Type, "mask_bits");
1789  llvm::Value *movmsk = ctx->LaneMask(oldFullMask);
1790  ctx->StoreInst(movmsk, maskBitsPtr);
1791 
1792  // Officially start the loop.
1793  ctx->StartScope();
1795  ctx->SetContinueTarget(bbCheckForMore);
1796 
1797  // Onward to find the first set of program instance to run the loop for
1798  ctx->BranchInst(bbFindNext);
1799 
1800  ctx->SetCurrentBasicBlock(bbFindNext);
1801  {
1802  // Load the bitmask of the lanes left to be processed
1803  llvm::Value *remainingBits = ctx->LoadInst(maskBitsPtr, NULL, "remaining_bits");
1804 
1805  // Find the index of the first set bit in the mask
1806  llvm::Function *ctlzFunc = m->module->getFunction("__count_trailing_zeros_i64");
1807  Assert(ctlzFunc != NULL);
1808  llvm::Value *firstSet = ctx->CallInst(ctlzFunc, NULL, remainingBits, "first_set");
1809 
1810  // Store that value into the storage allocated for the iteration
1811  // variable.
1812  ctx->StoreInst(firstSet, sym->storagePtr, sym->type);
1813 
1814  // Now set the execution mask to be only on for the current program
1815  // instance. (TODO: is there a more efficient way to do this? e.g.
1816  // for AVX1, we might want to do this as float rather than int
1817  // math...)
1818 
1819  // Get the "program index" vector value
1820  llvm::Value *programIndex = ctx->ProgramIndexVector();
1821 
1822  // And smear the current lane out to a vector
1823  llvm::Value *firstSet32 = ctx->TruncInst(firstSet, LLVMTypes::Int32Type, "first_set32");
1824  llvm::Value *firstSet32Smear = ctx->SmearUniform(firstSet32);
1825 
1826  // Now set the execution mask based on doing a vector compare of
1827  // these two
1828  llvm::Value *iterMask =
1829  ctx->CmpInst(llvm::Instruction::ICmp, llvm::CmpInst::ICMP_EQ, firstSet32Smear, programIndex);
1830  iterMask = ctx->I1VecToBoolVec(iterMask);
1831 
1832  ctx->SetInternalMask(iterMask);
1833 
1834  // Also update the bitvector of lanes left to turn off the bit for
1835  // the lane we're about to run.
1836  llvm::Value *setMask = ctx->BinaryOperator(llvm::Instruction::Shl, LLVMInt64(1), firstSet, "set_mask");
1837  llvm::Value *notSetMask = ctx->NotOperator(setMask);
1838  llvm::Value *newRemaining =
1839  ctx->BinaryOperator(llvm::Instruction::And, remainingBits, notSetMask, "new_remaining");
1840  ctx->StoreInst(newRemaining, maskBitsPtr);
1841 
1842  // and onward to run the loop body...
1843  ctx->BranchInst(bbBody);
1844  }
1845 
1846  ctx->SetCurrentBasicBlock(bbBody);
1847  {
1848  ctx->SetBlockEntryMask(ctx->GetFullMask());
1849 
1850  // Run the code in the body of the loop. This is easy now.
1851  if (stmts)
1852  stmts->EmitCode(ctx);
1853 
1854  Assert(ctx->GetCurrentBasicBlock() != NULL);
1855  ctx->BranchInst(bbCheckForMore);
1856  }
1857 
1858  ctx->SetCurrentBasicBlock(bbCheckForMore);
1859  {
1860  ctx->RestoreContinuedLanes();
1861  // At the end of the loop body (either due to running the
1862  // statements normally, or a continue statement in the middle of
1863  // the loop that jumps to the end, see if there are any lanes left
1864  // to be processed.
1865  llvm::Value *remainingBits = ctx->LoadInst(maskBitsPtr, NULL, "remaining_bits");
1866  llvm::Value *nonZero = ctx->CmpInst(llvm::Instruction::ICmp, llvm::CmpInst::ICMP_NE, remainingBits,
1867  LLVMInt64(0), "remaining_ne_zero");
1868  ctx->BranchInst(bbFindNext, bbDone, nonZero);
1869  }
1870 
1871  ctx->SetCurrentBasicBlock(bbDone);
1872  ctx->SetInternalMask(oldInternalMask);
1873  ctx->EndForeach();
1874  ctx->EndScope();
1875 }
1876 
1877 void ForeachActiveStmt::Print(int indent) const {
1878  printf("%*cForeach_active Stmt", indent, ' ');
1879  pos.Print();
1880  printf("\n");
1881 
1882  printf("%*cIter symbol: ", indent + 4, ' ');
1883  if (sym != NULL) {
1884  printf("%s", sym->name.c_str());
1885  if (sym->type != NULL)
1886  printf(" %s", sym->type->GetString().c_str());
1887  } else
1888  printf("NULL");
1889  printf("\n");
1890 
1891  printf("%*cStmts:\n", indent + 4, ' ');
1892  if (stmts != NULL)
1893  stmts->Print(indent + 8);
1894  else
1895  printf("NULL");
1896  printf("\n");
1897 }
1898 
1900  if (sym == NULL)
1901  return NULL;
1902 
1903  return this;
1904 }
1905 
1907 
1908 ///////////////////////////////////////////////////////////////////////////
1909 // ForeachUniqueStmt
1910 
1912  : Stmt(pos, ForeachUniqueStmtID) {
1913  sym = m->symbolTable->LookupVariable(iterName);
1914  expr = e;
1915  stmts = s;
1916 }
1917 
1919  if (!ctx->GetCurrentBasicBlock())
1920  return;
1921 
1922  // First, allocate local storage for the symbol that we'll use for the
1923  // uniform variable that holds the current unique value through each
1924  // loop.
1925  if (sym->type == NULL) {
1926  Assert(m->errorCount > 0);
1927  return;
1928  }
1929  llvm::Type *symType = sym->type->LLVMType(g->ctx);
1930  if (symType == NULL) {
1931  Assert(m->errorCount > 0);
1932  return;
1933  }
1934 
1935  sym->storagePtr = ctx->AllocaInst(sym->type, sym->name.c_str());
1936 
1937  ctx->SetDebugPos(pos);
1938  ctx->EmitVariableDebugInfo(sym);
1939 
1940  // The various basic blocks that we'll need in the below
1941  llvm::BasicBlock *bbFindNext = ctx->CreateBasicBlock("foreach_find_next");
1942  llvm::BasicBlock *bbBody = ctx->CreateBasicBlock("foreach_body");
1943  llvm::BasicBlock *bbCheckForMore = ctx->CreateBasicBlock("foreach_check_for_more");
1944  llvm::BasicBlock *bbDone = ctx->CreateBasicBlock("foreach_done");
1945 
1946  // Prepare the FunctionEmitContext
1947  ctx->StartScope();
1948 
1949  // Save the old internal mask so that we can restore it at the end
1950  llvm::Value *oldMask = ctx->GetInternalMask();
1951 
1952  // Now, *maskBitsPtr will maintain a bitmask for the lanes that remain
1953  // to be processed by a pass through the foreach_unique loop body. It
1954  // starts out with the full execution mask (which should never be all
1955  // off going in to this)...
1956  llvm::Value *oldFullMask = ctx->GetFullMask();
1957  llvm::Value *maskBitsPtr = ctx->AllocaInst(LLVMTypes::Int64Type, "mask_bits");
1958  llvm::Value *movmsk = ctx->LaneMask(oldFullMask);
1959  ctx->StoreInst(movmsk, maskBitsPtr);
1960 
1961  // Officially start the loop.
1963  ctx->SetContinueTarget(bbCheckForMore);
1964 
1965  // Evaluate the varying expression we're iterating over just once.
1966  llvm::Value *exprValue = expr->GetValue(ctx);
1967 
1968  // And we'll store its value into locally-allocated storage, for ease
1969  // of indexing over it with non-compile-time-constant indices.
1970  const Type *exprType;
1971  llvm::VectorType *llvmExprType;
1972  if (exprValue == NULL || (exprType = expr->GetType()) == NULL ||
1973  (llvmExprType = llvm::dyn_cast<llvm::VectorType>(exprValue->getType())) == NULL) {
1974  Assert(m->errorCount > 0);
1975  return;
1976  }
1977  ctx->SetDebugPos(pos);
1978  const Type *exprPtrType = PointerType::GetUniform(exprType);
1979  llvm::Value *exprMem = ctx->AllocaInst(exprType, "expr_mem");
1980  ctx->StoreInst(exprValue, exprMem, exprType);
1981 
1982  // Onward to find the first set of lanes to run the loop for
1983  ctx->BranchInst(bbFindNext);
1984 
1985  ctx->SetCurrentBasicBlock(bbFindNext);
1986  {
1987  // Load the bitmask of the lanes left to be processed
1988  llvm::Value *remainingBits = ctx->LoadInst(maskBitsPtr, NULL, "remaining_bits");
1989 
1990  // Find the index of the first set bit in the mask
1991  llvm::Function *ctlzFunc = m->module->getFunction("__count_trailing_zeros_i64");
1992  Assert(ctlzFunc != NULL);
1993  llvm::Value *firstSet = ctx->CallInst(ctlzFunc, NULL, remainingBits, "first_set");
1994 
1995  // And load the corresponding element value from the temporary
1996  // memory storing the value of the varying expr.
1997  llvm::Value *uniqueValue;
1998  llvm::Value *uniqueValuePtr =
1999  ctx->GetElementPtrInst(exprMem, LLVMInt64(0), firstSet, exprPtrType, "unique_index_ptr");
2000  uniqueValue = ctx->LoadInst(uniqueValuePtr, exprType, "unique_value");
2001  // If it's a varying pointer type, need to convert from the int
2002  // type we store in the vector to the actual pointer type
2003  if (llvm::dyn_cast<llvm::PointerType>(symType) != NULL)
2004  uniqueValue = ctx->IntToPtrInst(uniqueValue, symType);
2005  Assert(uniqueValue != NULL);
2006  // Store that value in sym's storage so that the iteration variable
2007  // has the right value inside the loop body
2008  ctx->StoreInst(uniqueValue, sym->storagePtr, sym->type);
2009 
2010  // Set the execution mask so that it's on for any lane that a) was
2011  // running at the start of the foreach loop, and b) where that
2012  // lane's value of the varying expression is the same as the value
2013  // we've selected to process this time through--i.e.:
2014  // oldMask & (smear(element) == exprValue)
2015  llvm::Value *uniqueSmear = ctx->SmearUniform(uniqueValue, "unique_smear");
2016  llvm::Value *matchingLanes = NULL;
2017  if (uniqueValue->getType()->isFloatingPointTy())
2018  matchingLanes = ctx->CmpInst(llvm::Instruction::FCmp, llvm::CmpInst::FCMP_OEQ, uniqueSmear, exprValue,
2019  "matching_lanes");
2020  else
2021  matchingLanes =
2022  ctx->CmpInst(llvm::Instruction::ICmp, llvm::CmpInst::ICMP_EQ, uniqueSmear, exprValue, "matching_lanes");
2023  matchingLanes = ctx->I1VecToBoolVec(matchingLanes);
2024 
2025  llvm::Value *loopMask =
2026  ctx->BinaryOperator(llvm::Instruction::And, oldMask, matchingLanes, "foreach_unique_loop_mask");
2027  ctx->SetInternalMask(loopMask);
2028 
2029  // Also update the bitvector of lanes left to process in subsequent
2030  // loop iterations:
2031  // remainingBits &= ~movmsk(current mask)
2032  llvm::Value *loopMaskMM = ctx->LaneMask(loopMask);
2033  llvm::Value *notLoopMaskMM = ctx->NotOperator(loopMaskMM);
2034  llvm::Value *newRemaining =
2035  ctx->BinaryOperator(llvm::Instruction::And, remainingBits, notLoopMaskMM, "new_remaining");
2036  ctx->StoreInst(newRemaining, maskBitsPtr);
2037 
2038  // and onward...
2039  ctx->BranchInst(bbBody);
2040  }
2041 
2042  ctx->SetCurrentBasicBlock(bbBody);
2043  {
2044  ctx->SetBlockEntryMask(ctx->GetFullMask());
2045  // Run the code in the body of the loop. This is easy now.
2046  if (stmts)
2047  stmts->EmitCode(ctx);
2048 
2049  Assert(ctx->GetCurrentBasicBlock() != NULL);
2050  ctx->BranchInst(bbCheckForMore);
2051  }
2052 
2053  ctx->SetCurrentBasicBlock(bbCheckForMore);
2054  {
2055  // At the end of the loop body (either due to running the
2056  // statements normally, or a continue statement in the middle of
2057  // the loop that jumps to the end, see if there are any lanes left
2058  // to be processed.
2059  ctx->RestoreContinuedLanes();
2060  llvm::Value *remainingBits = ctx->LoadInst(maskBitsPtr, NULL, "remaining_bits");
2061  llvm::Value *nonZero = ctx->CmpInst(llvm::Instruction::ICmp, llvm::CmpInst::ICMP_NE, remainingBits,
2062  LLVMInt64(0), "remaining_ne_zero");
2063  ctx->BranchInst(bbFindNext, bbDone, nonZero);
2064  }
2065 
2066  ctx->SetCurrentBasicBlock(bbDone);
2067  ctx->SetInternalMask(oldMask);
2068  ctx->EndForeach();
2069  ctx->EndScope();
2070 }
2071 
2072 void ForeachUniqueStmt::Print(int indent) const {
2073  printf("%*cForeach_unique Stmt", indent, ' ');
2074  pos.Print();
2075  printf("\n");
2076 
2077  printf("%*cIter symbol: ", indent + 4, ' ');
2078  if (sym != NULL) {
2079  printf("%s", sym->name.c_str());
2080  if (sym->type != NULL)
2081  printf(" %s", sym->type->GetString().c_str());
2082  } else
2083  printf("NULL");
2084  printf("\n");
2085 
2086  printf("%*cIter expr: ", indent + 4, ' ');
2087  if (expr != NULL)
2088  expr->Print();
2089  else
2090  printf("NULL");
2091  printf("\n");
2092 
2093  printf("%*cStmts:\n", indent + 4, ' ');
2094  if (stmts != NULL)
2095  stmts->Print(indent + 8);
2096  else
2097  printf("NULL");
2098  printf("\n");
2099 }
2100 
2102  const Type *type;
2103  if (sym == NULL || expr == NULL || (type = expr->GetType()) == NULL)
2104  return NULL;
2105 
2106  if (type->IsVaryingType() == false) {
2107  Error(expr->pos,
2108  "Iteration domain type in \"foreach_tiled\" loop "
2109  "must be \"varying\" type, not \"%s\".",
2110  type->GetString().c_str());
2111  return NULL;
2112  }
2113 
2114  if (Type::IsBasicType(type) == false) {
2115  Error(expr->pos,
2116  "Iteration domain type in \"foreach_tiled\" loop "
2117  "must be an atomic, pointer, or enum type, not \"%s\".",
2118  type->GetString().c_str());
2119  return NULL;
2120  }
2121 
2122  return this;
2123 }
2124 
2126 
2127 ///////////////////////////////////////////////////////////////////////////
2128 // CaseStmt
2129 
2130 /** Given the statements following a 'case' or 'default' label, this
2131  function determines whether the mask should be checked to see if it is
2132  "all off" immediately after the label, before executing the code for
2133  the statements.
2134  */
2135 static bool lCheckMask(Stmt *stmts) {
2136  if (stmts == NULL)
2137  return false;
2138 
2139  int cost = EstimateCost(stmts);
2140  bool safeToRunWithAllLanesOff = SafeToRunWithMaskAllOff(stmts);
2141 
2142  // The mask should be checked if the code following the
2143  // 'case'/'default' is relatively complex, or if it would be unsafe to
2144  // run that code with the execution mask all off.
2145  return (cost > PREDICATE_SAFE_IF_STATEMENT_COST || safeToRunWithAllLanesOff == false);
2146 }
2147 
2148 CaseStmt::CaseStmt(int v, Stmt *s, SourcePos pos) : Stmt(pos, CaseStmtID), value(v) { stmts = s; }
2149 
2152  if (stmts)
2153  stmts->EmitCode(ctx);
2154 }
2155 
2156 void CaseStmt::Print(int indent) const {
2157  printf("%*cCase [%d] label", indent, ' ', value);
2158  pos.Print();
2159  printf("\n");
2160  stmts->Print(indent + 4);
2161 }
2162 
2163 Stmt *CaseStmt::TypeCheck() { return this; }
2164 
2165 int CaseStmt::EstimateCost() const { return 0; }
2166 
2167 ///////////////////////////////////////////////////////////////////////////
2168 // DefaultStmt
2169 
2171 
2174  if (stmts)
2175  stmts->EmitCode(ctx);
2176 }
2177 
2178 void DefaultStmt::Print(int indent) const {
2179  printf("%*cDefault Stmt", indent, ' ');
2180  pos.Print();
2181  printf("\n");
2182  stmts->Print(indent + 4);
2183 }
2184 
2185 Stmt *DefaultStmt::TypeCheck() { return this; }
2186 
2187 int DefaultStmt::EstimateCost() const { return 0; }
2188 
2189 ///////////////////////////////////////////////////////////////////////////
2190 // SwitchStmt
2191 
2193  expr = e;
2194  stmts = s;
2195 }
2196 
2197 /* An instance of this structure is carried along as we traverse the AST
2198  nodes for the statements after a "switch" statement. We use this
2199  structure to record all of the 'case' and 'default' statements after the
2200  "switch". */
2203  ctx = c;
2204  defaultBlock = NULL;
2205  lastBlock = NULL;
2206  }
2207 
2209 
2210  /* Basic block for the code following the "default" label (if any). */
2211  llvm::BasicBlock *defaultBlock;
2212 
2213  /* Map from integer values after "case" labels to the basic blocks that
2214  follow the corresponding "case" label. */
2215  std::vector<std::pair<int, llvm::BasicBlock *>> caseBlocks;
2216 
2217  /* For each basic block for a "case" label or a "default" label,
2218  nextBlock[block] stores the basic block pointer for the next
2219  subsequent "case" or "default" label in the program. */
2220  std::map<llvm::BasicBlock *, llvm::BasicBlock *> nextBlock;
2221 
2222  /* The last basic block created for a "case" or "default" label; when
2223  we create the basic block for the next one, we'll use this to update
2224  the nextBlock map<> above. */
2225  llvm::BasicBlock *lastBlock;
2226 };
2227 
2228 static bool lSwitchASTPreVisit(ASTNode *node, void *d) {
2229  if (llvm::dyn_cast<SwitchStmt>(node) != NULL)
2230  // don't continue recursively into a nested switch--we only want
2231  // our own case and default statements!
2232  return false;
2233 
2234  CaseStmt *cs = llvm::dyn_cast<CaseStmt>(node);
2235  DefaultStmt *ds = llvm::dyn_cast<DefaultStmt>(node);
2236 
2237  SwitchVisitInfo *svi = (SwitchVisitInfo *)d;
2238  llvm::BasicBlock *bb = NULL;
2239  if (cs != NULL) {
2240  // Complain if we've seen a case statement with the same value
2241  // already
2242  for (int i = 0; i < (int)svi->caseBlocks.size(); ++i) {
2243  if (svi->caseBlocks[i].first == cs->value) {
2244  Error(cs->pos, "Duplicate case value \"%d\".", cs->value);
2245  return true;
2246  }
2247  }
2248 
2249  // Otherwise create a new basic block for the code following this
2250  // 'case' statement and record the mappign between the case label
2251  // value and the basic block
2252  char buf[32];
2253  snprintf(buf, sizeof(buf), "case_%d", cs->value);
2254  bb = svi->ctx->CreateBasicBlock(buf);
2255  svi->caseBlocks.push_back(std::make_pair(cs->value, bb));
2256  } else if (ds != NULL) {
2257  // And complain if we've seen another 'default' label..
2258  if (svi->defaultBlock != NULL) {
2259  Error(ds->pos, "Multiple \"default\" lables in switch statement.");
2260  return true;
2261  } else {
2262  // Otherwise create a basic block for the code following the
2263  // "default".
2264  bb = svi->ctx->CreateBasicBlock("default");
2265  svi->defaultBlock = bb;
2266  }
2267  }
2268 
2269  // If we saw a "case" or "default" label, then update the map to record
2270  // that the block we just created follows the block created for the
2271  // previous label in the "switch".
2272  if (bb != NULL) {
2273  svi->nextBlock[svi->lastBlock] = bb;
2274  svi->lastBlock = bb;
2275  }
2276 
2277  return true;
2278 }
2279 
2281  if (ctx->GetCurrentBasicBlock() == NULL)
2282  return;
2283 
2284  const Type *type;
2285  if (expr == NULL || ((type = expr->GetType()) == NULL)) {
2286  AssertPos(pos, m->errorCount > 0);
2287  return;
2288  }
2289 
2290  // Basic block we'll end up after the switch statement
2291  llvm::BasicBlock *bbDone = ctx->CreateBasicBlock("switch_done");
2292 
2293  // Walk the AST of the statements after the 'switch' to collect a bunch
2294  // of information about the structure of the 'case' and 'default'
2295  // statements.
2296  SwitchVisitInfo svi(ctx);
2297  WalkAST(stmts, lSwitchASTPreVisit, NULL, &svi);
2298  // Record that the basic block following the last one created for a
2299  // case/default is the block after the end of the switch statement.
2300  svi.nextBlock[svi.lastBlock] = bbDone;
2301 
2302  llvm::Value *exprValue = expr->GetValue(ctx);
2303  if (exprValue == NULL) {
2304  AssertPos(pos, m->errorCount > 0);
2305  return;
2306  }
2307 
2308  bool isUniformCF = (type->IsUniformType() && lHasVaryingBreakOrContinue(stmts) == false);
2309  ctx->StartSwitch(isUniformCF, bbDone);
2310  ctx->SetBlockEntryMask(ctx->GetFullMask());
2311  ctx->SwitchInst(exprValue, svi.defaultBlock ? svi.defaultBlock : bbDone, svi.caseBlocks, svi.nextBlock);
2312 
2313  if (stmts != NULL)
2314  stmts->EmitCode(ctx);
2315 
2316  if (ctx->GetCurrentBasicBlock() != NULL)
2317  ctx->BranchInst(bbDone);
2318 
2319  ctx->SetCurrentBasicBlock(bbDone);
2320  ctx->EndSwitch();
2321 }
2322 
2323 void SwitchStmt::Print(int indent) const {
2324  printf("%*cSwitch Stmt", indent, ' ');
2325  pos.Print();
2326  printf("\n");
2327  printf("%*cexpr = ", indent, ' ');
2328  expr->Print();
2329  printf("\n");
2330  stmts->Print(indent + 4);
2331 }
2332 
2334  const Type *exprType;
2335  if (expr == NULL || (exprType = expr->GetType()) == NULL) {
2336  Assert(m->errorCount > 0);
2337  return NULL;
2338  }
2339 
2340  const Type *toType = NULL;
2341  exprType = exprType->GetAsConstType();
2344 
2345  if (exprType->IsUniformType()) {
2346  if (is64bit)
2347  toType = AtomicType::UniformInt64;
2348  else
2349  toType = AtomicType::UniformInt32;
2350  } else {
2351  if (is64bit)
2352  toType = AtomicType::VaryingInt64;
2353  else
2354  toType = AtomicType::VaryingInt32;
2355  }
2356 
2357  expr = TypeConvertExpr(expr, toType, "switch expression");
2358  if (expr == NULL)
2359  return NULL;
2360 
2361  return this;
2362 }
2363 
2365  const Type *type = expr->GetType();
2366  if (type && type->IsVaryingType())
2367  return COST_VARYING_SWITCH;
2368  else
2369  return COST_UNIFORM_SWITCH;
2370 }
2371 
2372 ///////////////////////////////////////////////////////////////////////////
2373 // UnmaskedStmt
2374 
2376 
2378  if (!ctx->GetCurrentBasicBlock() || !stmts)
2379  return;
2380 
2381  llvm::Value *oldInternalMask = ctx->GetInternalMask();
2382  llvm::Value *oldFunctionMask = ctx->GetFunctionMask();
2383 
2386 
2387  stmts->EmitCode(ctx);
2388 
2389  // Do not restore old mask if our basic block is over. This happends if we emit code
2390  // for something like 'unmasked{return;}', for example.
2391  if (ctx->GetCurrentBasicBlock() == NULL)
2392  return;
2393 
2394  ctx->SetInternalMask(oldInternalMask);
2395  ctx->SetFunctionMask(oldFunctionMask);
2396 }
2397 
2398 void UnmaskedStmt::Print(int indent) const {
2399  printf("%*cUnmasked Stmt", indent, ' ');
2400  pos.Print();
2401  printf("\n");
2402 
2403  printf("%*cStmts:\n", indent + 4, ' ');
2404  if (stmts != NULL)
2405  stmts->Print(indent + 8);
2406  else
2407  printf("NULL");
2408  printf("\n");
2409 }
2410 
2411 Stmt *UnmaskedStmt::TypeCheck() { return this; }
2412 
2414 
2415 ///////////////////////////////////////////////////////////////////////////
2416 // ReturnStmt
2417 
2419 
2421  if (!ctx->GetCurrentBasicBlock())
2422  return;
2423 
2424  if (ctx->InForeachLoop()) {
2425  Error(pos, "\"return\" statement is illegal inside a \"foreach\" loop.");
2426  return;
2427  }
2428 
2429  // Make sure we're not trying to return a reference to something where
2430  // that doesn't make sense
2431  const Function *func = ctx->GetFunction();
2432  const Type *returnType = func->GetReturnType();
2433  if (IsReferenceType(returnType) == true && IsReferenceType(expr->GetType()) == false) {
2434  const Type *lvType = expr->GetLValueType();
2435  if (lvType == NULL) {
2436  Error(expr->pos,
2437  "Illegal to return non-lvalue from function "
2438  "returning reference type \"%s\".",
2439  returnType->GetString().c_str());
2440  return;
2441  } else if (lvType->IsUniformType() == false) {
2442  Error(expr->pos,
2443  "Illegal to return varying lvalue type from "
2444  "function returning a reference type \"%s\".",
2445  returnType->GetString().c_str());
2446  return;
2447  }
2448  }
2449 
2450  ctx->SetDebugPos(pos);
2451  ctx->CurrentLanesReturned(expr, true);
2452 }
2453 
2454 Stmt *ReturnStmt::TypeCheck() { return this; }
2455 
2456 int ReturnStmt::EstimateCost() const { return COST_RETURN; }
2457 
2458 void ReturnStmt::Print(int indent) const {
2459  printf("%*cReturn Stmt", indent, ' ');
2460  pos.Print();
2461  if (expr)
2462  expr->Print();
2463  else
2464  printf("(void)");
2465  printf("\n");
2466 }
2467 
2468 ///////////////////////////////////////////////////////////////////////////
2469 // GotoStmt
2470 
2471 GotoStmt::GotoStmt(const char *l, SourcePos gotoPos, SourcePos ip) : Stmt(gotoPos, GotoStmtID) {
2472  label = l;
2473  identifierPos = ip;
2474 }
2475 
2477  if (!ctx->GetCurrentBasicBlock())
2478  return;
2479 
2480  if (ctx->VaryingCFDepth() > 0) {
2481  Error(pos, "\"goto\" statements are only legal under \"uniform\" "
2482  "control flow.");
2483  return;
2484  }
2485  if (ctx->InForeachLoop()) {
2486  Error(pos, "\"goto\" statements are currently illegal inside "
2487  "\"foreach\" loops.");
2488  return;
2489  }
2490 
2491  llvm::BasicBlock *bb = ctx->GetLabeledBasicBlock(label);
2492  if (bb == NULL) {
2493  /* Label wasn't found. Look for suggestions that are close */
2494  std::vector<std::string> labels = ctx->GetLabels();
2495  std::vector<std::string> matches = MatchStrings(label, labels);
2496  std::string match_output;
2497  if (!matches.empty()) {
2498  /* Print up to 5 matches. Don't want to spew too much */
2499  match_output += "\nDid you mean:";
2500  for (unsigned int i = 0; i < matches.size() && i < 5; i++)
2501  match_output += "\n " + matches[i] + "?";
2502  }
2503 
2504  /* Label wasn't found. Emit an error */
2505  Error(identifierPos, "No label named \"%s\" found in current function.%s", label.c_str(), match_output.c_str());
2506 
2507  return;
2508  }
2509 
2510  ctx->BranchInst(bb);
2511  ctx->SetCurrentBasicBlock(NULL);
2512 }
2513 
2514 void GotoStmt::Print(int indent) const { printf("%*cGoto label \"%s\"\n", indent, ' ', label.c_str()); }
2515 
2516 Stmt *GotoStmt::Optimize() { return this; }
2517 
2518 Stmt *GotoStmt::TypeCheck() { return this; }
2519 
2520 int GotoStmt::EstimateCost() const { return COST_GOTO; }
2521 
2522 ///////////////////////////////////////////////////////////////////////////
2523 // LabeledStmt
2524 
2526  name = n;
2527  stmt = s;
2528 }
2529 
2531  llvm::BasicBlock *bblock = ctx->GetLabeledBasicBlock(name);
2532  AssertPos(pos, bblock != NULL);
2533 
2534  // End the current basic block with a jump to our basic block and then
2535  // set things up for emission to continue there. Note that the current
2536  // basic block may validly be NULL going into this statement due to an
2537  // earlier goto that NULLed it out; that doesn't stop us from
2538  // re-establishing a current basic block starting at the label..
2539  if (ctx->GetCurrentBasicBlock() != NULL)
2540  ctx->BranchInst(bblock);
2541  ctx->SetCurrentBasicBlock(bblock);
2542 
2543  if (stmt != NULL)
2544  stmt->EmitCode(ctx);
2545 }
2546 
2547 void LabeledStmt::Print(int indent) const {
2548  printf("%*cLabel \"%s\"\n", indent, ' ', name.c_str());
2549  if (stmt != NULL)
2550  stmt->Print(indent);
2551 }
2552 
2553 Stmt *LabeledStmt::Optimize() { return this; }
2554 
2556  if (!isalpha(name[0]) || name[0] == '_') {
2557  Error(pos, "Label must start with either alphabetic character or '_'.");
2558  return NULL;
2559  }
2560  for (unsigned int i = 1; i < name.size(); ++i) {
2561  if (!isalnum(name[i]) && name[i] != '_') {
2562  Error(pos, "Character \"%c\" is illegal in labels.", name[i]);
2563  return NULL;
2564  }
2565  }
2566  return this;
2567 }
2568 
2569 int LabeledStmt::EstimateCost() const { return 0; }
2570 
2571 ///////////////////////////////////////////////////////////////////////////
2572 // StmtList
2573 
2575  ctx->StartScope();
2576  ctx->SetDebugPos(pos);
2577  for (unsigned int i = 0; i < stmts.size(); ++i)
2578  if (stmts[i])
2579  stmts[i]->EmitCode(ctx);
2580  ctx->EndScope();
2581 }
2582 
2583 Stmt *StmtList::TypeCheck() { return this; }
2584 
2585 int StmtList::EstimateCost() const { return 0; }
2586 
2587 void StmtList::Print(int indent) const {
2588  printf("%*cStmt List", indent, ' ');
2589  pos.Print();
2590  printf(":\n");
2591  for (unsigned int i = 0; i < stmts.size(); ++i)
2592  if (stmts[i])
2593  stmts[i]->Print(indent + 4);
2594 }
2595 
2596 ///////////////////////////////////////////////////////////////////////////
2597 // PrintStmt
2598 
2599 PrintStmt::PrintStmt(const std::string &f, Expr *v, SourcePos p) : Stmt(p, PrintStmtID), format(f), values(v) {}
2600 
2601 /* Because the pointers to values that are passed to __do_print() are all
2602  void *s (and because ispc print() formatting strings statements don't
2603  encode types), we pass along a string to __do_print() where the i'th
2604  character encodes the type of the i'th value to be printed. Needless to
2605  say, the encoding chosen here and the decoding code in __do_print() need
2606  to agree on the below!
2607  */
2608 static char lEncodeType(const Type *t) {
2610  return 'b';
2612  return 'B';
2614  return 'i';
2616  return 'I';
2618  return 'u';
2620  return 'U';
2622  return 'f';
2624  return 'F';
2626  return 'l';
2628  return 'L';
2630  return 'v';
2632  return 'V';
2634  return 'd';
2636  return 'D';
2637  if (CastType<PointerType>(t) != NULL) {
2638  if (t->IsUniformType())
2639  return 'p';
2640  else
2641  return 'P';
2642  } else
2643  return '\0';
2644 }
2645 
2646 /** Given an Expr for a value to be printed, emit the code to evaluate the
2647  expression and store the result to alloca'd memory. Update the
2648  argTypes string with the type encoding for this expression.
2649  */
2650 static llvm::Value *lProcessPrintArg(Expr *expr, FunctionEmitContext *ctx, std::string &argTypes) {
2651  const Type *type = expr->GetType();
2652  if (type == NULL)
2653  return NULL;
2654 
2655  if (CastType<ReferenceType>(type) != NULL) {
2656  expr = new RefDerefExpr(expr, expr->pos);
2657  type = expr->GetType();
2658  if (type == NULL)
2659  return NULL;
2660  }
2661 
2662  // Just int8 and int16 types to int32s...
2663  const Type *baseType = type->GetAsNonConstType()->GetAsUniformType();
2667  expr->pos);
2668  type = expr->GetType();
2669  }
2670 
2671  char t = lEncodeType(type->GetAsNonConstType());
2672  if (t == '\0') {
2673  Error(expr->pos,
2674  "Only atomic types are allowed in print statements; "
2675  "type \"%s\" is illegal.",
2676  type->GetString().c_str());
2677  return NULL;
2678  } else {
2679  if (Type::Equal(baseType, AtomicType::UniformBool)) {
2680  // Blast bools to ints, but do it here to preserve encoding for
2681  // printing 'true' or 'false'
2683  expr->pos);
2684  type = expr->GetType();
2685  }
2686  argTypes.push_back(t);
2687 
2688  llvm::Value *ptr = ctx->AllocaInst(type, "print_arg");
2689  llvm::Value *val = expr->GetValue(ctx);
2690  if (!val)
2691  return NULL;
2692  ctx->StoreInst(val, ptr, type);
2693 
2694  ptr = ctx->BitCastInst(ptr, LLVMTypes::VoidPointerType);
2695  return ptr;
2696  }
2697 }
2698 
2699 /* PrintStmt works closely with the __do_print() function implemented in
2700  the builtins-c.c file. In particular, the EmitCode() method here needs to
2701  take the arguments passed to it from ispc and generate a valid call to
2702  __do_print() with the information that __do_print() then needs to do the
2703  actual printing work at runtime.
2704  */
2706  if (!ctx->GetCurrentBasicBlock())
2707  return;
2708 
2709  ctx->SetDebugPos(pos);
2710 
2711  // __do_print takes 5 arguments; we'll get them stored in the args[] array
2712  // in the code emitted below
2713  //
2714  // 1. the format string
2715  // 2. a string encoding the types of the values being printed,
2716  // one character per value
2717  // 3. the number of running program instances (i.e. the target's
2718  // vector width)
2719  // 4. the current lane mask
2720  // 5. a pointer to an array of pointers to the values to be printed
2721  llvm::Value *args[5];
2722  std::string argTypes;
2723 
2724  if (values == NULL) {
2725  llvm::Type *ptrPtrType = llvm::PointerType::get(LLVMTypes::VoidPointerType, 0);
2726  args[4] = llvm::Constant::getNullValue(ptrPtrType);
2727  } else {
2728  // Get the values passed to the print() statement evaluated and
2729  // stored in memory so that we set up the array of pointers to them
2730  // for the 5th __do_print() argument
2731  ExprList *elist = llvm::dyn_cast<ExprList>(values);
2732  int nArgs = elist ? elist->exprs.size() : 1;
2733 
2734  // Allocate space for the array of pointers to values to be printed
2735  llvm::Type *argPtrArrayType = llvm::ArrayType::get(LLVMTypes::VoidPointerType, nArgs);
2736  llvm::Value *argPtrArray = ctx->AllocaInst(argPtrArrayType, "print_arg_ptrs");
2737  // Store the array pointer as a void **, which is what __do_print()
2738  // expects
2739  args[4] = ctx->BitCastInst(argPtrArray, llvm::PointerType::get(LLVMTypes::VoidPointerType, 0));
2740 
2741  // Now, for each of the arguments, emit code to evaluate its value
2742  // and store the value into alloca'd storage. Then store the
2743  // pointer to the alloca'd storage into argPtrArray.
2744  if (elist) {
2745  for (unsigned int i = 0; i < elist->exprs.size(); ++i) {
2746  Expr *expr = elist->exprs[i];
2747  if (!expr)
2748  return;
2749  llvm::Value *ptr = lProcessPrintArg(expr, ctx, argTypes);
2750  if (!ptr)
2751  return;
2752 
2753  llvm::Value *arrayPtr = ctx->AddElementOffset(argPtrArray, i, NULL);
2754  ctx->StoreInst(ptr, arrayPtr);
2755  }
2756  } else {
2757  llvm::Value *ptr = lProcessPrintArg(values, ctx, argTypes);
2758  if (!ptr)
2759  return;
2760  llvm::Value *arrayPtr = ctx->AddElementOffset(argPtrArray, 0, NULL);
2761  ctx->StoreInst(ptr, arrayPtr);
2762  }
2763  }
2764 
2765  // Now we can emit code to call __do_print()
2766  llvm::Function *printFunc = m->module->getFunction("__do_print");
2767  AssertPos(pos, printFunc);
2768 
2769  llvm::Value *mask = ctx->GetFullMask();
2770  // Set up the rest of the parameters to it
2771  args[0] = ctx->GetStringPtr(format);
2772  args[1] = ctx->GetStringPtr(argTypes);
2773  args[2] = LLVMInt32(g->target->getVectorWidth());
2774  args[3] = ctx->LaneMask(mask);
2775  std::vector<llvm::Value *> argVec(&args[0], &args[5]);
2776  ctx->CallInst(printFunc, NULL, argVec, "");
2777 }
2778 
2779 void PrintStmt::Print(int indent) const { printf("%*cPrint Stmt (%s)", indent, ' ', format.c_str()); }
2780 
2781 Stmt *PrintStmt::TypeCheck() { return this; }
2782 
2783 int PrintStmt::EstimateCost() const { return COST_FUNCALL; }
2784 
2785 ///////////////////////////////////////////////////////////////////////////
2786 // AssertStmt
2787 
2788 AssertStmt::AssertStmt(const std::string &msg, Expr *e, SourcePos p) : Stmt(p, AssertStmtID), message(msg), expr(e) {}
2789 
2791  if (!ctx->GetCurrentBasicBlock())
2792  return;
2793 
2794  const Type *type;
2795  if (expr == NULL || (type = expr->GetType()) == NULL) {
2796  AssertPos(pos, m->errorCount > 0);
2797  return;
2798  }
2799  bool isUniform = type->IsUniformType();
2800 
2801  // The actual functionality to do the check and then handle falure is
2802  // done via a builtin written in bitcode in builtins/util.m4.
2803  llvm::Function *assertFunc =
2804  isUniform ? m->module->getFunction("__do_assert_uniform") : m->module->getFunction("__do_assert_varying");
2805  AssertPos(pos, assertFunc != NULL);
2806 
2807  char *errorString;
2808  if (asprintf(&errorString, "%s:%d:%d: Assertion failed: %s", pos.name, pos.first_line, pos.first_column,
2809  message.c_str()) == -1) {
2810  Error(pos, "Fatal error when generating assert string: asprintf() "
2811  "unable to allocate memory!");
2812  return;
2813  }
2814 
2815  std::vector<llvm::Value *> args;
2816  args.push_back(ctx->GetStringPtr(errorString));
2817  llvm::Value *exprValue = expr->GetValue(ctx);
2818  if (exprValue == NULL) {
2819  AssertPos(pos, m->errorCount > 0);
2820  return;
2821  }
2822  args.push_back(exprValue);
2823  args.push_back(ctx->GetFullMask());
2824  ctx->CallInst(assertFunc, NULL, args, "");
2825 
2826  free(errorString);
2827 }
2828 
2829 void AssertStmt::Print(int indent) const { printf("%*cAssert Stmt (%s)", indent, ' ', message.c_str()); }
2830 
2832  const Type *type;
2833  if (expr && (type = expr->GetType()) != NULL) {
2834  bool isUniform = type->IsUniformType();
2836  "\"assert\" statement");
2837  if (expr == NULL)
2838  return NULL;
2839  }
2840  return this;
2841 }
2842 
2843 int AssertStmt::EstimateCost() const { return COST_ASSERT; }
2844 
2845 ///////////////////////////////////////////////////////////////////////////
2846 // DeleteStmt
2847 
2849 
2851  if (!ctx->GetCurrentBasicBlock())
2852  return;
2853 
2854  const Type *exprType;
2855  if (expr == NULL || ((exprType = expr->GetType()) == NULL)) {
2856  AssertPos(pos, m->errorCount > 0);
2857  return;
2858  }
2859 
2860  llvm::Value *exprValue = expr->GetValue(ctx);
2861  if (exprValue == NULL) {
2862  AssertPos(pos, m->errorCount > 0);
2863  return;
2864  }
2865 
2866  // Typechecking should catch this
2867  AssertPos(pos, CastType<PointerType>(exprType) != NULL);
2868 
2869  if (exprType->IsUniformType()) {
2870  // For deletion of a uniform pointer, we just need to cast the
2871  // pointer type to a void pointer type, to match what
2872  // __delete_uniform() from the builtins expects.
2873  exprValue = ctx->BitCastInst(exprValue, LLVMTypes::VoidPointerType, "ptr_to_void");
2874  llvm::Function *func;
2875  if (g->target->is32Bit()) {
2876  func = m->module->getFunction("__delete_uniform_32rt");
2877  } else {
2878  func = m->module->getFunction("__delete_uniform_64rt");
2879  }
2880  AssertPos(pos, func != NULL);
2881 
2882  ctx->CallInst(func, NULL, exprValue, "");
2883  } else {
2884  // Varying pointers are arrays of ints, and __delete_varying()
2885  // takes a vector of i64s (even for 32-bit targets). Therefore, we
2886  // only need to extend to 64-bit values on 32-bit targets before
2887  // calling it.
2888  llvm::Function *func;
2889  if (g->target->is32Bit()) {
2890  func = m->module->getFunction("__delete_varying_32rt");
2891  } else {
2892  func = m->module->getFunction("__delete_varying_64rt");
2893  }
2894  AssertPos(pos, func != NULL);
2895  if (g->target->is32Bit())
2896  exprValue = ctx->ZExtInst(exprValue, LLVMTypes::Int64VectorType, "ptr_to_64");
2897  ctx->CallInst(func, NULL, exprValue, "");
2898  }
2899 }
2900 
2901 void DeleteStmt::Print(int indent) const { printf("%*cDelete Stmt", indent, ' '); }
2902 
2904  const Type *exprType;
2905  if (expr == NULL || ((exprType = expr->GetType()) == NULL))
2906  return NULL;
2907 
2908  if (CastType<PointerType>(exprType) == NULL) {
2909  Error(pos, "Illegal to delete non-pointer type \"%s\".", exprType->GetString().c_str());
2910  return NULL;
2911  }
2912 
2913  return this;
2914 }
2915 
2916 int DeleteStmt::EstimateCost() const { return COST_DELETE; }
const Function * GetFunction() const
Definition: ctx.cpp:357
llvm::Value * storagePtr
Definition: sym.h:70
int EstimateCost() const
Definition: stmt.cpp:2783
static const AtomicType * VaryingInt32
Definition: type.h:325
llvm::Value * Any(llvm::Value *mask)
Definition: ctx.cpp:1123
bool IsUniformType() const
Definition: type.h:134
void EmitCode(FunctionEmitContext *ctx) const
Definition: stmt.cpp:1918
Expr * expr
Definition: stmt.h:514
void EmitCode(FunctionEmitContext *ctx) const
Definition: stmt.cpp:2280
Stmt * bodyStmts
Definition: stmt.h:172
ForStmt(Stmt *initializer, Expr *testExpr, Stmt *stepStatements, Stmt *bodyStatements, bool doCoherentCheck, SourcePos pos)
Definition: stmt.cpp:918
std::vector< VariableDeclaration > vars
Definition: stmt.h:114
std::vector< std::pair< int, llvm::BasicBlock * > > caseBlocks
Definition: stmt.cpp:2215
void EmitCode(FunctionEmitContext *ctx) const
Definition: stmt.cpp:2790
static bool lIsVaryingFor(ASTNode *node)
Definition: stmt.cpp:697
static bool lHasVaryingBreakOrContinue(Stmt *stmt)
Definition: stmt.cpp:749
Definition: func.h:43
int EstimateCost() const
Definition: stmt.cpp:894
llvm::Value * AddElementOffset(llvm::Value *basePtr, int elementNum, const Type *ptrType, const char *name=NULL, const PointerType **resultPtrType=NULL)
Definition: ctx.cpp:1951
Opt opt
Definition: ispc.h:509
void StartUniformIf()
Definition: ctx.cpp:425
bool InForeachLoop() const
Definition: ctx.cpp:1004
void StartSwitch(bool isUniform, llvm::BasicBlock *bbAfterSwitch)
Definition: ctx.cpp:784
llvm::Value * ProgramIndexVector(bool is32bits=true)
Definition: ctx.cpp:1208
Stmt * stmts
Definition: stmt.h:355
static llvm::Value * lUpdateVaryingCounter(int dim, int nDims, FunctionEmitContext *ctx, llvm::Value *uniformCounterPtr, llvm::Value *varyingCounterPtr, const std::vector< int > &spans)
Definition: stmt.cpp:1154
ASTNode * WalkAST(ASTNode *node, ASTPreCallBackFunc preFunc, ASTPostCallBackFunc postFunc, void *data)
Definition: ast.cpp:68
void SetInternalMask(llvm::Value *val)
Definition: ctx.cpp:381
void StartLoop(llvm::BasicBlock *breakTarget, llvm::BasicBlock *continueTarget, bool uniformControlFlow)
Definition: ctx.cpp:487
const bool doCoherentCheck
Definition: stmt.h:203
void emitMaskAllOn(FunctionEmitContext *ctx, llvm::Value *test, llvm::BasicBlock *bDone) const
Definition: stmt.cpp:571
Declaration of the FunctionEmitContext class
void EmitVariableDebugInfo(Symbol *sym)
Definition: ctx.cpp:1333
Stmt * trueStmts
Definition: stmt.h:137
llvm::Constant * LLVMBoolVector(bool b)
Definition: llvmutil.cpp:403
void StartScope()
Definition: ctx.cpp:1304
void Print(int indent) const
Definition: stmt.cpp:901
static const AtomicType * VaryingUInt64
Definition: type.h:331
void Print(int indent) const
Definition: stmt.cpp:2901
Expr * expr
Definition: stmt.h:334
std::vector< Expr * > endExprs
Definition: stmt.h:256
bool SafeToRunWithMaskAllOff(ASTNode *root)
Definition: ast.cpp:417
SwitchVisitInfo(FunctionEmitContext *c)
Definition: stmt.cpp:2202
bool IsVaryingType() const
Definition: type.h:137
void SetInternalMaskAnd(llvm::Value *oldMask, llvm::Value *val)
Definition: ctx.cpp:387
void BranchInst(llvm::BasicBlock *block)
Definition: ctx.cpp:2819
static bool lSwitchASTPreVisit(ASTNode *node, void *d)
Definition: stmt.cpp:2228
llvm::Instruction * ZExtInst(llvm::Value *value, llvm::Type *type, const char *name=NULL)
Definition: ctx.cpp:1671
#define AssertPos(pos, expr)
Definition: util.h:142
Stmt * TypeCheck()
Definition: stmt.cpp:2454
Interface class for statements in the ispc language.
Definition: stmt.h:48
int EstimateCost() const
Definition: stmt.cpp:455
Stmt * TypeCheck()
Definition: stmt.cpp:1662
llvm::Value * NotOperator(llvm::Value *v, const char *name=NULL)
Definition: ctx.cpp:1412
int first_line
Definition: ispc.h:127
void Print(int indent) const
Definition: stmt.cpp:2587
void Print(int indent) const
Definition: stmt.cpp:463
Target * target
Definition: ispc.h:512
llvm::Value * LoadInst(llvm::Value *ptr, llvm::Value *mask, const Type *ptrType, const char *name=NULL, bool one_elem=false)
Definition: ctx.cpp:2172
void BranchIfMaskAll(llvm::BasicBlock *btrue, llvm::BasicBlock *bfalse)
Definition: ctx.cpp:407
BreakStmt(SourcePos pos)
Definition: stmt.cpp:1100
const std::string message
Definition: stmt.h:512
void EmitCode(FunctionEmitContext *ctx) const
Definition: stmt.cpp:71
void Print(int indent) const
Definition: stmt.cpp:1877
std::vector< std::string > GetLabels()
Definition: ctx.cpp:1043
const std::string format
Definition: stmt.h:484
int EstimateCost() const
Definition: stmt.cpp:2364
int EstimateCost() const
Definition: stmt.cpp:1906
static const AtomicType * VaryingDouble
Definition: type.h:332
llvm::Instruction * TruncInst(llvm::Value *value, llvm::Type *type, const char *name=NULL)
Definition: ctx.cpp:1606
llvm::Constant * LLVMMaskAllOn
Definition: llvmutil.cpp:94
llvm::Value * AllocaInst(llvm::Type *llvmType, const char *name=NULL, int align=0, bool atEntryBlock=true)
Definition: ctx.cpp:2401
int EstimateCost() const
Definition: stmt.cpp:2187
Expression representing a compile-time constant value.
Definition: expr.h:374
void EmitCode(FunctionEmitContext *ctx) const
Definition: stmt.cpp:2476
llvm::Value * CmpInst(llvm::Instruction::OtherOps inst, llvm::CmpInst::Predicate pred, llvm::Value *v0, llvm::Value *v1, const char *name=NULL)
Definition: ctx.cpp:1454
void EndSwitch()
Definition: ctx.cpp:805
void StartVaryingIf(llvm::Value *oldMask)
Definition: ctx.cpp:427
static llvm::Type * BoolType
Definition: llvmutil.h:62
void SetContinueTarget(llvm::BasicBlock *bb)
Definition: ctx.h:245
const Type * GetElementType() const
Definition: type.cpp:1185
static bool checkInit(const Type *type, Expr **init)
Definition: stmt.cpp:266
void Print(int indent) const
Definition: stmt.cpp:2178
void Print(int indent) const
Definition: stmt.cpp:2072
void StartForeach(ForeachType ft)
Definition: ctx.cpp:525
static llvm::VectorType * Int32VectorType
Definition: llvmutil.h:86
Expr * TypeConvertExpr(Expr *expr, const Type *toType, const char *errorMsgBase)
Definition: expr.cpp:548
bool PossiblyResolveFunctionOverloads(Expr *expr, const Type *type)
Definition: expr.cpp:565
static const AtomicType * UniformUInt32
Definition: type.h:328
Stmt * Optimize()
Definition: stmt.cpp:2553
void Continue(bool doCoherenceCheck)
Definition: ctx.cpp:660
llvm::Value * GetFullMask()
Definition: ctx.cpp:367
IfStmt(Expr *testExpr, Stmt *trueStmts, Stmt *falseStmts, bool doAllCheck, SourcePos pos)
Definition: stmt.cpp:333
Stmt * TypeCheck()
Definition: stmt.cpp:1899
int VaryingCFDepth() const
Definition: ctx.cpp:996
virtual std::pair< llvm::Constant *, bool > GetConstant(const Type *type) const
Definition: expr.cpp:85
Stmt * TypeCheck()
Definition: stmt.cpp:866
void Print(int indent) const
Definition: stmt.cpp:2829
Stmt * TypeCheck()
Definition: stmt.cpp:1110
void AddInstrumentationPoint(const char *note)
Definition: ctx.cpp:1269
llvm::BasicBlock * lastBlock
Definition: stmt.cpp:2225
Stmt * TypeCheck()
Definition: stmt.cpp:2185
Module * m
Definition: ispc.cpp:73
std::string name
Definition: sym.h:69
void EmitCode(FunctionEmitContext *ctx) const
Definition: stmt.cpp:922
static int lLog2(int i)
Definition: stmt.cpp:1189
A list of expressions.
Definition: expr.h:249
CaseStmt(int value, Stmt *stmt, SourcePos pos)
Definition: stmt.cpp:2148
static bool lCheckMask(Stmt *stmts)
Definition: stmt.cpp:2135
Symbol * LookupVariable(const char *name)
Definition: sym.cpp:112
void Print(int indent) const
Definition: stmt.cpp:2323
Stmt * TypeCheck()
Definition: stmt.cpp:2781
Statement implementation representing a &#39;do&#39; statement in the program.
Definition: stmt.h:158
int EstimateCost() const
Definition: stmt.cpp:1706
void Print(int indent) const
Definition: stmt.cpp:82
int EstimateCost() const
Definition: stmt.cpp:93
void EmitCode(FunctionEmitContext *ctx) const
Definition: stmt.cpp:2530
void BranchIfMaskAny(llvm::BasicBlock *btrue, llvm::BasicBlock *bfalse)
Definition: ctx.cpp:398
void RestoreContinuedLanes()
Definition: ctx.cpp:762
void Print(int indent) const
Definition: stmt.cpp:1114
void EmitCode(FunctionEmitContext *ctx) const
Definition: stmt.cpp:372
int EstimateCost() const
Definition: stmt.cpp:2456
virtual void Print() const =0
llvm::BasicBlock * GetCurrentBasicBlock()
Definition: ctx.cpp:359
static const AtomicType * UniformUInt16
Definition: type.h:327
static bool lHasUnsizedArrays(const Type *type)
Definition: stmt.cpp:100
std::vector< std::string > MatchStrings(const std::string &str, const std::vector< std::string > &options)
Definition: util.cpp:490
static PointerType * GetUniform(const Type *t, bool isSlice=false)
Definition: type.cpp:799
ReturnStmt(Expr *e, SourcePos p)
Definition: stmt.cpp:2418
virtual llvm::Value * GetValue(FunctionEmitContext *ctx) const =0
void Break(bool doCoherenceCheck)
Definition: ctx.cpp:589
const int value
Definition: stmt.h:354
virtual void EmitCode(FunctionEmitContext *ctx) const =0
ConstExpr * constValue
Definition: sym.h:85
llvm::Value * CallInst(llvm::Value *func, const FunctionType *funcType, const std::vector< llvm::Value *> &args, const char *name=NULL)
Definition: ctx.cpp:2975
llvm::BasicBlock * CreateBasicBlock(const char *name)
Definition: ctx.cpp:1228
virtual llvm::Type * LLVMType(llvm::LLVMContext *ctx) const =0
int EstimateCost() const
Definition: stmt.cpp:2569
header file with declarations for symbol and symbol table classes.
int EstimateCost() const
Definition: stmt.cpp:2520
static const AtomicType * UniformBool
Definition: type.h:322
llvm::Value * BroadcastValue(llvm::Value *v, llvm::Type *vecType, const char *name=NULL)
Definition: ctx.cpp:2893
Symbol * sym
Definition: stmt.h:296
bool disableMaskAllOnOptimizations
Definition: ispc.h:431
Expr * test
Definition: stmt.h:135
static ASTNode * lVaryingBCPostFunc(ASTNode *node, void *d)
Definition: stmt.cpp:736
llvm::Module * module
Definition: module.h:151
Stmt * stmts
Definition: stmt.h:393
File with declarations for classes related to statements in the language.
static void lEmitIfStatements(FunctionEmitContext *ctx, Stmt *stmts, const char *trueOrFalse)
Definition: stmt.cpp:337
void StoreInst(llvm::Value *value, llvm::Value *ptr, const Type *ptrType=NULL)
Definition: ctx.cpp:2674
void EmitCode(FunctionEmitContext *ctx) const
Definition: stmt.cpp:2377
ContinueStmt(SourcePos pos)
Definition: stmt.cpp:1123
void EmitCaseLabel(int value, bool checkMask, SourcePos pos)
Definition: ctx.cpp:902
Stmt * stmts
Definition: stmt.h:373
bool IsReferenceType(const Type *t)
Definition: type.h:1012
Expr * expr
Definition: stmt.h:391
Expression representing a type cast of the given expression to a probably-different type...
Definition: expr.h:491
ExprStmt(Expr *expr, SourcePos pos)
Definition: stmt.cpp:69
LabeledStmt(const char *label, Stmt *stmt, SourcePos p)
Definition: stmt.cpp:2525
static const AtomicType * UniformUInt64
Definition: type.h:331
void EndLoop()
Definition: ctx.cpp:512
llvm::Value * GetFunctionMask()
Definition: ctx.cpp:363
bool disableCoherentControlFlow
Definition: ispc.h:453
llvm::Constant * LLVMInt32Vector(int32_t ival)
Definition: llvmutil.cpp:313
SourcePos GetDebugPos() const
Definition: ctx.cpp:1290
void Print(int indent) const
Definition: stmt.cpp:2514
Abstract base class for nodes in the abstract syntax tree (AST).
Definition: ast.h:49
int EstimateCost() const
Definition: stmt.cpp:2413
llvm::Value * GetElementPtrInst(llvm::Value *basePtr, llvm::Value *index, const Type *ptrType, const char *name=NULL)
Definition: ctx.cpp:1825
void EmitCode(FunctionEmitContext *ctx) const
Definition: stmt.cpp:2172
Stmt * TypeCheck()
Definition: stmt.cpp:2163
void CurrentLanesReturned(Expr *value, bool doCoherenceCheck)
Definition: ctx.cpp:1055
Stmt * TypeCheck()
Definition: stmt.cpp:2583
llvm::Constant * LLVMTrue
Definition: llvmutil.cpp:90
ForeachUniqueStmt(const char *iterName, Expr *expr, Stmt *stmts, SourcePos pos)
Definition: stmt.cpp:1911
void Print(int indent) const
Definition: stmt.cpp:2156
Stmt * stmts
Definition: stmt.h:298
ForeachActiveStmt(Symbol *iterSym, Stmt *stmts, SourcePos pos)
Definition: stmt.cpp:1752
Stmt * TypeCheck()
Definition: stmt.cpp:80
llvm::Value * LaneMask(llvm::Value *mask)
Definition: ctx.cpp:1170
Stmt * Optimize()
Definition: stmt.cpp:2516
DeclStmt(const std::vector< VariableDeclaration > &v, SourcePos pos)
Definition: stmt.cpp:98
Stmt * step
Definition: stmt.h:200
Stmt * TypeCheck()
Definition: stmt.cpp:2555
static char lEncodeType(const Type *t)
Definition: stmt.cpp:2608
void Print(int indent) const
Definition: stmt.cpp:2779
Stmt * TypeCheck()
Definition: stmt.cpp:2903
virtual const Type * GetLValueType() const
Definition: expr.cpp:78
static llvm::Type * Int64Type
Definition: llvmutil.h:68
Stmt * TypeCheck()
Definition: stmt.cpp:2333
bool isTiled
Definition: stmt.h:257
Representation of a structure holding a number of members.
Definition: type.h:650
void InitSymbol(llvm::Value *ptr, const Type *symType, Expr *initExpr, FunctionEmitContext *ctx, SourcePos pos)
Definition: expr.cpp:594
FunctionEmitContext * ctx
Definition: stmt.cpp:2208
static llvm::VectorType * Int64VectorType
Definition: llvmutil.h:87
Header file with declarations for various LLVM utility stuff.
void Print(int indent) const
Definition: stmt.cpp:2547
const AtomicType * GetAsConstType() const
Definition: type.cpp:207
AssertStmt(const std::string &msg, Expr *e, SourcePos p)
Definition: stmt.cpp:2788
static bool IsBasicType(const Type *type)
Definition: type.cpp:2762
SourcePos pos
Definition: sym.h:68
virtual const Type * GetType() const =0
static void lGetSpans(int dimsLeft, int nDims, int itemsLeft, bool isTiled, int *a)
Definition: stmt.cpp:1207
Stmt * TypeCheck()
Definition: stmt.cpp:1133
void EmitCode(FunctionEmitContext *ctx) const
Definition: stmt.cpp:111
void EmitCode(FunctionEmitContext *ctx) const
Definition: stmt.cpp:2705
void SetBlockEntryMask(llvm::Value *mask)
Definition: ctx.cpp:379
int EstimateCost() const
Definition: stmt.cpp:2165
llvm::Constant * LLVMMaskAllOff
Definition: llvmutil.cpp:95
StorageClass storageClass
Definition: sym.h:94
Representation of a range of positions in a source file.
Definition: ispc.h:123
int EstimateCost() const
Definition: stmt.cpp:2916
Stmt * stmts
Definition: stmt.h:277
DoStmt(Expr *testExpr, Stmt *bodyStmts, bool doCoherentCheck, SourcePos pos)
Definition: stmt.cpp:755
void Print(int indent) const
Definition: stmt.cpp:313
Stmt * TypeCheck()
Definition: stmt.cpp:2518
llvm::ConstantInt * LLVMInt32(int32_t ival)
Definition: llvmutil.cpp:233
Stmt * stmts
Definition: stmt.h:202
virtual const Type * GetAsNonConstType() const =0
void ClearBreakLanes()
Definition: ctx.cpp:776
static const AtomicType * VaryingBool
Definition: type.h:322
virtual std::string GetString() const =0
void EmitCode(FunctionEmitContext *ctx) const
Definition: stmt.cpp:2574
void Print() const
Definition: ispc.cpp:1514
GotoStmt(const char *label, SourcePos gotoPos, SourcePos idPos)
Definition: stmt.cpp:2471
void Print(int indent) const
Definition: stmt.cpp:1137
void emitMaskedTrueAndFalse(FunctionEmitContext *ctx, llvm::Value *oldMask, llvm::Value *test) const
Definition: stmt.cpp:482
int GetElementCount() const
Definition: type.h:699
const char * name
Definition: ispc.h:126
SourcePos pos
Definition: ast.h:76
void Print(int indent) const
Definition: stmt.cpp:1074
int EstimateCost() const
Definition: stmt.cpp:328
Stmt * TypeCheck()
Definition: stmt.cpp:1051
static llvm::PointerType * VoidPointerType
Definition: llvmutil.h:60
static const AtomicType * VaryingInt64
Definition: type.h:330
const bool doCoherentCheck
Definition: stmt.h:173
void Error(SourcePos p, const char *fmt,...)
Definition: util.cpp:351
Expr * values
Definition: stmt.h:487
int getVectorWidth() const
Definition: ispc.h:245
void SwitchInst(llvm::Value *expr, llvm::BasicBlock *defaultBlock, const std::vector< std::pair< int, llvm::BasicBlock *>> &caseBlocks, const std::map< llvm::BasicBlock *, llvm::BasicBlock *> &nextBlocks)
Definition: ctx.cpp:949
bool foundVaryingBreakOrContinue
Definition: stmt.cpp:692
llvm::Value * GetStringPtr(const std::string &str)
Definition: ctx.cpp:1220
Expr * testExpr
Definition: stmt.h:171
void EmitCode(FunctionEmitContext *ctx) const
Definition: stmt.cpp:1757
SwitchStmt(Expr *expr, Stmt *stmts, SourcePos pos)
Definition: stmt.cpp:2192
static const AtomicType * UniformUInt8
Definition: type.h:326
void DisableGatherScatterWarnings()
Definition: ctx.cpp:1011
const Type * GetElementType(const std::string &name) const
Definition: type.cpp:1881
static llvm::Type * Int32Type
Definition: llvmutil.h:67
int EstimateCost() const
Definition: stmt.cpp:2843
void SetDebugPos(SourcePos pos)
Definition: ctx.cpp:1288
virtual const Type * GetAsUniformType() const =0
#define ISPC_MAX_NVEC
Definition: ispc.h:69
bool disableUniformControlFlow
Definition: ispc.h:459
Representation of a function in a source file.
Stmt * falseStmts
Definition: stmt.h:139
Stmt * TypeCheck()
Definition: stmt.cpp:2101
int first_column
Definition: ispc.h:128
void emitVaryingIf(FunctionEmitContext *ctx, llvm::Value *test) const
Definition: stmt.cpp:500
Expr * test
Definition: stmt.h:197
#define Assert(expr)
Definition: util.h:128
Stmt * init
Definition: stmt.h:194
static bool Equal(const Type *a, const Type *b)
Definition: type.cpp:2853
static bool lVaryingBCPreFunc(ASTNode *node, void *d)
Definition: stmt.cpp:708
Stmt * stmts
Definition: stmt.h:258
void EmitCode(FunctionEmitContext *ctx) const
Definition: stmt.cpp:1238
Definition: stmt.h:340
std::vector< Expr * > exprs
Definition: expr.h:266
llvm::BasicBlock * defaultBlock
Definition: stmt.cpp:2211
std::vector< Expr * > startExprs
Definition: stmt.h:255
static const AtomicType * UniformFloat
Definition: type.h:329
llvm::Value * GetInternalMask()
Definition: ctx.cpp:365
void EmitCode(FunctionEmitContext *ctx) const
Definition: stmt.cpp:1125
llvm::Value * BitCastInst(llvm::Value *value, llvm::Type *type, const char *name=NULL)
Definition: ctx.cpp:1518
static const AtomicType * UniformInt32
Definition: type.h:325
Symbol * sym
Definition: stmt.h:276
void SetInternalMaskAndNot(llvm::Value *oldMask, llvm::Value *test)
Definition: ctx.cpp:392
llvm::Constant * LLVMFalse
Definition: llvmutil.cpp:91
SourcePos identifierPos
Definition: stmt.h:413
void Print(int indent) const
Definition: stmt.cpp:2458
Representation of a program symbol.
Definition: sym.h:62
void EmitCode(FunctionEmitContext *ctx) const
Definition: stmt.cpp:758
Stmt * stmt
Definition: stmt.h:435
int varyingCFDepth
Definition: sym.h:96
void EndForeach()
Definition: ctx.cpp:556
int EstimateCost() const
Definition: stmt.cpp:1135
void Print(int indent) const
Definition: stmt.cpp:2398
void EnableGatherScatterWarnings()
Definition: ctx.cpp:1013
Stmt * TypeCheck()
Definition: stmt.cpp:2411
virtual bool IsConstType() const =0
Interface class that defines the type abstraction.
Definition: type.h:90
static const AtomicType * UniformDouble
Definition: type.h:332
Globals * g
Definition: ispc.cpp:72
int EstimateCost() const
Definition: stmt.cpp:1112
Expr abstract base class and expression implementations.
void SetCurrentBasicBlock(llvm::BasicBlock *bblock)
Definition: ctx.cpp:361
virtual const Type * GetAsConstType() const =0
static llvm::VectorType * MaskType
Definition: llvmutil.h:79
ForeachStmt(const std::vector< Symbol *> &loopVars, const std::vector< Expr *> &startExprs, const std::vector< Expr *> &endExprs, Stmt *bodyStatements, bool tiled, SourcePos pos)
Definition: stmt.cpp:1146
void EmitDefaultLabel(bool checkMask, SourcePos pos)
Definition: ctx.cpp:843
void Debug(SourcePos p, const char *fmt,...)
Definition: util.cpp:366
Expr * expr
Definition: stmt.h:86
Stmt * stmts
Definition: stmt.h:316
Stmt * Optimize()
Definition: stmt.cpp:235
DefaultStmt(Stmt *stmt, SourcePos pos)
Definition: stmt.cpp:2170
void EmitCode(FunctionEmitContext *ctx) const
Definition: stmt.cpp:1102
int EstimateCost() const
Definition: stmt.cpp:2125
Statement representing a single if statement, possibly with an else clause.
Definition: stmt.h:119
int GetElementCount() const
Definition: type.cpp:1183
void EmitCode(FunctionEmitContext *ctx) const
Definition: stmt.cpp:2150
Expr is the abstract base class that defines the interface that all expression types must implement...
Definition: expr.h:47
Expr * expr
Definition: stmt.h:533
virtual Stmt * Optimize()
Definition: stmt.cpp:64
std::vector< Symbol * > dimVariables
Definition: stmt.h:254
llvm::Value * IntToPtrInst(llvm::Value *value, llvm::Type *type, const char *name=NULL)
Definition: ctx.cpp:1578
const Function * parentFunction
Definition: sym.h:102
UnmaskedStmt(Stmt *stmt, SourcePos pos)
Definition: stmt.cpp:2375
void emitMaskMixed(FunctionEmitContext *ctx, llvm::Value *oldMask, llvm::Value *test, llvm::BasicBlock *bDone) const
Definition: stmt.cpp:638
llvm::Value * All(llvm::Value *mask)
Definition: ctx.cpp:1138
std::string name
Definition: stmt.h:433
virtual void Print(int indent) const =0
llvm::ConstantInt * LLVMInt64(int64_t ival)
Definition: llvmutil.cpp:241
Expression that represents dereferencing a reference to get its value.
Definition: expr.h:572
static const Type * SizeUnsizedArrays(const Type *type, Expr *initExpr)
Definition: type.cpp:1288
void EmitCode(FunctionEmitContext *ctx) const
Definition: stmt.cpp:2850
Stmt * TypeCheck()
Definition: stmt.cpp:296
llvm::Value * SmearUniform(llvm::Value *value, const char *name=NULL)
Definition: ctx.cpp:1481
Expr * expr
Definition: stmt.h:297
std::string label
Definition: stmt.h:412
const Type * GetReturnType() const
Definition: func.cpp:148
PrintStmt(const std::string &f, Expr *v, SourcePos p)
Definition: stmt.cpp:2599
bool is32Bit() const
Definition: ispc.h:235
int EstimateCost() const
Definition: stmt.cpp:1067
int EstimateCost() const
Definition: stmt.cpp:2585
Declaration of the Module class, which is the ispc-side representation of the results of compiling a ...
static const AtomicType * UniformInt64
Definition: type.h:330
int errorCount
Definition: module.h:144
llvm::LLVMContext * ctx
Definition: ispc.h:611
void Print(int indent) const
Definition: stmt.cpp:1708
static const AtomicType * UniformInt16
Definition: type.h:324
const Type * type
Definition: sym.h:82
void EmitCode(FunctionEmitContext *ctx) const
Definition: stmt.cpp:2420
static llvm::Value * lProcessPrintArg(Expr *expr, FunctionEmitContext *ctx, std::string &argTypes)
Definition: stmt.cpp:2650
int varyingControlFlowDepth
Definition: stmt.cpp:691
void Warning(SourcePos p, const char *fmt,...)
Definition: util.cpp:378
static bool EqualIgnoringConst(const Type *a, const Type *b)
Definition: type.cpp:2855
Stmt * TypeCheck()
Definition: stmt.cpp:440
DeleteStmt(Expr *e, SourcePos p)
Definition: stmt.cpp:2848
const bool doAllCheck
Definition: stmt.h:146
static const AtomicType * VaryingUInt32
Definition: type.h:328
llvm::Value * BinaryOperator(llvm::Instruction::BinaryOps inst, llvm::Value *v0, llvm::Value *v1, const char *name=NULL)
Definition: ctx.cpp:1383
llvm::BasicBlock * GetLabeledBasicBlock(const std::string &label)
Definition: ctx.cpp:1036
void SetFunctionMask(llvm::Value *val)
Definition: ctx.cpp:373
static const AtomicType * VaryingFloat
Definition: type.h:329
SymbolTable * symbolTable
Definition: module.h:148
static const AtomicType * UniformInt8
Definition: type.h:323
File with declarations for classes related to type representation.
Stmt * TypeCheck()
Definition: stmt.cpp:2831
llvm::Value * I1VecToBoolVec(llvm::Value *b)
Definition: ctx.cpp:1232
std::map< llvm::BasicBlock *, llvm::BasicBlock * > nextBlock
Definition: stmt.cpp:2220
One-dimensional array type.
Definition: type.h:521