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 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
|
/*
* Copyright (c) 2008, Mahadevan R All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of this software, nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* These are some "extra" functions not available in the standard LLVM-C
* bindings, but are required / good-to-have inorder to implement the
* Python bindings.
*/
// standard includes
#include <cassert>
#include <cstdlib>
#include <cstring>
#include <sstream>
// LLVM includes
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Casting.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/GlobalVariable.h"
#include "llvm/TypeSymbolTable.h"
#include "llvm/ModuleProvider.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/CallSite.h"
#include "llvm/IntrinsicInst.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Assembly/Parser.h"
#include "llvm/System/DynamicLibrary.h"
#include "llvm/PassManager.h"
#include "llvm/ExecutionEngine/ExecutionEngine.h"
#include "llvm/Analysis/LoopPass.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
#include "llvm/Transforms/Instrumentation.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/Linker.h"
#include "llvm/Support/SourceMgr.h"
// LLVM-C includes
#include "llvm-c/Core.h"
#include "llvm-c/ExecutionEngine.h"
// our includes
#include "extra.h"
//using namespace llvm;
/* Helper method for LLVMDumpXXXToString() methods. */
template <typename W, typename UW>
char *do_print(W obj)
{
std::string s;
llvm::raw_string_ostream buf(s);
UW *p = llvm::unwrap(obj);
assert(p);
p->print(buf);
return strdup(buf.str().c_str());
}
char *LLVMDumpModuleToString(LLVMModuleRef module)
{
std::string s;
llvm::raw_string_ostream buf(s);
llvm::Module *p = llvm::unwrap(module);
assert(p);
p->print(buf, NULL);
return strdup(buf.str().c_str());
}
char *LLVMDumpTypeToString(LLVMTypeRef type)
{
return do_print<LLVMTypeRef, llvm::Type>(type);
}
char *LLVMDumpValueToString(LLVMValueRef value)
{
return do_print<LLVMValueRef, llvm::Value>(value);
}
unsigned LLVMModuleGetPointerSize(LLVMModuleRef module)
{
llvm::Module *modulep = llvm::unwrap(module);
assert(modulep);
llvm::Module::PointerSize p = modulep->getPointerSize();
if (p == llvm::Module::Pointer32)
return 32;
else if (p == llvm::Module::Pointer64)
return 64;
return 0;
}
LLVMValueRef LLVMModuleGetOrInsertFunction(LLVMModuleRef module,
const char *name, LLVMTypeRef function_type)
{
assert(name);
llvm::Module *modulep = llvm::unwrap(module);
assert(modulep);
llvm::FunctionType *ftp = llvm::unwrap<llvm::FunctionType>(function_type);
assert(ftp);
llvm::Constant *f = modulep->getOrInsertFunction(name, ftp);
return wrap(f);
}
int LLVMHasInitializer(LLVMValueRef global_var)
{
llvm::GlobalVariable *gvp = llvm::unwrap<llvm::GlobalVariable>(global_var);
assert(gvp);
return gvp->hasInitializer();
}
#define inst_checkfn(ourfn, llvmfn) \
unsigned ourfn (LLVMValueRef v) { \
llvm::Instruction *ip = llvm::unwrap<llvm::Instruction>(v); \
assert(ip); \
return ip-> llvmfn () ? 1 : 0; \
}
inst_checkfn(LLVMInstIsTerminator, isTerminator)
inst_checkfn(LLVMInstIsBinaryOp, isBinaryOp)
inst_checkfn(LLVMInstIsShift, isShift)
inst_checkfn(LLVMInstIsCast, isCast)
inst_checkfn(LLVMInstIsLogicalShift, isLogicalShift)
inst_checkfn(LLVMInstIsArithmeticShift, isArithmeticShift)
inst_checkfn(LLVMInstIsAssociative, isAssociative)
inst_checkfn(LLVMInstIsCommutative, isCommutative)
unsigned LLVMInstIsVolatile(LLVMValueRef v)
{
using namespace llvm;
Instruction *ip = unwrap<Instruction>(v);
assert(ip);
return ((isa<LoadInst>(*ip) && cast<LoadInst>(*ip).isVolatile()) ||
(isa<StoreInst>(*ip) && cast<StoreInst>(*ip).isVolatile()) );
}
const char *LLVMInstGetOpcodeName(LLVMValueRef inst)
{
llvm::Instruction *instp = llvm::unwrap<llvm::Instruction>(inst);
assert(instp);
return instp->getOpcodeName();
}
unsigned LLVMInstGetOpcode(LLVMValueRef inst)
{
llvm::Instruction *instp = llvm::unwrap<llvm::Instruction>(inst);
assert(instp);
return instp->getOpcode();
}
unsigned LLVMCmpInstGetPredicate(LLVMValueRef cmpinst)
{
llvm::CmpInst *instp = llvm::unwrap<llvm::CmpInst>(cmpinst);
assert(instp);
return instp->getPredicate();
}
/* llvm::unwrap a set of `n' wrapped objects starting at `values',
* into a vector of pointers to llvm::unwrapped objects `out'. */
template <typename W, typename UW>
void unwrap_vec(W *values, unsigned n, std::vector<UW *>& out)
{
out.clear();
while (n--) {
UW *p = llvm::unwrap(*values);
assert(p);
out.push_back(p);
++values;
}
}
/* Same as llvm::unwrap_vec, but use a vector of const pointers. */
template <typename W, typename UW>
void unwrap_cvec(W *values, unsigned n, std::vector<const UW *>& out)
{
out.clear();
while (n--) {
UW *p = llvm::unwrap(*values);
assert(p);
out.push_back(p);
++values;
}
}
LLVMValueRef LLVMBuildRetMultiple(LLVMBuilderRef builder,
LLVMValueRef *values, unsigned n_values)
{
assert(values);
std::vector<llvm::Value *> values_vec;
unwrap_vec(values, n_values, values_vec);
llvm::IRBuilder<> *builderp = llvm::unwrap(builder);
assert(builderp);
return llvm::wrap(builderp->CreateAggregateRet(&values_vec[0], values_vec.size()));
}
LLVMValueRef LLVMBuildGetResult(LLVMBuilderRef builder,
LLVMValueRef value, unsigned index, const char *name)
{
assert(name);
llvm::IRBuilder<> *builderp = llvm::unwrap(builder);
assert(builderp);
return llvm::wrap(builderp->CreateExtractValue(llvm::unwrap(value), index, name));
}
unsigned LLVMValueGetID(LLVMValueRef value)
{
llvm::Value *valuep = llvm::unwrap(value);
assert(valuep);
return valuep->getValueID();
}
unsigned LLVMValueGetNumUses(LLVMValueRef value)
{
llvm::Value *valuep = llvm::unwrap(value);
assert(valuep);
return valuep->getNumUses();
}
unsigned LLVMValueGetUses(LLVMValueRef value, LLVMValueRef **refs)
{
llvm::Value *valuep = llvm::unwrap(value);
assert(valuep);
unsigned n = valuep->getNumUses();
if (n == 0)
return 0;
assert(refs);
LLVMValueRef *out = (LLVMValueRef *)malloc(sizeof(LLVMValueRef) * n);
if (!out)
return 0;
*refs = out;
memset(out, 0, sizeof(LLVMValueRef) * n);
llvm::Value::use_iterator it = valuep->use_begin();
while (it != valuep->use_end()) {
*out++ = llvm::wrap(*it);
++it;
}
return n;
}
void LLVMDisposeValueRefArray(LLVMValueRef *refs)
{
assert(refs);
free(refs);
}
unsigned LLVMUserGetNumOperands(LLVMValueRef user)
{
llvm::User *userp = llvm::unwrap<llvm::User>(user);
assert(userp);
return userp->getNumOperands();
}
LLVMValueRef LLVMUserGetOperand(LLVMValueRef user, unsigned idx)
{
llvm::User *userp = llvm::unwrap<llvm::User>(user);
assert(userp);
llvm::Value *operand = userp->getOperand(idx);
return llvm::wrap(operand);
}
unsigned LLVMGetDoesNotThrow(LLVMValueRef fn)
{
llvm::Function *fnp = llvm::unwrap<llvm::Function>(fn);
assert(fnp);
return fnp->doesNotThrow();
}
void LLVMSetDoesNotThrow(LLVMValueRef fn, int DoesNotThrow)
{
llvm::Function *fnp = llvm::unwrap<llvm::Function>(fn);
assert(fnp);
return fnp->setDoesNotThrow((bool)DoesNotThrow);
}
LLVMValueRef LLVMGetIntrinsic(LLVMModuleRef module, int id,
LLVMTypeRef *types, unsigned n_types)
{
assert(types);
std::vector<const llvm::Type*> types_vec;
unwrap_cvec(types, n_types, types_vec);
llvm::Module *modulep = llvm::unwrap(module);
assert(modulep);
llvm::Function *intfunc = llvm::Intrinsic::getDeclaration(modulep,
llvm::Intrinsic::ID(id), &types_vec[0], types_vec.size());
return wrap(intfunc);
}
LLVMModuleRef LLVMGetModuleFromAssembly(const char *asmtext, unsigned txtlen,
char **out)
{
assert(asmtext);
assert(out);
llvm::Module *modulep;
llvm::SMDiagnostic error;
if (!(modulep = llvm::ParseAssemblyString(asmtext, NULL, error,
llvm::getGlobalContext()))) {
std::string s;
llvm::raw_string_ostream buf(s);
error.Print("llvm-py", buf);
*out = strdup(buf.str().c_str());
return NULL;
}
return wrap(modulep);
}
LLVMModuleRef LLVMGetModuleFromBitcode(const char *bitcode, unsigned bclen,
char **out)
{
assert(bitcode);
assert(out);
llvm::MemoryBuffer *mbp;
if (!(mbp = llvm::MemoryBuffer::getMemBufferCopy(bitcode, bitcode+bclen)))
return NULL;
std::string msg;
llvm::Module *modulep;
if (!(modulep = llvm::ParseBitcodeFile(mbp, llvm::getGlobalContext(),
&msg)))
*out = strdup(msg.c_str());
delete mbp;
return wrap(modulep);
}
unsigned LLVMLinkModules(LLVMModuleRef dest, LLVMModuleRef src, char **out)
{
llvm::Module *sourcep = llvm::unwrap(src);
assert(sourcep);
llvm::Module *destinationp = llvm::unwrap(dest);
assert(destinationp);
std::string msg;
if (llvm::Linker::LinkModules(destinationp, sourcep, &msg)) {
*out = strdup(msg.c_str());
return 0;
}
return 1;
}
unsigned char *LLVMGetBitcodeFromModule(LLVMModuleRef module, unsigned *lenp)
{
assert(lenp);
llvm::Module *modulep = llvm::unwrap(module);
assert(modulep);
/* get bc into a string */
std::string s;
llvm::raw_string_ostream buf(s);
llvm::WriteBitcodeToFile(modulep, buf);
const std::string& bc = buf.str();
/* and then into a malloc()-ed block */
size_t bclen = bc.size();
unsigned char *bytes = (unsigned char *)malloc(bclen);
if (!bytes)
return NULL;
memcpy(bytes, bc.data(), bclen);
/* return */
*lenp = bclen;
return bytes;
}
/* Return 0 on failure (with errmsg filled in), 1 on success. */
unsigned LLVMLoadLibraryPermanently(const char* filename, char **errmsg)
{
assert(filename);
assert(errmsg);
/* Note: the LLVM API returns true on failure. Don't ask why. */
std::string msg;
if (llvm::sys::DynamicLibrary::LoadLibraryPermanently(filename, &msg)) {
*errmsg = strdup(msg.c_str());
return 0;
}
return 1;
}
void *LLVMGetPointerToFunction(LLVMExecutionEngineRef ee, LLVMValueRef fn)
{
llvm::ExecutionEngine *eep = llvm::unwrap(ee);
assert(eep);
llvm::Function *fnp = llvm::unwrap<llvm::Function>(fn);
assert(fnp);
return eep->getPointerToFunction(fnp);
}
int LLVMInlineFunction(LLVMValueRef call)
{
llvm::Value *callp = llvm::unwrap(call);
assert(callp);
llvm::CallSite cs = llvm::CallSite::get(callp);
return llvm::InlineFunction(cs);
}
/* Passes. A few passes (listed below) are used directly from LLVM-C,
* rest are defined here.
*
* ConstantPropagation
* GVN
* InstructionCombining
* PromoteMemoryToRegister
* Reassociate
* CFGSimplification
*/
#define define_pass(P) \
void LLVMAdd ## P ## Pass (LLVMPassManagerRef passmgr) { \
using namespace llvm; \
llvm::PassManagerBase *pmp = llvm::unwrap(passmgr); \
assert(pmp); \
pmp->add( create ## P ## Pass ()); \
}
define_pass( ArgumentPromotion )
define_pass( BlockPlacement )
define_pass( BreakCriticalEdges )
define_pass( CodeGenPrepare )
define_pass( ConstantMerge )
define_pass( DeadCodeElimination )
define_pass( DeadArgElimination )
define_pass( DeadTypeElimination )
define_pass( DeadInstElimination )
/* define_pass( GCSE ): removed in LLVM 2.4 */
define_pass( GlobalDCE )
define_pass( GlobalOptimizer )
define_pass( GVNPRE )
define_pass( IndMemRem )
define_pass( FunctionInlining )
define_pass( BlockProfiler )
define_pass( EdgeProfiler )
define_pass( FunctionProfiler )
define_pass( NullProfilerRS )
define_pass( RSProfiling )
/* we support only internalize(true) */
llvm::ModulePass *createInternalizePass() { return llvm::createInternalizePass(true); }
define_pass( Internalize )
define_pass( IPConstantPropagation )
define_pass( IPSCCP )
define_pass( LCSSA )
define_pass( LoopExtractor )
define_pass( SingleLoopExtractor )
define_pass( LoopStrengthReduce )
define_pass( LoopSimplify )
define_pass( LowerAllocations )
define_pass( LowerInvoke )
define_pass( LowerSetJmp )
define_pass( LowerSwitch )
define_pass( UnifyFunctionExitNodes )
define_pass( PredicateSimplifier )
define_pass( PruneEH )
define_pass( RaiseAllocations )
define_pass( DemoteRegisterToMemory )
define_pass( StripSymbols )
define_pass( StripDeadPrototypes )
define_pass( StructRetPromotion )
define_pass( TailDuplication )
|