Halide  12.0.1
Halide compiler and libraries
Func.h
Go to the documentation of this file.
1 #ifndef HALIDE_FUNC_H
2 #define HALIDE_FUNC_H
3 
4 /** \file
5  *
6  * Defines Func - the front-end handle on a halide function, and related classes.
7  */
8 
9 #include "Argument.h"
10 #include "Expr.h"
11 #include "JITModule.h"
12 #include "Module.h"
13 #include "Param.h"
14 #include "Pipeline.h"
15 #include "RDom.h"
16 #include "Target.h"
17 #include "Tuple.h"
18 #include "Var.h"
19 
20 #include <map>
21 #include <utility>
22 
23 namespace Halide {
24 
25 class OutputImageParam;
26 class ParamMap;
27 
28 /** A class that can represent Vars or RVars. Used for reorder calls
29  * which can accept a mix of either. */
30 struct VarOrRVar {
31  VarOrRVar(const std::string &n, bool r)
32  : var(n), rvar(n), is_rvar(r) {
33  }
34  VarOrRVar(const Var &v)
35  : var(v), is_rvar(false) {
36  }
37  VarOrRVar(const RVar &r)
38  : rvar(r), is_rvar(true) {
39  }
40  VarOrRVar(const RDom &r)
41  : rvar(RVar(r)), is_rvar(true) {
42  }
43  template<int N>
45  : var(u), is_rvar(false) {
46  }
47 
48  const std::string &name() const {
49  if (is_rvar) {
50  return rvar.name();
51  } else {
52  return var.name();
53  }
54  }
55 
58  bool is_rvar;
59 };
60 
61 class ImageParam;
62 
63 namespace Internal {
64 class Function;
65 struct Split;
66 struct StorageDim;
67 } // namespace Internal
68 
69 /** A single definition of a Func. May be a pure or update definition. */
70 class Stage {
71  /** Reference to the Function this stage (or definition) belongs to. */
72  Internal::Function function;
73  Internal::Definition definition;
74  /** Indicate which stage the definition belongs to (0 for initial
75  * definition, 1 for first update, etc.). */
76  size_t stage_index;
77  /** Pure Vars of the Function (from the init definition). */
78  std::vector<Var> dim_vars;
79 
80  void set_dim_type(const VarOrRVar &var, Internal::ForType t);
81  void set_dim_device_api(const VarOrRVar &var, DeviceAPI device_api);
82  void split(const std::string &old, const std::string &outer, const std::string &inner,
83  const Expr &factor, bool exact, TailStrategy tail);
84  void remove(const std::string &var);
85  Stage &purify(const VarOrRVar &old_name, const VarOrRVar &new_name);
86 
87  const std::vector<Internal::StorageDim> &storage_dims() const {
88  return function.schedule().storage_dims();
89  }
90 
91  Stage &compute_with(LoopLevel loop_level, const std::map<std::string, LoopAlignStrategy> &align);
92 
93 public:
94  Stage(Internal::Function f, Internal::Definition d, size_t stage_index)
95  : function(std::move(f)), definition(std::move(d)), stage_index(stage_index) {
96  internal_assert(definition.defined());
97  definition.schedule().touched() = true;
98 
99  dim_vars.reserve(function.args().size());
100  for (const auto &arg : function.args()) {
101  dim_vars.emplace_back(arg);
102  }
103  internal_assert(definition.args().size() == dim_vars.size());
104  }
105 
106  /** Return the current StageSchedule associated with this Stage. For
107  * introspection only: to modify schedule, use the Func interface. */
109  return definition.schedule();
110  }
111 
112  /** Return a string describing the current var list taking into
113  * account all the splits, reorders, and tiles. */
114  std::string dump_argument_list() const;
115 
116  /** Return the name of this stage, e.g. "f.update(2)" */
117  std::string name() const;
118 
119  /** Calling rfactor() on an associative update definition a Func will split
120  * the update into an intermediate which computes the partial results and
121  * replaces the current update definition with a new definition which merges
122  * the partial results. If called on a init/pure definition, this will
123  * throw an error. rfactor() will automatically infer the associative reduction
124  * operator and identity of the operator. If it can't prove the operation
125  * is associative or if it cannot find an identity for that operator, this
126  * will throw an error. In addition, commutativity of the operator is required
127  * if rfactor() is called on the inner dimension but excluding the outer
128  * dimensions.
129  *
130  * rfactor() takes as input 'preserved', which is a list of <RVar, Var> pairs.
131  * The rvars not listed in 'preserved' are removed from the original Func and
132  * are lifted to the intermediate Func. The remaining rvars (the ones in
133  * 'preserved') are made pure in the intermediate Func. The intermediate Func's
134  * update definition inherits all scheduling directives (e.g. split,fuse, etc.)
135  * applied to the original Func's update definition. The loop order of the
136  * intermediate Func's update definition is the same as the original, although
137  * the RVars in 'preserved' are replaced by the new pure Vars. The loop order of the
138  * intermediate Func's init definition from innermost to outermost is the args'
139  * order of the original Func's init definition followed by the new pure Vars.
140  *
141  * The intermediate Func also inherits storage order from the original Func
142  * with the new pure Vars added to the outermost.
143  *
144  * For example, f.update(0).rfactor({{r.y, u}}) would rewrite a pipeline like this:
145  \code
146  f(x, y) = 0;
147  f(x, y) += g(r.x, r.y);
148  \endcode
149  * into a pipeline like this:
150  \code
151  f_intm(x, y, u) = 0;
152  f_intm(x, y, u) += g(r.x, u);
153 
154  f(x, y) = 0;
155  f(x, y) += f_intm(x, y, r.y);
156  \endcode
157  *
158  * This has a variety of uses. You can use it to split computation of an associative reduction:
159  \code
160  f(x, y) = 10;
161  RDom r(0, 96);
162  f(x, y) = max(f(x, y), g(x, y, r.x));
163  f.update(0).split(r.x, rxo, rxi, 8).reorder(y, x).parallel(x);
164  f.update(0).rfactor({{rxo, u}}).compute_root().parallel(u).update(0).parallel(u);
165  \endcode
166  *
167  *, which is equivalent to:
168  \code
169  parallel for u = 0 to 11:
170  for y:
171  for x:
172  f_intm(x, y, u) = -inf
173  parallel for x:
174  for y:
175  parallel for u = 0 to 11:
176  for rxi = 0 to 7:
177  f_intm(x, y, u) = max(f_intm(x, y, u), g(8*u + rxi))
178  for y:
179  for x:
180  f(x, y) = 10
181  parallel for x:
182  for y:
183  for rxo = 0 to 11:
184  f(x, y) = max(f(x, y), f_intm(x, y, rxo))
185  \endcode
186  *
187  */
188  // @{
189  Func rfactor(std::vector<std::pair<RVar, Var>> preserved);
190  Func rfactor(const RVar &r, const Var &v);
191  // @}
192 
193  /** Schedule the iteration over this stage to be fused with another
194  * stage 's' from outermost loop to a given LoopLevel. 'this' stage will
195  * be computed AFTER 's' in the innermost fused dimension. There should not
196  * be any dependencies between those two fused stages. If either of the
197  * stages being fused is a stage of an extern Func, this will throw an error.
198  *
199  * Note that the two stages that are fused together should have the same
200  * exact schedule from the outermost to the innermost fused dimension, and
201  * the stage we are calling compute_with on should not have specializations,
202  * e.g. f2.compute_with(f1, x) is allowed only if f2 has no specializations.
203  *
204  * Also, if a producer is desired to be computed at the fused loop level,
205  * the function passed to the compute_at() needs to be the "parent". Consider
206  * the following code:
207  \code
208  input(x, y) = x + y;
209  f(x, y) = input(x, y);
210  f(x, y) += 5;
211  g(x, y) = x - y;
212  g(x, y) += 10;
213  f.compute_with(g, y);
214  f.update().compute_with(g.update(), y);
215  \endcode
216  *
217  * To compute 'input' at the fused loop level at dimension y, we specify
218  * input.compute_at(g, y) instead of input.compute_at(f, y) since 'g' is
219  * the "parent" for this fused loop (i.e. 'g' is computed first before 'f'
220  * is computed). On the other hand, to compute 'input' at the innermost
221  * dimension of 'f', we specify input.compute_at(f, x) instead of
222  * input.compute_at(g, x) since the x dimension of 'f' is not fused
223  * (only the y dimension is).
224  *
225  * Given the constraints, this has a variety of uses. Consider the
226  * following code:
227  \code
228  f(x, y) = x + y;
229  g(x, y) = x - y;
230  h(x, y) = f(x, y) + g(x, y);
231  f.compute_root();
232  g.compute_root();
233  f.split(x, xo, xi, 8);
234  g.split(x, xo, xi, 8);
235  g.compute_with(f, xo);
236  \endcode
237  *
238  * This is equivalent to:
239  \code
240  for y:
241  for xo:
242  for xi:
243  f(8*xo + xi) = (8*xo + xi) + y
244  for xi:
245  g(8*xo + xi) = (8*xo + xi) - y
246  for y:
247  for x:
248  h(x, y) = f(x, y) + g(x, y)
249  \endcode
250  *
251  * The size of the dimensions of the stages computed_with do not have
252  * to match. Consider the following code where 'g' is half the size of 'f':
253  \code
254  Image<int> f_im(size, size), g_im(size/2, size/2);
255  input(x, y) = x + y;
256  f(x, y) = input(x, y);
257  g(x, y) = input(2*x, 2*y);
258  g.compute_with(f, y);
259  input.compute_at(f, y);
260  Pipeline({f, g}).realize({f_im, g_im});
261  \endcode
262  *
263  * This is equivalent to:
264  \code
265  for y = 0 to size-1:
266  for x = 0 to size-1:
267  input(x, y) = x + y;
268  for x = 0 to size-1:
269  f(x, y) = input(x, y)
270  for x = 0 to size/2-1:
271  if (y < size/2-1):
272  g(x, y) = input(2*x, 2*y)
273  \endcode
274  *
275  * 'align' specifies how the loop iteration of each dimension of the
276  * two stages being fused should be aligned in the fused loop nests
277  * (see LoopAlignStrategy for options). Consider the following loop nests:
278  \code
279  for z = f_min_z to f_max_z:
280  for y = f_min_y to f_max_y:
281  for x = f_min_x to f_max_x:
282  f(x, y, z) = x + y + z
283  for z = g_min_z to g_max_z:
284  for y = g_min_y to g_max_y:
285  for x = g_min_x to g_max_x:
286  g(x, y, z) = x - y - z
287  \endcode
288  *
289  * If no alignment strategy is specified, the following loop nest will be
290  * generated:
291  \code
292  for z = min(f_min_z, g_min_z) to max(f_max_z, g_max_z):
293  for y = min(f_min_y, g_min_y) to max(f_max_y, g_max_y):
294  for x = f_min_x to f_max_x:
295  if (f_min_z <= z <= f_max_z):
296  if (f_min_y <= y <= f_max_y):
297  f(x, y, z) = x + y + z
298  for x = g_min_x to g_max_x:
299  if (g_min_z <= z <= g_max_z):
300  if (g_min_y <= y <= g_max_y):
301  g(x, y, z) = x - y - z
302  \endcode
303  *
304  * Instead, these alignment strategies:
305  \code
306  g.compute_with(f, y, {{z, LoopAlignStrategy::AlignStart}, {y, LoopAlignStrategy::AlignEnd}});
307  \endcode
308  * will produce the following loop nest:
309  \code
310  f_loop_min_z = f_min_z
311  f_loop_max_z = max(f_max_z, (f_min_z - g_min_z) + g_max_z)
312  for z = f_min_z to f_loop_max_z:
313  f_loop_min_y = min(f_min_y, (f_max_y - g_max_y) + g_min_y)
314  f_loop_max_y = f_max_y
315  for y = f_loop_min_y to f_loop_max_y:
316  for x = f_min_x to f_max_x:
317  if (f_loop_min_z <= z <= f_loop_max_z):
318  if (f_loop_min_y <= y <= f_loop_max_y):
319  f(x, y, z) = x + y + z
320  for x = g_min_x to g_max_x:
321  g_shift_z = g_min_z - f_loop_min_z
322  g_shift_y = g_max_y - f_loop_max_y
323  if (g_min_z <= (z + g_shift_z) <= g_max_z):
324  if (g_min_y <= (y + g_shift_y) <= g_max_y):
325  g(x, y + g_shift_y, z + g_shift_z) = x - (y + g_shift_y) - (z + g_shift_z)
326  \endcode
327  *
328  * LoopAlignStrategy::AlignStart on dimension z will shift the loop iteration
329  * of 'g' at dimension z so that its starting value matches that of 'f'.
330  * Likewise, LoopAlignStrategy::AlignEnd on dimension y will shift the loop
331  * iteration of 'g' at dimension y so that its end value matches that of 'f'.
332  */
333  // @{
334  Stage &compute_with(LoopLevel loop_level, const std::vector<std::pair<VarOrRVar, LoopAlignStrategy>> &align);
336  Stage &compute_with(const Stage &s, const VarOrRVar &var, const std::vector<std::pair<VarOrRVar, LoopAlignStrategy>> &align);
338  // @}
339 
340  /** Scheduling calls that control how the domain of this stage is
341  * traversed. See the documentation for Func for the meanings. */
342  // @{
343 
344  Stage &split(const VarOrRVar &old, const VarOrRVar &outer, const VarOrRVar &inner, const Expr &factor, TailStrategy tail = TailStrategy::Auto);
345  Stage &fuse(const VarOrRVar &inner, const VarOrRVar &outer, const VarOrRVar &fused);
346  Stage &serial(const VarOrRVar &var);
347  Stage &parallel(const VarOrRVar &var);
348  Stage &vectorize(const VarOrRVar &var);
349  Stage &unroll(const VarOrRVar &var);
350  Stage &parallel(const VarOrRVar &var, const Expr &task_size, TailStrategy tail = TailStrategy::Auto);
351  Stage &vectorize(const VarOrRVar &var, const Expr &factor, TailStrategy tail = TailStrategy::Auto);
352  Stage &unroll(const VarOrRVar &var, const Expr &factor, TailStrategy tail = TailStrategy::Auto);
353  Stage &tile(const VarOrRVar &x, const VarOrRVar &y,
354  const VarOrRVar &xo, const VarOrRVar &yo,
355  const VarOrRVar &xi, const VarOrRVar &yi, const Expr &xfactor, const Expr &yfactor,
357  Stage &tile(const VarOrRVar &x, const VarOrRVar &y,
358  const VarOrRVar &xi, const VarOrRVar &yi,
359  const Expr &xfactor, const Expr &yfactor,
361  Stage &tile(const std::vector<VarOrRVar> &previous,
362  const std::vector<VarOrRVar> &outers,
363  const std::vector<VarOrRVar> &inners,
364  const std::vector<Expr> &factors,
365  const std::vector<TailStrategy> &tails);
366  Stage &tile(const std::vector<VarOrRVar> &previous,
367  const std::vector<VarOrRVar> &outers,
368  const std::vector<VarOrRVar> &inners,
369  const std::vector<Expr> &factors,
371  Stage &tile(const std::vector<VarOrRVar> &previous,
372  const std::vector<VarOrRVar> &inners,
373  const std::vector<Expr> &factors,
375  Stage &reorder(const std::vector<VarOrRVar> &vars);
376 
377  template<typename... Args>
378  HALIDE_NO_USER_CODE_INLINE typename std::enable_if<Internal::all_are_convertible<VarOrRVar, Args...>::value, Stage &>::type
379  reorder(const VarOrRVar &x, const VarOrRVar &y, Args &&...args) {
380  std::vector<VarOrRVar> collected_args{x, y, std::forward<Args>(args)...};
381  return reorder(collected_args);
382  }
383 
384  Stage &rename(const VarOrRVar &old_name, const VarOrRVar &new_name);
385  Stage specialize(const Expr &condition);
386  void specialize_fail(const std::string &message);
387 
388  Stage &gpu_threads(const VarOrRVar &thread_x, DeviceAPI device_api = DeviceAPI::Default_GPU);
389  Stage &gpu_threads(const VarOrRVar &thread_x, const VarOrRVar &thread_y, DeviceAPI device_api = DeviceAPI::Default_GPU);
390  Stage &gpu_threads(const VarOrRVar &thread_x, const VarOrRVar &thread_y, const VarOrRVar &thread_z, DeviceAPI device_api = DeviceAPI::Default_GPU);
391 
392  Stage &gpu_lanes(const VarOrRVar &thread_x, DeviceAPI device_api = DeviceAPI::Default_GPU);
393 
395 
397  Stage &gpu_blocks(const VarOrRVar &block_x, const VarOrRVar &block_y, DeviceAPI device_api = DeviceAPI::Default_GPU);
398  Stage &gpu_blocks(const VarOrRVar &block_x, const VarOrRVar &block_y, const VarOrRVar &block_z, DeviceAPI device_api = DeviceAPI::Default_GPU);
399 
400  Stage &gpu(const VarOrRVar &block_x, const VarOrRVar &thread_x, DeviceAPI device_api = DeviceAPI::Default_GPU);
401  Stage &gpu(const VarOrRVar &block_x, const VarOrRVar &block_y,
402  const VarOrRVar &thread_x, const VarOrRVar &thread_y,
403  DeviceAPI device_api = DeviceAPI::Default_GPU);
404  Stage &gpu(const VarOrRVar &block_x, const VarOrRVar &block_y, const VarOrRVar &block_z,
405  const VarOrRVar &thread_x, const VarOrRVar &thread_y, const VarOrRVar &thread_z,
406  DeviceAPI device_api = DeviceAPI::Default_GPU);
407 
408  Stage &gpu_tile(const VarOrRVar &x, const VarOrRVar &bx, const VarOrRVar &tx, const Expr &x_size,
410  DeviceAPI device_api = DeviceAPI::Default_GPU);
411 
412  Stage &gpu_tile(const VarOrRVar &x, const VarOrRVar &tx, const Expr &x_size,
414  DeviceAPI device_api = DeviceAPI::Default_GPU);
415  Stage &gpu_tile(const VarOrRVar &x, const VarOrRVar &y,
416  const VarOrRVar &bx, const VarOrRVar &by,
417  const VarOrRVar &tx, const VarOrRVar &ty,
418  const Expr &x_size, const Expr &y_size,
420  DeviceAPI device_api = DeviceAPI::Default_GPU);
421 
422  Stage &gpu_tile(const VarOrRVar &x, const VarOrRVar &y,
423  const VarOrRVar &tx, const VarOrRVar &ty,
424  const Expr &x_size, const Expr &y_size,
426  DeviceAPI device_api = DeviceAPI::Default_GPU);
427 
428  Stage &gpu_tile(const VarOrRVar &x, const VarOrRVar &y, const VarOrRVar &z,
429  const VarOrRVar &bx, const VarOrRVar &by, const VarOrRVar &bz,
430  const VarOrRVar &tx, const VarOrRVar &ty, const VarOrRVar &tz,
431  const Expr &x_size, const Expr &y_size, const Expr &z_size,
433  DeviceAPI device_api = DeviceAPI::Default_GPU);
434  Stage &gpu_tile(const VarOrRVar &x, const VarOrRVar &y, const VarOrRVar &z,
435  const VarOrRVar &tx, const VarOrRVar &ty, const VarOrRVar &tz,
436  const Expr &x_size, const Expr &y_size, const Expr &z_size,
438  DeviceAPI device_api = DeviceAPI::Default_GPU);
439 
441  Stage &atomic(bool override_associativity_test = false);
442 
444  Stage &prefetch(const Func &f, const VarOrRVar &var, Expr offset = 1,
446  Stage &prefetch(const Internal::Parameter &param, const VarOrRVar &var, Expr offset = 1,
448  template<typename T>
449  Stage &prefetch(const T &image, VarOrRVar var, Expr offset = 1,
451  return prefetch(image.parameter(), var, offset, strategy);
452  }
453  // @}
454 
455  /** Attempt to get the source file and line where this stage was
456  * defined by parsing the process's own debug symbols. Returns an
457  * empty string if no debug symbols were found or the debug
458  * symbols were not understood. Works on OS X and Linux only. */
459  std::string source_location() const;
460 };
461 
462 // For backwards compatibility, keep the ScheduleHandle name.
464 
465 class FuncTupleElementRef;
466 
467 /** A fragment of front-end syntax of the form f(x, y, z), where x, y,
468  * z are Vars or Exprs. If could be the left hand side of a definition or
469  * an update definition, or it could be a call to a function. We don't know
470  * until we see how this object gets used.
471  */
472 class FuncRef {
473  Internal::Function func;
474  int implicit_placeholder_pos;
475  int implicit_count;
476  std::vector<Expr> args;
477  std::vector<Expr> args_with_implicit_vars(const std::vector<Expr> &e) const;
478 
479  /** Helper for function update by Tuple. If the function does not
480  * already have a pure definition, init_val will be used as RHS of
481  * each tuple element in the initial function definition. */
482  template<typename BinaryOp>
483  Stage func_ref_update(const Tuple &e, int init_val);
484 
485  /** Helper for function update by Expr. If the function does not
486  * already have a pure definition, init_val will be used as RHS in
487  * the initial function definition. */
488  template<typename BinaryOp>
489  Stage func_ref_update(Expr e, int init_val);
490 
491 public:
492  FuncRef(const Internal::Function &, const std::vector<Expr> &,
493  int placeholder_pos = -1, int count = 0);
494  FuncRef(Internal::Function, const std::vector<Var> &,
495  int placeholder_pos = -1, int count = 0);
496 
497  /** Use this as the left-hand-side of a definition or an update definition
498  * (see \ref RDom).
499  */
500  Stage operator=(const Expr &);
501 
502  /** Use this as the left-hand-side of a definition or an update definition
503  * for a Func with multiple outputs. */
505 
506  /** Define a stage that adds the given expression to this Func. If the
507  * expression refers to some RDom, this performs a sum reduction of the
508  * expression over the domain. If the function does not already have a
509  * pure definition, this sets it to zero.
510  */
511  // @{
515  // @}
516 
517  /** Define a stage that adds the negative of the given expression to this
518  * Func. If the expression refers to some RDom, this performs a sum reduction
519  * of the negative of the expression over the domain. If the function does
520  * not already have a pure definition, this sets it to zero.
521  */
522  // @{
526  // @}
527 
528  /** Define a stage that multiplies this Func by the given expression. If the
529  * expression refers to some RDom, this performs a product reduction of the
530  * expression over the domain. If the function does not already have a pure
531  * definition, this sets it to 1.
532  */
533  // @{
537  // @}
538 
539  /** Define a stage that divides this Func by the given expression.
540  * If the expression refers to some RDom, this performs a product
541  * reduction of the inverse of the expression over the domain. If the
542  * function does not already have a pure definition, this sets it to 1.
543  */
544  // @{
548  // @}
549 
550  /* Override the usual assignment operator, so that
551  * f(x, y) = g(x, y) defines f.
552  */
554 
555  /** Use this as a call to the function, and not the left-hand-side
556  * of a definition. Only works for single-output Funcs. */
557  operator Expr() const;
558 
559  /** When a FuncRef refers to a function that provides multiple
560  * outputs, you can access each output as an Expr using
561  * operator[].
562  */
564 
565  /** How many outputs does the function this refers to produce. */
566  size_t size() const;
567 
568  /** What function is this calling? */
569  Internal::Function function() const {
570  return func;
571  }
572 };
573 
574 /** Explicit overloads of min and max for FuncRef. These exist to
575  * disambiguate calls to min on FuncRefs when a user has pulled both
576  * Halide::min and std::min into their namespace. */
577 // @{
578 inline Expr min(const FuncRef &a, const FuncRef &b) {
579  return min(Expr(a), Expr(b));
580 }
581 inline Expr max(const FuncRef &a, const FuncRef &b) {
582  return max(Expr(a), Expr(b));
583 }
584 // @}
585 
586 /** A fragment of front-end syntax of the form f(x, y, z)[index], where x, y,
587  * z are Vars or Exprs. If could be the left hand side of an update
588  * definition, or it could be a call to a function. We don't know
589  * until we see how this object gets used.
590  */
592  FuncRef func_ref;
593  std::vector<Expr> args; // args to the function
594  int idx; // Index to function outputs
595 
596  /** Helper function that generates a Tuple where element at 'idx' is set
597  * to 'e' and the rests are undef. */
598  Tuple values_with_undefs(const Expr &e) const;
599 
600 public:
601  FuncTupleElementRef(const FuncRef &ref, const std::vector<Expr> &args, int idx);
602 
603  /** Use this as the left-hand-side of an update definition of Tuple
604  * component 'idx' of a Func (see \ref RDom). The function must
605  * already have an initial definition.
606  */
607  Stage operator=(const Expr &e);
608 
609  /** Define a stage that adds the given expression to Tuple component 'idx'
610  * of this Func. The other Tuple components are unchanged. If the expression
611  * refers to some RDom, this performs a sum reduction of the expression over
612  * the domain. The function must already have an initial definition.
613  */
614  Stage operator+=(const Expr &e);
615 
616  /** Define a stage that adds the negative of the given expression to Tuple
617  * component 'idx' of this Func. The other Tuple components are unchanged.
618  * If the expression refers to some RDom, this performs a sum reduction of
619  * the negative of the expression over the domain. The function must already
620  * have an initial definition.
621  */
622  Stage operator-=(const Expr &e);
623 
624  /** Define a stage that multiplies Tuple component 'idx' of this Func by
625  * the given expression. The other Tuple components are unchanged. If the
626  * expression refers to some RDom, this performs a product reduction of
627  * the expression over the domain. The function must already have an
628  * initial definition.
629  */
630  Stage operator*=(const Expr &e);
631 
632  /** Define a stage that divides Tuple component 'idx' of this Func by
633  * the given expression. The other Tuple components are unchanged.
634  * If the expression refers to some RDom, this performs a product
635  * reduction of the inverse of the expression over the domain. The function
636  * must already have an initial definition.
637  */
638  Stage operator/=(const Expr &e);
639 
640  /* Override the usual assignment operator, so that
641  * f(x, y)[index] = g(x, y) defines f.
642  */
644 
645  /** Use this as a call to Tuple component 'idx' of a Func, and not the
646  * left-hand-side of a definition. */
647  operator Expr() const;
648 
649  /** What function is this calling? */
650  Internal::Function function() const {
651  return func_ref.function();
652  }
653 
654  /** Return index to the function outputs. */
655  int index() const {
656  return idx;
657  }
658 };
659 
660 namespace Internal {
661 class IRMutator;
662 } // namespace Internal
663 
664 /** Helper class for identifying purpose of an Expr passed to memoize.
665  */
666 class EvictionKey {
667 protected:
669  friend class Func;
670 
671 public:
672  explicit EvictionKey(const Expr &expr = Expr())
673  : key(expr) {
674  }
675 };
676 
677 /** A halide function. This class represents one stage in a Halide
678  * pipeline, and is the unit by which we schedule things. By default
679  * they are aggressively inlined, so you are encouraged to make lots
680  * of little functions, rather than storing things in Exprs. */
681 class Func {
682 
683  /** A handle on the internal halide function that this
684  * represents */
685  Internal::Function func;
686 
687  /** When you make a reference to this function with fewer
688  * arguments than it has dimensions, the argument list is bulked
689  * up with 'implicit' vars with canonical names. This lets you
690  * pass around partially applied Halide functions. */
691  // @{
692  std::pair<int, int> add_implicit_vars(std::vector<Var> &) const;
693  std::pair<int, int> add_implicit_vars(std::vector<Expr> &) const;
694  // @}
695 
696  /** The imaging pipeline that outputs this Func alone. */
697  Pipeline pipeline_;
698 
699  /** Get the imaging pipeline that outputs this Func alone,
700  * creating it (and freezing the Func) if necessary. */
701  Pipeline pipeline();
702 
703  // Helper function for recursive reordering support
704  Func &reorder_storage(const std::vector<Var> &dims, size_t start);
705 
706  void invalidate_cache();
707 
708 public:
709  /** Declare a new undefined function with the given name */
710  explicit Func(const std::string &name);
711 
712  /** Declare a new undefined function with an
713  * automatically-generated unique name */
714  Func();
715 
716  /** Declare a new function with an automatically-generated unique
717  * name, and define it to return the given expression (which may
718  * not contain free variables). */
719  explicit Func(const Expr &e);
720 
721  /** Construct a new Func to wrap an existing, already-define
722  * Function object. */
724 
725  /** Construct a new Func to wrap a Buffer. */
726  template<typename T>
728  : Func() {
729  (*this)(_) = im(_);
730  }
731 
732  /** Evaluate this function over some rectangular domain and return
733  * the resulting buffer or buffers. Performs compilation if the
734  * Func has not previously been realized and compile_jit has not
735  * been called. If the final stage of the pipeline is on the GPU,
736  * data is copied back to the host before being returned. The
737  * returned Realization should probably be instantly converted to
738  * a Buffer class of the appropriate type. That is, do this:
739  *
740  \code
741  f(x) = sin(x);
742  Buffer<float> im = f.realize(...);
743  \endcode
744  *
745  * If your Func has multiple values, because you defined it using
746  * a Tuple, then casting the result of a realize call to a buffer
747  * or image will produce a run-time error. Instead you should do the
748  * following:
749  *
750  \code
751  f(x) = Tuple(x, sin(x));
752  Realization r = f.realize(...);
753  Buffer<int> im0 = r[0];
754  Buffer<float> im1 = r[1];
755  \endcode
756  *
757  * In Halide formal arguments of a computation are specified using
758  * Param<T> and ImageParam objects in the expressions defining the
759  * computation. The param_map argument to realize allows
760  * specifying a set of per-call parameters to be used for a
761  * specific computation. This method is thread-safe where the
762  * globals used by Param<T> and ImageParam are not. Any parameters
763  * that are not in the param_map are taken from the global values,
764  * so those can continue to be used if they are not changing
765  * per-thread.
766  *
767  * One can explicitly construct a ParamMap and
768  * use its set method to insert Parameter to scalar or Buffer
769  * value mappings:
770  *
771  \code
772  Param<int32> p(42);
773  ImageParam img(Int(32), 1);
774  f(x) = img(x) + p;
775 
776  Buffer<int32_t) arg_img(10, 10);
777  <fill in arg_img...>
778  ParamMap params;
779  params.set(p, 17);
780  params.set(img, arg_img);
781 
782  Target t = get_jit_target_from_environment();
783  Buffer<int32_t> result = f.realize({10, 10}, t, params);
784  \endcode
785  *
786  * Alternatively, an initializer list can be used
787  * directly in the realize call to pass this information:
788  *
789  \code
790  Param<int32> p(42);
791  ImageParam img(Int(32), 1);
792  f(x) = img(x) + p;
793 
794  Buffer<int32_t) arg_img(10, 10);
795  <fill in arg_img...>
796 
797  Target t = get_jit_target_from_environment();
798  Buffer<int32_t> result = f.realize({10, 10}, t, { { p, 17 }, { img, arg_img } });
799  \endcode
800  *
801  * If the Func cannot be realized into a buffer of the given size
802  * due to scheduling constraints on scattering update definitions,
803  * it will be realized into a larger buffer of the minimum size
804  * possible, and a cropped view at the requested size will be
805  * returned. It is thus not safe to assume the returned buffers
806  * are contiguous in memory. This behavior can be disabled with
807  * the NoBoundsQuery target flag, in which case an error about
808  * writing out of bounds on the output buffer will trigger
809  * instead.
810  *
811  */
812  // @{
813  Realization realize(std::vector<int32_t> sizes = {}, const Target &target = Target(),
814  const ParamMap &param_map = ParamMap::empty_map());
815  HALIDE_ATTRIBUTE_DEPRECATED("Call realize() with a vector<int> instead")
816  Realization realize(int x_size, int y_size, int z_size, int w_size, const Target &target = Target(),
817  const ParamMap &param_map = ParamMap::empty_map());
818  HALIDE_ATTRIBUTE_DEPRECATED("Call realize() with a vector<int> instead")
819  Realization realize(int x_size, int y_size, int z_size, const Target &target = Target(),
820  const ParamMap &param_map = ParamMap::empty_map());
821  HALIDE_ATTRIBUTE_DEPRECATED("Call realize() with a vector<int> instead")
822  Realization realize(int x_size, int y_size, const Target &target = Target(),
823  const ParamMap &param_map = ParamMap::empty_map());
824 
825  // Making this a template function is a trick: `{intliteral}` is a valid scalar initializer
826  // in C++, but we want it to match the vector call, not the (deprecated) scalar one.
827  template<typename T, typename = typename std::enable_if<std::is_same<T, int>::value>::type>
828  HALIDE_ATTRIBUTE_DEPRECATED("Call realize() with a vector<int> instead")
829  HALIDE_ALWAYS_INLINE Realization realize(T x_size, const Target &target = Target(),
830  const ParamMap &param_map = ParamMap::empty_map()) {
831  return realize(std::vector<int32_t>{x_size}, target, param_map);
832  }
833  // @}
834 
835  /** Evaluate this function into an existing allocated buffer or
836  * buffers. If the buffer is also one of the arguments to the
837  * function, strange things may happen, as the pipeline isn't
838  * necessarily safe to run in-place. If you pass multiple buffers,
839  * they must have matching sizes. This form of realize does *not*
840  * automatically copy data back from the GPU. */
842  const ParamMap &param_map = ParamMap::empty_map());
843 
844  /** For a given size of output, or a given output buffer,
845  * determine the bounds required of all unbound ImageParams
846  * referenced. Communicates the result by allocating new buffers
847  * of the appropriate size and binding them to the unbound
848  * ImageParams.
849  *
850  * Set the documentation for Func::realize regarding the
851  * ParamMap. There is one difference in that input Buffer<>
852  * arguments that are being inferred are specified as a pointer to
853  * the Buffer<> in the ParamMap. E.g.
854  *
855  \code
856  Param<int32> p(42);
857  ImageParam img(Int(32), 1);
858  f(x) = img(x) + p;
859 
860  Target t = get_jit_target_from_environment();
861  Buffer<> in;
862  f.infer_input_bounds({10, 10}, t, { { img, &in } });
863  \endcode
864  * On return, in will be an allocated buffer of the correct size
865  * to evaulate f over a 10x10 region.
866  */
867  // @{
868  void infer_input_bounds(const std::vector<int32_t> &sizes,
869  const Target &target = get_jit_target_from_environment(),
870  const ParamMap &param_map = ParamMap::empty_map());
872  const Target &target = get_jit_target_from_environment(),
873  const ParamMap &param_map = ParamMap::empty_map());
874  // @}
875 
876  /** Statically compile this function to llvm bitcode, with the
877  * given filename (which should probably end in .bc), type
878  * signature, and C function name (which defaults to the same name
879  * as this halide function */
880  //@{
881  void compile_to_bitcode(const std::string &filename, const std::vector<Argument> &, const std::string &fn_name,
882  const Target &target = get_target_from_environment());
883  void compile_to_bitcode(const std::string &filename, const std::vector<Argument> &,
884  const Target &target = get_target_from_environment());
885  // @}
886 
887  /** Statically compile this function to llvm assembly, with the
888  * given filename (which should probably end in .ll), type
889  * signature, and C function name (which defaults to the same name
890  * as this halide function */
891  //@{
892  void compile_to_llvm_assembly(const std::string &filename, const std::vector<Argument> &, const std::string &fn_name,
893  const Target &target = get_target_from_environment());
894  void compile_to_llvm_assembly(const std::string &filename, const std::vector<Argument> &,
895  const Target &target = get_target_from_environment());
896  // @}
897 
898  /** Statically compile this function to an object file, with the
899  * given filename (which should probably end in .o or .obj), type
900  * signature, and C function name (which defaults to the same name
901  * as this halide function. You probably don't want to use this
902  * directly; call compile_to_static_library or compile_to_file instead. */
903  //@{
904  void compile_to_object(const std::string &filename, const std::vector<Argument> &, const std::string &fn_name,
905  const Target &target = get_target_from_environment());
906  void compile_to_object(const std::string &filename, const std::vector<Argument> &,
907  const Target &target = get_target_from_environment());
908  // @}
909 
910  /** Emit a header file with the given filename for this
911  * function. The header will define a function with the type
912  * signature given by the second argument, and a name given by the
913  * third. The name defaults to the same name as this halide
914  * function. You don't actually have to have defined this function
915  * yet to call this. You probably don't want to use this directly;
916  * call compile_to_static_library or compile_to_file instead. */
917  void compile_to_header(const std::string &filename, const std::vector<Argument> &, const std::string &fn_name = "",
918  const Target &target = get_target_from_environment());
919 
920  /** Statically compile this function to text assembly equivalent
921  * to the object file generated by compile_to_object. This is
922  * useful for checking what Halide is producing without having to
923  * disassemble anything, or if you need to feed the assembly into
924  * some custom toolchain to produce an object file (e.g. iOS) */
925  //@{
926  void compile_to_assembly(const std::string &filename, const std::vector<Argument> &, const std::string &fn_name,
927  const Target &target = get_target_from_environment());
928  void compile_to_assembly(const std::string &filename, const std::vector<Argument> &,
929  const Target &target = get_target_from_environment());
930  // @}
931 
932  /** Statically compile this function to C source code. This is
933  * useful for providing fallback code paths that will compile on
934  * many platforms. Vectorization will fail, and parallelization
935  * will produce serial code. */
936  void compile_to_c(const std::string &filename,
937  const std::vector<Argument> &,
938  const std::string &fn_name = "",
939  const Target &target = get_target_from_environment());
940 
941  /** Write out an internal representation of lowered code. Useful
942  * for analyzing and debugging scheduling. Can emit html or plain
943  * text. */
944  void compile_to_lowered_stmt(const std::string &filename,
945  const std::vector<Argument> &args,
946  StmtOutputFormat fmt = Text,
947  const Target &target = get_target_from_environment());
948 
949  /** Write out the loop nests specified by the schedule for this
950  * Function. Helpful for understanding what a schedule is
951  * doing. */
953 
954  /** Compile to object file and header pair, with the given
955  * arguments. The name defaults to the same name as this halide
956  * function.
957  */
958  void compile_to_file(const std::string &filename_prefix, const std::vector<Argument> &args,
959  const std::string &fn_name = "",
960  const Target &target = get_target_from_environment());
961 
962  /** Compile to static-library file and header pair, with the given
963  * arguments. The name defaults to the same name as this halide
964  * function.
965  */
966  void compile_to_static_library(const std::string &filename_prefix, const std::vector<Argument> &args,
967  const std::string &fn_name = "",
968  const Target &target = get_target_from_environment());
969 
970  /** Compile to static-library file and header pair once for each target;
971  * each resulting function will be considered (in order) via halide_can_use_target_features()
972  * at runtime, with the first appropriate match being selected for subsequent use.
973  * This is typically useful for specializations that may vary unpredictably by machine
974  * (e.g., SSE4.1/AVX/AVX2 on x86 desktop machines).
975  * All targets must have identical arch-os-bits.
976  */
977  void compile_to_multitarget_static_library(const std::string &filename_prefix,
978  const std::vector<Argument> &args,
979  const std::vector<Target> &targets);
980 
981  /** Like compile_to_multitarget_static_library(), except that the object files
982  * are all output as object files (rather than bundled into a static library).
983  *
984  * `suffixes` is an optional list of strings to use for as the suffix for each object
985  * file. If nonempty, it must be the same length as `targets`. (If empty, Target::to_string()
986  * will be used for each suffix.)
987  *
988  * Note that if `targets.size()` > 1, the wrapper code (to select the subtarget)
989  * will be generated with the filename `${filename_prefix}_wrapper.o`
990  *
991  * Note that if `targets.size()` > 1 and `no_runtime` is not specified, the runtime
992  * will be generated with the filename `${filename_prefix}_runtime.o`
993  */
994  void compile_to_multitarget_object_files(const std::string &filename_prefix,
995  const std::vector<Argument> &args,
996  const std::vector<Target> &targets,
997  const std::vector<std::string> &suffixes);
998 
999  /** Store an internal representation of lowered code as a self
1000  * contained Module suitable for further compilation. */
1001  Module compile_to_module(const std::vector<Argument> &args, const std::string &fn_name = "",
1002  const Target &target = get_target_from_environment());
1003 
1004  /** Compile and generate multiple target files with single call.
1005  * Deduces target files based on filenames specified in
1006  * output_files map.
1007  */
1008  void compile_to(const std::map<Output, std::string> &output_files,
1009  const std::vector<Argument> &args,
1010  const std::string &fn_name,
1011  const Target &target = get_target_from_environment());
1012 
1013  /** Eagerly jit compile the function to machine code. This
1014  * normally happens on the first call to realize. If you're
1015  * running your halide pipeline inside time-sensitive code and
1016  * wish to avoid including the time taken to compile a pipeline,
1017  * then you can call this ahead of time. Default is to use the Target
1018  * returned from Halide::get_jit_target_from_environment()
1019  */
1021 
1022  /** Set the error handler function that be called in the case of
1023  * runtime errors during halide pipelines. If you are compiling
1024  * statically, you can also just define your own function with
1025  * signature
1026  \code
1027  extern "C" void halide_error(void *user_context, const char *);
1028  \endcode
1029  * This will clobber Halide's version.
1030  */
1031  void set_error_handler(void (*handler)(void *, const char *));
1032 
1033  /** Set a custom malloc and free for halide to use. Malloc should
1034  * return 32-byte aligned chunks of memory, and it should be safe
1035  * for Halide to read slightly out of bounds (up to 8 bytes before
1036  * the start or beyond the end). If compiling statically, routines
1037  * with appropriate signatures can be provided directly
1038  \code
1039  extern "C" void *halide_malloc(void *, size_t)
1040  extern "C" void halide_free(void *, void *)
1041  \endcode
1042  * These will clobber Halide's versions. See HalideRuntime.h
1043  * for declarations.
1044  */
1045  void set_custom_allocator(void *(*malloc)(void *, size_t),
1046  void (*free)(void *, void *));
1047 
1048  /** Set a custom task handler to be called by the parallel for
1049  * loop. It is useful to set this if you want to do some
1050  * additional bookkeeping at the granularity of parallel
1051  * tasks. The default implementation does this:
1052  \code
1053  extern "C" int halide_do_task(void *user_context,
1054  int (*f)(void *, int, uint8_t *),
1055  int idx, uint8_t *state) {
1056  return f(user_context, idx, state);
1057  }
1058  \endcode
1059  * If you are statically compiling, you can also just define your
1060  * own version of the above function, and it will clobber Halide's
1061  * version.
1062  *
1063  * If you're trying to use a custom parallel runtime, you probably
1064  * don't want to call this. See instead \ref Func::set_custom_do_par_for .
1065  */
1067  int (*custom_do_task)(void *, int (*)(void *, int, uint8_t *),
1068  int, uint8_t *));
1069 
1070  /** Set a custom parallel for loop launcher. Useful if your app
1071  * already manages a thread pool. The default implementation is
1072  * equivalent to this:
1073  \code
1074  extern "C" int halide_do_par_for(void *user_context,
1075  int (*f)(void *, int, uint8_t *),
1076  int min, int extent, uint8_t *state) {
1077  int exit_status = 0;
1078  parallel for (int idx = min; idx < min+extent; idx++) {
1079  int job_status = halide_do_task(user_context, f, idx, state);
1080  if (job_status) exit_status = job_status;
1081  }
1082  return exit_status;
1083  }
1084  \endcode
1085  *
1086  * However, notwithstanding the above example code, if one task
1087  * fails, we may skip over other tasks, and if two tasks return
1088  * different error codes, we may select one arbitrarily to return.
1089  *
1090  * If you are statically compiling, you can also just define your
1091  * own version of the above function, and it will clobber Halide's
1092  * version.
1093  */
1095  int (*custom_do_par_for)(void *, int (*)(void *, int, uint8_t *), int,
1096  int, uint8_t *));
1097 
1098  /** Set custom routines to call when tracing is enabled. Call this
1099  * on the output Func of your pipeline. This then sets custom
1100  * routines for the entire pipeline, not just calls to this
1101  * Func.
1102  *
1103  * If you are statically compiling, you can also just define your
1104  * own versions of the tracing functions (see HalideRuntime.h),
1105  * and they will clobber Halide's versions. */
1106  void set_custom_trace(int (*trace_fn)(void *, const halide_trace_event_t *));
1107 
1108  /** Set the function called to print messages from the runtime.
1109  * If you are compiling statically, you can also just define your
1110  * own function with signature
1111  \code
1112  extern "C" void halide_print(void *user_context, const char *);
1113  \endcode
1114  * This will clobber Halide's version.
1115  */
1116  void set_custom_print(void (*handler)(void *, const char *));
1117 
1118  /** Get a struct containing the currently set custom functions
1119  * used by JIT. */
1121 
1122  /** Add a custom pass to be used during lowering. It is run after
1123  * all other lowering passes. Can be used to verify properties of
1124  * the lowered Stmt, instrument it with extra code, or otherwise
1125  * modify it. The Func takes ownership of the pass, and will call
1126  * delete on it when the Func goes out of scope. So don't pass a
1127  * stack object, or share pass instances between multiple
1128  * Funcs. */
1129  template<typename T>
1131  // Template instantiate a custom deleter for this type, then
1132  // wrap in a lambda. The custom deleter lives in user code, so
1133  // that deletion is on the same heap as construction (I hate Windows).
1134  add_custom_lowering_pass(pass, [pass]() { delete_lowering_pass<T>(pass); });
1135  }
1136 
1137  /** Add a custom pass to be used during lowering, with the
1138  * function that will be called to delete it also passed in. Set
1139  * it to nullptr if you wish to retain ownership of the object. */
1140  void add_custom_lowering_pass(Internal::IRMutator *pass, std::function<void()> deleter);
1141 
1142  /** Remove all previously-set custom lowering passes */
1144 
1145  /** Get the custom lowering passes. */
1146  const std::vector<CustomLoweringPass> &custom_lowering_passes();
1147 
1148  /** When this function is compiled, include code that dumps its
1149  * values to a file after it is realized, for the purpose of
1150  * debugging.
1151  *
1152  * If filename ends in ".tif" or ".tiff" (case insensitive) the file
1153  * is in TIFF format and can be read by standard tools. Oherwise, the
1154  * file format is as follows:
1155  *
1156  * All data is in the byte-order of the target platform. First, a
1157  * 20 byte-header containing four 32-bit ints, giving the extents
1158  * of the first four dimensions. Dimensions beyond four are
1159  * folded into the fourth. Then, a fifth 32-bit int giving the
1160  * data type of the function. The typecodes are given by: float =
1161  * 0, double = 1, uint8_t = 2, int8_t = 3, uint16_t = 4, int16_t =
1162  * 5, uint32_t = 6, int32_t = 7, uint64_t = 8, int64_t = 9. The
1163  * data follows the header, as a densely packed array of the given
1164  * size and the given type. If given the extension .tmp, this file
1165  * format can be natively read by the program ImageStack. */
1166  void debug_to_file(const std::string &filename);
1167 
1168  /** The name of this function, either given during construction,
1169  * or automatically generated. */
1170  const std::string &name() const;
1171 
1172  /** Get the pure arguments. */
1173  std::vector<Var> args() const;
1174 
1175  /** The right-hand-side value of the pure definition of this
1176  * function. Causes an error if there's no pure definition, or if
1177  * the function is defined to return multiple values. */
1178  Expr value() const;
1179 
1180  /** The values returned by this function. An error if the function
1181  * has not been been defined. Returns a Tuple with one element for
1182  * functions defined to return a single value. */
1183  Tuple values() const;
1184 
1185  /** Does this function have at least a pure definition. */
1186  bool defined() const;
1187 
1188  /** Get the left-hand-side of the update definition. An empty
1189  * vector if there's no update definition. If there are
1190  * multiple update definitions for this function, use the
1191  * argument to select which one you want. */
1192  const std::vector<Expr> &update_args(int idx = 0) const;
1193 
1194  /** Get the right-hand-side of an update definition. An error if
1195  * there's no update definition. If there are multiple
1196  * update definitions for this function, use the argument to
1197  * select which one you want. */
1198  Expr update_value(int idx = 0) const;
1199 
1200  /** Get the right-hand-side of an update definition for
1201  * functions that returns multiple values. An error if there's no
1202  * update definition. Returns a Tuple with one element for
1203  * functions that return a single value. */
1204  Tuple update_values(int idx = 0) const;
1205 
1206  /** Get the RVars of the reduction domain for an update definition, if there is
1207  * one. */
1208  std::vector<RVar> rvars(int idx = 0) const;
1209 
1210  /** Does this function have at least one update definition? */
1212 
1213  /** How many update definitions does this function have? */
1215 
1216  /** Is this function an external stage? That is, was it defined
1217  * using define_extern? */
1218  bool is_extern() const;
1219 
1220  /** Add an extern definition for this Func. This lets you define a
1221  * Func that represents an external pipeline stage. You can, for
1222  * example, use it to wrap a call to an extern library such as
1223  * fftw. */
1224  // @{
1225  void define_extern(const std::string &function_name,
1226  const std::vector<ExternFuncArgument> &params, Type t,
1227  int dimensionality,
1229  DeviceAPI device_api = DeviceAPI::Host) {
1230  define_extern(function_name, params, t,
1231  Internal::make_argument_list(dimensionality), mangling,
1232  device_api);
1233  }
1234 
1235  void define_extern(const std::string &function_name,
1236  const std::vector<ExternFuncArgument> &params,
1237  const std::vector<Type> &types, int dimensionality,
1238  NameMangling mangling) {
1239  define_extern(function_name, params, types,
1240  Internal::make_argument_list(dimensionality), mangling);
1241  }
1242 
1243  void define_extern(const std::string &function_name,
1244  const std::vector<ExternFuncArgument> &params,
1245  const std::vector<Type> &types, int dimensionality,
1247  DeviceAPI device_api = DeviceAPI::Host) {
1248  define_extern(function_name, params, types,
1249  Internal::make_argument_list(dimensionality), mangling,
1250  device_api);
1251  }
1252 
1253  void define_extern(const std::string &function_name,
1254  const std::vector<ExternFuncArgument> &params, Type t,
1255  const std::vector<Var> &arguments,
1257  DeviceAPI device_api = DeviceAPI::Host) {
1258  define_extern(function_name, params, std::vector<Type>{t}, arguments,
1259  mangling, device_api);
1260  }
1261 
1262  void define_extern(const std::string &function_name,
1263  const std::vector<ExternFuncArgument> &params,
1264  const std::vector<Type> &types,
1265  const std::vector<Var> &arguments,
1267  DeviceAPI device_api = DeviceAPI::Host);
1268  // @}
1269 
1270  /** Get the types of the outputs of this Func. */
1271  const std::vector<Type> &output_types() const;
1272 
1273  /** Get the number of outputs of this Func. Corresponds to the
1274  * size of the Tuple this Func was defined to return. */
1275  int outputs() const;
1276 
1277  /** Get the name of the extern function called for an extern
1278  * definition. */
1279  const std::string &extern_function_name() const;
1280 
1281  /** The dimensionality (number of arguments) of this
1282  * function. Zero if the function is not yet defined. */
1283  int dimensions() const;
1284 
1285  /** Construct either the left-hand-side of a definition, or a call
1286  * to a functions that happens to only contain vars as
1287  * arguments. If the function has already been defined, and fewer
1288  * arguments are given than the function has dimensions, then
1289  * enough implicit vars are added to the end of the argument list
1290  * to make up the difference (see \ref Var::implicit) */
1291  // @{
1292  FuncRef operator()(std::vector<Var>) const;
1293 
1294  template<typename... Args>
1295  HALIDE_NO_USER_CODE_INLINE typename std::enable_if<Internal::all_are_convertible<Var, Args...>::value, FuncRef>::type
1296  operator()(Args &&...args) const {
1297  std::vector<Var> collected_args{std::forward<Args>(args)...};
1298  return this->operator()(collected_args);
1299  }
1300  // @}
1301 
1302  /** Either calls to the function, or the left-hand-side of
1303  * an update definition (see \ref RDom). If the function has
1304  * already been defined, and fewer arguments are given than the
1305  * function has dimensions, then enough implicit vars are added to
1306  * the end of the argument list to make up the difference. (see
1307  * \ref Var::implicit)*/
1308  // @{
1309  FuncRef operator()(std::vector<Expr>) const;
1310 
1311  template<typename... Args>
1312  HALIDE_NO_USER_CODE_INLINE typename std::enable_if<Internal::all_are_convertible<Expr, Args...>::value, FuncRef>::type
1313  operator()(const Expr &x, Args &&...args) const {
1314  std::vector<Expr> collected_args{x, std::forward<Args>(args)...};
1315  return (*this)(collected_args);
1316  }
1317  // @}
1318 
1319  /** Creates and returns a new identity Func that wraps this Func. During
1320  * compilation, Halide replaces all calls to this Func done by 'f'
1321  * with calls to the wrapper. If this Func is already wrapped for
1322  * use in 'f', will return the existing wrapper.
1323  *
1324  * For example, g.in(f) would rewrite a pipeline like this:
1325  \code
1326  g(x, y) = ...
1327  f(x, y) = ... g(x, y) ...
1328  \endcode
1329  * into a pipeline like this:
1330  \code
1331  g(x, y) = ...
1332  g_wrap(x, y) = g(x, y)
1333  f(x, y) = ... g_wrap(x, y)
1334  \endcode
1335  *
1336  * This has a variety of uses. You can use it to schedule this
1337  * Func differently in the different places it is used:
1338  \code
1339  g(x, y) = ...
1340  f1(x, y) = ... g(x, y) ...
1341  f2(x, y) = ... g(x, y) ...
1342  g.in(f1).compute_at(f1, y).vectorize(x, 8);
1343  g.in(f2).compute_at(f2, x).unroll(x);
1344  \endcode
1345  *
1346  * You can also use it to stage loads from this Func via some
1347  * intermediate buffer (perhaps on the stack as in
1348  * test/performance/block_transpose.cpp, or in shared GPU memory
1349  * as in test/performance/wrap.cpp). In this we compute the
1350  * wrapper at tiles of the consuming Funcs like so:
1351  \code
1352  g.compute_root()...
1353  g.in(f).compute_at(f, tiles)...
1354  \endcode
1355  *
1356  * Func::in() can also be used to compute pieces of a Func into a
1357  * smaller scratch buffer (perhaps on the GPU) and then copy them
1358  * into a larger output buffer one tile at a time. See
1359  * apps/interpolate/interpolate.cpp for an example of this. In
1360  * this case we compute the Func at tiles of its own wrapper:
1361  \code
1362  f.in(g).compute_root().gpu_tile(...)...
1363  f.compute_at(f.in(g), tiles)...
1364  \endcode
1365  *
1366  * A similar use of Func::in() wrapping Funcs with multiple update
1367  * stages in a pure wrapper. The following code:
1368  \code
1369  f(x, y) = x + y;
1370  f(x, y) += 5;
1371  g(x, y) = f(x, y);
1372  f.compute_root();
1373  \endcode
1374  *
1375  * Is equivalent to:
1376  \code
1377  for y:
1378  for x:
1379  f(x, y) = x + y;
1380  for y:
1381  for x:
1382  f(x, y) += 5
1383  for y:
1384  for x:
1385  g(x, y) = f(x, y)
1386  \endcode
1387  * using Func::in(), we can write:
1388  \code
1389  f(x, y) = x + y;
1390  f(x, y) += 5;
1391  g(x, y) = f(x, y);
1392  f.in(g).compute_root();
1393  \endcode
1394  * which instead produces:
1395  \code
1396  for y:
1397  for x:
1398  f(x, y) = x + y;
1399  f(x, y) += 5
1400  f_wrap(x, y) = f(x, y)
1401  for y:
1402  for x:
1403  g(x, y) = f_wrap(x, y)
1404  \endcode
1405  */
1406  Func in(const Func &f);
1407 
1408  /** Create and return an identity wrapper shared by all the Funcs in
1409  * 'fs'. If any of the Funcs in 'fs' already have a custom wrapper,
1410  * this will throw an error. */
1411  Func in(const std::vector<Func> &fs);
1412 
1413  /** Create and return a global identity wrapper, which wraps all calls to
1414  * this Func by any other Func. If a global wrapper already exists,
1415  * returns it. The global identity wrapper is only used by callers for
1416  * which no custom wrapper has been specified.
1417  */
1419 
1420  /** Similar to \ref Func::in; however, instead of replacing the call to
1421  * this Func with an identity Func that refers to it, this replaces the
1422  * call with a clone of this Func.
1423  *
1424  * For example, f.clone_in(g) would rewrite a pipeline like this:
1425  \code
1426  f(x, y) = x + y;
1427  g(x, y) = f(x, y) + 2;
1428  h(x, y) = f(x, y) - 3;
1429  \endcode
1430  * into a pipeline like this:
1431  \code
1432  f(x, y) = x + y;
1433  f_clone(x, y) = x + y;
1434  g(x, y) = f_clone(x, y) + 2;
1435  h(x, y) = f(x, y) - 3;
1436  \endcode
1437  *
1438  */
1439  //@{
1440  Func clone_in(const Func &f);
1441  Func clone_in(const std::vector<Func> &fs);
1442  //@}
1443 
1444  /** Declare that this function should be implemented by a call to
1445  * halide_buffer_copy with the given target device API. Asserts
1446  * that the Func has a pure definition which is a simple call to a
1447  * single input, and no update definitions. The wrapper Funcs
1448  * returned by in() are suitable candidates. Consumes all pure
1449  * variables, and rewrites the Func to have an extern definition
1450  * that calls halide_buffer_copy. */
1452 
1453  /** Declare that this function should be implemented by a call to
1454  * halide_buffer_copy with a NULL target device API. Equivalent to
1455  * copy_to_device(DeviceAPI::Host). Asserts that the Func has a
1456  * pure definition which is a simple call to a single input, and
1457  * no update definitions. The wrapper Funcs returned by in() are
1458  * suitable candidates. Consumes all pure variables, and rewrites
1459  * the Func to have an extern definition that calls
1460  * halide_buffer_copy.
1461  *
1462  * Note that if the source Func is already valid in host memory,
1463  * this compiles to code that does the minimum number of calls to
1464  * memcpy.
1465  */
1467 
1468  /** Split a dimension into inner and outer subdimensions with the
1469  * given names, where the inner dimension iterates from 0 to
1470  * factor-1. The inner and outer subdimensions can then be dealt
1471  * with using the other scheduling calls. It's ok to reuse the old
1472  * variable name as either the inner or outer variable. The final
1473  * argument specifies how the tail should be handled if the split
1474  * factor does not provably divide the extent. */
1475  Func &split(const VarOrRVar &old, const VarOrRVar &outer, const VarOrRVar &inner, const Expr &factor, TailStrategy tail = TailStrategy::Auto);
1476 
1477  /** Join two dimensions into a single fused dimenion. The fused
1478  * dimension covers the product of the extents of the inner and
1479  * outer dimensions given. */
1480  Func &fuse(const VarOrRVar &inner, const VarOrRVar &outer, const VarOrRVar &fused);
1481 
1482  /** Mark a dimension to be traversed serially. This is the default. */
1483  Func &serial(const VarOrRVar &var);
1484 
1485  /** Mark a dimension to be traversed in parallel */
1486  Func &parallel(const VarOrRVar &var);
1487 
1488  /** Split a dimension by the given task_size, and the parallelize the
1489  * outer dimension. This creates parallel tasks that have size
1490  * task_size. After this call, var refers to the outer dimension of
1491  * the split. The inner dimension has a new anonymous name. If you
1492  * wish to mutate it, or schedule with respect to it, do the split
1493  * manually. */
1494  Func &parallel(const VarOrRVar &var, const Expr &task_size, TailStrategy tail = TailStrategy::Auto);
1495 
1496  /** Mark a dimension to be computed all-at-once as a single
1497  * vector. The dimension should have constant extent -
1498  * e.g. because it is the inner dimension following a split by a
1499  * constant factor. For most uses of vectorize you want the two
1500  * argument form. The variable to be vectorized should be the
1501  * innermost one. */
1502  Func &vectorize(const VarOrRVar &var);
1503 
1504  /** Mark a dimension to be completely unrolled. The dimension
1505  * should have constant extent - e.g. because it is the inner
1506  * dimension following a split by a constant factor. For most uses
1507  * of unroll you want the two-argument form. */
1508  Func &unroll(const VarOrRVar &var);
1509 
1510  /** Split a dimension by the given factor, then vectorize the
1511  * inner dimension. This is how you vectorize a loop of unknown
1512  * size. The variable to be vectorized should be the innermost
1513  * one. After this call, var refers to the outer dimension of the
1514  * split. 'factor' must be an integer. */
1515  Func &vectorize(const VarOrRVar &var, const Expr &factor, TailStrategy tail = TailStrategy::Auto);
1516 
1517  /** Split a dimension by the given factor, then unroll the inner
1518  * dimension. This is how you unroll a loop of unknown size by
1519  * some constant factor. After this call, var refers to the outer
1520  * dimension of the split. 'factor' must be an integer. */
1521  Func &unroll(const VarOrRVar &var, const Expr &factor, TailStrategy tail = TailStrategy::Auto);
1522 
1523  /** Statically declare that the range over which a function should
1524  * be evaluated is given by the second and third arguments. This
1525  * can let Halide perform some optimizations. E.g. if you know
1526  * there are going to be 4 color channels, you can completely
1527  * vectorize the color channel dimension without the overhead of
1528  * splitting it up. If bounds inference decides that it requires
1529  * more of this function than the bounds you have stated, a
1530  * runtime error will occur when you try to run your pipeline. */
1531  Func &bound(const Var &var, Expr min, Expr extent);
1532 
1533  /** Statically declare the range over which the function will be
1534  * evaluated in the general case. This provides a basis for the auto
1535  * scheduler to make trade-offs and scheduling decisions. The auto
1536  * generated schedules might break when the sizes of the dimensions are
1537  * very different from the estimates specified. These estimates are used
1538  * only by the auto scheduler if the function is a pipeline output. */
1539  Func &set_estimate(const Var &var, const Expr &min, const Expr &extent);
1540 
1541  /** Set (min, extent) estimates for all dimensions in the Func
1542  * at once; this is equivalent to calling `set_estimate(args()[n], min, extent)`
1543  * repeatedly, but slightly terser. The size of the estimates vector
1544  * must match the dimensionality of the Func. */
1545  Func &set_estimates(const Region &estimates);
1546 
1547  /** Expand the region computed so that the min coordinates is
1548  * congruent to 'remainder' modulo 'modulus', and the extent is a
1549  * multiple of 'modulus'. For example, f.align_bounds(x, 2) forces
1550  * the min and extent realized to be even, and calling
1551  * f.align_bounds(x, 2, 1) forces the min to be odd and the extent
1552  * to be even. The region computed always contains the region that
1553  * would have been computed without this directive, so no
1554  * assertions are injected.
1555  */
1556  Func &align_bounds(const Var &var, Expr modulus, Expr remainder = 0);
1557 
1558  /** Expand the region computed so that the extent is a
1559  * multiple of 'modulus'. For example, f.align_extent(x, 2) forces
1560  * the extent realized to be even. The region computed always contains the
1561  * region that would have been computed without this directive, so no
1562  * assertions are injected. (This is essentially equivalent to align_bounds(),
1563  * but always leaving the min untouched.)
1564  */
1565  Func &align_extent(const Var &var, Expr modulus);
1566 
1567  /** Bound the extent of a Func's realization, but not its
1568  * min. This means the dimension can be unrolled or vectorized
1569  * even when its min is not fixed (for example because it is
1570  * compute_at tiles of another Func). This can also be useful for
1571  * forcing a function's allocation to be a fixed size, which often
1572  * means it can go on the stack. */
1573  Func &bound_extent(const Var &var, Expr extent);
1574 
1575  /** Split two dimensions at once by the given factors, and then
1576  * reorder the resulting dimensions to be xi, yi, xo, yo from
1577  * innermost outwards. This gives a tiled traversal. */
1578  Func &tile(const VarOrRVar &x, const VarOrRVar &y,
1579  const VarOrRVar &xo, const VarOrRVar &yo,
1580  const VarOrRVar &xi, const VarOrRVar &yi,
1581  const Expr &xfactor, const Expr &yfactor,
1583 
1584  /** A shorter form of tile, which reuses the old variable names as
1585  * the new outer dimensions */
1586  Func &tile(const VarOrRVar &x, const VarOrRVar &y,
1587  const VarOrRVar &xi, const VarOrRVar &yi,
1588  const Expr &xfactor, const Expr &yfactor,
1590 
1591  /** A more general form of tile, which defines tiles of any dimensionality. */
1592  Func &tile(const std::vector<VarOrRVar> &previous,
1593  const std::vector<VarOrRVar> &outers,
1594  const std::vector<VarOrRVar> &inners,
1595  const std::vector<Expr> &factors,
1596  const std::vector<TailStrategy> &tails);
1597 
1598  /** The generalized tile, with a single tail strategy to apply to all vars. */
1599  Func &tile(const std::vector<VarOrRVar> &previous,
1600  const std::vector<VarOrRVar> &outers,
1601  const std::vector<VarOrRVar> &inners,
1602  const std::vector<Expr> &factors,
1604 
1605  /** Generalized tiling, reusing the previous names as the outer names. */
1606  Func &tile(const std::vector<VarOrRVar> &previous,
1607  const std::vector<VarOrRVar> &inners,
1608  const std::vector<Expr> &factors,
1610 
1611  /** Reorder variables to have the given nesting order, from
1612  * innermost out */
1613  Func &reorder(const std::vector<VarOrRVar> &vars);
1614 
1615  template<typename... Args>
1616  HALIDE_NO_USER_CODE_INLINE typename std::enable_if<Internal::all_are_convertible<VarOrRVar, Args...>::value, Func &>::type
1617  reorder(const VarOrRVar &x, const VarOrRVar &y, Args &&...args) {
1618  std::vector<VarOrRVar> collected_args{x, y, std::forward<Args>(args)...};
1619  return reorder(collected_args);
1620  }
1621 
1622  /** Rename a dimension. Equivalent to split with a inner size of one. */
1623  Func &rename(const VarOrRVar &old_name, const VarOrRVar &new_name);
1624 
1625  /** Specify that race conditions are permitted for this Func,
1626  * which enables parallelizing over RVars even when Halide cannot
1627  * prove that it is safe to do so. Use this with great caution,
1628  * and only if you can prove to yourself that this is safe, as it
1629  * may result in a non-deterministic routine that returns
1630  * different values at different times or on different machines. */
1632 
1633  /** Issue atomic updates for this Func. This allows parallelization
1634  * on associative RVars. The function throws a compile error when
1635  * Halide fails to prove associativity. Use override_associativity_test
1636  * to disable the associativity test if you believe the function is
1637  * associative or the order of reduction variable execution does not
1638  * matter.
1639  * Halide compiles this into hardware atomic operations whenever possible,
1640  * and falls back to a mutex lock per storage element if it is impossible
1641  * to atomically update.
1642  * There are three possible outcomes of the compiled code:
1643  * atomic add, compare-and-swap loop, and mutex lock.
1644  * For example:
1645  *
1646  * hist(x) = 0;
1647  * hist(im(r)) += 1;
1648  * hist.compute_root();
1649  * hist.update().atomic().parallel();
1650  *
1651  * will be compiled to atomic add operations.
1652  *
1653  * hist(x) = 0;
1654  * hist(im(r)) = min(hist(im(r)) + 1, 100);
1655  * hist.compute_root();
1656  * hist.update().atomic().parallel();
1657  *
1658  * will be compiled to compare-and-swap loops.
1659  *
1660  * arg_max() = {0, im(0)};
1661  * Expr old_index = arg_max()[0];
1662  * Expr old_max = arg_max()[1];
1663  * Expr new_index = select(old_max < im(r), r, old_index);
1664  * Expr new_max = max(im(r), old_max);
1665  * arg_max() = {new_index, new_max};
1666  * arg_max.compute_root();
1667  * arg_max.update().atomic().parallel();
1668  *
1669  * will be compiled to updates guarded by a mutex lock,
1670  * since it is impossible to atomically update two different locations.
1671  *
1672  * Currently the atomic operation is supported by x86, CUDA, and OpenCL backends.
1673  * Compiling to other backends results in a compile error.
1674  * If an operation is compiled into a mutex lock, and is vectorized or is
1675  * compiled to CUDA or OpenCL, it also results in a compile error,
1676  * since per-element mutex lock on vectorized operation leads to a
1677  * deadlock.
1678  * Vectorization of predicated RVars (through rdom.where()) on CPU
1679  * is also unsupported yet (see https://github.com/halide/Halide/issues/4298).
1680  * 8-bit and 16-bit atomics on GPU are also not supported. */
1681  Func &atomic(bool override_associativity_test = false);
1682 
1683  /** Specialize a Func. This creates a special-case version of the
1684  * Func where the given condition is true. The most effective
1685  * conditions are those of the form param == value, and boolean
1686  * Params. Consider a simple example:
1687  \code
1688  f(x) = x + select(cond, 0, 1);
1689  f.compute_root();
1690  \endcode
1691  * This is equivalent to:
1692  \code
1693  for (int x = 0; x < width; x++) {
1694  f[x] = x + (cond ? 0 : 1);
1695  }
1696  \endcode
1697  * Adding the scheduling directive:
1698  \code
1699  f.specialize(cond)
1700  \endcode
1701  * makes it equivalent to:
1702  \code
1703  if (cond) {
1704  for (int x = 0; x < width; x++) {
1705  f[x] = x;
1706  }
1707  } else {
1708  for (int x = 0; x < width; x++) {
1709  f[x] = x + 1;
1710  }
1711  }
1712  \endcode
1713  * Note that the inner loops have been simplified. In the first
1714  * path Halide knows that cond is true, and in the second path
1715  * Halide knows that it is false.
1716  *
1717  * The specialized version gets its own schedule, which inherits
1718  * every directive made about the parent Func's schedule so far
1719  * except for its specializations. This method returns a handle to
1720  * the new schedule. If you wish to retrieve the specialized
1721  * sub-schedule again later, you can call this method with the
1722  * same condition. Consider the following example of scheduling
1723  * the specialized version:
1724  *
1725  \code
1726  f(x) = x;
1727  f.compute_root();
1728  f.specialize(width > 1).unroll(x, 2);
1729  \endcode
1730  * Assuming for simplicity that width is even, this is equivalent to:
1731  \code
1732  if (width > 1) {
1733  for (int x = 0; x < width/2; x++) {
1734  f[2*x] = 2*x;
1735  f[2*x + 1] = 2*x + 1;
1736  }
1737  } else {
1738  for (int x = 0; x < width/2; x++) {
1739  f[x] = x;
1740  }
1741  }
1742  \endcode
1743  * For this case, it may be better to schedule the un-specialized
1744  * case instead:
1745  \code
1746  f(x) = x;
1747  f.compute_root();
1748  f.specialize(width == 1); // Creates a copy of the schedule so far.
1749  f.unroll(x, 2); // Only applies to the unspecialized case.
1750  \endcode
1751  * This is equivalent to:
1752  \code
1753  if (width == 1) {
1754  f[0] = 0;
1755  } else {
1756  for (int x = 0; x < width/2; x++) {
1757  f[2*x] = 2*x;
1758  f[2*x + 1] = 2*x + 1;
1759  }
1760  }
1761  \endcode
1762  * This can be a good way to write a pipeline that splits,
1763  * vectorizes, or tiles, but can still handle small inputs.
1764  *
1765  * If a Func has several specializations, the first matching one
1766  * will be used, so the order in which you define specializations
1767  * is significant. For example:
1768  *
1769  \code
1770  f(x) = x + select(cond1, a, b) - select(cond2, c, d);
1771  f.specialize(cond1);
1772  f.specialize(cond2);
1773  \endcode
1774  * is equivalent to:
1775  \code
1776  if (cond1) {
1777  for (int x = 0; x < width; x++) {
1778  f[x] = x + a - (cond2 ? c : d);
1779  }
1780  } else if (cond2) {
1781  for (int x = 0; x < width; x++) {
1782  f[x] = x + b - c;
1783  }
1784  } else {
1785  for (int x = 0; x < width; x++) {
1786  f[x] = x + b - d;
1787  }
1788  }
1789  \endcode
1790  *
1791  * Specializations may in turn be specialized, which creates a
1792  * nested if statement in the generated code.
1793  *
1794  \code
1795  f(x) = x + select(cond1, a, b) - select(cond2, c, d);
1796  f.specialize(cond1).specialize(cond2);
1797  \endcode
1798  * This is equivalent to:
1799  \code
1800  if (cond1) {
1801  if (cond2) {
1802  for (int x = 0; x < width; x++) {
1803  f[x] = x + a - c;
1804  }
1805  } else {
1806  for (int x = 0; x < width; x++) {
1807  f[x] = x + a - d;
1808  }
1809  }
1810  } else {
1811  for (int x = 0; x < width; x++) {
1812  f[x] = x + b - (cond2 ? c : d);
1813  }
1814  }
1815  \endcode
1816  * To create a 4-way if statement that simplifies away all of the
1817  * ternary operators above, you could say:
1818  \code
1819  f.specialize(cond1).specialize(cond2);
1820  f.specialize(cond2);
1821  \endcode
1822  * or
1823  \code
1824  f.specialize(cond1 && cond2);
1825  f.specialize(cond1);
1826  f.specialize(cond2);
1827  \endcode
1828  *
1829  * Any prior Func which is compute_at some variable of this Func
1830  * gets separately included in all paths of the generated if
1831  * statement. The Var in the compute_at call to must exist in all
1832  * paths, but it may have been generated via a different path of
1833  * splits, fuses, and renames. This can be used somewhat
1834  * creatively. Consider the following code:
1835  \code
1836  g(x, y) = 8*x;
1837  f(x, y) = g(x, y) + 1;
1838  f.compute_root().specialize(cond);
1839  Var g_loop;
1840  f.specialize(cond).rename(y, g_loop);
1841  f.rename(x, g_loop);
1842  g.compute_at(f, g_loop);
1843  \endcode
1844  * When cond is true, this is equivalent to g.compute_at(f,y).
1845  * When it is false, this is equivalent to g.compute_at(f,x).
1846  */
1847  Stage specialize(const Expr &condition);
1848 
1849  /** Add a specialization to a Func that always terminates execution
1850  * with a call to halide_error(). By itself, this is of limited use,
1851  * but can be useful to terminate chains of specialize() calls where
1852  * no "default" case is expected (thus avoiding unnecessary code generation).
1853  *
1854  * For instance, say we want to optimize a pipeline to process images
1855  * in planar and interleaved format; we might typically do something like:
1856  \code
1857  ImageParam im(UInt(8), 3);
1858  Func f = do_something_with(im);
1859  f.specialize(im.dim(0).stride() == 1).vectorize(x, 8); // planar
1860  f.specialize(im.dim(2).stride() == 1).reorder(c, x, y).vectorize(c); // interleaved
1861  \endcode
1862  * This code will vectorize along rows for the planar case, and across pixel
1863  * components for the interleaved case... but there is an implicit "else"
1864  * for the unhandled cases, which generates unoptimized code. If we never
1865  * anticipate passing any other sort of images to this, we code streamline
1866  * our code by adding specialize_fail():
1867  \code
1868  ImageParam im(UInt(8), 3);
1869  Func f = do_something(im);
1870  f.specialize(im.dim(0).stride() == 1).vectorize(x, 8); // planar
1871  f.specialize(im.dim(2).stride() == 1).reorder(c, x, y).vectorize(c); // interleaved
1872  f.specialize_fail("Unhandled image format");
1873  \endcode
1874  * Conceptually, this produces codes like:
1875  \code
1876  if (im.dim(0).stride() == 1) {
1877  do_something_planar();
1878  } else if (im.dim(2).stride() == 1) {
1879  do_something_interleaved();
1880  } else {
1881  halide_error("Unhandled image format");
1882  }
1883  \endcode
1884  *
1885  * Note that calling specialize_fail() terminates the specialization chain
1886  * for a given Func; you cannot create new specializations for the Func
1887  * afterwards (though you can retrieve handles to previous specializations).
1888  */
1889  void specialize_fail(const std::string &message);
1890 
1891  /** Tell Halide that the following dimensions correspond to GPU
1892  * thread indices. This is useful if you compute a producer
1893  * function within the block indices of a consumer function, and
1894  * want to control how that function's dimensions map to GPU
1895  * threads. If the selected target is not an appropriate GPU, this
1896  * just marks those dimensions as parallel. */
1897  // @{
1898  Func &gpu_threads(const VarOrRVar &thread_x, DeviceAPI device_api = DeviceAPI::Default_GPU);
1899  Func &gpu_threads(const VarOrRVar &thread_x, const VarOrRVar &thread_y, DeviceAPI device_api = DeviceAPI::Default_GPU);
1900  Func &gpu_threads(const VarOrRVar &thread_x, const VarOrRVar &thread_y, const VarOrRVar &thread_z, DeviceAPI device_api = DeviceAPI::Default_GPU);
1901  // @}
1902 
1903  /** The given dimension corresponds to the lanes in a GPU
1904  * warp. GPU warp lanes are distinguished from GPU threads by the
1905  * fact that all warp lanes run together in lockstep, which
1906  * permits lightweight communication of data from one lane to
1907  * another. */
1908  Func &gpu_lanes(const VarOrRVar &thread_x, DeviceAPI device_api = DeviceAPI::Default_GPU);
1909 
1910  /** Tell Halide to run this stage using a single gpu thread and
1911  * block. This is not an efficient use of your GPU, but it can be
1912  * useful to avoid copy-back for intermediate update stages that
1913  * touch a very small part of your Func. */
1915 
1916  /** Tell Halide that the following dimensions correspond to GPU
1917  * block indices. This is useful for scheduling stages that will
1918  * run serially within each GPU block. If the selected target is
1919  * not ptx, this just marks those dimensions as parallel. */
1920  // @{
1922  Func &gpu_blocks(const VarOrRVar &block_x, const VarOrRVar &block_y, DeviceAPI device_api = DeviceAPI::Default_GPU);
1923  Func &gpu_blocks(const VarOrRVar &block_x, const VarOrRVar &block_y, const VarOrRVar &block_z, DeviceAPI device_api = DeviceAPI::Default_GPU);
1924  // @}
1925 
1926  /** Tell Halide that the following dimensions correspond to GPU
1927  * block indices and thread indices. If the selected target is not
1928  * ptx, these just mark the given dimensions as parallel. The
1929  * dimensions are consumed by this call, so do all other
1930  * unrolling, reordering, etc first. */
1931  // @{
1932  Func &gpu(const VarOrRVar &block_x, const VarOrRVar &thread_x, DeviceAPI device_api = DeviceAPI::Default_GPU);
1933  Func &gpu(const VarOrRVar &block_x, const VarOrRVar &block_y,
1934  const VarOrRVar &thread_x, const VarOrRVar &thread_y, DeviceAPI device_api = DeviceAPI::Default_GPU);
1935  Func &gpu(const VarOrRVar &block_x, const VarOrRVar &block_y, const VarOrRVar &block_z,
1936  const VarOrRVar &thread_x, const VarOrRVar &thread_y, const VarOrRVar &thread_z, DeviceAPI device_api = DeviceAPI::Default_GPU);
1937  // @}
1938 
1939  /** Short-hand for tiling a domain and mapping the tile indices
1940  * to GPU block indices and the coordinates within each tile to
1941  * GPU thread indices. Consumes the variables given, so do all
1942  * other scheduling first. */
1943  // @{
1944  Func &gpu_tile(const VarOrRVar &x, const VarOrRVar &bx, const VarOrRVar &tx, const Expr &x_size,
1946  DeviceAPI device_api = DeviceAPI::Default_GPU);
1947 
1948  Func &gpu_tile(const VarOrRVar &x, const VarOrRVar &tx, const Expr &x_size,
1950  DeviceAPI device_api = DeviceAPI::Default_GPU);
1951  Func &gpu_tile(const VarOrRVar &x, const VarOrRVar &y,
1952  const VarOrRVar &bx, const VarOrRVar &by,
1953  const VarOrRVar &tx, const VarOrRVar &ty,
1954  const Expr &x_size, const Expr &y_size,
1956  DeviceAPI device_api = DeviceAPI::Default_GPU);
1957 
1958  Func &gpu_tile(const VarOrRVar &x, const VarOrRVar &y,
1959  const VarOrRVar &tx, const VarOrRVar &ty,
1960  const Expr &x_size, const Expr &y_size,
1962  DeviceAPI device_api = DeviceAPI::Default_GPU);
1963 
1964  Func &gpu_tile(const VarOrRVar &x, const VarOrRVar &y, const VarOrRVar &z,
1965  const VarOrRVar &bx, const VarOrRVar &by, const VarOrRVar &bz,
1966  const VarOrRVar &tx, const VarOrRVar &ty, const VarOrRVar &tz,
1967  const Expr &x_size, const Expr &y_size, const Expr &z_size,
1969  DeviceAPI device_api = DeviceAPI::Default_GPU);
1970  Func &gpu_tile(const VarOrRVar &x, const VarOrRVar &y, const VarOrRVar &z,
1971  const VarOrRVar &tx, const VarOrRVar &ty, const VarOrRVar &tz,
1972  const Expr &x_size, const Expr &y_size, const Expr &z_size,
1974  DeviceAPI device_api = DeviceAPI::Default_GPU);
1975  // @}
1976 
1977  /** Schedule for execution on Hexagon. When a loop is marked with
1978  * Hexagon, that loop is executed on a Hexagon DSP. */
1980 
1981  /** Prefetch data written to or read from a Func or an ImageParam by a
1982  * subsequent loop iteration, at an optionally specified iteration offset.
1983  * 'var' specifies at which loop level the prefetch calls should be inserted.
1984  * The final argument specifies how prefetch of region outside bounds
1985  * should be handled.
1986  *
1987  * For example, consider this pipeline:
1988  \code
1989  Func f, g;
1990  Var x, y;
1991  f(x, y) = x + y;
1992  g(x, y) = 2 * f(x, y);
1993  \endcode
1994  *
1995  * The following schedule:
1996  \code
1997  f.compute_root();
1998  g.prefetch(f, x, 2, PrefetchBoundStrategy::NonFaulting);
1999  \endcode
2000  *
2001  * will inject prefetch call at the innermost loop of 'g' and generate
2002  * the following loop nest:
2003  * for y = ...
2004  * for x = ...
2005  * f(x, y) = x + y
2006  * for y = ..
2007  * for x = ...
2008  * prefetch(&f[x + 2, y], 1, 16);
2009  * g(x, y) = 2 * f(x, y)
2010  */
2011  // @{
2012  Func &prefetch(const Func &f, const VarOrRVar &var, Expr offset = 1,
2014  Func &prefetch(const Internal::Parameter &param, const VarOrRVar &var, Expr offset = 1,
2016  template<typename T>
2017  Func &prefetch(const T &image, VarOrRVar var, Expr offset = 1,
2019  return prefetch(image.parameter(), var, offset, strategy);
2020  }
2021  // @}
2022 
2023  /** Specify how the storage for the function is laid out. These
2024  * calls let you specify the nesting order of the dimensions. For
2025  * example, foo.reorder_storage(y, x) tells Halide to use
2026  * column-major storage for any realizations of foo, without
2027  * changing how you refer to foo in the code. You may want to do
2028  * this if you intend to vectorize across y. When representing
2029  * color images, foo.reorder_storage(c, x, y) specifies packed
2030  * storage (red, green, and blue values adjacent in memory), and
2031  * foo.reorder_storage(x, y, c) specifies planar storage (entire
2032  * red, green, and blue images one after the other in memory).
2033  *
2034  * If you leave out some dimensions, those remain in the same
2035  * positions in the nesting order while the specified variables
2036  * are reordered around them. */
2037  // @{
2038  Func &reorder_storage(const std::vector<Var> &dims);
2039 
2040  Func &reorder_storage(const Var &x, const Var &y);
2041  template<typename... Args>
2042  HALIDE_NO_USER_CODE_INLINE typename std::enable_if<Internal::all_are_convertible<Var, Args...>::value, Func &>::type
2043  reorder_storage(const Var &x, const Var &y, Args &&...args) {
2044  std::vector<Var> collected_args{x, y, std::forward<Args>(args)...};
2045  return reorder_storage(collected_args);
2046  }
2047  // @}
2048 
2049  /** Pad the storage extent of a particular dimension of
2050  * realizations of this function up to be a multiple of the
2051  * specified alignment. This guarantees that the strides for the
2052  * dimensions stored outside of dim will be multiples of the
2053  * specified alignment, where the strides and alignment are
2054  * measured in numbers of elements.
2055  *
2056  * For example, to guarantee that a function foo(x, y, c)
2057  * representing an image has scanlines starting on offsets
2058  * aligned to multiples of 16, use foo.align_storage(x, 16). */
2059  Func &align_storage(const Var &dim, const Expr &alignment);
2060 
2061  /** Store realizations of this function in a circular buffer of a
2062  * given extent. This is more efficient when the extent of the
2063  * circular buffer is a power of 2. If the fold factor is too
2064  * small, or the dimension is not accessed monotonically, the
2065  * pipeline will generate an error at runtime.
2066  *
2067  * The fold_forward option indicates that the new values of the
2068  * producer are accessed by the consumer in a monotonically
2069  * increasing order. Folding storage of producers is also
2070  * supported if the new values are accessed in a monotonically
2071  * decreasing order by setting fold_forward to false.
2072  *
2073  * For example, consider the pipeline:
2074  \code
2075  Func f, g;
2076  Var x, y;
2077  g(x, y) = x*y;
2078  f(x, y) = g(x, y) + g(x, y+1);
2079  \endcode
2080  *
2081  * If we schedule f like so:
2082  *
2083  \code
2084  g.compute_at(f, y).store_root().fold_storage(y, 2);
2085  \endcode
2086  *
2087  * Then g will be computed at each row of f and stored in a buffer
2088  * with an extent in y of 2, alternately storing each computed row
2089  * of g in row y=0 or y=1.
2090  */
2091  Func &fold_storage(const Var &dim, const Expr &extent, bool fold_forward = true);
2092 
2093  /** Compute this function as needed for each unique value of the
2094  * given var for the given calling function f.
2095  *
2096  * For example, consider the simple pipeline:
2097  \code
2098  Func f, g;
2099  Var x, y;
2100  g(x, y) = x*y;
2101  f(x, y) = g(x, y) + g(x, y+1) + g(x+1, y) + g(x+1, y+1);
2102  \endcode
2103  *
2104  * If we schedule f like so:
2105  *
2106  \code
2107  g.compute_at(f, x);
2108  \endcode
2109  *
2110  * Then the C code equivalent to this pipeline will look like this
2111  *
2112  \code
2113 
2114  int f[height][width];
2115  for (int y = 0; y < height; y++) {
2116  for (int x = 0; x < width; x++) {
2117  int g[2][2];
2118  g[0][0] = x*y;
2119  g[0][1] = (x+1)*y;
2120  g[1][0] = x*(y+1);
2121  g[1][1] = (x+1)*(y+1);
2122  f[y][x] = g[0][0] + g[1][0] + g[0][1] + g[1][1];
2123  }
2124  }
2125 
2126  \endcode
2127  *
2128  * The allocation and computation of g is within f's loop over x,
2129  * and enough of g is computed to satisfy all that f will need for
2130  * that iteration. This has excellent locality - values of g are
2131  * used as soon as they are computed, but it does redundant
2132  * work. Each value of g ends up getting computed four times. If
2133  * we instead schedule f like so:
2134  *
2135  \code
2136  g.compute_at(f, y);
2137  \endcode
2138  *
2139  * The equivalent C code is:
2140  *
2141  \code
2142  int f[height][width];
2143  for (int y = 0; y < height; y++) {
2144  int g[2][width+1];
2145  for (int x = 0; x < width; x++) {
2146  g[0][x] = x*y;
2147  g[1][x] = x*(y+1);
2148  }
2149  for (int x = 0; x < width; x++) {
2150  f[y][x] = g[0][x] + g[1][x] + g[0][x+1] + g[1][x+1];
2151  }
2152  }
2153  \endcode
2154  *
2155  * The allocation and computation of g is within f's loop over y,
2156  * and enough of g is computed to satisfy all that f will need for
2157  * that iteration. This does less redundant work (each point in g
2158  * ends up being evaluated twice), but the locality is not quite
2159  * as good, and we have to allocate more temporary memory to store
2160  * g.
2161  */
2162  Func &compute_at(const Func &f, const Var &var);
2163 
2164  /** Schedule a function to be computed within the iteration over
2165  * some dimension of an update domain. Produces equivalent code
2166  * to the version of compute_at that takes a Var. */
2167  Func &compute_at(const Func &f, const RVar &var);
2168 
2169  /** Schedule a function to be computed within the iteration over
2170  * a given LoopLevel. */
2171  Func &compute_at(LoopLevel loop_level);
2172 
2173  /** Schedule the iteration over the initial definition of this function
2174  * to be fused with another stage 's' from outermost loop to a
2175  * given LoopLevel. */
2176  // @{
2177  Func &compute_with(const Stage &s, const VarOrRVar &var, const std::vector<std::pair<VarOrRVar, LoopAlignStrategy>> &align);
2179  Func &compute_with(LoopLevel loop_level, const std::vector<std::pair<VarOrRVar, LoopAlignStrategy>> &align);
2181 
2182  /** Compute all of this function once ahead of time. Reusing
2183  * the example in \ref Func::compute_at :
2184  *
2185  \code
2186  Func f, g;
2187  Var x, y;
2188  g(x, y) = x*y;
2189  f(x, y) = g(x, y) + g(x, y+1) + g(x+1, y) + g(x+1, y+1);
2190 
2191  g.compute_root();
2192  \endcode
2193  *
2194  * is equivalent to
2195  *
2196  \code
2197  int f[height][width];
2198  int g[height+1][width+1];
2199  for (int y = 0; y < height+1; y++) {
2200  for (int x = 0; x < width+1; x++) {
2201  g[y][x] = x*y;
2202  }
2203  }
2204  for (int y = 0; y < height; y++) {
2205  for (int x = 0; x < width; x++) {
2206  f[y][x] = g[y][x] + g[y+1][x] + g[y][x+1] + g[y+1][x+1];
2207  }
2208  }
2209  \endcode
2210  *
2211  * g is computed once ahead of time, and enough is computed to
2212  * satisfy all uses of it. This does no redundant work (each point
2213  * in g is evaluated once), but has poor locality (values of g are
2214  * probably not still in cache when they are used by f), and
2215  * allocates lots of temporary memory to store g.
2216  */
2218 
2219  /** Use the halide_memoization_cache_... interface to store a
2220  * computed version of this function across invocations of the
2221  * Func.
2222  *
2223  * If an eviction_key is provided, it must be constructed with
2224  * Expr of integer or handle type. The key Expr will be promoted
2225  * to a uint64_t and can be used with halide_memoization_cache_evict
2226  * to remove memoized entries using this eviction key from the
2227  * cache. Memoized computations that do not provide an eviction
2228  * key will never be evicted by this mechanism.
2229  */
2230  Func &memoize(const EvictionKey &eviction_key = EvictionKey());
2231 
2232  /** Produce this Func asynchronously in a separate
2233  * thread. Consumers will be run by the task system when the
2234  * production is complete. If this Func's store level is different
2235  * to its compute level, consumers will be run concurrently,
2236  * blocking as necessary to prevent reading ahead of what the
2237  * producer has computed. If storage is folded, then the producer
2238  * will additionally not be permitted to run too far ahead of the
2239  * consumer, to avoid clobbering data that has not yet been
2240  * used.
2241  *
2242  * Take special care when combining this with custom thread pool
2243  * implementations, as avoiding deadlock with producer-consumer
2244  * parallelism requires a much more sophisticated parallel runtime
2245  * than with data parallelism alone. It is strongly recommended
2246  * you just use Halide's default thread pool, which guarantees no
2247  * deadlock and a bound on the number of threads launched.
2248  */
2250 
2251  /** Allocate storage for this function within f's loop over
2252  * var. Scheduling storage is optional, and can be used to
2253  * separate the loop level at which storage occurs from the loop
2254  * level at which computation occurs to trade off between locality
2255  * and redundant work. This can open the door for two types of
2256  * optimization.
2257  *
2258  * Consider again the pipeline from \ref Func::compute_at :
2259  \code
2260  Func f, g;
2261  Var x, y;
2262  g(x, y) = x*y;
2263  f(x, y) = g(x, y) + g(x+1, y) + g(x, y+1) + g(x+1, y+1);
2264  \endcode
2265  *
2266  * If we schedule it like so:
2267  *
2268  \code
2269  g.compute_at(f, x).store_at(f, y);
2270  \endcode
2271  *
2272  * Then the computation of g takes place within the loop over x,
2273  * but the storage takes place within the loop over y:
2274  *
2275  \code
2276  int f[height][width];
2277  for (int y = 0; y < height; y++) {
2278  int g[2][width+1];
2279  for (int x = 0; x < width; x++) {
2280  g[0][x] = x*y;
2281  g[0][x+1] = (x+1)*y;
2282  g[1][x] = x*(y+1);
2283  g[1][x+1] = (x+1)*(y+1);
2284  f[y][x] = g[0][x] + g[1][x] + g[0][x+1] + g[1][x+1];
2285  }
2286  }
2287  \endcode
2288  *
2289  * Provided the for loop over x is serial, halide then
2290  * automatically performs the following sliding window
2291  * optimization:
2292  *
2293  \code
2294  int f[height][width];
2295  for (int y = 0; y < height; y++) {
2296  int g[2][width+1];
2297  for (int x = 0; x < width; x++) {
2298  if (x == 0) {
2299  g[0][x] = x*y;
2300  g[1][x] = x*(y+1);
2301  }
2302  g[0][x+1] = (x+1)*y;
2303  g[1][x+1] = (x+1)*(y+1);
2304  f[y][x] = g[0][x] + g[1][x] + g[0][x+1] + g[1][x+1];
2305  }
2306  }
2307  \endcode
2308  *
2309  * Two of the assignments to g only need to be done when x is
2310  * zero. The rest of the time, those sites have already been
2311  * filled in by a previous iteration. This version has the
2312  * locality of compute_at(f, x), but allocates more memory and
2313  * does much less redundant work.
2314  *
2315  * Halide then further optimizes this pipeline like so:
2316  *
2317  \code
2318  int f[height][width];
2319  for (int y = 0; y < height; y++) {
2320  int g[2][2];
2321  for (int x = 0; x < width; x++) {
2322  if (x == 0) {
2323  g[0][0] = x*y;
2324  g[1][0] = x*(y+1);
2325  }
2326  g[0][(x+1)%2] = (x+1)*y;
2327  g[1][(x+1)%2] = (x+1)*(y+1);
2328  f[y][x] = g[0][x%2] + g[1][x%2] + g[0][(x+1)%2] + g[1][(x+1)%2];
2329  }
2330  }
2331  \endcode
2332  *
2333  * Halide has detected that it's possible to use a circular buffer
2334  * to represent g, and has reduced all accesses to g modulo 2 in
2335  * the x dimension. This optimization only triggers if the for
2336  * loop over x is serial, and if halide can statically determine
2337  * some power of two large enough to cover the range needed. For
2338  * powers of two, the modulo operator compiles to more efficient
2339  * bit-masking. This optimization reduces memory usage, and also
2340  * improves locality by reusing recently-accessed memory instead
2341  * of pulling new memory into cache.
2342  *
2343  */
2344  Func &store_at(const Func &f, const Var &var);
2345 
2346  /** Equivalent to the version of store_at that takes a Var, but
2347  * schedules storage within the loop over a dimension of a
2348  * reduction domain */
2349  Func &store_at(const Func &f, const RVar &var);
2350 
2351  /** Equivalent to the version of store_at that takes a Var, but
2352  * schedules storage at a given LoopLevel. */
2353  Func &store_at(LoopLevel loop_level);
2354 
2355  /** Equivalent to \ref Func::store_at, but schedules storage
2356  * outside the outermost loop. */
2358 
2359  /** Aggressively inline all uses of this function. This is the
2360  * default schedule, so you're unlikely to need to call this. For
2361  * a Func with an update definition, that means it gets computed
2362  * as close to the innermost loop as possible.
2363  *
2364  * Consider once more the pipeline from \ref Func::compute_at :
2365  *
2366  \code
2367  Func f, g;
2368  Var x, y;
2369  g(x, y) = x*y;
2370  f(x, y) = g(x, y) + g(x+1, y) + g(x, y+1) + g(x+1, y+1);
2371  \endcode
2372  *
2373  * Leaving g as inline, this compiles to code equivalent to the following C:
2374  *
2375  \code
2376  int f[height][width];
2377  for (int y = 0; y < height; y++) {
2378  for (int x = 0; x < width; x++) {
2379  f[y][x] = x*y + x*(y+1) + (x+1)*y + (x+1)*(y+1);
2380  }
2381  }
2382  \endcode
2383  */
2385 
2386  /** Get a handle on an update step for the purposes of scheduling
2387  * it. */
2388  Stage update(int idx = 0);
2389 
2390  /** Set the type of memory this Func should be stored in. Controls
2391  * whether allocations go on the stack or the heap on the CPU, and
2392  * in global vs shared vs local on the GPU. See the documentation
2393  * on MemoryType for more detail. */
2394  Func &store_in(MemoryType memory_type);
2395 
2396  /** Trace all loads from this Func by emitting calls to
2397  * halide_trace. If the Func is inlined, this has no
2398  * effect. */
2400 
2401  /** Trace all stores to the buffer backing this Func by emitting
2402  * calls to halide_trace. If the Func is inlined, this call
2403  * has no effect. */
2405 
2406  /** Trace all realizations of this Func by emitting calls to
2407  * halide_trace. */
2409 
2410  /** Add a string of arbitrary text that will be passed thru to trace
2411  * inspection code if the Func is realized in trace mode. (Funcs that are
2412  * inlined won't have their tags emitted.) Ignored entirely if
2413  * tracing is not enabled for the Func (or globally).
2414  */
2415  Func &add_trace_tag(const std::string &trace_tag);
2416 
2417  /** Get a handle on the internal halide function that this Func
2418  * represents. Useful if you want to do introspection on Halide
2419  * functions */
2420  Internal::Function function() const {
2421  return func;
2422  }
2423 
2424  /** You can cast a Func to its pure stage for the purposes of
2425  * scheduling it. */
2426  operator Stage() const;
2427 
2428  /** Get a handle on the output buffer for this Func. Only relevant
2429  * if this is the output Func in a pipeline. Useful for making
2430  * static promises about strides, mins, and extents. */
2431  // @{
2433  std::vector<OutputImageParam> output_buffers() const;
2434  // @}
2435 
2436  /** Use a Func as an argument to an external stage. */
2437  operator ExternFuncArgument() const;
2438 
2439  /** Infer the arguments to the Func, sorted into a canonical order:
2440  * all buffers (sorted alphabetically by name), followed by all non-buffers
2441  * (sorted alphabetically by name).
2442  This lets you write things like:
2443  \code
2444  func.compile_to_assembly("/dev/stdout", func.infer_arguments());
2445  \endcode
2446  */
2447  std::vector<Argument> infer_arguments() const;
2448 
2449  /** Get the source location of the pure definition of this
2450  * Func. See Stage::source_location() */
2451  std::string source_location() const;
2452 
2453  /** Return the current StageSchedule associated with this initial
2454  * Stage of this Func. For introspection only: to modify schedule,
2455  * use the Func interface. */
2457  return Stage(*this).get_schedule();
2458  }
2459 };
2460 
2461 namespace Internal {
2462 
2463 template<typename Last>
2464 inline void check_types(const Tuple &t, int idx) {
2465  using T = typename std::remove_pointer<typename std::remove_reference<Last>::type>::type;
2466  user_assert(t[idx].type() == type_of<T>())
2467  << "Can't evaluate expression "
2468  << t[idx] << " of type " << t[idx].type()
2469  << " as a scalar of type " << type_of<T>() << "\n";
2470 }
2471 
2472 template<typename First, typename Second, typename... Rest>
2473 inline void check_types(const Tuple &t, int idx) {
2474  check_types<First>(t, idx);
2475  check_types<Second, Rest...>(t, idx + 1);
2476 }
2477 
2478 template<typename Last>
2479 inline void assign_results(Realization &r, int idx, Last last) {
2480  using T = typename std::remove_pointer<typename std::remove_reference<Last>::type>::type;
2481  *last = Buffer<T>(r[idx])();
2482 }
2483 
2484 template<typename First, typename Second, typename... Rest>
2485 inline void assign_results(Realization &r, int idx, First first, Second second, Rest &&...rest) {
2486  assign_results<First>(r, idx, first);
2487  assign_results<Second, Rest...>(r, idx + 1, second, rest...);
2488 }
2489 
2490 } // namespace Internal
2491 
2492 /** JIT-Compile and run enough code to evaluate a Halide
2493  * expression. This can be thought of as a scalar version of
2494  * \ref Func::realize */
2495 template<typename T>
2497  user_assert(e.type() == type_of<T>())
2498  << "Can't evaluate expression "
2499  << e << " of type " << e.type()
2500  << " as a scalar of type " << type_of<T>() << "\n";
2501  Func f;
2502  f() = e;
2503  Buffer<T> im = f.realize();
2504  return im();
2505 }
2506 
2507 /** JIT-compile and run enough code to evaluate a Halide Tuple. */
2508 template<typename First, typename... Rest>
2509 HALIDE_NO_USER_CODE_INLINE void evaluate(Tuple t, First first, Rest &&...rest) {
2510  Internal::check_types<First, Rest...>(t, 0);
2511 
2512  Func f;
2513  f() = t;
2514  Realization r = f.realize();
2515  Internal::assign_results(r, 0, first, rest...);
2516 }
2517 
2518 namespace Internal {
2519 
2520 inline void schedule_scalar(Func f) {
2522  if (t.has_gpu_feature()) {
2523  f.gpu_single_thread();
2524  }
2525  if (t.has_feature(Target::HVX)) {
2526  f.hexagon();
2527  }
2528 }
2529 
2530 } // namespace Internal
2531 
2532 /** JIT-Compile and run enough code to evaluate a Halide
2533  * expression. This can be thought of as a scalar version of
2534  * \ref Func::realize. Can use GPU if jit target from environment
2535  * specifies one.
2536  */
2537 template<typename T>
2539  user_assert(e.type() == type_of<T>())
2540  << "Can't evaluate expression "
2541  << e << " of type " << e.type()
2542  << " as a scalar of type " << type_of<T>() << "\n";
2543  Func f;
2544  f() = e;
2546  Buffer<T> im = f.realize();
2547  return im();
2548 }
2549 
2550 /** JIT-compile and run enough code to evaluate a Halide Tuple. Can
2551  * use GPU if jit target from environment specifies one. */
2552 // @{
2553 template<typename First, typename... Rest>
2554 HALIDE_NO_USER_CODE_INLINE void evaluate_may_gpu(Tuple t, First first, Rest &&...rest) {
2555  Internal::check_types<First, Rest...>(t, 0);
2556 
2557  Func f;
2558  f() = t;
2560  Realization r = f.realize();
2561  Internal::assign_results(r, 0, first, rest...);
2562 }
2563 // @}
2564 
2565 } // namespace Halide
2566 
2567 #endif
Defines a type used for expressing the type signature of a generated halide pipeline.
#define internal_assert(c)
Definition: Errors.h:19
#define user_assert(c)
Definition: Errors.h:15
Base classes for Halide expressions (Halide::Expr) and statements (Halide::Internal::Stmt)
#define HALIDE_ATTRIBUTE_DEPRECATED(x)
#define HALIDE_ALWAYS_INLINE
Definition: HalideRuntime.h:38
Defines the struct representing lifetime and dependencies of a JIT compiled halide pipeline.
Defines Module, an IR container that fully describes a Halide program.
Classes for declaring scalar parameters to halide pipelines.
Defines the front-end class representing an entire Halide imaging pipeline.
Defines the front-end syntax for reduction domains and reduction variables.
Defines the structure that describes a Halide target.
Defines Tuple - the front-end handle on small arrays of expressions.
#define HALIDE_NO_USER_CODE_INLINE
Definition: Util.h:45
Defines the Var - the front-end variable.
A Halide::Buffer is a named shared reference to a Halide::Runtime::Buffer.
Definition: Buffer.h:115
Helper class for identifying purpose of an Expr passed to memoize.
Definition: Func.h:666
EvictionKey(const Expr &expr=Expr())
Definition: Func.h:672
A halide function.
Definition: Func.h:681
Func & prefetch(const Func &f, const VarOrRVar &var, Expr offset=1, PrefetchBoundStrategy strategy=PrefetchBoundStrategy::GuardWithIf)
Prefetch data written to or read from a Func or an ImageParam by a subsequent loop iteration,...
void print_loop_nest()
Write out the loop nests specified by the schedule for this Function.
Func & unroll(const VarOrRVar &var)
Mark a dimension to be completely unrolled.
bool is_extern() const
Is this function an external stage? That is, was it defined using define_extern?
FuncRef operator()(std::vector< Expr >) const
Either calls to the function, or the left-hand-side of an update definition (see RDom).
Func & hexagon(const VarOrRVar &x=Var::outermost())
Schedule for execution on Hexagon.
Func(const std::string &name)
Declare a new undefined function with the given name.
void compile_to_multitarget_object_files(const std::string &filename_prefix, const std::vector< Argument > &args, const std::vector< Target > &targets, const std::vector< std::string > &suffixes)
Like compile_to_multitarget_static_library(), except that the object files are all output as object f...
Func & align_extent(const Var &var, Expr modulus)
Expand the region computed so that the extent is a multiple of 'modulus'.
HALIDE_NO_USER_CODE_INLINE std::enable_if< Internal::all_are_convertible< Var, Args... >::value, FuncRef >::type operator()(Args &&...args) const
Definition: Func.h:1296
Func & tile(const VarOrRVar &x, const VarOrRVar &y, const VarOrRVar &xo, const VarOrRVar &yo, const VarOrRVar &xi, const VarOrRVar &yi, const Expr &xfactor, const Expr &yfactor, TailStrategy tail=TailStrategy::Auto)
Split two dimensions at once by the given factors, and then reorder the resulting dimensions to be xi...
void specialize_fail(const std::string &message)
Add a specialization to a Func that always terminates execution with a call to halide_error().
Func & memoize(const EvictionKey &eviction_key=EvictionKey())
Use the halide_memoization_cache_...
void compile_to_assembly(const std::string &filename, const std::vector< Argument > &, const std::string &fn_name, const Target &target=get_target_from_environment())
Statically compile this function to text assembly equivalent to the object file generated by compile_...
Func & gpu_tile(const VarOrRVar &x, const VarOrRVar &y, const VarOrRVar &z, const VarOrRVar &tx, const VarOrRVar &ty, const VarOrRVar &tz, const Expr &x_size, const Expr &y_size, const Expr &z_size, TailStrategy tail=TailStrategy::Auto, DeviceAPI device_api=DeviceAPI::Default_GPU)
Func & allow_race_conditions()
Specify that race conditions are permitted for this Func, which enables parallelizing over RVars even...
bool has_update_definition() const
Does this function have at least one update definition?
void compile_jit(const Target &target=get_jit_target_from_environment())
Eagerly jit compile the function to machine code.
Func()
Declare a new undefined function with an automatically-generated unique name.
Func & async()
Produce this Func asynchronously in a separate thread.
void compile_to_bitcode(const std::string &filename, const std::vector< Argument > &, const Target &target=get_target_from_environment())
void realize(Pipeline::RealizationArg outputs, const Target &target=Target(), const ParamMap &param_map=ParamMap::empty_map())
Evaluate this function into an existing allocated buffer or buffers.
void set_custom_trace(int(*trace_fn)(void *, const halide_trace_event_t *))
Set custom routines to call when tracing is enabled.
Func & gpu(const VarOrRVar &block_x, const VarOrRVar &block_y, const VarOrRVar &block_z, const VarOrRVar &thread_x, const VarOrRVar &thread_y, const VarOrRVar &thread_z, DeviceAPI device_api=DeviceAPI::Default_GPU)
Func & gpu_threads(const VarOrRVar &thread_x, const VarOrRVar &thread_y, const VarOrRVar &thread_z, DeviceAPI device_api=DeviceAPI::Default_GPU)
Func & compute_root()
Compute all of this function once ahead of time.
Func & tile(const std::vector< VarOrRVar > &previous, const std::vector< VarOrRVar > &inners, const std::vector< Expr > &factors, TailStrategy tail=TailStrategy::Auto)
Generalized tiling, reusing the previous names as the outer names.
Func & gpu(const VarOrRVar &block_x, const VarOrRVar &thread_x, DeviceAPI device_api=DeviceAPI::Default_GPU)
Tell Halide that the following dimensions correspond to GPU block indices and thread indices.
Func & compute_with(const Stage &s, const VarOrRVar &var, const std::vector< std::pair< VarOrRVar, LoopAlignStrategy >> &align)
Schedule the iteration over the initial definition of this function to be fused with another stage 's...
void compile_to_lowered_stmt(const std::string &filename, const std::vector< Argument > &args, StmtOutputFormat fmt=Text, const Target &target=get_target_from_environment())
Write out an internal representation of lowered code.
void compile_to_c(const std::string &filename, const std::vector< Argument > &, const std::string &fn_name="", const Target &target=get_target_from_environment())
Statically compile this function to C source code.
Func & fuse(const VarOrRVar &inner, const VarOrRVar &outer, const VarOrRVar &fused)
Join two dimensions into a single fused dimenion.
Func & fold_storage(const Var &dim, const Expr &extent, bool fold_forward=true)
Store realizations of this function in a circular buffer of a given extent.
Func & store_at(LoopLevel loop_level)
Equivalent to the version of store_at that takes a Var, but schedules storage at a given LoopLevel.
Stage update(int idx=0)
Get a handle on an update step for the purposes of scheduling it.
Func & reorder_storage(const Var &x, const Var &y)
HALIDE_NO_USER_CODE_INLINE std::enable_if< Internal::all_are_convertible< Expr, Args... >::value, FuncRef >::type operator()(const Expr &x, Args &&...args) const
Definition: Func.h:1313
bool defined() const
Does this function have at least a pure definition.
Func & compute_at(LoopLevel loop_level)
Schedule a function to be computed within the iteration over a given LoopLevel.
const Internal::StageSchedule & get_schedule() const
Return the current StageSchedule associated with this initial Stage of this Func.
Definition: Func.h:2456
Func & gpu_blocks(const VarOrRVar &block_x, DeviceAPI device_api=DeviceAPI::Default_GPU)
Tell Halide that the following dimensions correspond to GPU block indices.
Func & store_at(const Func &f, const Var &var)
Allocate storage for this function within f's loop over var.
Func copy_to_host()
Declare that this function should be implemented by a call to halide_buffer_copy with a NULL target d...
Func & split(const VarOrRVar &old, const VarOrRVar &outer, const VarOrRVar &inner, const Expr &factor, TailStrategy tail=TailStrategy::Auto)
Split a dimension into inner and outer subdimensions with the given names, where the inner dimension ...
Func & compute_with(LoopLevel loop_level, const std::vector< std::pair< VarOrRVar, LoopAlignStrategy >> &align)
std::vector< Argument > infer_arguments() const
Infer the arguments to the Func, sorted into a canonical order: all buffers (sorted alphabetically by...
void compile_to_header(const std::string &filename, const std::vector< Argument > &, const std::string &fn_name="", const Target &target=get_target_from_environment())
Emit a header file with the given filename for this function.
std::vector< Var > args() const
Get the pure arguments.
Func(const Expr &e)
Declare a new function with an automatically-generated unique name, and define it to return the given...
Func & add_trace_tag(const std::string &trace_tag)
Add a string of arbitrary text that will be passed thru to trace inspection code if the Func is reali...
int dimensions() const
The dimensionality (number of arguments) of this function.
HALIDE_NO_USER_CODE_INLINE std::enable_if< Internal::all_are_convertible< Var, Args... >::value, Func & >::type reorder_storage(const Var &x, const Var &y, Args &&...args)
Definition: Func.h:2043
void set_custom_do_par_for(int(*custom_do_par_for)(void *, int(*)(void *, int, uint8_t *), int, int, uint8_t *))
Set a custom parallel for loop launcher.
Func & align_bounds(const Var &var, Expr modulus, Expr remainder=0)
Expand the region computed so that the min coordinates is congruent to 'remainder' modulo 'modulus',...
std::string source_location() const
Get the source location of the pure definition of this Func.
Func & compute_with(LoopLevel loop_level, LoopAlignStrategy align=LoopAlignStrategy::Auto)
HALIDE_NO_USER_CODE_INLINE std::enable_if< Internal::all_are_convertible< VarOrRVar, Args... >::value, Func & >::type reorder(const VarOrRVar &x, const VarOrRVar &y, Args &&...args)
Definition: Func.h:1617
void infer_input_bounds(const std::vector< int32_t > &sizes, const Target &target=get_jit_target_from_environment(), const ParamMap &param_map=ParamMap::empty_map())
For a given size of output, or a given output buffer, determine the bounds required of all unbound Im...
Func & store_root()
Equivalent to Func::store_at, but schedules storage outside the outermost loop.
int outputs() const
Get the number of outputs of this Func.
void set_custom_allocator(void *(*malloc)(void *, size_t), void(*free)(void *, void *))
Set a custom malloc and free for halide to use.
Tuple update_values(int idx=0) const
Get the right-hand-side of an update definition for functions that returns multiple values.
void compile_to_bitcode(const std::string &filename, const std::vector< Argument > &, const std::string &fn_name, const Target &target=get_target_from_environment())
Statically compile this function to llvm bitcode, with the given filename (which should probably end ...
int num_update_definitions() const
How many update definitions does this function have?
Func & rename(const VarOrRVar &old_name, const VarOrRVar &new_name)
Rename a dimension.
Func & vectorize(const VarOrRVar &var)
Mark a dimension to be computed all-at-once as a single vector.
Func & tile(const std::vector< VarOrRVar > &previous, const std::vector< VarOrRVar > &outers, const std::vector< VarOrRVar > &inners, const std::vector< Expr > &factors, const std::vector< TailStrategy > &tails)
A more general form of tile, which defines tiles of any dimensionality.
Func & bound_extent(const Var &var, Expr extent)
Bound the extent of a Func's realization, but not its min.
Func & trace_stores()
Trace all stores to the buffer backing this Func by emitting calls to halide_trace.
Func & set_estimates(const Region &estimates)
Set (min, extent) estimates for all dimensions in the Func at once; this is equivalent to calling set...
Stage specialize(const Expr &condition)
Specialize a Func.
Func & compute_at(const Func &f, const Var &var)
Compute this function as needed for each unique value of the given var for the given calling function...
void set_custom_do_task(int(*custom_do_task)(void *, int(*)(void *, int, uint8_t *), int, uint8_t *))
Set a custom task handler to be called by the parallel for loop.
Func & tile(const std::vector< VarOrRVar > &previous, const std::vector< VarOrRVar > &outers, const std::vector< VarOrRVar > &inners, const std::vector< Expr > &factors, TailStrategy tail=TailStrategy::Auto)
The generalized tile, with a single tail strategy to apply to all vars.
Func & reorder_storage(const std::vector< Var > &dims)
Specify how the storage for the function is laid out.
Func & compute_at(const Func &f, const RVar &var)
Schedule a function to be computed within the iteration over some dimension of an update domain.
Func & gpu_tile(const VarOrRVar &x, const VarOrRVar &bx, const VarOrRVar &tx, const Expr &x_size, TailStrategy tail=TailStrategy::Auto, DeviceAPI device_api=DeviceAPI::Default_GPU)
Short-hand for tiling a domain and mapping the tile indices to GPU block indices and the coordinates ...
const std::vector< Expr > & update_args(int idx=0) const
Get the left-hand-side of the update definition.
Func & gpu_blocks(const VarOrRVar &block_x, const VarOrRVar &block_y, DeviceAPI device_api=DeviceAPI::Default_GPU)
Func & store_at(const Func &f, const RVar &var)
Equivalent to the version of store_at that takes a Var, but schedules storage within the loop over a ...
Realization realize(std::vector< int32_t > sizes={}, const Target &target=Target(), const ParamMap &param_map=ParamMap::empty_map())
Evaluate this function over some rectangular domain and return the resulting buffer or buffers.
void define_extern(const std::string &function_name, const std::vector< ExternFuncArgument > &params, const std::vector< Type > &types, const std::vector< Var > &arguments, NameMangling mangling=NameMangling::Default, DeviceAPI device_api=DeviceAPI::Host)
Func & parallel(const VarOrRVar &var, const Expr &task_size, TailStrategy tail=TailStrategy::Auto)
Split a dimension by the given task_size, and the parallelize the outer dimension.
Expr value() const
The right-hand-side value of the pure definition of this function.
Func & tile(const VarOrRVar &x, const VarOrRVar &y, const VarOrRVar &xi, const VarOrRVar &yi, const Expr &xfactor, const Expr &yfactor, TailStrategy tail=TailStrategy::Auto)
A shorter form of tile, which reuses the old variable names as the new outer dimensions.
void set_error_handler(void(*handler)(void *, const char *))
Set the error handler function that be called in the case of runtime errors during halide pipelines.
Func & gpu_tile(const VarOrRVar &x, const VarOrRVar &tx, const Expr &x_size, TailStrategy tail=TailStrategy::Auto, DeviceAPI device_api=DeviceAPI::Default_GPU)
Func clone_in(const std::vector< Func > &fs)
Module compile_to_module(const std::vector< Argument > &args, const std::string &fn_name="", const Target &target=get_target_from_environment())
Store an internal representation of lowered code as a self contained Module suitable for further comp...
void define_extern(const std::string &function_name, const std::vector< ExternFuncArgument > &params, const std::vector< Type > &types, int dimensionality, NameMangling mangling=NameMangling::Default, DeviceAPI device_api=DeviceAPI::Host)
Definition: Func.h:1243
void set_custom_print(void(*handler)(void *, const char *))
Set the function called to print messages from the runtime.
Func in()
Create and return a global identity wrapper, which wraps all calls to this Func by any other Func.
Func & vectorize(const VarOrRVar &var, const Expr &factor, TailStrategy tail=TailStrategy::Auto)
Split a dimension by the given factor, then vectorize the inner dimension.
OutputImageParam output_buffer() const
Get a handle on the output buffer for this Func.
Expr update_value(int idx=0) const
Get the right-hand-side of an update definition.
Func & bound(const Var &var, Expr min, Expr extent)
Statically declare that the range over which a function should be evaluated is given by the second an...
void compile_to_llvm_assembly(const std::string &filename, const std::vector< Argument > &, const Target &target=get_target_from_environment())
Func & gpu_threads(const VarOrRVar &thread_x, const VarOrRVar &thread_y, DeviceAPI device_api=DeviceAPI::Default_GPU)
void add_custom_lowering_pass(T *pass)
Add a custom pass to be used during lowering.
Definition: Func.h:1130
Func in(const std::vector< Func > &fs)
Create and return an identity wrapper shared by all the Funcs in 'fs'.
void compile_to(const std::map< Output, std::string > &output_files, const std::vector< Argument > &args, const std::string &fn_name, const Target &target=get_target_from_environment())
Compile and generate multiple target files with single call.
Func & gpu(const VarOrRVar &block_x, const VarOrRVar &block_y, const VarOrRVar &thread_x, const VarOrRVar &thread_y, DeviceAPI device_api=DeviceAPI::Default_GPU)
Func & parallel(const VarOrRVar &var)
Mark a dimension to be traversed in parallel.
Func & serial(const VarOrRVar &var)
Mark a dimension to be traversed serially.
const Internal::JITHandlers & jit_handlers()
Get a struct containing the currently set custom functions used by JIT.
const std::string & name() const
The name of this function, either given during construction, or automatically generated.
void define_extern(const std::string &function_name, const std::vector< ExternFuncArgument > &params, Type t, int dimensionality, NameMangling mangling=NameMangling::Default, DeviceAPI device_api=DeviceAPI::Host)
Add an extern definition for this Func.
Definition: Func.h:1225
Func & align_storage(const Var &dim, const Expr &alignment)
Pad the storage extent of a particular dimension of realizations of this function up to be a multiple...
void compile_to_file(const std::string &filename_prefix, const std::vector< Argument > &args, const std::string &fn_name="", const Target &target=get_target_from_environment())
Compile to object file and header pair, with the given arguments.
Func & prefetch(const T &image, VarOrRVar var, Expr offset=1, PrefetchBoundStrategy strategy=PrefetchBoundStrategy::GuardWithIf)
Definition: Func.h:2017
Func & gpu_threads(const VarOrRVar &thread_x, DeviceAPI device_api=DeviceAPI::Default_GPU)
Tell Halide that the following dimensions correspond to GPU thread indices.
void add_custom_lowering_pass(Internal::IRMutator *pass, std::function< void()> deleter)
Add a custom pass to be used during lowering, with the function that will be called to delete it also...
void clear_custom_lowering_passes()
Remove all previously-set custom lowering passes.
void compile_to_llvm_assembly(const std::string &filename, const std::vector< Argument > &, const std::string &fn_name, const Target &target=get_target_from_environment())
Statically compile this function to llvm assembly, with the given filename (which should probably end...
void compile_to_multitarget_static_library(const std::string &filename_prefix, const std::vector< Argument > &args, const std::vector< Target > &targets)
Compile to static-library file and header pair once for each target; each resulting function will be ...
Func & gpu_lanes(const VarOrRVar &thread_x, DeviceAPI device_api=DeviceAPI::Default_GPU)
The given dimension corresponds to the lanes in a GPU warp.
std::vector< OutputImageParam > output_buffers() const
Func & gpu_tile(const VarOrRVar &x, const VarOrRVar &y, const VarOrRVar &z, const VarOrRVar &bx, const VarOrRVar &by, const VarOrRVar &bz, const VarOrRVar &tx, const VarOrRVar &ty, const VarOrRVar &tz, const Expr &x_size, const Expr &y_size, const Expr &z_size, TailStrategy tail=TailStrategy::Auto, DeviceAPI device_api=DeviceAPI::Default_GPU)
Func & store_in(MemoryType memory_type)
Set the type of memory this Func should be stored in.
HALIDE_NO_USER_CODE_INLINE Func(Buffer< T > &im)
Construct a new Func to wrap a Buffer.
Definition: Func.h:727
void compile_to_assembly(const std::string &filename, const std::vector< Argument > &, const Target &target=get_target_from_environment())
Func clone_in(const Func &f)
Similar to Func::in; however, instead of replacing the call to this Func with an identity Func that r...
std::vector< RVar > rvars(int idx=0) const
Get the RVars of the reduction domain for an update definition, if there is one.
Func & gpu_single_thread(DeviceAPI device_api=DeviceAPI::Default_GPU)
Tell Halide to run this stage using a single gpu thread and block.
Func(Internal::Function f)
Construct a new Func to wrap an existing, already-define Function object.
void compile_to_object(const std::string &filename, const std::vector< Argument > &, const std::string &fn_name, const Target &target=get_target_from_environment())
Statically compile this function to an object file, with the given filename (which should probably en...
const std::string & extern_function_name() const
Get the name of the extern function called for an extern definition.
Func & prefetch(const Internal::Parameter &param, const VarOrRVar &var, Expr offset=1, PrefetchBoundStrategy strategy=PrefetchBoundStrategy::GuardWithIf)
Func & compute_with(const Stage &s, const VarOrRVar &var, LoopAlignStrategy align=LoopAlignStrategy::Auto)
Func & trace_realizations()
Trace all realizations of this Func by emitting calls to halide_trace.
Tuple values() const
The values returned by this function.
Func & gpu_tile(const VarOrRVar &x, const VarOrRVar &y, const VarOrRVar &bx, const VarOrRVar &by, const VarOrRVar &tx, const VarOrRVar &ty, const Expr &x_size, const Expr &y_size, TailStrategy tail=TailStrategy::Auto, DeviceAPI device_api=DeviceAPI::Default_GPU)
Func & compute_inline()
Aggressively inline all uses of this function.
const std::vector< Type > & output_types() const
Get the types of the outputs of this Func.
Func copy_to_device(DeviceAPI d=DeviceAPI::Default_GPU)
Declare that this function should be implemented by a call to halide_buffer_copy with the given targe...
Func & gpu_tile(const VarOrRVar &x, const VarOrRVar &y, const VarOrRVar &tx, const VarOrRVar &ty, const Expr &x_size, const Expr &y_size, TailStrategy tail=TailStrategy::Auto, DeviceAPI device_api=DeviceAPI::Default_GPU)
void compile_to_object(const std::string &filename, const std::vector< Argument > &, const Target &target=get_target_from_environment())
void define_extern(const std::string &function_name, const std::vector< ExternFuncArgument > &params, Type t, const std::vector< Var > &arguments, NameMangling mangling=NameMangling::Default, DeviceAPI device_api=DeviceAPI::Host)
Definition: Func.h:1253
Func & reorder(const std::vector< VarOrRVar > &vars)
Reorder variables to have the given nesting order, from innermost out.
Func & atomic(bool override_associativity_test=false)
Issue atomic updates for this Func.
const std::vector< CustomLoweringPass > & custom_lowering_passes()
Get the custom lowering passes.
void debug_to_file(const std::string &filename)
When this function is compiled, include code that dumps its values to a file after it is realized,...
Func & gpu_blocks(const VarOrRVar &block_x, const VarOrRVar &block_y, const VarOrRVar &block_z, DeviceAPI device_api=DeviceAPI::Default_GPU)
Func in(const Func &f)
Creates and returns a new identity Func that wraps this Func.
void compile_to_static_library(const std::string &filename_prefix, const std::vector< Argument > &args, const std::string &fn_name="", const Target &target=get_target_from_environment())
Compile to static-library file and header pair, with the given arguments.
Func & set_estimate(const Var &var, const Expr &min, const Expr &extent)
Statically declare the range over which the function will be evaluated in the general case.
Func & unroll(const VarOrRVar &var, const Expr &factor, TailStrategy tail=TailStrategy::Auto)
Split a dimension by the given factor, then unroll the inner dimension.
void infer_input_bounds(Pipeline::RealizationArg outputs, const Target &target=get_jit_target_from_environment(), const ParamMap &param_map=ParamMap::empty_map())
Func & trace_loads()
Trace all loads from this Func by emitting calls to halide_trace.
FuncRef operator()(std::vector< Var >) const
Construct either the left-hand-side of a definition, or a call to a functions that happens to only co...
void define_extern(const std::string &function_name, const std::vector< ExternFuncArgument > &params, const std::vector< Type > &types, int dimensionality, NameMangling mangling)
Definition: Func.h:1235
A fragment of front-end syntax of the form f(x, y, z), where x, y, z are Vars or Exprs.
Definition: Func.h:472
Stage operator*=(const FuncRef &)
FuncTupleElementRef operator[](int) const
When a FuncRef refers to a function that provides multiple outputs, you can access each output as an ...
Stage operator-=(const FuncRef &)
size_t size() const
How many outputs does the function this refers to produce.
Internal::Function function() const
What function is this calling?
Definition: Func.h:569
Stage operator+=(Expr)
Define a stage that adds the given expression to this Func.
Stage operator-=(Expr)
Define a stage that adds the negative of the given expression to this Func.
Stage operator*=(Expr)
Define a stage that multiplies this Func by the given expression.
Stage operator-=(const Tuple &)
Stage operator/=(Expr)
Define a stage that divides this Func by the given expression.
Stage operator+=(const FuncRef &)
Stage operator=(const Expr &)
Use this as the left-hand-side of a definition or an update definition (see RDom).
Stage operator=(const FuncRef &)
FuncRef(Internal::Function, const std::vector< Var > &, int placeholder_pos=-1, int count=0)
Stage operator+=(const Tuple &)
FuncRef(const Internal::Function &, const std::vector< Expr > &, int placeholder_pos=-1, int count=0)
Stage operator/=(const FuncRef &)
Stage operator*=(const Tuple &)
Stage operator/=(const Tuple &)
Stage operator=(const Tuple &)
Use this as the left-hand-side of a definition or an update definition for a Func with multiple outpu...
A fragment of front-end syntax of the form f(x, y, z)[index], where x, y, z are Vars or Exprs.
Definition: Func.h:591
int index() const
Return index to the function outputs.
Definition: Func.h:655
Stage operator+=(const Expr &e)
Define a stage that adds the given expression to Tuple component 'idx' of this Func.
Stage operator*=(const Expr &e)
Define a stage that multiplies Tuple component 'idx' of this Func by the given expression.
Stage operator/=(const Expr &e)
Define a stage that divides Tuple component 'idx' of this Func by the given expression.
Stage operator=(const Expr &e)
Use this as the left-hand-side of an update definition of Tuple component 'idx' of a Func (see RDom).
Stage operator=(const FuncRef &e)
Stage operator-=(const Expr &e)
Define a stage that adds the negative of the given expression to Tuple component 'idx' of this Func.
FuncTupleElementRef(const FuncRef &ref, const std::vector< Expr > &args, int idx)
An Image parameter to a halide pipeline.
Definition: ImageParam.h:23
A Function definition which can either represent a init or an update definition.
Definition: Definition.h:38
const StageSchedule & schedule() const
Get the default (no-specialization) stage-specific schedule associated with this definition.
const std::vector< Expr > & args() const
Get the default (no-specialization) arguments (left-hand-side) of the definition.
bool defined() const
Definition objects are nullable.
A reference-counted handle to Halide's internal representation of a function.
Definition: Function.h:38
A base class for passes over the IR which modify it (e.g.
Definition: IRMutator.h:26
A reference-counted handle to a parameter to a halide pipeline.
Definition: Parameter.h:29
A schedule for a single stage of a Halide pipeline.
Definition: Schedule.h:620
bool & touched()
This flag is set to true if the dims list has been manipulated by the user (or if a ScheduleHandle wa...
A reference to a site in a Halide statement at the top of the body of a particular for loop.
Definition: Schedule.h:153
A halide module.
Definition: Module.h:135
A handle on the output buffer of a pipeline.
static const ParamMap & empty_map()
A const ref to an empty ParamMap.
Definition: ParamMap.h:104
A class representing a Halide pipeline.
Definition: Pipeline.h:97
A multi-dimensional domain over which to iterate.
Definition: RDom.h:193
A reduction variable represents a single dimension of a reduction domain (RDom).
Definition: RDom.h:29
const std::string & name() const
The name of this reduction variable.
A Realization is a vector of references to existing Buffer objects.
Definition: Realization.h:21
A single definition of a Func.
Definition: Func.h:70
std::string name() const
Return the name of this stage, e.g.
Stage & rename(const VarOrRVar &old_name, const VarOrRVar &new_name)
Stage & gpu_threads(const VarOrRVar &thread_x, const VarOrRVar &thread_y, DeviceAPI device_api=DeviceAPI::Default_GPU)
Stage & gpu(const VarOrRVar &block_x, const VarOrRVar &block_y, const VarOrRVar &block_z, const VarOrRVar &thread_x, const VarOrRVar &thread_y, const VarOrRVar &thread_z, DeviceAPI device_api=DeviceAPI::Default_GPU)
Stage & gpu(const VarOrRVar &block_x, const VarOrRVar &block_y, const VarOrRVar &thread_x, const VarOrRVar &thread_y, DeviceAPI device_api=DeviceAPI::Default_GPU)
Stage & tile(const std::vector< VarOrRVar > &previous, const std::vector< VarOrRVar > &outers, const std::vector< VarOrRVar > &inners, const std::vector< Expr > &factors, TailStrategy tail=TailStrategy::Auto)
Stage & gpu_tile(const VarOrRVar &x, const VarOrRVar &tx, const Expr &x_size, TailStrategy tail=TailStrategy::Auto, DeviceAPI device_api=DeviceAPI::Default_GPU)
HALIDE_NO_USER_CODE_INLINE std::enable_if< Internal::all_are_convertible< VarOrRVar, Args... >::value, Stage & >::type reorder(const VarOrRVar &x, const VarOrRVar &y, Args &&...args)
Definition: Func.h:379
Stage & gpu(const VarOrRVar &block_x, const VarOrRVar &thread_x, DeviceAPI device_api=DeviceAPI::Default_GPU)
Stage & gpu_tile(const VarOrRVar &x, const VarOrRVar &y, const VarOrRVar &bx, const VarOrRVar &by, const VarOrRVar &tx, const VarOrRVar &ty, const Expr &x_size, const Expr &y_size, TailStrategy tail=TailStrategy::Auto, DeviceAPI device_api=DeviceAPI::Default_GPU)
Stage & hexagon(const VarOrRVar &x=Var::outermost())
Func rfactor(const RVar &r, const Var &v)
Stage & compute_with(const Stage &s, const VarOrRVar &var, LoopAlignStrategy align=LoopAlignStrategy::Auto)
Stage & vectorize(const VarOrRVar &var)
Stage & gpu_single_thread(DeviceAPI device_api=DeviceAPI::Default_GPU)
Stage & compute_with(LoopLevel loop_level, LoopAlignStrategy align=LoopAlignStrategy::Auto)
Stage & unroll(const VarOrRVar &var)
Stage & parallel(const VarOrRVar &var)
Stage & allow_race_conditions()
Stage & serial(const VarOrRVar &var)
Stage & gpu_tile(const VarOrRVar &x, const VarOrRVar &y, const VarOrRVar &z, const VarOrRVar &bx, const VarOrRVar &by, const VarOrRVar &bz, const VarOrRVar &tx, const VarOrRVar &ty, const VarOrRVar &tz, const Expr &x_size, const Expr &y_size, const Expr &z_size, TailStrategy tail=TailStrategy::Auto, DeviceAPI device_api=DeviceAPI::Default_GPU)
Stage & gpu_tile(const VarOrRVar &x, const VarOrRVar &bx, const VarOrRVar &tx, const Expr &x_size, TailStrategy tail=TailStrategy::Auto, DeviceAPI device_api=DeviceAPI::Default_GPU)
Stage & prefetch(const T &image, VarOrRVar var, Expr offset=1, PrefetchBoundStrategy strategy=PrefetchBoundStrategy::GuardWithIf)
Definition: Func.h:449
Stage & tile(const std::vector< VarOrRVar > &previous, const std::vector< VarOrRVar > &outers, const std::vector< VarOrRVar > &inners, const std::vector< Expr > &factors, const std::vector< TailStrategy > &tails)
Stage specialize(const Expr &condition)
Stage & compute_with(LoopLevel loop_level, const std::vector< std::pair< VarOrRVar, LoopAlignStrategy >> &align)
Schedule the iteration over this stage to be fused with another stage 's' from outermost loop to a gi...
Stage & tile(const VarOrRVar &x, const VarOrRVar &y, const VarOrRVar &xo, const VarOrRVar &yo, const VarOrRVar &xi, const VarOrRVar &yi, const Expr &xfactor, const Expr &yfactor, TailStrategy tail=TailStrategy::Auto)
Stage & split(const VarOrRVar &old, const VarOrRVar &outer, const VarOrRVar &inner, const Expr &factor, TailStrategy tail=TailStrategy::Auto)
Scheduling calls that control how the domain of this stage is traversed.
Stage & fuse(const VarOrRVar &inner, const VarOrRVar &outer, const VarOrRVar &fused)
Stage(Internal::Function f, Internal::Definition d, size_t stage_index)
Definition: Func.h:94
Stage & vectorize(const VarOrRVar &var, const Expr &factor, TailStrategy tail=TailStrategy::Auto)
Func rfactor(std::vector< std::pair< RVar, Var >> preserved)
Calling rfactor() on an associative update definition a Func will split the update into an intermedia...
Stage & parallel(const VarOrRVar &var, const Expr &task_size, TailStrategy tail=TailStrategy::Auto)
Stage & gpu_blocks(const VarOrRVar &block_x, const VarOrRVar &block_y, const VarOrRVar &block_z, DeviceAPI device_api=DeviceAPI::Default_GPU)
const Internal::StageSchedule & get_schedule() const
Return the current StageSchedule associated with this Stage.
Definition: Func.h:108
Stage & gpu_tile(const VarOrRVar &x, const VarOrRVar &y, const VarOrRVar &z, const VarOrRVar &tx, const VarOrRVar &ty, const VarOrRVar &tz, const Expr &x_size, const Expr &y_size, const Expr &z_size, TailStrategy tail=TailStrategy::Auto, DeviceAPI device_api=DeviceAPI::Default_GPU)
Stage & reorder(const std::vector< VarOrRVar > &vars)
Stage & gpu_blocks(const VarOrRVar &block_x, DeviceAPI device_api=DeviceAPI::Default_GPU)
Stage & gpu_blocks(const VarOrRVar &block_x, const VarOrRVar &block_y, DeviceAPI device_api=DeviceAPI::Default_GPU)
Stage & tile(const std::vector< VarOrRVar > &previous, const std::vector< VarOrRVar > &inners, const std::vector< Expr > &factors, TailStrategy tail=TailStrategy::Auto)
void specialize_fail(const std::string &message)
Stage & gpu_threads(const VarOrRVar &thread_x, const VarOrRVar &thread_y, const VarOrRVar &thread_z, DeviceAPI device_api=DeviceAPI::Default_GPU)
Stage & tile(const VarOrRVar &x, const VarOrRVar &y, const VarOrRVar &xi, const VarOrRVar &yi, const Expr &xfactor, const Expr &yfactor, TailStrategy tail=TailStrategy::Auto)
Stage & compute_with(const Stage &s, const VarOrRVar &var, const std::vector< std::pair< VarOrRVar, LoopAlignStrategy >> &align)
Stage & unroll(const VarOrRVar &var, const Expr &factor, TailStrategy tail=TailStrategy::Auto)
Stage & prefetch(const Func &f, const VarOrRVar &var, Expr offset=1, PrefetchBoundStrategy strategy=PrefetchBoundStrategy::GuardWithIf)
Stage & atomic(bool override_associativity_test=false)
std::string source_location() const
Attempt to get the source file and line where this stage was defined by parsing the process's own deb...
Stage & gpu_threads(const VarOrRVar &thread_x, DeviceAPI device_api=DeviceAPI::Default_GPU)
Stage & gpu_lanes(const VarOrRVar &thread_x, DeviceAPI device_api=DeviceAPI::Default_GPU)
Stage & gpu_tile(const VarOrRVar &x, const VarOrRVar &y, const VarOrRVar &tx, const VarOrRVar &ty, const Expr &x_size, const Expr &y_size, TailStrategy tail=TailStrategy::Auto, DeviceAPI device_api=DeviceAPI::Default_GPU)
std::string dump_argument_list() const
Return a string describing the current var list taking into account all the splits,...
Stage & prefetch(const Internal::Parameter &param, const VarOrRVar &var, Expr offset=1, PrefetchBoundStrategy strategy=PrefetchBoundStrategy::GuardWithIf)
Create a small array of Exprs for defining and calling functions with multiple outputs.
Definition: Tuple.h:18
A Halide variable, to be used when defining functions.
Definition: Var.h:19
const std::string & name() const
Get the name of a Var.
static Var outermost()
A Var that represents the location outside the outermost loop.
Definition: Var.h:163
void schedule_scalar(Func f)
Definition: Func.h:2520
void assign_results(Realization &r, int idx, Last last)
Definition: Func.h:2479
void check_types(const Tuple &t, int idx)
Definition: Func.h:2464
ForType
An enum describing a type of loop traversal.
Definition: Expr.h:395
std::vector< Var > make_argument_list(int dimensionality)
Make a list of unique arguments for definitions with unnamed arguments.
WEAK halide_do_task_t custom_do_task
WEAK halide_do_par_for_t custom_do_par_for
This file defines the class FunctionDAG, which is our representation of a Halide pipeline,...
@ Internal
Not visible externally, similar to 'static' linkage in C.
HALIDE_NO_USER_CODE_INLINE T evaluate(const Expr &e)
JIT-Compile and run enough code to evaluate a Halide expression.
Definition: Func.h:2496
PrefetchBoundStrategy
Different ways to handle accesses outside the original extents in a prefetch.
@ GuardWithIf
Guard the prefetch with if-guards that ignores the prefetch if any of the prefetched region ever goes...
HALIDE_NO_USER_CODE_INLINE T evaluate_may_gpu(const Expr &e)
JIT-Compile and run enough code to evaluate a Halide expression.
Definition: Func.h:2538
TailStrategy
Different ways to handle a tail case in a split when the factor does not provably divide the extent.
Definition: Schedule.h:32
@ Auto
For pure definitions use ShiftInwards.
LoopAlignStrategy
Different ways to handle the case when the start/end of the loops of stages computed with (fused) are...
Definition: Schedule.h:87
@ Auto
By default, LoopAlignStrategy is set to NoAlign.
Expr min(const FuncRef &a, const FuncRef &b)
Explicit overloads of min and max for FuncRef.
Definition: Func.h:578
NameMangling
An enum to specify calling convention for extern stages.
Definition: Function.h:24
@ Default
Match whatever is specified in the Target.
Target get_jit_target_from_environment()
Return the target that Halide will use for jit-compilation.
DeviceAPI
An enum describing a type of device API.
Definition: DeviceAPI.h:15
@ Host
Used to denote for loops that run on the same device as the containing code.
Target get_target_from_environment()
Return the target that Halide will use.
StmtOutputFormat
Used to determine if the output printed to file should be as a normal string or as an HTML file which...
Definition: Pipeline.h:61
@ Text
Definition: Pipeline.h:62
Stage ScheduleHandle
Definition: Func.h:463
std::vector< Range > Region
A multi-dimensional box.
Definition: Expr.h:343
Expr max(const FuncRef &a, const FuncRef &b)
Definition: Func.h:581
MemoryType
An enum describing different address spaces to be used with Func::store_in.
Definition: Expr.h:346
void * malloc(size_t)
unsigned __INT8_TYPE__ uint8_t
void free(void *)
A fragment of Halide syntax.
Definition: Expr.h:256
HALIDE_ALWAYS_INLINE Type type() const
Get the type of this expression node.
Definition: Expr.h:320
An argument to an extern-defined Func.
A struct representing a target machine and os to generate code for.
Definition: Target.h:19
bool has_gpu_feature() const
Is a fully feature GPU compute runtime enabled? I.e.
bool has_feature(Feature f) const
Types in the halide type system.
Definition: Type.h:269
A class that can represent Vars or RVars.
Definition: Func.h:30
bool is_rvar
Definition: Func.h:58
VarOrRVar(const Var &v)
Definition: Func.h:34
VarOrRVar(const RVar &r)
Definition: Func.h:37
const std::string & name() const
Definition: Func.h:48
VarOrRVar(const std::string &n, bool r)
Definition: Func.h:31
VarOrRVar(const ImplicitVar< N > &u)
Definition: Func.h:44
VarOrRVar(const RDom &r)
Definition: Func.h:40