summaryrefslogtreecommitdiff
path: root/mlir/lib/Debug/DebuggerExecutionContextHook.cpp
blob: 6cbd7f380c07f20c0e57a1eccf34adcd98f9572a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
//===- DebuggerExecutionContextHook.cpp - Debugger Support ----------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "mlir/Debug/DebuggerExecutionContextHook.h"

#include "mlir/Debug/BreakpointManagers/FileLineColLocBreakpointManager.h"
#include "mlir/Debug/BreakpointManagers/TagBreakpointManager.h"

using namespace mlir;
using namespace mlir::tracing;

namespace {
/// This structure tracks the state of the interactive debugger.
struct DebuggerState {
  /// This variable keeps track of the current control option. This is set by
  /// the debugger when control is handed over to it.
  ExecutionContext::Control debuggerControl = ExecutionContext::Apply;

  /// The breakpoint manager that allows the debugger to set breakpoints on
  /// action tags.
  TagBreakpointManager tagBreakpointManager;

  /// The breakpoint manager that allows the debugger to set breakpoints on
  /// FileLineColLoc locations.
  FileLineColLocBreakpointManager fileLineColLocBreakpointManager;

  /// Map of breakpoint IDs to breakpoint objects.
  DenseMap<unsigned, Breakpoint *> breakpointIdsMap;

  /// The current stack of actiive actions.
  const tracing::ActionActiveStack *actionActiveStack;

  /// This is a "cursor" in the IR, it is used for the debugger to navigate the
  /// IR associated to the actions.
  IRUnit cursor;
};
} // namespace

static DebuggerState &getGlobalDebuggerState() {
  static LLVM_THREAD_LOCAL DebuggerState debuggerState;
  return debuggerState;
}

