OSDN Git Service

621290fdfbdee9ab44066f13bddf5467a2608039
[android-x86/external-mesa.git] / src / gallium / auxiliary / gallivm / lp_bld_debug.cpp
1 /**************************************************************************
2  *
3  * Copyright 2009-2011 VMware, Inc.
4  * All Rights Reserved.
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the
8  * "Software"), to deal in the Software without restriction, including
9  * without limitation the rights to use, copy, modify, merge, publish,
10  * distribute, sub license, and/or sell copies of the Software, and to
11  * permit persons to whom the Software is furnished to do so, subject to
12  * the following conditions:
13  *
14  * The above copyright notice and this permission notice (including the
15  * next paragraph) shall be included in all copies or substantial portions
16  * of the Software.
17  *
18  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
19  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
21  * IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS BE LIABLE FOR
22  * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
23  * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
24  * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25  *
26  **************************************************************************/
27
28 #include <stddef.h>
29
30 #include <llvm-c/Core.h>
31 #include <llvm/Target/TargetMachine.h>
32 #include <llvm/Target/TargetInstrInfo.h>
33 #include <llvm/Support/raw_ostream.h>
34 #include <llvm/Support/Format.h>
35 #include <llvm/Support/MemoryObject.h>
36
37 #include <llvm/Support/TargetRegistry.h>
38 #include <llvm/MC/MCSubtargetInfo.h>
39
40 #include <llvm/Support/Host.h>
41
42 #include <llvm/IR/Module.h>
43
44 #include <llvm/MC/MCDisassembler.h>
45 #include <llvm/MC/MCAsmInfo.h>
46 #include <llvm/MC/MCInst.h>
47 #include <llvm/MC/MCInstPrinter.h>
48 #include <llvm/MC/MCRegisterInfo.h>
49
50 #if HAVE_LLVM >= 0x0303
51 #include <llvm/ADT/OwningPtr.h>
52 #endif
53
54 #if HAVE_LLVM >= 0x0305
55 #include <llvm/MC/MCContext.h>
56 #endif
57
58 #include "util/u_math.h"
59 #include "util/u_debug.h"
60
61 #include "lp_bld_debug.h"
62
63 #ifdef __linux__
64 #include <sys/stat.h>
65 #include <fcntl.h>
66 #endif
67
68
69
70 /**
71  * Check alignment.
72  *
73  * It is important that this check is not implemented as a macro or inlined
74  * function, as the compiler assumptions in respect to alignment of global
75  * and stack variables would often make the check a no op, defeating the
76  * whole purpose of the exercise.
77  */
78 extern "C" boolean
79 lp_check_alignment(const void *ptr, unsigned alignment)
80 {
81    assert(util_is_power_of_two(alignment));
82    return ((uintptr_t)ptr & (alignment - 1)) == 0;
83 }
84
85
86 class raw_debug_ostream :
87    public llvm::raw_ostream
88 {
89 private:
90    uint64_t pos;
91
92 public:
93    raw_debug_ostream() : pos(0) { }
94
95    void write_impl(const char *Ptr, size_t Size);
96
97    uint64_t current_pos() const { return pos; }
98    size_t preferred_buffer_size() const { return 512; }
99 };
100
101
102 void
103 raw_debug_ostream::write_impl(const char *Ptr, size_t Size)
104 {
105    if (Size > 0) {
106       char *lastPtr = (char *)&Ptr[Size];
107       char last = *lastPtr;
108       *lastPtr = 0;
109       _debug_printf("%*s", Size, Ptr);
110       *lastPtr = last;
111       pos += Size;
112    }
113 }
114
115
116 extern "C" const char *
117 lp_get_module_id(LLVMModuleRef module)
118 {
119    return llvm::unwrap(module)->getModuleIdentifier().c_str();
120 }
121
122
123 /**
124  * Same as LLVMDumpValue, but through our debugging channels.
125  */
126 extern "C" void
127 lp_debug_dump_value(LLVMValueRef value)
128 {
129 #if (defined(PIPE_OS_WINDOWS) && !defined(PIPE_CC_MSVC)) || defined(PIPE_OS_EMBDDED)
130    raw_debug_ostream os;
131    llvm::unwrap(value)->print(os);
132    os.flush();
133 #else
134    LLVMDumpValue(value);
135 #endif
136 }
137
138
139 /*
140  * MemoryObject wrapper around a buffer of memory, to be used by MC
141  * disassembler.
142  */
143 class BufferMemoryObject:
144    public llvm::MemoryObject
145 {
146 private:
147    const uint8_t *Bytes;
148    uint64_t Length;
149 public:
150    BufferMemoryObject(const uint8_t *bytes, uint64_t length) :
151       Bytes(bytes), Length(length)
152    {
153    }
154
155    uint64_t getBase() const
156    {
157       return 0;
158    }
159
160    uint64_t getExtent() const
161    {
162       return Length;
163    }
164
165    int readByte(uint64_t addr, uint8_t *byte) const
166    {
167       if (addr > getExtent())
168          return -1;
169       *byte = Bytes[addr];
170       return 0;
171    }
172 };
173
174
175 /*
176  * Disassemble a function, using the LLVM MC disassembler.
177  *
178  * See also:
179  * - http://blog.llvm.org/2010/01/x86-disassembler.html
180  * - http://blog.llvm.org/2010/04/intro-to-llvm-mc-project.html
181  */
182 static size_t
183 disassemble(const void* func, llvm::raw_ostream & Out)
184 {
185    using namespace llvm;
186
187    const uint8_t *bytes = (const uint8_t *)func;
188
189    /*
190     * Limit disassembly to this extent
191     */
192    const uint64_t extent = 96 * 1024;
193
194    uint64_t max_pc = 0;
195
196    /*
197     * Initialize all used objects.
198     */
199
200    std::string Triple = sys::getDefaultTargetTriple();
201
202    std::string Error;
203    const Target *T = TargetRegistry::lookupTarget(Triple, Error);
204
205 #if HAVE_LLVM >= 0x0304
206    OwningPtr<const MCAsmInfo> AsmInfo(T->createMCAsmInfo(*T->createMCRegInfo(Triple), Triple));
207 #else
208    OwningPtr<const MCAsmInfo> AsmInfo(T->createMCAsmInfo(Triple));
209 #endif
210
211    if (!AsmInfo) {
212       Out << "error: no assembly info for target " << Triple << "\n";
213       Out.flush();
214       return 0;
215    }
216
217    unsigned int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
218
219    OwningPtr<const MCRegisterInfo> MRI(T->createMCRegInfo(Triple));
220    if (!MRI) {
221       Out << "error: no register info for target " << Triple.c_str() << "\n";
222       Out.flush();
223       return 0;
224    }
225
226    OwningPtr<const MCInstrInfo> MII(T->createMCInstrInfo());
227    if (!MII) {
228       Out << "error: no instruction info for target " << Triple.c_str() << "\n";
229       Out.flush();
230       return 0;
231    }
232
233 #if HAVE_LLVM >= 0x0305
234    OwningPtr<const MCSubtargetInfo> STI(T->createMCSubtargetInfo(Triple, sys::getHostCPUName(), ""));
235    OwningPtr<MCContext> MCCtx(new MCContext(AsmInfo.get(), MRI.get(), 0));
236    OwningPtr<const MCDisassembler> DisAsm(T->createMCDisassembler(*STI, *MCCtx));
237 #else
238    OwningPtr<const MCSubtargetInfo> STI(T->createMCSubtargetInfo(Triple, sys::getHostCPUName(), ""));
239    OwningPtr<const MCDisassembler> DisAsm(T->createMCDisassembler(*STI));
240 #endif
241    if (!DisAsm) {
242       Out << "error: no disassembler for target " << Triple << "\n";
243       Out.flush();
244       return 0;
245    }
246
247
248    OwningPtr<MCInstPrinter> Printer(
249          T->createMCInstPrinter(AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));
250    if (!Printer) {
251       Out << "error: no instruction printer for target " << Triple.c_str() << "\n";
252       Out.flush();
253       return 0;
254    }
255
256    TargetOptions options;
257 #if defined(DEBUG)
258    options.JITEmitDebugInfo = true;
259 #endif
260 #if defined(PIPE_ARCH_X86)
261    options.StackAlignmentOverride = 4;
262 #endif
263 #if defined(DEBUG) || defined(PROFILE)
264    options.NoFramePointerElim = true;
265 #endif
266    OwningPtr<TargetMachine> TM(T->createTargetMachine(Triple, sys::getHostCPUName(), "", options));
267
268    const TargetInstrInfo *TII = TM->getInstrInfo();
269
270    /*
271     * Wrap the data in a MemoryObject
272     */
273    BufferMemoryObject memoryObject((const uint8_t *)bytes, extent);
274
275    uint64_t pc;
276    pc = 0;
277    while (true) {
278       MCInst Inst;
279       uint64_t Size;
280
281       /*
282        * Print address.  We use addresses relative to the start of the function,
283        * so that between runs.
284        */
285
286       Out << llvm::format("%6lu:\t", (unsigned long)pc);
287
288       if (!DisAsm->getInstruction(Inst, Size, memoryObject,
289                                  pc,
290                                   nulls(), nulls())) {
291          Out << "invalid";
292          pc += 1;
293       }
294
295       /*
296        * Output the bytes in hexidecimal format.
297        */
298
299       if (0) {
300          unsigned i;
301          for (i = 0; i < Size; ++i) {
302             Out << llvm::format("%02x ", ((const uint8_t*)bytes)[pc + i]);
303          }
304          for (; i < 16; ++i) {
305             Out << "   ";
306          }
307       }
308
309       /*
310        * Print the instruction.
311        */
312       Printer->printInst(&Inst, Out, "");
313
314       /*
315        * Advance.
316        */
317
318       pc += Size;
319
320       const MCInstrDesc &TID = TII->get(Inst.getOpcode());
321
322       /*
323        * Keep track of forward jumps to a nearby address.
324        */
325
326       if (TID.isBranch()) {
327          for (unsigned i = 0; i < Inst.getNumOperands(); ++i) {
328             const MCOperand &operand = Inst.getOperand(i);
329             if (operand.isImm()) {
330                uint64_t jump;
331
332                /*
333                 * FIXME: Handle both relative and absolute addresses correctly.
334                 * EDInstInfo actually has this info, but operandTypes and
335                 * operandFlags enums are not exposed in the public interface.
336                 */
337
338                if (1) {
339                   /*
340                    * PC relative addr.
341                    */
342
343                   jump = pc + operand.getImm();
344                } else {
345                   /*
346                    * Absolute addr.
347                    */
348
349                   jump = (uint64_t)operand.getImm();
350                }
351
352                /*
353                 * Output the address relative to the function start, given
354                 * that MC will print the addresses relative the current pc.
355                 */
356                Out << "\t\t; " << jump;
357
358                /*
359                 * Ignore far jumps given it could be actually a tail return to
360                 * a random address.
361                 */
362
363                if (jump > max_pc &&
364                    jump < extent) {
365                   max_pc = jump;
366                }
367             }
368          }
369       }
370
371       Out << "\n";
372
373       /*
374        * Stop disassembling on return statements, if there is no record of a
375        * jump to a successive address.
376        */
377
378       if (TID.isReturn()) {
379          if (pc > max_pc) {
380             break;
381          }
382       }
383    }
384
385    /*
386     * Print GDB command, useful to verify output.
387     */
388
389    if (0) {
390       _debug_printf("disassemble %p %p\n", bytes, bytes + pc);
391    }
392
393    Out << "\n";
394    Out.flush();
395
396    return pc;
397 }
398
399
400 extern "C" void
401 lp_disassemble(LLVMValueRef func, const void *code) {
402    raw_debug_ostream Out;
403    disassemble(code, Out);
404 }
405
406
407 /*
408  * Linux perf profiler integration.
409  *
410  * See also:
411  * - http://penberg.blogspot.co.uk/2009/06/jato-has-profiler.html
412  * - https://github.com/penberg/jato/commit/73ad86847329d99d51b386f5aba692580d1f8fdc
413  * - http://git.kernel.org/?p=linux/kernel/git/torvalds/linux.git;a=commitdiff;h=80d496be89ed7dede5abee5c057634e80a31c82d
414  */
415 extern "C" void
416 lp_profile(LLVMValueRef func, const void *code)
417 {
418 #if defined(__linux__) && (defined(DEBUG) || defined(PROFILE))
419    static boolean first_time = TRUE;
420    static FILE *perf_map_file = NULL;
421    static int perf_asm_fd = -1;
422    if (first_time) {
423       /*
424        * We rely on the disassembler for determining a function's size, but
425        * the disassembly is a leaky and slow operation, so avoid running
426        * this except when running inside linux perf, which can be inferred
427        * by the PERF_BUILDID_DIR environment variable.
428        */
429       if (getenv("PERF_BUILDID_DIR")) {
430          pid_t pid = getpid();
431          char filename[256];
432          util_snprintf(filename, sizeof filename, "/tmp/perf-%llu.map", (unsigned long long)pid);
433          perf_map_file = fopen(filename, "wt");
434          util_snprintf(filename, sizeof filename, "/tmp/perf-%llu.map.asm", (unsigned long long)pid);
435          mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
436          perf_asm_fd = open(filename, O_WRONLY | O_CREAT, mode);
437       }
438       first_time = FALSE;
439    }
440    if (perf_map_file) {
441       const char *symbol = LLVMGetValueName(func);
442       unsigned long addr = (uintptr_t)code;
443       llvm::raw_fd_ostream Out(perf_asm_fd, false);
444       Out << symbol << ":\n";
445       unsigned long size = disassemble(code, Out);
446       fprintf(perf_map_file, "%lx %lx %s\n", addr, size, symbol);
447       fflush(perf_map_file);
448    }
449 #else
450    (void)func;
451    (void)code;
452 #endif
453 }
454
455