1 /**************************************************************************
3 * Copyright 2009-2011 VMware, Inc.
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:
14 * The above copyright notice and this permission notice (including the
15 * next paragraph) shall be included in all copies or substantial portions
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.
26 **************************************************************************/
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>
36 #if HAVE_LLVM >= 0x0306
37 #include <llvm/Target/TargetSubtargetInfo.h>
39 #include <llvm/Support/MemoryObject.h>
42 #include <llvm/Support/TargetRegistry.h>
43 #include <llvm/MC/MCSubtargetInfo.h>
45 #include <llvm/Support/Host.h>
47 #include <llvm/IR/Module.h>
49 #include <llvm/MC/MCDisassembler.h>
50 #include <llvm/MC/MCAsmInfo.h>
51 #include <llvm/MC/MCInst.h>
52 #include <llvm/MC/MCInstPrinter.h>
53 #include <llvm/MC/MCRegisterInfo.h>
55 #if HAVE_LLVM >= 0x0305
56 #define OwningPtr std::unique_ptr
58 #include <llvm/ADT/OwningPtr.h>
61 #if HAVE_LLVM >= 0x0305
62 #include <llvm/MC/MCContext.h>
65 #include "util/u_math.h"
66 #include "util/u_debug.h"
68 #include "lp_bld_debug.h"
80 * It is important that this check is not implemented as a macro or inlined
81 * function, as the compiler assumptions in respect to alignment of global
82 * and stack variables would often make the check a no op, defeating the
83 * whole purpose of the exercise.
86 lp_check_alignment(const void *ptr
, unsigned alignment
)
88 assert(util_is_power_of_two(alignment
));
89 return ((uintptr_t)ptr
& (alignment
- 1)) == 0;
93 class raw_debug_ostream
:
94 public llvm::raw_ostream
100 raw_debug_ostream() : pos(0) { }
102 void write_impl(const char *Ptr
, size_t Size
);
104 uint64_t current_pos() const { return pos
; }
105 size_t preferred_buffer_size() const { return 512; }
110 raw_debug_ostream::write_impl(const char *Ptr
, size_t Size
)
113 char *lastPtr
= (char *)&Ptr
[Size
];
114 char last
= *lastPtr
;
116 _debug_printf("%*s", Size
, Ptr
);
123 extern "C" const char *
124 lp_get_module_id(LLVMModuleRef module
)
126 return llvm::unwrap(module
)->getModuleIdentifier().c_str();
131 * Same as LLVMDumpValue, but through our debugging channels.
134 lp_debug_dump_value(LLVMValueRef value
)
136 #if (defined(PIPE_OS_WINDOWS) && !defined(PIPE_CC_MSVC)) || defined(PIPE_OS_EMBDDED)
137 raw_debug_ostream os
;
138 llvm::unwrap(value
)->print(os
);
141 LLVMDumpValue(value
);
146 #if HAVE_LLVM < 0x0306
149 * MemoryObject wrapper around a buffer of memory, to be used by MC
152 class BufferMemoryObject
:
153 public llvm::MemoryObject
156 const uint8_t *Bytes
;
159 BufferMemoryObject(const uint8_t *bytes
, uint64_t length
) :
160 Bytes(bytes
), Length(length
)
164 uint64_t getBase() const
169 uint64_t getExtent() const
174 int readByte(uint64_t addr
, uint8_t *byte
) const
176 if (addr
> getExtent())
183 #endif /* HAVE_LLVM < 0x0306 */
187 * Disassemble a function, using the LLVM MC disassembler.
190 * - http://blog.llvm.org/2010/01/x86-disassembler.html
191 * - http://blog.llvm.org/2010/04/intro-to-llvm-mc-project.html
194 disassemble(const void* func
, llvm::raw_ostream
& Out
)
196 using namespace llvm
;
198 const uint8_t *bytes
= (const uint8_t *)func
;
201 * Limit disassembly to this extent
203 const uint64_t extent
= 96 * 1024;
208 * Initialize all used objects.
211 std::string Triple
= sys::getDefaultTargetTriple();
214 const Target
*T
= TargetRegistry::lookupTarget(Triple
, Error
);
216 #if HAVE_LLVM >= 0x0304
217 OwningPtr
<const MCAsmInfo
> AsmInfo(T
->createMCAsmInfo(*T
->createMCRegInfo(Triple
), Triple
));
219 OwningPtr
<const MCAsmInfo
> AsmInfo(T
->createMCAsmInfo(Triple
));
223 Out
<< "error: no assembly info for target " << Triple
<< "\n";
228 unsigned int AsmPrinterVariant
= AsmInfo
->getAssemblerDialect();
230 OwningPtr
<const MCRegisterInfo
> MRI(T
->createMCRegInfo(Triple
));
232 Out
<< "error: no register info for target " << Triple
.c_str() << "\n";
237 OwningPtr
<const MCInstrInfo
> MII(T
->createMCInstrInfo());
239 Out
<< "error: no instruction info for target " << Triple
.c_str() << "\n";
244 #if HAVE_LLVM >= 0x0305
245 OwningPtr
<const MCSubtargetInfo
> STI(T
->createMCSubtargetInfo(Triple
, sys::getHostCPUName(), ""));
246 OwningPtr
<MCContext
> MCCtx(new MCContext(AsmInfo
.get(), MRI
.get(), 0));
247 OwningPtr
<const MCDisassembler
> DisAsm(T
->createMCDisassembler(*STI
, *MCCtx
));
249 OwningPtr
<const MCSubtargetInfo
> STI(T
->createMCSubtargetInfo(Triple
, sys::getHostCPUName(), ""));
250 OwningPtr
<const MCDisassembler
> DisAsm(T
->createMCDisassembler(*STI
));
253 Out
<< "error: no disassembler for target " << Triple
<< "\n";
259 OwningPtr
<MCInstPrinter
> Printer(
260 T
->createMCInstPrinter(AsmPrinterVariant
, *AsmInfo
, *MII
, *MRI
, *STI
));
262 Out
<< "error: no instruction printer for target " << Triple
.c_str() << "\n";
267 TargetOptions options
;
269 options
.JITEmitDebugInfo
= true;
271 #if defined(PIPE_ARCH_X86)
272 options
.StackAlignmentOverride
= 4;
274 #if defined(DEBUG) || defined(PROFILE)
275 options
.NoFramePointerElim
= true;
277 OwningPtr
<TargetMachine
> TM(T
->createTargetMachine(Triple
, sys::getHostCPUName(), "", options
));
279 #if HAVE_LLVM >= 0x0306
280 const TargetInstrInfo
*TII
= TM
->getSubtargetImpl()->getInstrInfo();
282 const TargetInstrInfo
*TII
= TM
->getInstrInfo();
286 * Wrap the data in a MemoryObject
288 #if HAVE_LLVM >= 0x0306
289 ArrayRef
<uint8_t> memoryObject((const uint8_t *)bytes
, extent
);
291 BufferMemoryObject
memoryObject((const uint8_t *)bytes
, extent
);
301 * Print address. We use addresses relative to the start of the function,
302 * so that between runs.
305 Out
<< llvm::format("%6lu:\t", (unsigned long)pc
);
307 if (!DisAsm
->getInstruction(Inst
, Size
, memoryObject
,
315 * Output the bytes in hexidecimal format.
320 for (i
= 0; i
< Size
; ++i
) {
321 Out
<< llvm::format("%02x ", ((const uint8_t*)bytes
)[pc
+ i
]);
323 for (; i
< 16; ++i
) {
329 * Print the instruction.
331 Printer
->printInst(&Inst
, Out
, "");
339 const MCInstrDesc
&TID
= TII
->get(Inst
.getOpcode());
342 * Keep track of forward jumps to a nearby address.
345 if (TID
.isBranch()) {
346 for (unsigned i
= 0; i
< Inst
.getNumOperands(); ++i
) {
347 const MCOperand
&operand
= Inst
.getOperand(i
);
348 if (operand
.isImm()) {
352 * FIXME: Handle both relative and absolute addresses correctly.
353 * EDInstInfo actually has this info, but operandTypes and
354 * operandFlags enums are not exposed in the public interface.
362 jump
= pc
+ operand
.getImm();
368 jump
= (uint64_t)operand
.getImm();
372 * Output the address relative to the function start, given
373 * that MC will print the addresses relative the current pc.
375 Out
<< "\t\t; " << jump
;
378 * Ignore far jumps given it could be actually a tail return to
393 * Stop disassembling on return statements, if there is no record of a
394 * jump to a successive address.
397 if (TID
.isReturn()) {
405 * Print GDB command, useful to verify output.
409 _debug_printf("disassemble %p %p\n", bytes
, bytes
+ pc
);
420 lp_disassemble(LLVMValueRef func
, const void *code
) {
421 raw_debug_ostream Out
;
422 Out
<< LLVMGetValueName(func
) << ":\n";
423 disassemble(code
, Out
);
428 * Linux perf profiler integration.
431 * - http://penberg.blogspot.co.uk/2009/06/jato-has-profiler.html
432 * - https://github.com/penberg/jato/commit/73ad86847329d99d51b386f5aba692580d1f8fdc
433 * - http://git.kernel.org/?p=linux/kernel/git/torvalds/linux.git;a=commitdiff;h=80d496be89ed7dede5abee5c057634e80a31c82d
436 lp_profile(LLVMValueRef func
, const void *code
)
438 #if defined(__linux__) && (defined(DEBUG) || defined(PROFILE))
439 static boolean first_time
= TRUE
;
440 static FILE *perf_map_file
= NULL
;
441 static int perf_asm_fd
= -1;
444 * We rely on the disassembler for determining a function's size, but
445 * the disassembly is a leaky and slow operation, so avoid running
446 * this except when running inside linux perf, which can be inferred
447 * by the PERF_BUILDID_DIR environment variable.
449 if (getenv("PERF_BUILDID_DIR")) {
450 pid_t pid
= getpid();
452 util_snprintf(filename
, sizeof filename
, "/tmp/perf-%llu.map", (unsigned long long)pid
);
453 perf_map_file
= fopen(filename
, "wt");
454 util_snprintf(filename
, sizeof filename
, "/tmp/perf-%llu.map.asm", (unsigned long long)pid
);
455 mode_t mode
= S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IROTH
;
456 perf_asm_fd
= open(filename
, O_WRONLY
| O_CREAT
, mode
);
461 const char *symbol
= LLVMGetValueName(func
);
462 unsigned long addr
= (uintptr_t)code
;
463 llvm::raw_fd_ostream
Out(perf_asm_fd
, false);
464 Out
<< symbol
<< ":\n";
465 unsigned long size
= disassemble(code
, Out
);
466 fprintf(perf_map_file
, "%lx %lx %s\n", addr
, size
, symbol
);
467 fflush(perf_map_file
);