extern "C" {
void mlirDebuggerSetControl(int controlOption) {
  getGlobalDebuggerState().debuggerControl =
      static_cast<ExecutionContext::Control>(controlOption);
}

void mlirDebuggerPrintContext() {
  DebuggerState &state = getGlobalDebuggerState();
  if (!state.actionActiveStack) {
    llvm::outs() << "No active action.\n";
    return;
  }
  const ArrayRef<IRUnit> &units =
      state.actionActiveStack->getAction().getContextIRUnits();
  llvm::outs() << units.size() << " available IRUnits:\n";
  for (const IRUnit &unit : units) {
    llvm::outs() << "  - ";
    unit.print(
        llvm::outs(),
        OpPrintingFlags().useLocalScope().skipRegions().enableDebugInfo());
    llvm::outs() << "\n";
  }
}

void mlirDebuggerPrintActionBacktrace(bool withContext) {
  DebuggerState &state = getGlobalDebuggerState();
  if (!state.actionActiveStack) {
    llvm::outs() << "No active action.\n";
    return;
  }
  state.actionActiveStack->print(llvm::outs(), withContext);
}

//===----------------------------------------------------------------------===//
// Cursor Management
//===----------------------------------------------------------------------===//

void mlirDebuggerCursorPrint(bool withRegion) {
  auto &state = getGlobalDebuggerState();
  if (!state.cursor) {
    llvm::outs() << "No active MLIR cursor, select from the context first\n";
    return;
  }
  state.cursor.print(llvm::outs(), OpPrintingFlags()
                                       .skipRegions(!withRegion)
                                       .useLocalScope()
                                       .enableDebugInfo());
  llvm::outs() << "\n";
}

void mlirDebuggerCursorSelectIRUnitFromContext(int index) {
  auto &state = getGlobalDebuggerState();
  if (!state.actionActiveStack) {
    llvm::outs() << "No active MLIR Action stack\n";
    return;
  }
  ArrayRef<IRUnit> units =
      state.actionActiveStack->getAction().getContextIRUnits();
  if (index < 0 || index >= static_cast<int>(units.size())) {
    llvm::outs() << "Index invalid, bounds: [0, " << units.size()
                 << "] but got " << index << "\n";
    return;
  }
  state.cursor = units[index];
  state.cursor.print(llvm::outs());
  llvm::outs() << "\n";
}

void mlirDebuggerCursorSelectParentIRUnit() {
  auto &state = getGlobalDebuggerState();
  if (!state.cursor) {
    llvm::outs() << "No active MLIR cursor, select from the context first\n";
    return;
  }
  IRUnit *unit = &state.cursor;
  if (auto *op = unit->dyn_cast<Operation *>()) {
    state.cursor = op->getBlock();
  } else if (auto *region = unit->dyn_cast<Region *>()) {
    state.cursor = region->getParentOp();
  } else if (auto *block = unit->dyn_cast<Block *>()) {
    state.cursor = block->getParent();
  } else {
    llvm::outs() << "Current cursor is not a valid IRUnit";
    return;
  }
  state.cursor.print(llvm::outs());
  llvm::outs() << "\n";
}

void mlirDebuggerCursorSelectChildIRUnit(int index) {
  auto &state = getGlobalDebuggerState();
  if (!state.cursor) {
    llvm::outs() << "No active MLIR cursor, select from the context first\n";
    return;
  }
  IRUnit *unit = &state.cursor;
  if (auto *op = unit->dyn_cast<Operation *>()) {
    if (index < 0 || index >= static_cast<int>(op->getNumRegions())) {
      llvm::outs() << "Index invalid, op has " << op->getNumRegions()
                   << " but got " << index << "\n";
      return;
    }
    state.cursor = &op->getRegion(index);
  } else if (auto *region = unit->dyn_cast<Region *>()) {
    auto block = region->begin();
    int count = 0;
    while (block != region->end() && count != index) {
      ++block;
      ++count;
    }

    if (block == region->end()) {
      llvm::outs() << "Index invalid, region has " << count << " block but got "
                   << index << "\n";
      return;
    }
    state.cursor = &*block;
  } else if (auto *block = unit->dyn_cast<Block *>()) {
    auto op = block->begin();
    int count = 0;
    while (op != block->end() && count != index) {
      ++op;
      ++count;
    }

    if (op == block->end()) {
      llvm::outs() << "Index invalid, block has " << count
                   << "operations but got " << index << "\n";
      return;
    }
    state.cursor = &*op;
  } else {
    llvm::outs() << "Current cursor is not a valid IRUnit";
    return;
  }
  state.cursor.print(llvm::outs());
  llvm::outs() << "\n";
}

void mlirDebuggerCursorSelectPreviousIRUnit() {
  auto &state = getGlobalDebuggerState();
  if (!state.cursor) {
    llvm::outs() << "No active MLIR cursor, select from the context first\n";
    return;
  }
  IRUnit *unit = &state.cursor;
  if (auto *op = unit->dyn_cast<Operation *>()) {
    Operation *previous = op->getPrevNode();
    if (!previous) {
      llvm::outs() << "No previous operation in the current block\n";
      return;
    }
    state.cursor = previous;
  } else if (auto *region = unit->dyn_cast<Region *>()) {
    llvm::outs() << "Has region\n";
    Operation *parent = region->getParentOp();
    if (!parent) {
      llvm::outs() << "No parent operation for the current region\n";
      return;
    }
    if (region->getRegionNumber() == 0) {
      llvm::outs() << "No previous region in the current operation\n";
      return;
    }
    state.cursor =
        &region->getParentOp()->getRegion(region->getRegionNumber() - 1);
  } else if (auto *block = unit->dyn_cast<Block *>()) {
    Block *previous = block->getPrevNode();
    if (!previous) {
      llvm::outs() << "No previous block in the current region\n";
      return;
    }
    state.cursor = previous;
  } else {
    llvm::outs() << "Current cursor is not a valid IRUnit";
    return;
  }
  state.cursor.print(llvm::outs());
  llvm::outs() << "\n";
}

void mlirDebuggerCursorSelectNextIRUnit() {
  auto &state = getGlobalDebuggerState();
  if (!state.cursor) {
    llvm::outs() << "No active MLIR cursor, select from the context first\n";
    return;
  }
  IRUnit *unit = &state.cursor;
  if (auto *op = unit->dyn_cast<Operation *>()) {
    Operation *next = op->getNextNode();
    if (!next) {
      llvm::outs() << "No next operation in the current block\n";
      return;
    }
    state.cursor = next;
  } else if (auto *region = unit->dyn_cast<Region *>()) {
    Operation *parent = region->getParentOp();
    if (!parent) {
      llvm::outs() << "No parent operation for the current region\n";
      return;
    }
    if (region->getRegionNumber() == parent->getNumRegions() - 1) {
      llvm::outs() << "No next region in the current operation\n";
      return;
    }
    state.cursor =
        &region->getParentOp()->getRegion(region->getRegionNumber() + 1);
  } else if (auto *block = unit->dyn_cast<Block *>()) {
    Block *next = block->getNextNode();
    if (!next) {
      llvm::outs() << "No next block in the current region\n";
      return;
    }
    state.cursor = next;
  } else {
    llvm::outs() << "Current cursor is not a valid IRUnit";
    return;
  }
  state.cursor.print(llvm::outs());
  llvm::outs() << "\n";
}

//===----------------------------------------------------------------------===//
// Breakpoint Management
//===----------------------------------------------------------------------===//

void mlirDebuggerEnableBreakpoint(BreakpointHandle breakpoint) {
  reinterpret_cast<Breakpoint *>(breakpoint)->enable();
}

void mlirDebuggerDisableBreakpoint(BreakpointHandle breakpoint) {
  reinterpret_cast<Breakpoint *>(breakpoint)->disable();
}

BreakpointHandle mlirDebuggerAddTagBreakpoint(const char *tag) {
  DebuggerState &state = getGlobalDebuggerState();
  Breakpoint *breakpoint =
      state.tagBreakpointManager.addBreakpoint(StringRef(tag, strlen(tag)));
  int breakpointId = state.breakpointIdsMap.size() + 1;
  state.breakpointIdsMap[breakpointId] = breakpoint;
  return reinterpret_cast<BreakpointHandle>(breakpoint);
}

void mlirDebuggerAddRewritePatternBreakpoint(const char *patternNameInfo) {}

void mlirDebuggerAddFileLineColLocBreakpoint(const char *file, int line,
                                             int col) {
  getGlobalDebuggerState().fileLineColLocBreakpointManager.addBreakpoint(
      StringRef(file, strlen(file)), line, col);
}

} // extern "C"

