* New revised variable argument handling support

* More dense bytecode encoding for varargs calls (like printf)
* Eliminated the extremely old bytecode format.  rev #0 is now 1.0


git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@9220 91177308-0d34-0410-b5e6-96231b3b80d8
This commit is contained in:
Chris Lattner 2003-10-18 05:54:18 +00:00
parent 99e7ab72c8
commit cb7e2e2e0f
5 changed files with 290 additions and 149 deletions

View File

@ -258,64 +258,47 @@ Constant *BytecodeParser::parseConstantValue(const unsigned char *&Buf,
return ConstantStruct::get(ST, Elements);
}
case Type::PointerTyID: {
case Type::PointerTyID: { // ConstantPointerRef value...
const PointerType *PT = cast<PointerType>(Ty);
unsigned SubClass;
if (HasImplicitZeroInitializer)
SubClass = 1;
else
if (read_vbr(Buf, EndBuf, SubClass)) throw Error_readvbr;
switch (SubClass) {
case 0: // ConstantPointerNull value...
return ConstantPointerNull::get(PT);
case 1: { // ConstantPointerRef value...
unsigned Slot;
if (read_vbr(Buf, EndBuf, Slot)) throw Error_readvbr;
BCR_TRACE(4, "CPR: Type: '" << Ty << "' slot: " << Slot << "\n");
// Check to see if we have already read this global variable...
Value *Val = getValue(PT, Slot, false);
GlobalValue *GV;
if (Val) {
if (!(GV = dyn_cast<GlobalValue>(Val)))
throw std::string("Value of ConstantPointerRef not in ValueTable!");
BCR_TRACE(5, "Value Found in ValueTable!\n");
} else if (RevisionNum > 0) {
// Revision #0 could have forward references to globals that were weird.
// We got rid of this in subsequent revs.
throw std::string("Forward references to globals not allowed.");
} else { // Nope... find or create a forward ref. for it
GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PT, Slot));
if (I != GlobalRefs.end()) {
BCR_TRACE(5, "Previous forward ref found!\n");
GV = cast<GlobalValue>(I->second);
} else {
BCR_TRACE(5, "Creating new forward ref to a global variable!\n");
// Create a placeholder for the global variable reference...
GlobalVariable *GVar =
new GlobalVariable(PT->getElementType(), false,
GlobalValue::InternalLinkage);
// Keep track of the fact that we have a forward ref to recycle it
GlobalRefs.insert(std::make_pair(std::make_pair(PT, Slot), GVar));
// Must temporarily push this value into the module table...
TheModule->getGlobalList().push_back(GVar);
GV = GVar;
}
unsigned Slot;
if (read_vbr(Buf, EndBuf, Slot)) throw Error_readvbr;
BCR_TRACE(4, "CPR: Type: '" << Ty << "' slot: " << Slot << "\n");
// Check to see if we have already read this global variable...
Value *Val = getValue(PT, Slot, false);
GlobalValue *GV;
if (Val) {
if (!(GV = dyn_cast<GlobalValue>(Val)))
throw std::string("Value of ConstantPointerRef not in ValueTable!");
BCR_TRACE(5, "Value Found in ValueTable!\n");
} else if (RevisionNum > 0) {
// Revision #0 could have forward references to globals that were weird.
// We got rid of this in subsequent revs.
throw std::string("Forward references to globals not allowed.");
} else { // Nope... find or create a forward ref. for it
GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PT, Slot));
if (I != GlobalRefs.end()) {
BCR_TRACE(5, "Previous forward ref found!\n");
GV = cast<GlobalValue>(I->second);
} else {
BCR_TRACE(5, "Creating new forward ref to a global variable!\n");
// Create a placeholder for the global variable reference...
GlobalVariable *GVar =
new GlobalVariable(PT->getElementType(), false,
GlobalValue::InternalLinkage);
// Keep track of the fact that we have a forward ref to recycle it
GlobalRefs.insert(std::make_pair(std::make_pair(PT, Slot), GVar));
// Must temporarily push this value into the module table...
TheModule->getGlobalList().push_back(GVar);
GV = GVar;
}
return ConstantPointerRef::get(GV);
}
default:
BCR_TRACE(5, "UNKNOWN Pointer Constant Type!\n");
throw std::string("Unknown pointer constant type.");
}
return ConstantPointerRef::get(GV);
}
default:

