1 //===-- llvmAsmParser.y - Parser for llvm assembly files --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the bison parser for LLVM assembly languages files.
12 //===----------------------------------------------------------------------===//
15 #include "ParserInternals.h"
16 #include "llvm/SymbolTable.h"
17 #include "llvm/Module.h"
18 #include "llvm/iTerminators.h"
19 #include "llvm/iMemory.h"
20 #include "llvm/iOperators.h"
21 #include "llvm/iPHINode.h"
22 #include "Support/STLExtras.h"
27 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
28 int yylex(); // declaration" of xxx warnings.
33 static Module *ParserResult;
34 std::string CurFilename;
36 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
37 // relating to upreferences in the input stream.
39 //#define DEBUG_UPREFS 1
41 #define UR_OUT(X) std::cerr << X
46 #define YYERROR_VERBOSE 1
48 // HACK ALERT: This variable is used to implement the automatic conversion of
49 // variable argument instructions from their old to new forms. When this
50 // compatiblity "Feature" is removed, this should be too.
52 static BasicBlock *CurBB;
53 static bool ObsoleteVarArgs;
56 // This contains info used when building the body of a function. It is
57 // destroyed when the function is completed.
59 typedef std::vector<Value *> ValueList; // Numbered defs
60 static void ResolveDefinitions(std::vector<ValueList> &LateResolvers,
61 std::vector<ValueList> *FutureLateResolvers = 0);
63 static struct PerModuleInfo {
64 Module *CurrentModule;
65 std::vector<ValueList> Values; // Module level numbered definitions
66 std::vector<ValueList> LateResolveValues;
67 std::vector<PATypeHolder> Types;
68 std::map<ValID, PATypeHolder> LateResolveTypes;
70 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
71 // references to global values. Global values may be referenced before they
72 // are defined, and if so, the temporary object that they represent is held
73 // here. This is used for forward references of ConstantPointerRefs.
75 typedef std::map<std::pair<const PointerType *,
76 ValID>, GlobalVariable*> GlobalRefsType;
77 GlobalRefsType GlobalRefs;
80 // If we could not resolve some functions at function compilation time
81 // (calls to functions before they are defined), resolve them now... Types
82 // are resolved when the constant pool has been completely parsed.
84 ResolveDefinitions(LateResolveValues);
86 // Check to make sure that all global value forward references have been
89 if (!GlobalRefs.empty()) {
90 std::string UndefinedReferences = "Unresolved global references exist:\n";
92 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
94 UndefinedReferences += " " + I->first.first->getDescription() + " " +
95 I->first.second.getName() + "\n";
97 ThrowException(UndefinedReferences);
100 Values.clear(); // Clear out function local definitions
106 // DeclareNewGlobalValue - Called every time a new GV has been defined. This
107 // is used to remove things from the forward declaration map, resolving them
108 // to the correct thing as needed.
110 void DeclareNewGlobalValue(GlobalValue *GV, ValID D) {
111 // Check to see if there is a forward reference to this global variable...
112 // if there is, eliminate it and patch the reference to use the new def'n.
113 GlobalRefsType::iterator I =
114 GlobalRefs.find(std::make_pair(GV->getType(), D));
116 if (I != GlobalRefs.end()) {
117 GlobalVariable *OldGV = I->second; // Get the placeholder...
118 I->first.second.destroy(); // Free string memory if necessary
120 // Loop over all of the uses of the GlobalValue. The only thing they are
121 // allowed to be is ConstantPointerRef's.
122 assert(OldGV->hasOneUse() && "Only one reference should exist!");
123 User *U = OldGV->use_back(); // Must be a ConstantPointerRef...
124 ConstantPointerRef *CPR = cast<ConstantPointerRef>(U);
126 // Change the const pool reference to point to the real global variable
127 // now. This should drop a use from the OldGV.
128 CPR->mutateReferences(OldGV, GV);
129 assert(OldGV->use_empty() && "All uses should be gone now!");
131 // Remove OldGV from the module...
132 CurrentModule->getGlobalList().remove(OldGV);
133 delete OldGV; // Delete the old placeholder
135 // Remove the map entry for the global now that it has been created...
142 static struct PerFunctionInfo {
143 Function *CurrentFunction; // Pointer to current function being created
145 std::vector<ValueList> Values; // Keep track of numbered definitions
146 std::vector<ValueList> LateResolveValues;
147 std::vector<PATypeHolder> Types;
148 std::map<ValID, PATypeHolder> LateResolveTypes;
149 SymbolTable LocalSymtab;
150 bool isDeclare; // Is this function a forward declararation?
152 inline PerFunctionInfo() {
157 inline void FunctionStart(Function *M) {
161 void FunctionDone() {
162 // If we could not resolve some blocks at parsing time (forward branches)
163 // resolve the branches now...
164 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
166 // Make sure to resolve any constant expr references that might exist within
167 // the function we just declared itself.
169 if (CurrentFunction->hasName()) {
170 FID = ValID::create((char*)CurrentFunction->getName().c_str());
172 unsigned Slot = CurrentFunction->getType()->getUniqueID();
173 assert(CurModule.Values.size() > Slot && "Function not inserted?");
174 // Figure out which slot number if is...
175 for (unsigned i = 0; ; ++i) {
176 assert(i < CurModule.Values[Slot].size() && "Function not found!");
177 if (CurModule.Values[Slot][i] == CurrentFunction) {
178 FID = ValID::create((int)i);
183 CurModule.DeclareNewGlobalValue(CurrentFunction, FID);
185 Values.clear(); // Clear out function local definitions
186 Types.clear(); // Clear out function local types
187 LocalSymtab.clear(); // Clear out function local symbol table
191 } CurFun; // Info for the current function...
193 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
196 //===----------------------------------------------------------------------===//
197 // Code to handle definitions of all the types
198 //===----------------------------------------------------------------------===//
200 static int InsertValue(Value *D,
201 std::vector<ValueList> &ValueTab = CurFun.Values) {
202 if (D->hasName()) return -1; // Is this a numbered definition?
204 // Yes, insert the value into the value table...
205 unsigned type = D->getType()->getUniqueID();
206 if (ValueTab.size() <= type)
207 ValueTab.resize(type+1, ValueList());
208 //printf("Values[%d][%d] = %d\n", type, ValueTab[type].size(), D);
209 ValueTab[type].push_back(D);
210 return ValueTab[type].size()-1;
213 // TODO: FIXME when Type are not const
214 static void InsertType(const Type *Ty, std::vector<PATypeHolder> &Types) {
218 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
220 case ValID::NumberVal: { // Is it a numbered definition?
221 unsigned Num = (unsigned)D.Num;
223 // Module constants occupy the lowest numbered slots...
224 if (Num < CurModule.Types.size())
225 return CurModule.Types[Num];
227 Num -= CurModule.Types.size();
229 // Check that the number is within bounds...
230 if (Num <= CurFun.Types.size())
231 return CurFun.Types[Num];
234 case ValID::NameVal: { // Is it a named definition?
235 std::string Name(D.Name);
236 SymbolTable *SymTab = 0;
238 if (inFunctionScope()) {
239 SymTab = &CurFun.CurrentFunction->getSymbolTable();
240 N = SymTab->lookup(Type::TypeTy, Name);
244 // Symbol table doesn't automatically chain yet... because the function
245 // hasn't been added to the module...
247 SymTab = &CurModule.CurrentModule->getSymbolTable();
248 N = SymTab->lookup(Type::TypeTy, Name);
252 D.destroy(); // Free old strdup'd memory...
253 return cast<Type>(N);
256 ThrowException("Internal parser error: Invalid symbol type reference!");
259 // If we reached here, we referenced either a symbol that we don't know about
260 // or an id number that hasn't been read yet. We may be referencing something
261 // forward, so just create an entry to be resolved later and get to it...
263 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
265 std::map<ValID, PATypeHolder> &LateResolver = inFunctionScope() ?
266 CurFun.LateResolveTypes : CurModule.LateResolveTypes;
268 std::map<ValID, PATypeHolder>::iterator I = LateResolver.find(D);
269 if (I != LateResolver.end()) {
273 Type *Typ = OpaqueType::get();
274 LateResolver.insert(std::make_pair(D, Typ));
278 static Value *lookupInSymbolTable(const Type *Ty, const std::string &Name) {
279 SymbolTable &SymTab =
280 inFunctionScope() ? CurFun.CurrentFunction->getSymbolTable() :
281 CurModule.CurrentModule->getSymbolTable();
282 return SymTab.lookup(Ty, Name);
285 // getValNonImprovising - Look up the value specified by the provided type and
286 // the provided ValID. If the value exists and has already been defined, return
287 // it. Otherwise return null.
289 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
290 if (isa<FunctionType>(Ty))
291 ThrowException("Functions are not values and "
292 "must be referenced as pointers");
295 case ValID::NumberVal: { // Is it a numbered definition?
296 unsigned type = Ty->getUniqueID();
297 unsigned Num = (unsigned)D.Num;
299 // Module constants occupy the lowest numbered slots...
300 if (type < CurModule.Values.size()) {
301 if (Num < CurModule.Values[type].size())
302 return CurModule.Values[type][Num];
304 Num -= CurModule.Values[type].size();
307 // Make sure that our type is within bounds
308 if (CurFun.Values.size() <= type) return 0;
310 // Check that the number is within bounds...
311 if (CurFun.Values[type].size() <= Num) return 0;
313 return CurFun.Values[type][Num];
316 case ValID::NameVal: { // Is it a named definition?
317 Value *N = lookupInSymbolTable(Ty, std::string(D.Name));
318 if (N == 0) return 0;
320 D.destroy(); // Free old strdup'd memory...
324 // Check to make sure that "Ty" is an integral type, and that our
325 // value will fit into the specified type...
326 case ValID::ConstSIntVal: // Is it a constant pool reference??
327 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64))
328 ThrowException("Signed integral constant '" +
329 itostr(D.ConstPool64) + "' is invalid for type '" +
330 Ty->getDescription() + "'!");
331 return ConstantSInt::get(Ty, D.ConstPool64);
333 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
334 if (!ConstantUInt::isValueValidForType(Ty, D.UConstPool64)) {
335 if (!ConstantSInt::isValueValidForType(Ty, D.ConstPool64)) {
336 ThrowException("Integral constant '" + utostr(D.UConstPool64) +
337 "' is invalid or out of range!");
338 } else { // This is really a signed reference. Transmogrify.
339 return ConstantSInt::get(Ty, D.ConstPool64);
342 return ConstantUInt::get(Ty, D.UConstPool64);
345 case ValID::ConstFPVal: // Is it a floating point const pool reference?
346 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
347 ThrowException("FP constant invalid for type!!");
348 return ConstantFP::get(Ty, D.ConstPoolFP);
350 case ValID::ConstNullVal: // Is it a null value?
351 if (!isa<PointerType>(Ty))
352 ThrowException("Cannot create a a non pointer null!");
353 return ConstantPointerNull::get(cast<PointerType>(Ty));
355 case ValID::ConstantVal: // Fully resolved constant?
356 if (D.ConstantValue->getType() != Ty)
357 ThrowException("Constant expression type different from required type!");
358 return D.ConstantValue;
361 assert(0 && "Unhandled case!");
365 assert(0 && "Unhandled case!");
370 // getVal - This function is identical to getValNonImprovising, except that if a
371 // value is not already defined, it "improvises" by creating a placeholder var
372 // that looks and acts just like the requested variable. When the value is
373 // defined later, all uses of the placeholder variable are replaced with the
376 static Value *getVal(const Type *Ty, const ValID &D) {
377 assert(Ty != Type::TypeTy && "Should use getTypeVal for types!");
379 // See if the value has already been defined...
380 Value *V = getValNonImprovising(Ty, D);
383 // If we reached here, we referenced either a symbol that we don't know about
384 // or an id number that hasn't been read yet. We may be referencing something
385 // forward, so just create an entry to be resolved later and get to it...
388 switch (Ty->getPrimitiveID()) {
389 case Type::LabelTyID: d = new BBPlaceHolder(Ty, D); break;
390 default: d = new ValuePlaceHolder(Ty, D); break;
393 assert(d != 0 && "How did we not make something?");
394 if (inFunctionScope())
395 InsertValue(d, CurFun.LateResolveValues);
397 InsertValue(d, CurModule.LateResolveValues);
402 //===----------------------------------------------------------------------===//
403 // Code to handle forward references in instructions
404 //===----------------------------------------------------------------------===//
406 // This code handles the late binding needed with statements that reference
407 // values not defined yet... for example, a forward branch, or the PHI node for
410 // This keeps a table (CurFun.LateResolveValues) of all such forward references
411 // and back patchs after we are done.
414 // ResolveDefinitions - If we could not resolve some defs at parsing
415 // time (forward branches, phi functions for loops, etc...) resolve the
418 static void ResolveDefinitions(std::vector<ValueList> &LateResolvers,
419 std::vector<ValueList> *FutureLateResolvers) {
420 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
421 for (unsigned ty = 0; ty < LateResolvers.size(); ty++) {
422 while (!LateResolvers[ty].empty()) {
423 Value *V = LateResolvers[ty].back();
424 assert(!isa<Type>(V) && "Types should be in LateResolveTypes!");
426 LateResolvers[ty].pop_back();
427 ValID &DID = getValIDFromPlaceHolder(V);
429 Value *TheRealValue = getValNonImprovising(Type::getUniqueIDType(ty),DID);
431 V->replaceAllUsesWith(TheRealValue);
433 } else if (FutureLateResolvers) {
434 // Functions have their unresolved items forwarded to the module late
436 InsertValue(V, *FutureLateResolvers);
438 if (DID.Type == ValID::NameVal)
439 ThrowException("Reference to an invalid definition: '" +DID.getName()+
440 "' of type '" + V->getType()->getDescription() + "'",
441 getLineNumFromPlaceHolder(V));
443 ThrowException("Reference to an invalid definition: #" +
444 itostr(DID.Num) + " of type '" +
445 V->getType()->getDescription() + "'",
446 getLineNumFromPlaceHolder(V));
451 LateResolvers.clear();
454 // ResolveTypeTo - A brand new type was just declared. This means that (if
455 // name is not null) things referencing Name can be resolved. Otherwise, things
456 // refering to the number can be resolved. Do this now.
458 static void ResolveTypeTo(char *Name, const Type *ToTy) {
459 std::vector<PATypeHolder> &Types = inFunctionScope() ?
460 CurFun.Types : CurModule.Types;
463 if (Name) D = ValID::create(Name);
464 else D = ValID::create((int)Types.size());
466 std::map<ValID, PATypeHolder> &LateResolver = inFunctionScope() ?
467 CurFun.LateResolveTypes : CurModule.LateResolveTypes;
469 std::map<ValID, PATypeHolder>::iterator I = LateResolver.find(D);
470 if (I != LateResolver.end()) {
471 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
472 LateResolver.erase(I);
476 // ResolveTypes - At this point, all types should be resolved. Any that aren't
479 static void ResolveTypes(std::map<ValID, PATypeHolder> &LateResolveTypes) {
480 if (!LateResolveTypes.empty()) {
481 const ValID &DID = LateResolveTypes.begin()->first;
483 if (DID.Type == ValID::NameVal)
484 ThrowException("Reference to an invalid type: '" +DID.getName() + "'");
486 ThrowException("Reference to an invalid type: #" + itostr(DID.Num));
491 // setValueName - Set the specified value to the name given. The name may be
492 // null potentially, in which case this is a noop. The string passed in is
493 // assumed to be a malloc'd string buffer, and is freed by this function.
495 // This function returns true if the value has already been defined, but is
496 // allowed to be redefined in the specified context. If the name is a new name
497 // for the typeplane, false is returned.
499 static bool setValueName(Value *V, char *NameStr) {
500 if (NameStr == 0) return false;
502 std::string Name(NameStr); // Copy string
503 free(NameStr); // Free old string
505 if (V->getType() == Type::VoidTy)
506 ThrowException("Can't assign name '" + Name +
507 "' to a null valued instruction!");
509 SymbolTable &ST = inFunctionScope() ?
510 CurFun.CurrentFunction->getSymbolTable() :
511 CurModule.CurrentModule->getSymbolTable();
513 Value *Existing = ST.lookup(V->getType(), Name);
514 if (Existing) { // Inserting a name that is already defined???
515 // There is only one case where this is allowed: when we are refining an
516 // opaque type. In this case, Existing will be an opaque type.
517 if (const Type *Ty = dyn_cast<Type>(Existing)) {
518 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Ty)) {
519 // We ARE replacing an opaque type!
520 ((OpaqueType*)OpTy)->refineAbstractTypeTo(cast<Type>(V));
525 // Otherwise, we are a simple redefinition of a value, check to see if it
526 // is defined the same as the old one...
527 if (const Type *Ty = dyn_cast<Type>(Existing)) {
528 if (Ty == cast<Type>(V)) return true; // Yes, it's equal.
529 // std::cerr << "Type: " << Ty->getDescription() << " != "
530 // << cast<Type>(V)->getDescription() << "!\n";
531 } else if (const Constant *C = dyn_cast<Constant>(Existing)) {
532 if (C == V) return true; // Constants are equal to themselves
533 } else if (GlobalVariable *EGV = dyn_cast<GlobalVariable>(Existing)) {
534 // We are allowed to redefine a global variable in two circumstances:
535 // 1. If at least one of the globals is uninitialized or
536 // 2. If both initializers have the same value.
538 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
539 if (!EGV->hasInitializer() || !GV->hasInitializer() ||
540 EGV->getInitializer() == GV->getInitializer()) {
542 // Make sure the existing global version gets the initializer! Make
543 // sure that it also gets marked const if the new version is.
544 if (GV->hasInitializer() && !EGV->hasInitializer())
545 EGV->setInitializer(GV->getInitializer());
546 if (GV->isConstant())
547 EGV->setConstant(true);
548 EGV->setLinkage(GV->getLinkage());
550 delete GV; // Destroy the duplicate!
551 return true; // They are equivalent!
556 ThrowException("Redefinition of value named '" + Name + "' in the '" +
557 V->getType()->getDescription() + "' type plane!");
561 V->setName(Name, &ST);
563 // If we're in function scope
564 if (inFunctionScope()) {
565 // Look up the symbol in the function's local symboltable
566 Existing = CurFun.LocalSymtab.lookup(V->getType(),Name);
568 // If it already exists
571 ThrowException("Redefinition of value named '" + Name + "' in the '" +
572 V->getType()->getDescription() + "' type plane!");
574 // otherwise, since it doesn't exist
577 CurFun.LocalSymtab.insert(V);
584 //===----------------------------------------------------------------------===//
585 // Code for handling upreferences in type names...
588 // TypeContains - Returns true if Ty directly contains E in it.
590 static bool TypeContains(const Type *Ty, const Type *E) {
591 return find(Ty->subtype_begin(), Ty->subtype_end(), E) != Ty->subtype_end();
596 // NestingLevel - The number of nesting levels that need to be popped before
597 // this type is resolved.
598 unsigned NestingLevel;
600 // LastContainedTy - This is the type at the current binding level for the
601 // type. Every time we reduce the nesting level, this gets updated.
602 const Type *LastContainedTy;
604 // UpRefTy - This is the actual opaque type that the upreference is
608 UpRefRecord(unsigned NL, OpaqueType *URTy)
609 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
613 // UpRefs - A list of the outstanding upreferences that need to be resolved.
614 static std::vector<UpRefRecord> UpRefs;
616 /// HandleUpRefs - Every time we finish a new layer of types, this function is
617 /// called. It loops through the UpRefs vector, which is a list of the
618 /// currently active types. For each type, if the up reference is contained in
619 /// the newly completed type, we decrement the level count. When the level
620 /// count reaches zero, the upreferenced type is the type that is passed in:
621 /// thus we can complete the cycle.
623 static PATypeHolder HandleUpRefs(const Type *ty) {
624 if (!ty->isAbstract()) return ty;
626 UR_OUT("Type '" << Ty->getDescription() <<
627 "' newly formed. Resolving upreferences.\n" <<
628 UpRefs.size() << " upreferences active!\n");
629 for (unsigned i = 0; i != UpRefs.size(); ++i) {
630 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
631 << UpRefs[i].second->getDescription() << ") = "
632 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
633 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
634 // Decrement level of upreference
635 unsigned Level = --UpRefs[i].NestingLevel;
636 UpRefs[i].LastContainedTy = Ty;
637 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
638 if (Level == 0) { // Upreference should be resolved!
639 UR_OUT(" * Resolving upreference for "
640 << UpRefs[i].second->getDescription() << "\n";
641 std::string OldName = UpRefs[i].UpRefTy->getDescription());
642 UpRefs[i].UpRefTy->refineAbstractTypeTo(Ty);
643 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
644 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
645 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
646 --i; // Do not skip the next element...
655 //===----------------------------------------------------------------------===//
656 // RunVMAsmParser - Define an interface to this parser
657 //===----------------------------------------------------------------------===//
659 Module *RunVMAsmParser(const std::string &Filename, FILE *F) {
661 CurFilename = Filename;
662 llvmAsmlineno = 1; // Reset the current line number...
663 ObsoleteVarArgs = false;
665 // Allocate a new module to read
666 CurModule.CurrentModule = new Module(Filename);
669 yyparse(); // Parse the file.
671 // Clear the symbol table so it doesn't complain when it
673 CurFun.LocalSymtab.clear();
677 Module *Result = ParserResult;
679 // Check to see if they called va_start but not va_arg..
680 if (!ObsoleteVarArgs)
681 if (Function *F = Result->getNamedFunction("llvm.va_start"))
682 if (F->asize() == 1) {
683 std::cerr << "WARNING: this file uses obsolete features. "
684 << "Assemble and disassemble to update it.\n";
685 ObsoleteVarArgs = true;
689 if (ObsoleteVarArgs) {
690 // If the user is making use of obsolete varargs intrinsics, adjust them for
692 if (Function *F = Result->getNamedFunction("llvm.va_start")) {
693 assert(F->asize() == 1 && "Obsolete va_start takes 1 argument!");
695 const Type *RetTy = F->getFunctionType()->getParamType(0);
696 RetTy = cast<PointerType>(RetTy)->getElementType();
697 Function *NF = Result->getOrInsertFunction("llvm.va_start", RetTy, 0);
699 while (!F->use_empty()) {
700 CallInst *CI = cast<CallInst>(F->use_back());
701 Value *V = new CallInst(NF, "", CI);
702 new StoreInst(V, CI->getOperand(1), CI);
703 CI->getParent()->getInstList().erase(CI);
705 Result->getFunctionList().erase(F);
708 if (Function *F = Result->getNamedFunction("llvm.va_end")) {
709 assert(F->asize() == 1 && "Obsolete va_end takes 1 argument!");
710 const Type *ArgTy = F->getFunctionType()->getParamType(0);
711 ArgTy = cast<PointerType>(ArgTy)->getElementType();
712 Function *NF = Result->getOrInsertFunction("llvm.va_end", Type::VoidTy,
715 while (!F->use_empty()) {
716 CallInst *CI = cast<CallInst>(F->use_back());
717 Value *V = new LoadInst(CI->getOperand(1), "", CI);
718 new CallInst(NF, V, "", CI);
719 CI->getParent()->getInstList().erase(CI);
721 Result->getFunctionList().erase(F);
724 if (Function *F = Result->getNamedFunction("llvm.va_copy")) {
725 assert(F->asize() == 2 && "Obsolete va_copy takes 2 argument!");
726 const Type *ArgTy = F->getFunctionType()->getParamType(0);
727 ArgTy = cast<PointerType>(ArgTy)->getElementType();
728 Function *NF = Result->getOrInsertFunction("llvm.va_copy", ArgTy,
731 while (!F->use_empty()) {
732 CallInst *CI = cast<CallInst>(F->use_back());
733 Value *V = new CallInst(NF, CI->getOperand(2), "", CI);
734 new StoreInst(V, CI->getOperand(1), CI);
735 CI->getParent()->getInstList().erase(CI);
737 Result->getFunctionList().erase(F);
741 llvmAsmin = stdin; // F is about to go away, don't use it anymore...
747 } // End llvm namespace
749 using namespace llvm;
754 llvm::Module *ModuleVal;
755 llvm::Function *FunctionVal;
756 std::pair<llvm::PATypeHolder*, char*> *ArgVal;
757 llvm::BasicBlock *BasicBlockVal;
758 llvm::TerminatorInst *TermInstVal;
759 llvm::Instruction *InstVal;
760 llvm::Constant *ConstVal;
762 const llvm::Type *PrimType;
763 llvm::PATypeHolder *TypeVal;
764 llvm::Value *ValueVal;
766 std::vector<std::pair<llvm::PATypeHolder*,char*> > *ArgList;
767 std::vector<llvm::Value*> *ValueList;
768 std::list<llvm::PATypeHolder> *TypeList;
769 std::list<std::pair<llvm::Value*,
770 llvm::BasicBlock*> > *PHIList; // Represent the RHS of PHI node
771 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
772 std::vector<llvm::Constant*> *ConstVector;
774 llvm::GlobalValue::LinkageTypes Linkage;
782 char *StrVal; // This memory is strdup'd!
783 llvm::ValID ValIDVal; // strdup'd memory maybe!
785 llvm::Instruction::BinaryOps BinaryOpVal;
786 llvm::Instruction::TermOps TermOpVal;
787 llvm::Instruction::MemoryOps MemOpVal;
788 llvm::Instruction::OtherOps OtherOpVal;
789 llvm::Module::Endianness Endianness;
792 %type <ModuleVal> Module FunctionList
793 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
794 %type <BasicBlockVal> BasicBlock InstructionList
795 %type <TermInstVal> BBTerminatorInst
796 %type <InstVal> Inst InstVal MemoryInst
797 %type <ConstVal> ConstVal ConstExpr
798 %type <ConstVector> ConstVector
799 %type <ArgList> ArgList ArgListH
800 %type <ArgVal> ArgVal
801 %type <PHIList> PHIList
802 %type <ValueList> ValueRefList ValueRefListE // For call param lists
803 %type <ValueList> IndexList // For GEP derived indices
804 %type <TypeList> TypeListI ArgTypeListI
805 %type <JumpTable> JumpTable
806 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
807 %type <BoolVal> OptVolatile // 'volatile' or not
808 %type <Linkage> OptLinkage
809 %type <Endianness> BigOrLittle
811 // ValueRef - Unresolved reference to a definition or BB
812 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
813 %type <ValueVal> ResolvedVal // <type> <valref> pair
814 // Tokens and types for handling constant integer values
816 // ESINT64VAL - A negative number within long long range
817 %token <SInt64Val> ESINT64VAL
819 // EUINT64VAL - A positive number within uns. long long range
820 %token <UInt64Val> EUINT64VAL
821 %type <SInt64Val> EINT64VAL
823 %token <SIntVal> SINTVAL // Signed 32 bit ints...
824 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
825 %type <SIntVal> INTVAL
826 %token <FPVal> FPVAL // Float or Double constant
829 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
830 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
831 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
832 %token <PrimType> FLOAT DOUBLE TYPE LABEL
834 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
835 %type <StrVal> Name OptName OptAssign
838 %token IMPLEMENTATION ZEROINITIALIZER TRUE FALSE BEGINTOK ENDTOK
839 %token DECLARE GLOBAL CONSTANT VOLATILE
840 %token TO DOTDOTDOT NULL_TOK CONST INTERNAL LINKONCE WEAK APPENDING
841 %token OPAQUE NOT EXTERNAL TARGET ENDIAN POINTERSIZE LITTLE BIG
843 // Basic Block Terminating Operators
844 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND
847 %type <BinaryOpVal> BinaryOps // all the binary operators
848 %type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
849 %token <BinaryOpVal> ADD SUB MUL DIV REM AND OR XOR
850 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comarators
852 // Memory Instructions
853 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
856 %type <OtherOpVal> ShiftOps
857 %token <OtherOpVal> PHI_TOK CALL CAST SHL SHR VAARG VANEXT
858 %token VA_ARG // FIXME: OBSOLETE
863 // Handle constant integer size restriction and conversion...
867 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
868 ThrowException("Value too large for type!");
873 EINT64VAL : ESINT64VAL; // These have same type and can't cause problems...
874 EINT64VAL : EUINT64VAL {
875 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
876 ThrowException("Value too large for type!");
880 // Operations that are notably excluded from this list include:
881 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
883 ArithmeticOps: ADD | SUB | MUL | DIV | REM;
884 LogicalOps : AND | OR | XOR;
885 SetCondOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE;
886 BinaryOps : ArithmeticOps | LogicalOps | SetCondOps;
888 ShiftOps : SHL | SHR;
890 // These are some types that allow classification if we only want a particular
891 // thing... for example, only a signed, unsigned, or integral type.
892 SIntType : LONG | INT | SHORT | SBYTE;
893 UIntType : ULONG | UINT | USHORT | UBYTE;
894 IntType : SIntType | UIntType;
895 FPType : FLOAT | DOUBLE;
897 // OptAssign - Value producing statements have an optional assignment component
898 OptAssign : Name '=' {
905 OptLinkage : INTERNAL { $$ = GlobalValue::InternalLinkage; } |
906 LINKONCE { $$ = GlobalValue::LinkOnceLinkage; } |
907 WEAK { $$ = GlobalValue::WeakLinkage; } |
908 APPENDING { $$ = GlobalValue::AppendingLinkage; } |
909 /*empty*/ { $$ = GlobalValue::ExternalLinkage; };
911 //===----------------------------------------------------------------------===//
912 // Types includes all predefined types... except void, because it can only be
913 // used in specific contexts (function returning void for example). To have
914 // access to it, a user must explicitly use TypesV.
917 // TypesV includes all of 'Types', but it also includes the void type.
918 TypesV : Types | VOID { $$ = new PATypeHolder($1); };
919 UpRTypesV : UpRTypes | VOID { $$ = new PATypeHolder($1); };
923 ThrowException("Invalid upreference in type: " + (*$1)->getDescription());
928 // Derived types are added later...
930 PrimType : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT ;
931 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE | LABEL;
933 $$ = new PATypeHolder(OpaqueType::get());
936 $$ = new PATypeHolder($1);
938 UpRTypes : SymbolicValueRef { // Named types are also simple types...
939 $$ = new PATypeHolder(getTypeVal($1));
942 // Include derived types in the Types production.
944 UpRTypes : '\\' EUINT64VAL { // Type UpReference
945 if ($2 > (uint64_t)~0U) ThrowException("Value out of range!");
946 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
947 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
948 $$ = new PATypeHolder(OT);
949 UR_OUT("New Upreference!\n");
951 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
952 std::vector<const Type*> Params;
953 mapto($3->begin(), $3->end(), std::back_inserter(Params),
954 std::mem_fun_ref(&PATypeHolder::get));
955 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
956 if (isVarArg) Params.pop_back();
958 $$ = new PATypeHolder(HandleUpRefs(FunctionType::get(*$1,Params,isVarArg)));
959 delete $3; // Delete the argument list
960 delete $1; // Delete the return type handle
962 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
963 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
966 | '{' TypeListI '}' { // Structure type?
967 std::vector<const Type*> Elements;
968 mapto($2->begin(), $2->end(), std::back_inserter(Elements),
969 std::mem_fun_ref(&PATypeHolder::get));
971 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
974 | '{' '}' { // Empty structure type?
975 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
977 | UpRTypes '*' { // Pointer type?
978 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
982 // TypeList - Used for struct declarations and as a basis for function type
983 // declaration type lists
985 TypeListI : UpRTypes {
986 $$ = new std::list<PATypeHolder>();
987 $$->push_back(*$1); delete $1;
989 | TypeListI ',' UpRTypes {
990 ($$=$1)->push_back(*$3); delete $3;
993 // ArgTypeList - List of types for a function type declaration...
994 ArgTypeListI : TypeListI
995 | TypeListI ',' DOTDOTDOT {
996 ($$=$1)->push_back(Type::VoidTy);
999 ($$ = new std::list<PATypeHolder>())->push_back(Type::VoidTy);
1002 $$ = new std::list<PATypeHolder>();
1005 // ConstVal - The various declarations that go into the constant pool. This
1006 // production is used ONLY to represent constants that show up AFTER a 'const',
1007 // 'constant' or 'global' token at global scope. Constants that can be inlined
1008 // into other expressions (such as integers and constexprs) are handled by the
1009 // ResolvedVal, ValueRef and ConstValueRef productions.
1011 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1012 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1014 ThrowException("Cannot make array constant with type: '" +
1015 (*$1)->getDescription() + "'!");
1016 const Type *ETy = ATy->getElementType();
1017 int NumElements = ATy->getNumElements();
1019 // Verify that we have the correct size...
1020 if (NumElements != -1 && NumElements != (int)$3->size())
1021 ThrowException("Type mismatch: constant sized array initialized with " +
1022 utostr($3->size()) + " arguments, but has size of " +
1023 itostr(NumElements) + "!");
1025 // Verify all elements are correct type!
1026 for (unsigned i = 0; i < $3->size(); i++) {
1027 if (ETy != (*$3)[i]->getType())
1028 ThrowException("Element #" + utostr(i) + " is not of type '" +
1029 ETy->getDescription() +"' as required!\nIt is of type '"+
1030 (*$3)[i]->getType()->getDescription() + "'.");
1033 $$ = ConstantArray::get(ATy, *$3);
1034 delete $1; delete $3;
1037 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1039 ThrowException("Cannot make array constant with type: '" +
1040 (*$1)->getDescription() + "'!");
1042 int NumElements = ATy->getNumElements();
1043 if (NumElements != -1 && NumElements != 0)
1044 ThrowException("Type mismatch: constant sized array initialized with 0"
1045 " arguments, but has size of " + itostr(NumElements) +"!");
1046 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1049 | Types 'c' STRINGCONSTANT {
1050 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1052 ThrowException("Cannot make array constant with type: '" +
1053 (*$1)->getDescription() + "'!");
1055 int NumElements = ATy->getNumElements();
1056 const Type *ETy = ATy->getElementType();
1057 char *EndStr = UnEscapeLexed($3, true);
1058 if (NumElements != -1 && NumElements != (EndStr-$3))
1059 ThrowException("Can't build string constant of size " +
1060 itostr((int)(EndStr-$3)) +
1061 " when array has size " + itostr(NumElements) + "!");
1062 std::vector<Constant*> Vals;
1063 if (ETy == Type::SByteTy) {
1064 for (char *C = $3; C != EndStr; ++C)
1065 Vals.push_back(ConstantSInt::get(ETy, *C));
1066 } else if (ETy == Type::UByteTy) {
1067 for (char *C = $3; C != EndStr; ++C)
1068 Vals.push_back(ConstantUInt::get(ETy, (unsigned char)*C));
1071 ThrowException("Cannot build string arrays of non byte sized elements!");
1074 $$ = ConstantArray::get(ATy, Vals);
1077 | Types '{' ConstVector '}' {
1078 const StructType *STy = dyn_cast<StructType>($1->get());
1080 ThrowException("Cannot make struct constant with type: '" +
1081 (*$1)->getDescription() + "'!");
1083 if ($3->size() != STy->getNumContainedTypes())
1084 ThrowException("Illegal number of initializers for structure type!");
1086 // Check to ensure that constants are compatible with the type initializer!
1087 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1088 if ((*$3)[i]->getType() != STy->getElementTypes()[i])
1089 ThrowException("Expected type '" +
1090 STy->getElementTypes()[i]->getDescription() +
1091 "' for element #" + utostr(i) +
1092 " of structure initializer!");
1094 $$ = ConstantStruct::get(STy, *$3);
1095 delete $1; delete $3;
1098 const StructType *STy = dyn_cast<StructType>($1->get());
1100 ThrowException("Cannot make struct constant with type: '" +
1101 (*$1)->getDescription() + "'!");
1103 if (STy->getNumContainedTypes() != 0)
1104 ThrowException("Illegal number of initializers for structure type!");
1106 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1110 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1112 ThrowException("Cannot make null pointer constant with type: '" +
1113 (*$1)->getDescription() + "'!");
1115 $$ = ConstantPointerNull::get(PTy);
1118 | Types SymbolicValueRef {
1119 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1121 ThrowException("Global const reference must be a pointer type!");
1123 // ConstExprs can exist in the body of a function, thus creating
1124 // ConstantPointerRefs whenever they refer to a variable. Because we are in
1125 // the context of a function, getValNonImprovising will search the functions
1126 // symbol table instead of the module symbol table for the global symbol,
1127 // which throws things all off. To get around this, we just tell
1128 // getValNonImprovising that we are at global scope here.
1130 Function *SavedCurFn = CurFun.CurrentFunction;
1131 CurFun.CurrentFunction = 0;
1133 Value *V = getValNonImprovising(Ty, $2);
1135 CurFun.CurrentFunction = SavedCurFn;
1137 // If this is an initializer for a constant pointer, which is referencing a
1138 // (currently) undefined variable, create a stub now that shall be replaced
1139 // in the future with the right type of variable.
1142 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1143 const PointerType *PT = cast<PointerType>(Ty);
1145 // First check to see if the forward references value is already created!
1146 PerModuleInfo::GlobalRefsType::iterator I =
1147 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1149 if (I != CurModule.GlobalRefs.end()) {
1150 V = I->second; // Placeholder already exists, use it...
1153 // Create a placeholder for the global variable reference...
1154 GlobalVariable *GV = new GlobalVariable(PT->getElementType(),
1156 GlobalValue::ExternalLinkage);
1157 // Keep track of the fact that we have a forward ref to recycle it
1158 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1160 // Must temporarily push this value into the module table...
1161 CurModule.CurrentModule->getGlobalList().push_back(GV);
1166 GlobalValue *GV = cast<GlobalValue>(V);
1167 $$ = ConstantPointerRef::get(GV);
1168 delete $1; // Free the type handle
1171 if ($1->get() != $2->getType())
1172 ThrowException("Mismatched types for constant expression!");
1176 | Types ZEROINITIALIZER {
1177 $$ = Constant::getNullValue($1->get());
1181 ConstVal : SIntType EINT64VAL { // integral constants
1182 if (!ConstantSInt::isValueValidForType($1, $2))
1183 ThrowException("Constant value doesn't fit in type!");
1184 $$ = ConstantSInt::get($1, $2);
1186 | UIntType EUINT64VAL { // integral constants
1187 if (!ConstantUInt::isValueValidForType($1, $2))
1188 ThrowException("Constant value doesn't fit in type!");
1189 $$ = ConstantUInt::get($1, $2);
1191 | BOOL TRUE { // Boolean constants
1192 $$ = ConstantBool::True;
1194 | BOOL FALSE { // Boolean constants
1195 $$ = ConstantBool::False;
1197 | FPType FPVAL { // Float & Double constants
1198 $$ = ConstantFP::get($1, $2);
1202 ConstExpr: CAST '(' ConstVal TO Types ')' {
1203 if (!$3->getType()->isFirstClassType())
1204 ThrowException("cast constant expression from a non-primitive type: '" +
1205 $3->getType()->getDescription() + "'!");
1206 if (!$5->get()->isFirstClassType())
1207 ThrowException("cast constant expression to a non-primitive type: '" +
1208 $5->get()->getDescription() + "'!");
1209 $$ = ConstantExpr::getCast($3, $5->get());
1212 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1213 if (!isa<PointerType>($3->getType()))
1214 ThrowException("GetElementPtr requires a pointer operand!");
1217 GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1219 ThrowException("Index list invalid for constant getelementptr!");
1221 std::vector<Constant*> IdxVec;
1222 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1223 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1224 IdxVec.push_back(C);
1226 ThrowException("Indices to constant getelementptr must be constants!");
1230 $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1232 | BinaryOps '(' ConstVal ',' ConstVal ')' {
1233 if ($3->getType() != $5->getType())
1234 ThrowException("Binary operator types must match!");
1235 $$ = ConstantExpr::get($1, $3, $5);
1237 | ShiftOps '(' ConstVal ',' ConstVal ')' {
1238 if ($5->getType() != Type::UByteTy)
1239 ThrowException("Shift count for shift constant must be unsigned byte!");
1240 if (!$3->getType()->isInteger())
1241 ThrowException("Shift constant expression requires integer operand!");
1242 $$ = ConstantExpr::get($1, $3, $5);
1246 // ConstVector - A list of comma separated constants.
1247 ConstVector : ConstVector ',' ConstVal {
1248 ($$ = $1)->push_back($3);
1251 $$ = new std::vector<Constant*>();
1256 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1257 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1260 //===----------------------------------------------------------------------===//
1261 // Rules to match Modules
1262 //===----------------------------------------------------------------------===//
1264 // Module rule: Capture the result of parsing the whole file into a result
1267 Module : FunctionList {
1268 $$ = ParserResult = $1;
1269 CurModule.ModuleDone();
1272 // FunctionList - A list of functions, preceeded by a constant pool.
1274 FunctionList : FunctionList Function {
1276 assert($2->getParent() == 0 && "Function already in module!");
1277 $1->getFunctionList().push_back($2);
1278 CurFun.FunctionDone();
1280 | FunctionList FunctionProto {
1283 | FunctionList IMPLEMENTATION {
1287 $$ = CurModule.CurrentModule;
1288 // Resolve circular types before we parse the body of the module
1289 ResolveTypes(CurModule.LateResolveTypes);
1292 // ConstPool - Constants with optional names assigned to them.
1293 ConstPool : ConstPool OptAssign CONST ConstVal {
1294 if (!setValueName($4, $2))
1297 | ConstPool OptAssign TYPE TypesV { // Types can be defined in the const pool
1298 // Eagerly resolve types. This is not an optimization, this is a
1299 // requirement that is due to the fact that we could have this:
1301 // %list = type { %list * }
1302 // %list = type { %list * } ; repeated type decl
1304 // If types are not resolved eagerly, then the two types will not be
1305 // determined to be the same type!
1307 ResolveTypeTo($2, $4->get());
1309 // TODO: FIXME when Type are not const
1310 if (!setValueName(const_cast<Type*>($4->get()), $2)) {
1311 // If this is not a redefinition of a type...
1313 InsertType($4->get(),
1314 inFunctionScope() ? CurFun.Types : CurModule.Types);
1320 | ConstPool FunctionProto { // Function prototypes can be in const pool
1322 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
1323 const Type *Ty = $5->getType();
1324 // Global declarations appear in Constant Pool
1325 Constant *Initializer = $5;
1326 if (Initializer == 0)
1327 ThrowException("Global value initializer is not a constant!");
1329 GlobalVariable *GV = new GlobalVariable(Ty, $4, $3, Initializer);
1330 if (!setValueName(GV, $2)) { // If not redefining...
1331 CurModule.CurrentModule->getGlobalList().push_back(GV);
1332 int Slot = InsertValue(GV, CurModule.Values);
1335 CurModule.DeclareNewGlobalValue(GV, ValID::create(Slot));
1337 CurModule.DeclareNewGlobalValue(GV, ValID::create(
1338 (char*)GV->getName().c_str()));
1342 | ConstPool OptAssign EXTERNAL GlobalType Types {
1343 const Type *Ty = *$5;
1344 // Global declarations appear in Constant Pool
1345 GlobalVariable *GV = new GlobalVariable(Ty,$4,GlobalValue::ExternalLinkage);
1346 if (!setValueName(GV, $2)) { // If not redefining...
1347 CurModule.CurrentModule->getGlobalList().push_back(GV);
1348 int Slot = InsertValue(GV, CurModule.Values);
1351 CurModule.DeclareNewGlobalValue(GV, ValID::create(Slot));
1353 assert(GV->hasName() && "Not named and not numbered!?");
1354 CurModule.DeclareNewGlobalValue(GV, ValID::create(
1355 (char*)GV->getName().c_str()));
1360 | ConstPool TARGET TargetDefinition {
1362 | /* empty: end of list */ {
1367 BigOrLittle : BIG { $$ = Module::BigEndian; };
1368 BigOrLittle : LITTLE { $$ = Module::LittleEndian; };
1370 TargetDefinition : ENDIAN '=' BigOrLittle {
1371 CurModule.CurrentModule->setEndianness($3);
1373 | POINTERSIZE '=' EUINT64VAL {
1375 CurModule.CurrentModule->setPointerSize(Module::Pointer32);
1377 CurModule.CurrentModule->setPointerSize(Module::Pointer64);
1379 ThrowException("Invalid pointer size: '" + utostr($3) + "'!");
1383 //===----------------------------------------------------------------------===//
1384 // Rules to match Function Headers
1385 //===----------------------------------------------------------------------===//
1387 Name : VAR_ID | STRINGCONSTANT;
1388 OptName : Name | /*empty*/ { $$ = 0; };
1390 ArgVal : Types OptName {
1391 if (*$1 == Type::VoidTy)
1392 ThrowException("void typed arguments are invalid!");
1393 $$ = new std::pair<PATypeHolder*, char*>($1, $2);
1396 ArgListH : ArgListH ',' ArgVal {
1402 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1407 ArgList : ArgListH {
1410 | ArgListH ',' DOTDOTDOT {
1412 $$->push_back(std::pair<PATypeHolder*,
1413 char*>(new PATypeHolder(Type::VoidTy), 0));
1416 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1417 $$->push_back(std::make_pair(new PATypeHolder(Type::VoidTy), (char*)0));
1423 FunctionHeaderH : TypesV Name '(' ArgList ')' {
1425 std::string FunctionName($2);
1427 if (!(*$1)->isFirstClassType() && *$1 != Type::VoidTy)
1428 ThrowException("LLVM functions cannot return aggregate types!");
1430 std::vector<const Type*> ParamTypeList;
1431 if ($4) { // If there are arguments...
1432 for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $4->begin();
1433 I != $4->end(); ++I)
1434 ParamTypeList.push_back(I->first->get());
1437 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
1438 if (isVarArg) ParamTypeList.pop_back();
1440 const FunctionType *FT = FunctionType::get(*$1, ParamTypeList, isVarArg);
1441 const PointerType *PFT = PointerType::get(FT);
1445 // Is the function already in symtab?
1446 if ((Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
1447 // Yes it is. If this is the case, either we need to be a forward decl,
1448 // or it needs to be.
1449 if (!CurFun.isDeclare && !Fn->isExternal())
1450 ThrowException("Redefinition of function '" + FunctionName + "'!");
1452 // If we found a preexisting function prototype, remove it from the
1453 // module, so that we don't get spurious conflicts with global & local
1456 CurModule.CurrentModule->getFunctionList().remove(Fn);
1458 // Make sure to strip off any argument names so we can't get conflicts...
1459 for (Function::aiterator AI = Fn->abegin(), AE = Fn->aend(); AI != AE; ++AI)
1462 } else { // Not already defined?
1463 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName);
1464 InsertValue(Fn, CurModule.Values);
1465 CurModule.DeclareNewGlobalValue(Fn, ValID::create($2));
1467 free($2); // Free strdup'd memory!
1469 CurFun.FunctionStart(Fn);
1471 // Add all of the arguments we parsed to the function...
1472 if ($4) { // Is null if empty...
1473 if (isVarArg) { // Nuke the last entry
1474 assert($4->back().first->get() == Type::VoidTy && $4->back().second == 0&&
1475 "Not a varargs marker!");
1476 delete $4->back().first;
1477 $4->pop_back(); // Delete the last entry
1479 Function::aiterator ArgIt = Fn->abegin();
1480 for (std::vector<std::pair<PATypeHolder*, char*> >::iterator I =$4->begin();
1481 I != $4->end(); ++I, ++ArgIt) {
1482 delete I->first; // Delete the typeholder...
1484 if (setValueName(ArgIt, I->second)) // Insert arg into symtab...
1485 assert(0 && "No arg redef allowed!");
1490 delete $4; // We're now done with the argument list
1494 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
1496 FunctionHeader : OptLinkage FunctionHeaderH BEGIN {
1497 $$ = CurFun.CurrentFunction;
1499 // Make sure that we keep track of the linkage type even if there was a
1500 // previous "declare".
1503 // Resolve circular types before we parse the body of the function.
1504 ResolveTypes(CurFun.LateResolveTypes);
1507 END : ENDTOK | '}'; // Allow end of '}' to end a function
1509 Function : BasicBlockList END {
1513 FunctionProto : DECLARE { CurFun.isDeclare = true; } FunctionHeaderH {
1514 $$ = CurFun.CurrentFunction;
1515 assert($$->getParent() == 0 && "Function already in module!");
1516 CurModule.CurrentModule->getFunctionList().push_back($$);
1517 CurFun.FunctionDone();
1520 //===----------------------------------------------------------------------===//
1521 // Rules to match Basic Blocks
1522 //===----------------------------------------------------------------------===//
1524 ConstValueRef : ESINT64VAL { // A reference to a direct constant
1525 $$ = ValID::create($1);
1528 $$ = ValID::create($1);
1530 | FPVAL { // Perhaps it's an FP constant?
1531 $$ = ValID::create($1);
1534 $$ = ValID::create(ConstantBool::True);
1537 $$ = ValID::create(ConstantBool::False);
1540 $$ = ValID::createNull();
1543 $$ = ValID::create($1);
1546 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
1549 SymbolicValueRef : INTVAL { // Is it an integer reference...?
1550 $$ = ValID::create($1);
1552 | Name { // Is it a named reference...?
1553 $$ = ValID::create($1);
1556 // ValueRef - A reference to a definition... either constant or symbolic
1557 ValueRef : SymbolicValueRef | ConstValueRef;
1560 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
1561 // type immediately preceeds the value reference, and allows complex constant
1562 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
1563 ResolvedVal : Types ValueRef {
1564 $$ = getVal(*$1, $2); delete $1;
1567 BasicBlockList : BasicBlockList BasicBlock {
1568 ($$ = $1)->getBasicBlockList().push_back($2);
1570 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
1571 ($$ = $1)->getBasicBlockList().push_back($2);
1575 // Basic blocks are terminated by branching instructions:
1576 // br, br/cc, switch, ret
1578 BasicBlock : InstructionList OptAssign BBTerminatorInst {
1579 if (setValueName($3, $2)) { assert(0 && "No redefn allowed!"); }
1582 $1->getInstList().push_back($3);
1586 | LABELSTR InstructionList OptAssign BBTerminatorInst {
1587 if (setValueName($4, $3)) { assert(0 && "No redefn allowed!"); }
1590 $2->getInstList().push_back($4);
1591 if (setValueName($2, $1)) { assert(0 && "No label redef allowed!"); }
1597 InstructionList : InstructionList Inst {
1598 $1->getInstList().push_back($2);
1602 $$ = CurBB = new BasicBlock();
1605 BBTerminatorInst : RET ResolvedVal { // Return with a result...
1606 $$ = new ReturnInst($2);
1608 | RET VOID { // Return with no result...
1609 $$ = new ReturnInst();
1611 | BR LABEL ValueRef { // Unconditional Branch...
1612 $$ = new BranchInst(cast<BasicBlock>(getVal(Type::LabelTy, $3)));
1613 } // Conditional Branch...
1614 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
1615 $$ = new BranchInst(cast<BasicBlock>(getVal(Type::LabelTy, $6)),
1616 cast<BasicBlock>(getVal(Type::LabelTy, $9)),
1617 getVal(Type::BoolTy, $3));
1619 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
1620 SwitchInst *S = new SwitchInst(getVal($2, $3),
1621 cast<BasicBlock>(getVal(Type::LabelTy, $6)));
1624 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
1627 S->addCase(I->first, I->second);
1629 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
1630 SwitchInst *S = new SwitchInst(getVal($2, $3),
1631 cast<BasicBlock>(getVal(Type::LabelTy, $6)));
1634 | INVOKE TypesV ValueRef '(' ValueRefListE ')' TO ResolvedVal
1635 UNWIND ResolvedVal {
1636 const PointerType *PFTy;
1637 const FunctionType *Ty;
1639 if (!(PFTy = dyn_cast<PointerType>($2->get())) ||
1640 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1641 // Pull out the types of all of the arguments...
1642 std::vector<const Type*> ParamTypes;
1644 for (std::vector<Value*>::iterator I = $5->begin(), E = $5->end();
1646 ParamTypes.push_back((*I)->getType());
1649 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1650 if (isVarArg) ParamTypes.pop_back();
1652 Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1653 PFTy = PointerType::get(Ty);
1656 Value *V = getVal(PFTy, $3); // Get the function we're calling...
1658 BasicBlock *Normal = dyn_cast<BasicBlock>($8);
1659 BasicBlock *Except = dyn_cast<BasicBlock>($10);
1661 if (Normal == 0 || Except == 0)
1662 ThrowException("Invoke instruction without label destinations!");
1664 // Create the call node...
1665 if (!$5) { // Has no arguments?
1666 $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
1667 } else { // Has arguments?
1668 // Loop through FunctionType's arguments and ensure they are specified
1671 FunctionType::ParamTypes::const_iterator I = Ty->getParamTypes().begin();
1672 FunctionType::ParamTypes::const_iterator E = Ty->getParamTypes().end();
1673 std::vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1675 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1676 if ((*ArgI)->getType() != *I)
1677 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1678 (*I)->getDescription() + "'!");
1680 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1681 ThrowException("Invalid number of parameters detected!");
1683 $$ = new InvokeInst(V, Normal, Except, *$5);
1689 $$ = new UnwindInst();
1694 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
1696 Constant *V = cast<Constant>(getValNonImprovising($2, $3));
1698 ThrowException("May only switch on a constant pool value!");
1700 $$->push_back(std::make_pair(V, cast<BasicBlock>(getVal($5, $6))));
1702 | IntType ConstValueRef ',' LABEL ValueRef {
1703 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
1704 Constant *V = cast<Constant>(getValNonImprovising($1, $2));
1707 ThrowException("May only switch on a constant pool value!");
1709 $$->push_back(std::make_pair(V, cast<BasicBlock>(getVal($4, $5))));
1712 Inst : OptAssign InstVal {
1713 // Is this definition named?? if so, assign the name...
1714 if (setValueName($2, $1)) { assert(0 && "No redefin allowed!"); }
1719 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
1720 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
1721 $$->push_back(std::make_pair(getVal(*$1, $3),
1722 cast<BasicBlock>(getVal(Type::LabelTy, $5))));
1725 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
1727 $1->push_back(std::make_pair(getVal($1->front().first->getType(), $4),
1728 cast<BasicBlock>(getVal(Type::LabelTy, $6))));
1732 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
1733 $$ = new std::vector<Value*>();
1736 | ValueRefList ',' ResolvedVal {
1741 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
1742 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; };
1744 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
1745 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint())
1746 ThrowException("Arithmetic operator requires integer or FP operands!");
1747 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1749 ThrowException("binary operator returned null!");
1752 | LogicalOps Types ValueRef ',' ValueRef {
1753 if (!(*$2)->isIntegral())
1754 ThrowException("Logical operator requires integral operands!");
1755 $$ = BinaryOperator::create($1, getVal(*$2, $3), getVal(*$2, $5));
1757 ThrowException("binary operator returned null!");
1760 | SetCondOps Types ValueRef ',' ValueRef {
1761 $$ = new SetCondInst($1, getVal(*$2, $3), getVal(*$2, $5));
1763 ThrowException("binary operator returned null!");
1767 std::cerr << "WARNING: Use of eliminated 'not' instruction:"
1768 << " Replacing with 'xor'.\n";
1770 Value *Ones = ConstantIntegral::getAllOnesValue($2->getType());
1772 ThrowException("Expected integral type for not instruction!");
1774 $$ = BinaryOperator::create(Instruction::Xor, $2, Ones);
1776 ThrowException("Could not create a xor instruction!");
1778 | ShiftOps ResolvedVal ',' ResolvedVal {
1779 if ($4->getType() != Type::UByteTy)
1780 ThrowException("Shift amount must be ubyte!");
1781 if (!$2->getType()->isInteger())
1782 ThrowException("Shift constant expression requires integer operand!");
1783 $$ = new ShiftInst($1, $2, $4);
1785 | CAST ResolvedVal TO Types {
1786 if (!$4->get()->isFirstClassType())
1787 ThrowException("cast instruction to a non-primitive type: '" +
1788 $4->get()->getDescription() + "'!");
1789 $$ = new CastInst($2, *$4);
1792 | VA_ARG ResolvedVal ',' Types {
1793 // FIXME: This is emulation code for an obsolete syntax. This should be
1794 // removed at some point.
1795 if (!ObsoleteVarArgs) {
1796 std::cerr << "WARNING: this file uses obsolete features. "
1797 << "Assemble and disassemble to update it.\n";
1798 ObsoleteVarArgs = true;
1801 // First, load the valist...
1802 Instruction *CurVAList = new LoadInst($2, "");
1803 CurBB->getInstList().push_back(CurVAList);
1805 // Emit the vaarg instruction.
1806 $$ = new VAArgInst(CurVAList, *$4);
1808 // Now we must advance the pointer and update it in memory.
1809 Instruction *TheVANext = new VANextInst(CurVAList, *$4);
1810 CurBB->getInstList().push_back(TheVANext);
1812 CurBB->getInstList().push_back(new StoreInst(TheVANext, $2));
1815 | VAARG ResolvedVal ',' Types {
1816 $$ = new VAArgInst($2, *$4);
1819 | VANEXT ResolvedVal ',' Types {
1820 $$ = new VANextInst($2, *$4);
1824 const Type *Ty = $2->front().first->getType();
1825 if (!Ty->isFirstClassType())
1826 ThrowException("PHI node operands must be of first class type!");
1827 $$ = new PHINode(Ty);
1828 $$->op_reserve($2->size()*2);
1829 while ($2->begin() != $2->end()) {
1830 if ($2->front().first->getType() != Ty)
1831 ThrowException("All elements of a PHI node must be of the same type!");
1832 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
1835 delete $2; // Free the list...
1837 | CALL TypesV ValueRef '(' ValueRefListE ')' {
1838 const PointerType *PFTy;
1839 const FunctionType *Ty;
1841 if (!(PFTy = dyn_cast<PointerType>($2->get())) ||
1842 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
1843 // Pull out the types of all of the arguments...
1844 std::vector<const Type*> ParamTypes;
1846 for (std::vector<Value*>::iterator I = $5->begin(), E = $5->end();
1848 ParamTypes.push_back((*I)->getType());
1851 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
1852 if (isVarArg) ParamTypes.pop_back();
1854 Ty = FunctionType::get($2->get(), ParamTypes, isVarArg);
1855 PFTy = PointerType::get(Ty);
1858 Value *V = getVal(PFTy, $3); // Get the function we're calling...
1860 // Create the call node...
1861 if (!$5) { // Has no arguments?
1862 // Make sure no arguments is a good thing!
1863 if (Ty->getNumParams() != 0)
1864 ThrowException("No arguments passed to a function that "
1865 "expects arguments!");
1867 $$ = new CallInst(V, std::vector<Value*>());
1868 } else { // Has arguments?
1869 // Loop through FunctionType's arguments and ensure they are specified
1872 FunctionType::ParamTypes::const_iterator I = Ty->getParamTypes().begin();
1873 FunctionType::ParamTypes::const_iterator E = Ty->getParamTypes().end();
1874 std::vector<Value*>::iterator ArgI = $5->begin(), ArgE = $5->end();
1876 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
1877 if ((*ArgI)->getType() != *I)
1878 ThrowException("Parameter " +(*ArgI)->getName()+ " is not of type '" +
1879 (*I)->getDescription() + "'!");
1881 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
1882 ThrowException("Invalid number of parameters detected!");
1884 $$ = new CallInst(V, *$5);
1894 // IndexList - List of indices for GEP based instructions...
1895 IndexList : ',' ValueRefList {
1898 $$ = new std::vector<Value*>();
1901 OptVolatile : VOLATILE {
1909 MemoryInst : MALLOC Types {
1910 $$ = new MallocInst(*$2);
1913 | MALLOC Types ',' UINT ValueRef {
1914 $$ = new MallocInst(*$2, getVal($4, $5));
1918 $$ = new AllocaInst(*$2);
1921 | ALLOCA Types ',' UINT ValueRef {
1922 $$ = new AllocaInst(*$2, getVal($4, $5));
1925 | FREE ResolvedVal {
1926 if (!isa<PointerType>($2->getType()))
1927 ThrowException("Trying to free nonpointer type " +
1928 $2->getType()->getDescription() + "!");
1929 $$ = new FreeInst($2);
1932 | OptVolatile LOAD Types ValueRef {
1933 if (!isa<PointerType>($3->get()))
1934 ThrowException("Can't load from nonpointer type: " +
1935 (*$3)->getDescription());
1936 $$ = new LoadInst(getVal(*$3, $4), "", $1);
1939 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
1940 const PointerType *PT = dyn_cast<PointerType>($5->get());
1942 ThrowException("Can't store to a nonpointer type: " +
1943 (*$5)->getDescription());
1944 const Type *ElTy = PT->getElementType();
1945 if (ElTy != $3->getType())
1946 ThrowException("Can't store '" + $3->getType()->getDescription() +
1947 "' into space of type '" + ElTy->getDescription() + "'!");
1949 $$ = new StoreInst($3, getVal(*$5, $6), $1);
1952 | GETELEMENTPTR Types ValueRef IndexList {
1953 if (!isa<PointerType>($2->get()))
1954 ThrowException("getelementptr insn requires pointer operand!");
1955 if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
1956 ThrowException("Can't get element ptr '" + (*$2)->getDescription()+ "'!");
1957 $$ = new GetElementPtrInst(getVal(*$2, $3), *$4);
1958 delete $2; delete $4;
1963 int yyerror(const char *ErrorMsg) {
1965 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
1966 + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
1967 std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
1968 if (yychar == YYEMPTY)
1969 errMsg += "end-of-file.";
1971 errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
1972 ThrowException(errMsg);