LLVM_ATTRIBUTE_NOINLINE void mlirDebuggerBreakpointHook() {
  static LLVM_THREAD_LOCAL void *volatile sink;
  sink = (void *)&sink;
}

static void preventLinkerDeadCodeElim() {
  static void *volatile sink;
  static bool initialized = [&]() {
    sink = (void *)mlirDebuggerSetControl;
    sink = (void *)mlirDebuggerEnableBreakpoint;
    sink = (void *)mlirDebuggerDisableBreakpoint;
    sink = (void *)mlirDebuggerPrintContext;
    sink = (void *)mlirDebuggerPrintActionBacktrace;
    sink = (void *)mlirDebuggerCursorPrint;
    sink = (void *)mlirDebuggerCursorSelectIRUnitFromContext;
    sink = (void *)mlirDebuggerCursorSelectParentIRUnit;
    sink = (void *)mlirDebuggerCursorSelectChildIRUnit;
    sink = (void *)mlirDebuggerCursorSelectPreviousIRUnit;
    sink = (void *)mlirDebuggerCursorSelectNextIRUnit;
    sink = (void *)mlirDebuggerAddTagBreakpoint;
    sink = (void *)mlirDebuggerAddRewritePatternBreakpoint;
    sink = (void *)mlirDebuggerAddFileLineColLocBreakpoint;
    sink = (void *)&sink;
    return true;
  }();
  (void)initialized;
}

static tracing::ExecutionContext::Control
debuggerCallBackFunction(const tracing::ActionActiveStack *actionStack) {
  preventLinkerDeadCodeElim();
  // Invoke the breakpoint hook, the debugger is supposed to trap this.
  // The debugger controls the execution from there by invoking
  // `mlirDebuggerSetControl()`.
  auto &state = getGlobalDebuggerState();
  state.actionActiveStack = actionStack;
  getGlobalDebuggerState().debuggerControl = ExecutionContext::Apply;
  actionStack->getAction().print(llvm::outs());
  llvm::outs() << "\n";
  mlirDebuggerBreakpointHook();
  return getGlobalDebuggerState().debuggerControl;
}

namespace {
/// Manage the stack of actions that are currently active.
class DebuggerObserver : public ExecutionContext::Observer {
  void beforeExecute(const ActionActiveStack *action, Breakpoint *breakpoint,
                     bool willExecute) override {
    auto &state = getGlobalDebuggerState();
    state.actionActiveStack = action;
  }
  void afterExecute(const ActionActiveStack *action) override {
    auto &state = getGlobalDebuggerState();
    state.actionActiveStack = action->getParent();
    state.cursor = nullptr;
  }
};
} // namespace

void mlir::setupDebuggerExecutionContextHook(
    tracing::ExecutionContext &executionContext) {
  executionContext.setCallback(debuggerCallBackFunction);
  DebuggerState &state = getGlobalDebuggerState();
  static DebuggerObserver observer;
  executionContext.registerObserver(&observer);
  executionContext.addBreakpointManager(&state.fileLineColLocBreakpointManager);
  executionContext.addBreakpointManager(&state.tagBreakpointManager);
}