View File

@ -13,6 +13,7 @@
#include "llvm/iMemory.h"
#include "llvm/iPHINode.h"
#include "llvm/iOther.h"
#include "llvm/Module.h"
namespace {
struct RawInst { // The raw fields out of the bytecode stream...
@ -102,24 +103,61 @@ RawInst::RawInst(const unsigned char *&Buf, const unsigned char *EndBuf,
}
Instruction *BytecodeParser::ParseInstruction(const unsigned char *&Buf,
const unsigned char *EndBuf,
std::vector<unsigned> &Args) {
void BytecodeParser::ParseInstruction(const unsigned char *&Buf,
const unsigned char *EndBuf,
std::vector<unsigned> &Args,
BasicBlock *BB) {
Args.clear();
RawInst RI(Buf, EndBuf, Args);
const Type *InstTy = getType(RI.Type);
Instruction *Result = 0;
if (RI.Opcode >= Instruction::BinaryOpsBegin &&
RI.Opcode < Instruction::BinaryOpsEnd && Args.size() == 2)
return BinaryOperator::create((Instruction::BinaryOps)RI.Opcode,
getValue(RI.Type, Args[0]),
getValue(RI.Type, Args[1]));
Result = BinaryOperator::create((Instruction::BinaryOps)RI.Opcode,
getValue(RI.Type, Args[0]),
getValue(RI.Type, Args[1]));
switch (RI.Opcode) {
case Instruction::VarArg:
return new VarArgInst(getValue(RI.Type, Args[0]), getType(Args[1]));
default:
if (Result == 0) throw std::string("Illegal instruction read!");
break;
case Instruction::VAArg:
Result = new VAArgInst(getValue(RI.Type, Args[0]), getType(Args[1]));
break;
case Instruction::VANext:
if (!hasOldStyleVarargs) {
Result = new VANextInst(getValue(RI.Type, Args[0]), getType(Args[1]));
} else {
// In the old-style varargs scheme, this was the "va_arg" instruction.
// Emit emulation code now.
if (!usesOldStyleVarargs) {
usesOldStyleVarargs = true;
std::cerr << "WARNING: this bytecode file uses obsolete features. "
<< "Disassemble and assemble to update it.\n";
}
Value *VAListPtr = getValue(RI.Type, Args[0]);
const Type *ArgTy = getType(Args[1]);
// First, load the valist...
Instruction *CurVAList = new LoadInst(VAListPtr, "");
BB->getInstList().push_back(CurVAList);
// Construct the vaarg
Result = new VAArgInst(CurVAList, ArgTy);
// Now we must advance the pointer and update it in memory.
Instruction *TheVANext = new VANextInst(CurVAList, ArgTy);
BB->getInstList().push_back(TheVANext);
BB->getInstList().push_back(new StoreInst(TheVANext, VAListPtr));
}
break;
case Instruction::Cast:
return new CastInst(getValue(RI.Type, Args[0]), getType(Args[1]));
Result = new CastInst(getValue(RI.Type, Args[0]), getType(Args[1]));
break;
case Instruction::PHINode: {
if (Args.size() == 0 || (Args.size() & 1))
throw std::string("Invalid phi node encountered!\n");
@ -128,29 +166,34 @@ Instruction *BytecodeParser::ParseInstruction(const unsigned char *&Buf,
PN->op_reserve(Args.size());
for (unsigned i = 0, e = Args.size(); i != e; i += 2)
PN->addIncoming(getValue(RI.Type, Args[i]), getBasicBlock(Args[i+1]));
return PN;
Result = PN;
break;
}
case Instruction::Shl:
case Instruction::Shr:
return new ShiftInst((Instruction::OtherOps)RI.Opcode,
getValue(RI.Type, Args[0]),
getValue(Type::UByteTyID, Args[1]));
Result = new ShiftInst((Instruction::OtherOps)RI.Opcode,
getValue(RI.Type, Args[0]),
getValue(Type::UByteTyID, Args[1]));
break;
case Instruction::Ret:
if (Args.size() == 0)
return new ReturnInst();
Result = new ReturnInst();
else if (Args.size() == 1)
return new ReturnInst(getValue(RI.Type, Args[0]));
Result = new ReturnInst(getValue(RI.Type, Args[0]));
else
throw std::string("Unrecognized instruction!");
break;
case Instruction::Br:
if (Args.size() == 1)
return new BranchInst(getBasicBlock(Args[0]));
Result = new BranchInst(getBasicBlock(Args[0]));
else if (Args.size() == 3)
return new BranchInst(getBasicBlock(Args[0]), getBasicBlock(Args[1]),
getValue(Type::BoolTyID , Args[2]));
throw std::string("Invalid number of operands for a 'br' instruction!");
Result = new BranchInst(getBasicBlock(Args[0]), getBasicBlock(Args[1]),
getValue(Type::BoolTyID , Args[2]));
else
throw std::string("Invalid number of operands for a 'br' instruction!");
break;
case Instruction::Switch: {
if (Args.size() & 1)
throw std::string("Switch statement with odd number of arguments!");
@ -160,7 +203,8 @@ Instruction *BytecodeParser::ParseInstruction(const unsigned char *&Buf,
for (unsigned i = 2, e = Args.size(); i != e; i += 2)
I->addCase(cast<Constant>(getValue(RI.Type, Args[i])),
getBasicBlock(Args[i+1]));
return I;
Result = I;
break;
}
case Instruction::Call: {
@ -187,16 +231,31 @@ Instruction *BytecodeParser::ParseInstruction(const unsigned char *&Buf,
}
if (It != PL.end()) throw std::string("Invalid call instruction!");
} else {
// FIXME: Args[1] is currently just a dummy padding field!
Args.erase(Args.begin(), Args.begin()+1+hasVarArgCallPadding);
if (Args.size() & 1) // Must be pairs of type/value
unsigned FirstVariableOperand;
if (!hasVarArgCallPadding) {
if (Args.size() < FTy->getNumParams())
throw std::string("Call instruction missing operands!");
// Read all of the fixed arguments
for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
Params.push_back(getValue(FTy->getParamType(i), Args[i]));
FirstVariableOperand = FTy->getNumParams();
} else {
FirstVariableOperand = 0;
}
if ((Args.size()-FirstVariableOperand) & 1) // Must be pairs of type/value
throw std::string("Invalid call instruction!");
for (unsigned i = 2, e = Args.size(); i != e; i += 2)
for (unsigned i = FirstVariableOperand, e = Args.size(); i != e; i += 2)
Params.push_back(getValue(Args[i], Args[i+1]));
}
return new CallInst(F, Params);
Result = new CallInst(F, Params);
break;
}
case Instruction::Invoke: {
if (Args.size() < 3) throw std::string("Invalid invoke instruction!");
@ -224,46 +283,60 @@ Instruction *BytecodeParser::ParseInstruction(const unsigned char *&Buf,
}
if (It != PL.end()) throw std::string("Invalid invoke instruction!");
} else {
// FIXME: Args[1] is a dummy padding field
Args.erase(Args.begin(), Args.begin()+1+hasVarArgCallPadding);
if (Args.size() < 6) throw std::string("Invalid invoke instruction!");
if (Args[2] != Type::LabelTyID || Args[4] != Type::LabelTyID)
throw std::string("Invalid invoke instruction!");
unsigned FirstVariableArgument;
if (!hasVarArgCallPadding) {
Normal = getBasicBlock(Args[0]);
Except = getBasicBlock(Args[1]);
FirstVariableArgument = FTy->getNumParams()+2;
for (unsigned i = 2; i != FirstVariableArgument; ++i)
Params.push_back(getValue(FTy->getParamType(i-2), Args[i]));
Normal = getBasicBlock(Args[3]);
Except = getBasicBlock(Args[5]);
} else {
if (Args.size() < 4) throw std::string("Invalid invoke instruction!");
if (Args[0] != Type::LabelTyID || Args[2] != Type::LabelTyID)
throw std::string("Invalid invoke instruction!");
Normal = getBasicBlock(Args[1]);
Except = getBasicBlock(Args[3]);
if (Args.size() & 1) // Must be pairs of type/value
FirstVariableArgument = 4;
}
if (Args.size()-FirstVariableArgument & 1) // Must be pairs of type/value
throw std::string("Invalid invoke instruction!");
for (unsigned i = 6; i < Args.size(); i += 2)
for (unsigned i = FirstVariableArgument; i < Args.size(); i += 2)
Params.push_back(getValue(Args[i], Args[i+1]));
}
return new InvokeInst(F, Normal, Except, Params);
Result = new InvokeInst(F, Normal, Except, Params);
break;
}
case Instruction::Malloc:
if (Args.size() > 2) throw std::string("Invalid malloc instruction!");
if (!isa<PointerType>(InstTy))
throw std::string("Invalid malloc instruction!");
return new MallocInst(cast<PointerType>(InstTy)->getElementType(),
Args.size() ? getValue(Type::UIntTyID,
Args[0]) : 0);
Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
Args.size() ? getValue(Type::UIntTyID,
Args[0]) : 0);
break;
case Instruction::Alloca:
if (Args.size() > 2) throw std::string("Invalid alloca instruction!");
if (!isa<PointerType>(InstTy))
throw std::string("Invalid alloca instruction!");
return new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
Args.size() ? getValue(Type::UIntTyID,
Args[0]) : 0);
Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
Args.size() ? getValue(Type::UIntTyID, Args[0]) :0);
break;
case Instruction::Free:
if (!isa<PointerType>(InstTy))
throw std::string("Invalid free instruction!");
return new FreeInst(getValue(RI.Type, Args[0]));
Result = new FreeInst(getValue(RI.Type, Args[0]));
break;
case Instruction::GetElementPtr: {
if (Args.size() == 0 || !isa<PointerType>(InstTy))
throw std::string("Invalid getelementptr instruction!");
@ -278,14 +351,16 @@ Instruction *BytecodeParser::ParseInstruction(const unsigned char *&Buf,
NextTy = GetElementPtrInst::getIndexedType(InstTy, Idx, true);
}
return new GetElementPtrInst(getValue(RI.Type, Args[0]), Idx);
Result = new GetElementPtrInst(getValue(RI.Type, Args[0]), Idx);
break;
}
case 62: // volatile load
case Instruction::Load:
if (Args.size() != 1 || !isa<PointerType>(InstTy))
throw std::string("Invalid load instruction!");
return new LoadInst(getValue(RI.Type, Args[0]), "", RI.Opcode == 62);
Result = new LoadInst(getValue(RI.Type, Args[0]), "", RI.Opcode == 62);
break;
case 63: // volatile store
case Instruction::Store: {
@ -294,14 +369,16 @@ Instruction *BytecodeParser::ParseInstruction(const unsigned char *&Buf,
Value *Ptr = getValue(RI.Type, Args[1]);
const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
return new StoreInst(getValue(ValTy, Args[0]), Ptr, RI.Opcode == 63);
Result = new StoreInst(getValue(ValTy, Args[0]), Ptr, RI.Opcode == 63);
break;
}
case Instruction::Unwind:
if (Args.size() != 0) throw std::string("Invalid unwind instruction!");
return new UnwindInst();
Result = new UnwindInst();
break;
} // end switch(RI.Opcode)
std::cerr << "Unrecognized instruction! " << RI.Opcode
<< " ADDR = 0x" << (void*)Buf << "\n";
throw std::string("Unrecognized instruction!");
insertValue(Result, Values);
BB->getInstList().push_back(Result);
BCR_TRACE(4, *Result);
}

View File

@ -80,8 +80,7 @@ unsigned BytecodeParser::insertValue(Value *Val, ValueTable &ValueTab) {
unsigned BytecodeParser::insertValue(Value *Val, unsigned type,
ValueTable &ValueTab) {
assert((!HasImplicitZeroInitializer || !isa<Constant>(Val) ||
Val->getType()->isPrimitiveType() ||
assert((!isa<Constant>(Val) || Val->getType()->isPrimitiveType() ||
!cast<Constant>(Val)->isNullValue()) &&
"Cannot read null values from bytecode!");
assert(type != Type::TypeTyID && "Types should never be insertValue'd!");
@ -97,9 +96,7 @@ unsigned BytecodeParser::insertValue(Value *Val, unsigned type,
// << "] = " << Val << "\n";
ValueTab[type]->push_back(Val);
bool HasOffset = HasImplicitZeroInitializer &&
!Val->getType()->isPrimitiveType();
bool HasOffset = !Val->getType()->isPrimitiveType();
return ValueTab[type]->size()-1 + HasOffset;
}
@ -113,7 +110,7 @@ Value *BytecodeParser::getValue(unsigned type, unsigned oNum, bool Create) {
assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
unsigned Num = oNum;
if (HasImplicitZeroInitializer && type >= FirstDerivedTyID) {
if (type >= FirstDerivedTyID) {
if (Num == 0)
return Constant::getNullValue(getType(type));
--Num;
@ -203,13 +200,9 @@ BasicBlock *BytecodeParser::ParseBasicBlock(const unsigned char *&Buf,
else
BB = ParsedBasicBlocks[BlockNo];
while (Buf < EndBuf) {
std::vector<unsigned> Args;
Instruction *Inst = ParseInstruction(Buf, EndBuf, Args);
insertValue(Inst, Values);
BB->getInstList().push_back(Inst);
BCR_TRACE(4, Inst);
}
std::vector<unsigned> Args;
while (Buf < EndBuf)
ParseInstruction(Buf, EndBuf, Args, BB);
return BB;
}
@ -313,16 +306,19 @@ void BytecodeParser::materializeFunction(Function* F) {
GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
if (!hasInternalMarkerOnly) {
// We didn't support weak linkage explicitly.
unsigned LinkageType;
if (read_vbr(Buf, EndBuf, LinkageType))
throw std::string("ParseFunction: Error reading from buffer.");
if (LinkageType & ~0x3)
if ((!hasExtendedLinkageSpecs && LinkageType > 3) ||
( hasExtendedLinkageSpecs && LinkageType > 4))
throw std::string("Invalid linkage type for Function.");
switch (LinkageType) {
case 0: Linkage = GlobalValue::ExternalLinkage; break;
case 1: Linkage = GlobalValue::WeakLinkage; break;
case 2: Linkage = GlobalValue::AppendingLinkage; break;
case 3: Linkage = GlobalValue::InternalLinkage; break;
case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
}
} else {
// We used to only support two linkage models: internal and external
@ -538,31 +534,33 @@ void BytecodeParser::ParseVersionInfo(const unsigned char *&Buf,
RevisionNum = Version >> 4;
// Default values for the current bytecode version
HasImplicitZeroInitializer = true;
hasInternalMarkerOnly = false;
hasExtendedLinkageSpecs = true;
hasOldStyleVarargs = false;
hasVarArgCallPadding = false;
FirstDerivedTyID = 14;
switch (RevisionNum) {
case 0: // Initial revision
// Version #0 didn't have any of the flags stored correctly, and in fact as
// only valid with a 14 in the flags values. Also, it does not support
// encoding zero initializers for arrays compactly.
//
if (Version != 14) throw std::string("Unknown revision 0 flags?");
HasImplicitZeroInitializer = false;
Endianness = Module::BigEndian;
PointerSize = Module::Pointer64;
hasInternalMarkerOnly = true;
hasNoEndianness = hasNoPointerSize = false;
break;
case 1:
case 1: // LLVM pre-1.0 release: will be deleted on the next rev
// Version #1 has four bit fields: isBigEndian, hasLongPointers,
// hasNoEndianness, and hasNoPointerSize.
hasInternalMarkerOnly = true;
hasExtendedLinkageSpecs = false;
hasOldStyleVarargs = true;
hasVarArgCallPadding = true;
break;
case 2:
case 2: // LLVM pre-1.0 release:
// Version #2 added information about all 4 linkage types instead of just
// having internal and external.
hasExtendedLinkageSpecs = false;
hasOldStyleVarargs = true;
hasVarArgCallPadding = true;
break;
case 0: // LLVM 1.0 release version
// Compared to rev #2, we added support for weak linkage, a more dense
// encoding, and better varargs support.
// FIXME: densify the encoding!
break;
default:
throw std::string("Unknown bytecode version number!");
@ -576,7 +574,6 @@ void BytecodeParser::ParseVersionInfo(const unsigned char *&Buf,
BCR_TRACE(1, "Bytecode Rev = " << (unsigned)RevisionNum << "\n");
BCR_TRACE(1, "Endianness/PointerSize = " << Endianness << ","
<< PointerSize << "\n");
BCR_TRACE(1, "HasImplicitZeroInit = " << HasImplicitZeroInitializer << "\n");
}
void BytecodeParser::ParseModule(const unsigned char *Buf,
@ -656,9 +653,8 @@ void BytecodeParser::ParseModule(const unsigned char *Buf,
BCR_TRACE(0, "} end block\n\n");
}
void
BytecodeParser::ParseBytecode(const unsigned char *Buf, unsigned Length,
const std::string &ModuleID) {
void BytecodeParser::ParseBytecode(const unsigned char *Buf, unsigned Length,
const std::string &ModuleID) {
unsigned char *EndBuf = (unsigned char*)(Buf + Length);
@ -670,6 +666,7 @@ BytecodeParser::ParseBytecode(const unsigned char *Buf, unsigned Length,
TheModule = new Module(ModuleID);
try {
usesOldStyleVarargs = false;
ParseModule(Buf, EndBuf);
} catch (std::string &Error) {
freeState(); // Must destroy handles before deleting module!

View File

@ -80,8 +80,12 @@ private:
// Information about the module, extracted from the bytecode revision number.
unsigned char RevisionNum; // The rev # itself
unsigned char FirstDerivedTyID; // First variable index to use for type
bool HasImplicitZeroInitializer; // Is entry 0 of every slot implicity zeros?
bool hasInternalMarkerOnly; // Only types of linkage are intern/external
bool hasExtendedLinkageSpecs; // Supports more than 4 linkage types
bool hasOldStyleVarargs; // Has old version of varargs intrinsics?
bool hasVarArgCallPadding; // Bytecode has extra padding in vararg call
bool usesOldStyleVarargs; // Does this module USE old style varargs?
typedef std::vector<ValueList*> ValueTable;
ValueTable Values;
@ -148,9 +152,8 @@ private:
const unsigned char *End,
unsigned BlockNo);
Instruction *ParseInstruction(const unsigned char *&Buf,
const unsigned char *End,
std::vector<unsigned> &Args);
void ParseInstruction(const unsigned char *&Buf, const unsigned char *End,
std::vector<unsigned> &Args, BasicBlock *BB);
void ParseConstantPool(const unsigned char *&Buf, const unsigned char *EndBuf,
ValueTable &Tab, TypeValuesListTy &TypeTab);

View File

@ -6,12 +6,18 @@
//===----------------------------------------------------------------------===//
#include "ReaderInternals.h"
#include "llvm/Module.h"
#include "llvm/Instructions.h"
#include "Support/StringExtras.h"
#include "Config/fcntl.h"
#include <sys/stat.h>
#include "Config/unistd.h"
#include "Config/sys/mman.h"
//===----------------------------------------------------------------------===//
// BytecodeFileReader - Read from an mmap'able file descriptor.
//
namespace {
/// FDHandle - Simple handle class to make sure a file descriptor gets closed
/// when the object is destroyed.
@ -73,7 +79,9 @@ BytecodeFileReader::~BytecodeFileReader() {
munmap((char*)Buffer, Length);
}
////////////////////////////////////////////////////////////////////////////
//===----------------------------------------------------------------------===//
// BytecodeBufferReader - Read from a memory buffer
//
namespace {
/// BytecodeBufferReader - parses a bytecode file from a buffer
@ -123,7 +131,9 @@ BytecodeBufferReader::~BytecodeBufferReader() {
if (MustDelete) delete [] Buffer;
}
////////////////////////////////////////////////////////////////////////////
//===----------------------------------------------------------------------===//
// BytecodeStdinReader - Read bytecode from Standard Input
//
namespace {
/// BytecodeStdinReader - parses a bytecode file from stdin
@ -160,18 +170,89 @@ BytecodeStdinReader::BytecodeStdinReader() {
ParseBytecode(FileBuf, FileData.size(), "<stdin>");
}
/////////////////////////////////////////////////////////////////////////////
//===----------------------------------------------------------------------===//
// Varargs transmogrification code...
//
// CheckVarargs - This is used to automatically translate old-style varargs to
// new style varargs for backwards compatibility.
static ModuleProvider *CheckVarargs(ModuleProvider *MP) {
Module *M = MP->getModule();
// Check to see if va_start takes arguments...
Function *F = M->getNamedFunction("llvm.va_start");
if (F == 0) return MP; // No varargs use, just return.
if (F->getFunctionType()->getNumParams() == 0)
return MP; // Modern varargs processing, just return.
// If we get to this point, we know that we have an old-style module.
// Materialize the whole thing to perform the rewriting.
MP->materializeModule();
// If the user is making use of obsolete varargs intrinsics, adjust them for
// the user.
if (Function *F = M->getNamedFunction("llvm.va_start")) {
assert(F->asize() == 1 && "Obsolete va_start takes 1 argument!");
const Type *RetTy = F->getFunctionType()->getParamType(0);
RetTy = cast<PointerType>(RetTy)->getElementType();
Function *NF = M->getOrInsertFunction("llvm.va_start", RetTy, 0);
for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; )
if (CallInst *CI = dyn_cast<CallInst>(*I++)) {
Value *V = new CallInst(NF, "", CI);
new StoreInst(V, CI->getOperand(1), CI);
CI->getParent()->getInstList().erase(CI);
}
F->setName("");
}
if (Function *F = M->getNamedFunction("llvm.va_end")) {
assert(F->asize() == 1 && "Obsolete va_end takes 1 argument!");
const Type *ArgTy = F->getFunctionType()->getParamType(0);
ArgTy = cast<PointerType>(ArgTy)->getElementType();
Function *NF = M->getOrInsertFunction("llvm.va_end", Type::VoidTy,
ArgTy, 0);
for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; )
if (CallInst *CI = dyn_cast<CallInst>(*I++)) {
Value *V = new LoadInst(CI->getOperand(1), "", CI);
new CallInst(NF, V, "", CI);
CI->getParent()->getInstList().erase(CI);
}
F->setName("");
}
if (Function *F = M->getNamedFunction("llvm.va_copy")) {
assert(F->asize() == 2 && "Obsolete va_copy takes 2 argument!");
const Type *ArgTy = F->getFunctionType()->getParamType(0);
ArgTy = cast<PointerType>(ArgTy)->getElementType();
Function *NF = M->getOrInsertFunction("llvm.va_copy", ArgTy,
ArgTy, 0);
for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; )
if (CallInst *CI = dyn_cast<CallInst>(*I++)) {
Value *V = new CallInst(NF, CI->getOperand(2), "", CI);
new StoreInst(V, CI->getOperand(1), CI);
CI->getParent()->getInstList().erase(CI);
}
F->setName("");
}
return MP;
}
//===----------------------------------------------------------------------===//
// Wrapper functions
//
/////////////////////////////////////////////////////////////////////////////
//===----------------------------------------------------------------------===//
/// getBytecodeBufferModuleProvider - lazy function-at-a-time loading from a
/// buffer
ModuleProvider*
getBytecodeBufferModuleProvider(const unsigned char *Buffer, unsigned Length,
const std::string &ModuleID) {
return new BytecodeBufferReader(Buffer, Length, ModuleID);
return CheckVarargs(new BytecodeBufferReader(Buffer, Length, ModuleID));
}
/// ParseBytecodeBuffer - Parse a given bytecode buffer
@ -192,9 +273,9 @@ Module *ParseBytecodeBuffer(const unsigned char *Buffer, unsigned Length,
///
ModuleProvider *getBytecodeModuleProvider(const std::string &Filename) {
if (Filename != std::string("-")) // Read from a file...
return new BytecodeFileReader(Filename);
return CheckVarargs(new BytecodeFileReader(Filename));
else // Read from stdin
return new BytecodeStdinReader();
return CheckVarargs(new BytecodeStdinReader());
}
/// ParseBytecodeFile - Parse the given bytecode file